From 005ad49872fba7b7234e0be26690f10ae1edcd82 Mon Sep 17 00:00:00 2001 From: 9hvn9yt2vk-netizen <360448330+9hvn9yt2vk-netizen@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:01:06 +0100 Subject: [PATCH 001/445] xma: stop at a zero-length frame instead of looping forever next_frame walks the frames before `start` to learn whether the frame at `start` is the packet's last. A damaged packet whose earlier frame has a length of 0 never advanced `at`, so the walk spun forever (in a debug build it overflowed `number` after about 4 billion rounds and panicked). Apply the rule read_frame already uses: a length that does not cover its own 15-bit field is not a frame, and the search ends. Found with a random-input harness. The new test hangs without the fix and passes at once with it. --- crates/victory-formats/src/xma.rs | 33 ++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs index 06aa427..4a9e606 100644 --- a/crates/victory-formats/src/xma.rs +++ b/crates/victory-formats/src/xma.rs @@ -136,7 +136,14 @@ fn next_frame(data: &[u8], start: usize, end: usize) -> Option { let mut number = 0; while at < start { let mut cursor = Cursor { data, pos: at }; - at += cursor.bits(LENGTH_BITS)? as usize; + let bits = cursor.bits(LENGTH_BITS)? as usize; + // The same rule as `read_frame`: a length that does not cover its own + // field is not a frame. A zero length would never move `at`, so a + // damaged packet would loop here for good. + if bits <= LENGTH_BITS as usize { + return None; + } + at += bits; number += 1; } let last = number + 1 >= header.frames; @@ -1015,6 +1022,30 @@ fn to_i16(v: f32) -> i16 { mod tests { use super::*; + /// Writes `value` as `n` bits, MSB first, at bit `pos`. + fn put_bits(data: &mut [u8], pos: usize, n: u32, value: u32) { + for i in 0..n as usize { + if value >> (n as usize - 1 - i) & 1 == 1 { + data[(pos + i) / 8] |= 1 << (7 - (pos + i) % 8); + } + } + } + + /// A damaged packet whose first frame says it is 0 bits long: finding + /// the frame after a later one must give up, not walk in place forever + /// (found by random-input testing). + #[test] + fn a_zero_length_frame_before_the_start_ends_the_search() { + let mut data = vec![0u8; PACKET_BYTES]; + // Two frames, the first at payload bit 0; its 15-bit length stays 0. + put_bits(&mut data, 0, 32, 2 << 26); + let start = HEADER_BITS + 100; + put_bits(&mut data, start, LENGTH_BITS, 200); + let frame = read_frame(&data, start).expect("the frame at `start` is well formed"); + assert_eq!(frame.bits, 200); + assert_eq!(frame.next, None); + } + /// The direct sum `imdct_half` stands for (FFmpeg's naive inverse MDCT: /// the standard formula, negated). fn imdct_reference(input: &[f32]) -> Vec { From d4ed2de2f474ab867e0ea4f50ebaa523a87c4dd2 Mon Sep 17 00:00:00 2001 From: raffclar Date: Mon, 23 Nov 2026 23:08:01 +0000 Subject: [PATCH 002/445] Process exit: start the watchdog before other threads end The exit code ended the other threads first and then started the watchdog. A thread that ends can hold the heap lock or the loader lock. A new thread needs both, so the watchdog did not start and the exit did not stop. Now the exit code starts the watchdog and waits until it runs its own code: only then are its loader notices and Rust's thread set-up done. The watchdog publishes its thread id, and end_other_threads does not end it. The wait has the same deadline as the detach, because this thread, or a thread that waits for it, can hold the loader lock; then the watchdog cannot start. After the deadline the watchdog only ends the process. It does not log, because logging needs the heap and the lock of the log writer. The exit test now also checks that a thread in `keep` is not ended. --- crates/victory-loader/src/threads.rs | 137 +++++++++++++++++++-------- 1 file changed, 98 insertions(+), 39 deletions(-) diff --git a/crates/victory-loader/src/threads.rs b/crates/victory-loader/src/threads.rs index a4333b2..903aebd 100644 --- a/crates/victory-loader/src/threads.rs +++ b/crates/victory-loader/src/threads.rs @@ -6,9 +6,9 @@ //! callbacks, then a DLL's `DllMain`. use std::ffi::c_void; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::{Arc, Mutex}; -use std::time::Duration; +use std::time::{Duration, Instant}; use crate::{DLL_PROCESS_DETACH, LoadedImage}; @@ -99,20 +99,35 @@ extern "C" fn detach_all() { "process exit: ending other threads, detaching title images" ); EXITING.store(true, Ordering::SeqCst); - end_other_threads(); // As on Windows, a lock a thread held when it ended stays taken; detach - // code that waits for one would hang the exit. - std::thread::spawn(|| { + // code that waits for one would hang the exit. The watchdog runs before + // the other threads end: a thread that ends can hold the heap lock or + // the loader lock, and a new thread needs both to start. After the + // deadline it only ends the process; it does not log, because logging + // needs the heap and the log writer's lock. + // Its thread id, set when it runs its own code; 0 until then. + static WATCHDOG: AtomicU32 = AtomicU32::new(0); + drop(std::thread::spawn(|| { + // SAFETY: a plain query of the calling thread. + let id = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + WATCHDOG.store(id, Ordering::SeqCst); std::thread::sleep(DETACH_DEADLINE); - tracing::warn!("process exit: title images did not detach in time; ending"); - // SAFETY: ends this process, which is exiting anyway. - unsafe { - windows_sys::Win32::System::Threading::TerminateProcess( - windows_sys::Win32::System::Threading::GetCurrentProcess(), - 1, - ) - }; - }); + end_process(); + })); + // Its start (loader notices, Rust's thread set-up) is done only when + // it runs its own code. The loader notices need the loader lock. This + // thread can hold it, or a thread that waits for this thread can hold + // it. Then the watchdog does not start, so this wait has the same + // deadline. + let waiting = Instant::now(); + let watchdog = loop { + match WATCHDOG.load(Ordering::SeqCst) { + 0 if waiting.elapsed() >= DETACH_DEADLINE => end_process(), + 0 => std::thread::yield_now(), + id => break id, + } + }; + end_other_threads(&[watchdog]); for image in dlls.iter().chain(&exes) { // SAFETY: attached images are bound. A non-null third argument // tells the entry points the process is ending. @@ -126,11 +141,24 @@ extern "C" fn detach_all() { } } -/// Ends every thread of the process but this one (and the ones started -/// while doing so), as `ExitProcess` does first; except the system's -/// thread-pool workers, which `TerminateThread` refuses (the process fails -/// fast) and which run no title code (no title image uses that pool). -fn end_other_threads() { +/// Ends this process when the title images do not detach in time. It does +/// not use the heap or any lock: a thread that ended can hold them. +fn end_process() { + // SAFETY: ends this process, which is exiting anyway. + unsafe { + windows_sys::Win32::System::Threading::TerminateProcess( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + 1, + ) + }; +} + +/// Ends every thread of the process but this one and those in `keep` (and +/// the ones started while doing so), as `ExitProcess` does first; except +/// the system's thread-pool workers, which `TerminateThread` refuses (the +/// process fails fast) and which run no title code (no title image uses +/// that pool). +fn end_other_threads(keep: &[u32]) { use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; use windows_sys::Win32::System::Diagnostics::ToolHelp::{ CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, @@ -156,7 +184,10 @@ fn end_other_threads() { let mut ids = Vec::new(); let mut more = Thread32First(snapshot, &mut entry) != 0; while more { - if entry.th32OwnerProcessID == process && entry.th32ThreadID != me { + if entry.th32OwnerProcessID == process + && entry.th32ThreadID != me + && !keep.contains(&entry.th32ThreadID) + { ids.push(entry.th32ThreadID); } more = Thread32Next(snapshot, &mut entry) != 0; @@ -338,32 +369,57 @@ fn starts_in(thread: windows_sys::Win32::Foundation::HANDLE, module: &std::ffi:: #[cfg(test)] mod tests { - use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use std::time::Duration; - /// In a child process of the next test: ends the other threads and - /// checks that a busy one stopped. + /// A thread that counts in `ticks` until it ends; returns its thread id + /// when it has counted once. + fn busy(ticks: &'static AtomicU64) -> u32 { + static ID: AtomicU32 = AtomicU32::new(0); + ID.store(0, Ordering::SeqCst); + std::thread::spawn(move || { + // SAFETY: a plain query of the calling thread. + let id = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + ID.store(id, Ordering::SeqCst); + loop { + ticks.fetch_add(1, Ordering::SeqCst); + std::thread::yield_now(); + } + }); + while ticks.load(Ordering::SeqCst) == 0 { + std::thread::yield_now(); + } + ID.load(Ordering::SeqCst) + } + + /// Whether `ticks` stays the same for a short time. + fn stopped(ticks: &AtomicU64) -> bool { + let at = ticks.load(Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(50)); + ticks.load(Ordering::SeqCst) == at + } + + /// In a child process of the next test: ends the other threads but one + /// kept thread, and checks that a busy thread stopped and the kept one + /// did not. #[test] fn exit_child() { if std::env::var_os("VICTORY_EXIT_CHILD").is_none() { return; } - static TICKS: AtomicU64 = AtomicU64::new(0); - std::thread::spawn(|| { - loop { - TICKS.fetch_add(1, Ordering::SeqCst); - std::thread::yield_now(); - } - }); - while TICKS.load(Ordering::SeqCst) == 0 { - std::thread::yield_now(); - } - super::end_other_threads(); - let at = TICKS.load(Ordering::SeqCst); - std::thread::sleep(Duration::from_millis(50)); - let ended = TICKS.load(Ordering::SeqCst) == at; + static ENDS: AtomicU64 = AtomicU64::new(0); + static KEPT: AtomicU64 = AtomicU64::new(0); + busy(&ENDS); + let kept = busy(&KEPT); + super::end_other_threads(&[kept]); + let ended = stopped(&ENDS); + let still_running = !stopped(&KEPT); // The test harness's threads are gone too: leave at once. - println!("{}", if ended { "ENDED" } else { "STILL RUNNING" }); + println!( + "{} {}", + if ended { "ENDED" } else { "STILL RUNNING" }, + if still_running { "KEPT" } else { "NOT KEPT" } + ); std::process::exit(0); } @@ -375,6 +431,9 @@ mod tests { .output() .unwrap(); let text = String::from_utf8_lossy(&out.stdout); - assert!(out.status.success() && text.contains("ENDED"), "{text}"); + assert!( + out.status.success() && text.contains("ENDED KEPT"), + "{text}" + ); } } From e6a2c5471aa80e5669c78e424cadc9cf428208df Mon Sep 17 00:00:00 2001 From: 9hvn9yt2vk-netizen <360448330+9hvn9yt2vk-netizen@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:01:09 +0100 Subject: [PATCH 003/445] texture: refuse extents past 16384 texels instead of overflowing Layout::new checked that width, height and depth are non-zero but not that they are bounded, so values a title passes unchecked (up to u32::MAX) overflowed the size arithmetic: `offset * depth` in the linear layout, `slice_size * slices` and the per-mip sizes in the tiled one, and a u32 next_multiple_of in Layout::tiled. Debug builds panicked; release builds wrapped silently and returned a wrong size. Refuse anything past 16384 texels per side, the most a GFX10 image descriptor holds, so no texture the GPU can use is affected. Found with a random-input harness (four distinct overflow sites, none left after this change). --- crates/victory-formats/src/texture.rs | 34 ++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 8752447..73ef98d 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -249,6 +249,13 @@ fn spread(bits: &[u32]) -> Vec { const MAX_MIPS: u32 = 16; +/// The largest width, height and depth (or array size) accepted, in texels. +/// GFX10's image descriptors hold at most 16384 texels per side, so no +/// texture the GPU can use is refused. The bound also keeps every size +/// computed below within `u64` (and its `u32` steps), which unchecked +/// values from a title would otherwise overflow. +const MAX_EXTENT: u32 = 1 << 14; + /// 256-byte micro tile dimensions by log2 element size, 2D and 3D. const BLOCK_256_2D: [[u32; 2]; 5] = [[16, 16], [16, 8], [8, 8], [8, 4], [4, 4]]; const BLOCK_256_3D: [[u32; 3]; 5] = [[8, 4, 8], [4, 4, 8], [4, 4, 4], [4, 2, 4], [2, 2, 4]]; @@ -258,9 +265,9 @@ impl Layout { pub fn new(desc: &Desc) -> Result { let d = *desc; let block_log2 = d.swizzle.block_log2().ok_or(Error::Invalid)?; - let valid = d.width > 0 - && d.height > 0 - && d.depth > 0 + let valid = (1..=MAX_EXTENT).contains(&d.width) + && (1..=MAX_EXTENT).contains(&d.height) + && (1..=MAX_EXTENT).contains(&d.depth) && (1..=MAX_MIPS).contains(&d.mips) && d.element_bytes.is_power_of_two() && d.element_bytes <= 16 @@ -838,6 +845,27 @@ mod tests { } } + /// Sizes past the hardware's 16384 texels per side are refused instead + /// of overflowing the size arithmetic (found by random-input testing). + #[test] + fn extents_past_the_hardware_limit_are_invalid() { + for swizzle in [Swizzle::LINEAR, Swizzle::SW_64KB_D_X] { + let largest = Layout::new(&desc(MAX_EXTENT, MAX_EXTENT, 15, 16, swizzle)).unwrap(); + assert!(largest.size >= u64::from(MAX_EXTENT) * u64::from(MAX_EXTENT) * 16); + for (w, h) in [ + (MAX_EXTENT + 1, 1), + (1, MAX_EXTENT + 1), + (u32::MAX, u32::MAX), + ] { + let result = Layout::new(&desc(w, h, 1, 16, swizzle)); + assert_eq!(result, Err(Error::Invalid), "{w}x{h}"); + } + let mut deep = desc(1, 1, 1, 16, swizzle); + deep.depth = u32::MAX; + assert_eq!(Layout::new(&deep), Err(Error::Invalid)); + } + } + #[test] fn blocks_hold_their_size_in_elements() { for log2 in [8u32, 12, 16] { From 36eb0b4ea78e5a30482639ac085a3e34e9562d0c Mon Sep 17 00:00:00 2001 From: Marvis Date: Mon, 23 Nov 2026 23:51:56 +0100 Subject: [PATCH 004/445] Shaders: med3 with NaN, fract below 1.0, signed bit fields past bit 31 Three lowerings gave results the console's GPU does not (issue #2, from hardware measurements published by another project): - v_med3_f32/f16: with a NaN operand the hardware gives the minimum of the three; we gave the median of the other two. - v_fract_f32/f16: the hardware never reaches 1.0 (a tiny negative input gives the largest value below it); the host's own fract differs by vendor and can give 1.0. - v_bfe_i32/s_bfe_i32: a signed field running past bit 31 extends from bit 31; the shift is arithmetic now. Fields that fit are unchanged. The fract case is asserted in float_semantics_are_the_consoles (the console compiler emits v_fract_f32 for frac). The other two cannot be produced from HLSL with the compiler the tests use and rest on the measured values in the issue. Still open from the issue: range reduction before sine and cosine, and denormal operands of the legacy multiply. Refs #2 Co-Authored-By: Claude Fable 5.2 --- crates/victory-shader/src/emit/diff_tests.rs | 13 +++- crates/victory-shader/src/emit/lower.rs | 62 +++++++++++++++----- 2 files changed, 56 insertions(+), 19 deletions(-) diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index a5ad838..2f0d6f3 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -977,8 +977,9 @@ fn translated_mesh_shaders_draw_as_pc_ones() { /// Where PC code and the console differ by design, the translation must /// give the console's results: float-to-int conversions saturate and give -/// 0 for NaN (`v_cvt_i32/u32_f32`), and the legacy multiply the compiler -/// uses for `*` gives 0 for 0 × NaN. +/// 0 for NaN (`v_cvt_i32/u32_f32`), the legacy multiply the compiler +/// uses for `*` gives 0 for 0 × NaN, and `frac` never reaches 1.0 (it gives +/// the largest value below; some hosts' own `frac` gives 1.0). #[test] fn float_semantics_are_the_consoles() { use super::host::{Dispatch, View}; @@ -998,6 +999,8 @@ fn float_semantics_are_the_consoles() { outb.Store(4 * i, asuint(int(x))); outb.Store(16 + 4 * i, uint(x)); outb.Store(32 + 4 * i, asuint(x * k.w)); + float y = i == 0 ? k.w - 1e-10 : i == 1 ? k.z : i == 2 ? k.w - 1e-8 : k.z + 0.25; + outb.Store(48 + 4 * i, asuint(frac(y))); }"#; let cs = translate(&compile(&console, &dir, src, "cs", "cs_6_5")).unwrap(); let (root, pso) = host.compute_pipeline(&cs).unwrap(); @@ -1009,7 +1012,7 @@ fn float_semantics_are_the_consoles() { View::Texture(1, 1, &[[0.0; 4]]), View::Texture(1, 1, &[[0.0; 4]]), View::Texture(1, 1, &[[0.0; 4]]), - View::RawUav(12), + View::RawUav(16), View::TextureUav(1, 1), ]; let out = host @@ -1040,6 +1043,10 @@ fn float_semantics_are_the_consoles() { 0, 0, 0, // x * 0, NaN included + 0x3F7F_FFFF, + 0.5f32.to_bits(), + 0x3F7F_FFFF, + 0.75f32.to_bits(), // frac ] ); } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 9a8ac9c..317336f 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1356,7 +1356,9 @@ impl<'a> Lower<'a> { } /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's - /// top bit when `signed`; widths from 32 on take every bit. + /// top bit when `signed`; widths from 32 on take every bit. A signed + /// field that runs past bit 31 extends from bit 31, as the hardware + /// does: the shift is arithmetic then. fn bfe(&mut self, a: V, off: V, width: V, signed: bool) -> V { let c = self.cur; let (k31, k32, zero, one, ones) = ( @@ -1367,7 +1369,8 @@ impl<'a> Lower<'a> { self.s.m.i32(u32::MAX), ); let off = self.s.m.bin(c, Bin::And, off, k31); - let shifted = self.s.m.bin(c, Bin::LShr, a, off); + let shift = if signed { Bin::AShr } else { Bin::LShr }; + let shifted = self.s.m.bin(c, shift, a, off); let full = self.s.m.cmp(c, pred::IUGE, width, k32); let w = self.s.m.bin(c, Bin::And, width, k31); let mask = self.s.m.bin(c, Bin::Shl, one, w); @@ -1387,6 +1390,34 @@ impl<'a> Lower<'a> { self.s.m.select(c, keep, r, t) } + /// The median of three. With a NaN among them the hardware gives the + /// minimum of the three instead (the host's minimum skips NaNs, so that + /// is the smallest number among them). + fn med3(&mut self, a: V, b: V, third: V) -> V { + let c = self.cur; + let lo = self.binary(36, a, b); + let hi = self.binary(35, a, b); + let t = self.binary(36, hi, third); + let median = self.binary(35, lo, t); + let least = self.binary(36, lo, third); + let ab = self.s.m.cmp(c, pred::UNO, a, b); + let nan3 = self.s.m.cmp(c, pred::UNO, third, third); + let nan = self.s.m.bin(c, Bin::Or, ab, nan3); + self.s.m.select(c, nan, least, median) + } + + /// `a - floor(a)`, which on the hardware never reaches 1.0: where it + /// would round to it (a tiny negative `a`), the result is `below_one`, + /// the largest value under 1.0 in the operation's width. Hosts differ + /// here (some give 1.0). NaN stays NaN. + fn fract(&mut self, a: V, below_one: f32) -> V { + let c = self.cur; + let r = self.unary(22, a); + let k = self.s.m.f32(below_one.to_bits()); + let over = self.s.m.cmp(c, pred::OGT, r, k); + self.s.m.select(c, over, k, r) + } + /// The high dword of a 32 × 32-bit product. fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V { let c = self.cur; @@ -3624,12 +3655,7 @@ impl<'a> Lower<'a> { let t = self.binary(36, a, bb); self.binary(36, t, cc) } - _ => { - let lo = self.binary(36, a, bb); - let hi = self.binary(35, a, bb); - let t = self.binary(36, hi, cc); - self.binary(35, lo, t) - } + _ => self.med3(a, bb, cc), }; float(self, r) } @@ -3662,7 +3688,11 @@ impl<'a> Lower<'a> { let k = self.s.m.f32(TWO_PI.to_bits()); a = self.s.m.bin(c, Bin::Mul, a, k); } - let r = self.unary(op, a); + let r = if op == 22 { + self.fract(a, f32::from_bits(0x3F7F_FFFF)) + } else { + self.unary(op, a) + }; float(self, r) } "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => { @@ -4221,12 +4251,7 @@ impl<'a> Lower<'a> { let t = self.binary(36, a, b); self.binary(36, t, acc) } - _ => { - let lo = self.binary(36, a, b); - let hi = self.binary(35, a, b); - let t = self.binary(36, hi, acc); - self.binary(35, lo, t) - } + _ => self.med3(a, b, acc), }; return float_result(self, r); } @@ -4268,7 +4293,12 @@ impl<'a> Lower<'a> { let k = self.s.m.f32(TWO_PI.to_bits()); a = self.s.m.bin(c, Bin::Mul, a, k); } - self.unary(op, a) + if op == 22 { + // 0x3bff as a half: 1 - 2^-11. + self.fract(a, 1.0 - 1.0 / 2048.0) + } else { + self.unary(op, a) + } } }; return float_result(self, r); From 0b499d7afd74652bfdd19d0f2e5823c91fe6bef7 Mon Sep 17 00:00:00 2001 From: Marvis Date: Tue, 24 Nov 2026 00:00:19 +0100 Subject: [PATCH 005/445] Shaders: sine and cosine in turns, exact zeros at half and quarter turns v_sin and v_cos (f32 and f16) take an angle in turns. The whole turns now come off first (x - round_even(x), exact), so a large angle keeps its fraction of a turn instead of losing it when scaled to radians. The sine of a half turn and the cosine of a quarter turn are exactly +0, as the hardware gives; the host's functions of the rounded angle give about 1e-7. A zero operand passes unreduced, so sin(-0) stays -0. float_semantics_are_the_consoles asserts the exact zeros (it failed before this change). The compiler the tests use takes whole turns off itself, so the large-angle path cannot be reached from HLSL and rests on the measurements cited in issue #2. Left from the issue: denormal operands of the legacy multiply, which needs the float mode register as state first. Refs #2 Co-Authored-By: Claude Fable 5.2 --- crates/victory-shader/src/emit/diff_tests.rs | 21 ++++++-- crates/victory-shader/src/emit/lower.rs | 55 +++++++++++++------- 2 files changed, 53 insertions(+), 23 deletions(-) diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index 2f0d6f3..fdc02aa 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -978,8 +978,12 @@ fn translated_mesh_shaders_draw_as_pc_ones() { /// Where PC code and the console differ by design, the translation must /// give the console's results: float-to-int conversions saturate and give /// 0 for NaN (`v_cvt_i32/u32_f32`), the legacy multiply the compiler -/// uses for `*` gives 0 for 0 × NaN, and `frac` never reaches 1.0 (it gives -/// the largest value below; some hosts' own `frac` gives 1.0). +/// uses for `*` gives 0 for 0 × NaN, `frac` never reaches 1.0 (it gives +/// the largest value below; some hosts' own `frac` gives 1.0), and sine +/// and cosine take turns: the sine of a half turn and the cosine of a +/// quarter turn are exactly +0 (the host's functions of the rounded angle +/// give about 1e-7). The compiler takes whole turns off itself, so large +/// angles cannot be tried from here. #[test] fn float_semantics_are_the_consoles() { use super::host::{Dispatch, View}; @@ -1001,6 +1005,9 @@ fn float_semantics_are_the_consoles() { outb.Store(32 + 4 * i, asuint(x * k.w)); float y = i == 0 ? k.w - 1e-10 : i == 1 ? k.z : i == 2 ? k.w - 1e-8 : k.z + 0.25; outb.Store(48 + 4 * i, asuint(frac(y))); + float r = i == 0 ? k.w + 3.14159274 : i == 1 ? k.w + 1.0 + : i == 2 ? k.w - 3.14159274 : k.w + 1.57079637; + outb.Store(64 + 4 * i, asuint(i == 3 ? cos(r) : sin(r))); }"#; let cs = translate(&compile(&console, &dir, src, "cs", "cs_6_5")).unwrap(); let (root, pso) = host.compute_pipeline(&cs).unwrap(); @@ -1012,7 +1019,7 @@ fn float_semantics_are_the_consoles() { View::Texture(1, 1, &[[0.0; 4]]), View::Texture(1, 1, &[[0.0; 4]]), View::Texture(1, 1, &[[0.0; 4]]), - View::RawUav(16), + View::RawUav(20), View::TextureUav(1, 1), ]; let out = host @@ -1029,7 +1036,7 @@ fn float_semantics_are_the_consoles() { .unwrap(); let _ = std::fs::remove_dir_all(&dir); assert_eq!( - out[0], + out[0][..16], [ 0x7FFF_FFFF, 0x8000_0000, @@ -1049,6 +1056,12 @@ fn float_semantics_are_the_consoles() { 0.75f32.to_bits(), // frac ] ); + // sin(pi), sin(-pi) and cos(pi/2): the compiler turns radians into + // exactly 0.5, -0.5 and 0.25 turns. + assert_eq!([out[0][16], out[0][18], out[0][19]], [0, 0, 0]); + // An ordinary angle is untouched: sin(1 rad). + let one = f32::from_bits(out[0][17]); + assert!((one - 0.841_470_96).abs() < 1e-4, "{one}"); } /// Equal bits, both zero (the console's legacy multiply gives +0 where PC diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 317336f..1f6ab71 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1418,6 +1418,32 @@ impl<'a> Lower<'a> { self.s.m.select(c, over, k, r) } + /// Sine, or cosine, of an angle in turns, as the hardware takes it. The + /// whole turns are taken off first (`x - round_even(x)`, exact, within + /// half a turn), so a large angle keeps its fraction; scaling to radians + /// first rounds it away. A zero passes unreduced (the sine of -0 is -0). + /// The sine of a half turn and the cosine of a quarter turn are exactly + /// +0 on the hardware, where the host's function of the rounded angle + /// gives about 1e-7. Infinities and NaN give NaN. + /// shortcut: below 2^-12 turns the hardware scales by a slightly + /// different constant than 2π (a last-place difference). + fn trig_turns(&mut self, x: V, cosine: bool) -> V { + let c = self.cur; + let zero = self.s.m.f32(0); + let whole = self.unary(26, x); + let part = self.s.m.bin(c, Bin::Sub, x, whole); + let is_zero = self.s.m.cmp(c, pred::OEQ, x, zero); + let part = self.s.m.select(c, is_zero, x, part); + let k = self.s.m.f32(TWO_PI.to_bits()); + let angle = self.s.m.bin(c, Bin::Mul, part, k); + let r = self.unary(if cosine { 12 } else { 13 }, angle); + let at = if cosine { 0.25f32 } else { 0.5 }; + let at = self.s.m.f32(at.to_bits()); + let size = self.unary(6, part); + let exact = self.s.m.cmp(c, pred::OEQ, size, at); + self.s.m.select(c, exact, zero, r) + } + /// The high dword of a 32 × 32-bit product. fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V { let c = self.cur; @@ -3669,7 +3695,7 @@ impl<'a> Lower<'a> { "v_rsq_f32" | "v_sqrt_f32" | "v_log_f32" | "v_exp_f32" | "v_fract_f32" | "v_trunc_f32" | "v_floor_f32" | "v_ceil_f32" | "v_rndne_f32" | "v_sin_f32" | "v_cos_f32" => { - let mut a = f(self, 0)?; + let a = f(self, 0)?; let op = match name { "v_rsq_f32" => 25, "v_sqrt_f32" => 24, @@ -3683,15 +3709,10 @@ impl<'a> Lower<'a> { "v_sin_f32" => 13, _ => 12, }; - if op == 13 || op == 12 { - // The hardware takes revolutions. - let k = self.s.m.f32(TWO_PI.to_bits()); - a = self.s.m.bin(c, Bin::Mul, a, k); - } - let r = if op == 22 { - self.fract(a, f32::from_bits(0x3F7F_FFFF)) - } else { - self.unary(op, a) + let r = match op { + 12 | 13 => self.trig_turns(a, op == 12), + 22 => self.fract(a, f32::from_bits(0x3F7F_FFFF)), + _ => self.unary(op, a), }; float(self, r) } @@ -4275,7 +4296,7 @@ impl<'a> Lower<'a> { self.s.m.bin(c, Bin::SDiv, one, a) } _ => { - let mut a = self.half_fsrc(inst, 0)?; + let a = self.half_fsrc(inst, 0)?; let op = match name { "v_sqrt_f16" => 24, "v_rsq_f16" => 25, @@ -4289,15 +4310,11 @@ impl<'a> Lower<'a> { "v_sin_f16" => 13, _ => 12, }; - if op == 13 || op == 12 { - let k = self.s.m.f32(TWO_PI.to_bits()); - a = self.s.m.bin(c, Bin::Mul, a, k); - } - if op == 22 { + match op { + 12 | 13 => self.trig_turns(a, op == 12), // 0x3bff as a half: 1 - 2^-11. - self.fract(a, 1.0 - 1.0 / 2048.0) - } else { - self.unary(op, a) + 22 => self.fract(a, 1.0 - 1.0 / 2048.0), + _ => self.unary(op, a), } } }; From 8c26061f3a467cc5798f5d77469bcfe73e333e73 Mon Sep 17 00:00:00 2001 From: Marvis Date: Tue, 24 Nov 2026 00:12:44 +0100 Subject: [PATCH 006/445] GPU: the world stays up; indirect execution behind a switch The host device was removed seconds into the world because a shader read a descriptor of the wrong kind: empty slots held a null 2D texture view where the shader expected a buffer, which gave a garbage heap index and a read far past the view heap. Null descriptors now have the kind the shader expects (raw buffer, constant buffer, or a texture of the title's own dimension). The world then ran to a 240 s time limit with no removal. Also: - Host lists hold the textures, pipelines, root signatures and heaps they name, and heap slots hold the resource they view (the title releases objects before submitting lists that use them). - The device-removed report places the fault against the host descriptor heaps and names our own uploads; VICTORY_D3D12_GBV turns on GPU-based validation, VICTORY_DUMP_TARGETS works. - Indirect execution (draw, indexed draw, dispatch, mesh dispatch): the world draws most of its geometry this way. Arguments are clamped and charged to a per-list budget by a small compute pass first, so garbage cannot hang the GPU. Off by default (VICTORY_INDIRECT=1): with it on the title's own GPU watchdog ends the run about 30 s into the world. - Shader-written ranges are copied back once per submission and only where they differ; refreshes beside them copy only stale pages. The frame-rate line counts copy-backs and dropped draws. Not working yet: the world's picture is black (indirect draws off, and hundreds of draws per frame have no translated shader). Co-Authored-By: Claude Fable 5.2 --- README.md | 6 +- crates/victory-gpu/Cargo.toml | 1 + crates/victory-gpu/src/capture.rs | 36 ++-- crates/victory-gpu/src/descriptor/host.rs | 195 +++++++++++++++---- crates/victory-gpu/src/draw.rs | 154 ++++++++++++++- crates/victory-gpu/src/host.rs | 216 ++++++++++++++++++---- crates/victory-gpu/src/indirect.rs | 209 +++++++++++++++++++++ crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/list.rs | 113 +++++++++-- crates/victory-gpu/src/pipeline/host.rs | 3 + crates/victory-gpu/src/resource.rs | 80 +++++--- crates/victory-gpu/src/shadow.rs | 58 ++++-- crates/victory-gpu/src/signature.rs | 11 ++ crates/victory-gpu/src/texture.rs | 40 ++++ 14 files changed, 973 insertions(+), 151 deletions(-) create mode 100644 crates/victory-gpu/src/indirect.rs diff --git a/README.md b/README.md index 2da9b45..3c0b5a9 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ loads the world, where rendering fails. | Intro video with sound | works | | Start screen, profile and saves | works | | Loading into the world (about 50 s) | works | -| The world (first mission's intro) | reached; the picture is black and the host GPU fails within seconds | +| The world (first mission's intro) | reached and runs (two minutes without a GPU failure); the picture is black, 1.5-3 s per frame | Tested on one machine: Windows 11, AMD RX 6700 XT. @@ -39,7 +39,7 @@ What each part does today and what it still needs: | Input | XInput pads, keyboard, keyboard stand-in pad | Trigger rumble | | Audio | Menu, video and loading sound; XMA voices and Opus streams decode | Reverb is silent; Opus results unverified against the title | | GPU: menus | Draws, compute and presentation on host D3D12; only changed title memory is copied | Frame pacing drifts on one screen in release builds | -| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes are in | The host device is lost and frames are black; frames take seconds; indirect dispatches, real queries, depth bounds, HDR and scaling are missing | +| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped) are in | Frames are black (most geometry is drawn indirectly; untranslated shaders drop the rest); frames take seconds; real queries, depth bounds, HDR and scaling are missing | | Shaders | Console GPU code recompiled to DXIL at first use, cached on disk. Menus: all. World: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539 | 64-bit image atomics, merged geometry stages, the ray-tracing builder's shaders; some compute programs need a GPU with 64-lane waves | | Textures | Console tiled layouts and detiling for the modes the title uses | Render-target metadata planes | | Series S mode | Runs through the menus to the loading screen | The world, as above | @@ -114,6 +114,8 @@ cargo build --profile diag -p victory --features diagnostics # target\diag\vic | `VICTORY_CAPTURE=` | saves presented frames (powers of two, or `VICTORY_CAPTURE_FRAMES=`) | | `VICTORY_DUMP_TARGETS=1` | with the two above, saves every render target of those frames | | `VICTORY_D3D12_DEBUG=1` | host debug layer | +| `VICTORY_INDIRECT=1` | runs the title's indirect draws and dispatches (off: the world's first frame stalls with it) | +| `VICTORY_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) | | `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | | `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | | `VICTORY_AUDIO_CAPTURE=` | records what the title plays (our process only) | diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index 70a01a9..a24dd1a 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -30,6 +30,7 @@ workspace = true windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D_Fxc", "Win32_Graphics_Direct3D12", "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common", diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index b886893..28c2569 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -203,7 +203,10 @@ pub(crate) fn save_read_back( /// at that frame's present as `frame----x-f.png` /// (what each holds at the end of the frame; formats normalized to show /// structure: floats scaled by their largest value, depth by its range). -static TARGETS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +/// The host copies are held: the title may release a target before the +/// frame is presented. +static TARGETS: std::sync::Mutex)>> = + std::sync::Mutex::new(Vec::new()); fn dump_on() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -216,33 +219,28 @@ pub(crate) fn note_target(resource: crate::object::This) { return; } let mut targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner()); - if !targets.contains(&(resource as usize)) { - targets.push(resource as usize); + if !targets.iter().any(|&(r, _)| r == resource as usize) + && let Some(copy) = crate::resource::host_copy(resource) + { + targets.push((resource as usize, copy)); } } /// At the present of frame `frame`: saves the noted targets. pub(crate) fn dump_targets(frame: u64) { + use std::sync::atomic::Ordering::Relaxed; let targets = std::mem::take(&mut *TARGETS.lock().unwrap_or_else(|e| e.into_inner())); let Some(host) = crate::host::host() else { return }; - for (i, &resource) in targets.iter().enumerate() { - let resource = resource as crate::object::This; - let Some(texture) = crate::resource::host_resource(resource) else { - continue; - }; + for (i, (resource, copy)) in targets.iter().enumerate() { + let texture = ©.texture; // SAFETY: a live resource. let d = unsafe { texture.GetDesc() }; if d.SampleDesc.Count > 1 || d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D { continue; } - const COPY_SOURCE: u32 = 0x800; - let Some(before) = crate::resource::host_transition(resource, COPY_SOURCE).map(|(_, b)| b) - else { - dump_one(host, texture, COPY_SOURCE, frame, i, resource, &d); - continue; - }; - dump_one(host, texture, before, frame, i, resource, &d); - crate::resource::host_transition(resource, before); + // Every submission has run; the dump's list moves it there and back. + let state = copy.state.load(Relaxed); + dump_one(host, texture, state, frame, i, *resource as crate::object::This, &d); } } @@ -363,8 +361,10 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option 15..=16 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)), f32::from_bits(u32_at(b, 1)), 0.0])), 35..=38 => (4, Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0])), 48..=52 => (2, Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0])), - // Single channels: shown as grey. + // Single channels (and depth planes): shown as grey. 39..=43 => (4, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])), + 19..=22 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])), + 44..=47 => (4, Box::new(move |b| [(u32_at(b, 0) & 0xff_ffff) as f32; 3])), 53..=54 => (2, Box::new(move |b| [half(u16_at(b, 0)); 3])), 55..=59 => (2, Box::new(move |b| [f32::from(u16_at(b, 0)); 3])), 60..=65 => (1, Box::new(move |b| [f32::from(b[0]); 3])), @@ -374,7 +374,7 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option .flat_map(|y| (0..w).map(move |x| (x, y))) .map(|(x, y)| decode(px(x, y, n))) .collect(); - let grey = matches!(format, 39..=43 | 53..=65); + let grey = matches!(format, 19..=22 | 39..=47 | 53..=65); let finite = values.iter().flatten().copied().filter(|v| v.is_finite()); let (low, high) = if grey { finite.fold((f32::MAX, f32::MIN), |(l, h), v| (l.min(v), h.max(v))) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 27655d1..3a79aae 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -22,11 +22,39 @@ pub(crate) struct HostHeap { sampler: bool, /// The record (view index and generation) each slot was last made from. made: Mutex>, + /// The host resource each slot views, held while the slot does: shaders + /// index heaps directly, so a slot the title has not rewritten since it + /// released the resource may still be read, and a freed host resource + /// read there is a GPU page fault (the console reads stale memory). + kept: Mutex>>, /// Where the search for free dynamic slots starts, and which are taken /// (by lists not yet reset). next: Mutex<(u32, Vec)>, } +/// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for +/// device-removed reports: a shader indexing a heap past its end faults. +static GPU_RANGES: Mutex> = Mutex::new(Vec::new()); + +/// For device-removed reports: where host GPU address `va` lies against +/// the host descriptor heaps. +pub(crate) fn near_heaps(va: u64) -> String { + let ranges = GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()); + let mut text = String::new(); + for &(start, bytes, step, sampler) in ranges.iter() { + let kind = if sampler { "sampler" } else { "view" }; + let place = if va < start { + format!("{:#x} below", start - va) + } else if va < start + bytes { + format!("inside, slot {}", (va - start) / step) + } else { + format!("{:#x} past its end (slot {})", va - start - bytes, (va - start) / step) + }; + text.push_str(&format!("; {kind} heap {start:#x}+{bytes:#x}: {place}")); + } + text +} + /// The host's limit for shader-visible view heaps on resource binding /// tiers 1 and 2; tier 3 hardware may take more. const PORTABLE_VIEWS: u32 = 1_000_000; @@ -78,6 +106,14 @@ impl HostHeap { ) }; tracing::debug!(count, sampler, "host descriptor heap"); + // SAFETY: a live shader-visible heap. + let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr }; + GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push(( + gpu, + u64::from(count + extra) * u64::from(step), + u64::from(step), + sampler, + )); let h = HostHeap { heap, cpu, @@ -85,6 +121,7 @@ impl HostHeap { count, sampler, made: Mutex::new(vec![0; count as usize]), + kept: Mutex::new(vec![None; (count + extra) as usize]), next: Mutex::new((0, vec![false; DYNAMIC as usize])), }; // A slot never written is undefined: shaders reading one (a slot @@ -215,9 +252,11 @@ impl HostHeap { /// Makes slot `index` (a dynamic one) from `view`; a null view if the /// host cannot. pub(crate) fn make_at(&self, index: u32, view: &View) { - if !make(view, self.cpu(index)) { + let kept = make(view, self.cpu(index)); + if kept.is_none() { null_for(view, self.cpu(index)); } + self.keep(index, kept.flatten()); } /// Makes slot `index` read nothing: a null view, or a plain sampler. @@ -227,11 +266,21 @@ impl HostHeap { } else { null_view(self.cpu(index)); } + self.keep(index, None); + } + + /// Slot `index` now views `resource` (or nothing of the host's). + fn keep(&self, index: u32, resource: Option) { + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(slot) = kept.get_mut(index as usize) { + *slot = resource; + } } /// Makes slot `index` (a dynamic one) a constant buffer view of host - /// memory. + /// memory (the list's own, which it holds). pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) { + self.keep(index, None); let Some(host) = host() else { return }; let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, @@ -276,9 +325,15 @@ impl HostHeap { if made[index as usize] != key { let later = !for_draw && view.is_buffer(); made[index as usize] = if later { 0 } else { key }; - if (later || !make(&view, self.cpu(index))) && !self.sampler { + let kept = if later { + None + } else { + make(&view, self.cpu(index)) + }; + if kept.is_none() && !self.sampler { null_for(&view, self.cpu(index)); } + self.keep(index, kept.flatten()); } Some(view) } @@ -398,15 +453,16 @@ fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { )) } +/// The host resource a slot made by [`make`] views, if any. +type Kept = Option; + fn buffer_srv( address: u64, len: u64, mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE, -) -> bool { - let Some(shadow) = crate::shadow::find(address, len) else { - return false; - }; +) -> Option { + let shadow = crate::shadow::find(address, len)?; let element = element_size(&desc); // SAFETY: a buffer view's union member. let buffer = unsafe { &mut desc.Anonymous.Buffer }; @@ -417,16 +473,16 @@ fn buffer_srv( element, "buffer view not on an element of its host copy" ); - return false; + return None; } buffer.FirstElement += offset / element; - let Some(host) = host() else { return false }; + let host = host()?; // SAFETY: a live buffer and a slot of our heap. unsafe { host.device .CreateShaderResourceView(&shadow.buffer, Some(&desc), at) }; - true + Some(Some(shadow.buffer.clone())) } /// An unordered access view of title buffer memory at `address` (`len` @@ -439,15 +495,13 @@ fn buffer_uav( len: u64, mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE, -) -> bool { - let Some(shadow) = crate::shadow::find(address, len) else { - return false; - }; +) -> Option { + let shadow = crate::shadow::find(address, len)?; // SAFETY: a live buffer. let flags = unsafe { shadow.buffer.GetDesc() }.Flags; if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { once!("unordered access to a buffer whose host copy shaders cannot write"); - return false; + return None; } // SAFETY: a buffer view's union member. let buffer = unsafe { &mut desc.Anonymous.Buffer }; @@ -461,17 +515,17 @@ fn buffer_uav( let offset = shadow.offset(address); if element == 0 || offset % element != 0 { once!(offset, element, "unordered buffer view not on an element of its host copy"); - return false; + return None; } buffer.FirstElement += offset / element; buffer.CounterOffsetInBytes = 0; - let Some(host) = host() else { return false }; + let host = host()?; // SAFETY: a live buffer and a slot of our heap. unsafe { host.device .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) }; - true + Some(Some(shadow.buffer.clone())) } /// Whether the host can make a shader (or unordered access) view of @@ -527,22 +581,21 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere true } -/// Makes the host descriptor for `view` at `at`; false if it cannot. -fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool { - let Some(host) = host() else { return false }; +/// Makes the host descriptor for `view` at `at`: the host resource it +/// views, or `None` if it cannot. +fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { + let host = host()?; let device = &host.device; match view { &View::Constant(address, size) => { - let Some(shadow) = crate::shadow::find(address, u64::from(size)) else { - return false; - }; + let shadow = crate::shadow::find(address, u64::from(size))?; let gpu = shadow.gpu(address); if gpu % 256 != 0 { once!( address = format_args!("{address:#x}"), "constant buffer not 256-byte aligned on the host" ); - return false; + return None; } let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, @@ -550,14 +603,14 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool { }; // SAFETY: a slot of our heap; the range lies in the host copy. unsafe { device.CreateConstantBufferView(Some(&desc), at) }; - true + Some(Some(shadow.buffer.clone())) } View::Shader(resource, desc) => { let resource = *resource as crate::object::This; if let Some(texture) = crate::resource::host_resource(resource) { let mut desc = desc.as_ref().map(srv_desc); if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { - return false; + return None; } // SAFETY: a live texture and a slot of our heap. unsafe { @@ -567,13 +620,13 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool { at, ) }; - true + Some(Some(texture.clone())) } else if let (Some((data, len)), Some(desc)) = (crate::resource::buffer_bytes(resource), desc) { buffer_srv(data as u64, len, srv_desc(desc), at) } else { - false + None } } View::Unordered(resource, _counter, desc) => { @@ -583,12 +636,12 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool { (Some((data, len)), Some(desc)) => { buffer_uav(data as u64, len, uav_desc(desc), at) } - _ => false, + _ => None, }; }; let mut desc = desc.as_ref().map(uav_desc); if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) { - return false; + return None; } // SAFETY: a live texture and a slot of our heap. unsafe { @@ -599,7 +652,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool { at, ) }; - true + Some(Some(texture.clone())) } View::Sampler(words) => { // SAFETY: 13 words in the host's layout. @@ -610,13 +663,13 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool { }; // SAFETY: a slot of our sampler heap. unsafe { device.CreateSampler(&desc, at) }; - true + Some(None) } View::ConsoleSampler(words) => { let desc = crate::sampler::console(words); // SAFETY: a slot of our sampler heap. unsafe { device.CreateSampler(&desc, at) }; - true + Some(None) } View::Placed(unordered, resource, desc) => { if let Some(view) = placed_texture(view) { @@ -628,7 +681,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool { // itself is not mirrored; give it a resource as shader // views of such textures get when a dispatch writes one. once!(dimension = resource[0], "placed unordered texture view not mirrored"); - return false; + return None; } // The resource description's width, after the alignment. let len = u64::from(resource[4]) | u64::from(resource[5]) << 32; @@ -662,12 +715,30 @@ pub(crate) fn placed_texture(view: &View) -> Option { /// cannot make: unordered access (to a buffer or a 2D texture) or a shader /// view. Writes to it are dropped, reads give zeros. fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some(); let buffer = match view { - View::Unordered(r, _, _) => crate::resource::buffer_bytes(*r as crate::object::This).is_some(), + View::Unordered(r, _, _) => is_buffer(r), View::Placed(true, resource, _) => resource[0] == 1, + // Shader views of buffers read nothing through a null buffer view: + // a null 2D view where the shader expects a buffer is a mismatch + // the hardware does not survive in general (GPU-based validation + // reports it). + View::Shader(r, _) if is_buffer(r) => return null_buffer_view(at), + View::Placed(false, resource, _) if resource[0] == 1 => return null_buffer_view(at), + // Textures: a null view of the title's dimension (1D, arrays, 3D, + // cubes), not always 2D. + View::Shader(_, Some(desc)) => return null_like(desc, at), + View::Placed(false, _, desc) => { + return null_like(desc[..10].try_into().unwrap_or(&[0; 10]), at); + } + View::Constant(..) => { + let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC::default(); + // SAFETY: a slot of our heap; a zero location makes a null view. + return unsafe { host.device.CreateConstantBufferView(Some(&desc), at) }; + } _ => return null_view(at), }; - let Some(host) = host() else { return }; let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_UINT, ViewDimension: if buffer { @@ -688,6 +759,56 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { }; } +/// A buffer view that reads zeros (raw, as translated shaders mostly read +/// buffers). +fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + NumElements: 1, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + ..Default::default() + }, + }, + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device + .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) + }; +} + +/// A texture view that reads zeros with the dimension (and mip and array +/// counts) of the title's description `words`; 2D if it names none. +fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) { + const TEXTURES: std::ops::RangeInclusive = 2..=10; + if !TEXTURES.contains(&words[1]) { + return null_view(at); + } + let Some(host) = host() else { return }; + // One mip, one slice or cube, plane 0: fields a null view still checks. + let mut w = [0u32; 10]; + w[1] = words[1]; + match words[1] { + 6 => {} + 7 => w[5] = 1, + 3 | 5 | 10 => (w[5], w[7]) = (1, 1), + _ => w[5] = 1, + } + let mut desc = srv_desc(&w); + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device + .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) + }; +} + /// A view that reads zeros, for slots whose view the host cannot make. fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e7a3ec4..8762d33 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -106,6 +106,13 @@ pub(crate) fn take_frame() -> Vec { std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner())) } +/// 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 { + DROPPED.swap(0, Ordering::Relaxed) +} +static DROPPED: AtomicU64 = AtomicU64::new(0); + /// Marks the last traced draw as not run on the host. #[cfg(feature = "diagnostics")] fn dropped() { @@ -403,6 +410,7 @@ impl State { .filter_map(|&h| crate::descriptor::heap(h as This).host()) .map(|h| Some(h.heap.clone())) .collect(); + heaps.iter().flatten().for_each(|h| list.keep(h)); // SAFETY: an open list and shader-visible heaps. unsafe { l.SetDescriptorHeaps(&heaps) }; self.host_heaps = self.heaps; @@ -420,11 +428,16 @@ impl State { } self.host_roots[usize::from(compute)] = root; } - if self.host_pipeline != self.pipeline { + // By host object: a title pipeline released and another made at its + // address is another host pipeline (the list keeps the old one). + if self.host_pipeline != p.pso.as_raw() as usize { // SAFETY: an open list and a live pipeline. unsafe { l.SetPipelineState(&p.pso) }; - self.host_pipeline = self.pipeline; + self.host_pipeline = p.pso.as_raw() as usize; list.used_pipeline(&p.name); + // The title may release the pipeline before it submits the list. + list.keep(&p.pso); + list.keep(&p.root); } for stage in &p.stages { let t = stage.translated(); @@ -480,6 +493,7 @@ impl State { pipeline = format_args!("{:#x}", self.pipeline), "a dispatch without a host pipeline dropped" ); + DROPPED.fetch_add(1, Ordering::Relaxed); return; }; if !p.compute { @@ -548,12 +562,11 @@ impl State { } Err(_) => false, }; - #[cfg(feature = "diagnostics")] if !ran { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] dropped(); } - #[cfg(not(feature = "diagnostics"))] - let _ = ran; } fn roots_ref(&self, compute: bool) -> &Vec { @@ -781,8 +794,9 @@ impl State { }; DRAWN.fetch_add(1, Ordering::Relaxed); } - #[cfg(feature = "diagnostics")] if !ran { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] dropped(); } } @@ -867,13 +881,139 @@ impl State { }; DRAWN.fetch_add(1, Ordering::Relaxed); } - #[cfg(feature = "diagnostics")] if !ran { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] dropped(); } } } +impl State { + /// Indirect execution of a one-argument signature of `kind` (PC + /// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with + /// records `stride` bytes apart at title address `arguments`, and the + /// record count at `count` if the title gives one: the GPU reads them + /// from the buffer's host copy, where earlier dispatches may have + /// written them. False if it cannot run on the host. + pub(crate) fn execute_indirect( + &mut self, + list: &HostList, + (kind, stride, max): (u32, u32, u32), + arguments: u64, + count: Option, + ) -> bool { + const DRAW: u32 = 0; + const INDEXED: u32 = 1; + const DISPATCH: u32 = 2; + const MESH: u32 = 10; + let len = u64::from(stride) * u64::from(max.max(1)); + let Some(args) = crate::shadow::find(arguments, len) else { + return false; + }; + let counter = match count { + Some(at) => match crate::shadow::find(at, 4) { + Some(s) => Some((s, at)), + None => return false, + }, + None => None, + }; + let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH) + .then(|| host_signature(kind, stride)) + .flatten() + else { + return false; + }; + args.refresh(list, arguments, len); + if let Some((s, at)) = &counter { + s.refresh(list, *at, 4); + } + // Bounded first: the clamp binds a compute pipeline of its own. + if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) { + return false; + } + self.host_pipeline = 0; + self.host_roots[1] = 0; + let ran = match kind { + DRAW | INDEXED => self.topology != RECTANGLES && self.prepare(list, kind == INDEXED), + MESH => self.prepare_for(list, false, true), + DISPATCH => match crate::pipeline::host_pipeline(self.pipeline as This) { + Some(p) if p.compute => { + self.bind(list, p, true); + true + } + _ => false, + }, + _ => false, + }; + if !ran { + crate::indirect::done(list, &args.buffer); + return false; + } + #[cfg(feature = "diagnostics")] + list.note_op(|| { + self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) + }); + // SAFETY: an open list with everything set; the buffers are host + // copies the list keeps alive (refresh), the signature is cached. + unsafe { + list.list.ExecuteIndirect( + &signature, + max, + &args.buffer, + args.offset(arguments), + counter.as_ref().map(|(s, _)| &s.buffer), + counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), + ) + }; + crate::indirect::done(list, &args.buffer); + if kind == DISPATCH { + DISPATCHED.fetch_add(1, Ordering::Relaxed); + } else { + DRAWN.fetch_add(1, Ordering::Relaxed); + } + true + } +} + +/// The host command signature for one argument of `kind` with records +/// `stride` bytes apart (no root arguments, so no root signature), made +/// once. +fn host_signature(kind: u32, stride: u32) -> Option { + static MADE: std::sync::Mutex> = + std::sync::Mutex::new(Vec::new()); + let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, s)) = made.iter().find(|(k, _)| *k == (kind, stride)) { + return Some(s.clone()); + } + let argument = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: stride, + NumArgumentDescs: 1, + pArgumentDescs: &argument, + NodeMask: 0, + }; + let mut signature: Option = None; + // SAFETY: a description of one argument; no root arguments. + let result = unsafe { + crate::host::host()?.device.CreateCommandSignature( + &desc, + None::<&ID3D12RootSignature>, + &mut signature, + ) + }; + if let Err(e) = result { + once!(error = %e, kind, stride, "host command signature refused"); + return None; + } + let signature = signature?; + made.push(((kind, stride), signature.clone())); + Some(signature) +} + /// Gets what a shader reads or writes through a view ready: buffer data /// copied, textures moved to the state they need. fn readable(list: &HostList, u: &UsedResource, view: &View) { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 476ce4d..51c7b47 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -67,6 +67,12 @@ unsafe impl Sync for Host {} static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] = [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; +/// After submissions: shader-written ranges compared and copied back into +/// title memory (microseconds, bytes that differed), since the last +/// frame-rate line. +static COPY_BACK: [std::sync::atomic::AtomicU64; 2] = + [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; + /// Of the preparing: title memory copies (microseconds, bytes) and texture /// refreshes (microseconds, bytes hashed), since the last frame-rate line. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [ @@ -134,9 +140,26 @@ fn create() -> windows::core::Result { if debug { let mut layer: Option = None; match D3D12GetDebugInterface(&mut layer) { - Ok(()) => layer.into_iter().for_each(|l| l.EnableDebugLayer()), + Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()), Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"), } + // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range + // descriptor heap indices and the like become messages naming + // the command instead of page faults. Without state tracking + // (directly indexed textures are not transitioned). + if std::env::var_os("VICTORY_D3D12_GBV").is_some() + && let Some(l) = &layer + { + if let Ok(d1) = l.cast::() { + d1.SetEnableGPUBasedValidation(true); + } + if let Ok(d2) = l.cast::() { + d2.SetGPUBasedValidationFlags( + D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING, + ); + } + tracing::info!("GPU-based validation on"); + } } // Diagnostics: device-removed data (the command that faulted, the // faulting address), read when the device is removed. @@ -213,21 +236,35 @@ pub(crate) struct HostList { /// Upload memory for data the list's draws make (expanded vertices), /// reused after a reset. scratch: Mutex, - /// Host texture states the list assumes, by title resource: at its - /// start and at its end. Lists are recorded on many threads and run in - /// submission order, so the transitions from a texture's real state are - /// made at submission, in `prelude`. - states: Mutex>, + /// Host texture states the list assumes, by host copy: at its start and + /// at its end. Lists are recorded on many threads and run in submission + /// order, so the transitions from a texture's real state are made at + /// submission, in `prelude`. Holding the copies keeps every texture the + /// list names alive until it is reset, even if the title releases the + /// resource first. + states: Mutex, /// The list that runs those transitions just before this one. prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), /// The pipelines the list binds, for reports of slow submissions. pipelines: Mutex>, + /// The work its indirect executions may still do (`indirect`): a + /// shader-writable word, zeroed when the list is submitted. + budget: OnceLock>, /// The texts of the markers `note_op` set, in order (for device-removed - /// data without marker texts). + /// data without marker texts), with the host GPU range a copy reads. #[cfg(feature = "diagnostics")] - notes: Mutex>, + notes: Mutex>, } +/// A marker's text and the host range its command reads (diagnostics). +#[cfg(feature = "diagnostics")] +type Note = (String, Option<(u64, u64)>); + +type States = std::collections::HashMap< + usize, + (u32, u32, std::sync::Arc), +>; + /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics /// builds). pub(crate) fn dred_on() -> bool { @@ -289,6 +326,10 @@ struct Deferred { /// Destination, source, bytes. copies: Vec, uploads: Vec, + /// Host objects the list's commands name (pipelines, root signatures, + /// descriptor heaps): the title may release its objects before it + /// submits the list. + kept: Vec, /// Buffer ranges refreshed since the last title copy (host copy, /// address, bytes): refreshing them again would find the same bytes. refreshed: std::collections::HashSet<(usize, usize, usize)>, @@ -297,6 +338,8 @@ struct Deferred { /// Bottom-of-pipe writes, done once the list has run: address, what, /// bytes. writes: Vec<(usize, crate::queue::Written, usize)>, + /// Whether a step zeroes the indirect-work budget. + budget_zeroed: bool, } impl Host { @@ -366,6 +409,7 @@ impl Host { states: Mutex::default(), prelude: (prelude_allocator, prelude), pipelines: Mutex::default(), + budget: OnceLock::new(), #[cfg(feature = "diagnostics")] notes: Mutex::default(), }) @@ -424,16 +468,32 @@ impl Host { last_notes(runs) )); } + // What shaders wrote goes back before the bottom-of-pipe writes, + // which tell the title the GPU is done; each range once per + // submission, however many dispatches declared it (the world's + // passes declare the same big ranges dozens of times). + let copying = std::time::Instant::now(); + // One list's lock at a time: a submission may name a list twice. + let mut back: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); for list in runs { - let deferred = list.deferred(); - // Before the bottom-of-pipe writes, which tell the title the - // GPU is done. - for step in &deferred.copies { - if let Step::GpuWrite(shadow, address, len) = step { - shadow.copy_back(*address, *len); + for step in &list.deferred().copies { + if let Step::GpuWrite(shadow, address, len) = step + && !back + .iter() + .any(|(s, a, l)| std::sync::Arc::ptr_eq(s, shadow) && (*a, *l) == (*address, *len)) + { + back.push((shadow.clone(), *address, *len)); } } - for &(at, what, bytes) in &deferred.writes { + } + for (shadow, address, len) in &back { + let (address, len) = (*address, *len); + let written = shadow.copy_back(address, len); + COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + } + COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed); + for list in runs { + for &(at, what, bytes) in &list.deferred().writes { what.write(at as *mut u8, bytes); } } @@ -450,6 +510,7 @@ impl Host { return String::new(); }; let mut text = String::new(); + let mut fault_va = None; // SAFETY: the outputs are the runtime's, valid while the device // lives; nodes are walked as linked, histories have their counts. unsafe { @@ -457,6 +518,7 @@ impl Host { && fault.PageFaultVA != 0 { let va = fault.PageFaultVA; + fault_va = Some(va); text.push_str(&format!("; page fault at {va:#x}")); for (what, head) in [ ("inside", fault.pHeadExistingAllocationNode), @@ -480,12 +542,28 @@ impl Host { } } text.push_str(&crate::shadow::near(va)); + text.push_str(&crate::descriptor::host::near_heaps(va)); } // The plain output: the extended one (with marker texts) came // back without stopped lists on this host. - let Ok(crumbs) = dred.GetAutoBreadcrumbsOutput() else { - return text; + let crumbs = match dred.GetAutoBreadcrumbsOutput() { + Ok(crumbs) => crumbs, + Err(e) => { + text.push_str(&format!("; no breadcrumbs ({e})")); + return text; + } }; + // Every list's progress (done/count), in the runtime's order. + let mut progress = Vec::new(); + let mut node = crumbs.pHeadAutoBreadcrumbNode; + while let Some(p) = node.as_ref() { + let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0); + let ours = p.pCommandList.as_ref().map(|l| l.as_raw()); + let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours); + progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount)); + node = p.pNext; + } + text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}")); let mut plain = crumbs.pHeadAutoBreadcrumbNode; while let Some(p) = plain.as_ref() { let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0); @@ -507,11 +585,16 @@ impl Host { .enumerate() .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER) .zip(notes.iter()) - .map(|((at, _), note)| (at as u32, note.clone())) + .map(|((at, _), (note, range))| { + let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r)); + (at as u32, format!("{note}{}", place.unwrap_or_default())) + }) .collect() }); #[cfg(not(feature = "diagnostics"))] let markers: Vec<(u32, String)> = Vec::new(); + #[cfg(not(feature = "diagnostics"))] + let _ = fault_va; if done > 0 { text.push_str(&in_flight(history, &markers, done as usize)); } else if let Some(r) = run { @@ -636,11 +719,12 @@ impl HostList { wanted: u32, ) -> Option<(&'static ID3D12Resource, u32)> { let texture = crate::resource::host_resource(resource)?; + let copy = crate::resource::host_copy(resource)?; let wanted = legal_state(texture, wanted); let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); - match states.entry(resource as usize) { + match states.entry(std::sync::Arc::as_ptr(©) as usize) { std::collections::hash_map::Entry::Vacant(v) => { - v.insert((wanted, wanted)); + v.insert((wanted, wanted, copy)); None } std::collections::hash_map::Entry::Occupied(mut o) => { @@ -656,16 +740,14 @@ impl HostList { fn prelude(&self) -> Option { let states = self.states.lock().unwrap_or_else(|e| e.into_inner()); let barriers: Vec = states - .iter() - .filter_map(|(&resource, &(first, last))| { - let resource = resource as crate::object::This; - let texture = crate::resource::host_resource(resource)?; - let real = crate::resource::swap_host_state(resource, last); - (real != first).then(|| { + .values() + .filter_map(|(first, last, copy)| { + let real = copy.state.swap(*last, Ordering::Relaxed); + (real != *first).then(|| { transition( - texture, + ©.texture, D3D12_RESOURCE_STATES(real as i32), - D3D12_RESOURCE_STATES(first as i32), + D3D12_RESOURCE_STATES(*first as i32), ) }) }) @@ -695,6 +777,18 @@ impl HostList { /// texts in order and names the commands a fault stopped among. #[cfg(feature = "diagnostics")] pub(crate) fn note_op(&self, what: impl FnOnce() -> String) { + self.note(what, None); + } + + /// As [`HostList::note_op`], for a copy that reads the host GPU range + /// `(address, bytes)`: the report places the faulting address in it. + #[cfg(feature = "diagnostics")] + pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) { + self.note(what, Some(range)); + } + + #[cfg(feature = "diagnostics")] + fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) { if dred_on() { let what = what(); let text: Vec = what.encode_utf16().chain([0]).collect(); @@ -703,7 +797,10 @@ impl HostList { unsafe { self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32) }; - self.notes.lock().unwrap_or_else(|e| e.into_inner()).push(what); + self.notes + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((what, range)); } } @@ -778,6 +875,7 @@ impl HostList { /// shortcut: one buffer per copy; pool them once uploads are frequent. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { let (buffer, data) = host.upload_buffer(size)?; + name(&buffer, || format!("list upload {size:#x}")); self.deferred().uploads.push(buffer.clone()); Some((buffer, data)) } @@ -813,6 +911,36 @@ impl HostList { Some((gpu + at, (data + at as usize) as *mut u8)) } + /// The host address of the list's indirect-work budget, zeroed at each + /// submission of the list from the first use after a reset on. + pub(crate) fn budget(&self) -> Option { + let (buffer, data) = self + .budget + .get_or_init(|| { + let (b, d) = host()?.shared_buffer(256)?; + Some((b, d as usize)) + }) + .as_ref()?; + let mut deferred = self.deferred(); + if !deferred.budget_zeroed { + deferred.budget_zeroed = true; + let at = *data; + // SAFETY: the list's own mapped word, written before it runs. + deferred + .copies + .push(Step::Host(Box::new(move || unsafe { (at as *mut u32).write_volatile(0) }))); + } + // SAFETY: a live buffer. + Some(unsafe { buffer.GetGPUVirtualAddress() }) + } + + /// Keeps `object` alive until the list is reset. + pub(crate) fn keep(&self, object: &impl Interface) { + if let Ok(object) = object.cast::() { + self.deferred().kept.push(object); + } + } + /// Whether this is the first time since the reset that the list asks /// about `key` (a texture to bring up to date). pub(crate) fn first_use(&self, key: usize) -> bool { @@ -976,6 +1104,12 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b }); } +/// Reads title memory at `src` into `dst`; false if a page of it is not +/// readable. +pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool { + read(src, dst.as_mut_ptr(), dst.len()) +} + /// Copies `len` bytes from `src` to `dst` unless a source page is not /// readable. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool { @@ -1141,12 +1275,18 @@ impl Meter { let scale = if i % 2 == 0 { 1e3 } else { 1e6 }; PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames }); + let [back_ms, back_mb] = [0, 1].map(|i| { + COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames + }); + let dropped = crate::draw::take_dropped() as f64 / frames; + let indirect = crate::list::take_indirect() as f64 / frames; if self.logged.elapsed() >= std::time::Duration::from_secs(5) { self.logged = std::time::Instant::now(); tracing::info!( "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \ {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \ - GPU), {draws:.0} draws/frame" + GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \ + dropped {dropped:.0} without a host pipeline and {indirect:.0} indirect" ); #[cfg(feature = "diagnostics")] crate::copystat::log(frames); @@ -1429,7 +1569,7 @@ fn last_notes(runs: &[&HostList]) -> String { let mut text = String::new(); for (i, r) in runs.iter().enumerate() { let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); - for n in notes.iter().rev().take(6).rev() { + for (n, _) in notes.iter().rev().take(6).rev() { text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len())); } } @@ -1442,6 +1582,20 @@ fn last_notes(runs: &[&HostList]) -> String { } } +/// Where the faulting address `va` lies against a range `(start, bytes)` a +/// command reads (diagnostics). +#[cfg(feature = "diagnostics")] +fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String { + let end = start + bytes; + if va < start { + format!(" (fault {:#x} below its source)", start - va) + } else if va < end { + format!(" (fault at source +{:#x})", va - start) + } else { + format!(" (fault {:#x} past its source's end)", va - end) + } +} + /// The commands that may have been running where a list stopped at /// command `done`: those between the barriers around it (work between /// barriers overlaps on the GPU), by kind, and what the markers just diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs new file mode 100644 index 0000000..097011b --- /dev/null +++ b/crates/victory-gpu/src/indirect.rs @@ -0,0 +1,209 @@ +//! Indirect execution's arguments, bounded before the GPU reads them. The +//! title's own compute passes write most of them; a pass we drop or +//! translate wrongly leaves whatever the memory held, and a draw of four +//! billion vertices or a dispatch past the host's limits runs until the +//! host resets the display driver. So every record is clamped on the GPU, +//! just before its execution, by a compute shader of ours (HLSL compiled by +//! the system's compiler; a 5.1 shader with its root signature inside). +//! +//! Each list also has a budget (2^28 vertex instances or threads, mesh +//! groups counted as 128): records past it run empty, so a list of +//! thousands of garbage records cannot run for seconds either. +//! +//! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535 +//! groups per dimension, one-dimensional mesh dispatches, the budget) cut +//! legitimate work beyond them; raise them if the title needs more. + +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::s; + +use crate::host::{HostList, host, transition}; + +const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)" +cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; }; +RWByteAddressBuffer args : register(u0); +// The list's work so far (vertex instances, threads): past the budget, +// records run empty. +RWByteAddressBuffer budget : register(u1); +static const uint BUDGET = 1u << 28; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= records) return; + uint at = id.x * stride; + uint cost; + if (kind <= 1) { + // Draws: vertex or index count, then instances. + uint count = min(args.Load(at), 1u << 24); + uint instances = min(args.Load(at + 4), (1u << 26) / max(count, 1u)); + cost = count * instances; + args.Store2(at, uint2(count, instances)); + } else if (kind == 2) { + uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535)); + cost = min(g.x * g.y * g.z, 1u << 20) * 64; + args.Store3(at, g); + } else { + // Mesh dispatches: the console's are one-dimensional. + uint3 g = args.Load3(at); + g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); + cost = g.x * g.y * g.z * 128; + args.Store3(at, g); + } + uint before; + budget.InterlockedAdd(0, cost, before); + if (before >= BUDGET || before + cost > BUDGET) { + // Draws keep their layout with no vertices; groups become zero. + args.Store(at, 0); + } +} +"#; + +struct Clamp { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Clamp {} +// SAFETY: as above. +unsafe impl Sync for Clamp {} + +fn clamp() -> Option<&'static Clamp> { + static CLAMP: std::sync::OnceLock> = std::sync::OnceLock::new(); + CLAMP + .get_or_init(|| match make() { + Ok(c) => Some(c), + Err(e) => { + tracing::warn!(error = %e, "no argument clamp: indirect execution dropped"); + None + } + }) + .as_ref() +} + +fn make() -> windows::core::Result { + let device = &host().ok_or_else(windows::core::Error::empty)?.device; + let mut code: Option = None; + let mut errors: Option = None; + // SAFETY: the source and names live through the call; out pointers ours. + let compiled = unsafe { + D3DCompile( + SOURCE.as_ptr().cast(), + SOURCE.len(), + s!("clamp"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + Some(&mut errors), + ) + }; + if let Err(e) = compiled { + if let Some(errors) = errors { + // SAFETY: the blob's own bytes. + let text = unsafe { + std::slice::from_raw_parts(errors.GetBufferPointer().cast::(), errors.GetBufferSize()) + }; + tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text)); + } + return Err(e); + } + let code = code.ok_or_else(windows::core::Error::empty)?; + // SAFETY: the blob's own bytes; the root signature is inside the shader. + unsafe { + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; + let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + Ok(Clamp { root, pso }) + } +} + +/// Records, in `list`, the clamp of `records` records of `kind` (PC +/// argument numbering) `stride` bytes apart at host address `gpu` in +/// `buffer`, and leaves the buffer ready to be read as arguments. Replaces +/// the list's compute root signature and pipeline (callers bind theirs +/// after). False if the clamp is not available. +pub(crate) fn bound( + list: &HostList, + buffer: &ID3D12Resource, + gpu: u64, + (kind, stride, records): (u32, u32, u32), +) -> bool { + let (Some(c), Some(budget)) = (clamp(), list.budget()) else { + return false; + }; + if !gpu.is_multiple_of(4) || !stride.is_multiple_of(4) { + return false; + } + let l = &list.list; + let constants = [kind, stride, records, 0]; + // SAFETY: an open list; our root signature, pipeline and a live buffer + // the caller's list holds. + unsafe { + // Earlier shader writes (the title's argument passes) first. + l.ResourceBarrier(&[uav_barrier()]); + l.SetComputeRootSignature(&c.root); + l.SetPipelineState(&c.pso); + l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + l.SetComputeRootUnorderedAccessView(1, gpu); + l.SetComputeRootUnorderedAccessView(2, budget); + l.Dispatch(records.div_ceil(64), 1, 1); + l.ResourceBarrier(&[ + uav_barrier(), + transition( + buffer, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + ), + ]); + } + true +} + +/// After the execution: the buffer back to unordered access, where the +/// title's passes keep using it. +pub(crate) fn done(list: &HostList, buffer: &ID3D12Resource) { + // SAFETY: an open list and a live buffer. + unsafe { + list.list.ResourceBarrier(&[transition( + buffer, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]) + }; +} + +fn uav_barrier() -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }), + }, + } +} + +#[cfg(test)] +mod tests { + /// The clamp compiles with the system's compiler and the host takes it. + #[test] + fn argument_clamp_builds() { + if super::host().is_none() { + return; // no host GPU here + } + assert!(super::clamp().is_some()); + } +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 7558568..f91782d 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -29,6 +29,8 @@ pub mod fence; pub mod frame; #[cfg(windows)] mod host; +#[cfg(windows)] +mod indirect; pub mod list; pub mod object; pub mod pipeline; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 6f11cc7..6fc2fb7 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -510,6 +510,8 @@ extern "system" fn copy_texture_region( }; let mut from = src; let _upload; // keeps the source alive while this call records it + #[cfg(feature = "diagnostics")] + let mut read = None; if src.kind == FOOTPRINT { let (Some(host), Some(bytes)) = (crate::host::host(), src.footprint.bytes()) else { return; @@ -523,6 +525,11 @@ extern "system" fn copy_texture_region( list.defer_copy(staging, data, bytes as usize); from.resource = buffer.as_raw().cast_const().cast(); from.footprint.offset = 0; + #[cfg(feature = "diagnostics")] + { + // SAFETY: a live buffer. + read = Some((unsafe { buffer.GetGPUVirtualAddress() }, bytes)); + } _upload = buffer; } else { let Some(texture) = crate::resource::host_resource(src.resource) else { @@ -537,21 +544,27 @@ extern "system" fn copy_texture_region( to_location.resource = to.as_raw().cast_const().cast(); let host_box = (!source_box.is_null()).then(|| source_box.cast::()); #[cfg(feature = "diagnostics")] - list.note_op(|| { - // SAFETY: a live texture; the box is the title's or null. - let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) }; - format!( - "copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}", - dst.resource, - d.Width, - d.Height, - d.Format.0, - dst.kind, - src.resource, - src.kind, - (src.kind == FOOTPRINT).then_some(src.footprint) - ) - }); + { + let text = || { + // SAFETY: a live texture; the box is the title's or null. + let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) }; + format!( + "copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}", + dst.resource, + d.Width, + d.Height, + d.Format.0, + dst.kind, + src.resource, + src.kind, + (src.kind == FOOTPRINT).then_some(src.footprint) + ) + }; + match read { + Some(range) => list.note_read(text, range), + None => list.note_op(text), + } + } const _: () = assert!(size_of::() == size_of::()); // SAFETY: an open list; both locations in the host's layout, naming @@ -1110,9 +1123,77 @@ fn count_draw() { /// Draws of the kinds the host does not run yet (indirect, mesh), and /// dispatches, counted per frame for the log. /// shortcut: dropped until their shaders translate (decision 0007). +#[cfg(not(windows))] extern "system" fn draw(_: This) { count_draw(); } + +/// `ExecuteIndirect(signature, max count, arguments, offset, count buffer, +/// offset)`. Grand Theft Auto VI's signatures (2026-11-23) hold one +/// argument each: draw (stride 16), indexed draw (20), dispatch (12), mesh +/// dispatch (12), and a console type 105 (stride 12, fields 0, 60000, 0, +/// over its 174 MB buffer) whose meaning is unknown. Those of PC types run +/// through the host's indirect execution (`State::execute_indirect`). +/// shortcut: type 105 and signatures that change root arguments are +/// dropped (logged once per signature); decode 105 when its draws are +/// missed. +extern "system" fn execute_indirect( + this: This, + signature: This, + max: u32, + arguments: This, + offset: u64, + count: This, + count_offset: u64, +) { + count_draw(); + let Some((stride, args)) = crate::signature::layout(signature) else { + return; + }; + let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset); + let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset); + let mut ran = false; + // shortcut: off unless `VICTORY_INDIRECT` is set (diagnostics builds): + // with it the world presented no frame for 30 s and the title's own + // GPU watchdog ended it (2026-11-24, cause not found); without it the + // world runs, with most geometry missing. + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = *ON.get_or_init(|| { + cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_INDIRECT").is_some() + }); + #[cfg(windows)] + if on + && let ([[kind, ..]], Some(address)) = (args, address) + && (count.is_null() || counter.is_some()) + { + with_state(this, |list, s| { + ran = s.execute_indirect(list, (*kind, stride, max), address, counter); + }); + } + if ran { + return; + } + INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + static SEEN: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.contains(&(signature as usize)) { + seen.push(signature as usize); + tracing::info!( + stride, + ?args, + max, + address = ?address.map(|a| format!("{a:#x}")), + counted = !count.is_null(), + "indirect execution dropped (first time for this signature)" + ); + } +} + +/// Indirect executions dropped since the last call. +pub(crate) fn take_indirect() -> u64 { + INDIRECT.swap(0, std::sync::atomic::Ordering::Relaxed) +} +static INDIRECT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); fn count_dispatch() { DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } @@ -1231,7 +1312,7 @@ const METHODS: [(usize, *const ()); 52] = [ (50, state::targets as *const ()), // 0x190 (51, clear_dsv as *const ()), // 0x198 (52, clear_rtv as *const ()), // 0x1a0 - (59, draw as *const ()), // 0x1d8 indirect + (59, execute_indirect as *const ()), // 0x1d8 indirect (60, copy_memory as *const ()), // 0x1e0 (68, ignored_state as *const ()), // 0x220 depth bounds (69, write32 as *const ()), // 0x228 diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index fd413f1..b409c4c 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -406,6 +406,7 @@ impl HostPipeline { } }; tracing::info!(?shaders, "host pipeline"); + crate::host::name(&pso, || format!("{shaders:?}")); return Some(HostPipeline { compute: true, mesh: false, @@ -430,6 +431,7 @@ impl HostPipeline { } }; tracing::info!(?shaders, "host mesh pipeline"); + crate::host::name(&pso, || format!("{shaders:?}")); return Some(HostPipeline { compute: false, mesh: true, @@ -478,6 +480,7 @@ impl HostPipeline { } }; tracing::info!(?shaders, "host pipeline"); + crate::host::name(&pso, || format!("{shaders:?}")); tracing::debug!( ?shaders, depth = ?g.depth, diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 828113e..46c5c71 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -748,11 +748,19 @@ struct Resource { /// Textures also live on the host GPU (decision 0007); buffers do not /// yet. #[cfg(windows)] - host: Option, - /// The state the host texture is in. The title's barriers name console - /// states (looser than the host's), so we transition from this one. - #[cfg(windows)] - host_state: std::sync::atomic::AtomicU32, + host: Option>, +} + +/// A title texture's host copy and the state it is in. The title's barriers +/// name console states (looser than the host's), so we transition from this +/// one. Lists that use the texture hold it until they are reset: the title +/// may release a resource whose commands it recorded but not yet submitted +/// (console memory outlives the object; a host texture must outlive the +/// lists that name it). +#[cfg(windows)] +pub(crate) struct HostTexture { + pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, + pub(crate) state: std::sync::atomic::AtomicU32, } /// Moves the host texture to `wanted` (a host texture state); the host @@ -760,21 +768,11 @@ struct Resource { #[cfg(windows)] pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u32)> { use windows::core::Interface; - let r = resource(this); - let host = r.host.as_ref()?; - let before = r - .host_state + let host = resource(this).host.as_ref()?; + let before = host + .state .swap(wanted, std::sync::atomic::Ordering::Relaxed); - (before != wanted).then(|| (host.as_raw(), before)) -} - -/// Sets the state the host texture is in after a submission; returns the -/// one it was in. -#[cfg(windows)] -pub(crate) fn swap_host_state(this: This, state: u32) -> u32 { - resource(this) - .host_state - .swap(state, std::sync::atomic::Ordering::Relaxed) + (before != wanted).then(|| (host.texture.as_raw(), before)) } /// The host GPU's copy of a title resource, if it has one. @@ -785,7 +783,16 @@ pub(crate) fn host_resource<'a>( if this.is_null() { return None; } - resource(this).host.as_ref() + resource(this).host.as_deref().map(|h| &h.texture) +} + +/// A title texture's host copy, shared, for a list to hold. +#[cfg(windows)] +pub(crate) fn host_copy(this: This) -> Option> { + if this.is_null() { + return None; + } + resource(this).host.clone() } /// A host texture like the title's: same description, in GPU memory, @@ -929,12 +936,13 @@ fn hand_out_resource( heap_flags, backing, #[cfg(windows)] - host_state: host - .as_ref() - .map_or(0, |t| crate::host::legal_state(t, crate::host::texture_state(state))) - .into(), - #[cfg(windows)] - host, + host: host.map(|texture| { + let state = crate::host::legal_state(&texture, crate::host::texture_state(state)); + std::sync::Arc::new(HostTexture { + texture, + state: state.into(), + }) + }), }); #[cfg(windows)] if desc.dimension == BUFFER { @@ -947,6 +955,24 @@ fn hand_out_resource( #[cfg(windows)] impl Drop for Resource { fn drop(&mut self) { + #[cfg(feature = "diagnostics")] + if self + .host + .as_ref() + .is_some_and(|h| std::sync::Arc::strong_count(h) > 1) + { + // Before lists held their textures, this freed a texture that + // lists not yet run still named (a GPU page fault). + static OUTLIVED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = OUTLIVED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::info!( + n, + desc = ?self.desc, + "a title texture was released while a list not yet reset names its host copy" + ); + } + } crate::texture::forget(std::ptr::from_ref::(self) as usize); crate::descriptor::forget(std::ptr::from_ref::(self) as usize); if self.desc.dimension == BUFFER { @@ -1705,6 +1731,8 @@ mod tests { let host_image = host_resource(image).unwrap(); let back = host.new_list().unwrap(); let (_, before) = host_transition(image, 0x800).unwrap(); + // The upload list holds the texture until it is reset. + assert!(std::sync::Arc::strong_count(&host_copy(image).unwrap()) > 2); use windows::core::Interface; let out_to = Location { resource: readback.as_raw().cast_const().cast(), diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index e2793e1..3c39a30 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -113,14 +113,30 @@ impl Shadow { /// back into title memory (unmapped pages left alone). Pages wholly /// written are current in this copy, so our own write is not taken for /// the title's. - pub(crate) fn copy_back(&self, address: usize, len: usize) { + /// Returns the bytes written. + pub(crate) fn copy_back(&self, address: usize, len: usize) -> usize { + let mut written = 0; let (start, end) = (self.start as usize, (self.start + self.len) as usize); let (from, to) = (address.max(start), (address + len).min(end)); if from < to { - // SAFETY: inside the mapping. - let at = unsafe { self.data.add(from - start) }; - crate::watch::writing(from, to - from); - crate::host::write_mapped(from as *mut u8, at, to - from); + // Only the pieces that differ: shaders rewrite part of what they + // may write, and writing title memory through the kernel (and + // opening guarded blocks) was the world's biggest cost (~1 s per + // frame for 450 MB). + const PIECE: usize = 64 << 10; + let mut title = vec![0u8; PIECE]; + let mut at = from; + while at < to { + let n = (PIECE - at % PIECE).min(to - at); + // SAFETY: inside the mapping. + let host = unsafe { std::slice::from_raw_parts(self.data.add(at - start), n) }; + if !crate::host::read_into(at as *const u8, &mut title[..n]) || title[..n] != *host { + crate::watch::writing(at, n); + crate::host::write_mapped(at as *mut u8, host.as_ptr(), n); + written += n; + } + at += n; + } let (first, last) = (from.div_ceil(PAGE), to / PAGE); if first < last && self.watched.load(Ordering::Relaxed) != NOT_WATCHED @@ -131,10 +147,10 @@ impl Shadow { copied[first - base..last - base].fill(now); } } + // Every submitted step that declared the range is done with it. let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(i) = pending.iter().position(|&r| r == (address, address + len)) { - pending.swap_remove(i); - } + pending.retain(|&r| r != (address, address + len)); + written } /// At submission: copies what changed of `[address, address + len)` @@ -155,20 +171,28 @@ impl Shadow { .filter(|&(a, e)| a < to && e > from) .collect(); if !busy.is_empty() { - // Rare: around ranges shaders are writing, everything is copied. + // Around ranges shaders are writing: the gaps, each as below + // (in the world most submissions have such ranges; copying the + // gaps whole cost ~1 s per frame). busy.sort_unstable(); let (mut at, mut bytes) = (from, 0); for (a, e) in busy { if a > at { - bytes += self.copy(at, a); + bytes += self.update_free(at, a); } at = at.max(e); } if at < to { - bytes += self.copy(at, to); + bytes += self.update_free(at, to); } return bytes; } + self.update_free(from, to) + } + + /// [`Shadow::update`] of `[from, to)` (inside the buffer) where no + /// shader writes. + 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) { self.watched.store(1, Ordering::Relaxed); @@ -206,14 +230,20 @@ impl Shadow { }; let at = &mut copied[page - base]; if *at == 0 || write > *at { - *at = now; + // A page only partly in the range is copied in part: it + // stays stale for the rest. + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to { + *at = now; + } run.get_or_insert(page); } else if let Some(first) = run.take() { - bytes += self.copy(first * PAGE, page * PAGE); + bytes += self.copy((first * PAGE).max(from), (page * PAGE).min(to)); } } + // Cut to the range: next to it shaders may be writing the copy. if let Some(first) = run { - bytes += self.copy(first * PAGE, (last + 1) * PAGE); + bytes += self.copy((first * PAGE).max(from), ((last + 1) * PAGE).min(to)); } bytes } diff --git a/crates/victory-gpu/src/signature.rs b/crates/victory-gpu/src/signature.rs index dd5b3d7..3c7b5d5 100644 --- a/crates/victory-gpu/src/signature.rs +++ b/crates/victory-gpu/src/signature.rs @@ -65,6 +65,17 @@ pub(crate) extern "system" fn create( object::hand_out(COMMAND_SIGNATURE, signature, iid, &SIGNATURE_IIDS, out) } +/// A signature's record stride and arguments (type, then up to three +/// fields each). +pub(crate) fn layout<'a>(this: This) -> Option<(u32, &'a [[u32; 4]])> { + if this.is_null() { + return None; + } + // SAFETY: the title passes one of our signatures. + let s = unsafe { &*this.cast::() }; + Some((s.stride, &s.arguments)) +} + extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { let found = object::is(iid, &SIGNATURE_IIDS).then_some(this); object::answer(COMMAND_SIGNATURE, iid, found, out) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 0a8de93..30193d5 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -34,6 +34,9 @@ macro_rules! once { /// texture's subresources, and what was last detiled. struct Staging { buffer: ID3D12Resource, + /// Its bytes. + #[cfg(feature = "diagnostics")] + size: u64, data: *mut u8, footprints: Vec, rows: Vec, @@ -113,7 +116,36 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) }; const COPY_DEST: u32 = 0x400; crate::list::ensure_state(list, resource, COPY_DEST); + // The staging buffer lives as long as `staging`, which the deferred + // refresh below holds until the list is reset. for (i, footprint) in staging.footprints.iter().enumerate() { + #[cfg(feature = "diagnostics")] + { + let f = footprint.Footprint; + // SAFETY: live resources. + let (gpu, d) = unsafe { (staging.buffer.GetGPUVirtualAddress(), texture.GetDesc()) }; + let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth); + list.note_read( + || { + format!( + "texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", + d.Width, + d.Height, + d.DepthOrArraySize, + d.Format.0, + d.MipLevels, + staging.footprints.len(), + staging.size, + footprint.Offset, + f.Width, + f.Height, + f.Depth, + f.RowPitch + ) + }, + (gpu + footprint.Offset, len), + ); + } let to = D3D12_TEXTURE_COPY_LOCATION { // SAFETY: a borrowed pointer the location never releases. pResource: unsafe { std::mem::transmute_copy(texture) }, @@ -287,9 +319,17 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { ); } let (buffer, data) = host.upload_buffer(total)?; + crate::host::name(&buffer, || { + format!( + "staging of {resource:?} {}x{}x{} f{}", + d.Width, d.Height, d.DepthOrArraySize, d.Format.0 + ) + }); tracing::debug!(?desc, total, "texture contents uploaded from title memory"); let s = Arc::new(Staging { buffer, + #[cfg(feature = "diagnostics")] + size: total, data, footprints, rows, From 38277675fac45d2c28a3c717fe7a8e343b532874 Mon Sep 17 00:00:00 2001 From: Nostyxx Date: Tue, 24 Nov 2026 06:16:01 +0700 Subject: [PATCH 007/445] GPU: make tables past a capped host view heap afresh The title's shader-visible view heap has 1,245,184 slots. NVIDIA caps shader-visible view heaps at 1,000,000, so HostHeap::new falls back to a heap of 1,000,000 whose title part ends at 934,464, with the dynamic slots after it. The title binds a per-frame table ring in its top slots (934,464 to 1,245,184, moving 4,096 slots a frame), so those tables' host offsets either aliased the dynamic slots or ran past the heap's end. On NVIDIA the GPU then hangs within the first-boot screens (DXGI_ERROR_DEVICE_HUNG), after black and glitched frames. A table that reaches past the host heap's title slots is now made afresh in dynamic slots, as tables holding constant buffers already are, and the shader is given the new offset. Hosts that take the whole heap (AMD) are unchanged. mirror() logs the highest title slot it meets past the host heap, once per new maximum. Tested on an RTX 3080 (driver 32.0.16.2114): the first-boot screens and menus run without glitches, and the title loads into the intro with no device loss (before: device removed about 45-60 s in, 3 of 3 runs). The slot warning went from 78 lines to none. cargo test --workspace passes. Refs #16, #11 Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 17 +++++++++++++++++ crates/victory-gpu/src/draw.rs | 21 +++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 27655d1..bad23fc 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -197,6 +197,12 @@ impl HostHeap { Some(self.count + first as u32) } + /// The title slots this heap has host slots for; fewer than the title's + /// when the host caps its size. + pub(crate) fn count(&self) -> u32 { + self.count + } + /// Gives back `n` dynamic slots from `first` (an index [`dynamic`] /// returned). /// @@ -256,6 +262,17 @@ impl HostHeap { /// data: a host copy of a buffer is made on first use. pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option { if index >= self.count { + // Diagnostic (NVIDIA heap cap): the highest title slot past the + // host heap seen so far. + static HIGHEST: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if HIGHEST.fetch_max(index, std::sync::atomic::Ordering::Relaxed) < index { + tracing::warn!( + index, + count = self.count, + for_draw, + "title slot past the host heap" + ); + } return None; } // SAFETY: the handle is a descriptor slot in title memory. diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e7a3ec4..f743c68 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -599,6 +599,27 @@ impl State { .filter(|u| u.kind == ResourceType::Cbv) .map(|u| u.slot) .collect(); + // Tables reaching past a host heap smaller than the title's (the + // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the + // title's slots there have no host slot of their own. + for u in used.iter().filter(tables) { + if fresh.contains(&u.slot) { + continue; + } + let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else { + continue; + }; + let end = table + u64::from(u.table_offset_dwords) * 4; + let Some(heap) = self.heap_of(table) else { + continue; + }; + let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else { + continue; + }; + if index >= host.count() { + fresh.push(u.slot); + } + } fresh.sort_unstable(); fresh.dedup(); for u in used.iter().filter(tables) { From e98d3ca96e77304c9e805ed765041ca63b8d9c3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9rez?= Date: Mon, 23 Nov 2026 23:33:46 +0100 Subject: [PATCH 008/445] PE: checked file offset in rva_to_file_offset A section whose PointerToRawData lies near 4 GiB made file_offset + delta overflow: a panic in debug builds, a wrong offset in release ones. The section now yields no offset. Co-Authored-By: Claude Opus 5.5 --- crates/victory-pe/src/image.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/victory-pe/src/image.rs b/crates/victory-pe/src/image.rs index 4acc6e3..8e7f542 100644 --- a/crates/victory-pe/src/image.rs +++ b/crates/victory-pe/src/image.rs @@ -215,7 +215,8 @@ impl ImageInfo { 0 => s.file_size, vs => vs.min(s.file_size), }; - (delta < backed).then(|| s.file_offset + delta) + // Header values are untrusted: an offset near 4 GiB overflows. + (delta < backed).then(|| s.file_offset.checked_add(delta))? }) } @@ -433,6 +434,17 @@ mod tests { assert!(off < data.len()); } + #[test] + fn rva_to_file_offset_rejects_offsets_past_4_gib() { + let mut info = ImageInfo::parse(&own_image()).unwrap(); + let rva = info.sections[0].rva + 0x20; + assert!(info.rva_to_file_offset(rva).is_some()); + // Used to overflow (a panic in debug builds, a wrong offset in + // release ones). + info.sections[0].file_offset = u32::MAX - 0x10; + assert_eq!(info.rva_to_file_offset(rva), None); + } + #[test] fn rejects_garbage_without_panicking() { assert!(ImageInfo::parse(b"").is_err()); From d85097af2ea1151cc7ba2277c26e5e3d0927d5bf Mon Sep 17 00:00:00 2001 From: ifBars Date: Mon, 23 Nov 2026 15:20:22 -0800 Subject: [PATCH 009/445] Keep an empty import descriptor for the Windows 10 loader --- crates/victory-loader/src/prepare.rs | 48 ++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 6 deletions(-) diff --git a/crates/victory-loader/src/prepare.rs b/crates/victory-loader/src/prepare.rs index 9895db1..1b601b4 100644 --- a/crates/victory-loader/src/prepare.rs +++ b/crates/victory-loader/src/prepare.rs @@ -35,7 +35,7 @@ impl PreparedImage { /// /// * `IMAGE_FILE_DLL` set, entry point cleared: the OS maps it like a DLL /// and calls nothing; -/// * import and bound-import directories cleared: we bind imports +/// * import directory made empty and bound-import directory cleared: we bind imports /// ourselves, using `info.imports` from the original; /// * TLS callback pointer cleared: the OS still allocates static TLS for /// the image, but callbacks only run when we call them (after binding); @@ -64,11 +64,20 @@ pub fn prepare(original: &[u8]) -> Result { dll_characteristics, )?; - for index in [dir::IMPORT, dir::BOUND_IMPORT] { - if let Some(at) = layout::data_directory_offset(&bytes, index) { - write_u32(&mut bytes, at, 0)?; - write_u32(&mut bytes, at + 4, 0)?; - } + // Windows 10 can read the import directory when an IAT is still + // advertised. Point it at the empty descriptor that ends the table. + if let Some(at) = layout::data_directory_offset(&bytes, dir::IMPORT) { + let terminator = import_terminator(&bytes, &info, at); + write_u32(&mut bytes, at, terminator.unwrap_or(0))?; + write_u32( + &mut bytes, + at + 4, + terminator.map_or(0, |_| IMPORT_DESCRIPTOR_SIZE), + )?; + } + if let Some(at) = layout::data_directory_offset(&bytes, dir::BOUND_IMPORT) { + write_u32(&mut bytes, at, 0)?; + write_u32(&mut bytes, at + 4, 0)?; } if let Some(tls) = &info.tls @@ -101,6 +110,21 @@ pub fn prepare(original: &[u8]) -> Result { }) } +const IMPORT_DESCRIPTOR_SIZE: u32 = 20; + +/// The RVA of the all-zero descriptor at the end of the import directory. +fn import_terminator(bytes: &[u8], info: &ImageInfo, directory: usize) -> Option { + let rva = layout::read_u32(bytes, directory)?; + if rva == 0 { + return None; + } + let size = layout::read_u32(bytes, directory + 4)?; + let end_rva = rva.checked_add(size.checked_sub(IMPORT_DESCRIPTOR_SIZE)?)?; + let offset = info.rva_to_file_offset(end_rva)? as usize; + let descriptor = bytes.get(offset..offset + IMPORT_DESCRIPTOR_SIZE as usize)?; + descriptor.iter().all(|&byte| byte == 0).then_some(end_rva) +} + /// Every `IMAGE_REL_BASED_DIR64` base relocation: (file offset of its entry, /// RVA it patches). Empty if the image has no readable relocation table. fn dir64_relocations(bytes: &[u8], info: &ImageInfo) -> Vec<(usize, u32)> { @@ -173,6 +197,18 @@ mod tests { assert!(patched.is_dll()); assert_eq!(patched.entry_rva, 0); assert!(patched.imports.is_empty()); + let import = layout::data_directory_offset(&original, dir::IMPORT).unwrap(); + let rva = layout::read_u32(&original, import).unwrap(); + let size = layout::read_u32(&original, import + 4).unwrap(); + assert_ne!(rva, 0); + assert_eq!( + layout::read_u32(&prepared.bytes, import), + Some(rva + size - IMPORT_DESCRIPTOR_SIZE) + ); + assert_eq!( + layout::read_u32(&prepared.bytes, import + 4), + Some(IMPORT_DESCRIPTOR_SIZE) + ); assert_eq!(patched.dll_characteristics & dll_flags::FORCE_INTEGRITY, 0); if let Some(tls) = &patched.tls { assert_eq!(tls.callbacks_va, 0); From 29b558c26351dacedbbc8d7932e640fece7090f7 Mon Sep 17 00:00:00 2001 From: Jeremy Goldberg Date: Mon, 23 Nov 2026 18:27:12 -0500 Subject: [PATCH 010/445] test(gpu): use the SDK root parameter in the serializer fixture --- crates/victory-gpu/src/root.rs | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/crates/victory-gpu/src/root.rs b/crates/victory-gpu/src/root.rs index 0c6b698..10368e9 100644 --- a/crates/victory-gpu/src/root.rs +++ b/crates/victory-gpu/src/root.rs @@ -221,20 +221,20 @@ mod tests { #[cfg(windows)] #[test] fn host_serialized_blobs_create_root_signatures() { - #[repr(C)] - struct Constants { - kind: u32, - register: u32, - space: u32, - count: u32, - visibility: u32, - } - let parameter = Constants { - kind: 1, - register: 0, - space: 0, - count: 1, - visibility: 0, + use windows::Win32::Graphics::Direct3D12::{ + D3D12_ROOT_CONSTANTS, D3D12_ROOT_PARAMETER, D3D12_ROOT_PARAMETER_0, + D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, D3D12_SHADER_VISIBILITY_ALL, + }; + let parameter = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: 0, + Num32BitValues: 1, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }; let desc = Desc { parameter_count: 1, From 0c91c03116e4491339d554bbfad783efa3b88e6b Mon Sep 17 00:00:00 2001 From: raffclar Date: Mon, 23 Nov 2026 23:30:15 +0000 Subject: [PATCH 011/445] Loader: test the AMD-only instruction emulation on any CPU The test for the emulation runs the real instructions. AMD CPUs, and most CI runners, execute them natively, so the emulation was tested only on Intel CPUs. The new tests give the emulation instruction bytes and saved registers directly, so they work on any CPU. They cover clzero, monitorx/mwaitx, the immediate and register forms of extrq/insertq, xmm8 to xmm15, length 0, and the instructions and exceptions it must not emulate. The old test stays: on an Intel CPU it is the only test of the full path through the vectored handler. --- crates/victory-loader/src/crash.rs | 154 ++++++++++++++++++++++++++++- 1 file changed, 153 insertions(+), 1 deletion(-) diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index eb6bb5e..e68ab1d 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -433,7 +433,7 @@ fn module_of(address: usize) -> Option { mod tests { use super::*; use windows_sys::Win32::System::Diagnostics::Debug::{ - RtlCaptureContext, RtlCaptureStackBackTrace, + EXCEPTION_RECORD, RtlCaptureContext, RtlCaptureStackBackTrace, }; #[test] @@ -457,6 +457,9 @@ mod tests { assert_eq!(ours, system); } + /// On an Intel CPU, the real instructions go through the vectored + /// handler. On an AMD CPU they run natively, and the tests below test + /// the emulation. #[test] fn clzero_zeroes_its_line_on_any_cpu() { report_crashes(); @@ -488,4 +491,153 @@ mod tests { in("rax") at, in("ecx") 0, in("edx") 0) }; } + + fn reg(low: u64, high: u64) -> M128A { + M128A { + Low: low, + High: high as i64, + } + } + + /// Gives `code` to the emulation as if it faulted with `exception` at + /// its first byte, with `rax` and `xmm` as the saved registers. The + /// emulation does not execute `code`, so this works on any CPU. Returns + /// the number of bytes that the emulation skipped, or `None` if it did + /// not emulate the instruction. `xmm` gets the saved registers after. + fn emulate_as(exception: i32, code: &[u8], rax: u64, xmm: &mut [M128A; 16]) -> Option { + // `int3` after the instruction, so that a decoder that reads too + // far sees no valid bytes. + let mut bytes = [0xcc_u8; 16]; + bytes[..code.len()].copy_from_slice(code); + let start = bytes.as_ptr() as u64; + // SAFETY: a zeroed record and context are valid; the emulation + // reads only `bytes` and writes only `context` (and memory at + // `rax` for clzero, which the caller owns). + unsafe { + let mut record: EXCEPTION_RECORD = std::mem::zeroed(); + record.ExceptionCode = exception; + let mut context: CONTEXT = std::mem::zeroed(); + context.Rip = start; + context.Rax = rax; + context.Anonymous.FltSave.XmmRegisters = *xmm; + let mut pointers = EXCEPTION_POINTERS { + ExceptionRecord: &mut record, + ContextRecord: &mut context, + }; + let emulated = emulate_amd_only(&mut pointers); + *xmm = context.Anonymous.FltSave.XmmRegisters; + emulated.then(|| context.Rip - start) + } + } + + fn emulate(code: &[u8], rax: u64, xmm: &mut [M128A; 16]) -> Option { + emulate_as(EXCEPTION_ILLEGAL_INSTRUCTION, code, rax, xmm) + } + + fn low(xmm: &[M128A; 16], i: usize) -> u64 { + xmm[i].Low + } + + #[test] + fn emulated_clzero_zeroes_its_line() { + #[repr(align(64))] + struct Line([u8; 128]); + let mut line = Line([0xff; 128]); + let at = line.0.as_mut_ptr().wrapping_add(5) as u64; // inside the first line + let mut xmm = [reg(0, 0); 16]; + assert_eq!(emulate(&[0x0f, 0x01, 0xfc], at, &mut xmm), Some(3)); + assert!(line.0[..64].iter().all(|&b| b == 0)); + assert!(line.0[64..].iter().all(|&b| b == 0xff)); + } + + #[test] + fn emulated_monitorx_and_mwaitx_are_skipped() { + let mut xmm = [reg(1, 2); 16]; + assert_eq!(emulate(&[0x0f, 0x01, 0xfa], 0, &mut xmm), Some(3)); + assert_eq!(emulate(&[0x0f, 0x01, 0xfb], 0, &mut xmm), Some(3)); + assert!(xmm.iter().all(|r| r.Low == 1 && r.High == 2)); + } + + #[test] + fn emulated_insertq_and_extrq_with_immediates() { + let mut xmm = [reg(0, 0); 16]; + xmm[0] = reg(0x1111_2222_3333_4444, 0x5555); + xmm[1] = reg(0xabcd, 0x6666); + // insertq xmm0, xmm1, length 16, index 16 + let insertq = [0xf2, 0x0f, 0x78, 0xc1, 0x10, 0x10]; + assert_eq!(emulate(&insertq, 0, &mut xmm), Some(6)); + assert_eq!(low(&xmm, 0), 0x1111_2222_abcd_4444); + assert_eq!((low(&xmm, 1), xmm[1].High), (0xabcd, 0x6666)); + // extrq xmm0, length 8, index 20 + let extrq = [0x66, 0x0f, 0x78, 0xc0, 0x08, 0x14]; + assert_eq!(emulate(&extrq, 0, &mut xmm), Some(6)); + assert_eq!(low(&xmm, 0), 0xbc); + } + + #[test] + fn emulated_insertq_and_extrq_with_fields_in_a_register() { + let mut xmm = [reg(0, 0); 16]; + // insertq xmm0, xmm1: length and index in xmm1's high half. + xmm[0] = reg(0x1111_2222_3333_4444, 0); + xmm[1] = reg(0xabcd, 0x10_10); + assert_eq!(emulate(&[0xf2, 0x0f, 0x79, 0xc1], 0, &mut xmm), Some(4)); + assert_eq!(low(&xmm, 0), 0x1111_2222_abcd_4444); + // extrq xmm0, xmm1: length and index in xmm1's low half. + xmm[1] = reg(0x14_08, 0); + assert_eq!(emulate(&[0x66, 0x0f, 0x79, 0xc1], 0, &mut xmm), Some(4)); + assert_eq!(low(&xmm, 0), 0xbc); + } + + #[test] + fn emulated_sse4a_reaches_xmm8_to_xmm15() { + let mut xmm = [reg(0, 0); 16]; + xmm[8] = reg(0x1111_2222_3333_4444, 0); + xmm[9] = reg(0xabcd, 0); + // insertq xmm8, xmm9, length 16, index 16 (REX.R and REX.B) + let insertq = [0xf2, 0x45, 0x0f, 0x78, 0xc1, 0x10, 0x10]; + assert_eq!(emulate(&insertq, 0, &mut xmm), Some(7)); + assert_eq!(low(&xmm, 8), 0x1111_2222_abcd_4444); + assert_eq!((low(&xmm, 0), low(&xmm, 1)), (0, 0)); + // extrq xmm9, length 8, index 4 (REX.B) + let extrq = [0x66, 0x41, 0x0f, 0x78, 0xc1, 0x08, 0x04]; + assert_eq!(emulate(&extrq, 0, &mut xmm), Some(7)); + assert_eq!(low(&xmm, 9), 0xbc); + assert_eq!(low(&xmm, 1), 0); + } + + #[test] + fn emulated_sse4a_length_0_is_64_bits() { + let mut xmm = [reg(0, 0); 16]; + xmm[0] = reg(0x1122_3344_5566_7788, 0); + // extrq xmm0, length 0 (64), index 8 + assert_eq!( + emulate(&[0x66, 0x0f, 0x78, 0xc0, 0x00, 0x08], 0, &mut xmm), + Some(6) + ); + assert_eq!(low(&xmm, 0), 0x0011_2233_4455_6677); + // insertq xmm0, xmm1, length 0 (64), index 0 + xmm[1] = reg(0xdead_beef_cafe_f00d, 0); + assert_eq!( + emulate(&[0xf2, 0x0f, 0x78, 0xc1, 0x00, 0x00], 0, &mut xmm), + Some(6) + ); + assert_eq!(low(&xmm, 0), 0xdead_beef_cafe_f00d); + } + + #[test] + fn other_instructions_and_exceptions_are_not_emulated() { + let mut xmm = [reg(0, 0); 16]; + assert_eq!(emulate(&[0x0f, 0x0b], 0, &mut xmm), None); // ud2 + // extrq with a memory operand, which does not exist + assert_eq!(emulate(&[0x66, 0x0f, 0x79, 0x00], 0, &mut xmm), None); + // extrq with immediates needs ModRM.reg 0 + let bad_extrq = [0x66, 0x0f, 0x78, 0xc8, 0x08, 0x14]; + assert_eq!(emulate(&bad_extrq, 0, &mut xmm), None); + // a clzero that did not cause an illegal instruction + let clzero = [0x0f, 0x01, 0xfc]; + assert_eq!( + emulate_as(EXCEPTION_ACCESS_VIOLATION, &clzero, 0, &mut xmm), + None + ); + } } From f00caec1cf577673d8f2a6e9def49db35a7562e5 Mon Sep 17 00:00:00 2001 From: raffclar Date: Mon, 23 Nov 2026 23:34:49 +0000 Subject: [PATCH 012/445] Loader: test 64-bit extrq at index 0, not in AMD's undefined range --- crates/victory-loader/src/crash.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index e68ab1d..5d6260f 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -609,12 +609,13 @@ mod tests { fn emulated_sse4a_length_0_is_64_bits() { let mut xmm = [reg(0, 0); 16]; xmm[0] = reg(0x1122_3344_5566_7788, 0); - // extrq xmm0, length 0 (64), index 8 + // extrq xmm0, length 0 (64), index 0. A non-zero index with + // length 64 goes past bit 63, and AMD leaves that result undefined. assert_eq!( - emulate(&[0x66, 0x0f, 0x78, 0xc0, 0x00, 0x08], 0, &mut xmm), + emulate(&[0x66, 0x0f, 0x78, 0xc0, 0x00, 0x00], 0, &mut xmm), Some(6) ); - assert_eq!(low(&xmm, 0), 0x0011_2233_4455_6677); + assert_eq!(low(&xmm, 0), 0x1122_3344_5566_7788); // insertq xmm0, xmm1, length 0 (64), index 0 xmm[1] = reg(0xdead_beef_cafe_f00d, 0); assert_eq!( From 0b607b1ca55f12b090a28f1d31e9d6a3296935da Mon Sep 17 00:00:00 2001 From: LaunchDoesntCode Date: Mon, 23 Nov 2026 17:31:08 -0600 Subject: [PATCH 013/445] GPU: verify WARP adapter is software before using it --- crates/victory-gpu/src/host.rs | 53 ++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 51c7b47..d9fdc17 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -177,8 +177,7 @@ fn create() -> windows::core::Result { // is an access violation in this process (a crash report with the // address and instruction) instead of a GPU fault and driver reset. if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() { - let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; - let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?; + let adapter = warp_adapter()?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; tracing::info!("host device on the software adapter (WARP)"); } else { @@ -227,6 +226,56 @@ fn create() -> windows::core::Result { } } +/// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). +/// Reject it before creating a device in diagnostics' software-only mode. +fn warp_adapter() -> windows::core::Result { + // SAFETY: plain DXGI adapter queries. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?; + let desc = adapter.cast::()?.GetDesc1()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + tracing::warn!( + vendor = format_args!("{:#x}", desc.VendorId), + flags = format_args!("{:#x}", desc.Flags), + "DXGI did not identify the WARP adapter as software; refusing device" + ); + return Err(windows::core::Error::from_hresult( + windows::Win32::Foundation::E_FAIL, + )); + } + Ok(adapter) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn warp_adapter_accepts_only_software() { + // This probes DXGI without creating a D3D12 device or running a title. + // SAFETY: plain DXGI adapter queries. + let raw = unsafe { + let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + else { + return; + }; + factory.EnumWarpAdapter::() + }; + let Ok(raw) = raw else { return }; + let desc = unsafe { raw.cast::().unwrap().GetDesc1().unwrap() }; + eprintln!( + "EnumWarpAdapter: vendor={:#x}, flags={:#x}", + desc.VendorId, desc.Flags + ); + assert_eq!( + warp_adapter().is_ok(), + desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0, + ); + } +} + /// A host command list and its allocator, always used together. pub(crate) struct HostList { allocator: ID3D12CommandAllocator, From ea24ea109c6a808d084aeff16f59375cd7dcf4e4 Mon Sep 17 00:00:00 2001 From: 9hvn9yt2vk-netizen <360448330+9hvn9yt2vk-netizen@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:37:58 +0100 Subject: [PATCH 014/445] shader: a lane mask that needs its own value fails instead of overflowing the stack In a wave64 compute program, writing only EXEC's high dword (for example s_mov_b32 exec_hi, 0) and then running any vector instruction crashed the whole process with a stack overflow. The new mask is opaque and keyed by the unchanged low dword, so lowering the instruction's guard asked for that dword's value, the value is a lane mask read as data, its ballot needs the mask's lane bit, and that bit needs the value again: mask_dword -> boolean -> atom -> get -> mask_dword, without end. mask_dword now notes the masks whose ballot it is building, and a mask reached again on the way fails with a reason. The instruction then fails like any other that cannot be expressed: its result is missing, and only a side effect that uses it stops the translation. A shader the translator cannot handle must not take the title down at pipeline creation. Found with a random-input harness over the whole translation (ir, resource, io, structure, emit) of random decodable compute programs. The new test overflows the stack without the fix. One million further programs (about 160,000 fully translated) gave no panic, hang or overflow. --- crates/victory-shader/src/emit/lower.rs | 12 +++++++- crates/victory-shader/src/emit/mod.rs | 37 +++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 1f6ab71..0edc5dd 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -183,6 +183,10 @@ struct Lower<'a> { mask_ok: bool, /// Ballots of masks read as data, by low dword: (low, high). ballots: HashMap, + /// Masks whose ballot is being built: a mask whose lane bit needs its + /// own value as a number (an opaque mask keyed by a dword it shares + /// with another) would otherwise recurse until the stack overflows. + balloting: HashSet, /// Block writing each value. def_block: HashMap, /// IR block being lowered. @@ -472,6 +476,7 @@ impl<'a> Lower<'a> { }, mask_ok: false, ballots: HashMap::new(), + balloting: HashSet::new(), def_block: p .blocks .iter() @@ -1161,7 +1166,12 @@ impl<'a> Lower<'a> { Some(&b) if b == self.cur_ir => self.cur, Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?, }; - let bit = self.boolean(m, at)?; + if !self.balloting.insert(lo) { + return Err("a lane mask whose lanes depend on its own value"); + } + let bit = self.boolean(m, at); + self.balloting.remove(&lo); + let bit = bit?; let i32t = self.s.t.i32; let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); let r = self diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index a283545..a922e1b 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -355,6 +355,43 @@ mod tests { use super::bitcode::Attr; use super::container::SigElement; use super::shader::Shader; + use super::*; + use crate::native::{ComputeIo, StageIo}; + + /// A wave64 compute program that writes only EXEC's high dword + /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask is + /// opaque and keyed by the unchanged low dword, so building its lane bit + /// needed the mask's own value: lowering recursed until the stack + /// overflowed, which takes the whole process down (found by + /// random-input testing). Now the instruction fails like any other that + /// cannot be expressed: its result is missing, and only a side effect + /// that uses it would stop the translation. + #[test] + fn an_exec_high_write_does_not_overflow_the_stack() { + // s_mov_b32 exec_hi, 0; v_mov_b32 v1, v0; s_endpgm + let words = [0xBEFF_0380u32, 0x7E02_0300, 0xBF81_0000]; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 2, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 0, + threads: [64, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + let container = crate::dxbc::build(&[]); + let c = Container::parse(&container).unwrap(); + if let Err(e) = emit(&c, &native, &p, &st, &io, &res) { + assert!(e.to_string().contains("its own value"), "{e}"); + } + } /// A pixel shader writing a constant colour. fn constant_color() -> Vec { From 71cfe8455846957cd1f9d200dd6107a59fb00107 Mon Sep 17 00:00:00 2001 From: Henrique Bueno Date: Mon, 23 Nov 2026 20:40:31 -0300 Subject: [PATCH 015/445] loader: emulate clwb on Intel CPUs before Ice Lake --- crates/victory-loader/src/crash.rs | 50 ++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index eb6bb5e..c724af1 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -153,6 +153,11 @@ unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { [0x0f, 0x01, 0xfa] => {} [0x0f, 0x01, 0xfb] => std::thread::yield_now(), _ => { + if let Some(len) = clwb_len(code.cast::<[u8; 15]>().read_unaligned()) { + // A write-back hint: the PC's memory is coherent, so it has nothing to do. + context.Rip += len as u64; + return true; + } let Some(len) = sse4a(code, &mut context.Anonymous.FltSave.XmmRegisters) else { return false; }; @@ -165,6 +170,33 @@ unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { true } +/// `clwb m8` (`66 [rex] 0f ae /6`, a memory operand), which Intel CPUs before +/// Ice Lake lack: its length, or `None` for any other instruction. +fn clwb_len(code: [u8; 15]) -> Option { + let at = if code[1] & 0xf0 == 0x40 { 2 } else { 1 }; + if code[0] != 0x66 || code[at] != 0x0f || code[at + 1] != 0xae { + return None; + } + let modrm = code[at + 2]; + let (mode, rm) = (modrm >> 6, modrm & 7); + if mode == 3 || (modrm >> 3) & 7 != 6 { + return None; + } + let mut len = at + 3; + let mut base = rm; + if rm == 4 { + base = code[len] & 7; + len += 1; + } + len += match mode { + 0 if rm == 5 || (rm == 4 && base == 5) => 4, + 1 => 1, + 2 => 4, + _ => 0, + }; + Some(len) +} + /// SSE4a's `extrq`/`insertq` (register forms, the only ones there are) on /// the saved XMM registers; returns the instruction's length. unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option { @@ -457,6 +489,24 @@ mod tests { assert_eq!(ours, system); } + #[test] + fn clwb_lengths() { + let pad = |b: &[u8]| { + let mut c = [0u8; 15]; + c[..b.len()].copy_from_slice(b); + c + }; + assert_eq!(clwb_len(pad(&[0x66, 0x41, 0x0f, 0xae, 0x31])), Some(5)); // clwb [r9] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x30])), Some(4)); // clwb [rax] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x70, 0x40])), Some(5)); // clwb [rax+0x40] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0xb0, 0, 1, 0, 0])), Some(8)); // [rax+disp32] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x34, 0x24])), Some(5)); // clwb [rsp] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x35, 0, 0, 0, 0])), Some(8)); // [rip+disp32] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x38])), None); // clflushopt, /7 + assert_eq!(clwb_len(pad(&[0x0f, 0xae, 0x30])), None); // xsaveopt, no 66 + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0xf0])), None); // register form + } + #[test] fn clzero_zeroes_its_line_on_any_cpu() { report_crashes(); From 15b0091e877509878214b5585c27d631d27fea86 Mon Sep 17 00:00:00 2001 From: 9hvn9yt2vk-netizen <360448330+9hvn9yt2vk-netizen@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:19:16 +0100 Subject: [PATCH 016/445] shader: VICTORY_SHADER_LOOP_LIMIT to find what makes world frames slow Translated loops stop after 2^20 iterations per lane so that a loop over not yet mirrored data (zeros) cannot run four billion times. A pass where every lane reaches that limit still takes seconds, though: 2^20 iterations times a 4K screen's 8 million pixels is about 10^13 loop bodies. The world's frames now take 1.5-3 s, and loops spinning to the limit on data that reads as zeros are one candidate. A diagnostics build now reads VICTORY_SHADER_LOOP_LIMIT (decimal or 0x hex, at least 1). If a low value such as 4096 makes world frames much faster, loops hitting the limit are what makes them slow. If not, they are ruled out. The limit is part of the translation, so the shader cache keys on it, and a run that overrides it logs a warning. Release builds always use 2^20. --- README.md | 1 + crates/victory-gpu/src/shader_cache.rs | 16 +++++++- crates/victory-shader/src/emit/lower.rs | 15 ++++---- crates/victory-shader/src/emit/mod.rs | 51 +++++++++++++++++++++++++ 4 files changed, 74 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 3c0b5a9..9509b54 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,7 @@ cargo build --profile diag -p victory --features diagnostics # target\diag\vic | `VICTORY_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) | | `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | | `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | +| `VICTORY_SHADER_LOOP_LIMIT=` | translated shader loops stop after `n` iterations per lane instead of 2^20 (own shader cache entries); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow | | `VICTORY_AUDIO_CAPTURE=` | records what the title plays (our process only) | | `VICTORY_XMA_DUMP=` | saves the first 32 XMA voices' context and input | diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index b52d7f0..0cba938 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -36,13 +36,25 @@ pub(crate) fn counts() -> (u64, u64) { (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed)) } -/// What identifies this build: the BLAKE3 of our executable file. +/// What identifies this build: the BLAKE3 of our executable file and of +/// the translation settings it runs with (the loop limit, which a +/// diagnostics build can change at run time). fn build() -> &'static [u8; 32] { static BUILD: OnceLock<[u8; 32]> = OnceLock::new(); BUILD.get_or_init(|| { let exe = std::env::current_exe().and_then(std::fs::read); + let limit = victory_shader::emit::loop_limit(); + if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT { + tracing::warn!( + limit, + "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner" + ); + } match exe { - Ok(bytes) => *blake3::hash(&bytes).as_bytes(), + Ok(mut bytes) => { + bytes.extend_from_slice(&limit.to_le_bytes()); + *blake3::hash(&bytes).as_bytes() + } Err(e) => { // Without it no entry can be trusted: a fresh key per run. tracing::warn!(error = %e, "cannot read our executable; shader cache unused"); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 1f6ab71..d449c71 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -201,13 +201,14 @@ struct Lower<'a> { abort: Option, } -/// Iterations after which a loop is left (per entry into it). The console -/// runs a loop as long as its data says; data the host has not mirrored -/// yet (a null view reads zeros) can make that four billion iterations, -/// which hangs the host GPU until the driver resets it. A lane that -/// reaches the limit leaves the program as killed (a pixel discards). +/// Iterations after which a loop is left (per entry into it), unless +/// [`super::loop_limit`] says otherwise. The console runs a loop as long as +/// its data says; data the host has not mirrored yet (a null view reads +/// zeros) can make that four billion iterations, which hangs the host GPU +/// until the driver resets it. A lane that reaches the limit leaves the +/// program as killed (a pixel discards). // shortcut: a genuine loop of more iterations than this is cut short too. -const LOOP_LIMIT: u32 = 1 << 20; +pub(super) const LOOP_LIMIT: u32 = 1 << 20; /// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar /// compares, bit tests) are ballots of the lanes' booleans, taken where the @@ -6426,7 +6427,7 @@ impl<'a> Lower<'a> { let (phi, _) = self.counters[&to]; let one = self.s.m.i32(1); let next = self.s.m.bin(c, Bin::Add, phi, one); - let limit = self.s.m.i32(LOOP_LIMIT); + let limit = self.s.m.i32(super::loop_limit()); self.counters .get_mut(&to) .expect("header") diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index a283545..5b8be04 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -95,6 +95,44 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use sampler::StaticSampler; pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; +/// The loop limit without an override: 2^20. +pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; + +/// The iteration count after which a translated loop is left, per lane and +/// per entry into the loop: [`DEFAULT_LOOP_LIMIT`]. +/// +/// With the `diagnostics` feature, `VICTORY_SHADER_LOOP_LIMIT` (decimal or +/// `0x` hex, at least 1) sets it instead. A loop that hits the limit in +/// every lane of a full-screen pass still runs for seconds (2^20 times a +/// 4K screen is about 10^13 iterations); a much lower limit shows whether +/// such loops are what makes a frame slow. The value is part of the +/// translation, so the shader cache must key on it (`victory-gpu`'s does). +pub fn loop_limit() -> u32 { + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + *LIMIT.get_or_init(|| { + if cfg!(feature = "diagnostics") { + parse_loop_limit(std::env::var("VICTORY_SHADER_LOOP_LIMIT").ok().as_deref()) + } else { + lower::LOOP_LIMIT + } + }) +} + +/// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset, +/// unreadable or 0. Pure, for testing. +fn parse_loop_limit(value: Option<&str>) -> u32 { + let parsed = value + .map(str::trim) + .and_then(|v| match v.strip_prefix("0x") { + Some(hex) => u32::from_str_radix(hex, 16).ok(), + None => v.parse().ok(), + }); + match parsed { + Some(n) if n > 0 => n, + _ => lower::LOOP_LIMIT, + } +} + /// A translated shader and what the host binds for it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HostShader { @@ -353,6 +391,19 @@ fn signature(part: &[u8]) -> Result, ShaderError> { #[cfg(test)] mod tests { use super::bitcode::Attr; + use super::lower::LOOP_LIMIT; + use super::parse_loop_limit; + + #[test] + fn the_loop_limit_switch_parses_or_falls_back() { + assert_eq!(parse_loop_limit(None), LOOP_LIMIT); + assert_eq!(parse_loop_limit(Some("4096")), 4096); + assert_eq!(parse_loop_limit(Some(" 0x1000 ")), 4096); + assert_eq!(parse_loop_limit(Some("1")), 1); + for bad in ["", "0", "-5", "lots", "0x", "4294967296"] { + assert_eq!(parse_loop_limit(Some(bad)), LOOP_LIMIT, "{bad:?}"); + } + } use super::container::SigElement; use super::shader::Shader; From e158d9524795fea918dd1c3167d2cd0330e9b4bc Mon Sep 17 00:00:00 2001 From: Vanthys Date: Tue, 24 Nov 2026 00:46:54 +0100 Subject: [PATCH 017/445] Guard texture and XMA offsets against overflow --- crates/victory-formats/src/texture.rs | 38 ++++++++++++++++++++++++++- crates/victory-formats/src/xma.rs | 9 ++++++- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 73ef98d..f512b10 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -651,7 +651,12 @@ impl Layout { } let n = self.desc.element_bytes as usize; let bytes = m.width as usize * n; - let need = (depth as usize - 1) * depth_pitch + (m.height as usize - 1) * row_pitch + bytes; + let need = (depth as usize - 1) + .checked_mul(depth_pitch) + .zip((m.height as usize - 1).checked_mul(row_pitch)) + .and_then(|(depth_offset, row_offset)| depth_offset.checked_add(row_offset)) + .and_then(|offset| offset.checked_add(bytes)) + .ok_or(Error::TooSmall)?; if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes { return Err(Error::TooSmall); } @@ -1010,6 +1015,37 @@ mod tests { assert!(!t.planes[0].layout.addressable()); } + #[test] + fn texture_copies_reject_overflowing_pitches() { + let layout = Layout::new(&desc(4, 2, 1, 4, Swizzle::LINEAR)).unwrap(); + let mut tiled = vec![0; layout.size as usize]; + let mut linear = [0; 32]; + assert_eq!( + layout.detile(&tiled, 0, 0, &mut linear, usize::MAX, 0), + Err(Error::TooSmall) + ); + assert_eq!( + layout.tile(&mut tiled, 0, 0, &linear, usize::MAX, 0), + Err(Error::TooSmall) + ); + } + + #[test] + fn volume_copy_rejects_overflowing_depth_pitch() { + let layout = Layout::new(&Desc { + dimension: Dimension::Tex3d, + depth: 3, + ..desc(4, 2, 1, 4, Swizzle::LINEAR) + }) + .unwrap(); + let tiled = vec![0; layout.size as usize]; + let mut linear = [0; 96]; + assert_eq!( + layout.detile(&tiled, 0, 0, &mut linear, 16, usize::MAX), + Err(Error::TooSmall) + ); + } + #[test] fn bad_descriptions_and_buffers_are_refused() { assert_eq!( diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs index 4a9e606..757dc6a 100644 --- a/crates/victory-formats/src/xma.rs +++ b/crates/victory-formats/src/xma.rs @@ -53,7 +53,8 @@ pub struct Packet { } pub fn packet(data: &[u8], index: usize) -> Option { - let b = data.get(index * PACKET_BYTES..index * PACKET_BYTES + 4)?; + let start = index.checked_mul(PACKET_BYTES)?; + let b = data.get(start..)?.get(..4)?; let h = u32::from_be_bytes([b[0], b[1], b[2], b[3]]); Some(Packet { frames: h >> 26, @@ -1112,6 +1113,12 @@ mod tests { } } + #[test] + fn packet_rejects_out_of_range_indices_and_partial_headers() { + assert!(packet(&[0; 4], usize::MAX / PACKET_BYTES + 1).is_none()); + assert!(packet(&[0; 3], 0).is_none()); + } + #[test] fn packet_headers_and_frame_walk() { // Two packets: frame A (100 bits) and B (16300 bits, crossing into From 4cca76795fed5f9ca6ed5fe87a2abd46b20bcc8b Mon Sep 17 00:00:00 2001 From: Vanthys Date: Tue, 24 Nov 2026 00:46:54 +0100 Subject: [PATCH 018/445] Reject empty XMA test fixture directories --- crates/victory-formats/src/xma.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs index 757dc6a..e6ca931 100644 --- a/crates/victory-formats/src/xma.rs +++ b/crates/victory-formats/src/xma.rs @@ -1162,11 +1162,13 @@ mod tests { fn walks_saved_streams() { let dir = std::env::var("VICTORY_XMA_STREAMS").unwrap(); let mut bad = 0; + let mut streams = 0; for entry in std::fs::read_dir(dir).unwrap() { let path = entry.unwrap().path(); if path.extension().is_none_or(|e| e != "xma") { continue; } + streams += 1; let data = std::fs::read(&path).unwrap(); let counted: u32 = (0..data.len() / PACKET_BYTES) .map(|i| packet(&data, i).unwrap().frames) @@ -1192,6 +1194,7 @@ mod tests { ); bad += u32::from(walked != counted || errors > 0); } + assert!(streams > 0, "VICTORY_XMA_STREAMS contains no .xma files"); assert_eq!(bad, 0); } From 7e42fefebc75780b575b92e5045d6212c70bfacc Mon Sep 17 00:00:00 2001 From: BaggyALPHA <257889696+BaggyALPHA@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:48:23 -0500 Subject: [PATCH 019/445] Report Windows commit-limit failures in crashes.log --- README.md | 5 ++ crates/victory-hle/src/modules/xmem.rs | 73 ++++++++++++++++++++++---- 2 files changed, 68 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 3c0b5a9..e6ee88f 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,11 @@ Requirements: Windows 10/11 x64, a CPU with AVX2, a Direct3D 12 GPU with shader model 6.6 (and mesh shaders for the world), Rust (pinned in `rust-toolchain.toml`). +The title also needs several GiB of available Windows commit at startup. +Check **Committed** under **Task Manager → Performance → Memory**. If +`crashes.log` reports Windows error 1455, close other applications or increase +the Windows paging file size, then retry. + ```powershell cargo xtask install-hooks # asset-policy check on every commit copy victory.example.toml victory.toml # then set your paths (outside the repo) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index bcd3222..8d2c682 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -13,7 +13,9 @@ use std::ffi::c_void; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, LazyLock, Mutex, MutexGuard}; -use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; +use windows_sys::Win32::Foundation::{ + CloseHandle, ERROR_COMMITMENT_LIMIT, HANDLE, INVALID_HANDLE_VALUE, +}; use windows_sys::Win32::System::Memory::{ CreateFileMappingW, MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, @@ -21,7 +23,10 @@ use windows_sys::Win32::System::Memory::{ MemExtendedParameterAddressRequirements, PAGE_NOACCESS, PAGE_READWRITE, SEC_RESERVE, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQueryEx, }; -use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; +use windows_sys::Win32::System::ProcessStatus::{ + K32GetPerformanceInfo, K32GetProcessMemoryInfo, PERFORMANCE_INFORMATION, + PROCESS_MEMORY_COUNTERS, +}; use windows_sys::Win32::System::Threading::GetCurrentProcess; use windows_sys::core::BOOL; @@ -636,16 +641,44 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { /// Commits the section pages a view shows (once per page, whichever view). fn commit(base: usize, len: usize) -> bool { // SAFETY: `[base, base + len)` is a view of a reserved section. - let done = - !unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null(); - if !done { - tracing::warn!( - len, - error = %std::io::Error::last_os_error(), - "committing physical pages failed" + if !unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null() { + return true; + } + let error = std::io::Error::last_os_error(); + if error.raw_os_error() == Some(ERROR_COMMITMENT_LIMIT as i32) { + let mut info = PERFORMANCE_INFORMATION::default(); + info.cb = size_of::() as u32; + // SAFETY: the buffer and size describe a writable PERFORMANCE_INFORMATION. + let queried = unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0; + victory_loader::log_crash(&commit_limit_message(len, &error, queried.then_some(&info))); + } else { + tracing::warn!(len, %error, "committing physical pages failed"); + } + false +} + +fn commit_limit_message( + len: usize, + error: &std::io::Error, + info: Option<&PERFORMANCE_INFORMATION>, +) -> String { + let mut message = format!( + "VIctory: Windows commit limit reached while committing {len} bytes of physical pages: {error}.\n" + ); + if let Some(info) = info { + use std::fmt::Write; + + let committed = info.CommitTotal * info.PageSize / MIB; + let limit = info.CommitLimit * info.PageSize / MIB; + let _ = writeln!( + message, + "System commit: {committed} MiB of {limit} MiB in use." ); } - done + message.push_str( + "Close other applications or increase the Windows paging file size, then retry.\n", + ); + message } /// Returns `[base, base + len)` to placeholders; views reaching past it @@ -877,6 +910,26 @@ mod tests { assert_eq!(std::mem::offset_of!(WorkingSet, gpu_optimal_limit), 0x28); } + #[test] + fn commit_limit_report_includes_request_and_system_commit() { + let error = std::io::Error::from_raw_os_error(ERROR_COMMITMENT_LIMIT as i32); + let info = PERFORMANCE_INFORMATION { + CommitTotal: 512, + CommitLimit: 768, + PageSize: 4096, + ..Default::default() + }; + let report = commit_limit_message(4 * MIB, &error, Some(&info)); + assert!(report.contains("4194304 bytes")); + assert!(report.contains("2 MiB of 3 MiB in use")); + let fallback = commit_limit_message(4 * MIB, &error, None); + for report in [&report, &fallback] { + assert!(report.contains("os error 1455")); + assert!(report.contains("Windows paging file size")); + } + assert!(!fallback.contains("System commit:")); + } + #[test] fn physical_pages_map_alias_and_unmap() { let mut pages = [0usize; 3]; From ef22723e84e4e0a48edcda67fb4d71b6adc08054 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9rez?= Date: Tue, 24 Nov 2026 00:43:16 +0100 Subject: [PATCH 020/445] PE: remove leftover dbg_tls test and check layout offsets Removes the print-only dbg_tls test in image.rs (TLS presence is already asserted in parses_own_test_binary) and switches layout.rs offset helpers (read_u32, read_u64, optional_header_offset, file_header_offset, data_directory_offset) to checked arithmetic so extreme offsets return None instead of overflowing. --- crates/victory-pe/src/image.rs | 11 ----------- crates/victory-pe/src/layout.rs | 30 ++++++++++++++++++++++++------ 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/crates/victory-pe/src/image.rs b/crates/victory-pe/src/image.rs index 8e7f542..b9e54b2 100644 --- a/crates/victory-pe/src/image.rs +++ b/crates/victory-pe/src/image.rs @@ -471,14 +471,3 @@ mod tests { )); } } - -#[cfg(test)] -mod dbg_tls { - #[test] - fn dump_tls() { - let data = std::fs::read(std::env::current_exe().unwrap()).unwrap(); - let info = super::ImageInfo::parse(&data).unwrap(); - eprintln!("TLS = {:?}", info.tls); - eprintln!("image_base = {:x}", info.image_base); - } -} diff --git a/crates/victory-pe/src/layout.rs b/crates/victory-pe/src/layout.rs index fd99b7f..09330a9 100644 --- a/crates/victory-pe/src/layout.rs +++ b/crates/victory-pe/src/layout.rs @@ -66,26 +66,44 @@ pub mod subsystem { /// Offset of the optional header from the start of the file. pub fn optional_header_offset(data: &[u8]) -> Option { let lfanew = read_u32(data, DOS_E_LFANEW)? as usize; - Some(lfanew + NT_SIGNATURE_SIZE + FILE_HEADER_SIZE) + lfanew.checked_add(NT_SIGNATURE_SIZE + FILE_HEADER_SIZE) } /// Offset of the file header from the start of the file. pub fn file_header_offset(data: &[u8]) -> Option { let lfanew = read_u32(data, DOS_E_LFANEW)? as usize; - Some(lfanew + NT_SIGNATURE_SIZE) + lfanew.checked_add(NT_SIGNATURE_SIZE) } /// Offset of data directory `index` from the start of the file. pub fn data_directory_offset(data: &[u8], index: usize) -> Option { let opt = optional_header_offset(data)?; - let count = read_u32(data, opt + OPT_NUMBER_OF_RVA_AND_SIZES)? as usize; - (index < count).then_some(opt + OPT_DATA_DIRECTORY + index * DATA_DIRECTORY_SIZE) + let count = read_u32(data, opt.checked_add(OPT_NUMBER_OF_RVA_AND_SIZES)?)? as usize; + if index >= count { + return None; + } + opt.checked_add(OPT_DATA_DIRECTORY)? + .checked_add(index.checked_mul(DATA_DIRECTORY_SIZE)?) } pub fn read_u32(data: &[u8], at: usize) -> Option { - Some(u32::from_le_bytes(data.get(at..at + 4)?.try_into().ok()?)) + let end = at.checked_add(4)?; + Some(u32::from_le_bytes(data.get(at..end)?.try_into().ok()?)) } pub fn read_u64(data: &[u8], at: usize) -> Option { - Some(u64::from_le_bytes(data.get(at..at + 8)?.try_into().ok()?)) + let end = at.checked_add(8)?; + Some(u64::from_le_bytes(data.get(at..end)?.try_into().ok()?)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_reject_overflowing_offsets() { + let data = [0u8; 16]; + assert_eq!(read_u32(&data, usize::MAX - 1), None); + assert_eq!(read_u64(&data, usize::MAX - 2), None); + } } From 2e5001cf9d11c7210c5f1409b7418e49c17e8ff3 Mon Sep 17 00:00:00 2001 From: alessiodeia <75262890+alessiodeia@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:38:04 +0100 Subject: [PATCH 021/445] shader: keep fract(NaN) as NaN on NVIDIA and add synthetic GPU VALU tests Fixes a real-hardware NVIDIA bug in fract() from 36eb0b4 and adds synthetic GFX10 -> DXIL -> GPU/WARP regression tests for the RDNA2 VALU lowerings from #2: - fract(): select(OGT(r, k), k, r) is folded by NVIDIA's DXIL compiler into FMNMX (minNum), which swallows NaN and turns v_fract_f32(NaN) into 0x3f7fffff (and v_fract_f16(NaN) into 0x3bff). Comparing with pred::OGE against a distinct threshold (1.0 for f32, 1 - 2^-12 for f16) prevents the minNum fold and preserves NaN and +/-inf -> NaN on both NVIDIA hardware and WARP. - valu_tests.rs: builds minimal synthetic GFX10 compute shaders, lowers them through the full pipeline (ir::build -> resource::track -> io::raise -> structure -> lower), validates with dxil.dll when present, and executes them via Host::dispatch on both hardware GPU and WARP without requiring console dxc. Covers v_fract_f32/f16, v_med3_f32/f16, v_sin/v_cos_f32/f16, and v_bfe_i32/u32 + s_bfe_i32. Co-authored-by: BlueKaiman <360454391+BlueKaiman@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 15 +- crates/victory-shader/src/emit/mod.rs | 2 + crates/victory-shader/src/emit/valu_tests.rs | 675 +++++++++++++++++++ 3 files changed, 686 insertions(+), 6 deletions(-) create mode 100644 crates/victory-shader/src/emit/valu_tests.rs diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 1f6ab71..e3bba6d 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1409,12 +1409,15 @@ impl<'a> Lower<'a> { /// `a - floor(a)`, which on the hardware never reaches 1.0: where it /// would round to it (a tiny negative `a`), the result is `below_one`, /// the largest value under 1.0 in the operation's width. Hosts differ - /// here (some give 1.0). NaN stays NaN. - fn fract(&mut self, a: V, below_one: f32) -> V { + /// here (some give 1.0). Comparing against a `threshold` distinct from + /// `below_one` prevents drivers (observed on NVIDIA) from folding + /// `r > k ? k : r` into `minNum` (`FMNMX`) and swallowing NaN. + fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V { let c = self.cur; let r = self.unary(22, a); + let limit = self.s.m.f32(threshold.to_bits()); let k = self.s.m.f32(below_one.to_bits()); - let over = self.s.m.cmp(c, pred::OGT, r, k); + let over = self.s.m.cmp(c, pred::OGE, r, limit); self.s.m.select(c, over, k, r) } @@ -3711,7 +3714,7 @@ impl<'a> Lower<'a> { }; let r = match op { 12 | 13 => self.trig_turns(a, op == 12), - 22 => self.fract(a, f32::from_bits(0x3F7F_FFFF)), + 22 => self.fract(a, 1.0, f32::from_bits(0x3F7F_FFFF)), _ => self.unary(op, a), }; float(self, r) @@ -4312,8 +4315,8 @@ impl<'a> Lower<'a> { }; match op { 12 | 13 => self.trig_turns(a, op == 12), - // 0x3bff as a half: 1 - 2^-11. - 22 => self.fract(a, 1.0 - 1.0 / 2048.0), + // Any f16 in (-2^-11, 0) has fract >= 1 - 2^-12; clamp to 0x3bff (1 - 2^-11). + 22 => self.fract(a, 1.0 - 1.0 / 4096.0, 1.0 - 1.0 / 2048.0), _ => self.unary(op, a), } } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index a283545..3fd0f5e 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -86,6 +86,8 @@ mod sampler; mod shader; #[cfg(windows)] pub mod validator; +#[cfg(all(test, windows))] +mod valu_tests; mod wave; use crate::dxbc::{Container, FourCC}; diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs new file mode 100644 index 0000000..1b95ca6 --- /dev/null +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -0,0 +1,675 @@ +//! End-to-end tests of synthetic GFX10 VALU shaders lowered to DXIL, validated +//! by `dxil.dll` when present, and executed on the host GPU and WARP. +//! +//! Covers RDNA2 hardware semantics that differ from naive DXIL lowering: +//! `v_med3_f32`/`v_med3_f16` with NaN operands, `v_fract_f32`/`v_fract_f16` +//! near `1.0`, and turn-range reduction for `v_sin_*`/`v_cos_*`. + +use super::host::{Dispatch, Host, Root, View}; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, ir, resource, structure}; + +const S_ENDPGM: u32 = 0xBF81_0000; + +/// SOP1 `s_mov_b32 sdst, src0`. +const fn s_mov_b32(sdst: u8, src0: u8) -> u32 { + 0xBE80_0000 | (sdst as u32) << 16 | 0x03 << 8 | src0 as u32 +} + +/// SOP2 `op sdst, src0, src1`. +const fn sop2(op: u8, sdst: u8, src0: u8, src1: u8) -> u32 { + 0x8000_0000 + | (op as u32 & 0x7F) << 23 + | (sdst as u32 & 0x7F) << 16 + | (src1 as u32) << 8 + | src0 as u32 +} + +/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], 0` (soffset = null). +const fn s_load_dwordx4(dst: u8, base: u8) -> [u32; 2] { + [ + 0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1), + 125 << 25, + ] +} + +/// VOP1 `op vdst, src0` (`src0`: 0..105 = SGPR, 256..511 = VGPR). +const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 { + 0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF) +} + +/// VOP3 `op vdst, src0, src1, src2` (no modifiers). +const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] { + [ + 0x35 << 26 | (op as u32 & 0x3FF) << 16 | vdst as u32, + (src0 as u32 & 0x1FF) | (src1 as u32 & 0x1FF) << 9 | (src2 as u32 & 0x1FF) << 18, + ] +} + +/// MUBUF `buffer_store_dword vdata, off, s[srsrc:srsrc+3], 0 offset:byte_off`. +const fn buffer_store_dword(vdata: u8, srsrc: u8, byte_off: u16) -> [u32; 2] { + [ + 0x38 << 26 | 0x1C << 18 | (byte_off as u32 & 0xFFF), + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8, + ] +} + +const fn sgpr(n: u8) -> u16 { + n as u16 +} + +const fn vgpr(n: u8) -> u16 { + 256 + n as u16 +} + +/// Builds and lowers a 1-thread synthetic RDNA2 compute shader that receives +/// 4 dwords of root constants in `s0..s3`, runs `body` (leaving its result in +/// `v0`), and stores `v0` to dword 0 of the raw UAV at heap index 0. +fn build_valu_cs(body: &[u32]) -> HostShader { + let mut words = Vec::new(); + // s[4:5] = descriptor table address (heap index 0 -> byte offset 0). + words.push(s_mov_b32(5, 0x80)); // inline constant 0 + words.extend_from_slice(&s_load_dwordx4(8, 4)); + // Copy root constants s0..s3 into v1..v4 so VALU instructions operate on + // VGPRs just as they do in real shaders. + for i in 0..4u8 { + words.push(vop1(0x001, i + 1, sgpr(i))); // v_mov_b32 + } + words.extend_from_slice(body); + words.extend_from_slice(&buffer_store_dword(0, 8, 0)); + words.push(S_ENDPGM); + + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 + threads: [1, 1, 1], + }), + code, + }; + + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let res = resource::track(&p, &native.layout, native.stage).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let st = structure::structure(&p).expect("structure"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + }; + + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + let ours = copy[4..20].to_vec(); + v.validate(&mut copy).expect("DXIL validation failed"); + assert_eq!(copy[4..20], ours[..], "container hash mismatch"); + } + + shader +} + +/// Runs `shader` on every available SM 6.6 host (hardware GPU and WARP) for +/// each 4-dword input set and invokes `check(backend, case_index, inputs, result_dword)`. +fn run_cases( + shader: &HostShader, + cases: &[[u32; 4]], + mut check: impl FnMut(&str, usize, [u32; 4], u32), +) { + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host + .compute_pipeline(shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + for (i, &inputs) in cases.iter().enumerate() { + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.slot) { + (RootType::Constants, 0) => inputs[u.dword as usize], + (RootType::Table, 1) => 0, + other => panic!("unexpected user data {other:?}"), + }; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + check(label, i, inputs, out[0][0]); + } + ran += 1; + } + assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); +} + +fn is_f16_nan(bits: u16) -> bool { + (bits & 0x7FFF) > 0x7C00 +} + +fn f16_to_f32(bits: u16) -> f32 { + let sign = u32::from(bits >> 15) << 31; + let exp = (bits >> 10) & 0x1F; + let mant = bits & 0x3FF; + let f32_bits = match exp { + 0 => { + if mant == 0 { + sign + } else { + let mut m = u32::from(mant); + let mut e = 127 - 14; + while (m & 0x400) == 0 { + m <<= 1; + e -= 1; + } + sign | (e << 23) | ((m & 0x3FF) << 13) + } + } + 0x1F => sign | (0xFF << 23) | (u32::from(mant) << 13), + _ => sign | ((u32::from(exp) + 112) << 23) | (u32::from(mant) << 13), + }; + f32::from_bits(f32_bits) +} + +#[test] +fn v_med3_f32_matches_rdna2_with_nan() { + // v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157) + let shader = build_valu_cs(&vop3(0x157, 0, vgpr(1), vgpr(2), vgpr(3))); + let nan = f32::NAN.to_bits(); + let f = f32::to_bits; + + let cases: &[([u32; 4], Option)] = &[ + // Normal medians (all orderings). + ([f(1.0), f(2.0), f(3.0), 0], Some(2.0)), + ([f(3.0), f(1.0), f(2.0), 0], Some(2.0)), + ([f(-5.0), f(0.0), f(5.0), 0], Some(0.0)), + ([f(1.0), f(1.0), f(2.0), 0], Some(1.0)), + // One NaN: RDNA2 returns min3 of the non-NaN operands. + ([f(1.0), f(2.0), nan, 0], Some(1.0)), + ([nan, f(1.0), f(0.0), 0], Some(0.0)), + ([nan, f(0.0), f(1.0), 0], Some(0.0)), + ([f(2.0), nan, f(1.0), 0], Some(1.0)), + ([f(-3.0), nan, f(4.0), 0], Some(-3.0)), + // Two NaNs: returns the sole non-NaN operand. + ([nan, f(5.0), nan, 0], Some(5.0)), + ([nan, nan, f(-2.0), 0], Some(-2.0)), + ([f(7.0), nan, nan, 0], Some(7.0)), + // Three NaNs: returns NaN. + ([nan, nan, nan, 0], None), + ]; + + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let expect = cases[i].1; + let got_f = f32::from_bits(got); + match expect { + Some(want) => assert_eq!( + got_f, + want, + "{backend}: v_med3_f32({:?}, {:?}, {:?}) = {got_f} ({got:#010x}), want {want}", + f32::from_bits(inp[0]), + f32::from_bits(inp[1]), + f32::from_bits(inp[2]), + ), + None => assert!( + got_f.is_nan(), + "{backend}: v_med3_f32(NaN, NaN, NaN) = {got_f} ({got:#010x}), want NaN", + ), + } + }); +} + +#[test] +fn v_med3_f16_matches_rdna2_with_nan() { + // v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357) + let shader = build_valu_cs(&vop3(0x357, 0, vgpr(1), vgpr(2), vgpr(3))); + let h0 = 0x0000u32; // 0.0 + let h1 = 0x3C00u32; // 1.0 + let h2 = 0x4000u32; // 2.0 + let h3 = 0x4200u32; // 3.0 + let h5 = 0x4500u32; // 5.0 + let hn2 = 0xC000u32; // -2.0 + let nan = 0x7E00u32; + + let cases: &[([u32; 4], Option)] = &[ + ([h1, h2, h3, 0], Some(h2 as u16)), + ([hn2, h0, h3, 0], Some(h0 as u16)), + ([h1, h2, nan, 0], Some(h1 as u16)), + ([nan, h1, h0, 0], Some(h0 as u16)), + ([nan, h0, h1, 0], Some(h0 as u16)), + ([h2, nan, h1, 0], Some(h1 as u16)), + ([nan, h5, nan, 0], Some(h5 as u16)), + ([nan, nan, nan, 0], None), + ]; + + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let expect = cases[i].1; + let got_h = got as u16; + match expect { + Some(want) => assert_eq!( + got_h, want, + "{backend}: v_med3_f16({:#06x}, {:#06x}, {:#06x}) = {got_h:#06x}, want {want:#06x}", + inp[0], inp[1], inp[2], + ), + None => assert!( + is_f16_nan(got_h), + "{backend}: v_med3_f16(NaN, NaN, NaN) = {got_h:#06x}, want NaN", + ), + } + }); +} + +#[test] +fn v_fract_f32_never_returns_one() { + // v_fract_f32 v0, v1 (VOP1 opcode 0x020) + let shader = build_valu_cs(&[vop1(0x020, 0, vgpr(1))]); + let f = f32::to_bits; + let below_one = 0x3F7F_FFFFu32; + + let cases: &[(u32, Option)] = &[ + // Tiny negatives: must clamp strictly below 1.0 (not 0x3f800000). + (f(-1e-10), Some(below_one)), + (f(-1e-8), Some(below_one)), + (f(-2.0f32.powi(-25)), Some(below_one)), + (f(-2.0f32.powi(-24)), Some(below_one)), + // Normal values. + (f(0.0), Some(f(0.0))), + (f(-0.0), Some(f(0.0))), + (f(0.25), Some(f(0.25))), + (f(3.75), Some(f(0.75))), + (f(-0.25), Some(f(0.75))), + (f(-3.25), Some(f(0.75))), + (f(1.0), Some(f(0.0))), + (f(-1.0), Some(f(0.0))), + // Non-finite inputs yield NaN. + (f(f32::NAN), None), + (f(f32::INFINITY), None), + (f(f32::NEG_INFINITY), None), + ]; + + let inputs: Vec<[u32; 4]> = cases.iter().map(|&(x, _)| [x, 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let expect = cases[i].1; + match expect { + Some(want) => assert_eq!( + got, + want, + "{backend}: v_fract_f32({:?} / {:#010x}) = {got:#010x} ({:?}), want {want:#010x}", + f32::from_bits(inp[0]), + inp[0], + f32::from_bits(got), + ), + None => assert!( + f32::from_bits(got).is_nan(), + "{backend}: v_fract_f32({:?}) = {got:#010x}, want NaN", + f32::from_bits(inp[0]), + ), + } + }); +} + +#[test] +fn v_fract_f16_never_returns_one() { + // v_fract_f16 v0, v1 (VOP1 opcode 0x05f) + let shader = build_valu_cs(&[vop1(0x05f, 0, vgpr(1))]); + let below_one = 0x3BFFu16; // 1.0 - 2^-11 + + assert_eq!(f16_to_f32(0x9400), -2.0f32.powi(-10)); + assert_eq!(f16_to_f32(0x9000), -2.0f32.powi(-11)); + assert_eq!(f16_to_f32(0x8C00), -2.0f32.powi(-12)); + + let cases: &[(u16, Option)] = &[ + // Negatives in (-2^-11, 0): must clamp to 0x3BFF, never 0x3C00 (1.0). + (0x8C00, Some(below_one)), // -2^-12 + (0x8400, Some(below_one)), // -2^-14 + (0x8001, Some(below_one)), // -2^-24 (smallest negative f16 subnormal) + (0x9000, Some(below_one)), // -2^-11 (exact 1 - 2^-11 = 0x3BFF) + (0x9400, Some(0x3BFE)), // -2^-10 (exact 1 - 2^-10 = 0x3BFE) + // Normal values. + (0x0000, Some(0x0000)), // 0.0 -> 0.0 + (0x3400, Some(0x3400)), // 0.25 -> 0.25 + (0xB400, Some(0x3A00)), // -0.25 -> 0.75 + (0x4300, Some(0x3800)), // 3.5 -> 0.5 + (0x3C00, Some(0x0000)), // 1.0 -> 0.0 + // Non-finite inputs yield NaN. + (0x7E00, None), // NaN + (0x7C00, None), // +inf + (0xFC00, None), // -inf + ]; + + let inputs: Vec<[u32; 4]> = cases + .iter() + .map(|&(x, _)| [u32::from(x), 0, 0, 0]) + .collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let expect = cases[i].1; + let got_h = got as u16; + match expect { + Some(want) => assert_eq!( + got_h, want, + "{backend}: v_fract_f16({:#06x}) = {got_h:#06x}, want {want:#06x}", + inp[0], + ), + None => assert!( + is_f16_nan(got_h), + "{backend}: v_fract_f16({:#06x}) = {got_h:#06x}, want NaN", + inp[0], + ), + } + }); +} + +#[test] +fn v_sin_and_v_cos_f32_reduce_large_turns() { + let sin_shader = build_valu_cs(&[vop1(0x035, 0, vgpr(1))]); + let cos_shader = build_valu_cs(&[vop1(0x036, 0, vgpr(1))]); + let f = f32::to_bits; + let half_sqrt2 = std::f32::consts::FRAC_1_SQRT_2; + + let sin_cases: &[(f32, Option)] = &[ + (0.0, Some(0.0)), + (0.25, Some(1.0)), + (255.0, Some(0.0)), + (255.25, Some(1.0)), + (255.5, Some(0.0)), + (-255.25, Some(-1.0)), + (10_000.125, Some(half_sqrt2)), + (f32::NAN, None), + (f32::INFINITY, None), + (f32::NEG_INFINITY, None), + ]; + let sin_inputs: Vec<[u32; 4]> = sin_cases.iter().map(|&(x, _)| [f(x), 0, 0, 0]).collect(); + run_cases(&sin_shader, &sin_inputs, |backend, i, inp, got| { + let expect = sin_cases[i].1; + let got_f = f32::from_bits(got); + match expect { + Some(want) => assert!( + (got_f - want).abs() < 1e-5, + "{backend}: v_sin_f32({}) = {got_f}, want {want} (err = {})", + f32::from_bits(inp[0]), + (got_f - want).abs(), + ), + None => assert!( + got_f.is_nan(), + "{backend}: v_sin_f32({}) = {got_f}, want NaN", + f32::from_bits(inp[0]), + ), + } + }); + + let cos_cases: &[(f32, Option)] = &[ + (0.0, Some(1.0)), + (0.25, Some(0.0)), + (255.0, Some(1.0)), + (255.25, Some(0.0)), + (255.5, Some(-1.0)), + (-255.5, Some(-1.0)), + (10_000.125, Some(half_sqrt2)), + (f32::NAN, None), + (f32::INFINITY, None), + (f32::NEG_INFINITY, None), + ]; + let cos_inputs: Vec<[u32; 4]> = cos_cases.iter().map(|&(x, _)| [f(x), 0, 0, 0]).collect(); + run_cases(&cos_shader, &cos_inputs, |backend, i, inp, got| { + let expect = cos_cases[i].1; + let got_f = f32::from_bits(got); + match expect { + Some(want) => assert!( + (got_f - want).abs() < 1e-5, + "{backend}: v_cos_f32({}) = {got_f}, want {want} (err = {})", + f32::from_bits(inp[0]), + (got_f - want).abs(), + ), + None => assert!( + got_f.is_nan(), + "{backend}: v_cos_f32({}) = {got_f}, want NaN", + f32::from_bits(inp[0]), + ), + } + }); + + // Main's `trig_turns` preserves sin(-0.0) = -0.0 and produces exact +0.0 at + // half-turns (sin) and quarter-turns (cos). + let exact_sin: &[(u32, u32)] = &[ + (0x8000_0000, 0x8000_0000), // sin(-0.0) = -0.0 + (f(255.0), 0), // sin(255.0) = +0.0 + (f(255.5), 0), // sin(255.5) = +0.0 + ]; + let exact_sin_in: Vec<[u32; 4]> = exact_sin.iter().map(|&(x, _)| [x, 0, 0, 0]).collect(); + run_cases(&sin_shader, &exact_sin_in, |backend, i, inp, got| { + let want = exact_sin[i].1; + assert_eq!( + got, want, + "{backend}: v_sin_f32({:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], + ); + }); + let exact_cos: &[(u32, u32)] = &[ + (f(0.25), 0), // cos(0.25) = +0.0 + (f(255.25), 0), // cos(255.25) = +0.0 + ]; + let exact_cos_in: Vec<[u32; 4]> = exact_cos.iter().map(|&(x, _)| [x, 0, 0, 0]).collect(); + run_cases(&cos_shader, &exact_cos_in, |backend, i, inp, got| { + let want = exact_cos[i].1; + assert_eq!( + got, want, + "{backend}: v_cos_f32({:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], + ); + }); +} + +#[test] +fn v_sin_and_v_cos_f16_reduce_large_turns() { + let sin_shader = build_valu_cs(&[vop1(0x060, 0, vgpr(1))]); + let cos_shader = build_valu_cs(&[vop1(0x061, 0, vgpr(1))]); + + // Sanity-check the f16 bit encodings of large turns. + assert_eq!(f16_to_f32(0x5BF8), 255.0); + assert_eq!(f16_to_f32(0x5BFA), 255.25); + assert_eq!(f16_to_f32(0x5BFC), 255.5); + assert_eq!(f16_to_f32(0x7BFF), 65504.0); + + let sin_cases: &[(u16, Option)] = &[ + (0x5BF8, Some(0.0)), // 255.0 + (0x5BFA, Some(1.0)), // 255.25 + (0x5BFC, Some(0.0)), // 255.5 + (0xDBFA, Some(-1.0)), // -255.25 + (0x7BFF, Some(0.0)), // 65504.0 (largest finite f16, exact integer) + (0x7E00, None), // NaN + (0x7C00, None), // +inf + (0xFC00, None), // -inf + ]; + let sin_inputs: Vec<[u32; 4]> = sin_cases + .iter() + .map(|&(x, _)| [u32::from(x), 0, 0, 0]) + .collect(); + run_cases(&sin_shader, &sin_inputs, |backend, i, inp, got| { + let expect = sin_cases[i].1; + let got_h = got as u16; + match expect { + Some(want) => { + let got_f = f16_to_f32(got_h); + assert!( + (got_f - want).abs() < 1e-3, + "{backend}: v_sin_f16({:#06x} = {}) = {got_f} ({got_h:#06x}), want {want}", + inp[0], + f16_to_f32(inp[0] as u16), + ); + } + None => assert!( + is_f16_nan(got_h), + "{backend}: v_sin_f16({:#06x}) = {got_h:#06x}, want NaN", + inp[0], + ), + } + }); + + let cos_cases: &[(u16, Option)] = &[ + (0x5BF8, Some(1.0)), // 255.0 + (0x5BFA, Some(0.0)), // 255.25 + (0x5BFC, Some(-1.0)), // 255.5 + (0x7BFF, Some(1.0)), // 65504.0 (largest finite f16, exact integer) + (0x7E00, None), // NaN + (0x7C00, None), // +inf + (0xFC00, None), // -inf + ]; + let cos_inputs: Vec<[u32; 4]> = cos_cases + .iter() + .map(|&(x, _)| [u32::from(x), 0, 0, 0]) + .collect(); + run_cases(&cos_shader, &cos_inputs, |backend, i, inp, got| { + let expect = cos_cases[i].1; + let got_h = got as u16; + match expect { + Some(want) => { + let got_f = f16_to_f32(got_h); + assert!( + (got_f - want).abs() < 1e-3, + "{backend}: v_cos_f16({:#06x} = {}) = {got_f} ({got_h:#06x}), want {want}", + inp[0], + f16_to_f32(inp[0] as u16), + ); + } + None => assert!( + is_f16_nan(got_h), + "{backend}: v_cos_f16({:#06x}) = {got_h:#06x}, want NaN", + inp[0], + ), + } + }); +} + +#[test] +fn bfe_signed_and_unsigned_match_rdna2() { + // v_bfe_i32 v0, v1, v2, v3 (VOP3 opcode 0x149) + let v_signed = build_valu_cs(&vop3(0x149, 0, vgpr(1), vgpr(2), vgpr(3))); + // v_bfe_u32 v0, v1, v2, v3 (VOP3 opcode 0x148) + let v_unsigned = build_valu_cs(&vop3(0x148, 0, vgpr(1), vgpr(2), vgpr(3))); + // s_bfe_i32 s6, s0, s1 (SOP2 opcode 0x28: s1 = off[4:0] | width[22:16]); v_mov_b32 v0, s6 + let s_signed = build_valu_cs(&[sop2(0x28, 6, 0, 1), vop1(0x001, 0, sgpr(6))]); + + let signed_cases: &[([u32; 4], u32)] = &[ + // Field crosses bit 31: extends from bit 31. + ([0xd2f9_0159, 28, 16, 0], 0xffff_fffd), + ([0x8000_0000, 31, 4, 0], 0xffff_ffff), + ([0x7000_0000, 28, 8, 0], 0x0000_0007), + // Normal fields inside 32 bits. + ([0x0000_0080, 4, 4, 0], 0xffff_fff8), + ([0x0000_0070, 4, 4, 0], 0x0000_0007), + // Edge widths: 0 yields 0; v_bfe masks width to 5 bits (32 -> 0), + // while 31 extracts all remaining bits from offset 4. + ([0xffff_ffff, 4, 0, 0], 0), + ([0x8000_0000, 4, 31, 0], 0xf800_0000), + ]; + let v_in: Vec<[u32; 4]> = signed_cases.iter().map(|c| c.0).collect(); + run_cases(&v_signed, &v_in, |backend, i, inp, got| { + let want = signed_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_bfe_i32({:#010x}, {}, {}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], inp[2], + ); + }); + // v_bfe_i32 width is 5-bit (src2[4:0]), so width=32 wraps to 0. + run_cases( + &v_signed, + &[[0x8000_0000, 4, 32, 0]], + |backend, _, _, got| { + assert_eq!(got, 0, "{backend}: v_bfe_i32 width 32 should mask to 0"); + }, + ); + + // s_bfe_i32 width is 7-bit (src1[22:16]), so width=32 keeps all 32 bits. + let mut s_cases = signed_cases.to_vec(); + s_cases.push(([0x8000_0000, 4, 32, 0], 0xf800_0000)); + let s_in: Vec<[u32; 4]> = s_cases + .iter() + .map(|&(inp, _)| [inp[0], (inp[1] & 31) | ((inp[2] & 0x7F) << 16), 0, 0]) + .collect(); + run_cases(&s_signed, &s_in, |backend, i, inp, got| { + let want = s_cases[i].1; + assert_eq!( + got, want, + "{backend}: s_bfe_i32({:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], + ); + }); + + let unsigned_cases: &[([u32; 4], u32)] = &[ + ([0xd2f9_0159, 28, 16, 0], 0x0000_000d), + ([0x8000_0000, 31, 4, 0], 0x0000_0001), + ([0xffff_ffff, 4, 0, 0], 0), + ([0x8000_0000, 4, 31, 0], 0x0800_0000), + ]; + let u_in: Vec<[u32; 4]> = unsigned_cases.iter().map(|c| c.0).collect(); + run_cases(&v_unsigned, &u_in, |backend, i, inp, got| { + let want = unsigned_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_bfe_u32({:#010x}, {}, {}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], inp[2], + ); + }); +} From 4da3d63666df07246808055fa70e5eef6717e988 Mon Sep 17 00:00:00 2001 From: ifBars Date: Mon, 23 Nov 2026 15:55:36 -0800 Subject: [PATCH 022/445] Clear the IAT directory alongside the import directory Windows 10 maps the prepared image with both entries empty. The binder already retains the original slot RVAs, so preparation need not locate a linker-provided terminator. --- crates/victory-loader/src/prepare.rs | 82 +++++++++++++--------------- crates/victory-pe/src/layout.rs | 1 + 2 files changed, 40 insertions(+), 43 deletions(-) diff --git a/crates/victory-loader/src/prepare.rs b/crates/victory-loader/src/prepare.rs index 1b601b4..336f278 100644 --- a/crates/victory-loader/src/prepare.rs +++ b/crates/victory-loader/src/prepare.rs @@ -35,8 +35,8 @@ impl PreparedImage { /// /// * `IMAGE_FILE_DLL` set, entry point cleared: the OS maps it like a DLL /// and calls nothing; -/// * import directory made empty and bound-import directory cleared: we bind imports -/// ourselves, using `info.imports` from the original; +/// * import, bound-import and IAT directories cleared: we bind the original +/// IAT slots ourselves, using `info.imports`; /// * TLS callback pointer cleared: the OS still allocates static TLS for /// the image, but callbacks only run when we call them (after binding); /// its base relocation is made a no-op so the 0 survives a rebase; @@ -64,20 +64,12 @@ pub fn prepare(original: &[u8]) -> Result { dll_characteristics, )?; - // Windows 10 can read the import directory when an IAT is still - // advertised. Point it at the empty descriptor that ends the table. - if let Some(at) = layout::data_directory_offset(&bytes, dir::IMPORT) { - let terminator = import_terminator(&bytes, &info, at); - write_u32(&mut bytes, at, terminator.unwrap_or(0))?; - write_u32( - &mut bytes, - at + 4, - terminator.map_or(0, |_| IMPORT_DESCRIPTOR_SIZE), - )?; - } - if let Some(at) = layout::data_directory_offset(&bytes, dir::BOUND_IMPORT) { - write_u32(&mut bytes, at, 0)?; - write_u32(&mut bytes, at + 4, 0)?; + // Clear the IAT directory along with the import directory for Windows 10. + // The slots themselves stay in the image for our binder. + for index in [dir::IMPORT, dir::BOUND_IMPORT, dir::IAT] { + if let Some(at) = layout::data_directory_offset(&bytes, index) { + write(&mut bytes, at, &[0; layout::DATA_DIRECTORY_SIZE])?; + } } if let Some(tls) = &info.tls @@ -110,21 +102,6 @@ pub fn prepare(original: &[u8]) -> Result { }) } -const IMPORT_DESCRIPTOR_SIZE: u32 = 20; - -/// The RVA of the all-zero descriptor at the end of the import directory. -fn import_terminator(bytes: &[u8], info: &ImageInfo, directory: usize) -> Option { - let rva = layout::read_u32(bytes, directory)?; - if rva == 0 { - return None; - } - let size = layout::read_u32(bytes, directory + 4)?; - let end_rva = rva.checked_add(size.checked_sub(IMPORT_DESCRIPTOR_SIZE)?)?; - let offset = info.rva_to_file_offset(end_rva)? as usize; - let descriptor = bytes.get(offset..offset + IMPORT_DESCRIPTOR_SIZE as usize)?; - descriptor.iter().all(|&byte| byte == 0).then_some(end_rva) -} - /// Every `IMAGE_REL_BASED_DIR64` base relocation: (file offset of its entry, /// RVA it patches). Empty if the image has no readable relocation table. fn dir64_relocations(bytes: &[u8], info: &ImageInfo) -> Vec<(usize, u32)> { @@ -197,18 +174,13 @@ mod tests { assert!(patched.is_dll()); assert_eq!(patched.entry_rva, 0); assert!(patched.imports.is_empty()); - let import = layout::data_directory_offset(&original, dir::IMPORT).unwrap(); - let rva = layout::read_u32(&original, import).unwrap(); - let size = layout::read_u32(&original, import + 4).unwrap(); - assert_ne!(rva, 0); - assert_eq!( - layout::read_u32(&prepared.bytes, import), - Some(rva + size - IMPORT_DESCRIPTOR_SIZE) - ); - assert_eq!( - layout::read_u32(&prepared.bytes, import + 4), - Some(IMPORT_DESCRIPTOR_SIZE) - ); + for index in [dir::IMPORT, dir::BOUND_IMPORT, dir::IAT] { + let at = layout::data_directory_offset(&original, index).unwrap(); + assert_eq!( + &prepared.bytes[at..at + layout::DATA_DIRECTORY_SIZE], + &[0; 8] + ); + } assert_eq!(patched.dll_characteristics & dll_flags::FORCE_INTEGRITY, 0); if let Some(tls) = &patched.tls { assert_eq!(tls.callbacks_va, 0); @@ -225,6 +197,30 @@ mod tests { assert_eq!(prepared.bytes.len(), original.len()); } + #[test] + fn keeps_iat_slots_when_import_size_excludes_the_terminator() { + let mut original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + let info = ImageInfo::parse(&original).unwrap(); + let directory = layout::data_directory_offset(&original, dir::IMPORT).unwrap(); + // This linker layout counts the descriptors for real modules only. + let descriptor_bytes = u32::try_from(info.imports.len() * 20).unwrap(); + write_u32(&mut original, directory + 4, descriptor_bytes).unwrap(); + let prepared = prepare(&original).unwrap(); + let iat = layout::data_directory_offset(&original, dir::IAT).unwrap(); + assert_ne!(layout::read_u32(&original, iat), Some(0)); + assert_eq!( + &prepared.bytes[iat..iat + layout::DATA_DIRECTORY_SIZE], + &[0; 8] + ); + assert_eq!(prepared.info.import_count(), info.import_count()); + for module in &prepared.info.imports { + for entry in &module.entries { + let at = info.rva_to_file_offset(entry.iat_slot_rva).unwrap() as usize; + assert_eq!(&prepared.bytes[at..at + 8], &original[at..at + 8]); + } + } + } + #[test] fn file_name_is_stable_per_build() { let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); diff --git a/crates/victory-pe/src/layout.rs b/crates/victory-pe/src/layout.rs index fd99b7f..3f8b0ce 100644 --- a/crates/victory-pe/src/layout.rs +++ b/crates/victory-pe/src/layout.rs @@ -37,6 +37,7 @@ pub mod dir { pub const BASERELOC: usize = 5; pub const LOAD_CONFIG: usize = 10; pub const BOUND_IMPORT: usize = 11; + pub const IAT: usize = 12; } /// `IMAGE_FILE_HEADER::Characteristics` flags. From 5fbea4730bd7aac700fc436c94df5490afc83916 Mon Sep 17 00:00:00 2001 From: 9hvn9yt2vk-netizen <360448330+9hvn9yt2vk-netizen@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:53:38 +0100 Subject: [PATCH 023/445] shader: look up an input channel without underflowing find_input matched each input element with `(row and channel in the element).then_some((id, channel - e.col))`. then_some evaluates its argument first, so the subtraction ran for every element, also those whose first channel is past the one asked for. In a build with overflow checks (tests, debug runs) a pixel shader reading a channel below any element that starts at z or w panicked, whichever row that element was in, and packed inputs such as a float2 in .zw are common. Release builds wrapped and threw the value away. then() computes it only when the element holds the channel. Found with a random-input harness over pixel, vertex and mesh programs with matching signatures. The new test panics without the fix. --- crates/victory-shader/src/emit/lower.rs | 4 +- crates/victory-shader/src/emit/mod.rs | 55 +++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 1f6ab71..ce63d53 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1013,8 +1013,10 @@ impl<'a> Lower<'a> { fn find_input(&self, row: u8, channel: u8) -> Option<(usize, u8)> { self.s.inputs.iter().enumerate().find_map(|(id, e)| { let r = e.row?; + // `then`, not `then_some`: the channel is only past `col` when + // the condition holds. (r == u32::from(row) && channel >= e.col && channel < e.col + e.cols) - .then_some((id, channel - e.col)) + .then(|| (id, channel - e.col)) }) } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index a283545..f936698 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -449,4 +449,59 @@ mod tests { v.validate(&mut c).unwrap(); assert_eq!(c[4..20], ours[..], "our hash differs from the validator's"); } + + /// A pixel shader reading channel z of an input whose element starts at + /// w. Looking the channel up subtracted the element's first channel + /// before checking the channel lies in it, so in a build with overflow + /// checks (tests, debug) any read below an element that starts at z or + /// w panicked, whichever row it was in (found by random-input testing). + #[test] + fn reading_a_channel_below_an_input_element_does_not_underflow() { + // v_interp_mov_f32 v3, p0, attr0.z; s_endpgm + let words = [0xC80E_0202u32, 0xBF81_0000]; + let native = super::NativeProgram { + stage: super::HwStage::Ps, + wave64: false, + vgprs: 4, + layout: vec![], + used: vec![], + io: crate::native::StageIo::Ps { + inputs: vec![crate::native::PsInput { + usage: crate::native::Usage::Generic, + row: 0, + mask: 0b1000, + attr: 0, + flat: false, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let w_only = SigElement { + name: "TEXCOORD".into(), + index: 0, + kind: 0, + comp: 9, + interp: 0, + row: Some(0), + col: 3, + cols: 1, + usage: 0, + half: false, + }; + let isg1 = super::container::signature(&[w_only], true); + let bytes = crate::dxbc::build(&[(super::FourCC::ISG1, &isg1)]); + let c = super::Container::parse(&bytes).unwrap(); + let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + // Translated or refused with a reason; it must not panic. + let _ = super::emit(&c, &native, &p, &st, &io, &res); + } } From 071487fb2d247da90d5a0942245ef0544e113947 Mon Sep 17 00:00:00 2001 From: Yaekai <21324379+Yaekai@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:59:49 +0100 Subject: [PATCH 024/445] GPU: emit null buffer SRV/UAV when descriptor names a buffer with null resource When a title creates a null buffer view (resource == 0, ViewDimension == BUFFER), buffer_bytes(0) returns None, so null_for() fell through to null_like() / null_view() (or a 2D texture UAV) and emitted a 2D texture descriptor into a slot where a shader expects a buffer. Check desc[1] == 1 (D3D12_SRV_DIMENSION_BUFFER / D3D12_UAV_DIMENSION_BUFFER) in null_for() for both View::Shader and View::Unordered so null buffer views get a matching null buffer descriptor. --- crates/victory-gpu/src/descriptor/host.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index ccc295f..f652c4a 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -735,13 +735,15 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some(); let buffer = match view { - View::Unordered(r, _, _) => is_buffer(r), + View::Unordered(r, _, desc) => is_buffer(r) || desc.is_some_and(|d| d[1] == 1), View::Placed(true, resource, _) => resource[0] == 1, // Shader views of buffers read nothing through a null buffer view: // a null 2D view where the shader expects a buffer is a mismatch // the hardware does not survive in general (GPU-based validation // reports it). - View::Shader(r, _) if is_buffer(r) => return null_buffer_view(at), + View::Shader(r, desc) if is_buffer(r) || desc.is_some_and(|d| d[1] == 1) => { + return null_buffer_view(at); + } View::Placed(false, resource, _) if resource[0] == 1 => return null_buffer_view(at), // Textures: a null view of the title's dimension (1D, arrays, 3D, // cubes), not always 2D. From 0c560918b3ae73fd0499b2d74d1df466b4f5dec7 Mon Sep 17 00:00:00 2001 From: Yaekai <21324379+Yaekai@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:59:52 +0100 Subject: [PATCH 025/445] Shaders: lower v_xnor_b32 and v_swap_b32 Add lowering for v_xnor_b32 and v_swap_b32 (seen in GTA VI world compute shaders), and record v.dst as a read in ir.rs for v_swap_b32 / v_swaprel_b32 since both operands are read before being swapped. --- crates/victory-shader/src/emit/lower.rs | 22 ++++++++++++++++++++++ crates/victory-shader/src/ir.rs | 14 ++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 1f6ab71..090d8b6 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -3597,6 +3597,22 @@ impl<'a> Lower<'a> { } Ok(()) } + "v_swap_b32" => { + let ( + Some(&Operand::Vector { reg: sreg, .. }), + Some(Operand::Vector { reg: dreg, .. }), + ) = (v.src.first(), v.dst) + else { + return Err("v_swap_b32"); + }; + let a = self.i32_of(inst.read(Reg::V(dreg)).ok_or("v_swap_b32")?)?; + let b = self.i32_of(inst.read(Reg::V(sreg)).ok_or("v_swap_b32")?)?; + self.write_placed(inst, Reg::V(dreg), b, guard); + if dreg != sreg { + self.write_placed(inst, Reg::V(sreg), a, guard); + } + Ok(()) + } "v_ffbh_u32" | "v_ffbh_i32" => { // Counted from the top bit, -1 when none (DXIL's too). let a = s(self, 0)?; @@ -4548,6 +4564,12 @@ impl<'a> Lower<'a> { }; self.s.m.bin(c, op, a, b) } + "v_xnor_b32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let x = self.s.m.bin(c, Bin::Xor, a, b); + let ones = k(self, u32::MAX); + self.s.m.bin(c, Bin::Xor, x, ones) + } "v_not_b32" => { let a = s(self, 0)?; let ones = k(self, u32::MAX); diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 2b90661..cc73a49 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -806,8 +806,18 @@ fn effects( regs(c, &mut w)?; } match name { - "v_swap_b32" => regs(&v.src[0], &mut w)?, - "v_swaprel_b32" => indexed(&v.src[0], &mut w)?, + "v_swap_b32" => { + regs(&v.src[0], &mut w)?; + if let Some(d) = &v.dst { + regs(d, &mut r)?; + } + } + "v_swaprel_b32" => { + indexed(&v.src[0], &mut w)?; + if let Some(d) = &v.dst { + indexed(d, &mut r)?; + } + } _ => {} } if name.starts_with("v_interp_") || src_indexed || dst_indexed { From 4e94c2b05ace8d499fdd91589bd9ad6338c68422 Mon Sep 17 00:00:00 2001 From: TG0000 <122870448+TG0000@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:59:56 +0100 Subject: [PATCH 026/445] xmem: write DirectStorage page destinations one view per run write_physical mapped, committed and unmapped a view for every 64 KiB page it wrote, and DirectStorage decoded each page-destination request into a zeroed buffer first, then copied it. Every unmap flushes every core's TLB, so with all the workers loading at once these writes were a serial cost per page. Pages are now looked up once and grouped into runs of consecutive slices of one section (how titles allocate them), and each run is written through one view. When a request's pages form a single run, DirectStorage inflates or unpacks straight into that view instead of a buffer; pages of several allocations still go through the buffer, written run by run. Synthetic release benchmark (16 MiB destinations, Ryzen 9 5900X): 8 threads 3.5 -> 7.8 GiB/s; one thread, buffered then copied 0.96 GiB/s vs in place 2.1 GiB/s. Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/dstorage.rs | 79 ++++++- crates/victory-hle/src/modules/xmem.rs | 237 +++++++++++++++++---- 2 files changed, 274 insertions(+), 42 deletions(-) diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 302dcbe..c94146f 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -941,7 +941,8 @@ fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { /// Runs `fill` on the destination's first `len` bytes; `fill` returns how /// many it produced. GPU-visible destinations are host memory like the /// rest (GPU address = CPU address), so an address is written in place; -/// physical pages go through a buffer. +/// physical pages are too when they are consecutive pages of one +/// allocation, and otherwise go through a buffer. fn into_destination( request: &Request, len: usize, @@ -956,12 +957,22 @@ fn into_destination( let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::(), len) }; return fill(out).map(drop); } + let offset = (request.page_offset & 0xffff) as usize; + // SAFETY: the title passes a page number per 64 KiB of destination, + // which holds at least `len` bytes from `offset`. + let pages = unsafe { + std::slice::from_raw_parts( + request.destination.cast::(), + (offset + len).div_ceil(PAGE), + ) + }; + // Consecutive pages of one allocation (the usual case): written in + // place through one view. + if let Some(mut window) = super::xmem::page_window(pages, offset, len) { + return fill(window.bytes()).map(drop); + } let mut data = vec![0; len]; let n = fill(&mut data)?; - let offset = (request.page_offset & 0xffff) as usize; - let pages = (offset + n).div_ceil(PAGE); - // SAFETY: the title passes a page number per 64 KiB of destination. - let pages = unsafe { std::slice::from_raw_parts(request.destination.cast::(), pages) }; if super::xmem::write_physical(pages, offset, &data[..n]) { Ok(()) } else { @@ -1473,4 +1484,62 @@ mod tests { let seen = unsafe { std::slice::from_raw_parts(mapped.cast::().add(PAGE - 40), 100) }; assert_eq!(seen, plain); } + #[test] + fn zlib_into_pages_in_place_and_across_allocations() { + use crate::modules::xmem; + let allocate = |n: usize| { + let (mut pages, mut given) = (vec![0usize; n], n); + assert_eq!( + xmem::XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()), + 1 + ); + pages + }; + let (a, b) = (allocate(3), allocate(1)); + let plain = pattern(2 * PAGE + 100); + let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + // One allocation's pages in order (one window), then pages of two + // (through a buffer), both from 50 bytes into the first. + let mut destinations = [a.clone(), vec![a[0], a[1], b[0]]]; + let (queue, array) = (new_queue(1), status_array(1)); + for pages in &mut destinations { + let mut r = request( + ZLIB | PAGE_DESTINATION | MEMORY_SOURCE, + pages.as_mut_ptr().cast(), + plain.len(), + packed.as_ptr().cast(), + 0, + packed.len(), + ); + r.page_offset = 50; + enqueue(queue, &r); + } + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + for pages in &destinations { + let mapped = xmem::XMemVirtualAlloc( + std::ptr::null_mut(), + 3 * PAGE, + 0x2000 | 0x2040_0000, // reserve, 64 KiB pages + 0, + 0x04, + ); + assert!(!mapped.is_null()); + assert_eq!( + xmem::XMemMapPhysicalPages(mapped, 3, pages.as_ptr()), + mapped + ); + // SAFETY: all three pages are mapped read-write. + let seen = unsafe { std::slice::from_raw_parts(mapped.cast::(), 3 * PAGE) }; + assert!(seen[..50].iter().all(|&b| b == 0)); + assert_eq!(seen[50..50 + plain.len()], plain); + assert_eq!( + xmem::XMemMapPhysicalPages(mapped, 3, std::ptr::null()), + mapped + ); + } + assert_eq!(xmem::XMemFreePhysicalPages(3, a.as_ptr()), 1); + assert_eq!(xmem::XMemFreePhysicalPages(1, b.as_ptr()), 1); + } } diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index bcd3222..15f8368 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -441,53 +441,130 @@ pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> B 1 } -/// Copies `data` into physical pages, from `offset` bytes into the first, -/// whether or not they are mapped anywhere (DirectStorage destinations). -/// False if a page is unknown or the host fails. -pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> bool { - use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile}; - let mut done = 0; - while done < data.len() { - let (page, within) = ((offset + done) / PAGE, (offset + done) % PAGE); - let Some(slice) = pages - .get(page) - .and_then(|p| physical().pages.get(p).cloned()) - else { - return false; - }; - let at = (slice.index * PAGE) as u64; - // SAFETY: one page of a section we own, mapped for the copy only. - let view = unsafe { +/// A view of our own on consecutive slices of one section, committed and +/// writable, unmapped when dropped. +struct View { + at: MEMORY_MAPPED_VIEW_ADDRESS, + len: usize, +} + +impl View { + /// Maps `n` slices from `slice` on. + fn map(slice: &Slice, n: usize) -> Option { + use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile}; + let (offset, len) = ((slice.index * PAGE) as u64, n * PAGE); + // SAFETY: slices of a section we own; the view is ours until dropped. + let at = unsafe { MapViewOfFile( slice.section.0, FILE_MAP_WRITE, - (at >> 32) as u32, - at as u32, - PAGE, + (offset >> 32) as u32, + offset as u32, + len, ) }; - if view.Value.is_null() { + if at.Value.is_null() { + return None; + } + let view = View { at, len }; + commit(at.Value as usize, len).then_some(view) + } + + fn bytes(&mut self) -> &mut [u8] { + // SAFETY: the view holds `len` committed read-write bytes, ours + // alone while `self` lives (other views of the slices only alias + // them, as the console's do). + unsafe { std::slice::from_raw_parts_mut(self.at.Value.cast(), self.len) } + } +} + +impl Drop for View { + fn drop(&mut self) { + use windows_sys::Win32::System::Memory::UnmapViewOfFile; + // SAFETY: our view. + unsafe { UnmapViewOfFile(self.at) }; + } +} + +/// The pages behind bytes `[offset, offset + len)` of `pages` (64 KiB +/// each), as runs of consecutive slices of one section: each run's first +/// slice and its length in pages. One look at the page table, which the +/// title's own mapping calls share with every DirectStorage worker. `None` +/// if a page is unknown or `pages` ends early. +fn runs(pages: &[usize], offset: usize, len: usize) -> Option> { + let end = offset.checked_add(len)?; + let pages = pages.get(offset / PAGE..end.div_ceil(PAGE))?; + let physical = physical(); + let mut runs: Vec<(Slice, usize)> = Vec::new(); + for page in pages { + let slice = physical.pages.get(page)?; + match runs.last_mut() { + Some((first, n)) + if Arc::ptr_eq(&first.section, &slice.section) + && slice.index == first.index + *n => + { + *n += 1; + } + _ => runs.push((slice.clone(), 1)), + } + } + Some(runs) +} + +/// Copies `data` into physical pages, from `offset` bytes into the first, +/// whether or not they are mapped anywhere (DirectStorage destinations). +/// One view per run of consecutive pages, not one per page: each view +/// costs a map, a commit and an unmap (which flushes every core's TLB). +/// False if a page is unknown or the host fails. +pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> bool { + let Some(runs) = runs(pages, offset, data.len()) else { + return false; + }; + let (mut within, mut done) = (offset % PAGE, 0); + for (slice, n) in &runs { + let Some(mut view) = View::map(slice, *n) else { return false; - } - if !commit(view.Value as usize, PAGE) { - // SAFETY: our view. - unsafe { UnmapViewOfFile(view) }; - return false; - } - let n = (PAGE - within).min(data.len() - done); - // SAFETY: the view holds `PAGE` bytes; `within + n <= PAGE`. - unsafe { - view.Value - .cast::() - .add(within) - .copy_from_nonoverlapping(data[done..].as_ptr(), n); - UnmapViewOfFile(view); - } - done += n; + }; + let k = (n * PAGE - within).min(data.len() - done); + view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]); + (within, done) = (0, done + k); } true } +/// Bytes `[offset, offset + len)` of physical pages, writable in place +/// until dropped: DirectStorage decodes into it instead of a buffer it +/// would then copy. +pub(crate) struct PageWindow { + view: View, + within: usize, + len: usize, +} + +impl PageWindow { + pub(crate) fn bytes(&mut self) -> &mut [u8] { + let (within, len) = (self.within, self.len); + &mut self.view.bytes()[within..within + len] + } +} + +/// A window on bytes `[offset, offset + len)` of `pages` when they are +/// consecutive pages of one allocation (how titles usually hand them out); +/// `None` otherwise (pages of several allocations, out of order, or +/// unknown, or a host failure), which `write_physical` then handles or +/// reports. +pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option { + let runs = runs(pages, offset, len)?; + let [(slice, n)] = runs.as_slice() else { + return None; + }; + Some(PageWindow { + view: View::map(slice, *n)?, + within: offset % PAGE, + len, + }) +} + /// Maps `n` pages at `address`, in place of what is mapped there; null /// `pages` unmaps. Returns `address`, or null if a page or the host fails. pub extern "system" fn XMemMapPhysicalPages( @@ -953,4 +1030,90 @@ mod tests { assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); assert_eq!(XMemIsToolsMemAvailable(), 0); } + /// `n` pages of one new allocation. + fn allocate(n: usize) -> Vec { + let (mut pages, mut given) = (vec![0; n], n); + assert_eq!( + XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()), + 1 + ); + assert_eq!(given, n); + pages + } + + /// The bytes of one page, through a view of our own. + fn page_bytes(page: usize) -> Vec { + let slice = physical().pages.get(&page).cloned().expect("known page"); + View::map(&slice, 1).expect("mapped").bytes().to_vec() + } + + #[test] + fn runs_group_consecutive_pages_of_one_allocation() { + let (a, b) = (allocate(3), allocate(1)); + let lengths = |pages: &[usize], offset, len| { + runs(pages, offset, len).map(|r| r.iter().map(|&(_, n)| n).collect::>()) + }; + assert_eq!(lengths(&a, 0, 3 * PAGE), Some(vec![3])); + // Only the pages the bytes reach. + assert_eq!(lengths(&a, PAGE + 5, 10), Some(vec![1])); + assert_eq!(lengths(&a, PAGE - 1, 2), Some(vec![2])); + assert_eq!(lengths(&a, 0, 0), Some(vec![])); + // Out of order, or across allocations: one run each. + assert_eq!( + lengths(&[a[0], a[2], a[1]], 0, 3 * PAGE), + Some(vec![1, 1, 1]) + ); + assert_eq!(lengths(&[a[1], a[2], b[0]], 0, 3 * PAGE), Some(vec![2, 1])); + // A slice that follows on in another section starts a run. + assert_eq!(lengths(&[b[0], a[1]], 0, 2 * PAGE), Some(vec![1, 1])); + // Too few pages for the bytes, or an unknown one. + assert_eq!(lengths(&a, 0, 3 * PAGE + 1), None); + assert_eq!(lengths(&[a[0], 0x10], 0, 2 * PAGE), None); + assert_eq!(lengths(&a, usize::MAX, 2), None); + assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); + } + + #[test] + fn writes_cross_runs_and_allocations() { + let (a, b) = (allocate(2), allocate(1)); + let pages = [a[0], a[1], b[0]]; + let data: Vec = (0..2 * PAGE + 64).map(|i| (i * 7 % 251) as u8).collect(); + let offset = PAGE - 32; + // Past the third page: the second run is too short. + assert!(!write_physical(&pages, offset, &data)); + assert!(write_physical(&pages, offset, &data[..2 * PAGE])); + let seen: Vec = pages.iter().flat_map(|&p| page_bytes(p)).collect(); + assert!(seen[..offset].iter().all(|&b| b == 0), "before the offset"); + assert_eq!(seen[offset..offset + 2 * PAGE], data[..2 * PAGE]); + assert!(seen[offset + 2 * PAGE..].iter().all(|&b| b == 0), "after"); + assert!( + !write_physical(&[a[0], 0x10], 0, &data[..PAGE + 1]), + "unknown page" + ); + assert_eq!(XMemFreePhysicalPages(2, a.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); + } + + #[test] + fn page_windows_cover_one_run_in_place() { + let (a, b) = (allocate(3), allocate(1)); + let mut window = page_window(&a, PAGE + 3, PAGE).expect("one run"); + assert_eq!(window.bytes().len(), PAGE); + window.bytes().fill(0x5a); + drop(window); + let (second, third) = (page_bytes(a[1]), page_bytes(a[2])); + assert!(second[..3].iter().all(|&b| b == 0)); + assert!(second[3..].iter().all(|&b| b == 0x5a)); + assert!(third[..3].iter().all(|&b| b == 0x5a)); + assert!(third[3..].iter().all(|&b| b == 0)); + // Several runs, or an unknown page: no window. + assert!(page_window(&[a[0], b[0]], 0, PAGE + 1).is_none()); + assert!(page_window(&[a[1], a[0]], 0, PAGE + 1).is_none()); + assert!(page_window(&[0x10], 0, 1).is_none()); + // One page of several is still one run. + assert!(page_window(&[a[0], b[0]], 0, PAGE).is_some()); + assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); + } } From fc807b6e76afe1d6926ac2ea1124866a545b3c3e Mon Sep 17 00:00:00 2001 From: ifBars Date: Mon, 23 Nov 2026 15:52:26 -0800 Subject: [PATCH 027/445] Reuse texture row spans when converting Xbox pixel layouts --- crates/victory-formats/src/texture.rs | 97 +++++++++++++-------------- 1 file changed, 46 insertions(+), 51 deletions(-) diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 73ef98d..c99fc87 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -594,11 +594,8 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - let n = self.desc.element_bytes as usize; - self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, count| { - for (i, len) in runs(t, count, n) { - linear[l + i * n..][..len].copy_from_slice(&tiled[t[i] as usize..][..len]); - } + self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| { + linear[l..][..len].copy_from_slice(&tiled[t..][..len]); }) } @@ -612,16 +609,12 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - let n = self.desc.element_bytes as usize; - self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, count| { - for (i, len) in runs(t, count, n) { - tiled[t[i] as usize..][..len].copy_from_slice(&linear[l + i * n..][..len]); - } + self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| { + tiled[t..][..len].copy_from_slice(&linear[l..][..len]); }) } - /// Calls `row(tiled offsets, linear offset, elements)` for each row of a - /// subresource, after checking both buffers are large enough. + /// Visits contiguous runs as (tiled byte offset, linear byte offset, length). #[allow(clippy::too_many_arguments)] fn walk( &self, @@ -631,7 +624,7 @@ impl Layout { linear_len: usize, row_pitch: usize, depth_pitch: usize, - mut row: impl FnMut(&[u64], usize, usize), + mut copy: impl FnMut(usize, usize, usize), ) -> Result<(), Error> { let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; let depth = m.depth; @@ -656,53 +649,43 @@ impl Layout { return Err(Error::TooSmall); } let linear = self.desc.swizzle == Swizzle::LINEAR; - let columns: Vec = (0..m.width) - .map(|x| { - if linear { - u64::from(x) * n as u64 - } else { - self.column(m, x) + // The row and depth contribute one common base to every column, so + // the same contiguous runs repeat on every row, including mip tails. + let mut runs = Vec::new(); + if !linear { + let mut first_linear = 0; + let mut first_tiled = self.column(m, 0) as usize; + for x in 1..m.width { + let offset = self.column(m, x) as usize; + let at = x as usize * n; + if offset != first_tiled + (at - first_linear) { + runs.push((first_tiled, first_linear, at - first_linear)); + first_tiled = offset; + first_linear = at; } - }) - .collect(); - let mut offsets = vec![0u64; m.width as usize]; + } + runs.push((first_tiled, first_linear, bytes - first_linear)); + } for z in 0..depth { let (s, inner) = self.split(first + z); let base = u64::from(s) * self.slice_size + m.offset; for y in 0..m.height { - let start = if linear { - base + u64::from(y) * u64::from(m.pitch) * n as u64 + let linear_row = z as usize * depth_pitch + y as usize * row_pitch; + if linear { + let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64; + copy(tiled_row as usize, linear_row, bytes); } else { - base + self.row(m, y, inner) - }; - for (o, c) in offsets.iter_mut().zip(&columns) { - *o = start + c; + let tiled_row = (base + self.row(m, y, inner)) as usize; + for &(tiled, linear, len) in &runs { + copy(tiled_row + tiled, linear_row + linear, len); + } } - row(&offsets, z as usize * depth_pitch + y as usize * row_pitch, m.width as usize); } } Ok(()) } } -/// The first `count` element offsets as runs of contiguous memory: (first -/// element, bytes), so a linear row (or a swizzle's contiguous columns) is -/// copied at once rather than element by element. -fn runs(t: &[u64], count: usize, n: usize) -> impl Iterator + '_ { - let mut i = 0; - std::iter::from_fn(move || { - if i >= count { - return None; - } - let start = i; - i += 1; - while i < count && t[i] == t[i - 1] + n as u64 { - i += 1; - } - Some((start, (i - start) * n)) - }) -} - /// What a DXGI format stores per element: bytes, texels per element side /// (4 for block compression), and whether its stencil is a second plane /// (the GPU keeps depth and stencil apart). @@ -900,6 +883,11 @@ mod tests { desc(33, 17, 6, 1, Swizzle::SW_4KB_D), desc(40, 9, 3, 2, Swizzle::SW_64KB_S), desc(30, 20, 5, 4, Swizzle::LINEAR), + desc(83, 31, 6, 1, Swizzle::SW_256B_S), + Desc { + block: 4, + ..desc(109, 71, 6, 16, Swizzle::SW_256B_D) + }, Desc { depth: 3, ..desc(70, 70, 4, 16, Swizzle::SW_4KB_S) @@ -919,25 +907,32 @@ mod tests { for slice in 0..slices { for mip in 0..d.mips { let m = l.mips[mip as usize]; - let row = m.width as usize * n; - let plane = row * m.height as usize; + let active = m.width as usize * n; + let row = active + 13; + let plane = row * m.height as usize + 11; let linear: Vec = (0..plane * m.depth as usize) .map(|i| (i * 7 + mip as usize * 13 + slice as usize) as u8) .collect(); l.tile(&mut tiled, mip, slice, &linear, row, plane).unwrap(); - let mut back = vec![0u8; linear.len()]; + let mut back = vec![0xcc; linear.len()]; l.detile(&tiled, mip, slice, &mut back, row, plane).unwrap(); - assert_eq!(back, linear, "{d:?} mip {mip}"); for z in 0..m.depth { + let base = z as usize * plane; for y in 0..m.height { + let start = base + y as usize * row; + assert_eq!(back[start..start + active], linear[start..start + active]); + assert!(back[start + active..start + row].iter().all(|&b| b == 0xcc)); for x in 0..m.width { let at = l.offset(mip, x, y, slice + z).unwrap() as usize; + let source = start + x as usize * n; + assert_eq!(tiled[at..at + n], linear[source..source + n]); assert!(at + n <= seen.len(), "{d:?} mip {mip} outside"); assert!(at.is_multiple_of(n)); assert!(!seen[at], "{d:?} mip {mip} ({x},{y},{z}) twice"); seen[at] = true; } } + assert!(back[base + plane - 11..base + plane].iter().all(|&b| b == 0xcc)); } } } From 35b054ec038c11bc8a0de66b1eee764b1ad4f101 Mon Sep 17 00:00:00 2001 From: Marvis Date: Tue, 24 Nov 2026 01:02:03 +0100 Subject: [PATCH 028/445] GPU: pipelines off the render thread and cached; indirect execution on With indirect execution the world's first frame asked for over 1,200 pipelines at once and took more than 30 s, so the title's own GPU watchdog ended the run. Host pipelines are now made by worker threads: a first use waits at most 0.5 s per title frame, and that pipeline's draws are dropped until it is ready. The world presents frames again, and indirect execution is the default (the switch is gone). Pipelines are cached across runs: - every host pipeline goes into a pipeline library saved under the cache folder (named by a hash of the translated code, our root signature and the state; a blob the device rejects starts an empty library); - the pipelines drawn with are remembered and started during loading on the next run. One cold and one warm run: the last pipeline was ready 38 s after the world's first frame cold, 1.4 s warm; the first world frame took 3.2 s cold, 0.37 s warm. Also: - Copy-backs of shader-written ranges return only the bytes the GPU changed; they used to overwrite what the title's CPU wrote meanwhile, which crashed the title. - Indirect dispatch records are bounded (group counts were not), and the console's single-dispatch argument type runs as a dispatch. - Per-shader counts of dropped draws in the diagnostics log; a switch that submits and times each list alone. Not working yet: the world shows no geometry, and runs end on a GPU page fault after at most about 55 s. Co-Authored-By: Claude Fable 5.2 --- README.md | 6 +- crates/victory-gpu/src/descriptor/host.rs | 3 + crates/victory-gpu/src/draw.rs | 28 ++- crates/victory-gpu/src/host.rs | 185 ++++++++++++-- crates/victory-gpu/src/indirect.rs | 22 +- crates/victory-gpu/src/list.rs | 37 +-- crates/victory-gpu/src/pipeline.rs | 87 +++++-- crates/victory-gpu/src/pipeline/host.rs | 90 ++++++- crates/victory-gpu/src/pipeline/library.rs | 254 ++++++++++++++++++++ crates/victory-gpu/src/pipeline/make.rs | 238 ++++++++++++++++++ crates/victory-gpu/src/shadow.rs | 158 ++++++++++-- crates/victory-hle/src/modules/d3d12x.rs | 8 +- crates/victory-hle/src/modules/lifecycle.rs | 3 + 13 files changed, 1018 insertions(+), 101 deletions(-) create mode 100644 crates/victory-gpu/src/pipeline/library.rs create mode 100644 crates/victory-gpu/src/pipeline/make.rs diff --git a/README.md b/README.md index 3c0b5a9..81eedb3 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ loads the world, where rendering fails. | Intro video with sound | works | | Start screen, profile and saves | works | | Loading into the world (about 50 s) | works | -| The world (first mission's intro) | reached and runs (two minutes without a GPU failure); the picture is black, 1.5-3 s per frame | +| The world (first mission's intro) | reached and runs with indirect draws; its title card renders, the scene after it is still dark; 0.5-1.8 s per frame | Tested on one machine: Windows 11, AMD RX 6700 XT. @@ -39,7 +39,7 @@ What each part does today and what it still needs: | Input | XInput pads, keyboard, keyboard stand-in pad | Trigger rumble | | Audio | Menu, video and loading sound; XMA voices and Opus streams decode | Reverb is silent; Opus results unverified against the title | | GPU: menus | Draws, compute and presentation on host D3D12; only changed title memory is copied | Frame pacing drifts on one screen in release builds | -| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped) are in | Frames are black (most geometry is drawn indirectly; untranslated shaders drop the rest); frames take seconds; real queries, depth bounds, HDR and scaling are missing | +| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped), pipelines made by worker threads and kept on disk | Most of the scene is still missing (untranslated shaders drop draws); frames take seconds; real queries, depth bounds, HDR and scaling are missing | | Shaders | Console GPU code recompiled to DXIL at first use, cached on disk. Menus: all. World: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539 | 64-bit image atomics, merged geometry stages, the ray-tracing builder's shaders; some compute programs need a GPU with 64-lane waves | | Textures | Console tiled layouts and detiling for the modes the title uses | Render-target metadata planes | | Series S mode | Runs through the menus to the loading screen | The world, as above | @@ -114,9 +114,9 @@ cargo build --profile diag -p victory --features diagnostics # target\diag\vic | `VICTORY_CAPTURE=` | saves presented frames (powers of two, or `VICTORY_CAPTURE_FRAMES=`) | | `VICTORY_DUMP_TARGETS=1` | with the two above, saves every render target of those frames | | `VICTORY_D3D12_DEBUG=1` | host debug layer | -| `VICTORY_INDIRECT=1` | runs the title's indirect draws and dispatches (off: the world's first frame stalls with it) | | `VICTORY_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) | | `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | +| `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands | | `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | | `VICTORY_AUDIO_CAPTURE=` | records what the title plays (our process only) | | `VICTORY_XMA_DUMP=` | saves the first 32 XMA voices' context and input | diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index ccc295f..46be86e 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -827,6 +827,9 @@ fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) { } /// A view that reads zeros, for slots whose view the host cannot make. +/// shortcut: slots with no view at all (kind unknown) get this null 2D +/// view; null buffer views there did not stop the world's low-address +/// page faults (2026-11-24, run w10), so they are not the cause. fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index f624f1b..af6ad04 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -115,7 +115,8 @@ static DROPPED: AtomicU64 = AtomicU64::new(0); /// Marks the last traced draw as not run on the host. #[cfg(feature = "diagnostics")] -fn dropped() { +fn dropped(pipeline: usize) { + crate::pipeline::note_drop(pipeline as This); if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() { last.push_str(" DROPPED"); } @@ -494,6 +495,8 @@ impl State { "a dispatch without a host pipeline dropped" ); DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::pipeline::note_drop(self.pipeline as This); return; }; if !p.compute { @@ -565,7 +568,7 @@ impl State { if !ran { DROPPED.fetch_add(1, Ordering::Relaxed); #[cfg(feature = "diagnostics")] - dropped(); + dropped(self.pipeline); } } @@ -818,7 +821,7 @@ impl State { if !ran { DROPPED.fetch_add(1, Ordering::Relaxed); #[cfg(feature = "diagnostics")] - dropped(); + dropped(self.pipeline); } } @@ -905,7 +908,7 @@ impl State { if !ran { DROPPED.fetch_add(1, Ordering::Relaxed); #[cfg(feature = "diagnostics")] - dropped(); + dropped(self.pipeline); } } } @@ -928,14 +931,22 @@ impl State { const INDEXED: u32 = 1; const DISPATCH: u32 = 2; const MESH: u32 = 10; + #[cfg(feature = "diagnostics")] + let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}")); + #[cfg(not(feature = "diagnostics"))] + let why = |_: &str| {}; let len = u64::from(stride) * u64::from(max.max(1)); let Some(args) = crate::shadow::find(arguments, len) else { + why("arguments outside title buffers"); return false; }; let counter = match count { Some(at) => match crate::shadow::find(at, 4) { Some(s) => Some((s, at)), - None => return false, + None => { + why("count outside title buffers"); + return false; + } }, None => None, }; @@ -943,6 +954,7 @@ impl State { .then(|| host_signature(kind, stride)) .flatten() else { + why("no host signature"); return false; }; args.refresh(list, arguments, len); @@ -951,6 +963,7 @@ impl State { } // Bounded first: the clamp binds a compute pipeline of its own. if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) { + why("not bounded (no clamp, or arguments not 4-byte aligned)"); return false; } self.host_pipeline = 0; @@ -969,6 +982,11 @@ impl State { }; if !ran { crate::indirect::done(list, &args.buffer); + #[cfg(feature = "diagnostics")] + match crate::pipeline::host_pipeline(self.pipeline as This) { + None => crate::pipeline::note_drop(self.pipeline as This), + Some(p) => why(&format!("prepare failed (compute {}, mesh {})", p.compute, p.mesh)), + } return false; } #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 51c7b47..d89159e 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -254,8 +254,16 @@ pub(crate) struct HostList { /// data without marker texts), with the host GPU range a copy reads. #[cfg(feature = "diagnostics")] notes: Mutex>, + /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command + /// and at the end, and where they are read back. + #[cfg(feature = "diagnostics")] + stamps: OnceLock>, } +/// Timestamps per list (diagnostics); commands past them are not timed. +#[cfg(feature = "diagnostics")] +const STAMPS: u32 = 4096; + /// A marker's text and the host range its command reads (diagnostics). #[cfg(feature = "diagnostics")] type Note = (String, Option<(u64, u64)>); @@ -274,6 +282,15 @@ pub(crate) fn dred_on() -> bool { }) } +/// Whether each list of a submission runs and is timed on its own, slow +/// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics +/// builds; the commands are noted with `VICTORY_D3D12_DRED` on). +#[cfg(feature = "diagnostics")] +fn timing() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some()) +} + /// Names a host object for the device-removed report, which names the /// allocations a page fault hit (only with device-removed data on). pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) { @@ -412,42 +429,77 @@ impl Host { budget: OnceLock::new(), #[cfg(feature = "diagnostics")] notes: Mutex::default(), + #[cfg(feature = "diagnostics")] + stamps: OnceLock::new(), }) } } /// Runs closed lists and waits for them. pub(crate) fn execute(&self, runs: &[&HostList]) { + // One submission at a time from preparation to copy-back: snapshots + // and the ranges shaders write are per host copy, not per submission. + let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Submissions, 1); let mut lists: Vec> = Vec::with_capacity(2 * runs.len()); + // Where each run's lists start in `lists`. + let mut firsts = Vec::with_capacity(runs.len()); let mut batch = Batch::default(); for list in runs { list.run_deferred(&mut batch); + firsts.push(lists.len()); if let Some(prelude) = list.prelude() { lists.push(Some(prelude)); } lists.push(list.list.cast().ok()); } batch.flush(); - let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); - *submitted += 1; let prepared = std::time::Instant::now(); - // SAFETY: closed lists; the fence and event are ours. - unsafe { - self.queue.ExecuteCommandLists(&lists); - let waited = self - .queue - .Signal(&self.fence, *submitted) - .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)); - match waited { - Ok(()) => { - WaitForSingleObject(self.event, INFINITE); + // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`). + #[cfg(feature = "diagnostics")] + let groups: Vec<&[Option]> = if timing() { + firsts + .iter() + .zip(firsts.iter().skip(1).chain([&lists.len()])) + .map(|(&a, &b)| &lists[a..b]) + .collect() + } else { + vec![&lists[..]] + }; + #[cfg(not(feature = "diagnostics"))] + let groups = [&lists[..]]; + for (i, group) in groups.iter().enumerate() { + *submitted += 1; + let started = std::time::Instant::now(); + // SAFETY: closed lists; the fence and event are ours. + unsafe { + self.queue.ExecuteCommandLists(group); + let waited = self + .queue + .Signal(&self.fence, *submitted) + .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)); + match waited { + Ok(()) => { + WaitForSingleObject(self.event, INFINITE); + } + Err(e) => tracing::warn!(error = %e, "host submission not waited for"), } - Err(e) => tracing::warn!(error = %e, "host submission not waited for"), } + #[cfg(feature = "diagnostics")] + if groups.len() > 1 && started.elapsed() > std::time::Duration::from_millis(50) { + // SAFETY: a plain query. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); + let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len(); + tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list"); + for (ms, op) in runs[i].slowest(frequency, 6) { + tracing::warn!("slow list command, {ms:.1} ms: {op}"); + } + } + let _ = (i, started); } + let _ = &firsts; let gpu = prepared.elapsed(); SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed); SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); @@ -677,7 +729,92 @@ impl Host { } impl HostList { + /// The timestamp heap and its read-back buffer (diagnostics, timing on). + #[cfg(feature = "diagnostics")] + fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> { + if !timing() { + return None; + } + self.stamps + .get_or_init(|| { + let device = &host()?.device; + let mut heap: Option = None; + let mut back: Option = None; + let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: u64::from(STAMPS) * 8, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + // SAFETY: plain object creation. + unsafe { + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 }, + &mut heap, + ) + .ok()?; + device + .CreateCommittedResource( + &readback, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut back, + ) + .ok()?; + } + Some((heap?, back?)) + }) + .as_ref() + } + + /// The noted commands that took longest on the GPU, longest first, as + /// (milliseconds, text) (diagnostics, timing on, after the list ran). + #[cfg(feature = "diagnostics")] + fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> { + let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner()); + let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else { + return Vec::new(); + }; + let mut data = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 }; + // SAFETY: a read-back buffer the finished list resolved into. + let stamps: Vec = unsafe { + if back.Map(0, Some(&range), Some(&mut data)).is_err() { + return Vec::new(); + } + let s = std::slice::from_raw_parts(data.cast::(), count + 1).to_vec(); + back.Unmap(0, None); + s + }; + let mut times: Vec<(f64, String)> = (0..count) + .map(|i| { + let ticks = stamps[i + 1].saturating_sub(stamps[i]); + (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect()) + }) + .collect(); + times.sort_by(|a, b| b.0.total_cmp(&a.0)); + times.truncate(n); + times + } + pub(crate) fn close(&self) { + #[cfg(feature = "diagnostics")] + if let Some((heap, back)) = self.stamps() { + let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); + // SAFETY: an open list, our heap and read-back buffer. + unsafe { + self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count); + self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0); + } + } // SAFETY: our list. if let Err(e) = unsafe { self.list.Close() } { fail(format_args!( @@ -790,6 +927,11 @@ impl HostList { #[cfg(feature = "diagnostics")] fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) { if dred_on() { + let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32; + if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 { + // SAFETY: an open list and our query heap. + unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) }; + } let what = what(); let text: Vec = what.encode_utf16().chain([0]).collect(); const UNICODE: u32 = 0; @@ -1280,16 +1422,29 @@ impl Meter { }); let dropped = crate::draw::take_dropped() as f64 / frames; let indirect = crate::list::take_indirect() as f64 / frames; + // Over the same frames as the counts above. + #[cfg(feature = "diagnostics")] + let drops = crate::pipeline::take_drops(); if self.logged.elapsed() >= std::time::Duration::from_secs(5) { self.logged = std::time::Instant::now(); tracing::info!( "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \ {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \ GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \ - dropped {dropped:.0} without a host pipeline and {indirect:.0} indirect" + dropped {dropped:.0} without a host pipeline ({making} being made) and \ + {indirect:.0} indirect", + making = crate::pipeline::making() ); #[cfg(feature = "diagnostics")] - crate::copystat::log(frames); + { + crate::copystat::log(frames); + for (why, n) in drops.iter().take(40) { + tracing::info!( + "dropped {:.1}/frame without a host pipeline: {why}", + *n as f64 / frames + ); + } + } } if self.caption.is_none() { // The window's own text, read without a message. diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 097011b..c0236d8 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -6,13 +6,15 @@ //! just before its execution, by a compute shader of ours (HLSL compiled by //! the system's compiler; a 5.1 shader with its root signature inside). //! -//! Each list also has a budget (2^28 vertex instances or threads, mesh -//! groups counted as 128): records past it run empty, so a list of -//! thousands of garbage records cannot run for seconds either. +//! Each list also has a budget (2^27 vertex instances or threads, groups +//! counted as 64 threads, mesh groups as 128): records past it run empty, +//! so a list of thousands of garbage records cannot run for seconds +//! either. //! //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535 -//! groups per dimension, one-dimensional mesh dispatches, the budget) cut -//! legitimate work beyond them; raise them if the title needs more. +//! groups per dimension and 2^20 per dispatch, one-dimensional mesh +//! dispatches, the budget) cut legitimate work beyond them; raise them if +//! the title needs more. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Direct3D::ID3DBlob; @@ -28,7 +30,9 @@ RWByteAddressBuffer args : register(u0); // The list's work so far (vertex instances, threads): past the budget, // records run empty. RWByteAddressBuffer budget : register(u1); -static const uint BUDGET = 1u << 28; +static const uint BUDGET = 1u << 27; +// Groups of one dispatch; more run empty. +static const uint GROUPS = 1u << 20; [RootSignature(RS)] [numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { @@ -43,7 +47,11 @@ void main(uint3 id : SV_DispatchThreadID) { args.Store2(at, uint2(count, instances)); } else if (kind == 2) { uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535)); - cost = min(g.x * g.y * g.z, 1u << 20) * 64; + // x * y fits 32 bits; the whole count may not. + if (g.z != 0 && g.x * g.y > GROUPS / g.z) { + g = uint3(0, 0, 0); + } + cost = g.x * g.y * g.z * 64; args.Store3(at, g); } else { // Mesh dispatches: the console's are one-dimensional. diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 6fc2fb7..78d6d73 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1129,14 +1129,14 @@ extern "system" fn draw(_: This) { } /// `ExecuteIndirect(signature, max count, arguments, offset, count buffer, -/// offset)`. Grand Theft Auto VI's signatures (2026-11-23) hold one -/// argument each: draw (stride 16), indexed draw (20), dispatch (12), mesh -/// dispatch (12), and a console type 105 (stride 12, fields 0, 60000, 0, -/// over its 174 MB buffer) whose meaning is unknown. Those of PC types run +/// offset)`. Grand Theft Auto VI's signatures (title+0x2479466, 2026-11-24) +/// hold one argument each: draw (stride 16), indexed draw (20), dispatch +/// (12), mesh dispatch (12), and the console's single-pass dispatch, type +/// 105 (stride 12: the three group counts; its flags live in the +/// signature, the title passes none), run as a plain dispatch. They run /// through the host's indirect execution (`State::execute_indirect`). -/// shortcut: type 105 and signatures that change root arguments are -/// dropped (logged once per signature); decode 105 when its draws are -/// missed. +/// shortcut: signatures that change root arguments are dropped (logged +/// once per signature). extern "system" fn execute_indirect( this: This, signature: This, @@ -1153,22 +1153,23 @@ extern "system" fn execute_indirect( let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset); let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset); let mut ran = false; - // shortcut: off unless `VICTORY_INDIRECT` is set (diagnostics builds): - // with it the world presented no frame for 30 s and the title's own - // GPU watchdog ended it (2026-11-24, cause not found); without it the - // world runs, with most geometry missing. - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - let on = *ON.get_or_init(|| { - cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_INDIRECT").is_some() - }); #[cfg(windows)] - if on - && let ([[kind, ..]], Some(address)) = (args, address) + if let ([[kind, ..]], Some(address)) = (args, address) && (count.is_null() || counter.is_some()) { + const DISPATCH: u32 = 2; + const DISPATCH_SINGLE: u32 = 105; + let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind }; with_state(this, |list, s| { - ran = s.execute_indirect(list, (*kind, stride, max), address, counter); + ran = s.execute_indirect(list, (kind, stride, max), address, counter); }); + } else { + #[cfg(all(windows, feature = "diagnostics"))] + crate::pipeline::note_why(format!( + "indirect signature {args:?}: arguments in a buffer {}, count in a buffer {}", + address.is_some(), + count.is_null() || counter.is_some() + )); } if ran { return; diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index ad450cc..f351c9a 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -159,11 +159,10 @@ struct Pipeline { shaders: Vec>, /// Whether a list has bound it yet (its shaders are logged then). bound: std::sync::atomic::AtomicBool, - /// The rest of a stream's graphics state, for the host pipeline. + /// What its host pipeline is made from, and the host pipeline once made + /// (by a worker: the title may release the pipeline meanwhile). #[cfg(windows)] - graphics: Option>, - #[cfg(windows)] - host: OnceLock>, + host: Arc, } const _: () = assert!(offset_of!(Pipeline, packet) == 0x10); @@ -191,17 +190,56 @@ pub(crate) fn bound(this: This) { } } -/// The host pipeline of a title pipeline, made on first use; `None` if one -/// of its shaders does not translate or the host refuses it. +/// The host pipeline of a title pipeline; `None` if one of its shaders does +/// not translate, the host refuses it, or it is still being made (its first +/// use starts that, see [`make`]). #[cfg(windows)] pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> { if this.is_null() { return None; } - let p = pipeline(this); - p.host - .get_or_init(|| host::HostPipeline::new(&p.shaders, p.graphics.as_deref())) - .as_ref() + make::ready(&pipeline(this).host) +} + +/// Host pipelines queued and not made yet. +#[cfg(windows)] +pub(crate) fn making() -> u64 { + make::waiting() +} + +/// Draws and dispatches dropped since the last [`take_drops`], by why their +/// pipeline has no host pipeline (diagnostics). +#[cfg(all(windows, feature = "diagnostics"))] +static DROPS: Mutex>> = Mutex::new(None); + +/// Counts a draw or dispatch of `this` dropped for want of a host pipeline +/// (diagnostics). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn note_drop(this: This) { + let why = if this.is_null() { + Some("no pipeline set".to_owned()) + } else { + make::missing(&pipeline(this).host) + }; + if let Some(why) = why { + note_why(why); + } +} + +/// Counts a draw or dispatch dropped for `why` (diagnostics). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn note_why(why: String) { + let mut drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()); + *drops.get_or_insert_with(HashMap::new).entry(why).or_default() += 1; +} + +/// The drops counted since the last call, most first (diagnostics). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn take_drops() -> Vec<(String, u64)> { + let drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut drops: Vec<(String, u64)> = drops.into_iter().flatten().collect(); + drops.sort_by_key(|d| std::cmp::Reverse(d.1)); + drops } /// The stage's container, if it has one. @@ -222,15 +260,17 @@ fn hand_out( out: *mut This, ) -> HRESULT { tracing::trace!(?shaders, "pipeline state"); + #[cfg(windows)] + let host = Arc::new(make::Pending::new(shaders.clone(), graphics)); + #[cfg(windows)] + make::early(&host); let pipeline = Box::new(Pipeline { object: Object::new(&FUNCTIONS), packet: [0; 8], + #[cfg(windows)] + host, shaders, bound: std::sync::atomic::AtomicBool::new(false), - #[cfg(windows)] - graphics, - #[cfg(windows)] - host: OnceLock::new(), }); object::hand_out(PIPELINE, pipeline, iid, &PIPELINE_IIDS, out) } @@ -398,6 +438,23 @@ static FUNCTIONS: Table<24> = { #[cfg(windows)] pub(crate) mod host; +#[cfg(windows)] +mod library; +#[cfg(windows)] +mod make; + +/// Keeps compiled host pipelines, and the list of title pipelines to start +/// early, in `dir` (a folder of the cache) across runs. +#[cfg(windows)] +pub fn use_pipeline_cache(dir: std::path::PathBuf) { + library::use_pipeline_cache(dir); +} + +/// Saves the pipeline cache now if anything was added (at the end of a run). +#[cfg(windows)] +pub fn save_pipeline_cache() { + library::save(true); +} #[cfg(test)] mod tests { @@ -499,7 +556,7 @@ mod tests { assert_eq!(shaders(p), [("mesh", ms.to_vec()), ("pixel", ps.to_vec())]); #[cfg(windows)] { - let g = pipeline(p).graphics.as_deref().unwrap(); + let g = pipeline(p).host.graphics.as_deref().unwrap(); assert_eq!(g.topology.0, 3); assert_eq!( (g.targets.NumRenderTargets, g.targets.RTFormats[0].0), diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index b409c4c..00aa9aa 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -169,6 +169,34 @@ impl GraphicsState { } } + /// Everything the state holds, as text: part of a pipeline's name in + /// the library and of the key a title pipeline is started early by. + pub(crate) fn describe(&self) -> String { + let inputs: Vec = self + .inputs + .iter() + .zip(&self.names) + .map(|(e, name)| { + format!( + "{name:?} {} {} {} {} {} {}", + e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0, e.InstanceDataStepRate + ) + }) + .collect(); + format!( + "{:?} {} {:?} {:?} {inputs:?} {} {} {:?} {} {:?}", + self.blend, + self.sample_mask, + self.rasterizer, + self.depth, + self.strip_cut.0, + self.topology.0, + self.targets, + self.depth_format.0, + self.samples + ) + } + /// The vertex buffer slots the input layout reads. fn slots(&self) -> u32 { self.inputs @@ -373,7 +401,7 @@ impl HostPipeline { } bound.push(stage); } - let root = match root_signature(&host.device, ¶ms, &samplers, compute.is_some()) { + let (root, root_blob) = match root_signature(&host.device, ¶ms, &samplers, compute.is_some()) { Ok(root) => root, Err(e) => { tracing::warn!(error = %e, ?shaders, "host root signature refused"); @@ -396,8 +424,15 @@ impl HostPipeline { CS: code(0), ..Default::default() }; - // SAFETY: the description points at live data. - let pso = match unsafe { host.device.CreateComputePipelineState(&desc) } { + let name = super::library::name("compute", &root_blob, &[&code_bytes(&code(0))], ""); + let made = super::library::pipeline( + &name, + // SAFETY: the description points at live data. + |library, name| unsafe { library.LoadComputePipeline(name, &desc) }, + // SAFETY: as above. + || unsafe { host.device.CreateComputePipelineState(&desc) }, + ); + let pso = match made { Ok(pso) => pso, Err(e) => { tracing::warn!(error = %e, ?shaders, "host pipeline refused"); @@ -421,8 +456,15 @@ impl HostPipeline { let Some(g) = g else { return refuse("graphics state not kept (plain description)", shaders); }; + let state = g.describe(); if mesh.is_some() { - let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g) { + let name = super::library::name( + "mesh", + &root_blob, + &[&code_bytes(&code(0)), &code_bytes(&code(1))], + &state, + ); + let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g, &name) { Ok(pso) => pso, Err(e) => { tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused"); @@ -470,8 +512,20 @@ impl HostPipeline { SampleDesc: g.samples, ..Default::default() }; - // SAFETY: the description points at live data. - let pso = match unsafe { host.device.CreateGraphicsPipelineState(&desc) } { + let name = super::library::name( + "graphics", + &root_blob, + &[&code_bytes(&code(0)), &code_bytes(&code(1))], + &state, + ); + let made = super::library::pipeline( + &name, + // SAFETY: the description points at live data. + |library, name| unsafe { library.LoadGraphicsPipeline(name, &desc) }, + // SAFETY: as above. + || unsafe { host.device.CreateGraphicsPipelineState(&desc) }, + ); + let pso = match made { Ok(pso) => pso, Err(e) => { tracing::warn!(error = %e, ?shaders, "host pipeline refused"); @@ -511,6 +565,7 @@ fn mesh_pipeline( ms: D3D12_SHADER_BYTECODE, ps: D3D12_SHADER_BYTECODE, g: &GraphicsState, + name: &str, ) -> windows::core::Result { use windows::core::Interface; /// A stream subobject: its type, then its description, pointer-aligned. @@ -545,8 +600,23 @@ fn mesh_pipeline( SizeInBytes: size_of::(), pPipelineStateSubobjectStream: (&raw mut stream).cast(), }; - // SAFETY: the stream holds whole subobjects pointing at live data. - unsafe { device.cast::()?.CreatePipelineState(&desc) } + let device = device.cast::()?; + super::library::pipeline( + name, + // SAFETY: the stream holds whole subobjects pointing at live data. + |library, name| unsafe { library.LoadPipeline(name, &desc) }, + // SAFETY: as above. + || unsafe { device.CreatePipelineState(&desc) }, + ) +} + +/// The bytes of shader code (none for an absent stage). +fn code_bytes(code: &D3D12_SHADER_BYTECODE) -> Vec { + if code.pShaderBytecode.is_null() { + return Vec::new(); + } + // SAFETY: a translation's own bytes, alive while its shader is. + unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::(), code.BytecodeLength) }.to_vec() } fn root_signature( @@ -554,7 +624,7 @@ fn root_signature( params: &[D3D12_ROOT_PARAMETER1], samplers: &[D3D12_STATIC_SAMPLER_DESC], compute: bool, -) -> windows::core::Result { +) -> windows::core::Result<(ID3D12RootSignature, Vec)> { let input = if compute { D3D12_ROOT_SIGNATURE_FLAG_NONE } else { @@ -592,6 +662,6 @@ fn root_signature( let blob = blob.ok_or_else(windows::core::Error::empty)?; let bytes = std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()); - device.CreateRootSignature(0, bytes) + Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec())) } } diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs new file mode 100644 index 0000000..aa611e2 --- /dev/null +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -0,0 +1,254 @@ +//! Compiled host pipelines kept on disk, and the title pipelines worth +//! starting early (decision 0007, "Pipeline cache"). +//! +//! 1. Every host pipeline goes into the host's pipeline library, named by +//! a hash of all that its host description holds (the translated +//! shaders' code, which changes when a translation does, our root +//! signature, the graphics state). The library is saved under the cache +//! folder; the host refuses a library of another adapter or driver, and +//! an entry whose description differs, so neither is ever used. +//! 2. The title pipelines a run drew or dispatched with are listed by a key +//! known when the title creates them (their shader containers and +//! graphics state); the next run hands those to the workers at +//! creation, during loading. +//! +//! All library calls are serialised: the interface does not promise that +//! stores, loads and serialising may overlap. + +use std::collections::HashSet; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::{HSTRING, Interface, PCWSTR}; + +static DIR: OnceLock = OnceLock::new(); + +/// Keeps the pipeline library and the early list in `dir` from now on. +pub fn use_pipeline_cache(dir: PathBuf) { + let _ = DIR.set(dir); +} + +/// Host pipelines created, loaded from the library, and title pipelines +/// started at creation, since the start. +pub(crate) static MADE: AtomicU64 = AtomicU64::new(0); +pub(crate) static LOADED: AtomicU64 = AtomicU64::new(0); +pub(crate) static EARLY: AtomicU64 = AtomicU64::new(0); + +struct Library { + library: ID3D12PipelineLibrary1, + /// The blob the library was made from: it must outlive the library. + _blob: Vec, + /// Pipelines stored since the last save. + added: u64, +} + +// SAFETY: D3D12 objects are free-threaded; every call is made under the +// mutex that holds the library. +unsafe impl Send for Library {} + +const LIBRARY_FILE: &str = "host-pipelines.bin"; +const EARLY_FILE: &str = "early-pipelines.txt"; +/// Title pipelines listed for an early start, at most. +const EARLY_MAX: usize = 8192; + +fn library() -> Option<&'static Mutex> { + static LIBRARY: OnceLock>> = OnceLock::new(); + LIBRARY + .get_or_init(|| { + let device = crate::host::host()?.device.cast::().ok()?; + let blob = DIR + .get() + .and_then(|d| std::fs::read(d.join(LIBRARY_FILE)).ok()) + .unwrap_or_default(); + let library = open(&device, blob); + if library.is_none() { + tracing::warn!("no host pipeline library: pipelines are not kept"); + } + library.map(Mutex::new) + }) + .as_ref() +} + +/// The library in `blob`, or an empty one if the host rejects the blob (an +/// adapter or driver change, damage). +fn open(device: &ID3D12Device1, blob: Vec) -> Option { + let make = |bytes: &[u8]| -> windows::core::Result { + // SAFETY: the bytes outlive the library (kept beside it). + unsafe { + device.CreatePipelineLibrary::(bytes)?.cast() + } + }; + if !blob.is_empty() { + match make(&blob) { + Ok(library) => { + tracing::info!(bytes = blob.len(), "host pipeline library loaded"); + return Some(Library { library, _blob: blob, added: 0 }); + } + Err(e) => tracing::info!(error = %e, "host pipeline library rejected; starting an empty one"), + } + } else { + tracing::info!("no host pipeline library yet; starting an empty one"); + } + let library = make(&[]).ok()?; + Some(Library { library, _blob: Vec::new(), added: 0 }) +} + +/// A pipeline's name in the library: the hash of what its host +/// description holds. +pub(crate) fn name(kind: &str, root: &[u8], code: &[&[u8]], state: &str) -> String { + let mut h = blake3::Hasher::new(); + for part in [kind.as_bytes(), root].into_iter().chain(code.iter().copied()).chain([state.as_bytes()]) { + h.update(&(part.len() as u64).to_le_bytes()); + h.update(part); + } + h.finalize().to_hex()[..32].to_owned() +} + +/// The pipeline named `name`: loaded from the library by `load` if it is +/// there with the same description, else made by `create` and stored. +pub(crate) fn pipeline( + name: &str, + load: impl FnOnce(&ID3D12PipelineLibrary1, PCWSTR) -> windows::core::Result, + create: impl FnOnce() -> windows::core::Result, +) -> windows::core::Result { + let wide = HSTRING::from(name); + let Some(library) = library() else { + MADE.fetch_add(1, Ordering::Relaxed); + return create(); + }; + if let Ok(pso) = load(&library.lock().unwrap_or_else(|e| e.into_inner()).library, PCWSTR(wide.as_ptr())) { + LOADED.fetch_add(1, Ordering::Relaxed); + return Ok(pso); + } + // Compiled outside the lock: compiles take up to seconds. + let pso = create()?; + MADE.fetch_add(1, Ordering::Relaxed); + let mut l = library.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: a live pipeline; a name already stored (a description that + // differs) is refused, which leaves the library as it was. + if unsafe { l.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() { + l.added += 1; + } + Ok(pso) +} + +/// Writes the library and the early list if pipelines were added since the +/// last save and `SAVE_EVERY` has passed (or `now`). +pub(crate) fn save(now: bool) { + static LAST: Mutex> = Mutex::new(None); + const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20); + let (Some(dir), Some(library)) = (DIR.get(), library()) else { return }; + { + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + if !now && last.is_some_and(|t| t.elapsed() < SAVE_EVERY) { + return; + } + *last = Some(std::time::Instant::now()); + } + let blob = { + let mut l = library.lock().unwrap_or_else(|e| e.into_inner()); + if l.added == 0 && !USED_CHANGED.swap(false, Ordering::Relaxed) { + return; + } + // SAFETY: a buffer of the size the library asks for. + let bytes = unsafe { + let mut bytes = vec![0u8; l.library.GetSerializedSize()]; + l.library.Serialize(&mut bytes).map(|()| bytes) + }; + match bytes { + Ok(bytes) => { + l.added = 0; + bytes + } + Err(e) => { + tracing::warn!(error = %e, "host pipeline library not serialised"); + return; + } + } + }; + let used: Vec = USED.lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().cloned().collect(); + let written = std::fs::create_dir_all(dir) + .and_then(|()| write_atomically(&dir.join(LIBRARY_FILE), &blob)) + .and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes())); + match written { + Ok(()) => tracing::info!( + bytes = blob.len(), + early = used.len(), + made = MADE.load(Ordering::Relaxed), + loaded = LOADED.load(Ordering::Relaxed), + started_early = EARLY.load(Ordering::Relaxed), + "host pipeline library saved" + ), + Err(e) => tracing::warn!(error = %e, "host pipeline library not saved"), + } +} + +/// Writes `bytes` to a temporary file beside `path`, then renames it over +/// `path`: a reader never sees a part. +fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, bytes)?; + std::fs::rename(&tmp, path) +} + +/// Title pipeline keys drawn or dispatched with (this run and the last). +static USED: Mutex>> = Mutex::new(None); +static USED_CHANGED: AtomicBool = AtomicBool::new(false); + +fn used() -> std::sync::MutexGuard<'static, Option>> { + let mut used = USED.lock().unwrap_or_else(|e| e.into_inner()); + if used.is_none() { + let listed = DIR + .get() + .and_then(|d| std::fs::read_to_string(d.join(EARLY_FILE)).ok()) + .unwrap_or_default(); + let set: HashSet = listed.lines().filter(|l| !l.is_empty()).map(str::to_owned).collect(); + tracing::info!(pipelines = set.len(), "title pipelines to start early"); + *used = Some(set); + } + used +} + +/// Whether the title pipeline with `key` was drawn with in an earlier run. +pub(crate) fn wanted_early(key: &str) -> bool { + used().as_ref().is_some_and(|s| s.contains(key)) +} + +/// The title pipeline with `key` was drawn or dispatched with. +pub(crate) fn note_used(key: &str) { + let mut used = used(); + let set = used.get_or_insert_with(HashSet::new); + if set.len() < EARLY_MAX && set.insert(key.to_owned()) { + USED_CHANGED.store(true, Ordering::Relaxed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_change_with_what_goes_into_the_pipeline() { + let a = name("graphics", b"root", &[b"vs", b"ps"], "state"); + assert_eq!(a, name("graphics", b"root", &[b"vs", b"ps"], "state")); + assert_ne!(a, name("graphics", b"root", &[b"vs", b"ps2"], "state")); + assert_ne!(a, name("graphics", b"root", &[b"vs", b"ps"], "state2")); + assert_ne!(a, name("graphics", b"root2", &[b"vs", b"ps"], "state")); + assert_ne!(a, name("mesh", b"root", &[b"vs", b"ps"], "state")); + // Parts do not run into each other. + assert_ne!(a, name("graphics", b"root", &[b"vsp", b"s"], "state")); + } + + #[test] + fn a_rejected_blob_gives_an_empty_library() { + let Some(device) = crate::host::host().and_then(|h| h.device.cast::().ok()) else { + return; // no host GPU here + }; + let library = open(&device, b"not a pipeline library".repeat(16)).expect("an empty library"); + // SAFETY: a plain query on a live library. + assert!(unsafe { library.library.GetSerializedSize() } > 0); + assert!(library._blob.is_empty()); + } +} diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs new file mode 100644 index 0000000..6ffc032 --- /dev/null +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -0,0 +1,238 @@ +//! Host pipelines are made by workers, not by the title thread that first +//! records a draw with them. Translating a shader and the host driver's +//! compile take from milliseconds to seconds each (structurisation of the +//! biggest compute programs ~0.4 s, some driver compiles 3.4 s), and Grand +//! Theft Auto VI's first world frame wants over 1,200 new pipelines: made +//! on its recording threads, that frame took more than 30 s and the +//! title's GPU watchdog ended the run (decision 0007, "Pipelines made off +//! the title's threads"). +//! +//! A first use queues the pipeline and waits for it within a budget per +//! frame, so the cheap ones (menus, one-off passes such as a colour-grading +//! bake) are there at once as before; past the budget a draw or dispatch +//! whose pipeline is not ready is dropped, as an untranslated one is. +//! +//! shortcut: the budget (half a second of waiting per title frame) is a +//! guess; a pass the title runs only once and whose pipeline takes longer +//! is lost. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use super::Shader; +use super::host::{GraphicsState, HostPipeline}; + +/// What a host pipeline is made from, and the host pipeline once made. +pub(crate) struct Pending { + shaders: Vec>, + pub(crate) graphics: Option>, + queued: AtomicBool, + made: OnceLock>, + /// What identifies it across runs (shader containers and state), and + /// whether a draw has used it yet. + key: String, + used: AtomicBool, +} + +// SAFETY: D3D12 objects are free-threaded; the graphics state (whose input +// elements point into its own names) is only read after creation. +unsafe impl Send for Pending {} +// SAFETY: as above. +unsafe impl Sync for Pending {} + +impl Pending { + pub(crate) fn new(shaders: Vec>, graphics: Option>) -> Pending { + let mut key = blake3::Hasher::new(); + for s in &shaders { + key.update(s.stage.as_bytes()); + key.update(s.hash.as_bytes()); + } + key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes()); + Pending { + shaders, + graphics, + queued: AtomicBool::new(false), + made: OnceLock::new(), + key: key.finalize().to_hex()[..32].to_owned(), + used: AtomicBool::new(false), + } + } + + fn make(&self) { + self.made + .get_or_init(|| HostPipeline::new(&self.shaders, self.graphics.as_deref())); + let (lock, done) = &DONE; + let _held = lock.lock().unwrap_or_else(|e| e.into_inner()); + done.notify_all(); + } +} + +/// Why a pipeline has no host pipeline (diagnostics): its shaders that do +/// not translate, else "refused" or "being made"; `None` if it has one. +#[cfg(feature = "diagnostics")] +pub(crate) fn missing(p: &Pending) -> Option { + match p.made.get() { + Some(Some(_)) => None, + None => Some("being made".into()), + Some(None) => { + let failed: Vec = p + .shaders + .iter() + .filter(|s| matches!(s.translated.get(), Some(None))) + .map(|s| format!("{} {}", s.stage, s.hash)) + .collect(); + Some(if failed.is_empty() { + format!("refused {:?}", p.shaders) + } else { + failed.join(" + ") + }) + } + } +} + +/// Signalled whenever a worker has made a pipeline. +static DONE: (Mutex<()>, Condvar) = (Mutex::new(()), Condvar::new()); + +/// Waiting allowed per title frame, over all threads. +const BUDGET: Duration = Duration::from_millis(500); + +/// Pipelines queued and not made yet. +static WAITING: AtomicU64 = AtomicU64::new(0); + +/// Pipelines queued and not made yet (for the frame line). +pub(crate) fn waiting() -> u64 { + WAITING.load(Ordering::Relaxed) +} + +/// The host pipeline if it is made (or is made within the frame's budget); +/// queues it on first use. +pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { + if p.made.get().is_none() { + start(p); + wait(p, crate::frame::current()); + } + let made = p.made.get()?.as_ref(); + if made.is_some() && !p.used.swap(true, Ordering::Relaxed) { + super::library::note_used(&p.key); + } + made +} + +/// Queues `p` for the workers, once. +fn start(p: &Arc) { + if !p.queued.swap(true, Ordering::Relaxed) { + PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed); + queue(p.clone()); + } +} + +/// At the title's creation of a pipeline: starts it at once if an earlier +/// run drew with it (during loading, so the world's first frames find it). +pub(crate) fn early(p: &Arc) { + if !p.shaders.is_empty() && super::library::wanted_early(&p.key) { + super::library::EARLY.fetch_add(1, Ordering::Relaxed); + start(p); + } +} + +/// Waits for `p` while frame `frame` has budget left. +fn wait(p: &Pending, frame: u64) { + static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + static WAITED_US: AtomicU64 = AtomicU64::new(0); + if FRAME.swap(frame, Ordering::Relaxed) != frame { + WAITED_US.store(0, Ordering::Relaxed); + } + let left = BUDGET.saturating_sub(Duration::from_micros(WAITED_US.load(Ordering::Relaxed))); + let started = Instant::now(); + let (lock, done) = &DONE; + let mut held = lock.lock().unwrap_or_else(|e| e.into_inner()); + while p.made.get().is_none() { + let rest = left.saturating_sub(started.elapsed()); + if rest.is_zero() { + break; + } + held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0; + } + WAITED_US.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); +} + +/// Hands `p` to the workers (half the logical processors, 2 to 8), started +/// on first use. +fn queue(p: Arc) { + static SENDER: OnceLock>> = OnceLock::new(); + let sender = SENDER.get_or_init(|| { + let (sender, receiver) = std::sync::mpsc::channel::>(); + let receiver = Arc::new(Mutex::new(receiver)); + let workers = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8)); + for i in 0..workers { + let receiver = receiver.clone(); + let spawned = std::thread::Builder::new() + .name(format!("victory-pipelines-{i}")) + .spawn(move || { + // Below the title's own threads (loading, recording). + // SAFETY: a plain call on our own thread. + unsafe { + use windows::Win32::System::Threading::*; + let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + } + loop { + let next = receiver.lock().unwrap_or_else(|e| e.into_inner()).recv(); + let Ok(p) = next else { return }; + p.make(); + if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 { + drained(); + } else { + super::library::save(false); + } + } + }); + if let Err(e) = spawned { + tracing::warn!(error = %e, "no pipeline worker"); + } + } + sender + }); + if let Err(e) = sender.send(p) { + // No worker: made here instead. + e.0.make(); + WAITING.fetch_sub(1, Ordering::Relaxed); + } +} + +/// The most pipelines waiting at once since the workers last ran out. +static PEAK: AtomicU64 = AtomicU64::new(0); + +/// The workers ran out of work: logged after a batch of 10 or more, and +/// the cache saved (at most every 20 s). +fn drained() { + use super::library::{EARLY, LOADED, MADE}; + if PEAK.swap(0, Ordering::Relaxed) >= 10 { + tracing::info!( + made = MADE.load(Ordering::Relaxed), + loaded = LOADED.load(Ordering::Relaxed), + started_early = EARLY.load(Ordering::Relaxed), + "host pipelines all made" + ); + } + super::library::save(false); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A first use queues the pipeline and, within the budget, gets the + /// worker's answer (here: no host pipeline for no shaders). + #[test] + fn first_use_is_made_by_a_worker() { + let p = Arc::new(Pending::new(Vec::new(), None)); + assert!(ready(&p).is_none()); + assert!(p.queued.load(Ordering::Relaxed)); + let started = Instant::now(); + while p.made.get().is_none() && started.elapsed() < Duration::from_secs(10) { + std::thread::yield_now(); + } + assert!(matches!(p.made.get(), Some(None))); + } +} diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 3c39a30..c7b390b 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -40,6 +40,39 @@ pub(crate) struct Shadow { /// Ranges shaders of a submission not yet copied back may be writing: /// title memory there is older than the copy. pending: Mutex>, + /// The copy's bytes before the submission ran, from an offset on, + /// covering the ranges its shaders write: what the GPU wrote differs. + before: Mutex)>>, +} + +/// Snapshot memory kept for reuse (already touched, so no page faults). +static POOL: Mutex>> = Mutex::new(Vec::new()); + +/// An empty buffer with room for `n` bytes, from the pool if it has one. +fn pooled(n: usize) -> Vec { + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let fit = pool + .iter() + .enumerate() + .filter(|(_, v)| v.capacity() >= n) + .min_by_key(|(_, v)| v.capacity()) + .map(|(i, _)| i); + let mut v = match fit { + Some(i) => pool.swap_remove(i), + None => Vec::with_capacity(n), + }; + v.clear(); + v +} + +/// Returns a snapshot buffer to the pool (at most 8 kept, the largest). +fn give_back(v: Vec) { + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + pool.push(v); + if pool.len() > 8 { + pool.sort_by_key(|v| std::cmp::Reverse(v.capacity())); + pool.truncate(8); + } } const NOT_WATCHED: u8 = 2; @@ -84,72 +117,145 @@ impl Shadow { copied: Mutex::new(vec![0; pages as usize]), watched: AtomicU8::new(0), pending: Mutex::default(), + before: Mutex::default(), } } + /// `[address, address + len)` cut to the buffer, as offsets in the copy. + fn inside(&self, address: usize, len: usize) -> (usize, usize) { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let from = address.clamp(start, end); + (from - start, (address + len).clamp(from, end) - start) + } + /// Shaders of `list` may write `[address, address + len)` of the copy /// (unordered access): after the list's submission has run, the range /// is copied back into title memory, where the title reads it; until /// then no refresh copies title memory over it. Call after the /// [`Shadow::refresh`] that gives the shaders the title's data. /// - /// shortcut: the whole range goes back after every submission that - /// declares it; copy back only what shaders wrote (a GPU-side dirty - /// mask) if big unordered-access buffers make it slow. + /// shortcut: what shaders wrote is found by keeping the range's bytes + /// before the submission (a copy per declared range and submission); + /// a GPU-side dirty mask would save that if big ranges make it slow. pub(crate) fn gpu_writes(self: &Arc, list: &HostList, address: u64, len: u64) { let len = len.min(self.left(address)); list.defer_gpu_write(self, address as usize, len as usize); } - /// At submission: a submitted list's shaders write this range. + /// At submission, after the range's refresh: a submitted list's shaders + /// write this range. Its bytes are kept to tell later what the GPU wrote: + /// one snapshot per copy and submission, grown to cover every range the + /// submission declares (the world declares overlapping views of its + /// 174 MB heap dozens of times), in reused memory (fresh snapshots cost + /// ~2.3 million page faults per world frame). pub(crate) fn writing(&self, address: usize, len: usize) { self.pending .lock() .unwrap_or_else(|e| e.into_inner()) .push((address, address + len)); + let (from, to) = self.inside(address, len); + // SAFETY: inside the mapping. + let host = |a: usize, b: usize| unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) }; + let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); + let (start, end) = match &*before { + Some((at, bytes)) => ((*at).min(from), (at + bytes.len()).max(to)), + None => (from, to), + }; + if let Some((at, bytes)) = &*before + && (*at, at + bytes.len()) == (start, end) + { + return; + } + // Parts newly covered from the copy, the rest as it was taken. + let mut grown = pooled(end - start); + match before.take() { + Some((at, bytes)) => { + grown.extend_from_slice(host(start, at)); + grown.extend_from_slice(&bytes); + grown.extend_from_slice(host(at + bytes.len(), end)); + give_back(bytes); + } + None => grown.extend_from_slice(host(start, end)), + } + *before = Some((start, grown)); } - /// After the submission ran: copies what its shaders may have written - /// back into title memory (unmapped pages left alone). Pages wholly - /// written are current in this copy, so our own write is not taken for - /// the title's. - /// Returns the bytes written. + /// After the submission ran: copies the bytes its shaders wrote back + /// into title memory (unmapped pages left alone), and only those: the + /// title's threads write the same buffers while the GPU runs (its + /// command memory shares the big GPU heap with what shaders write), and + /// putting back the copy's older bytes there broke the title's own + /// records (a fence list read as -1, title+0x4e9b54a). Returns the bytes + /// written. pub(crate) fn copy_back(&self, address: usize, len: usize) -> usize { + let mut snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner()); let mut written = 0; - let (start, end) = (self.start as usize, (self.start + self.len) as usize); - let (from, to) = (address.max(start), (address + len).min(end)); - if from < to { - // Only the pieces that differ: shaders rewrite part of what they - // may write, and writing title memory through the kernel (and - // opening guarded blocks) was the world's biggest cost (~1 s per - // frame for 450 MB). + let (from, to) = self.inside(address, len); + let start = self.start as usize; + if let Some((taken, before)) = &*snapshot + && *taken <= from + && to <= taken + before.len() + && from < to + { + let before = &before[from - taken..to - taken]; + // By 64 KiB piece: the copy compared with its bytes before the + // submission, title memory read only where the GPU wrote. const PIECE: usize = 64 << 10; let mut title = vec![0u8; PIECE]; + let mut synced = Vec::new(); let mut at = from; while at < to { - let n = (PIECE - at % PIECE).min(to - at); - // SAFETY: inside the mapping. - let host = unsafe { std::slice::from_raw_parts(self.data.add(at - start), n) }; - if !crate::host::read_into(at as *const u8, &mut title[..n]) || title[..n] != *host { - crate::watch::writing(at, n); - crate::host::write_mapped(at as *mut u8, host.as_ptr(), n); - written += n; + let n = (PIECE - (start + at) % PIECE).min(to - at); + // SAFETY: inside the mapping; only the submitting thread + // writes it. + let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; + let old = &before[at - from..at - from + n]; + let title = &mut title[..n]; + if host != old && crate::host::read_into((start + at) as *const u8, title) { + // Title memory with the GPU's bytes put in; the copy + // takes the title's bytes in turn. + let mut changed = false; + for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) { + if *h != *o && *t != *h { + *t = *h; + changed = true; + } + *h = *t; + } + if changed { + crate::watch::writing(start + at, n); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + written += n; + } + synced.push((start + at) / PAGE); } at += n; } - let (first, last) = (from.div_ceil(PAGE), to / PAGE); + // Pages made equal to title memory are current in the copy, so + // our own write is not taken for the title's; others keep what + // they had (a title write there shows at the next refresh). + let (first, last) = ((start + from).div_ceil(PAGE), (start + to) / PAGE); if first < last + && !synced.is_empty() && self.watched.load(Ordering::Relaxed) != NOT_WATCHED && let Some((now, _)) = crate::watch::writes(first * PAGE, last * PAGE, true) { let base = start / PAGE; let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - copied[first - base..last - base].fill(now); + for page in synced.into_iter().filter(|p| (first..last).contains(p)) { + copied[page - base] = now; + } } } - // Every submitted step that declared the range is done with it. + // Every submitted step that declared the range is done with it (one + // submission runs at a time), and the snapshot with the last range. let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); pending.retain(|&r| r != (address, address + len)); + if pending.is_empty() + && let Some((_, bytes)) = snapshot.take() + { + give_back(bytes); + } written } diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index ef8b231..23bbccf 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -37,10 +37,14 @@ fn host_gpu_failed(what: &str) -> ! { } /// Keeps the host's translations of the title's shaders in `dir` (a -/// folder of the cache) across runs. +/// folder of the cache) across runs, and its compiled pipelines beside it +/// (`pipelines`). pub fn use_shader_cache(dir: std::path::PathBuf) { #[cfg(windows)] - victory_gpu::shader_cache::use_shader_cache(dir); + { + victory_gpu::pipeline::use_pipeline_cache(dir.with_file_name("pipelines")); + victory_gpu::shader_cache::use_shader_cache(dir); + } #[cfg(not(windows))] let _ = dir; } diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs index 6ab93ea..3e5e00f 100644 --- a/crates/victory-hle/src/modules/lifecycle.rs +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -277,6 +277,9 @@ pub fn wait_for_previous() { } fn end() { + // Compiled host pipelines kept for the next run. + #[cfg(windows)] + victory_gpu::pipeline::save_pipeline_cache(); // SAFETY: ends this process, as the console ends a suspended title. unsafe { TerminateProcess(GetCurrentProcess(), 0) }; } From f3c7f0f2ad4cd9071fe1e90b187217f0445ea5aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9rez?= Date: Tue, 24 Nov 2026 01:06:44 +0100 Subject: [PATCH 029/445] GPU: leave rectangle vertex components past the stride alone Expanding a rectangle list makes the fourth corner from the other three, element by element. An element that reaches past the vertex stride (the input layout allows it to overlap the next vertex) was read and written past the vertex's bytes, which panicked at submission. Only the components inside the vertex are computed now; the rest keep the first vertex's bytes, as unknown formats already do. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/primitive.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index 74c6f69..c11c647 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -8,7 +8,9 @@ //! shortcut: the fourth vertex is computed from vertex inputs, not from //! vertex shader outputs as the hardware does; that is the same for vertex //! shaders linear in their inputs (blits, 2D quads). Inputs in formats -//! [`components`] does not know keep the first vertex's value. +//! [`components`] does not know keep the first vertex's value, and so do +//! components past the end of the vertex (an element that reaches into the +//! next one, which the layout allows). /// Expands `rects` rectangles of `stride`-byte vertices from `src` into six /// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both @@ -29,7 +31,10 @@ pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: let Some((n, kind)) = components(format) else { continue; }; - for c in 0..n { + // Only the components inside the vertex: the rest belong to the + // next one. + let inside = stride.saturating_sub(at) / kind.bytes(); + for c in 0..n.min(inside) { let get = |i: usize| kind.read(&v(i)[at..], c); let value = get(0) + get(2) - get(1); kind.write(&mut fourth[at..], c, value); @@ -159,4 +164,18 @@ mod tests { assert_eq!(half_to_f32(0x3e00), 1.5); assert_eq!(half_to_f32(0xc000), -2.0); } + + /// An element that reaches past the stride (float4 at 4 in 8-byte + /// vertices, RGBA8 at the stride itself): the components inside get + /// the fourth corner, the rest keep the first vertex's bytes. The old + /// code indexed past the vertex and panicked. + #[test] + fn elements_past_the_stride_are_left_alone() { + let vertex = |x: f32, y: f32| [x.to_le_bytes(), y.to_le_bytes()].concat(); + let src = [vertex(0.0, 2.0), vertex(1.0, 3.0), vertex(5.0, 7.0)].concat(); + let mut dst = vec![0u8; 6 * 8]; + expand_rects(&src, &mut dst, 8, &[(0, 16), (4, 2), (8, 28)]); + assert_eq!(dst[..40], [&src[..], &src[..8], &src[16..]].concat()[..]); + assert_eq!(dst[40..], vertex(4.0, 6.0)[..]); + } } From 25a3e9596f7403ffea784e20b08696d937a71f2a Mon Sep 17 00:00:00 2001 From: ifBars Date: Mon, 23 Nov 2026 16:07:09 -0800 Subject: [PATCH 030/445] Keep an empty import descriptor so Windows assigns static TLS Use the descriptor count already validated by the PE parser, so the directory size need not include the null terminator. Check the OS-assigned static TLS index on a mapped test DLL. --- crates/victory-loader/src/prepare.rs | 86 ++++++++++++++++++++++------ 1 file changed, 69 insertions(+), 17 deletions(-) diff --git a/crates/victory-loader/src/prepare.rs b/crates/victory-loader/src/prepare.rs index 336f278..c893508 100644 --- a/crates/victory-loader/src/prepare.rs +++ b/crates/victory-loader/src/prepare.rs @@ -35,8 +35,8 @@ impl PreparedImage { /// /// * `IMAGE_FILE_DLL` set, entry point cleared: the OS maps it like a DLL /// and calls nothing; -/// * import, bound-import and IAT directories cleared: we bind the original -/// IAT slots ourselves, using `info.imports`; +/// * import directory points to its empty terminator and the bound-import +/// directory is cleared: we bind the original slots using `info.imports`; /// * TLS callback pointer cleared: the OS still allocates static TLS for /// the image, but callbacks only run when we call them (after binding); /// its base relocation is made a no-op so the 0 survives a rebase; @@ -64,13 +64,24 @@ pub fn prepare(original: &[u8]) -> Result { dll_characteristics, )?; - // Clear the IAT directory along with the import directory for Windows 10. - // The slots themselves stay in the image for our binder. - for index in [dir::IMPORT, dir::BOUND_IMPORT, dir::IAT] { - if let Some(at) = layout::data_directory_offset(&bytes, index) { - write(&mut bytes, at, &[0; layout::DATA_DIRECTORY_SIZE])?; + // Windows 10 assigns static TLS to the prepared DLL when its empty + // import table is present. The parser has already walked one descriptor + // per module up to the null terminator, regardless of the recorded Size. + if let Some(at) = layout::data_directory_offset(&bytes, dir::IMPORT) { + let rva = layout::read_u32(&bytes, at).ok_or(PrepareError::Patch("no import RVA"))?; + if rva != 0 { + let terminator = u32::try_from(info.imports.len()) + .ok() + .and_then(|count| count.checked_mul(IMPORT_DESCRIPTOR_SIZE)) + .and_then(|offset| rva.checked_add(offset)) + .ok_or(PrepareError::Patch("import terminator RVA overflow"))?; + write_u32(&mut bytes, at, terminator)?; + write_u32(&mut bytes, at + 4, IMPORT_DESCRIPTOR_SIZE)?; } } + if let Some(at) = layout::data_directory_offset(&bytes, dir::BOUND_IMPORT) { + write(&mut bytes, at, &[0; layout::DATA_DIRECTORY_SIZE])?; + } if let Some(tls) = &info.tls && tls.callbacks_va != 0 @@ -102,6 +113,9 @@ pub fn prepare(original: &[u8]) -> Result { }) } +/// Size of an IMAGE_IMPORT_DESCRIPTOR in the PE file. +const IMPORT_DESCRIPTOR_SIZE: u32 = 20; + /// Every `IMAGE_REL_BASED_DIR64` base relocation: (file offset of its entry, /// RVA it patches). Empty if the image has no readable relocation table. fn dir64_relocations(bytes: &[u8], info: &ImageInfo) -> Vec<(usize, u32)> { @@ -174,13 +188,6 @@ mod tests { assert!(patched.is_dll()); assert_eq!(patched.entry_rva, 0); assert!(patched.imports.is_empty()); - for index in [dir::IMPORT, dir::BOUND_IMPORT, dir::IAT] { - let at = layout::data_directory_offset(&original, index).unwrap(); - assert_eq!( - &prepared.bytes[at..at + layout::DATA_DIRECTORY_SIZE], - &[0; 8] - ); - } assert_eq!(patched.dll_characteristics & dll_flags::FORCE_INTEGRITY, 0); if let Some(tls) = &patched.tls { assert_eq!(tls.callbacks_va, 0); @@ -203,14 +210,27 @@ mod tests { let info = ImageInfo::parse(&original).unwrap(); let directory = layout::data_directory_offset(&original, dir::IMPORT).unwrap(); // This linker layout counts the descriptors for real modules only. - let descriptor_bytes = u32::try_from(info.imports.len() * 20).unwrap(); + let descriptor_bytes = u32::try_from(info.imports.len()).unwrap() * IMPORT_DESCRIPTOR_SIZE; write_u32(&mut original, directory + 4, descriptor_bytes).unwrap(); let prepared = prepare(&original).unwrap(); + let empty = layout::read_u32(&prepared.bytes, directory).unwrap(); + assert_eq!( + empty, + layout::read_u32(&original, directory).unwrap() + descriptor_bytes + ); + assert_eq!( + layout::read_u32(&prepared.bytes, directory + 4), + Some(IMPORT_DESCRIPTOR_SIZE) + ); + let at = info.rva_to_file_offset(empty).unwrap() as usize; + assert_eq!( + &prepared.bytes[at..at + IMPORT_DESCRIPTOR_SIZE as usize], + &[0; 20] + ); let iat = layout::data_directory_offset(&original, dir::IAT).unwrap(); - assert_ne!(layout::read_u32(&original, iat), Some(0)); assert_eq!( &prepared.bytes[iat..iat + layout::DATA_DIRECTORY_SIZE], - &[0; 8] + &original[iat..iat + layout::DATA_DIRECTORY_SIZE] ); assert_eq!(prepared.info.import_count(), info.import_count()); for module in &prepared.info.imports { @@ -221,6 +241,38 @@ mod tests { } } + #[cfg(windows)] + #[test] + fn windows_assigns_static_tls_to_a_prepared_dll() { + // Model a title DLL using our own linked image. Loading a DLL leaves + // its assigned index intact; the executable-specific redirect resets it. + let mut original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + let flags = + layout::file_header_offset(&original).unwrap() + layout::FILE_HEADER_CHARACTERISTICS; + let characteristics = + ImageInfo::parse(&original).unwrap().characteristics | file_flags::DLL; + write_u16(&mut original, flags, characteristics).unwrap(); + let prepared = prepare(&original).unwrap(); + let info = &prepared.info; + let tls = info.tls.as_ref().expect("the test binary uses static TLS"); + let directory = info.rva_to_file_offset(tls.directory_rva).unwrap() as usize; + let index_va = layout::read_u64(&original, directory + 16).unwrap(); + let index_rva = index_va.checked_sub(info.image_base).unwrap(); + assert!(index_rva + 4 <= u64::from(info.size_of_image)); + + let folder = tempfile::tempdir().unwrap(); + let image = crate::load(&prepared, folder.path()).unwrap(); + // SAFETY: the mapped test image contains the checked DWORD above. + let assigned = + unsafe { ((image.base() + index_rva as usize) as *const u32).read_unaligned() }; + // SAFETY: the prepared DLL has never been attached or given to a caller. + unsafe { image.unload() }; + assert_ne!( + assigned, 0, + "the process executable already owns TLS slot zero" + ); + } + #[test] fn file_name_is_stable_per_build() { let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); From 78b84047e5cfc94cc85abd9e7178bc13a84612d3 Mon Sep 17 00:00:00 2001 From: meower <59313695+a55uka@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:36:59 +0000 Subject: [PATCH 031/445] xmem: commit physical-page sections whole under Wine XMemAllocatePhysicalPages makes SEC_RESERVE sections and commits their pages one view at a time. Under Wine each commit is a wineserver request that scans every range committed so far, so wineserver ran at full load while the title's threads waited on it, and loading hardly moved. Under Wine (detected by ntdll's wine_get_version export) the sections are now SEC_COMMIT and the per-view commit is skipped. Wine backs a committed section with a sparse file, so untouched pages still cost nothing. Windows keeps SEC_RESERVE, since a busy host may be unable to commit the 6.1 GiB the title asks for in one go. Tested: Linux (Wine 11.21), i7-12700K, RTX 4070. wineserver load drops after the first seconds and the title gets to its loading screen, drawing and dispatching. --- crates/victory-hle/src/modules/xmem.rs | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index bcd3222..0f463b7 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -18,8 +18,8 @@ use windows_sys::Win32::System::Memory::{ CreateFileMappingW, MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, MEM_RESERVE_PLACEHOLDER, MEMORY_BASIC_INFORMATION, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile3, - MemExtendedParameterAddressRequirements, PAGE_NOACCESS, PAGE_READWRITE, SEC_RESERVE, - UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQueryEx, + MemExtendedParameterAddressRequirements, PAGE_NOACCESS, PAGE_READWRITE, SEC_COMMIT, + SEC_RESERVE, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQueryEx, }; use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; use windows_sys::Win32::System::Threading::GetCurrentProcess; @@ -29,6 +29,19 @@ use crate::{HleModule, hle_export}; const MIB: usize = 1 << 20; +/// Whether we run under Wine (its ntdll exports `wine_get_version`). +pub(crate) fn on_wine() -> bool { + static WINE: LazyLock = LazyLock::new(|| { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + // SAFETY: plain lookups in ntdll, always loaded. + unsafe { + let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast()); + !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some() + } + }); + *WINE +} + /// Standard memory the title has handed to the system. static TRANSFERRED: AtomicUsize = AtomicUsize::new(0); @@ -388,7 +401,11 @@ pub extern "system" fn XMemAllocatePhysicalPages( CreateFileMappingW( INVALID_HANDLE_VALUE, std::ptr::null(), - PAGE_READWRITE | SEC_RESERVE, + // Under Wine a committed section is a sparse file, free until + // touched, and committing a reserved one page by page costs a + // wineserver request each that scans every range committed so + // far: commit it whole there. + PAGE_READWRITE | if on_wine() { SEC_COMMIT } else { SEC_RESERVE }, (size as u64 >> 32) as u32, size as u32, std::ptr::null(), @@ -635,6 +652,9 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { /// Commits the section pages a view shows (once per page, whichever view). fn commit(base: usize, len: usize) -> bool { + if on_wine() { + return true; // sections are committed whole there + } // SAFETY: `[base, base + len)` is a view of a reserved section. let done = !unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null(); From 0eca412a4673f12d28a40b5ed7e9ffefca90454e Mon Sep 17 00:00:00 2001 From: FIocker <4461558+FIocker@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:12:41 +0100 Subject: [PATCH 032/445] GPU diagnostics: skip pipelines by shader hash Co-authored-by: Claude Opus 5.5 --- README.md | 1 + crates/victory-gpu/src/draw.rs | 16 ++++++++ crates/victory-gpu/src/pipeline.rs | 65 +++++++++++++++++++++++++++--- 3 files changed, 77 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 81eedb3..304ea8d 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,7 @@ cargo build --profile diag -p victory --features diagnostics # target\diag\vic | `VICTORY_D3D12_DEBUG=1` | host debug layer | | `VICTORY_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) | | `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | +| `VICTORY_SKIP_PIPELINES=,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash | | `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands | | `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | | `VICTORY_AUDIO_CAPTURE=` | records what the title plays (our process only) | diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index af6ad04..5f1f034 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -333,6 +333,10 @@ impl State { /// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches. fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool { + #[cfg(feature = "diagnostics")] + if crate::pipeline::is_skipped(self.pipeline as This) { + return false; + } let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { return false; }; @@ -489,6 +493,12 @@ impl State { /// Runs a dispatch on the host. pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) { + #[cfg(feature = "diagnostics")] + if crate::pipeline::is_skipped(self.pipeline as This) { + DROPPED.fetch_add(1, Ordering::Relaxed); + crate::pipeline::note_drop(self.pipeline as This); + return; + } let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { once!( pipeline = format_args!("{:#x}", self.pipeline), @@ -935,6 +945,12 @@ impl State { let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}")); #[cfg(not(feature = "diagnostics"))] let why = |_: &str| {}; + // Skip before the argument clamp can mutate the indirect buffer. + #[cfg(feature = "diagnostics")] + if crate::pipeline::is_skipped(self.pipeline as This) { + crate::pipeline::note_drop(self.pipeline as This); + return false; + } let len = u64::from(stride) * u64::from(max.max(1)); let Some(args) = crate::shadow::find(arguments, len) else { why("arguments outside title buffers"); diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index f351c9a..d488d03 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -207,19 +207,64 @@ pub(crate) fn making() -> u64 { make::waiting() } -/// Draws and dispatches dropped since the last [`take_drops`], by why their -/// pipeline has no host pipeline (diagnostics). +/// Draws and dispatches dropped since the last [`take_drops`], by reason +/// (diagnostics). #[cfg(all(windows, feature = "diagnostics"))] static DROPS: Mutex>> = Mutex::new(None); -/// Counts a draw or dispatch of `this` dropped for want of a host pipeline -/// (diagnostics). +/// Shader hashes as printed in the pipeline diagnostics. +#[cfg(all(windows, feature = "diagnostics"))] +fn parse_skip_hashes(value: &str) -> Vec { + value + .split(',') + .map(str::trim) + .filter(|hash| !hash.is_empty()) + .filter_map(|hash| { + if hash.len() == 16 && hash.bytes().all(|byte| byte.is_ascii_hexdigit()) { + Some(hash.to_ascii_lowercase()) + } else { + tracing::warn!( + hash, + "VICTORY_SKIP_PIPELINES expects 16-digit shader hashes" + ); + None + } + }) + .collect() +} + +#[cfg(all(windows, feature = "diagnostics"))] +fn skipped_shader(p: &Pipeline) -> Option<&str> { + static HASHES: OnceLock> = OnceLock::new(); + let hashes = HASHES.get_or_init(|| { + let value = std::env::var("VICTORY_SKIP_PIPELINES").unwrap_or_default(); + parse_skip_hashes(&value) + }); + if hashes.is_empty() { + return None; + } + p.shaders + .iter() + .find(|shader| hashes.contains(&shader.hash)) + .map(|shader| shader.hash.as_str()) +} + +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn is_skipped(this: This) -> bool { + !this.is_null() && skipped_shader(pipeline(this)).is_some() +} + +/// Counts a draw or dispatch of `this` intentionally skipped or dropped +/// for want of a host pipeline (diagnostics). #[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn note_drop(this: This) { let why = if this.is_null() { Some("no pipeline set".to_owned()) } else { - make::missing(&pipeline(this).host) + let p = pipeline(this); + skipped_shader(p) + .map(|hash| format!("skipped shader {hash}")) + .or_else(|| make::missing(&p.host)) }; if let Some(why) = why { note_why(why); @@ -458,6 +503,16 @@ pub fn save_pipeline_cache() { #[cfg(test)] mod tests { + #[cfg(all(windows, feature = "diagnostics"))] + #[test] + fn skip_hashes_accepts_full_hashes_only() { + assert!(super::parse_skip_hashes(" , ").is_empty()); + assert_eq!( + super::parse_skip_hashes(" 0123456789ABCDEF, 0123456789abcde, xyz, 0011223344556677,"), + ["0123456789abcdef", "0011223344556677"] + ); + } + use super::*; use crate::object::{S_OK, slot}; From c4e915f95ea9015214eba0c3fc1a4511d5a611f3 Mon Sep 17 00:00:00 2001 From: Henrique Bueno Date: Mon, 23 Nov 2026 21:11:33 -0300 Subject: [PATCH 033/445] loader: a clwb write-back loop runs in one exception --- crates/victory-loader/src/crash.rs | 165 ++++++++++++++++++++++++++++- 1 file changed, 161 insertions(+), 4 deletions(-) diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index c724af1..d067bf6 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -153,7 +153,29 @@ unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { [0x0f, 0x01, 0xfa] => {} [0x0f, 0x01, 0xfb] => std::thread::yield_now(), _ => { - if let Some(len) = clwb_len(code.cast::<[u8; 15]>().read_unaligned()) { + // Only bytes inside the faulting instruction's page are read: the next page may + // not be mapped. + let room = 0x1000 - (context.Rip as usize & 0xfff); + let mut bytes = [0u8; 32]; + let n = room.min(bytes.len()); + std::ptr::copy_nonoverlapping(code, bytes.as_mut_ptr(), n); + if let Some(pass) = clwb_loop(&bytes[..n]) { + // A whole write-back loop in one exception (see `clwb_loop`). + let limit = *gpr(context, pass.limit); + let base = gpr(context, pass.base); + *base = if *base <= limit { + base.wrapping_add(((limit - *base) / 64 + 1) * 64) + } else { + base.wrapping_add(64) + }; + let flags = cmp_flags(*base, limit); + context.EFlags = context.EFlags & !CMP_FLAGS | flags; + context.Rip += pass.len as u64; + return true; + } + if n >= 15 + && let Some(len) = clwb_len(bytes[..15].try_into().unwrap_or([0; 15])) + { // A write-back hint: the PC's memory is coherent, so it has nothing to do. context.Rip += len as u64; return true; @@ -197,13 +219,109 @@ fn clwb_len(code: [u8; 15]) -> Option { Some(len) } +/// A `clwb` write-back loop as the title's compilers build it, one cache line a +/// pass (`base` and `limit` any registers): +/// +/// ```text +/// top: clwb [base] +/// add base, 0x40 +/// cmp base, limit +/// jbe top +/// ``` +/// +/// An exception costs about a microsecond and the title writes back whole +/// buffers this way while it loads, so the loop is done in one: `clwb` has +/// nothing to do on the PC, `base` ends past `limit` as the last pass leaves it. +struct ClwbLoop { + base: u8, + limit: u8, + /// Bytes from `clwb` to the instruction after `jbe`. + len: usize, +} + +fn clwb_loop(code: &[u8]) -> Option { + // clwb [base]: 66 [40|41] 0f ae, ModRM mod 00, reg 6, no SIB or displacement. + let (rex, at) = match code.get(1)? { + 0x40 | 0x41 => (code[1], 2), + _ => (0, 1), + }; + if *code.first()? != 0x66 || code.get(at..at + 2)? != [0x0f, 0xae] { + return None; + } + let modrm = *code.get(at + 2)?; + let rm = modrm & 7; + if modrm >> 6 != 0 || (modrm >> 3) & 7 != 6 || rm == 4 || rm == 5 { + return None; + } + let base = rm | (rex & 1) << 3; + // add base, 0x40: REX.W(+B) 83 /0 ib. + let add = at + 3; + if *code.get(add..add + 4)? != [0x48 | base >> 3, 0x83, 0xc0 | (base & 7), 0x40] { + return None; + } + // cmp base, limit: REX.W 39 /r with base in r/m. + let cmp = add + 4; + let &[cmp_rex @ 0x48..=0x4f, 0x39, cmp_modrm] = code.get(cmp..cmp + 3)? else { + return None; + }; + if cmp_modrm >> 6 != 3 || (cmp_modrm & 7 | (cmp_rex & 1) << 3) != base { + return None; + } + let limit = (cmp_modrm >> 3) & 7 | (cmp_rex & 4) << 1; + // jbe top. + let jump = cmp + 3; + let len = jump + 2; + if *code.get(jump)? != 0x76 || i64::from(*code.get(jump + 1)? as i8) != -(len as i64) { + return None; + } + (limit != base).then_some(ClwbLoop { base, limit, len }) +} + +/// The general register numbered `n` as instructions encode it. +fn gpr(context: &mut CONTEXT, n: u8) -> &mut u64 { + match n & 15 { + 0 => &mut context.Rax, + 1 => &mut context.Rcx, + 2 => &mut context.Rdx, + 3 => &mut context.Rbx, + 4 => &mut context.Rsp, + 5 => &mut context.Rbp, + 6 => &mut context.Rsi, + 7 => &mut context.Rdi, + 8 => &mut context.R8, + 9 => &mut context.R9, + 10 => &mut context.R10, + 11 => &mut context.R11, + 12 => &mut context.R12, + 13 => &mut context.R13, + 14 => &mut context.R14, + _ => &mut context.R15, + } +} + +/// The status flags `cmp a, b` leaves (CF, PF, AF, ZF, SF, OF) as `EFLAGS` bits. +fn cmp_flags(a: u64, b: u64) -> u32 { + let r = a.wrapping_sub(b); + u32::from(a < b) + | u32::from((r as u8).count_ones().is_multiple_of(2)) << 2 + | (((a ^ b ^ r) >> 4) as u32 & 1) << 4 + | u32::from(r == 0) << 6 + | ((r >> 63) as u32) << 7 + | ((((a ^ b) & (a ^ r)) >> 63) as u32) << 11 +} +const CMP_FLAGS: u32 = 0x8d5; + /// SSE4a's `extrq`/`insertq` (register forms, the only ones there are) on /// the saved XMM registers; returns the instruction's length. unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option { // SAFETY: the caller's code bytes are readable up to the instruction's end. let b = |i: usize| unsafe { code.add(i).read() }; let prefix = b(0); - let (rex, at) = if b(1) & 0xf0 == 0x40 { (b(1), 2) } else { (0, 1) }; + let (rex, at) = if b(1) & 0xf0 == 0x40 { + (b(1), 2) + } else { + (0, 1) + }; if !matches!(prefix, 0x66 | 0xf2) || b(at) != 0x0f || !matches!(b(at + 1), 0x78 | 0x79) { return None; } @@ -489,6 +607,39 @@ mod tests { assert_eq!(ours, system); } + #[test] + fn clwb_loops() { + // clwb [rcx]; add rcx, 0x40; cmp rcx, rax; jbe top + let a = clwb_loop(&[ + 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40, 0x48, 0x39, 0xc1, 0x76, 0xf3, + ]) + .expect("rcx loop"); + assert_eq!((a.base, a.limit, a.len), (1, 0, 13)); + // clwb [r9]; add r9, 0x40; cmp r9, rax; jbe top + let b = clwb_loop(&[ + 0x66, 0x41, 0x0f, 0xae, 0x31, 0x49, 0x83, 0xc1, 0x40, 0x49, 0x39, 0xc1, 0x76, 0xf2, + ]) + .expect("r9 loop"); + assert_eq!((b.base, b.limit, b.len), (9, 0, 14)); + // A different stride, a jump elsewhere, or a cut-off loop is not one. + assert!( + clwb_loop(&[ + 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x20, 0x48, 0x39, 0xc1, 0x76, 0xf3 + ]) + .is_none() + ); + assert!( + clwb_loop(&[ + 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40, 0x48, 0x39, 0xc1, 0x76, 0xf0 + ]) + .is_none() + ); + assert!(clwb_loop(&[0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40]).is_none()); + // The flags the last cmp leaves: base just past limit. + assert_eq!(cmp_flags(0x1040, 0x1000) & 0x41, 0); // CF and ZF clear: the loop ends + assert_eq!(cmp_flags(0x1000, 0x1000) & 0x40, 0x40); + } + #[test] fn clwb_lengths() { let pad = |b: &[u8]| { @@ -499,9 +650,15 @@ mod tests { assert_eq!(clwb_len(pad(&[0x66, 0x41, 0x0f, 0xae, 0x31])), Some(5)); // clwb [r9] assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x30])), Some(4)); // clwb [rax] assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x70, 0x40])), Some(5)); // clwb [rax+0x40] - assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0xb0, 0, 1, 0, 0])), Some(8)); // [rax+disp32] + assert_eq!( + clwb_len(pad(&[0x66, 0x0f, 0xae, 0xb0, 0, 1, 0, 0])), + Some(8) + ); // [rax+disp32] assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x34, 0x24])), Some(5)); // clwb [rsp] - assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x35, 0, 0, 0, 0])), Some(8)); // [rip+disp32] + assert_eq!( + clwb_len(pad(&[0x66, 0x0f, 0xae, 0x35, 0, 0, 0, 0])), + Some(8) + ); // [rip+disp32] assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x38])), None); // clflushopt, /7 assert_eq!(clwb_len(pad(&[0x0f, 0xae, 0x30])), None); // xsaveopt, no 66 assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0xf0])), None); // register form From 9a5cbbeb64066d721274d14b75426c74e8bea791 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 01:15:10 +0100 Subject: [PATCH 034/445] fix: skip unused export address slots instead of reporting them at RVA 0 --- crates/victory-pe/src/image.rs | 74 ++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/crates/victory-pe/src/image.rs b/crates/victory-pe/src/image.rs index 4acc6e3..8885761 100644 --- a/crates/victory-pe/src/image.rs +++ b/crates/victory-pe/src/image.rs @@ -331,6 +331,9 @@ fn parse_exports(file: &PeFile64<'_>) -> Result, PeError> { Ok(table .exports()? .into_iter() + // An address of 0 marks an unused slot in the address table (a gap + // in the ordinals), not an export at the image base. + .filter(|e| !matches!(e.target, ExportTarget::Address(0))) .map(|e| { let (rva, forward) = match e.target { ExportTarget::Address(rva) => (Some(rva), None), @@ -458,6 +461,77 @@ mod tests { Err(PeError::Malformed(_)) )); } + /// A minimal PE32+ image: one section at RVA 0x1000 holding `body`, with + /// the export directory (RVA 0x1000, 0x80 bytes) pointing at it. + fn synthetic_image(body: &[u8]) -> Vec { + let mut d = vec![0u8; 0x200]; + d[0..2].copy_from_slice(b"MZ"); + d[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes()); + d[0x40..0x44].copy_from_slice(b"PE\0\0"); + d[0x44..0x46].copy_from_slice(&MACHINE_AMD64.to_le_bytes()); + d[0x46..0x48].copy_from_slice(&1u16.to_le_bytes()); // sections + d[0x54..0x56].copy_from_slice(&240u16.to_le_bytes()); // optional header size + d[0x56..0x58].copy_from_slice(&0x2022u16.to_le_bytes()); // DLL, large address aware + let opt = 0x58; + d[opt..opt + 2].copy_from_slice(&0x20Bu16.to_le_bytes()); + d[opt + 24..opt + 32].copy_from_slice(&0x1_8000_0000u64.to_le_bytes()); + d[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes()); + d[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes()); + d[opt + 56..opt + 60].copy_from_slice(&0x2000u32.to_le_bytes()); + d[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes()); + d[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes()); + d[opt + 112..opt + 116].copy_from_slice(&0x1000u32.to_le_bytes()); + d[opt + 116..opt + 120].copy_from_slice(&0x80u32.to_le_bytes()); + let sec = opt + 240; + d[sec..sec + 6].copy_from_slice(b".edata"); + d[sec + 8..sec + 12].copy_from_slice(&0x200u32.to_le_bytes()); // virtual size + d[sec + 12..sec + 16].copy_from_slice(&0x1000u32.to_le_bytes()); + d[sec + 16..sec + 20].copy_from_slice(&0x200u32.to_le_bytes()); // raw size + d[sec + 20..sec + 24].copy_from_slice(&0x200u32.to_le_bytes()); // raw offset + d.extend_from_slice(body); + d.resize(0x400, 0); + d + } + + #[test] + fn unused_export_slots_are_not_exports() { + // Ordinal base 1; three address slots: "alpha", an unused hole (0), + // and "gamma". The Windows loader treats address 0 as "not exported". + let mut body = vec![0u8; 0x100]; + let put32 = + |b: &mut Vec, at: usize, v: u32| b[at..at + 4].copy_from_slice(&v.to_le_bytes()); + put32(&mut body, 12, 0x1040); // name of the DLL + put32(&mut body, 16, 1); // ordinal base + put32(&mut body, 20, 3); // number of functions + put32(&mut body, 24, 2); // number of names + put32(&mut body, 28, 0x1028); // address table + put32(&mut body, 32, 0x1034); // name pointer table + put32(&mut body, 36, 0x103C); // name ordinal table + put32(&mut body, 0x28, 0x1200); + put32(&mut body, 0x2C, 0); + put32(&mut body, 0x30, 0x1204); + put32(&mut body, 0x34, 0x1044); + put32(&mut body, 0x38, 0x104A); + body[0x3C..0x3E].copy_from_slice(&0u16.to_le_bytes()); + body[0x3E..0x40].copy_from_slice(&2u16.to_le_bytes()); + body[0x40..0x44].copy_from_slice(b"t.dl"); + body[0x44..0x4A].copy_from_slice(b"alpha\0"); + body[0x4A..0x50].copy_from_slice(b"gamma\0"); + + let info = ImageInfo::parse(&synthetic_image(&body)).unwrap(); + let exports: Vec<_> = info + .exports + .iter() + .map(|e| (e.name.as_deref(), e.ordinal, e.rva)) + .collect(); + assert_eq!( + exports, + [ + (Some("alpha"), 1, Some(0x1200)), + (Some("gamma"), 3, Some(0x1204)) + ] + ); + } } #[cfg(test)] From 4c1766c235492291718a96d6e3a2f92de934affc Mon Sep 17 00:00:00 2001 From: Exorion <8749995+Exorion1er@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:15:23 +0100 Subject: [PATCH 035/445] GPU: keep a guarded block's write fault from being declined in a race The write-fault handler opens the guarded block under the guard lock, then, if it found none, asks whether the address is writable without it. Between the two, another thread's fault could open the block and a copy could guard it again: the handler then saw a read-only block that is in fact ours, declined the fault, and the title crashed on a plain write (seen 1-3 minutes into the world under Wine, where exception dispatch is slow enough to hit it every run). The lock is now held across both checks, so a block that is not ours while it is held really is not ours. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/watch.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index a64e3e3..1cbe2b7 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -247,12 +247,15 @@ fn install() { return EXCEPTION_CONTINUE_SEARCH; } let at = r.ExceptionInformation[1]; - if open(&mut guards(), at, at + 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) { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::GuardFaults, 1); return EXCEPTION_CONTINUE_EXECUTION; } - // Another thread may have opened the block since this one faulted. if writable(at) { EXCEPTION_CONTINUE_EXECUTION } else { From 73d776b9c9915867eaa8e495f0e7cb99d0924220 Mon Sep 17 00:00:00 2001 From: TG0000 <122870448+TG0000@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:16:34 +0100 Subject: [PATCH 036/445] GPU: check a sampled texture once per submission, not once per list A title texture's staging refresh ran as a host step of every list that sampled it. When several lists in one submission sampled the same texture, it was checked again for each of them. In physical-page memory, which cannot be write-watched, each check is a VirtualQuery walk and a blake3 hash of the whole texture. Every list's GPU copy reads the same staging buffer after all submission-time steps have run, so checks after the first one in a submission did nothing unless title memory had been written in between. Texture refreshes are now their own step. The submission's Batch, which already merges buffer refreshes, records the staging buffers it has refreshed. A Copy into title memory or a Run step (work that may write title memory) clears that record, so a texture is checked again after any such write, as buffer refreshes are. A synthetic benchmark (ignored test, release build, 12 lists sampling 48 textures of 4 MiB): 576 hashes in ~690 ms before, 48 in ~60 ms after (~11x). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 127 ++++++++++++++++++++++++++++-- crates/victory-gpu/src/texture.rs | 7 +- 2 files changed, 125 insertions(+), 9 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index d89159e..a42c9a2 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -333,6 +333,9 @@ enum Step { Host(Box), /// Shaders write a range (address, bytes) of a buffer's host copy. GpuWrite(std::sync::Arc, usize, usize), + /// Brings a texture's staging buffer up to date: once per submission, + /// whichever lists sample it, until a `Copy` or `Run` intervenes. + Texture(std::sync::Arc), } /// What a list does on the CPU when it is submitted: copies between host @@ -1101,6 +1104,12 @@ impl HostList { self.deferred().copies.push(Step::Host(Box::new(work))); } + /// Brings a texture's staging buffer up to date when the list is + /// submitted, keeping it alive until the list is reset. + pub(crate) fn defer_texture(&self, staging: std::sync::Arc) { + self.deferred().copies.push(Step::Texture(staging)); + } + /// Runs the list's submission-time steps; refreshes go into `batch` /// (the title's big buffers, a 174 MB one among them, are read by most /// lists of a submission, through many ranges). @@ -1116,7 +1125,7 @@ impl HostList { add(C::Copies, 1); add(C::CopyBytes, len as u64); } - batch.flush(); + batch.title_written(); copy_mapped(dst as *mut u8, src as *const u8, len, true); len } @@ -1140,7 +1149,7 @@ impl HostList { } Step::Run(work) | Step::Host(work) => { if matches!(step, Step::Run(_)) { - batch.flush(); + batch.title_written(); } work(); #[cfg(feature = "diagnostics")] @@ -1156,6 +1165,12 @@ impl HostList { shadow.writing(*address, *len); continue; } + Step::Texture(staging) => { + if batch.texture_due(staging) { + staging.refresh(); + } + continue; + } }; PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); @@ -1166,20 +1181,46 @@ impl HostList { /// A submission's refreshes not done yet, merged per buffer copy into the /// range that covers them: done before a step that writes title memory or /// gives a range to shaders, and before the lists run. +/// +/// Also the textures brought up to date in the submission so far: most +/// lists of a world submission sample the same textures, and a texture in +/// physical-page memory is hashed whole each time it is checked. Checked +/// once, it is checked again only after a step that writes title memory. #[derive(Default)] -struct Batch(Vec<(std::sync::Arc, usize, usize)>); +struct Batch { + refreshes: Vec<(std::sync::Arc, usize, usize)>, + /// Staging buffers (by address) refreshed since the last title write. + textures: std::collections::HashSet, +} impl Batch { fn add(&mut self, shadow: &std::sync::Arc, address: usize, len: usize) { let end = address + len; - match self.0.iter_mut().find(|(s, ..)| std::sync::Arc::ptr_eq(s, shadow)) { + match self + .refreshes + .iter_mut() + .find(|(s, ..)| std::sync::Arc::ptr_eq(s, shadow)) + { Some((_, from, to)) => (*from, *to) = ((*from).min(address), (*to).max(end)), - None => self.0.push((shadow.clone(), address, end)), + None => self.refreshes.push((shadow.clone(), address, end)), } } + /// Whether `staging` is still to be refreshed in this submission (and + /// notes it refreshed). + fn texture_due(&mut self, staging: &std::sync::Arc) -> bool { + self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize) + } + + /// Before a step that writes title memory: pending refreshes are done + /// first, and textures are checked again after it. + fn title_written(&mut self) { + self.flush(); + self.textures.clear(); + } + fn flush(&mut self) { - for (shadow, from, to) in self.0.drain(..) { + for (shadow, from, to) in self.refreshes.drain(..) { let started = std::time::Instant::now(); let copied = shadow.update(from, to - from); let us = started.elapsed().as_micros() as u64; @@ -1879,3 +1920,77 @@ fn pump() { } } } + +#[cfg(test)] +mod tests { + use super::Batch; + use std::sync::Arc; + + #[test] + fn a_texture_is_checked_once_per_submission() { + let mut batch = Batch::default(); + let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16])); + // The first list sampling each texture checks it ... + assert!(batch.texture_due(&a)); + assert!(batch.texture_due(&b)); + // ... later lists of the same submission do not. + assert!(!batch.texture_due(&a)); + assert!(!batch.texture_due(&a.clone())); + assert!(!batch.texture_due(&b)); + } + + #[test] + fn title_writes_make_textures_due_again() { + let mut batch = Batch::default(); + let a = Arc::new(1u32); + assert!(batch.texture_due(&a)); + assert!(!batch.texture_due(&a)); + // A copy into title memory or work that may write it may have + // changed the texture's memory. + batch.title_written(); + assert!(batch.texture_due(&a)); + assert!(!batch.texture_due(&a)); + // A fresh submission starts over. + let mut next = Batch::default(); + assert!(next.texture_due(&a)); + } + + /// The hashing a submission does for textures in physical-page memory, + /// with every list checking the textures it samples (before) and with + /// each checked once (after). Run with + /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`. + #[test] + #[ignore = "benchmark"] + fn texture_checks_per_submission() { + const TEXTURES: usize = 48; + const SIZE: usize = 4 << 20; + const LISTS: usize = 12; + let textures: Vec>> = (0..TEXTURES) + .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect())) + .collect(); + let submit = |dedupe: bool| { + let mut batch = Batch::default(); + let mut hashed = 0usize; + let started = std::time::Instant::now(); + for _ in 0..LISTS { + for t in &textures { + if !dedupe || batch.texture_due(t) { + std::hint::black_box(blake3::hash(t)); + hashed += 1; + } + } + } + (started.elapsed(), hashed) + }; + submit(false); // warm up + let (before, n_before) = submit(false); + let (after, n_after) = submit(true); + assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES)); + println!( + "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \ + before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)", + SIZE >> 20, + before.as_secs_f64() / after.as_secs_f64() + ); + } +} diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 30193d5..60eab0c 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -32,7 +32,7 @@ macro_rules! once { /// A texture's upload state: the staging buffer laid out as the host /// texture's subresources, and what was last detiled. -struct Staging { +pub(crate) struct Staging { buffer: ID3D12Resource, /// Its bytes. #[cfg(feature = "diagnostics")] @@ -165,13 +165,14 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) // SAFETY: an open list; both locations name live resources. unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; } - list.defer_host(move || staging.refresh()); + // Once per submission however many of its lists sample the texture. + list.defer_texture(staging); } impl Staging { /// Detiles the texture memory into the staging buffer if it changed /// since the last time (and is mapped at all). - fn refresh(&self) { + pub(crate) fn refresh(&self) { use std::sync::atomic::Ordering::Relaxed; let started = std::time::Instant::now(); let read = self.refresh_now(); From c963b7168d6354783410a6b5fe48940eeb75cf21 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 01:17:00 +0100 Subject: [PATCH 037/445] fix: read a far jump's offset as signed so backward far jumps decode --- crates/victory-shader/src/gfx10/mod.rs | 31 +++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/gfx10/mod.rs b/crates/victory-shader/src/gfx10/mod.rs index 5d6cf6a..f029ff4 100644 --- a/crates/victory-shader/src/gfx10/mod.rs +++ b/crates/victory-shader/src/gfx10/mod.rs @@ -175,7 +175,9 @@ fn far_jump<'a>( (Encoding::Sop2, Some(op @ ("s_add_u32" | "s_sub_u32"))) if sdst == n && ssrc0 == n && ssrc1 == 0xFF && delta.is_none() => { - let literal = i64::from(prev.words[1]); + // The low dword of a signed 64-bit offset: a backward jump + // adds a negative one (its high dword is -1). + let literal = i64::from(prev.words[1] as i32); delta = Some(if op == "s_add_u32" { literal } else { -literal }); } (Encoding::Sop1, Some("s_getpc_b64")) if sdst == n => { @@ -446,6 +448,33 @@ mod tests { assert_eq!(summary(&[0xBE80_2018, S_ENDPGM]).len(), 1); } + #[test] + fn follows_far_jumps_backward() { + // The compiler's backward far jump adds a negative offset: the low + // dword as a 32-bit literal, the high dword as -1 with the carry. + let code = [ + sopp(0x02, 1), // s_branch -> 8, past the jump target + S_ENDPGM, // the far jump's target: only it reaches here + 0xBE88_1F00, // s_getpc_b64 s[8:9] + 0x8008_FF08, + 0xFFFF_FFF8, // s_add_u32 s8, s8, -8 -> 12 - 8 = 4 + 0x8209_C109, // s_addc_u32 s9, s9, -1 + 0xBE80_2008, // s_setpc_b64 s[8:9] + ]; + let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect(); + assert_eq!( + found, + [ + (0, "s_branch"), + (4, "s_endpgm"), + (8, "s_getpc_b64"), + (12, "s_add_u32"), + (20, "s_addc_u32"), + (24, "s_setpc_b64"), + ] + ); + } + #[test] fn rejects_bad_code() { assert!(decode(&[0; 3]).is_err(), "size not a multiple of 4"); From a2f5f4351dff5af82f9d5eb5e262019293234705 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 01:17:24 +0100 Subject: [PATCH 038/445] Shaders: set SCC from the carry of s_addc_u32 and s_subb_u32 Both returned no carry, so SCC was missing and a branch or select on a 64-bit scalar add or subtract failed to translate. They now share the carry logic of v_add_co_ci_u32 and v_sub_co_ci_u32. --- crates/victory-shader/src/emit/lower.rs | 128 ++++++++++++++++++------ 1 file changed, 98 insertions(+), 30 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 1f6ab71..5e9f338 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2508,15 +2508,8 @@ impl<'a> Lower<'a> { "s_addc_u32" | "s_subb_u32" => { let (a, b) = (src32(self, 0)?, src32(self, 1)?); let cin = self.scc_in(inst)?; - let cin32 = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32); - let op = if name == "s_addc_u32" { - Bin::Add - } else { - Bin::Sub - }; - let t = self.s.m.bin(c, op, a, b); - let r = self.s.m.bin(c, op, t, cin32); - (r, None) + let (r, carry) = self.add_sub_carry(c, name == "s_addc_u32", a, b, Some(cin)); + (r, Some(carry)) } "s_mul_i32" | "s_mulk_i32" => { let a = src32(self, 0)?; @@ -2667,6 +2660,31 @@ impl<'a> Lower<'a> { Ok(()) } + /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the + /// scalar and vector add-with-carry instructions set it. + fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option) -> (V, V) { + let op = if add { Bin::Add } else { Bin::Sub }; + let mut r = self.s.m.bin(c, op, a, b); + // Without a carry in: a + b wraps below a; a - b borrows when a < b. + let mut carry = if add { + self.s.m.cmp(c, pred::IULT, r, a) + } else { + self.s.m.cmp(c, pred::IULT, a, b) + }; + if let Some(cin) = cin { + let one = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32); + let t = r; + r = self.s.m.bin(c, op, t, one); + // The carry in carries on when the partial result is all ones + // (add) or zero (sub). + let edge = self.s.m.i32(if add { u32::MAX } else { 0 }); + let at_edge = self.s.m.cmp(c, pred::EQ, t, edge); + let more = self.s.m.bin(c, Bin::And, cin, at_edge); + carry = self.s.m.bin(c, Bin::Or, carry, more); + } + (r, carry) + } + fn scc_in(&mut self, inst: &Inst) -> Result { let v = inst.read(Reg::Scc).ok_or("an unread SCC")?; match self.get(v)? { @@ -3900,26 +3918,7 @@ impl<'a> Lower<'a> { } else { None }; - let add = name.starts_with("v_add"); - let op = if add { Bin::Add } else { Bin::Sub }; - let mut r = self.s.m.bin(c, op, a, bb); - // Without a carry in: a + b wraps below a; a - b borrows when a < b. - let mut carry = if add { - self.s.m.cmp(c, pred::IULT, r, a) - } else { - self.s.m.cmp(c, pred::IULT, a, bb) - }; - if let Some(cin) = cin { - let one = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32); - let t = r; - r = self.s.m.bin(c, op, t, one); - // The carry in carries on when the partial result is all - // ones (add) or zero (sub). - let edge = self.s.m.i32(if add { u32::MAX } else { 0 }); - let at_edge = self.s.m.cmp(c, pred::EQ, t, edge); - let more = self.s.m.bin(c, Bin::And, cin, at_edge); - carry = self.s.m.bin(c, Bin::Or, carry, more); - } + let (r, carry) = self.add_sub_carry(c, name.starts_with("v_add"), a, bb, cin); int(self, r)?; if let Some(Operand::Scalar { code, .. }) = v.carry && let Some(w) = inst.write(Reg::S(code)) @@ -6522,7 +6521,76 @@ impl<'a> Lower<'a> { #[cfg(test)] mod tests { - use super::{Numeric, buffer_format}; + use super::{Numeric, Parts, buffer_format, lower}; + use crate::native::{ComputeIo, HwStage, NativeProgram, StageIo}; + use crate::{io, ir, resource, structure}; + + const S_ENDPGM: u32 = 0xBF81_0000; + + /// Lowers a compute program of constants: whether it translates. + fn lowers(words: &[u32]) -> Result<(), crate::ShaderError> { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 0, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + .map(|_| ()) + } + + #[test] + fn a_scalar_carry_chain_reaches_the_select() { + // The high dword of a 64-bit add or subtract, then a select on the + // carry (borrow) the high half leaves in SCC, and a branch on it + // (only code with an effect needs its operands). + let add = [ + 0xBE80_03C1, // s_mov_b32 s0, -1 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8000_8100, // s_add_u32 s0, s0, 1 + 0x8201_8001, // s_addc_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + let sub = [ + 0xBE80_0380, // s_mov_b32 s0, 0 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8080_8100, // s_sub_u32 s0, s0, 1 + 0x8281_8001, // s_subb_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + for words in [add, sub] { + lowers(&words).unwrap(); + } + } #[test] fn buffer_formats_by_number() { From b304b7ddbfb916c1e822bd2dc3ad4fc9ae696af9 Mon Sep 17 00:00:00 2001 From: Jeremy Goldberg Date: Mon, 23 Nov 2026 19:21:40 -0500 Subject: [PATCH 039/445] fix(gpu): average copy statistics over the full reporting interval --- crates/victory-gpu/src/host.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index d89159e..b06be74 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1376,6 +1376,8 @@ struct Presenter { struct Meter { since: std::time::Instant, frames: u32, + #[cfg(feature = "diagnostics")] + copy_stats_frames: u64, drawn: u64, logged: std::time::Instant, /// The caption the window had, once read. @@ -1388,6 +1390,8 @@ impl Meter { Meter { since: now, frames: 0, + #[cfg(feature = "diagnostics")] + copy_stats_frames: 0, drawn: crate::draw::drawn(), logged: now, caption: None, @@ -1399,6 +1403,10 @@ impl Meter { #[cfg(feature = "diagnostics")] tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present"); self.frames += 1; + #[cfg(feature = "diagnostics")] + { + self.copy_stats_frames += 1; + } let elapsed = self.since.elapsed(); if elapsed < std::time::Duration::from_secs(1) { return; @@ -1437,7 +1445,7 @@ impl Meter { ); #[cfg(feature = "diagnostics")] { - crate::copystat::log(frames); + crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64); for (why, n) in drops.iter().take(40) { tracing::info!( "dropped {:.1}/frame without a host pipeline: {why}", From 257d8bbab241c096625ccca7ff24b8a551e3ab36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9rez?= Date: Tue, 24 Nov 2026 01:21:41 +0100 Subject: [PATCH 040/445] Audio: reduce the title's XMA read advance before adding it ADVANCE_XMA_READ added the title's block count to the 5-bit read block in u32 before taking it modulo the ring size, so a count near u32::MAX overflowed (a panic in debug builds). The count is reduced modulo the ring first; the result is the same for every count that did not overflow. Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/audio.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index 0a11195..4bd223a 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -471,7 +471,8 @@ impl Xma { // The decoder writes the same words. let mut slot = lock(&self.voices[index as usize]); let size = context.field(0, 22, 5).max(1); - let read = (context.field(9, 0, 5) + blocks) % size; + // The count is the title's: reduced first, so the sum stays small. + let read = (context.field(9, 0, 5) + blocks % size) % size; context.set_field(9, 0, 5, read); if blocks > 0 { context.set_field(1, 31, 1, 1); @@ -1062,6 +1063,13 @@ mod tests { assert_eq!(context.field(0, 20, 2), 0, "input used up"); assert_eq!(context.field(2, 26, 5), INPUT_INVALID); + // A count near `u32::MAX` wraps the read block like any other + // (3 + 0xffff_ffff blocks on a ring of four is block 2); the sum + // used to overflow. + context.set_field(9, 0, 5, 3); + submit(ADVANCE_XMA_READ, &[1, u32::MAX]); + assert_eq!(context.field(9, 0, 5), 2); + submit(DISABLE_XMA, &[1]); assert_eq!(produced(&xma()), None); (m.release)(acp); From ec0d15592530c535bdb049aeb5831fe7b1ef80d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9rez?= Date: Tue, 24 Nov 2026 01:21:42 +0100 Subject: [PATCH 041/445] Watch: saturate the end of announced writes and remaps kernel_will_write (fread's size times count, saturated) and title_memory_remapped added the length to the address unchecked, so a huge fread count overflowed (a panic in debug builds). The end now saturates at the top of the address space. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/watch.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index a64e3e3..2012acd 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -210,7 +210,8 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { /// The runtime calls it (as `kernel_will_write`) before the title's kernel /// reads into its own memory. pub fn writing(at: usize, len: usize) { - open(&mut guards(), at, at + len); + // The length is the title's (`fread`'s size times count, saturated). + open(&mut guards(), at, at.saturating_add(len)); } /// The runtime mapped or unmapped title memory `[at, at + len)`: what it @@ -219,7 +220,7 @@ pub fn title_memory_remapped(at: usize, len: usize) { let mut g = guards(); let blocks: Vec = g .protected - .range(at / BLOCK..(at + len).div_ceil(BLOCK)) + .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) .copied() .collect(); for block in blocks { @@ -364,4 +365,14 @@ mod tests { unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) }; title_memory_remapped(view, 2 * BLOCK); } + + /// A write or mapping that runs past the end of the address space (a + /// title's `fread` with a huge count) covers up to the end; the sum used + /// to overflow. Up there no test has guarded blocks. + #[test] + fn ranges_past_the_address_space_end_do_not_overflow() { + let top = usize::MAX - 16; + writing(top, PAGE); + title_memory_remapped(top, usize::MAX); + } } From 38ae55dc1328535c18890cf8edf5563d79e39c78 Mon Sep 17 00:00:00 2001 From: FIocker <4461558+FIocker@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:22:49 +0100 Subject: [PATCH 042/445] Keep the diagnostic skip outside indirect argument validation --- crates/victory-gpu/src/draw.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 5f1f034..b6e043b 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -937,6 +937,12 @@ impl State { arguments: u64, count: Option, ) -> bool { + // Skip before the argument clamp can mutate the indirect buffer. + #[cfg(feature = "diagnostics")] + if crate::pipeline::is_skipped(self.pipeline as This) { + crate::pipeline::note_drop(self.pipeline as This); + return false; + } const DRAW: u32 = 0; const INDEXED: u32 = 1; const DISPATCH: u32 = 2; @@ -945,12 +951,6 @@ impl State { let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}")); #[cfg(not(feature = "diagnostics"))] let why = |_: &str| {}; - // Skip before the argument clamp can mutate the indirect buffer. - #[cfg(feature = "diagnostics")] - if crate::pipeline::is_skipped(self.pipeline as This) { - crate::pipeline::note_drop(self.pipeline as This); - return false; - } let len = u64::from(stride) * u64::from(max.max(1)); let Some(args) = crate::shadow::find(arguments, len) else { why("arguments outside title buffers"); From 3e982f7ec436003226c134315f993d2bf23b9286 Mon Sep 17 00:00:00 2001 From: TG0000 <122870448+TG0000@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:24:21 +0100 Subject: [PATCH 043/445] BCPack: find a slot's bucket from a window table Each rANS symbol scanned all of its model's bucket starts to find the slot's bucket, then rebuilt the symbol's frequency and start from the symbol. A per-model table of the bucket at each 256-slot window's first slot now starts the search, which steps over the few buckets that begin inside the window; the symbol, frequency and remainder come straight from that bucket. The lane loop also keeps the record offset instead of dividing by the symbols per block on every symbol. Synthetic streams, release, one core (median of 3 runs, 16384 blocks): BC1 177 -> 128 ns/block, BC4 184 -> 128, BC7 591 -> 452. Tests: the window lookup against the scan for every slot of every model (shipped tables, uniform tables, one-slot buckets); a payload step against the first version's arithmetic on the shipped tables; every format's lane layout round trips at 1 to 1000 blocks; an ignored throughput benchmark. Co-Authored-By: Claude Opus 5.5 --- crates/victory-formats/src/bcpack.rs | 251 ++++++++++++++++++++++++--- 1 file changed, 223 insertions(+), 28 deletions(-) diff --git a/crates/victory-formats/src/bcpack.rs b/crates/victory-formats/src/bcpack.rs index cb4ea53..360dce1 100644 --- a/crates/victory-formats/src/bcpack.rs +++ b/crates/victory-formats/src/bcpack.rs @@ -80,7 +80,12 @@ struct Bc7Ix { /// The format's constant tables. pub struct Tables { freq: [[u32; BUCKETS]; MODELS], - start: [[u32; BUCKETS]; MODELS], + /// Each bucket's first slot; 65536 past the model's last, and one more + /// 65536 at the end so a bucket always has a next start. + start: [[u32; BUCKETS + 1]; MODELS], + /// Per model, the bucket of the first slot of each 256-slot window: the + /// search for a slot's bucket starts there and seldom moves on. + bucket: Box<[[u8; 256]; MODELS]>, /// ceil(2^32 / freq): exact division for the offsets inside a bucket. recip: [[u64; BUCKETS]; MODELS], rank1: [u8; 256], @@ -132,7 +137,8 @@ impl Tables { } let mut r = Reader(bytes); let mut freq = [[0u32; BUCKETS]; MODELS]; - let mut start = [[0u32; BUCKETS]; MODELS]; + let mut start = [[0u32; BUCKETS + 1]; MODELS]; + let mut bucket = Box::new([[0u8; 256]; MODELS]); let mut recip = [[0u64; BUCKETS]; MODELS]; for m in 0..MODELS { for f in &mut freq[m] { @@ -153,6 +159,10 @@ impl Tables { return Err(Error("a model does not tile 65536")); } start[m][used..].fill(1 << 16); + for (window, b) in bucket[m].iter_mut().enumerate() { + let first = (window as u32) << 8; + *b = start[m][1..].iter().filter(|&&s| s <= first).count() as u8; + } } let rank1 = r.bytes(); let rank3a = r.bytes(); @@ -221,6 +231,7 @@ impl Tables { Ok(Tables { freq, start, + bucket, recip, rank1, rank3a, @@ -342,33 +353,20 @@ impl Lane { let start = &t.start[usize::from(self.model)]; let slot = x & 0xffff; // The bucket: starts are ascending, and 65536 past the model's last. - let b = start[1..].iter().filter(|&&s| s <= slot).count(); - // Buckets 0 and 1 hold one symbol. Elsewhere offset and frequency - // are below 2^16, where the reciprocal divides exactly. - let sym = match b { - 0 => 0, - 1 => 1, - _ => { - let rec = t.recip[usize::from(self.model)][b]; - (1 << (b - 1)) + ((u64::from(slot - start[b]) * rec) >> 32) as u8 - } - }; - // Slot 0 is never used: symbol 0 owns 1 .. f[0] - 1. - let (f, c) = if sym == 0 { - (freq[0] - 1, 1) + let b = bucket_of(t, self.model, slot); + // Bucket 0 holds symbol 0, which owns slots 1 .. f[0] - 1 (slot 0 + // is never used). Bucket b > 0 holds 2^(b-1) symbols of frequency + // f[b] from start[b] on; offset and frequency are below 2^16, where + // the reciprocal divides exactly. + let (sym, f, rem) = if b == 0 { + (0, freq[0] - 1, slot.wrapping_sub(1)) } else { - let k = (8 - sym.leading_zeros()) as usize; - let f = freq[k]; - ( - f, - (u32::from(sym) - (1 << (k - 1))) - .wrapping_mul(f) - .wrapping_add(start[k]) - & 0xffff, - ) + let offset = slot - start[b]; + let q = ((u64::from(offset) * t.recip[usize::from(self.model)][b]) >> 32) as u32; + ((1u32 << (b - 1)) + q, freq[b], offset - q * freq[b]) }; - self.x = (x >> 16).wrapping_mul(f).wrapping_sub(c).wrapping_add(slot); - self.out = Some(sym); + self.x = (x >> 16).wrapping_mul(f).wrapping_add(rem); + self.out = Some(sym as u8); } else if self.left != 0 { // At exactly 2^24 the lane neither reads nor decodes again; only a // lane that has delivered its symbols may end up there. @@ -385,6 +383,19 @@ impl Lane { } } +/// The bucket holding `slot` (below 65536): the last whose start is at or +/// below it. The window table gives the bucket of the window's first slot; +/// later buckets that start inside the window are stepped over. +#[inline] +fn bucket_of(t: &Tables, model: u8, slot: u32) -> usize { + let start = &t.start[usize::from(model)]; + let mut b = usize::from(t.bucket[usize::from(model)][(slot >> 8) as usize]); + while start[b + 1] <= slot { + b += 1; + } + b +} + /// Decodes `per` symbols per block on every lane into `records` (one record /// of `widths.len() * per` symbols per block), taking input from `fetch` /// (given the lane that takes the byte) in the order of the schedule: each @@ -409,6 +420,8 @@ fn lanes( let stride = widths.len() * per; let full = (1u32 << widths.len()) - 1; let (mut pos, mut done, mut idle) = (0, 0u32, 0); + // Where symbol `pos` of lane 0 goes; lane j's is `per * j` further on. + let mut at = 0; while pos < blocks * per { let (mut taken, mut moved) = (0, false); for (j, lane) in lanes.iter_mut().enumerate() { @@ -429,13 +442,18 @@ fn lanes( if !lane.stalled && let Some(sym) = lane.out.take() { - records[pos / per * stride + j * per + pos % per] = sym; + records[at + j * per] = sym; done |= bit; moved = true; } } if done == full { pos += 1; + at += if pos.is_multiple_of(per) { + stride - per + 1 + } else { + 1 + }; done = 0; moved = true; } @@ -1369,6 +1387,183 @@ mod tests { } } + /// The window table finds the bucket a scan of the starts finds, for + /// every slot of every model, in the shipped tables and in ours (whose + /// buckets are wide) and in tables whose buckets are one slot wide. + #[test] + fn bucket_lookup_matches_a_scan_of_the_starts() { + let mut narrow = tables(); + for m in 0..MODELS { + // Buckets 1.. of one slot each where they fit; bucket 0 takes the rest. + let used = m / 16 + 2; + let rest = (1u32 << 16) - (1..used).map(|b| 1u32 << (b - 1)).sum::(); + for b in 0..used { + let f = if b == 0 { rest } else { 1 }; + narrow[(m * BUCKETS + b) * 2..][..2].copy_from_slice(&(f as u16).to_le_bytes()); + } + } + for t in [ + Tables::builtin().unwrap(), + Tables::parse(&tables()).unwrap(), + Tables::parse(&narrow).unwrap(), + ] { + for model in 0..MODELS as u8 { + let start = &t.start[usize::from(model)]; + for slot in 0..1u32 << 16 { + let scan = start[1..].iter().filter(|&&s| s <= slot).count(); + assert_eq!( + bucket_of(&t, model, slot), + scan, + "model {model} slot {slot}" + ); + } + } + } + } + + /// One rANS decode as first written: scan for the bucket, divide for the + /// symbol, rebuild its frequency and start from the symbol. + fn reference_decode(t: &Tables, model: u8, x: u32) -> (u8, u32) { + let (freq, start) = (&t.freq[usize::from(model)], &t.start[usize::from(model)]); + let slot = x & 0xffff; + let b = start[1..BUCKETS].iter().filter(|&&s| s <= slot).count(); + let sym = match b { + 0 => 0, + 1 => 1, + _ => (1u32 << (b - 1)) + (slot - start[b]) / freq[b], + } as u8; + let (f, c) = if sym == 0 { + (freq[0] - 1, 1) + } else { + let k = (8 - sym.leading_zeros()) as usize; + let f = freq[k]; + ( + f, + ((u32::from(sym) - (1 << (k - 1))) * f + start[k]) & 0xffff, + ) + }; + ( + sym, + (x >> 16).wrapping_mul(f).wrapping_sub(c).wrapping_add(slot), + ) + } + + /// A payload step decodes the symbol and state the first version did, for + /// every model and slot of the shipped tables and ours, at assorted states. + #[test] + fn payload_step_matches_the_reference_decode() { + for t in [ + Tables::builtin().unwrap(), + Tables::parse(&tables()).unwrap(), + ] { + for model in 0..MODELS as u8 { + for high in [0x100u32, 0x1234, 0xffff] { + for slot in 0..1u32 << 16 { + let x = high << 16 | slot; + if x <= LOW { + continue; + } + let mut lane = Lane { + phase: 3, + model, + x, + left: 1, + ..Default::default() + }; + lane.step(&t).unwrap(); + let (sym, next) = reference_decode(&t, model, x); + assert_eq!( + (lane.out, lane.x), + (Some(sym), next), + "model {model} x {x:#x}" + ); + } + } + } + } + } + + /// Pseudo-random records that fit each lane's alphabet; BC7 keeps control + /// code 0 (mode 6), the only one the synthetic tables define. + fn random_records(widths: &[u8], per: usize, blocks: usize, bc7: bool) -> Vec> { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + (0..blocks) + .map(|_| { + let mut r: Vec = (0..widths.len() * per) + .map(|k| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let alphabet = 1u32 << (widths[k / per] + 1); + (seed as u32 % alphabet) as u8 + }) + .collect(); + if bc7 { + r[30] = 0; + r[31] = 0; + } + r + }) + .collect() + } + + /// The fast paths decode exactly what one lane step at a time does, on + /// every format's lane layout, with short and long fragments. + #[test] + fn every_layout_round_trips_through_the_lanes() { + let t = Tables::parse(&tables()).unwrap(); + let layouts: [(&[u8], usize); 6] = [ + (&[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1), + (&[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], 2), + (&BC4_LANES, 1), + (&[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 2), + (&[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], 2), + (&[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2), + ]; + for (widths, per) in layouts { + for blocks in [1, 2, 17, 300, 1000] { + let records = random_records(widths, per, blocks, false); + let src = stream(&t, widths, per, &records); + let mut got = vec![0u8; records.concat().len()]; + let mut next = src.iter().copied(); + lanes(&t, widths, per, blocks, |_| next.next(), &mut got).unwrap(); + assert_eq!(got, records.concat(), "{widths:?} x{per}, {blocks} blocks"); + } + } + } + + /// Decode throughput on synthetic streams (no game data): + /// `cargo test --release -p victory-formats bcpack_throughput -- --ignored --nocapture`. + #[test] + #[ignore = "benchmark"] + fn bcpack_throughput() { + let t = Tables::parse(&tables()).unwrap(); + let cases: [(u8, &[u8], usize, usize); 3] = [ + (1, &[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1, 8), + (4, &BC4_LANES, 1, 8), + (7, &[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2, 16), + ]; + for (bc, widths, per, block) in cases { + // One fragment per lane holds at most 65792 bytes. + let blocks = 1 << 14; + let records = random_records(widths, per, blocks, bc == 7); + let src = stream(&t, widths, per, &records); + let mut dst = vec![0u8; blocks * block]; + decode(bc, &src, &mut dst, &t).unwrap(); + let runs = 40; + let started = std::time::Instant::now(); + for _ in 0..runs { + decode(bc, std::hint::black_box(&src), &mut dst, &t).unwrap(); + } + let secs = started.elapsed().as_secs_f64() / f64::from(runs); + println!( + "BC{bc}: {blocks} blocks, {:.1} MB out/s, {:.1} ns/block", + (blocks * block) as f64 / secs / 1e6, + secs * 1e9 / blocks as f64 + ); + } + } + /// Compares with reference outputs made outside the repository: /// `VICTORY_BCPACK_TABLES` (the table file) and `VICTORY_BCPACK_CASES`, a /// directory of `.bc` packed chunks with `.out` beside them. From 27b530e7e14bcca992c8c128efedaf718723e6a0 Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:31:06 +0100 Subject: [PATCH 044/445] Files: send rewritten narrow paths to the host, not to our wide wrappers CreateFileA, GetFileAttributesA, fopen, fopen_s and the narrow std::_Fiopen turn the title's virtual-drive path into a host path and then passed it to our own wide wrapper, which looked it up a second time. When the host path starts with a letter that is itself mounted, it was rewritten again: with the game on a host G: drive (say G:\GTA6), the title's G:\x64\a.rpf became G:\GTA6\x64\a.rpf and then G:\GTA6\GTA6\x64\a.rpf, so every narrow open of a title file failed. The same happens for T: when the data folder is on a host T: drive. They now call the host's wide function directly, as DeleteFileA, SetCurrentDirectoryA, _open, _stat64i32 and remove already do. --- crates/victory-hle/src/modules/files.rs | 104 ++++++++++++++++++++---- 1 file changed, 88 insertions(+), 16 deletions(-) diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index 8806ff8..e25513d 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -4,9 +4,11 @@ //! Every title import that takes a path is bound here. A path on a virtual //! drive (`X:\..`, `X:/..`, `X:`, `\\?\X:\..`) is rewritten to the host //! folder behind it and handed to the host's own function; any other path -//! goes to the host unchanged. A rewritten narrow path goes to the wide -//! twin, so host folders outside the ANSI code page work. Letters are -//! chosen among those the host does not use, so no host drive is hidden. +//! goes to the host unchanged. A rewritten narrow path goes to the host's +//! wide twin, so host folders outside the ANSI code page work; never to our +//! wide wrapper, which would rewrite the host path a second time when its +//! drive letter is mounted too. Letters are chosen among those the host +//! does not use, so no host drive is hidden. #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] #![allow(clippy::too_many_arguments)] @@ -282,15 +284,17 @@ pub extern "system" fn CreateFileA( template: Handle, ) -> Handle { match narrow(path) { - Some(p) => CreateFileW( - p.as_ptr(), - access, - share, - security, - disposition, - flags, - template, - ), + Some(p) => { + host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( + p.as_ptr(), + access, + share, + security, + disposition, + flags, + template, + ) + } None => { host!("kernel32.dll", "CreateFileA": extern "system" fn(*const c_char, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( path, @@ -354,7 +358,11 @@ pub extern "system" fn SetFileAttributesW(path: *const u16, attributes: u32) -> pub extern "system" fn GetFileAttributesA(path: *const c_char) -> u32 { match narrow(path) { - Some(p) => GetFileAttributesW(p.as_ptr()), + Some(p) => { + host!("kernel32.dll", "GetFileAttributesW": extern "system" fn(*const u16) -> u32)( + p.as_ptr(), + ) + } None => { host!("kernel32.dll", "GetFileAttributesA": extern "system" fn(*const c_char) -> u32)( path, @@ -536,7 +544,10 @@ pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File { match narrow(path) { - Some(p) => _wfopen(p.as_ptr(), widen(mode).as_ptr()), + Some(p) => host!("ucrtbase.dll", "_wfopen": extern "C" fn(*const u16, *const u16) -> File)( + p.as_ptr(), + widen(mode).as_ptr(), + ), None => { host!("ucrtbase.dll", "fopen": extern "C" fn(*const c_char, *const c_char) -> File)( path, mode, @@ -547,7 +558,13 @@ pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File { pub extern "C" fn fopen_s(out: *mut File, path: *const c_char, mode: *const c_char) -> i32 { match narrow(path) { - Some(p) => _wfopen_s(out, p.as_ptr(), widen(mode).as_ptr()), + Some(p) => { + host!("ucrtbase.dll", "_wfopen_s": extern "C" fn(*mut File, *const u16, *const u16) -> i32)( + out, + p.as_ptr(), + widen(mode).as_ptr(), + ) + } None => { host!("ucrtbase.dll", "fopen_s": extern "C" fn(*mut File, *const c_char, *const c_char) -> i32)( out, path, mode, @@ -640,7 +657,13 @@ extern "C" fn fiopen_wide(path: *const u16, mode: i32, protection: i32) -> File /// `_Fiopen(const char* path, ios_base::openmode, int protection)`. extern "C" fn fiopen(path: *const c_char, mode: i32, protection: i32) -> File { match narrow(path) { - Some(p) => fiopen_wide(p.as_ptr(), mode, protection), + Some(p) => { + host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)( + p.as_ptr(), + mode, + protection, + ) + } None => { host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z": extern "C" fn(*const c_char, i32, i32) -> File)( path, mode, protection, @@ -866,4 +889,53 @@ mod tests { fclose(f); assert!(dir.path().join("plain.txt").is_file()); } + + /// A narrow path is rewritten once, as its wide twin is. The inner + /// drive's folder lies on the outer virtual drive, as the title folder + /// does when it sits on a host `G:` drive and is mounted as `G:`. The + /// outer letter is no host drive, so the host finds nothing there; a + /// narrow call that reaches the outer folder rewrote the path twice. + #[test] + fn narrow_paths_are_rewritten_once() { + let dir = tempfile::tempdir().unwrap(); + let folder = dir.path().join("inner"); + std::fs::create_dir(&folder).unwrap(); + std::fs::write(folder.join("present.txt"), b"").unwrap(); + let outer = mount(dir.path()).unwrap(); + let inner = mount(Path::new(&format!(r"{outer}:\inner"))).unwrap(); + let path = |name: &str| format!("{inner}:/{name}\0"); + + const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX; + let wide = GetFileAttributesW(w(&format!("{inner}:/present.txt")).as_ptr()); + assert_eq!(wide, INVALID_FILE_ATTRIBUTES); + let narrow = GetFileAttributesA(path("present.txt").as_ptr().cast()); + assert_eq!(narrow, wide, "GetFileAttributesA agrees with its wide twin"); + + const GENERIC_WRITE: u32 = 0x4000_0000; + const CREATE_ALWAYS: u32 = 2; + let null = std::ptr::null_mut(); + let h = CreateFileA( + path("a.bin").as_ptr().cast(), + GENERIC_WRITE, + 0, + null, + CREATE_ALWAYS, + 0, + null, + ); + assert_eq!(h as isize, -1); + assert!(fopen(path("b.txt").as_ptr().cast(), c"wb".as_ptr()).is_null()); + let mut f: File = std::ptr::null_mut(); + let error = fopen_s(&mut f, path("c.txt").as_ptr().cast(), c"wb".as_ptr()); + assert_ne!(error, 0); + const OUT: i32 = 2; + assert!(fiopen(path("d.txt").as_ptr().cast(), OUT, 0x40).is_null()); + + // Nothing was made behind a path rewritten twice. + let names: Vec<_> = std::fs::read_dir(&folder) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(names, ["present.txt"]); + } } From 24480a73f5bba85d560aab1393c93bdc1d203e68 Mon Sep 17 00:00:00 2001 From: TG0000 <122870448+TG0000@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:31:44 +0100 Subject: [PATCH 045/445] Shaders: find the written instructions with a worklist, not repeated passes Module::write dropped unread phis by sweeping every instruction until a sweep changed nothing, allocating an operand Vec per instruction per sweep. A chain of merges needs one sweep per merge, so the cost grew with instructions x merges. A worklist now visits each instruction once and reads operands through a callback; the block DFS, latch folding and the call/phi/gep records stop allocating too. The written bytes are the same (pinned by a test against the previous writer's output). Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/bitcode.rs | 308 ++++++++++++++++++---- 1 file changed, 258 insertions(+), 50 deletions(-) diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 8b555ad..0bfbcc0 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -473,6 +473,37 @@ impl Module { } /// The module as bitcode. + /// Which instructions are written: every body instruction, the branch + /// conditions, and whatever they read, transitively (a phi nothing reads + /// is dropped). A worklist visits each instruction once, so a long chain + /// of merges costs one pass, not one pass per merge. + fn live(&self) -> Vec { + let mut live = vec![false; self.insts.len()]; + let mut work: Vec = Vec::new(); + let mark = |live: &mut [bool], work: &mut Vec, v: V| { + if let V::Inst(i) = v + && !live[i as usize] + { + live[i as usize] = true; + work.push(i); + } + }; + for b in &self.blocks { + for &i in &b.body { + mark(&mut live, &mut work, V::Inst(i)); + } + if let Some(Term::CondBr(c, ..)) = b.term { + mark(&mut live, &mut work, c); + } + } + while let Some(i) = work.pop() { + for_each_operand(&self.insts[i as usize].op, |v| { + mark(&mut live, &mut work, v) + }); + } + live + } + pub fn write(&self) -> Vec { let mut w = Writer::default(); w.bytes(b"BC\xC0\xDE"); @@ -606,56 +637,12 @@ impl Module { w.exit(); // Phis nothing reads are left out (one register per phi makes many). - let mut live = vec![false; self.insts.len()]; - let mark = |live: &mut Vec, v: V| { - if let V::Inst(i) = v - && !live[i as usize] - { - live[i as usize] = true; - return true; - } - false - }; - let operands = |op: &Op| -> Vec { - match op { - Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => { - vec![*a, *b] - } - Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => vec![*v], - Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => vec![*a, *b, *c], - Op::Call(_, args) => args.clone(), - Op::Phi(inc) => inc.iter().map(|x| x.0).collect(), - Op::Gep(_, p, idx) => std::iter::once(*p).chain(idx.iter().copied()).collect(), - } - }; - for b in &self.blocks { - for &i in &b.body { - live[i as usize] = true; - } - if let Some(Term::CondBr(c, ..)) = b.term { - mark(&mut live, c); - } - } - let mut changed = true; - while changed { - changed = false; - for (i, inst) in self.insts.iter().enumerate() { - if live[i] { - for v in operands(&inst.op) { - changed |= mark(&mut live, v); - } - } - } - } + let live = self.live(); // Blocks are laid out in reverse postorder, so every block follows // its forward predecessors (drivers take a branch to an earlier // block for a loop's back edge). - let succs = |b: usize| match self.blocks[b].term { - Some(Term::Br(t)) => vec![t], - Some(Term::CondBr(_, t, f)) => vec![t, f], - _ => vec![], - }; + let succs = |b: usize| successors(self.blocks[b].term); let mut seen = vec![false; self.blocks.len()]; let mut post = Vec::new(); let mut stack = vec![(0usize, 0usize)]; @@ -685,7 +672,7 @@ impl Module { // DXC's loops; the AMD driver hangs on divergent loops otherwise. let mut preds = vec![Vec::new(); self.blocks.len()]; for &b in &post { - for s in succs(b) { + for &s in succs(b).iter() { preds[s].push(b); } } @@ -795,6 +782,8 @@ impl Module { w.enter(FUNCTION_BLOCK, 4); w.record(1, &[layout.len() as u64]); let mut inst_id = base; + // The operands of variable-length records, reused across them. + let mut r: Vec = Vec::new(); for b in layout.iter().map(|&b| &self.blocks[b]) { for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) { let inst = &self.insts[i as usize]; @@ -810,13 +799,15 @@ impl Module { Op::Select(c, t, f) => w.record(29, &[rel(*t), rel(*f), rel(*c)]), Op::Extract(a, idx) => w.record(26, &[rel(*a), u64::from(*idx)]), Op::Call(f, args) => { - let mut r = vec![0, 1 << 15, u64::from(self.funcs[*f as usize].ty.0)]; + r.clear(); + r.extend([0, 1 << 15, u64::from(self.funcs[*f as usize].ty.0)]); r.push(rel(V::Func(*f))); r.extend(args.iter().map(|&a| rel(a))); w.record(34, &r); } Op::Phi(incoming) => { - let mut r = vec![u64::from(inst.ty.0)]; + r.clear(); + r.push(u64::from(inst.ty.0)); for &(v, b) in incoming { r.push(signed(i64::from(inst_id) - i64::from(abs(v)))); r.push(from(b)); @@ -824,7 +815,8 @@ impl Module { w.record(16, &r); } Op::Gep(ty, p, idx) => { - let mut r = vec![0, u64::from(ty.0), rel(*p)]; + r.clear(); + r.extend([0, u64::from(ty.0), rel(*p)]); r.extend(idx.iter().map(|&i| rel(i))); w.record(43, &r); } @@ -868,6 +860,49 @@ const VALUE_SYMTAB_BLOCK: u64 = 14; const METADATA_BLOCK: u64 = 15; const TYPE_BLOCK: u64 = 17; +/// Calls `f` with every value `op` reads, in operand order. +fn for_each_operand(op: &Op, mut f: impl FnMut(V)) { + match op { + Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => { + f(*a); + f(*b); + } + Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => f(*v), + Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { + f(*a); + f(*b); + f(*c); + } + Op::Call(_, args) => args.iter().copied().for_each(f), + Op::Phi(inc) => inc.iter().for_each(|x| f(x.0)), + Op::Gep(_, p, idx) => { + f(*p); + idx.iter().copied().for_each(f); + } + } +} + +/// A block's successors (at most two), without allocating. +struct Succs { + to: [usize; 2], + len: usize, +} + +impl std::ops::Deref for Succs { + type Target = [usize]; + fn deref(&self) -> &[usize] { + &self.to[..self.len] + } +} + +fn successors(term: Option) -> Succs { + match term { + Some(Term::Br(t)) => Succs { to: [t, 0], len: 1 }, + Some(Term::CondBr(_, t, f)) => Succs { to: [t, f], len: 2 }, + _ => Succs { to: [0, 0], len: 0 }, + } +} + fn chars(s: &str) -> Vec { s.bytes().map(u64::from).collect() } @@ -983,4 +1018,177 @@ mod tests { assert_eq!(signed(-3), 7); assert_eq!(signed(2), 4); } + + /// A structured shader's shape: `stages` if/else diamonds in a row, each + /// merge with one phi per register (as the lowering makes them), then a + /// loop, and a tail that reads only the first `read` registers. + fn synthetic(regs: usize, stages: usize, read: usize) -> Module { + let mut m = Module::default(); + let i32t = m.int(32); + let void = m.void(); + let fty = m.func_ty(i32t, vec![i32t, i32t]); + let f = m.function("dx.op.synthetic", fty, Some(Attr::ReadNone), false); + let main_ty = m.func_ty(void, vec![]); + m.function("main", main_ty, None, true); + let mut b = m.new_block(); + let mut cur: Vec = (0..regs).map(|r| m.i32(r as u32)).collect(); + for s in 0..stages { + let c = m.cmp(b, pred::EQ, cur[0], cur[s % regs]); + let (t, e, j) = (m.new_block(), m.new_block(), m.new_block()); + m.terminate(b, Term::CondBr(c, t, e)); + let x = m.call(t, f, vec![cur[s % regs], cur[(s + 1) % regs]]); + m.terminate(t, Term::Br(j)); + m.terminate(e, Term::Br(j)); + cur = (0..regs) + .map(|r| { + let p = m.phi(j, i32t); + let tv = if r == s % regs { x } else { cur[r] }; + m.set_phi(p, vec![(tv, t), (cur[r], e)]); + p + }) + .collect(); + b = j; + } + // A loop: header phis fed back from an empty latch (which is folded). + let (head, body, latch, exit) = + (m.new_block(), m.new_block(), m.new_block(), m.new_block()); + m.terminate(b, Term::Br(head)); + let phis: Vec = (0..regs).map(|_| m.phi(head, i32t)).collect(); + let one = m.i32(1); + let stepped: Vec = phis + .iter() + .map(|&p| m.bin(body, Bin::Add, p, one)) + .collect(); + let c = m.cmp(body, pred::IULT, stepped[0], cur[0]); + m.terminate(head, Term::Br(body)); + m.terminate(body, Term::CondBr(c, latch, exit)); + m.terminate(latch, Term::Br(head)); + for r in 0..regs { + m.set_phi(phis[r], vec![(cur[r], b), (stepped[r], latch)]); + } + let mut acc = stepped[0]; + for &v in &stepped[1..read.max(1)] { + acc = m.bin(exit, Bin::Add, acc, v); + } + let _ = m.call(exit, f, vec![acc, cur[0]]); + m.terminate(exit, Term::Ret); + m + } + + /// FNV-1a, to pin a written module's exact bytes. + fn fnv(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| { + (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3) + }) + } + + /// Liveness as `write` computed it before the worklist: whole passes over + /// the instructions until one changes nothing. + fn live_by_passes(m: &Module) -> Vec { + let mut live = vec![false; m.insts.len()]; + for b in &m.blocks { + for &i in &b.body { + live[i as usize] = true; + } + if let Some(Term::CondBr(V::Inst(c), ..)) = b.term { + live[c as usize] = true; + } + } + let mut changed = true; + while changed { + changed = false; + for (i, inst) in m.insts.iter().enumerate() { + if live[i] { + for_each_operand(&inst.op, |v| { + if let V::Inst(j) = v + && !live[j as usize] + { + live[j as usize] = true; + changed = true; + } + }); + } + } + } + live + } + + #[test] + fn worklist_liveness_matches_passes() { + for (regs, stages, read) in [(1, 0, 1), (1, 1, 1), (4, 3, 1), (8, 17, 3), (16, 40, 16)] { + let m = synthetic(regs, stages, read); + let live = m.live(); + assert_eq!(live, live_by_passes(&m), "{regs} regs x {stages} stages"); + } + } + + #[test] + fn unread_phis_are_dropped() { + let mut m = Module::default(); + let i32t = m.int(32); + let (entry, join) = (m.new_block(), m.new_block()); + let (a, b) = (m.i32(1), m.i32(2)); + m.terminate(entry, Term::Br(join)); + let read = m.phi(join, i32t); + let unread = m.phi(join, i32t); + // A cycle of phis that only feed each other stays dead. + let cyc_a = m.phi(join, i32t); + let cyc_b = m.phi(join, i32t); + m.set_phi(read, vec![(a, entry)]); + m.set_phi(unread, vec![(b, entry)]); + m.set_phi(cyc_a, vec![(cyc_b, entry)]); + m.set_phi(cyc_b, vec![(cyc_a, entry)]); + let sum = m.bin(join, Bin::Add, read, b); + m.terminate(join, Term::Ret); + let ids = |v: V| match v { + V::Inst(i) => i as usize, + _ => unreachable!(), + }; + let live = m.live(); + assert!(live[ids(read)] && live[ids(sum)]); + assert!(!live[ids(unread)] && !live[ids(cyc_a)] && !live[ids(cyc_b)]); + assert_eq!(live, live_by_passes(&m)); + } + + #[test] + fn successors_of_each_terminator() { + assert!(successors(None).is_empty()); + assert!(successors(Some(Term::Ret)).is_empty()); + assert_eq!(&*successors(Some(Term::Br(7))), &[7]); + assert_eq!(&*successors(Some(Term::CondBr(V::Const(0), 3, 5))), &[3, 5]); + } + + /// The written bytes are pinned to what the writer produced before the + /// worklist and the reused record buffers. + #[test] + fn written_bytes_unchanged() { + for ((regs, stages, read), len, hash) in [ + ((64, 64, 64), 38_916, 0x9586_730c_f953_4a45), + ((128, 256, 32), 295_952, 0x89e5_de2d_64f0_8785), + ] { + let bytes = synthetic(regs, stages, read).write(); + assert_eq!((bytes.len(), fnv(&bytes)), (len, hash), "{regs}x{stages}"); + } + } + + #[test] + #[ignore = "benchmark: cargo test --release -p victory-shader bitcode -- --ignored --nocapture"] + fn bench_write() { + for (regs, stages, read) in [(64, 64, 64), (128, 256, 32), (256, 512, 256)] { + let m = synthetic(regs, stages, read); + let bytes = m.write(); + let runs = 5; + let t = std::time::Instant::now(); + for _ in 0..runs { + std::hint::black_box(m.write()); + } + let per = t.elapsed() / runs; + println!( + "write {regs} regs x {stages} stages ({} insts): {per:?}, {} bytes, fnv {:#018x}", + m.insts.len(), + bytes.len(), + fnv(&bytes) + ); + } + } } From 3c860538e18fe6e1bb7b0fdcdf6daefa83904d35 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 01:27:38 +0100 Subject: [PATCH 046/445] Shaders: lower s_bitcmp0/1_b32 and s_bitcmp0/1_b64 The scalar bit tests decode and are tracked in ir.rs (they write SCC) but the lowering had no case for them, so any shader using one failed to translate with Unsupported. --- crates/victory-shader/src/emit/lower.rs | 52 +++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index f8a1f5a..f9c4d9b 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2303,6 +2303,29 @@ impl<'a> Lower<'a> { _ => Ok(l.s.m.i32(0)), } }; + if let Some(op) = name.strip_prefix("s_bitcmp") { + // SCC is whether bit src1 (mod 32, or mod 64 for the 64-bit form) + // of src0 is clear (bitcmp0) or set (bitcmp1). + let (bit, k31) = (src32(self, 1)?, self.s.m.i32(31)); + let idx = self.s.m.bin(c, Bin::And, bit, k31); + let word = if op.ends_with("_b64") { + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let k32 = self.s.m.i32(32); + let upper = self.s.m.bin(c, Bin::And, bit, k32); + let z = self.s.m.i32(0); + let upper = self.s.m.cmp(c, pred::NE, upper, z); + self.s.m.select(c, upper, b, a) + } else { + src32(self, 0)? + }; + let shifted = self.s.m.bin(c, Bin::LShr, word, idx); + let one = self.s.m.i32(1); + let tested = self.s.m.bin(c, Bin::And, shifted, one); + let want = self.s.m.i32(u32::from(op.starts_with('1'))); + let r = self.s.m.cmp(c, pred::EQ, tested, want); + self.set(scc, Val::Bit(r)); + return Ok(()); + } if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) { // eq and lg only: both dwords. let mut r = None; @@ -6629,6 +6652,35 @@ mod tests { } } + #[test] + fn scalar_bit_tests_lower() { + // Each tests one bit of a constant into SCC and branches on it (only + // code with an effect needs its operands). + let tail = [ + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE84_0380, // s_mov_b32 s4, 0 + S_ENDPGM, + ]; + let bit_tests: [&[u32]; 4] = [ + &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3 + &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3 + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3 + ], + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3 + ], + ]; + for head in bit_tests { + let words: Vec = head.iter().chain(&tail).copied().collect(); + lowers(&words).unwrap(); + } + } + #[test] fn buffer_formats_by_number() { // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, From 7102a4989c77fa2f157766f3b8c8c683249c4f3f Mon Sep 17 00:00:00 2001 From: LUIS LARIOS Date: Mon, 23 Nov 2026 18:46:12 -0600 Subject: [PATCH 047/445] GPU: rename the second test module in host.rs so the tests compile cargo test --workspace does not compile on main: host.rs declares #[cfg(test)] mod tests twice, once near the top for the warp adapter test and once at the end for the Batch::texture_due tests, so rustc rejects the crate with E0428 before running anything: error[E0428]: the name ests is defined multiple times --> crates\victory-gpu\src\host.rs:1974:1 The second block only touches Batch, so it becomes mod batch and keeps its two tests. cargo test -p victory-gpu --lib goes from "could not compile" to 43 passed, 0 failed, 1 ignored, and cargo test --workspace compiles again. Nothing else changes: one line, no test bodies touched. --- crates/victory-gpu/src/host.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 8277c9d..c041282 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1971,7 +1971,7 @@ fn pump() { } #[cfg(test)] -mod tests { +mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file use super::Batch; use std::sync::Arc; From 1823079f6c9ce760774146334d97282c6a9752af Mon Sep 17 00:00:00 2001 From: lordon1a <183556939+lordon1a@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:53:26 +0300 Subject: [PATCH 048/445] Shaders: lower v_cmp_class_f16 and v_cmpx_class_f16 --- crates/victory-shader/src/emit/lower.rs | 54 ++++++++++----- crates/victory-shader/src/emit/valu_tests.rs | 70 ++++++++++++++++++++ 2 files changed, 108 insertions(+), 16 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..846a51e 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4937,28 +4937,50 @@ impl<'a> Lower<'a> { let (op, ty) = rest.rsplit_once('_').ok_or("a compare")?; let c = self.cur; let r = match ty { - "f32" if op == "class" => { + "f32" | "f16" if op == "class" => { // Bit k of src1 tests class k: signalling NaN, quiet NaN, // -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf. - let x = self.fsrc(inst, 0)?; - let x = self.as_int(x); + let f16 = ty == "f16"; + let x = if f16 { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let mut h = self.half_src(inst, 0)?; + if v.abs & 1 != 0 { + let m = self.s.m.i32(0x7FFF); + h = self.s.m.bin(c, Bin::And, h, m); + } + if v.neg & 1 != 0 { + let s = self.s.m.i32(0x8000); + h = self.s.m.bin(c, Bin::Xor, h, s); + } + h + } else { + let x = self.fsrc(inst, 0)?; + self.as_int(x) + }; let mask = self.src(inst, 1)?; let k = |l: &mut Self, v: u32| l.s.m.i32(v); - let (k23, k31, kff, mant, quiet) = ( - k(self, 23), - k(self, 31), - k(self, 0xFF), - k(self, 0x7F_FFFF), - k(self, 0x40_0000), + let (exp_sh, sign_sh, exp_mask, mant_mask, quiet_bit) = if f16 { + (10, 15, 0x1F, 0x03FF, 0x0200) + } else { + (23, 31, 0xFF, 0x7F_FFFF, 0x40_0000) + }; + let (k_exp, k_sign, k_emax, mant, quiet) = ( + k(self, exp_sh), + k(self, sign_sh), + k(self, exp_mask), + k(self, mant_mask), + k(self, quiet_bit), ); - let e = self.s.m.bin(c, Bin::LShr, x, k23); - let e = self.s.m.bin(c, Bin::And, e, kff); + let e = self.s.m.bin(c, Bin::LShr, x, k_exp); + let e = self.s.m.bin(c, Bin::And, e, k_emax); let m = self.s.m.bin(c, Bin::And, x, mant); - let neg = self.s.m.bin(c, Bin::LShr, x, k31); + let neg = self.s.m.bin(c, Bin::LShr, x, k_sign); let zero = k(self, 0); - let (e0, e255) = ( + let (e0, emax) = ( self.s.m.cmp(c, pred::EQ, e, zero), - self.s.m.cmp(c, pred::EQ, e, kff), + self.s.m.cmp(c, pred::EQ, e, k_emax), ); let m0 = self.s.m.cmp(c, pred::EQ, m, zero); let q = self.s.m.bin(c, Bin::And, x, quiet); @@ -4968,7 +4990,7 @@ impl<'a> Lower<'a> { (k(self, 8), k(self, 9), k(self, 6), k(self, 7)); let t = self.s.m.select(c, m0, zero_c, denorm); let t = self.s.m.select(c, e0, t, normal); - let t = self.s.m.select(c, e255, inf, t); + let t = self.s.m.select(c, emax, inf, t); let eleven = k(self, 11); let mirrored = self.s.m.bin(c, Bin::Sub, eleven, t); let is_neg = self.s.m.cmp(c, pred::NE, neg, zero); @@ -4977,7 +4999,7 @@ impl<'a> Lower<'a> { let nan_class = self.s.m.select(c, q, one, snan); let yes = self.s.m.bool(true); let nan = self.s.m.bin(c, Bin::Xor, m0, yes); - let nan = self.s.m.bin(c, Bin::And, nan, e255); + let nan = self.s.m.bin(c, Bin::And, nan, emax); let t = self.s.m.select(c, nan, nan_class, t); let bit = self.s.m.bin(c, Bin::LShr, mask, t); let bit = self.s.m.bin(c, Bin::And, bit, one); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6..566bec8 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -673,3 +673,73 @@ fn bfe_signed_and_unsigned_match_rdna2() { ); }); } + +#[test] +fn v_cmp_class_f16_matches_rdna2() { + // v_cmp_class_f16_e64 s6, v1, v2 (VOP3 opcode 0x08f); v_cndmask_b32_e64 v0, 0, 1, s6 + let cmp_lo = build_valu_cs(&[ + vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[0], + vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[1], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + ]); + // Same with op_sel:[1,0] (high half of v1) + neg on src0 (bit 29 of w1). + let [mut w0, mut w1] = vop3(0x08f, 6, vgpr(1), vgpr(2), 0); + w0 |= 1 << 11; // opsel[0] = 1 (high half) + w1 |= 1 << 29; // neg[0] = 1 + let cmp_hi_neg = build_valu_cs(&[ + w0, + w1, + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + ]); + + // All 10 IEEE-754 binary16 classes: bit k corresponds to class k. + let classes: &[(u32, u32)] = &[ + (0x7C01, 0), // sNaN (+sNaN, quiet bit 0x0200 clear) + (0xFDFF, 0), // -sNaN (sign ignored for NaNs) + (0x7E00, 1), // +qNaN + (0xFE01, 1), // -qNaN + (0xFC00, 2), // -inf + (0xBC00, 3), // -normal (-1.0) + (0x8001, 4), // -denormal + (0x8000, 5), // -0.0 + (0x0000, 6), // +0.0 + (0x0001, 7), // +denormal + (0x3C00, 8), // +normal (+1.0) + (0x7C00, 9), // +inf + ]; + let mut cases = Vec::new(); + for &(bits, cls) in classes { + // Exact class bit -> true; complement of class bit across all 10 bits -> false. + cases.push(([bits, 1u32 << cls, 0, 0], 1u32)); + cases.push(([bits, 0x3FF & !(1u32 << cls), 0, 0], 0u32)); + } + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&cmp_lo, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!( + got, want, + "{backend}: v_cmp_class_f16({:#06x}, {:#05x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + + // High half with neg: high half 0x3C00 (+1.0) negated -> -normal (class 3); + // high half 0x7C01 (+sNaN) negated -> still sNaN (class 0, not quieted). + let hi_cases: &[([u32; 4], u32)] = &[ + ([0x3C00_0000, 1 << 3, 0, 0], 1), + ([0x3C00_0000, 1 << 8, 0, 0], 0), + ([0x7C01_FFFF, 1 << 0, 0, 0], 1), + ([0x7C01_FFFF, 1 << 1, 0, 0], 0), + ]; + let hi_in: Vec<[u32; 4]> = hi_cases.iter().map(|c| c.0).collect(); + run_cases(&cmp_hi_neg, &hi_in, |backend, i, inp, got| { + let want = hi_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_cmp_class_f16(-hi({:#010x}), {:#05x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); +} From 7d73e2b249c975d0a6ffd1be0256b8ea8db63c4e Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 24 Nov 2026 03:35:47 +0300 Subject: [PATCH 049/445] pipeline: remove staging files when cache publication fails Reserve a new staging path and clean it up if writing or publishing fails. Cover a failed publication with a synthetic destination directory. --- crates/victory-pipeline/src/cache.rs | 33 ++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/victory-pipeline/src/cache.rs b/crates/victory-pipeline/src/cache.rs index 1e4b7ec..81e57de 100644 --- a/crates/victory-pipeline/src/cache.rs +++ b/crates/victory-pipeline/src/cache.rs @@ -1,3 +1,4 @@ +use std::io::Write; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; @@ -58,8 +59,17 @@ impl Cache { std::fs::create_dir_all(dir)?; // Write-then-rename so readers never see partial output. let tmp = tempfile_in(dir); - std::fs::write(&tmp, &output)?; - std::fs::rename(&tmp, &path)?; + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp)?; + let written = file.write_all(&output); + drop(file); + let published = written.and_then(|()| std::fs::rename(&tmp, &path)); + if published.is_err() { + let _ = std::fs::remove_file(&tmp); + } + published?; Ok(path) } } @@ -109,6 +119,25 @@ mod tests { assert_eq!(conv.runs.load(Ordering::Relaxed), 1); } + #[test] + fn failed_publication_removes_the_staging_file() { + let tmp = tempfile::tempdir().unwrap(); + let cache = Cache::open(tmp.path().join("cache")).unwrap(); + let conv = Upper { + version: 1, + runs: AtomicUsize::new(0), + }; + let path = cache.path_for(&CacheKey::new(&conv, b"abc")); + std::fs::create_dir_all(&path).unwrap(); + + assert!(cache.get_or_convert(&conv, b"abc").is_err()); + assert!(path.is_dir()); + assert_eq!( + std::fs::read_dir(path.parent().unwrap()).unwrap().count(), + 1 + ); + } + #[test] fn version_bump_invalidates() { let v1 = Upper { From 02fcf7240740e670a50bb5fcaa37e7b3525f6682 Mon Sep 17 00:00:00 2001 From: Maraco91 <43787609+Maraco91@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:02:38 +0100 Subject: [PATCH 050/445] xmem: mapping or unmapping no pages changes nothing XMemMapPhysicalPages with a count of 0, and the GPU's page-mapping copy of a zero-length range, went into unmap with an empty range. Its search for views starting inside asked the view map for a range that runs backwards, which BTreeMap panics on once any view exists; in an extern "system" function that aborts the process. Without that panic the view holding the address would have been unmapped and mapped again as two. unmap now returns at once for a length of 0. Co-Authored-By: Claude Fable 5.2 --- crates/victory-hle/src/modules/xmem.rs | 48 ++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 07a149a..52d48d6 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -781,6 +781,12 @@ fn commit_limit_message( /// Returns `[base, base + len)` to placeholders; views reaching past it /// are mapped again outside it. fn unmap(physical: &mut Physical, base: usize, len: usize) { + // No bytes: no view to return. The search below would still find the + // view holding `base` and cut it in two there, and its range of views + // starting inside would run backwards (which `BTreeMap` panics on). + if len == 0 { + return; + } let end = base + len; // Views do not overlap: the one holding `base`, then those starting // inside (the GPU's page mappings make one view per page). @@ -1103,6 +1109,48 @@ mod tests { assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); assert_eq!(XMemIsToolsMemAvailable(), 0); } + + #[test] + fn mapping_no_pages_changes_nothing() { + let pages = allocate(2); + let a = XMemVirtualAlloc( + std::ptr::null_mut(), + 2 * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ); + assert!(!a.is_null()); + assert_eq!(XMemMapPhysicalPages(a, 2, pages.as_ptr()), a); + // SAFETY: both pages are mapped read-write. + unsafe { a.cast::().write(5) }; + let second = a.wrapping_byte_add(PAGE); + + // A count of 0 at the start of a view, inside it and past it: with + // pages, without (an unmap), and as the GPU's page-mapping copy. + for at in [a, second, a.wrapping_byte_add(2 * PAGE)] { + assert_eq!(XMemMapPhysicalPages(at, 0, pages.as_ptr()), at); + assert_eq!(XMemMapPhysicalPages(at, 0, std::ptr::null()), at); + assert!(map_alias(at as u64, a as u64, 0)); + assert!(map_alias(at as u64, 0, 0)); + } + + // The view is still the one view it was. + let view = physical().views.get(&(a as usize)).map(|v| v.0); + assert_eq!(view, Some(2 * PAGE)); + assert_eq!(query(a).host.State, MEM_COMMIT); + assert_eq!(query(second).host.State, MEM_COMMIT); + // SAFETY: still mapped. + assert_eq!(unsafe { a.cast::().read() }, 5); + + // A count of 1 still unmaps that page alone. + assert_eq!(XMemMapPhysicalPages(second, 1, std::ptr::null()), second); + assert_eq!(query(second).host.State, MEM_RESERVE); + assert_eq!(query(a).host.State, MEM_COMMIT); + assert_eq!(XMemMapPhysicalPages(a, 1, std::ptr::null()), a); + assert_eq!(XMemFreePhysicalPages(2, pages.as_ptr()), 1); + } + /// `n` pages of one new allocation. fn allocate(n: usize) -> Vec { let (mut pages, mut given) = (vec![0; n], n); From babe2db61fa1125746e448cbd314c69dfec770bb Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:12:05 +0100 Subject: [PATCH 051/445] Crash reports: show the bytes of an instruction the CPU refused An illegal or privileged instruction is reported by its address only, which does not say which instruction it was. On an Intel host that is the question every such report raises (clwb, clzero, rdpru, an SSE4a form...), and reporters have had to guess or dump the bytes by hand. The report's first line now ends with up to 15 bytes at the faulting address, as hex, read no further than the end of that page, so the report names the instruction by itself. --- crates/victory-loader/src/crash.rs | 53 ++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index ac31566..14c12dc 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -379,6 +379,22 @@ pub unsafe fn report_unhandled(info: *const EXCEPTION_POINTERS) { unsafe { report("unhandled exception", info, true) }; } +/// The bytes at `at` as hex, as many as the longest x86 instruction (15), +/// but none past the end of `at`'s page: the next page may not be mapped. +/// For an instruction the CPU refused, they name it (`0f 01 fd` is +/// `rdpru`), which the address alone does not. +/// +/// # Safety +/// `at`'s page is readable. +unsafe fn instruction_bytes(at: usize) -> String { + let n = (0x1000 - (at & 0xfff)).min(15); + // SAFETY: `n` bytes from `at` stay inside its page, which the caller + // says is readable. + let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, n) }; + let hex: Vec<_> = bytes.iter().map(|b| format!("{b:02x}")).collect(); + hex.join(" ") +} + /// MSVC's code for a C++ `throw`, and its magic first parameter. const CPP_EXCEPTION: i32 = 0xE06D_7363_u32 as i32; const CPP_MAGIC: usize = 0x1993_0520; @@ -440,6 +456,9 @@ unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) { } else if code == CPP_EXCEPTION && record.NumberParameters >= 4 && p[0] == CPP_MAGIC { // SAFETY: a live MSVC throw. format!(" (C++ {} thrown)", unsafe { thrown(&p) }) + } else if code == EXCEPTION_ILLEGAL_INSTRUCTION || code == EXCEPTION_PRIV_INSTRUCTION { + // SAFETY: the CPU refused the instruction at `at`, so it fetched it. + format!(" (code {})", unsafe { instruction_bytes(at) }) } else { String::new() }; @@ -848,4 +867,38 @@ mod tests { None ); } + + #[test] + fn instruction_bytes_stop_at_the_end_of_their_page() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, + VirtualFree, VirtualProtect, + }; + // rdpru, then the next instruction (mov rcx, rax) and padding. + let mut code = [0x90_u8; 16]; + code[..6].copy_from_slice(&[0x0f, 0x01, 0xfd, 0x48, 0x89, 0xc1]); + // SAFETY: two fresh pages of ours, the second made unreadable, so a + // read past the end of the first faults. + unsafe { + let page = VirtualAlloc( + std::ptr::null(), + 0x2000, + MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE, + ) + .cast::(); + assert!(!page.is_null()); + let mut old = 0; + let guard = page.add(0x1000).cast(); + assert_ne!(VirtualProtect(guard, 0x1000, PAGE_NOACCESS, &mut old), 0); + page.copy_from_nonoverlapping(code.as_ptr(), code.len()); + let whole = "0f 01 fd 48 89 c1 90 90 90 90 90 90 90 90 90"; + assert_eq!(instruction_bytes(page as usize), whole); + // The page's last three bytes: rdpru, and nothing read after it. + let end = page.add(0x1000 - 3); + end.copy_from_nonoverlapping(code.as_ptr(), 3); + assert_eq!(instruction_bytes(end as usize), "0f 01 fd"); + VirtualFree(page.cast(), 0, MEM_RELEASE); + } + } } From 3390e47328e057badbb3cf2a2f565a3a05291960 Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:18:49 +0100 Subject: [PATCH 052/445] Crash reports: say what an access violation's address holds An access violation is reported with the address it touched and nothing else, so a read of free memory, a write to memory that was reserved but whose commit failed, a stack guard page and a write to code or constants all look the same in a report. The report now adds what VirtualQuery says is at that address: nothing, reserved but never committed, a guard page, or the page's protection, with the module for an image's pages. --- crates/victory-loader/src/crash.rs | 79 +++++++++++++++++++++++++++++- 1 file changed, 78 insertions(+), 1 deletion(-) diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index ac31566..b3e8214 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -436,7 +436,7 @@ unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) { 1 => "write", _ => "execute", }; - format!(" ({kind} {:#x})", p[1]) + format!(" ({kind} {:#x}: {})", p[1], memory_at(p[1])) } else if code == CPP_EXCEPTION && record.NumberParameters >= 4 && p[0] == CPP_MAGIC { // SAFETY: a live MSVC throw. format!(" (C++ {} thrown)", unsafe { thrown(&p) }) @@ -579,6 +579,48 @@ fn module_of(address: usize) -> Option { Some(format!("{name}+{:#x}", address - module as usize)) } +/// What is at `address`, for an access violation there: nothing, memory +/// reserved but never committed, a guard page, or the protection the access +/// broke (with the module, for an image's pages). Each points at a different +/// cause: a wild pointer, an allocation whose commit failed, a stack +/// overrun, a write to code or constants. +fn memory_at(address: usize) -> String { + use windows_sys::Win32::System::Memory::{ + MEM_FREE, MEM_IMAGE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE, + PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_GUARD, + PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, VirtualQuery, + }; + // SAFETY: a zeroed MEMORY_BASIC_INFORMATION is valid. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: reads the address space's bookkeeping, not `address` itself. + let n = unsafe { VirtualQuery(address as *const _, &mut info, size_of_val(&info)) }; + if n == 0 { + // Above the process's address space: Windows reports a + // non-canonical address as all ones. + return "outside the address space".into(); + } + let protect = match info.State { + MEM_FREE => return "nothing mapped there".into(), + MEM_RESERVE => return "reserved, never committed".into(), + _ if info.Protect & PAGE_GUARD != 0 => return "a guard page".into(), + _ => match info.Protect & 0xff { + PAGE_NOACCESS => "no access".into(), + PAGE_READONLY => "read-only".into(), + PAGE_READWRITE => "read-write".into(), + PAGE_WRITECOPY => "copy-on-write".into(), + PAGE_EXECUTE => "execute-only".into(), + PAGE_EXECUTE_READ => "read-execute".into(), + PAGE_EXECUTE_READWRITE => "read-write-execute".into(), + PAGE_EXECUTE_WRITECOPY => "copy-on-write, executable".into(), + _ => format!("protection {:#x}", info.Protect), + }, + }; + match module_of(address) { + Some(module) if info.Type == MEM_IMAGE => format!("{protect}, in {module}"), + _ => protect, + } +} + #[cfg(test)] mod tests { use super::*; @@ -607,6 +649,41 @@ mod tests { assert_eq!(ours, system); } + #[test] + fn memory_at_names_what_an_access_hit() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, + PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + // SAFETY: reserves four pages of ours and commits three of them; + // nothing reads or writes them. + let base = unsafe { + let base = VirtualAlloc(std::ptr::null(), 0x4000, MEM_RESERVE, PAGE_NOACCESS); + assert!(!base.is_null()); + let page = |i: usize, protect| { + let at = base.cast::().add(i * 0x1000).cast(); + assert!(!VirtualAlloc(at, 0x1000, MEM_COMMIT, protect).is_null()); + }; + page(1, PAGE_READONLY); + page(2, PAGE_READWRITE | PAGE_GUARD); + page(3, PAGE_NOACCESS); + base as usize + }; + assert_eq!(memory_at(base + 8), "reserved, never committed"); + assert_eq!(memory_at(base + 0x1008), "read-only"); + assert_eq!(memory_at(base + 0x2008), "a guard page"); + assert_eq!(memory_at(base + 0x3008), "no access"); + // SAFETY: releases the reservation made above. + unsafe { VirtualFree(base as *mut _, 0, MEM_RELEASE) }; + assert_eq!(memory_at(base + 8), "nothing mapped there"); + assert_eq!(memory_at(0), "nothing mapped there"); + assert_eq!(memory_at(usize::MAX), "outside the address space"); + // This test's own code: an image page, named by its module. + let code = memory_at(memory_at_names_what_an_access_hit as *const () as usize); + let named = code.starts_with("read-execute, in victory_loader-"); + assert!(named, "{code}"); + } + /// On an Intel CPU, the real instructions go through the vectored /// handler. On an AMD CPU they run natively, and the tests below test /// the emulation. From cbb50b8016c2115448a130331afc7ab4a64dd5a5 Mon Sep 17 00:00:00 2001 From: julio Date: Mon, 23 Nov 2026 21:24:11 -0400 Subject: [PATCH 053/445] GPU: give null texture UAVs the title's view dimension When the host cannot make an unordered-access view (no host texture, a format the host does not allow, a placed texture not mirrored), null_for() wrote a 2D null UAV whatever the title asked for. A shader that writes a 3D texture through it then has a dimension mismatch: GPU-based validation reports it ("UAV Dimension Expected: TEXTURE3D, UAV Dimension In Descriptor: TEXTURE2D") for the world's wind field (WindNew:CS_CopyWindFieldBeforeUpdateWithSmooth, compute 5bb23d336331db1d, image_load/image_store dim:SQ_RSRC_IMG_3D). Shader views already get a null view of the title's dimension (null_like); unordered views did not. Null texture UAVs now keep the title's dimension: 1D, 1D and 2D arrays, 3D (WSize -1). Multisampled and unnamed dimensions stay 2D. With this, the validation error is gone on an RTX 5070. Tests: the dimension mapping, and a null 3D UAV made on the real device leaves it alive. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 101 +++++++++++++++++++--- 1 file changed, 90 insertions(+), 11 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 43dba24..33843d4 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -734,9 +734,13 @@ pub(crate) fn placed_texture(view: &View) -> Option { fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some(); - let buffer = match view { - View::Unordered(r, _, desc) => is_buffer(r) || desc.is_some_and(|d| d[1] == 1), - View::Placed(true, resource, _) => resource[0] == 1, + // Unordered views: whether a buffer, and the title's view dimension. + let (buffer, dimension) = match view { + View::Unordered(r, _, desc) => ( + is_buffer(r) || desc.is_some_and(|d| d[1] == 1), + desc.map(|d| d[1]), + ), + View::Placed(true, resource, desc) => (resource[0] == 1, Some(desc[1])), // Shader views of buffers read nothing through a null buffer view: // a null 2D view where the shader expects a buffer is a mismatch // the hardware does not survive in general (GPU-based validation @@ -758,14 +762,14 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { } _ => return null_view(at), }; - let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { - Format: DXGI_FORMAT_R32_UINT, - ViewDimension: if buffer { - D3D12_UAV_DIMENSION_BUFFER - } else { - D3D12_UAV_DIMENSION_TEXTURE2D - }, - ..Default::default() + let desc = if buffer { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + ..Default::default() + } + } else { + null_uav_desc(dimension) }; // SAFETY: a slot of our heap; a null resource is allowed with a desc. unsafe { @@ -778,6 +782,46 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { }; } +/// A null texture UAV of the title's view dimension (1D, 1D or 2D arrays, +/// 3D), 2D if it names none: a 2D null view where the shader writes a 3D +/// texture is a mismatch GPU-based validation reports (the world's wind +/// field, CS_CopyWindFieldBeforeUpdateWithSmooth, 2026-11-24). +fn null_uav_desc(dimension: Option) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + let mut desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + match dimension.map(|d| D3D12_UAV_DIMENSION(d as i32)) { + Some(D3D12_UAV_DIMENSION_TEXTURE1D) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; + } + Some(D3D12_UAV_DIMENSION_TEXTURE1DARRAY) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; + desc.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_UAV { + ArraySize: 1, + ..Default::default() + }; + } + Some(D3D12_UAV_DIMENSION_TEXTURE2DARRAY) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + desc.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { + ArraySize: 1, + ..Default::default() + }; + } + Some(D3D12_UAV_DIMENSION_TEXTURE3D) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + desc.Anonymous.Texture3D = D3D12_TEX3D_UAV { + WSize: u32::MAX, + ..Default::default() + }; + } + _ => {} + } + desc +} + /// A buffer view that reads zeros (raw, as translated shaders mostly read /// buffers). fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { @@ -856,6 +900,41 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { mod tests { use super::*; + /// A null texture UAV keeps the title's dimension (3D for the world's + /// wind field), and is 2D when the title names none. + #[test] + fn null_uavs_keep_the_titles_dimension() { + let d = null_uav_desc(Some(8)); + assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE3D); + // SAFETY: the member the dimension names. + assert_eq!(unsafe { d.Anonymous.Texture3D.WSize }, u32::MAX); + let d = null_uav_desc(Some(5)); + assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE2DARRAY); + // SAFETY: the member the dimension names. + assert_eq!(unsafe { d.Anonymous.Texture2DArray.ArraySize }, 1); + let dimension = |d| null_uav_desc(d).ViewDimension; + assert_eq!(dimension(Some(2)), D3D12_UAV_DIMENSION_TEXTURE1D); + assert_eq!(dimension(Some(4)), D3D12_UAV_DIMENSION_TEXTURE2D); + assert_eq!(dimension(None), D3D12_UAV_DIMENSION_TEXTURE2D); + // Multisampled UAVs need a cap; they stay 2D. + assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D); + } + + /// A null 3D UAV made on the real device leaves it alive. + #[test] + fn null_3d_uav_is_accepted_by_the_device() { + let Some(host) = host() else { + return; // no host GPU + }; + let Some(heap) = HostHeap::new(false, 4) else { + return; + }; + let view = View::Unordered(0, 0, Some([28, 8, 0, 0, 0, 0, 0, 0, 0, 0])); + null_for(&view, heap.cpu(0)); + // SAFETY: a plain device query. + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + } + /// Dynamic slots stay taken until given back, and runs do not wrap. #[test] fn dynamic_slots_are_held_until_released() { From c88b7ac1cce4d2d3b12d761bd66632f65a5a6e23 Mon Sep 17 00:00:00 2001 From: Maraco91 <43787609+Maraco91@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:26:58 +0100 Subject: [PATCH 054/445] Game saves: an empty configuration id is the default, not every configuration's folder A provider's folder is the user's folder plus the configuration id as a file name. An empty id gave the user's folder itself, where the other configurations' folders are. Opening the provider converts containers of the old layout, which are folders without a `~` or a dot in their name, as a configuration's folder is: each was taken for one, an empty container was committed in its place and the folder was removed with every save in it. An empty id is now treated as no id (the default configuration). Co-Authored-By: Claude Fable 5.2 --- crates/victory-hle/src/modules/xgamesave.rs | 32 +++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs index 7282284..0d552e7 100644 --- a/crates/victory-hle/src/modules/xgamesave.rs +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -362,11 +362,14 @@ fn take(handle: *mut T) { impl Provider { /// The provider for the only user and `config` (the service - /// configuration id), under `saves`. + /// configuration id), under `saves`. An empty id names no + /// configuration, like none: as a folder name it would be the user's + /// folder itself, where the other configurations' folders are. fn open(saves: &Path, config: Option<&str>) -> Result { + let config = config.filter(|c| !c.is_empty()).unwrap_or("default"); let root = saves .join(format!("{:016X}", xuser::XUID)) - .join(file_name(config.unwrap_or("default"))); + .join(file_name(config)); std::fs::create_dir_all(&root).map_err(|_| NO_ACCESS)?; let _saves = saves_lock(); containers(&root); // converts old containers now @@ -1108,6 +1111,31 @@ mod tests { assert_eq!((v.number, v.display.as_str()), (1, "Chapter 1")); } + /// An empty configuration id names none. As a folder name it would be + /// the folder every configuration lives in, whose folders then look + /// like containers of the old layout and are converted away. + #[test] + fn an_empty_configuration_id_is_the_default_one() { + let saves = tempfile::tempdir().unwrap(); + let scid = Provider::open(saves.path(), Some("scid")).unwrap(); + assert_eq!(update(&scid.root, "one", &[("a", Some("kept"))]), S_OK); + let kept = Some(("one".into(), vec![("a".into(), "kept".into())])); + assert_eq!(state(&scid.root), kept); + + let empty = Provider::open(saves.path(), Some("")).unwrap(); + assert!(scid.root.is_dir(), "another configuration's saves are gone"); + assert_eq!(state(&scid.root), kept); + let default = Provider::open(saves.path(), None).unwrap(); + assert_eq!(empty.root, default.root); + + // Named configurations stay apart, from it and from each other. + assert_ne!(empty.root, scid.root); + assert_eq!(state(&empty.root), None); + let other = Provider::open(saves.path(), Some("other")).unwrap(); + assert_eq!(state(&other.root), None); + assert_eq!(state(&scid.root), kept); + } + #[test] fn saves_persist_across_providers() { let this: This = &OBJECT; From afc4641bd762512c7106c4cece0bf249b14a8504 Mon Sep 17 00:00:00 2001 From: Andrea Casale Date: Tue, 24 Nov 2026 01:57:51 +0100 Subject: [PATCH 055/445] net: skip newer-Windows-only exports in only_loopback_is_reachable WinHttpGetProxySettingsEx is absent from Windows 10's winhttp.dll, so the host-presence assertion panicked there. The HLE supplies it itself; skip it only when the host lacks it, keeping the check for every other export. Fixes #118 --- crates/victory-hle/src/modules/net.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/victory-hle/src/modules/net.rs b/crates/victory-hle/src/modules/net.rs index 6f61a27..09bd266 100644 --- a/crates/victory-hle/src/modules/net.rs +++ b/crates/victory-hle/src/modules/net.rs @@ -1048,15 +1048,23 @@ mod tests { named.name ); } - // Every override names a real export of its DLL. + // Every override names a real export of its DLL. Some exports only + // exist on newer Windows (WinHttpGetProxySettingsEx is absent from + // Windows 10's winhttp.dll); the HLE supplies those itself, so skip + // them only when the host really lacks them. + const NEWER_WINDOWS_ONLY: &[&str] = &["WinHttpGetProxySettingsEx"]; for e in m.exports.iter().filter(|e| !e.name.starts_with('#')) { let dll = if e.name.starts_with("WinHttp") { "winhttp.dll" } else { "ws2_32.dll" }; + let present = crate::host::function(dll, e.name).is_some(); + if !present && NEWER_WINDOWS_ONLY.contains(&e.name) { + continue; + } assert!( - crate::host::function(dll, e.name).is_some(), + present, "{dll} lacks {}", e.name ); From 18b2716a2c73e37ed8db346bcc3dcc0479f4b632 Mon Sep 17 00:00:00 2001 From: Andrea Casale Date: Tue, 24 Nov 2026 02:00:22 +0100 Subject: [PATCH 056/445] net: rustfmt the presence assertion --- crates/victory-hle/src/modules/net.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/victory-hle/src/modules/net.rs b/crates/victory-hle/src/modules/net.rs index 09bd266..857b351 100644 --- a/crates/victory-hle/src/modules/net.rs +++ b/crates/victory-hle/src/modules/net.rs @@ -1063,11 +1063,7 @@ mod tests { if !present && NEWER_WINDOWS_ONLY.contains(&e.name) { continue; } - assert!( - present, - "{dll} lacks {}", - e.name - ); + assert!(present, "{dll} lacks {}", e.name); } } } From d46b07803c80c6f05ae1738254ec98c7d50529a9 Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:32:25 +0100 Subject: [PATCH 057/445] XUser: a gamertag without a suffix has an empty modern suffix XUserGetGamertag returned the name for every component, the modern suffix included. The GDK documents the suffix as empty when there is none, and a title that shows "name#suffix" whenever the suffix is not empty showed "Player#Player". The modern suffix (component 2) is now empty; the classic, modern and unique modern components are still the name. --- crates/victory-hle/src/modules/xuser.rs | 32 ++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/victory-hle/src/modules/xuser.rs b/crates/victory-hle/src/modules/xuser.rs index 33c05d6..8b48dfc 100644 --- a/crates/victory-hle/src/modules/xuser.rs +++ b/crates/victory-hle/src/modules/xuser.rs @@ -154,16 +154,23 @@ extern "system" fn get_is_guest(_: This, _: Handle, out: *mut bool) -> HRESULT { extern "system" fn get_state(_: This, _: Handle, out: *mut u32) -> HRESULT { put(out, 0) } -/// The same name for every component (classic, modern, suffix, unique). +/// The user's gamertag as the component asked for (`XUserGamertagComponent`): +/// it has no suffix, so the modern suffix is empty and every other component +/// (classic, modern, unique modern) is the name itself. extern "system" fn get_gamertag( _: This, _: Handle, - _component: u32, + component: u32, size: usize, buffer: *mut u8, used: *mut usize, ) -> HRESULT { - put_string(GAMERTAG, size, buffer, used) + const MODERN_SUFFIX: u32 = 2; + let text = match component { + MODERN_SUFFIX => "", + _ => GAMERTAG, + }; + put_string(text, size, buffer, used) } /// Granted; deny reason 0 (none). extern "system" fn check_privilege( @@ -322,6 +329,25 @@ mod tests { use crate::modules::xasync::E_NOT_SUFFICIENT_BUFFER; use crate::modules::xgameruntime::method as slot; + #[test] + fn a_gamertag_without_a_suffix_has_an_empty_modern_suffix() { + type Gamertag = + extern "system" fn(This, Handle, u32, usize, *mut u8, *mut usize) -> HRESULT; + let this: This = &OBJECT; + let user = std::ptr::null(); + // Classic, modern, modern suffix, unique modern; through both slots. + let expected: [&[u8]; 4] = [b"Player\0", b"Player\0", b"\0", b"Player\0"]; + for (object, at) in [(&GAMERTAG_OBJECT, 0x18), (&OBJECT, 0x78)] { + let get = slot::(object, at); + for (component, expected) in (0..).zip(expected) { + let (mut name, mut used) = ([0xff_u8; 16], 0); + let hr = get(this, user, component, 16, name.as_mut_ptr(), &mut used); + assert_eq!(hr, S_OK); + assert_eq!(&name[..used], expected, "component {component}"); + } + } + } + #[test] fn startup_adds_the_user_and_reads_its_id() { type Add = extern "system" fn(This, u32, *mut AsyncBlock) -> HRESULT; From 5f670bbfdba199a7537124adaa7ef5b0871e352b Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:39:39 +0100 Subject: [PATCH 058/445] Loader: a trapped unimplemented import goes into the crash log An unimplemented import with the default Trap policy printed its name and aborted. abort() is a fast fail: it skips the exception handlers and the panic hook, which are what append to crashes.log, so the most common bring-up crash left nothing there, not even which import it was. The trap now reports through log_crash, which prints the same line, appends it to the crash log and adds the title's last debug output. --- crates/victory-loader/src/thunks.rs | 46 ++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/crates/victory-loader/src/thunks.rs b/crates/victory-loader/src/thunks.rs index 9dd2796..48a7998 100644 --- a/crates/victory-loader/src/thunks.rs +++ b/crates/victory-loader/src/thunks.rs @@ -62,10 +62,11 @@ extern "system" fn unimplemented_import(site: &'static ImportSite) -> u64 { } UnimplementedPolicy::Trap => { tracing::error!(dll = %site.dll, symbol = %site.symbol, "unimplemented import called"); - eprintln!( - "VIctory: unimplemented import {}!{} called", - site.dll, site.symbol - ); + // Into the crash log too: `abort` ends the process without + // running the handlers that write it. + let (dll, symbol) = (&site.dll, &site.symbol); + let text = format!("VIctory: unimplemented import {dll}!{symbol} called"); + crate::log_crash(&text); // SAFETY: plain Win32 calls without preconditions. unsafe { if IsDebuggerPresent() != 0 { @@ -147,3 +148,40 @@ impl ThunkBlock { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// In a child process of the next test: calls an unimplemented import + /// that traps, with the crash log where `VICTORY_TRAP_LOG` says. + #[test] + fn trap_child() { + let Some(log) = std::env::var_os("VICTORY_TRAP_LOG") else { + return; + }; + crate::log_crashes_to(log.into()); + let site = Box::leak(Box::new(ImportSite { + dll: "probe.dll".into(), + symbol: "Missing".into(), + policy: UnimplementedPolicy::Trap, + calls: AtomicU64::new(0), + })); + unimplemented_import(site); + } + + #[test] + fn a_trapped_import_is_in_the_crash_log() { + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("crashes.log"); + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "thunks::tests::trap_child", "--nocapture"]) + .env("VICTORY_TRAP_LOG", &log) + .output() + .unwrap(); + assert!(!out.status.success(), "the trap ends the process"); + let text = std::fs::read_to_string(&log).unwrap_or_default(); + let named = text.contains("VIctory: unimplemented import probe.dll!Missing called"); + assert!(named, "crash log: {text:?}"); + } +} From 36d6a79595ff9c24930f7c881bd34d7fd56e425a Mon Sep 17 00:00:00 2001 From: Maraco91 <43787609+Maraco91@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:42:41 +0100 Subject: [PATCH 059/445] XTaskQueue: terminating a queue ends a dispatch waiting on it XTaskQueueDispatch with an infinite timeout waited until a callback was queued. Terminating the queue refuses new callbacks and drained the queued ones without waking anyone, so a dispatcher thread's loop (`while (XTaskQueueDispatch(queue, port, INFINITE));`, which ends by terminating the queue) stayed in its wait for good, and so did whoever joined that thread. A dispatch begun after the termination did the same. A dispatch now also ends, returning false, when its queue is terminated: the termination wakes the port's waiters after draining it. The flag is the queue's, so a dispatch on another queue that shares the port waits on. Co-Authored-By: Claude Fable 5.2 --- crates/victory-hle/src/modules/xasync.rs | 89 ++++++++++++++++++++++-- 1 file changed, 82 insertions(+), 7 deletions(-) diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index 6795057..529774a 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -105,7 +105,7 @@ impl Port { let worker = port.clone(); std::thread::spawn(move || { loop { - match worker.take(1000) { + match worker.take(1000, || false) { Some(task) => task.run(false), None if Arc::strong_count(&worker) == 1 => break, None => {} @@ -127,17 +127,19 @@ impl Port { } } - /// The next queued task, waiting up to `timeout_ms`. - fn take(&self, timeout_ms: u32) -> Option { + /// The next queued task, waiting up to `timeout_ms`, or until `ended` + /// (checked whenever the port is woken) says no task will come. + fn take(&self, timeout_ms: u32, ended: impl Fn() -> bool) -> Option { + let waiting = |t: &mut VecDeque| t.is_empty() && !ended(); let tasks = lock(&self.tasks); let mut tasks = if timeout_ms == INFINITE { self.ready - .wait_while(tasks, |t| t.is_empty()) + .wait_while(tasks, waiting) .unwrap_or_else(|e| e.into_inner()) } else { let timeout = Duration::from_millis(timeout_ms.into()); self.ready - .wait_timeout_while(tasks, timeout, |t| t.is_empty()) + .wait_timeout_while(tasks, timeout, waiting) .unwrap_or_else(|e| e.into_inner()) .0 }; @@ -332,7 +334,9 @@ pub fn XTaskQueueCloseHandle(handle: *const Queue) { } } -/// Runs one queued callback of a manual port; false if none came in time. +/// Runs one queued callback of a manual port; false if none came in time, +/// or none can come: the queue was terminated (which ends a wait under way, +/// as a dispatcher thread's loop expects). pub fn XTaskQueueDispatch(handle: *const Queue, port: u32, timeout_ms: u32) -> bool { let Some(queue) = queue(handle) else { return false; @@ -343,7 +347,7 @@ pub fn XTaskQueueDispatch(handle: *const Queue, port: u32, timeout_ms: u32) -> b if port.mode != Mode::Manual { return false; } - match port.take(timeout_ms) { + match port.take(timeout_ms, || queue.terminated.load(Ordering::Acquire)) { Some(task) => { task.run(false); true @@ -379,6 +383,10 @@ pub fn XTaskQueueTerminate( queue.terminated.store(true, Ordering::Release); for port in &queue.ports { let pending: Vec = lock(&port.tasks).drain(..).collect(); + // Dispatches waiting on this queue end: nothing more will come. + // (Those of other queues on the port see theirs is open and wait + // on.) After the lock above, so none misses both flag and wake. + port.ready.notify_all(); for task in pending { task.run(true); } @@ -1179,6 +1187,73 @@ mod tests { XTaskQueueCloseHandle(q); } + /// A dispatcher thread's loop, `while (XTaskQueueDispatch(queue, port, + /// INFINITE));`, ends when its queue is terminated: nothing can be + /// submitted to it any more, so nothing else would ever wake it. + #[test] + fn terminate_ends_a_waiting_dispatch() { + static RAN: AtomicU32 = AtomicU32::new(0); + extern "system" fn ran(_: *mut c_void, _: bool) { + RAN.fetch_add(1, Ordering::SeqCst); + } + /// Dispatches `queue`'s work until a dispatch returns false, then + /// says so. + fn dispatcher(queue: *const Queue) -> std::sync::mpsc::Receiver<()> { + let (done, ended) = std::sync::mpsc::channel(); + let queue = queue as usize; + std::thread::spawn(move || { + while XTaskQueueDispatch(queue as *const Queue, WORK, INFINITE) {} + let _ = done.send(()); + }); + ended + } + let run_one = |queue, total| { + let none = std::ptr::null_mut(); + assert_eq!( + XTaskQueueSubmitDelayedCallback(queue, WORK, 0, none, Some(ran)), + S_OK + ); + for _ in 0..500 { + if RAN.load(Ordering::SeqCst) == total { + return; + } + std::thread::sleep(Duration::from_millis(10)); + } + panic!("callback {total} did not run"); + }; + let (long, short) = (Duration::from_secs(5), Duration::from_millis(200)); + let none = std::ptr::null_mut(); + + // Two queues on the same manual ports. + let (mut a, mut b) = (std::ptr::null(), std::ptr::null()); + assert_eq!(XTaskQueueCreate(0, 0, &mut a), S_OK); + let (mut work, mut completion) = (std::ptr::null(), std::ptr::null()); + assert_eq!(XTaskQueueGetPort(a, WORK, &mut work), S_OK); + assert_eq!(XTaskQueueGetPort(a, COMPLETION, &mut completion), S_OK); + assert_eq!(XTaskQueueCreateComposite(work, completion, &mut b), S_OK); + + let ended = dispatcher(a); + run_one(a, 1); + // The other queue's end is not this one's: the wait goes on and + // still runs what comes in. + assert_eq!(XTaskQueueTerminate(b, false, none, None), S_OK); + assert!( + ended.recv_timeout(short).is_err(), + "ended with another queue" + ); + run_one(a, 2); + // Its own queue's end is. + assert_eq!(XTaskQueueTerminate(a, false, none, None), S_OK); + assert!( + ended.recv_timeout(long).is_ok(), + "still waiting on a terminated queue" + ); + // And a dispatch that starts after the end returns at once. + assert!(!XTaskQueueDispatch(a, WORK, INFINITE)); + XTaskQueueCloseHandle(a); + XTaskQueueCloseHandle(b); + } + #[test] fn terminate_cancels_what_is_queued() { static TERMINATED: AtomicBool = AtomicBool::new(false); From 79fb722a530056ce1f193b2a4476901de414a8d7 Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:45:09 +0100 Subject: [PATCH 060/445] Shaders: s_ttracedata_imm is SOPP opcode 0x28, not 0x26 The SOPP table had s_ttracedata_imm at 0x26, as Mesa's opcode list does; RDNA2 encodes it at 0x28 (AMD's RDNA2 ISA, LLVM's GFX10 tables and disassembler tests). A shader with the thread-trace marker decoded it as an unknown opcode and failed to translate, though the IR drops the marker as harmless. --- crates/victory-shader/src/gfx10/opcodes.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/gfx10/opcodes.rs b/crates/victory-shader/src/gfx10/opcodes.rs index 18dac4f..d1ba275 100644 --- a/crates/victory-shader/src/gfx10/opcodes.rs +++ b/crates/victory-shader/src/gfx10/opcodes.rs @@ -236,7 +236,7 @@ pub(super) const SOPP: &[(u16, &str)] = &[ (0x023, "s_waitcnt_depctr"), (0x024, "s_round_mode"), (0x025, "s_denorm_mode"), - (0x026, "s_ttracedata_imm"), + (0x028, "s_ttracedata_imm"), ]; pub(super) const SMEM: &[(u16, &str)] = &[ @@ -1313,3 +1313,21 @@ pub(super) const SCRATCH: &[(u16, &str)] = &[ (0x024, "scratch_load_short_d16"), (0x025, "scratch_load_short_d16_hi"), ]; + +#[cfg(test)] +mod tests { + fn bytes(words: &[u32]) -> Vec { + words.iter().flat_map(|w| w.to_le_bytes()).collect() + } + + /// `s_ttracedata_imm 0x1234` as LLVM's GFX10 disassembler tests have it + /// (`gfx10_sopp.txt`: `0x34,0x12,0xa8,0xbf`), SOPP opcode 0x28 as in + /// AMD's RDNA2 ISA. A thread-trace marker, which translation drops. + #[test] + fn s_ttracedata_imm_is_sopp_0x28() { + let code = bytes(&[0xBFA8_1234, 0xBF81_0000]); + let decoded = super::super::decode(&code).unwrap(); + assert_eq!(decoded[0].name(), Some("s_ttracedata_imm")); + assert!(crate::ir::build(&code, false, 1).is_ok()); + } +} From 63df36315956f1fef1dd7068a336ce5177b0baa3 Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:47:28 +0100 Subject: [PATCH 061/445] GPU: a half-float rounding carry raises the exponent, not halves the value f32_to_half rounds to nearest by adding half an ulp to the mantissa, then or-ed the shifted mantissa into the exponent field. When the rounding carried out of the mantissa, that carry is the exponent's low bit: or-ed into an odd exponent it was lost, so values just below a power of two came out at the power below (2 - 2^-12 gave 1.0, not 2.0). Rectangle lists use it for the fourth corner of half-float elements. The carry is now added into the exponent. --- crates/victory-gpu/src/primitive.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index c11c647..a9810d3 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -129,7 +129,10 @@ fn f32_to_half(v: f32) -> u16 { if exp <= 0 { return sign; // too small: zero } - sign | (exp as u16) << 10 | ((man + 0x1000) >> 13) as u16 + // Rounded to nearest: a carry out of the mantissa is added into the + // exponent (`2 - 2^-12` is 2.0); at most it reaches infinity, 0x7c00. + let half = (exp as u32) << 10; + sign | (half + ((man + 0x1000) >> 13)) as u16 } #[cfg(test)] @@ -165,6 +168,24 @@ mod tests { assert_eq!(half_to_f32(0xc000), -2.0); } + /// A rounding that carries out of the mantissa raises the exponent + /// (the carry used to be or-ed into an odd exponent, halving the value). + #[test] + fn halves_round_up_into_the_next_power_of_two() { + assert_eq!(f32_to_half(2.0 - 2f32.powi(-12)), 0x4000); + assert_eq!(f32_to_half(0.5 - 2f32.powi(-13)), 0x3800); + assert_eq!(f32_to_half(65520.0), 0x7c00, "past the largest half"); + // An R16_FLOAT element at 1.0, 2^-12 and 1.0: the fourth corner is + // 2 - 2^-12, which rounds to 2.0. + let src: Vec = [0x3c00_u16, 0x0c00, 0x3c00] + .iter() + .flat_map(|h| h.to_le_bytes()) + .collect(); + let mut dst = vec![0u8; 6 * 2]; + expand_rects(&src, &mut dst, 2, &[(0, 54)]); + assert_eq!(dst[10..], 0x4000_u16.to_le_bytes()); + } + /// An element that reaches past the stride (float4 at 4 in 8-byte /// vertices, RGBA8 at the stride itself): the components inside get /// the fourth corner, the rest keep the first vertex's bytes. The old From 717f322c3ced51ea6f4baae4790a83efa2b2e184 Mon Sep 17 00:00:00 2001 From: Maraco91 <43787609+Maraco91@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:48:40 +0100 Subject: [PATCH 062/445] GPU: GetDevice and the DXGI device hand out the device at every level The device answers QueryInterface for ID3D12Device and for its newer levels (Grand Theft Auto VI creates it as ID3D12Device11). A device child's GetDevice and the DXGI device's QueryInterface knew only the first: asked for the device by the interface the title holds, they answered E_NOINTERFACE with a null pointer. Both now ask the device's own test (is_device). Co-Authored-By: Claude Fable 5.2 --- crates/victory-gpu/src/device.rs | 51 +++++++++++++++++++++++++++++++- crates/victory-gpu/src/dxgi.rs | 2 +- crates/victory-gpu/src/object.rs | 5 ++-- 3 files changed, 54 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index 39a38a0..cce7ed2 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -88,7 +88,8 @@ const LEVEL_IIDS: [Iid; 9] = [ ), ]; -fn is_device(iid: *const Iid) -> bool { +/// Whether `iid` names the device: its first interface or a newer level. +pub(crate) fn is_device(iid: *const Iid) -> bool { object::is(iid, &[IID]) || object::is(iid, &LEVEL_IIDS) } @@ -445,6 +446,54 @@ mod tests { assert_eq!(missing(), E_NOTIMPL); } + /// A device child, and the DXGI device, hand out the device as any + /// interface the device itself answers to. + #[test] + fn the_device_is_found_at_every_level_through_others() { + type Get = extern "system" fn(This, *const Iid, *mut This) -> HRESULT; + let fence_iid = &crate::fence::FENCE_IIDS[0]; + let mut fence = std::ptr::null(); + assert_eq!( + crate::fence::create(std::ptr::null(), 0, 0, fence_iid, &mut fence), + S_OK + ); + let get_device = slot::(fence, 0x38); + let dxgi = dxgi::device(); + let query = slot::(dxgi, 0); + for iid in std::iter::once(&IID).chain(&LEVEL_IIDS) { + let mut found = std::ptr::null(); + assert_eq!(get_device(fence, iid, &mut found), S_OK, "{iid:02x?}"); + assert_eq!(found, device()); + let mut found = std::ptr::null(); + assert_eq!(query(dxgi, iid, &mut found), S_OK, "{iid:02x?}"); + assert_eq!(found, device()); + } + // What the device is not, it is not through them either. + let mut found = device(); + assert_eq!(get_device(fence, fence_iid, &mut found), E_NOINTERFACE); + assert!(found.is_null()); + slot:: u32>(fence, 0x10)(fence); + } + + /// The host's: a fence's `GetDevice` for `ID3D12Device5`. + #[cfg(windows)] + #[test] + fn the_hosts_children_hand_out_newer_device_levels() { + use windows::Win32::Graphics::Direct3D12::{ + D3D12_FENCE_FLAG_NONE, ID3D12Device5, ID3D12Fence, + }; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + // SAFETY: plain calls on the host device and its fence. + unsafe { + let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut device: Option = None; + assert!(fence.GetDevice(&mut device).is_ok()); + assert!(device.is_some()); + } + } + #[test] fn virtual_memory_configuration_reports_user_space() { let mut config = VirtualMemory { diff --git a/crates/victory-gpu/src/dxgi.rs b/crates/victory-gpu/src/dxgi.rs index 1ce11c7..c7f7c45 100644 --- a/crates/victory-gpu/src/dxgi.rs +++ b/crates/victory-gpu/src/dxgi.rs @@ -92,7 +92,7 @@ fn query(kind: usize, iid: *const Iid, known: &[Iid], found: This, out: *mut Thi /// The DXGI device also answers for the D3D12 device. extern "system" fn device_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { - if object::is(iid, &[crate::device::IID]) { + if crate::device::is_device(iid) { return object::answer(DXGI_DEVICE, iid, Some(crate::device::device()), out); } query(DXGI_DEVICE, iid, &DEVICE_IIDS, this, out) diff --git a/crates/victory-gpu/src/object.rs b/crates/victory-gpu/src/object.rs index 3d48fe3..156c92d 100644 --- a/crates/victory-gpu/src/object.rs +++ b/crates/victory-gpu/src/object.rs @@ -223,13 +223,14 @@ pub(crate) extern "system" fn set_name(this: This, name: *const u16) -> HRESULT S_OK } -/// The device-child method: the device that made the object. +/// The device-child method: the device that made the object, as any of +/// the interfaces the device itself answers to. pub(crate) extern "system" fn parent_device(_: This, iid: *const Iid, out: *mut This) -> HRESULT { let device = crate::device::device(); answer( DEVICE, iid, - is(iid, &[crate::device::IID]).then_some(device), + crate::device::is_device(iid).then_some(device), out, ) } From 5f29f3ae5a92eef900c77cfa0dc824cc4b812e09 Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:54:49 +0100 Subject: [PATCH 063/445] Loader: a title DLL that fails to prepare is named in the error Reading and loading a title DLL report its path when they fail; preparing it, in between, did not. A DLL the PE parser refuses ended the run with just "malformed image: ..." (or the like), without saying which of the title's DLLs it was. The prepare step now adds "preparing " like its neighbours. --- crates/victory-loader/src/windows.rs | 4 ++-- crates/victory-loader/tests/title_dlls.rs | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 crates/victory-loader/tests/title_dlls.rs diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs index 67845f1..e709d11 100644 --- a/crates/victory-loader/src/windows.rs +++ b/crates/victory-loader/src/windows.rs @@ -152,8 +152,8 @@ fn map_dll( return Ok(()); } let original = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?; - let image = load(&prepare(&original)?, dirs.1) - .with_context(|| format!("loading {}", path.display()))?; + let prepared = prepare(&original).with_context(|| format!("preparing {}", path.display()))?; + let image = load(&prepared, dirs.1).with_context(|| format!("loading {}", path.display()))?; map_imports(&image.info, dirs, wanted, seen, loaded)?; loaded.push((name, image)); Ok(()) diff --git a/crates/victory-loader/tests/title_dlls.rs b/crates/victory-loader/tests/title_dlls.rs new file mode 100644 index 0000000..49101bf --- /dev/null +++ b/crates/victory-loader/tests/title_dlls.rs @@ -0,0 +1,16 @@ +//! A title DLL that cannot be loaded is named in the error. +#![cfg(windows)] + +#[test] +fn a_title_dll_that_does_not_prepare_is_named() { + let title = tempfile::tempdir().unwrap(); + let cache = tempfile::tempdir().unwrap(); + std::fs::write(title.path().join("broken.dll"), b"MZ not a PE").unwrap(); + let wanted = |_: &str| true; + let loaded = victory_loader::load_title_dll("broken.dll", title.path(), cache.path(), &wanted); + let Err(error) = loaded else { + panic!("a DLL that is not a PE loaded"); + }; + let text = format!("{error:#}"); + assert!(text.contains("broken.dll"), "{text}"); +} From 9fe73ba9774cc6d81d221fe74aaf870b68cfe43c Mon Sep 17 00:00:00 2001 From: artor410 <62668404+artor410@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:15:06 -0300 Subject: [PATCH 064/445] shader: decode the packed typed-buffer formats Typed buffer loads in the 10_11_11, 11_11_10 and 10_10_10_2 families (GFX10 unified formats 30-49) were refused, failing the shader. Fill in their channel layouts and decode the unsigned 11- and 10-bit floats by shifting them into half position for legacyF16ToF32, which is exact for denormals, infinities and NaNs. Format numbers from LLVM's UfmtGFX10, channel order from Mesa's ac_formats.c. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 143 +++++++++++++++++++----- 1 file changed, 117 insertions(+), 26 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..67415f3 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -101,33 +101,46 @@ fn buffer_format(format: u8) -> Option<(&'static [u32], Numeric)> { const NORM: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint]; const ALL: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float]; const WIDE: &[Numeric] = &[Uint, Sint, Float]; - // `None`: a family not decoded (packed floats, 10_10_10_2). - const FAMILIES: [(Option<&[u32]>, &[Numeric]); 14] = [ - (Some(&[8]), NORM), - (Some(&[16]), ALL), - (Some(&[8, 8]), NORM), - (Some(&[32]), WIDE), - (Some(&[16, 16]), ALL), - (None, ALL), // 10_11_11 - (None, ALL), // 11_11_10 - (None, NORM), // 10_10_10_2 - (Some(&[10, 10, 10, 2]), NORM), // 2_10_10_10 - (Some(&[8, 8, 8, 8]), NORM), - (Some(&[32, 32]), WIDE), - (Some(&[16, 16, 16, 16]), ALL), - (Some(&[32, 32, 32]), WIDE), - (Some(&[32, 32, 32, 32]), WIDE), + // Numbers and order from LLVM's `UfmtGFX10` (`SIDefines.h`); the GFX10 + // buffer formats have no 5_9_9_9. Channel order from Mesa + // (`ac_formats.c`): R11G11B10_FLOAT is 10_11_11, and 10_10_10_2 has + // its 2-bit channel in the lowest bits. + const FAMILIES: [(&[u32], &[Numeric]); 14] = [ + (&[8], NORM), + (&[16], ALL), + (&[8, 8], NORM), + (&[32], WIDE), + (&[16, 16], ALL), + (&[11, 11, 10], ALL), // 10_11_11 + (&[10, 11, 11], ALL), // 11_11_10 + (&[2, 10, 10, 10], NORM), // 10_10_10_2 + (&[10, 10, 10, 2], NORM), // 2_10_10_10 + (&[8, 8, 8, 8], NORM), + (&[32, 32], WIDE), + (&[16, 16, 16, 16], ALL), + (&[32, 32, 32], WIDE), + (&[32, 32, 32, 32], WIDE), ]; let mut n = usize::from(format.checked_sub(1)?); for (bits, numerics) in FAMILIES { if n < numerics.len() { - return Some((bits?, numerics[n])); + return Some((bits, numerics[n])); } n -= numerics.len(); } None } +/// How far a float channel of `width` bits (16, or the unsigned 11- and +/// 10-bit floats of the packed formats) shifts up to be a half: +/// the small floats are a half's exponent (5 bits, biased 15) and the top +/// of its mantissa, without the sign, so `legacyF16ToF32` widens them +/// exactly, denormals, infinities and NaNs included. +fn half_shift(width: u32) -> u32 { + debug_assert!(matches!(width, 10 | 11 | 16), "{width}-bit float"); + if width == 16 { 0 } else { 15 - width } +} + struct Lower<'a> { s: Shader, x: &'a Parts<'a>, @@ -3041,11 +3054,10 @@ 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, and the packed float and 10_10_10_2 - // layouts are refused; decode them when a program needs them. 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. 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. 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; @@ -3132,9 +3144,16 @@ impl<'a> Lower<'a> { Numeric::Sint => signed(self), Numeric::Float if w == 32 => field, Numeric::Float => { + let h = match half_shift(w) { + 0 => field, + k => { + let sh = self.s.m.i32(k); + self.s.m.bin(c, Bin::Shl, field, sh) + } + }; let f = self .s - .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[field]); + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]); float(self, f) } }; @@ -6559,7 +6578,7 @@ impl<'a> Lower<'a> { #[cfg(test)] mod tests { - use super::{Numeric, Parts, buffer_format, lower}; + use super::{Numeric, Parts, buffer_format, half_shift, lower}; use crate::native::{ComputeIo, HwStage, NativeProgram, StageIo}; use crate::{io, ir, resource, structure}; @@ -6645,9 +6664,81 @@ mod tests { buffer_format(77), Some((&[32, 32, 32, 32][..], Numeric::Float)) ); - // Invalid, a packed float, past the table. + // Invalid, past the table. assert_eq!(buffer_format(0), None); - assert_eq!(buffer_format(36), None); assert_eq!(buffer_format(78), None); } + + #[test] + fn packed_buffer_formats_by_number() { + // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, + // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT + // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. + assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); + assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); + assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); + assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); + assert_eq!( + buffer_format(44), + Some((&[2, 10, 10, 10][..], Numeric::Unorm)) + ); + assert_eq!( + buffer_format(45), + Some((&[2, 10, 10, 10][..], Numeric::Snorm)) + ); + assert_eq!( + buffer_format(46), + Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) + ); + assert_eq!( + buffer_format(47), + Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) + ); + assert_eq!( + buffer_format(48), + Some((&[2, 10, 10, 10][..], Numeric::Uint)) + ); + assert_eq!( + buffer_format(49), + Some((&[2, 10, 10, 10][..], Numeric::Sint)) + ); + } + + /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as + /// `legacyF16ToF32` widens it. + fn half(h: u32) -> f32 { + let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); + let v = match e { + 0 => m as f32 * 2f32.powi(-24), + 31 if m == 0 => f32::INFINITY, + 31 => f32::NAN, + _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), + }; + if s == 1 { -v } else { v } + } + + #[test] + fn small_floats_widen_as_halves() { + // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a + // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. + let f11 = |x: u32| half(x << half_shift(11)); + let f10 = |x: u32| half(x << half_shift(10)); + assert_eq!(f11(0), 0.0); + assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal + assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal + assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal + assert_eq!(f11(0x3C0), 1.0); + assert_eq!(f11(0x3E0), 1.5); + assert_eq!(f11(0x7BF), 65024.0); // largest + assert_eq!(f11(0x7C0), f32::INFINITY); + assert!(f11(0x7C1).is_nan()); + assert_eq!(f10(0x001), 2f32.powi(-19)); + assert_eq!(f10(0x020), 2f32.powi(-14)); + assert_eq!(f10(0x1E0), 1.0); + assert_eq!(f10(0x3DF), 64512.0); + assert_eq!(f10(0x3E0), f32::INFINITY); + assert!(f10(0x3FF).is_nan()); + // A 16-bit float is a half already, sign included. + assert_eq!(half(0xBC00 << half_shift(16)), -1.0); + } } From a3d3bc91e7c645414b09a6db910154720f499a80 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 01:09:16 +0000 Subject: [PATCH 065/445] Shaders: trace descriptors chosen by s_cselect and s_cmov A descriptor picked without a branch, as the compiler does when it hoists both loads (invariant memory) and turns the if/else into a select, reaches the resource instruction through s_cselect_b64 per half (or s_cselect_b32 / s_cmov per dword). None of its dwords is then a load, so tracking stopped with "a descriptor neither loaded nor built" and the whole program, and every draw using it, was dropped. Such words are now split by the SCC value they all read: what each is when SCC is set (S0) and when it is clear (S1, or the old destination for s_cmov), with words not selected the same on both sides, and each side traced on its own into a new Source::Select. Selections with different conditions stop, and a choice that mixes two descriptors still stops as "a descriptor changed after loading". The lowering picks the heap index of the two loaded descriptors by SCC and creates one heap handle, as a phi of loaded descriptors already does per edge. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66 --- crates/victory-shader/src/emit/lower.rs | 125 ++++++++++++++++- crates/victory-shader/src/resource.rs | 175 +++++++++++++++++++++++- 2 files changed, 296 insertions(+), 4 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..25c1657 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -3168,7 +3168,7 @@ impl<'a> Lower<'a> { /// The used-resource entry a descriptor loaded from a table falls in. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> { - if let Source::Phi { args, .. } = src { + if let Source::Phi { args, .. } | Source::Select { args, .. } = src { return self.used_kind(args.first()?); } if let Source::Built { address, .. } = src { @@ -3287,6 +3287,24 @@ impl<'a> Lower<'a> { self.s.m.set_phi(phi, incoming); Ok(self.s.heap_handle(self.cur, phi, sampler, props)) } + Source::Select { scc, args } => { + // The heap index of each choice, picked by SCC (uniform). + let [ + Source::Loaded { load: a, first: fa }, + Source::Loaded { load: b, first: fb }, + ] = args[..] + else { + return Err("a descriptor chosen by a condition"); + }; + let cond = match self.get(*scc)? { + Val::Bit(x) => x, + _ => return Err("SCC without a value"), + }; + let set = self.heap_index(a, fa, sampler)?; + let clear = self.heap_index(b, fb, sampler)?; + let index = self.s.m.select(self.cur, cond, set, clear); + Ok(self.s.heap_handle(self.cur, index, sampler, props)) + } } } @@ -6559,8 +6577,10 @@ impl<'a> Lower<'a> { #[cfg(test)] mod tests { - use super::{Numeric, Parts, buffer_format, lower}; - use crate::native::{ComputeIo, HwStage, NativeProgram, StageIo}; + use super::{Lowered, Numeric, Parts, buffer_format, lower}; + use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, + }; use crate::{io, ir, resource, structure}; const S_ENDPGM: u32 = 0xBF81_0000; @@ -6598,6 +6618,67 @@ mod tests { .map(|_| ()) } + /// Lowers a compute program with the root parameters `layout` (in user + /// SGPRs from s0 on) and the used resources `used`. + fn lower_with( + words: &[u32], + layout: Vec, + used: Vec, + ) -> Result { + lower_wave(words, layout, used, false) + } + + /// [`lower_with`] in wave64 if `wave64`. + fn lower_wave( + words: &[u32], + layout: Vec, + used: Vec, + wave64: bool, + ) -> Result { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: 256, + layout, + used, + io: StageIo::Cs(ComputeIo { + // The layout's user SGPRs (at least two), 512 bytes of LDS. + rsrc2: 1 << 15 | sgprs.max(2) << 1, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, wave64, 256).unwrap(); + let res = resource::track(&p, &native.layout, native.stage)?; + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + } + + /// Root parameter `slot` in user SGPRs from `user_data` on. + fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs: if root == RootType::Descriptor { 2 } else { 1 }, + base_register: 0, + user_data, + slot, + } + } + #[test] fn a_scalar_carry_chain_reaches_the_select() { // The high dword of a 64-bit add or subtract, then a select on the @@ -6630,6 +6711,44 @@ mod tests { } } + #[test] + fn a_descriptor_selected_by_scc_picks_its_heap_index() { + // Two buffer descriptors loaded from the table at s0, one picked by + // a root constant (s1) with s_cselect_b64 per half, and loaded + // through by index and stored to LDS so the load is needed. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xF408_0302, + 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] + 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] + 0xE030_2000, + 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + // Both are structured buffers of dwords in the table's range. + let used = || { + vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }] + }; + lower_with(&words, layout(), used()).unwrap(); + } + #[test] fn buffer_formats_by_number() { // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 46cf891..f2cf696 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -54,13 +54,18 @@ pub enum Source { /// Chosen by control flow: one source per predecessor of `block`, in /// [`crate::ir::Block::preds`] order. Phi { block: usize, args: Vec }, + /// Chosen by SCC (`scc`, the value an `s_cselect` or `s_cmov` of each + /// dword reads): the source when it is set, then when it is clear. + Select { scc: Value, args: Vec }, } impl Source { /// The sources this one picks from (itself unless a phi). pub fn leaves(&self) -> Vec<&Source> { match self { - Source::Phi { args, .. } => args.iter().flat_map(Source::leaves).collect(), + Source::Phi { args, .. } | Source::Select { args, .. } => { + args.iter().flat_map(Source::leaves).collect() + } s => vec![s], } } @@ -644,6 +649,9 @@ impl<'a> Tracer<'a> { if let Some(source) = self.phi(words, joins)? { return Ok(source); } + if let Some(source) = self.select(words, joins)? { + return Ok(source); + } if let Some(consts) = words .iter() .map(|w| match *w { @@ -728,6 +736,96 @@ impl<'a> Tracer<'a> { Ok(Some(Source::Phi { block, args: args? })) } + /// Words that `s_cselect` (or `s_cmov`) picks by one SCC value, traced + /// per outcome (other words are the same for both). + fn select( + &self, + words: &[Term], + joins: &mut Vec, + ) -> Result, &'static str> { + let picks: Vec<_> = words + .iter() + .map(|w| match *w { + Term::Value(v) => self.picked(v), + Term::Const(_) => None, + }) + .collect(); + let Some(scc) = picks.iter().flatten().map(|p| p.0).next() else { + return Ok(None); + }; + if picks.iter().flatten().any(|p| p.0 != scc) { + return Err("a descriptor chosen by several conditions"); + } + // Each level doubles the sources; selects count like joins (a + // marker no block index reaches). + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(usize::MAX); + let side = |set: bool| -> Vec { + words + .iter() + .zip(&picks) + .map(|(w, p)| match p { + Some((_, t, f)) => { + if set { + *t + } else { + *f + } + } + None => *w, + }) + .collect() + }; + let args = [true, false] + .into_iter() + .map(|set| self.classify(&side(set), joins)) + .collect::>(); + joins.pop(); + Ok(Some(Source::Select { scc, args: args? })) + } + + /// For `v` written by `s_cselect_b32`/`_b64` or `s_cmov_b32`/`_b64`: + /// the SCC it reads and the dword it is when SCC is set, then clear. + fn picked(&self, v: Value) -> Option<(Value, Term, Term)> { + let inst = self.def(v)?; + let Fields::Sop { dst, src, .. } = &inst.fields else { + return None; + }; + let k = inst.writes.iter().position(|w| w.1 == v)? as u8; + let wide = match inst.name() { + "s_cselect_b32" | "s_cmov_b32" => false, + "s_cselect_b64" | "s_cmov_b64" => true, + _ => return None, + }; + // A dword of a 32- or 64-bit operand: 64-bit inline integers are + // sign-extended; 64-bit literals and float constants are not + // followed. + let dword = |op: &Operand| match *op { + Operand::Scalar { code: NULL, .. } => Some(Term::Const(0)), + Operand::Scalar { code, .. } => Some(self.origin(inst.read(Reg::S(code + k))?)), + Operand::Const(c) if !wide => inline(c).map(Term::Const), + Operand::Const(c @ 128..=208) => { + let low = inline(c)?; + Some(Term::Const(if k == 0 { + low + } else { + ((low as i32) >> 31) as u32 + })) + } + Operand::Literal(x) if !wide => Some(Term::Const(x)), + _ => None, + }; + let set = dword(src.first()?)?; + let clear = if inst.name().starts_with("s_cmov") { + dword(dst.as_ref()?)? + } else { + dword(src.get(1)?)? + }; + Some((inst.read(Reg::Scc)?, set, clear)) + } + /// `v` as some other dword with constant bits set. fn set_bits(&self, v: Value) -> Option<(Term, u32)> { if let Some((_, [x, Term::Const(bits)] | [Term::Const(bits), x])) = @@ -1097,6 +1195,81 @@ mod tests { ); } + #[test] + fn descriptors_selected_by_scc_are_traced_per_outcome() { + // Two buffer descriptors loaded from the table at s9 and one + // picked with s_cselect_b64 per half, as the compiler makes a + // conditional choice of resources without a branch. + let r = track_words( + &[ + 0xBE8C_0309, // s_mov_b32 s12, s9 + 0xBE8D_0380, // s_mov_b32 s13, 0 + 0xF408_0006, + 0xFA00_0000, // s_load_dwordx4 s[0:3], s[12:13], null + 0xF408_0106, + 0xFA00_0010, // s_load_dwordx4 s[4:7], s[12:13], 0x10 + 0xBF06_800E, // s_cmp_eq_u32 s14, 0 + 0x8588_0400, // s_cselect_b64 s[8:9], s[0:1], s[4:5] + 0x858A_0602, // s_cselect_b64 s[10:11], s[2:3], s[6:7] + 0xF420_0404, + 0xFA00_0000, // s_buffer_load_dword s16, s[8:11], null + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + let Source::Select { args, .. } = &r.descriptors[0].source else { + panic!("{:?}", r.descriptors) + }; + // SCC set picks the first operand. + assert_eq!( + args[..], + [ + Source::Loaded { + load: (0, 2), + first: 0 + }, + Source::Loaded { + load: (0, 3), + first: 0 + }, + ] + ); + assert_eq!(r.scalar, [((0, 2), at(0, 0)), ((0, 3), at(0, 0x10))]); + } + + #[test] + fn a_selection_that_mixes_two_descriptors_fails() { + // The high half picked from the first load whatever SCC is: when + // clear, the descriptor is half of one load and half of the other. + let code: Vec = [ + 0xBE8C_0309, // s_mov_b32 s12, s9 + 0xBE8D_0380, // s_mov_b32 s13, 0 + 0xF408_0006, + 0xFA00_0000, // s_load_dwordx4 s[0:3], s[12:13], null + 0xF408_0106, + 0xFA00_0010, // s_load_dwordx4 s[4:7], s[12:13], 0x10 + 0xBF06_800E, // s_cmp_eq_u32 s14, 0 + 0x8588_0400, // s_cselect_b64 s[8:9], s[0:1], s[4:5] + 0x858A_0202, // s_cselect_b64 s[10:11], s[2:3], s[2:3] + 0xF420_0404, + 0xFA00_0000, // s_buffer_load_dword s16, s[8:11], null + S_ENDPGM, + ] + .iter() + .flat_map(|w: &u32| w.to_le_bytes()) + .collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps).unwrap_err(); + assert_eq!( + err, + ShaderError::Unsupported { + offset: 36, + what: "a descriptor changed after loading" + } + ); + } + #[test] fn untraceable_addresses_fail_with_a_reason() { let code: Vec = [0xF408_0001, 0xFA00_0000, S_ENDPGM] // s_load_dwordx4 s[0:3], s[2:3] From ffa663571fd0a14b9beb0889d6c48468010601fb Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 01:41:38 +0000 Subject: [PATCH 066/445] Shaders: lower waterfall loops over per-lane descriptors in one pass A descriptor held in VGPRs is used through a waterfall loop: each pass reads the first active lane's dwords with v_readfirstlane_b32, compares them with every lane's own (v_cmp_eq), runs the access with the lanes that match and repeats for the rest. Tracing stopped at the readfirstlane results ("a descriptor neither loaded nor built"). The tracer now follows the read lanes' dwords to where each lane gets its own: global_load_dword* from a table or heap at a per-lane address (an image descriptor's two x4 loads lined up), or a v_cndmask_b32 choice per lane between such sources (e.g. two s_load descriptors). Other sources fail naming them (LDS read, buffer load, phi, input, computed VGPRs). The loop's compares of those reads with their own dwords are recorded. Lowering gives the access each lane's heap index (its load address over the descriptor size, or a per-lane select of indices) with createHandleFromHeap's nonUniformIndex set, lowers the recorded readfirstlanes as the lane's own dword and their compares as true, so the loop runs once with all lanes. Wave32 and wave64 are tested. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66 --- crates/victory-shader/src/emit/lower.rs | 159 +++++- crates/victory-shader/src/emit/shader.rs | 18 +- crates/victory-shader/src/resource.rs | 584 ++++++++++++++++++++++- docs/architecture.md | 5 +- 4 files changed, 755 insertions(+), 11 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 25c1657..a255d8b 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -37,6 +37,12 @@ pub(crate) struct Lowered { pub root_srvs: Vec, pub user_data: Vec, pub samplers: Vec<[u32; 4]>, + /// Heap handles made with a non-uniform index. + #[cfg(test)] + pub nonuniform_handles: u32, + /// Whether the program uses wave operations. + #[cfg(test)] + pub wave_ops: bool, } pub(crate) struct Parts<'a> { @@ -887,6 +893,10 @@ impl<'a> Lower<'a> { cmp_samplers, root_cbvs, root_srvs, + #[cfg(test)] + nonuniform_handles: self.s.nonuniform_handles, + #[cfg(test)] + wave_ops: self.s.flags & flags::WAVE_OPS != 0, dxil: self.s.finish(), user_data, samplers: self.samplers, @@ -3168,7 +3178,9 @@ impl<'a> Lower<'a> { /// The used-resource entry a descriptor loaded from a table falls in. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> { - if let Source::Phi { args, .. } | Source::Select { args, .. } = src { + if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } = + src + { return self.used_kind(args.first()?); } if let Source::Built { address, .. } = src { @@ -3180,7 +3192,7 @@ impl<'a> Lower<'a> { .iter() .find(|u| u.root == RootType::Descriptor && u.user_data == rp.user_data); } - let Source::Loaded { load, first } = src else { + let (Source::Loaded { load, first } | Source::Fetched { load, first }) = src else { return None; }; let a = self.scalar.get(load)?; @@ -3216,7 +3228,7 @@ impl<'a> Lower<'a> { return Ok(h); } let index = self.heap_index(*load, *first, sampler)?; - let h = self.s.heap_handle(self.cur, index, sampler, props); + let h = self.s.heap_handle(self.cur, index, sampler, false, props); self.handles.insert(key, h); Ok(h) } @@ -3285,7 +3297,7 @@ impl<'a> Lower<'a> { let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; let phi = self.s.m.phi(join, self.s.t.i32); self.s.m.set_phi(phi, incoming); - Ok(self.s.heap_handle(self.cur, phi, sampler, props)) + Ok(self.s.heap_handle(self.cur, phi, sampler, false, props)) } Source::Select { scc, args } => { // The heap index of each choice, picked by SCC (uniform). @@ -3303,11 +3315,92 @@ impl<'a> Lower<'a> { let set = self.heap_index(a, fa, sampler)?; let clear = self.heap_index(b, fb, sampler)?; let index = self.s.m.select(self.cur, cond, set, clear); - Ok(self.s.heap_handle(self.cur, index, sampler, props)) + Ok(self.s.heap_handle(self.cur, index, sampler, false, props)) + } + Source::Fetched { .. } | Source::Lanes { .. } => { + // A descriptor each lane has its own of (a waterfall loop + // reads it from the first active lane): each lane's heap + // index, non-uniform. + let index = self.lane_heap_index(src, sampler)?; + Ok(self.s.heap_handle(self.cur, index, sampler, true, props)) } } } + /// The heap index of a descriptor that may differ between lanes, + /// computed in the current block. + fn lane_heap_index(&mut self, src: &Source, sampler: bool) -> Result { + match src { + Source::Loaded { load, first } => self.heap_index(*load, *first, sampler), + Source::Fetched { load, first } => self.fetched_index(*load, *first, sampler), + Source::Lanes { mask, args } | Source::Select { scc: mask, args } => { + let [a, b] = &args[..] else { + return Err("a descriptor chosen per lane"); + }; + let cond = if matches!(src, Source::Lanes { .. }) { + let &m = self + .x + .st + .masks + .get(mask) + .ok_or("a descriptor chosen per lane by an untracked mask")?; + self.boolean(m, self.cur)? + } else { + match self.get(*mask)? { + Val::Bit(x) => x, + _ => return Err("SCC without a value"), + } + }; + let set = self.lane_heap_index(a, sampler)?; + let clear = self.lane_heap_index(b, sampler)?; + Ok(self.s.m.select(self.cur, cond, set, clear)) + } + _ => Err("a per-lane descriptor from neither a heap load nor a choice of them"), + } + } + + /// The heap index of the descriptor at dword `first` of what the global + /// load at `load` reads, in each lane: its address (base plus offsets) + /// over the descriptor size. + fn fetched_index(&mut self, load: Site, first: u8, sampler: bool) -> Result { + const WHY: Why = "a per-lane descriptor load"; + let a = *self + .scalar + .get(&load) + .ok_or("an untracked descriptor load")?; + match self.x.native.layout.get(a.param).map(|p| p.root) { + Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {} + _ => return Err("a descriptor outside the heaps"), + } + let li: &Inst = &self.x.p.blocks[load.0].insts[load.1]; + let Fields::Flat { + addr: Some(Operand::Vector { reg, .. }), + saddr, + offset, + .. + } = li.fields + else { + return Err(WHY); + }; + let c = self.cur; + // The low dword of the address: SGPR base plus VGPR offset, or the + // VGPR pair's low half (heap addresses fit in 32 bits). + let mut at = self.i32_of(li.read(Reg::V(reg)).ok_or(WHY)?)?; + if let Some(Operand::Scalar { code, .. }) = saddr + && code != NULL + { + let base = self.i32_of(li.read(Reg::S(code)).ok_or(WHY)?)?; + at = self.s.m.bin(c, Bin::Add, base, at); + } + let k = self + .s + .m + .i32((offset as i32 as u32).wrapping_add(4 * u32::from(first))); + at = self.s.m.bin(c, Bin::Add, at, k); + let shift = self.s.m.i32(if sampler { 4 } else { 5 }); + Ok(self.s.m.bin(c, Bin::LShr, at, shift)) + } + /// The heap index of the descriptor at dword `first` of what the scalar /// load at `load` reads, computed in the current block. fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result { @@ -3353,6 +3446,12 @@ impl<'a> Lower<'a> { unreachable!() }; let name = inst.name(); + if self.x.res.waterfall.compares.contains(&(b, i)) { + // The first lane's dwords of a waterfall loop are each lane's + // own (see `resource::Waterfall`). + self.lane(inst, Some(true)); + return Ok(()); + } if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) { let r = if v.dpp.is_some() { Err("a compare with DPP") @@ -4010,6 +4109,16 @@ impl<'a> Lower<'a> { let r = self.s.m.select(c, is, a, old); int(self, r) } + "v_readfirstlane_b32" + if inst + .writes + .first() + .is_some_and(|w| self.x.res.waterfall.reads.contains(&w.1)) => + { + // A waterfall loop's read of a descriptor dword: the lane's own. + let a = s(self, 0)?; + int(self, a) + } "v_readfirstlane_b32" => { let a = s(self, 0)?; self.s.flags |= flags::WAVE_OPS; @@ -6749,6 +6858,46 @@ mod tests { lower_with(&words, layout(), used()).unwrap(); } + /// Tables of 2D textures at s0 and samplers at s1. + fn texture_tables() -> (Vec, Vec) { + let range = |kind, user_data, slot| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, + user_data, + slot, + }; + ( + vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], + vec![ + range(ResourceType::Srv, 0, 0), + range(ResourceType::Sampler, 1, 1), + ], + ) + } + + #[test] + fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { + use crate::resource::tests::{ + WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, + }; + for (words, wave64) in [ + (WATERFALL_FETCHED_WAVE32, false), + (WATERFALL_FETCHED_WAVE64, true), + (WATERFALL_PICKED_WAVE32, false), + ] { + let (layout, used) = texture_tables(); + let l = lower_wave(words, layout, used, wave64).unwrap(); + // The loop's reads of the first lane became each lane's own + // dwords: no wave operation is left. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } + } + #[test] fn buffer_formats_by_number() { // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 8389c17..e02747e 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -65,6 +65,8 @@ pub(crate) struct Shader { /// Root SRVs (raw buffers) read, likewise. pub root_srvs: Vec<(u8, V)>, pub flags: u64, + /// Heap handles made with a non-uniform index. + pub nonuniform_handles: u32, /// A compute shader with this thread-group size. pub threads: Option<[u32; 3]>, /// The wave size a compute shader requires (`WaveSize`). @@ -118,6 +120,7 @@ impl Shader { root_cbvs: Vec::new(), root_srvs: Vec::new(), flags: 0, + nonuniform_handles: 0, threads: None, wave_size: None, lds_dwords: 0, @@ -272,14 +275,23 @@ impl Shader { ) } - /// A descriptor heap handle, annotated with `props`. - pub fn heap_handle(&mut self, block: usize, index: V, sampler: bool, props: (u32, u32)) -> V { + /// A descriptor heap handle, annotated with `props`; `nonuniform` when + /// the index may differ between lanes (`NonUniformResourceIndex`). + pub fn heap_handle( + &mut self, + block: usize, + index: V, + sampler: bool, + nonuniform: bool, + props: (u32, u32), + ) -> V { self.flags |= if sampler { flags::SAMPLER_HEAP } else { flags::RESOURCE_HEAP }; - let (s, n) = (self.m.bool(sampler), self.m.bool(false)); + self.nonuniform_handles += u32::from(nonuniform); + let (s, n) = (self.m.bool(sampler), self.m.bool(nonuniform)); let h = self.op( block, "createHandleFromHeap", diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index f2cf696..c7a522f 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -57,13 +57,22 @@ pub enum Source { /// Chosen by SCC (`scc`, the value an `s_cselect` or `s_cmov` of each /// dword reads): the source when it is set, then when it is clear. Select { scc: Value, args: Vec }, + /// Dwords `first..` of what the vector load at `load` (`global_load_*`) + /// reads, each lane at its own address (see [`Resources::scalar`]); the + /// dwords past that load come from loads of the bytes that follow. A + /// descriptor that differs between lanes. + Fetched { load: Site, first: u8 }, + /// Picked per lane by `v_cndmask_b32` reading the lane mask whose low + /// dword is `mask`: the source where the lane's bit is set, then where it + /// is clear. + Lanes { mask: Value, args: Vec }, } impl Source { /// The sources this one picks from (itself unless a phi). pub fn leaves(&self) -> Vec<&Source> { match self { - Source::Phi { args, .. } | Source::Select { args, .. } => { + Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } => { args.iter().flat_map(Source::leaves).collect() } s => vec![s], @@ -94,6 +103,23 @@ pub struct Resources { /// User SGPRs holding root parameters: value on entry, layout index, /// dword within the parameter. pub params: Vec<(Value, usize, u32)>, + pub waterfall: Waterfall, +} + +/// Waterfall loops over descriptors that differ between lanes: each pass +/// reads the first active lane's descriptor with `v_readfirstlane_b32`, +/// compares it with every lane's own (`v_cmp_eq`), and runs the access with +/// the lanes that match. Their accesses take each lane's own descriptor +/// ([`Source::Fetched`], [`Source::Lanes`]), so the first lane's dwords are +/// each lane's own too: the compares hold in every lane and one pass serves +/// all lanes. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Waterfall { + /// The compares, true in every lane. + pub compares: Vec, + /// The `v_readfirstlane_b32` results they compare, each the lane's own + /// source dword. + pub reads: Vec, } /// Traces every descriptor and scalar address of `p`, which runs as @@ -112,6 +138,8 @@ pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result = Vec::new(); for (b, block) in p.blocks.iter().enumerate() { for (i, inst) in block.insts.iter().enumerate() { let site = (b, i); @@ -121,6 +149,7 @@ pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result Result<(), ShaderError> { let source = t.descriptor(inst, op).map_err(fail)?; + first_lane.extend(t.first_lane_words(inst, op).unwrap_or_default()); out.descriptors.push(Descriptor { site, role, source }); Ok(()) }; @@ -159,6 +188,7 @@ pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result Tracer<'a> { if let Some(source) = self.select(words, joins)? { return Ok(source); } + let read = |w: &Term| match *w { + Term::Value(v) => self.first_lane_source(v), + Term::Const(_) => None, + }; + if let Some(sources) = words.iter().map(read).collect::>>() { + // Read from the first active lane, as a waterfall loop does: the + // dwords each lane holds. + let lanes: Vec = sources + .into_iter() + .map(|v| self.lane_term(Term::Value(v))) + .collect(); + return self.per_lane(&lanes, joins); + } + if words.iter().any(|w| read(w).is_some()) { + return Err("a descriptor partly read from the first lane"); + } if let Some(consts) = words .iter() .map(|w| match *w { @@ -850,6 +896,290 @@ impl<'a> Tracer<'a> { } } + /// For a `v_readfirstlane_b32` result: the VGPR value it reads. + fn first_lane_source(&self, v: Value) -> Option { + let inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if inst.name() != "v_readfirstlane_b32" || f.sdwa.is_some() || f.dpp.is_some() { + return None; + } + let Some(&Operand::Vector { reg, .. }) = f.src.first() else { + return None; + }; + inst.read(Reg::V(reg)) + } + + /// The `v_readfirstlane_b32` results the descriptor operand `op` of + /// `inst` is, when every dword is one. + fn first_lane_words(&self, inst: &Inst, op: &Operand) -> Option> { + let Operand::Scalar { code, dwords } = *op else { + return None; + }; + (0..dwords) + .map(|k| match self.origin(inst.read(Reg::S(code + k))?) { + Term::Value(v) => self.first_lane_source(v).map(|_| v), + Term::Const(_) => None, + }) + .collect() + } + + /// `t` through VGPR copies (of VGPRs or of scalars) and copies. + fn lane_term(&self, mut t: Term) -> Term { + for _ in 0..MAX_JOINS * 2 { + let Term::Value(v) = t else { break }; + let next = self.vorigin(v); + if next == t { + break; + } + t = next; + } + t + } + + /// Whether `t` is a value each lane holds its own of (one in VGPRs). + fn varies(&self, t: Term) -> bool { + let Term::Value(v) = t else { return false }; + let reg = match (self.inputs[v.0 as usize], self.phis[v.0 as usize]) { + (Some(reg), _) => Some(reg), + (None, Some((b, i))) => Some(self.p.blocks[b].phis[i].reg), + (None, None) => self + .def(v) + .and_then(|i| i.writes.iter().find(|w| w.1 == v)) + .map(|w| w.0), + }; + matches!(reg, Some(Reg::V(_))) + } + + /// The source of descriptor dwords each lane holds its own of (a + /// waterfall loop reads them from the first active lane): the same in + /// every lane, loaded per lane from memory a heap address points to, or + /// picked per lane between such sources. + fn per_lane(&self, words: &[Term], joins: &mut Vec) -> Result { + let Some(&lane) = words.iter().find(|&&w| self.varies(w)) else { + return self.classify(words, joins); + }; + if let Some(source) = self.fetched(words)? { + return Ok(source); + } + if let Some(source) = self.lane_select(words, joins)? { + return Ok(source); + } + let Term::Value(v) = lane else { unreachable!() }; + let name = self.def(v).map(|i| i.name()); + Err(match name { + _ if self.inputs[v.0 as usize].is_some() => { + "a descriptor read from the first lane of an input VGPR" + } + None => "a descriptor read from the first lane of a phi", + Some(n) if n.starts_with("ds_read") => { + "a descriptor read from the first lane of an LDS read" + } + Some(n) if n.starts_with("buffer_load") => { + "a descriptor read from the first lane of a buffer load" + } + Some(n) if n.starts_with("global_load") || n.starts_with("flat_load") => { + "a descriptor read from the first lane of a partial or mixed load" + } + Some(_) => "a descriptor read from the first lane of computed VGPRs", + }) + } + + /// Dwords of `global_load_dword*` that line up: `first..` of one load, + /// then the bytes that follow (an image descriptor takes two + /// `global_load_dwordx4`). + fn fetched(&self, words: &[Term]) -> Result, &'static str> { + let at = |w: &Term| -> Option<(Site, usize)> { + let Term::Value(v) = *w else { return None }; + let site = self.defs[v.0 as usize]?; + let inst = self.inst(site); + if !inst.name().starts_with("global_load_dword") { + return None; + } + let k = inst + .writes + .iter() + .filter(|w| matches!(w.0, Reg::V(_))) + .position(|w| w.1 == v)?; + Some((site, k)) + }; + let Some(sites) = words.iter().map(at).collect::>>() else { + return Ok(None); + }; + let address = |site: Site| { + let inst = self.inst(site); + let Fields::Flat { + addr, + saddr, + offset, + .. + } = &inst.fields + else { + return Err("a global load"); + }; + self.flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset) + }; + let (load, first) = sites[0]; + let a0 = address(load)?; + for (k, &(site, dword)) in sites.iter().enumerate() { + let a = address(site)?; + let want = a0.offset.wrapping_add(4 * (first + k) as u32); + if (a.param, a.dynamic) != (a0.param, a0.dynamic) + || a.offset.wrapping_add(4 * dword as u32) != want + { + return Err("a descriptor read from the first lane of loads that do not line up"); + } + } + Ok(Some(Source::Fetched { + load, + first: first as u8, + })) + } + + /// Words that `v_cndmask_b32` picks by one lane mask, traced per outcome + /// (other words are the same for both). + fn lane_select( + &self, + words: &[Term], + joins: &mut Vec, + ) -> Result, &'static str> { + let picks: Vec<_> = words + .iter() + .map(|w| match *w { + Term::Value(v) => self.lane_picked(v), + Term::Const(_) => None, + }) + .collect(); + let Some(mask) = picks.iter().flatten().map(|p| p.0).next() else { + return Ok(None); + }; + if picks.iter().flatten().any(|p| p.0 != mask) { + return Err("a descriptor chosen per lane by several masks"); + } + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(usize::MAX); + let side = |set: bool| -> Vec { + words + .iter() + .zip(&picks) + .map(|(w, p)| match p { + Some((_, t, f)) => { + if set { + *t + } else { + *f + } + } + None => *w, + }) + .collect() + }; + let args = [true, false] + .into_iter() + .map(|set| self.per_lane(&side(set), joins)) + .collect::>(); + joins.pop(); + Ok(Some(Source::Lanes { mask, args: args? })) + } + + /// For `v` written by a plain `v_cndmask_b32`: the low dword of the + /// lane mask it reads, and the dword it is where the lane's bit is set + /// (src1), then clear (src0). + fn lane_picked(&self, v: Value) -> Option<(Value, Term, Term)> { + let inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + let Some(Operand::Vector { reg, .. }) = f.dst else { + return None; + }; + if inst.name() != "v_cndmask_b32" + || inst.write(Reg::V(reg)) != Some(v) + || f.abs != 0 + || f.neg != 0 + || f.clamp + || f.omod != 0 + || f.sdwa.is_some() + || f.dpp.is_some() + { + return None; + } + let [clear, set, Operand::Scalar { code, .. }] = f.src[..] else { + return None; + }; + let mask = inst.read(Reg::S(code))?; + let side = |op: &Operand| self.vterm(inst, op).map(|t| self.lane_term(t)); + Some((mask, side(&set)?, side(&clear)?)) + } + + /// The waterfall loops over descriptors read from the first lane (the + /// `v_readfirstlane_b32` results `reads`): the `v_cmp_eq` of those + /// results with the dwords they read. + fn waterfall(&self, reads: &[Value]) -> Waterfall { + let mut out = Waterfall::default(); + if reads.is_empty() { + return out; + } + for (b, block) in self.p.blocks.iter().enumerate() { + for (i, inst) in block.insts.iter().enumerate() { + let Fields::Valu(f) = &inst.fields else { + continue; + }; + let Some(ty) = inst + .name() + .strip_prefix("v_cmp_eq_") + .or(inst.name().strip_prefix("v_cmpx_eq_")) + else { + continue; + }; + let dwords = match ty { + "u32" | "i32" => 1, + "u64" | "i64" => 2, + _ => continue, + }; + if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + continue; + } + // The first lane's dwords on one side, the lane's own on the + // other. + let pair = |first: &Operand, own: &Operand| -> Option> { + let (&Operand::Scalar { code, .. }, &Operand::Vector { reg, .. }) = + (first, own) + else { + return None; + }; + (0..dwords) + .map(|k| { + let Term::Value(x) = self.origin(inst.read(Reg::S(code + k))?) else { + return None; + }; + let lane = inst.read(Reg::V(reg + k))?; + let same = reads.contains(&x) + && self.lane_term(Term::Value(self.first_lane_source(x)?)) + == self.lane_term(Term::Value(lane)); + same.then_some(x) + }) + .collect() + }; + let (Some(a), Some(c)) = (f.src.first(), f.src.get(1)) else { + continue; + }; + if let Some(xs) = pair(a, c).or_else(|| pair(c, a)) { + out.compares.push((b, i)); + for x in xs { + if !out.reads.contains(&x) { + out.reads.push(x); + } + } + } + } + } + out + } + /// Consecutive dwords of one scalar load. fn loaded(&self, words: &[Term]) -> Option { let Term::Value(v0) = words[0] else { @@ -1004,7 +1334,7 @@ pub(crate) fn inline(code: u8) -> Option { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use crate::native::RootType::*; @@ -1286,4 +1616,254 @@ mod tests { } ); } + + /// A waterfall loop over an image descriptor each lane loads from the + /// table at s0 (wave32, assembled with llvm-mc for gfx1030): lane i + /// reads entry i with two `global_load_dwordx4`, the loop reads the + /// first active lane's descriptor into s[12:19], samples with the lanes + /// whose descriptor it is, and repeats for the others. The sampler comes + /// from the table at s1; the result goes to LDS so the sample is needed. + pub(crate) const WATERFALL_FETCHED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0x3402_0085, // v_lshlrev_b32 v1, 5, v0 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94_037E, // s_mov_b32 s20, exec_lo + 0x7E18_0504, // 0x3c: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0x3c + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0xD834_0000, + 0x0000_0C00, // ds_write_b32 v0, v12 + 0xBF81_0000, // s_endpgm + ]; + + /// [`WATERFALL_FETCHED_WAVE32`] in wave64: 64-bit lane masks. + pub(crate) const WATERFALL_FETCHED_WAVE64: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0x3402_0085, // v_lshlrev_b32 v1, 5, v0 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94_047E, // s_mov_b64 s[20:21], exec + 0x7E18_0504, // 0x3c: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0016, + 0x0002_080C, // v_cmp_eq_u64_e64 s[22:23], s[12:13], v[4:5] + 0xD4E2_0018, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s[24:25], s[14:15], v[6:7] + 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xD4E2_0018, + 0x0002_1010, // v_cmp_eq_u64_e64 s[24:25], s[16:17], v[8:9] + 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xD4E2_0018, + 0x0002_1412, // v_cmp_eq_u64_e64 s[24:25], s[18:19], v[10:11] + 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xBE96_2416, // s_and_saveexec_b64 s[22:23], s[22:23] + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x89FE_167E, // s_xor_b64 exec, exec, s[22:23] + 0xBF89_FFE6, // s_cbranch_execnz -> 0x3c + 0xBEFE_0414, // s_mov_b64 exec, s[20:21] + 0xD834_0000, + 0x0000_0C00, // ds_write_b32 v0, v12 + 0xBF81_0000, // s_endpgm + ]; + + /// The same waterfall over one of two image descriptors loaded from the + /// table at s0, picked per lane by `v_cndmask_b32` (lanes below 16 take + /// the first). + pub(crate) const WATERFALL_PICKED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x0208_0820, // v_cndmask_b32 v4, s32, v4, vcc_lo + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x020A_0A21, // v_cndmask_b32 v5, s33, v5, vcc_lo + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x020C_0C22, // v_cndmask_b32 v6, s34, v6, vcc_lo + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0x020E_0E23, // v_cndmask_b32 v7, s35, v7, vcc_lo + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x0210_1024, // v_cndmask_b32 v8, s36, v8, vcc_lo + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x0212_1225, // v_cndmask_b32 v9, s37, v9, vcc_lo + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x0214_1426, // v_cndmask_b32 v10, s38, v10, vcc_lo + 0x7E16_021F, // v_mov_b32 v11, s31 + 0x0216_1627, // v_cndmask_b32 v11, s39, v11, vcc_lo + 0xBE94_037E, // s_mov_b32 s20, exec_lo + 0x7E18_0504, // 0x7c: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0x7c + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0xD834_0000, + 0x0000_0C00, // ds_write_b32 v0, v12 + 0xBF81_0000, // s_endpgm + ]; + + fn waterfall(words: &[u32], wave64: bool) -> Result { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, wave64, 256).unwrap(); + track(&p, &[param(Table, 0, 1), param(Table, 1, 1)], HwStage::Cs) + } + + #[test] + fn descriptors_read_from_the_first_lane_of_per_lane_loads_are_traced_to_them() { + for (words, wave64) in [ + (WATERFALL_FETCHED_WAVE32, false), + (WATERFALL_FETCHED_WAVE64, true), + ] { + let r = waterfall(words, wave64).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| d.role == Role::Resource) + .unwrap(); + let Source::Fetched { load, first: 0 } = image.source else { + panic!("{:?}", image.source) + }; + // The first of the two loads: entry v0 * 32 of the table at s0. + let a = r.scalar.iter().find(|s| s.0 == load).unwrap().1; + assert_eq!((a.param, a.offset), (0, 0)); + assert!(a.dynamic.is_some()); + // The sampler is the same for every lane. + let sampler = r.descriptors.iter().find(|d| d.role == Role::Sampler); + assert!(matches!( + sampler.unwrap().source, + Source::Loaded { first: 0, .. } + )); + // Four 64-bit compares of the first lane's dwords with the lane's + // own; the eight reads become the lane's own dwords. + assert_eq!(r.waterfall.compares.len(), 4); + assert_eq!(r.waterfall.reads.len(), 8); + } + } + + #[test] + fn descriptors_read_from_the_first_lane_of_a_per_lane_choice_are_traced_per_lane() { + let r = waterfall(WATERFALL_PICKED_WAVE32, false).unwrap(); + let image = &r.descriptors[0]; + let Source::Lanes { args, .. } = &image.source else { + panic!("{:?}", image.source) + }; + // Lanes with their bit set take the first load (offset 0), the + // others the second (0x20). + let offsets: Vec = args + .iter() + .map(|a| match *a { + Source::Loaded { load, first: 0 } => { + r.scalar.iter().find(|s| s.0 == load).unwrap().1.offset + } + ref a => panic!("{a:?}"), + }) + .collect(); + assert_eq!(offsets, [0, 0x20]); + assert_eq!(r.waterfall.compares.len(), 4); + } + + #[test] + fn descriptors_read_from_the_first_lane_of_lds_fail_naming_it() { + // The waterfall over descriptors each lane read from LDS: + // ds_read_b128 v[4:7], v1 and ds_read_b128 v[8:11], v1 offset:16 + // in place of the global loads. + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + words[5..9].copy_from_slice(&[0xDBFC_0000, 0x0400_0001, 0xDBFC_0010, 0x0800_0001]); + let err = waterfall(&words, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane of an LDS read", + .. + } + ), + "{err:?}" + ); + } } diff --git a/docs/architecture.md b/docs/architecture.md index a4a95f2..50c9338 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -89,6 +89,9 @@ removes EXEC: lane masks become per-lane booleans, wave-wide mask tests become per-lane branches, and vector instructions keep a guard only where a lane can reach them with its EXEC bit clear. `victory_shader::resource` traces each descriptor and scalar memory address to the root parameter it -comes from (table, heap, root descriptor or constant). `victory translate` +comes from (table, heap, root descriptor or constant). A descriptor a +waterfall loop reads from the first lane (`v_readfirstlane_b32`) is traced +to the per-lane load or choice that gives each lane its own, and accessed +with a non-uniform heap index in one pass. `victory translate` runs every shader it finds (containers, SGD5 files) through these and lists what they cannot handle yet. From b5c66787dafdb16e3090af49cd17682fd2713d5a Mon Sep 17 00:00:00 2001 From: "Abdellah K." <118073627+Abdellah-Khanani@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:14:00 +0100 Subject: [PATCH 067/445] loader: unwind a 16-byte aligned copy of the context RtlVirtualUnwind and RtlCaptureContext want a 16-byte aligned CONTEXT, and windows-sys 0.61 declares the x64 CONTEXT without align(16). In a debug build the by-value copy in unwind_into, and the test's stack context, landed 8 bytes off (an address ending in ...838), so unwinds_like_the_system_walk crashed the whole victory-loader test binary with a stack-overflow message and STATUS_ACCESS_VIOLATION. Aligning only the test's context was not enough: the copy in unwind_into, which the crash handler and stacks.rs also unwind with, faulted as well. unwind_into now copies its context into an Aligned16 wrapper and unwinds that; the test captures into one. Co-Authored-By: Claude Opus 5.5 --- crates/victory-loader/src/crash.rs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index ac31566..47f402e 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -512,10 +512,19 @@ fn unwind(context: CONTEXT) -> Vec { frames } +/// A `CONTEXT` at the 16-byte alignment the unwind and capture functions need. +#[repr(C, align(16))] +pub(crate) struct Aligned16(pub(crate) CONTEXT); + /// [`unwind`] for any thread of the process, its stack being `low..high`; /// pushes no more than `MAX_FRAMES`, so it does not allocate when `frames` /// has that capacity (another thread may be suspended holding the heap). -pub(crate) fn unwind_into(mut context: CONTEXT, low: usize, high: usize, frames: &mut Vec) { +pub(crate) fn unwind_into(context: CONTEXT, low: usize, high: usize, frames: &mut Vec) { + // `RtlVirtualUnwind` writes the context with 16-byte aligned stores, and + // windows-sys declares `CONTEXT` without that alignment: a by-value copy on + // the stack can land 8 bytes off and fault (seen in a debug build). + let mut aligned = Aligned16(context); + let context = &mut aligned.0; frames.push(context.Rip); while frames.len() < MAX_FRAMES { // Stop where reading the stack would fault inside this handler. @@ -539,7 +548,7 @@ pub(crate) fn unwind_into(mut context: CONTEXT, low: usize, high: usize, frames: image, context.Rip, entry, - &mut context, + context, &mut data, &mut frame, null_mut(), @@ -591,11 +600,12 @@ mod tests { fn unwinds_like_the_system_walk() { // SAFETY: zeroed CONTEXT is valid; both calls write our buffers. let (frames, walked) = unsafe { - let mut context: CONTEXT = std::mem::zeroed(); - RtlCaptureContext(&mut context); + // `RtlCaptureContext` wants it 16-byte aligned too. + let mut context = Aligned16(std::mem::zeroed()); + RtlCaptureContext(&mut context.0); let mut walked = [null_mut(); 8]; let n = RtlCaptureStackBackTrace(0, 8, walked.as_mut_ptr(), null_mut()); - (unwind(context), walked[..usize::from(n)].to_vec()) + (unwind(context.0), walked[..usize::from(n)].to_vec()) }; // Frame 0 differs (two call sites in this function); callers agree. assert!(walked.len() >= 4, "{walked:?}"); From 3c814208f1160a1c70f02b13617d652927fbda88 Mon Sep 17 00:00:00 2001 From: hophaver <86059649+hophaver@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:22:41 +0200 Subject: [PATCH 068/445] GPU: drop draws whose fresh tables cannot be made; 2^18 dynamic slots When HostHeap::dynamic ran out, State::tables skipped the fresh table and the stage's user data fell back to the title's table offset. Constant buffer tables are always made fresh and never mirrored, so the shader read whatever host descriptor sat at those slots as a constant buffer; on AMD a texture or null descriptor read as a buffer gives a wild base address and the device is removed (#59: faults at 0x7000037xxxxx, 0x8000037xxxxx, 0x33c4000, a different pipeline every run, about 60 s in). bind now reports that a table could not be made, and the draw, mesh dispatch, dispatch or indirect execution is dropped. The dynamic range grows from 2^16 to 2^18 slots, which the world did not exhaust on an RX 9070 XT. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 4 ++- crates/victory-gpu/src/draw.rs | 39 +++++++++++++++++++---- 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 43dba24..7315840 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -62,7 +62,9 @@ const PORTABLE_VIEWS: u32 = 1_000_000; /// Slots past the title's in a view heap, for tables a draw needs made /// afresh (constant buffers copied per draw). A list holds the slots it /// took until it is reset (its submissions have run) or released. -const DYNAMIC: u32 = 1 << 16; +/// 2^16 ran out seconds into the world (every world run on an RX 9070 XT, +/// each a device removal shortly after; #59). +const DYNAMIC: u32 = 1 << 18; impl HostHeap { pub(crate) fn new(sampler: bool, count: u32) -> Option { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index b6e043b..3cf7121 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -77,6 +77,8 @@ pub(crate) struct State { /// The dynamic slots the list holds: title heap, first, count; given /// back when the list is reset or released. dynamic: Vec<(usize, u32, u32)>, + /// A fresh table of the stage being bound could not be made. + table_failed: bool, } impl Drop for State { @@ -344,7 +346,9 @@ impl State { once!(mesh, "a draw or mesh dispatch with another kind of pipeline"); return false; } - self.bind(list, p, false); + if !self.bind(list, p, false) { + return false; + } let l = &list.list; // Vertex buffers the input layout reads. let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32]; @@ -403,7 +407,9 @@ impl State { /// What draws and dispatches share: heaps, our root signature, the /// pipeline, and per stage the user data, root views and the /// descriptors its tables hold. - fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) { + /// False if the draw or dispatch must not run: a table it reads could + /// not be made. + fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { let l = &list.list; // Heaps first: a root signature with directly indexed heaps must be // set after them. @@ -446,7 +452,19 @@ impl State { } for stage in &p.stages { let t = stage.translated(); + self.table_failed = false; let made = self.tables(list, &t.used, compute); + if self.table_failed { + static DROPPED_TABLES: AtomicU64 = AtomicU64::new(0); + let n = DROPPED_TABLES.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::warn!( + dropped = n, + "a draw or dispatch dropped: no dynamic slots for its tables" + ); + } + return false; + } if let Some((param, dwords)) = stage.user_data { let mut values = vec![0u32; dwords as usize]; for u in &t.host.user_data { @@ -489,6 +507,7 @@ impl State { } } } + true } /// Runs a dispatch on the host. @@ -513,7 +532,10 @@ impl State { once!("a dispatch with a graphics pipeline"); return; } - self.bind(list, p, true); + if !self.bind(list, p, true) { + DROPPED.fetch_add(1, Ordering::Relaxed); + return; + } #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); // SAFETY: an open list with everything set. @@ -696,6 +718,12 @@ impl State { continue; } let Some(first) = host.dynamic(n) else { + // Without its fresh table the shader would read the title's + // slots, which for constant buffer tables hold no constant + // view: a texture or null descriptor read as a buffer gives + // a wild address on AMD and the device is removed (#59). + // The draw or dispatch is dropped instead. + self.table_failed = true; continue; }; self.fresh_tables.insert(key, first); @@ -988,10 +1016,7 @@ impl State { DRAW | INDEXED => self.topology != RECTANGLES && self.prepare(list, kind == INDEXED), MESH => self.prepare_for(list, false, true), DISPATCH => match crate::pipeline::host_pipeline(self.pipeline as This) { - Some(p) if p.compute => { - self.bind(list, p, true); - true - } + Some(p) if p.compute => self.bind(list, p, true), _ => false, }, _ => false, From cc63aa269f0750b8848813c467676d3a23f188a4 Mon Sep 17 00:00:00 2001 From: Enzo Souza Duarte Date: Mon, 23 Nov 2026 23:24:21 -0300 Subject: [PATCH 069/445] Config: ignore an empty VICTORY_TEST_TITLES --- crates/victory-core/src/config.rs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/victory-core/src/config.rs b/crates/victory-core/src/config.rs index 596aa43..4697996 100644 --- a/crates/victory-core/src/config.rs +++ b/crates/victory-core/src/config.rs @@ -80,10 +80,10 @@ impl Config { ) -> Result { let env_path = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from); let test_titles = match env("VICTORY_TEST_TITLES") { - Some(v) => std::env::split_paths(&v) + Some(v) if !v.is_empty() => std::env::split_paths(&v) .filter(|p| !p.as_os_str().is_empty()) .collect(), - None => file.test_titles, + _ => file.test_titles, }; let cache_dir = env_path("VICTORY_CACHE_DIR") .or(file.cache_dir) @@ -165,6 +165,29 @@ mod tests { assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-file")); } + #[test] + fn empty_test_titles_env_is_ignored() { + let file = FilePaths { + test_titles: vec!["from-file".into()], + ..Default::default() + }; + let env = |k: &str| (k == "VICTORY_TEST_TITLES").then(OsString::new); + let cfg = Config::resolve(file, None, env).unwrap(); + assert_eq!(cfg.test_titles, vec![PathBuf::from("from-file")]); + } + + #[test] + fn test_titles_env_splits_paths() { + let value = std::env::join_paths(["first", "second"]).unwrap(); + let file = FilePaths::default(); + let env = |k: &str| (k == "VICTORY_TEST_TITLES").then(|| value.clone()); + let cfg = Config::resolve(file, None, env).unwrap(); + assert_eq!( + cfg.test_titles, + vec![PathBuf::from("first"), PathBuf::from("second")] + ); + } + #[test] fn example_config_parses() { let text = include_str!("../../../victory.example.toml"); From 40c127cbb3f43eabf42eb2576c767b6c98f82647 Mon Sep 17 00:00:00 2001 From: Enzo Souza Duarte Date: Mon, 23 Nov 2026 23:33:45 -0300 Subject: [PATCH 070/445] Chore: clear two workspace Clippy errors --- crates/victory-gpu/src/host.rs | 2 ++ crates/victory-hle/src/modules/xmem.rs | 6 ++++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index c041282..8026ee3 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -264,6 +264,8 @@ mod tests { factory.EnumWarpAdapter::() }; let Ok(raw) = raw else { return }; + // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements + // IDXGIAdapter1; `raw` owns that interface. let desc = unsafe { raw.cast::().unwrap().GetDesc1().unwrap() }; eprintln!( "EnumWarpAdapter: vendor={:#x}, flags={:#x}", diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 07a149a..851fcbd 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -743,8 +743,10 @@ fn commit(base: usize, len: usize) -> bool { } let error = std::io::Error::last_os_error(); if error.raw_os_error() == Some(ERROR_COMMITMENT_LIMIT as i32) { - let mut info = PERFORMANCE_INFORMATION::default(); - info.cb = size_of::() as u32; + let mut info = PERFORMANCE_INFORMATION { + cb: size_of::() as u32, + ..Default::default() + }; // SAFETY: the buffer and size describe a writable PERFORMANCE_INFORMATION. let queried = unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0; victory_loader::log_crash(&commit_limit_message(len, &error, queried.then_some(&info))); From efb3e3d3da6deb6aa61e2e5efb7ded4af358d233 Mon Sep 17 00:00:00 2001 From: FIocker <4461558+FIocker@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:34:24 +0100 Subject: [PATCH 071/445] GPU diagnostics: order tied drop counts consistently --- crates/victory-gpu/src/pipeline.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index d488d03..b1dc393 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -283,7 +283,9 @@ pub(crate) fn note_why(why: String) { pub(crate) fn take_drops() -> Vec<(String, u64)> { let drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut drops: Vec<(String, u64)> = drops.into_iter().flatten().collect(); - drops.sort_by_key(|d| std::cmp::Reverse(d.1)); + // Frame reports only show the first 40 reasons. Keep ties ordered so + // a HashMap iteration order change cannot change which reasons appear. + drops.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); drops } From 376b3cf1785380cc397fdf89027f46e3472a6b55 Mon Sep 17 00:00:00 2001 From: marquezini Date: Mon, 23 Nov 2026 23:35:59 -0300 Subject: [PATCH 072/445] Storage: a path buffer too small fails with E_FAIL, as on Xbox XPersistentLocalStorageGetPath documents E_FAIL for a pathSize smaller than the path on Xbox devices; ERROR_INSUFFICIENT_BUFFER is the PC result, which put_string gave us. --- crates/victory-hle/src/modules/storage.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/victory-hle/src/modules/storage.rs b/crates/victory-hle/src/modules/storage.rs index c8863fb..585b641 100644 --- a/crates/victory-hle/src/modules/storage.rs +++ b/crates/victory-hle/src/modules/storage.rs @@ -38,6 +38,8 @@ pub const IID_2026: Guid = Guid::new( pub static OBJECT: Object = Object::new("persistent local storage", &VTABLE); pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT), (PROVIDER, IID_2026, &OBJECT)]; +const E_FAIL: HRESULT = 0x8000_4005_u32 as i32; + type This = *const Object; /// The path titles get: the root of a virtual drive over the folder. On the @@ -63,8 +65,11 @@ extern "system" fn path_size(_: This, out: *mut usize) -> HRESULT { } } +/// A buffer too small for the path fails with `E_FAIL`, the documented +/// Xbox result (a PC gets `ERROR_INSUFFICIENT_BUFFER`). extern "system" fn path(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { match folder() { + Some(path) if size <= path.len() => E_FAIL, Some(path) => put_string(&path, size, buffer, used), None => NOT_SUPPORTED, } @@ -196,6 +201,7 @@ mod tests { let (mut buffer, mut used) = ([0u8; 4], 0); let get = method::(&OBJECT, 0x20); assert_eq!(get(this, 4, buffer.as_mut_ptr(), &mut used), S_OK); + assert_eq!(get(this, 3, buffer.as_mut_ptr(), &mut used), E_FAIL); let drive = std::str::from_utf8(&buffer[..3]).unwrap(); assert!(drive.ends_with(":\\"), "{drive}"); // Title file calls on it reach the folder. From a4e7f1d004bff927c205981c623142c8e7dbb4a4 Mon Sep 17 00:00:00 2001 From: FIocker <4461558+FIocker@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:37:31 +0100 Subject: [PATCH 073/445] GPU: replay pending descriptors before publishing the host heap --- crates/victory-gpu/src/descriptor.rs | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 9ae83bd..20b33fb 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -85,15 +85,18 @@ impl Heap { return None; } let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); - let h = self - .host - .get_or_init(|| host::HostHeap::new(self.samplers(), self.desc.count)) - .as_ref()?; - let step = u64::from(increment(self.desc.kind)?); - for i in pending.drain(..) { - h.mirror(i, self.start + u64::from(i) * step, false); - } - Some(h) + // A recorder can take the fast path as soon as the OnceLock is + // initialized. Publish only after replaying the queued writes. + self.host + .get_or_init(|| { + let step = u64::from(increment(self.desc.kind)?); + let h = host::HostHeap::new(self.samplers(), self.desc.count)?; + for i in pending.drain(..) { + h.mirror(i, self.start + u64::from(i) * step, false); + } + Some(h) + }) + .as_ref() } /// The descriptor index of `handle` in this heap, if it lies in it. From 0f369d660c9e5ace8482f2f9cc5572c9805e9416 Mon Sep 17 00:00:00 2001 From: marquezini Date: Mon, 23 Nov 2026 23:37:46 -0300 Subject: [PATCH 074/445] Capture: R16G16B16A16_UNORM targets are integers, format 89 is 10:10:10:2 Frame dumps decoded DXGI format 11 (R16G16B16A16_UNORM) as half floats, so 0x8000 came out as -0 and 0xffff as -inf, and 12-14 were not handled. Format 89 (R10G10B10_XR_BIAS_A2_UNORM) went through the B8G8R8A8 swap. --- crates/victory-gpu/src/capture.rs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index 28c2569..e91cf62 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -336,7 +336,8 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option } return Some(out); } - 87..=93 => { + // B8G8R8A8 and B8G8R8X8 (89 is R10G10B10_XR_BIAS_A2, below). + 87 | 88 | 90..=93 => { for y in 0..h { for x in 0..w { let p = px(x, y, 4); @@ -345,7 +346,7 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option } return Some(out); } - 23..=25 => (4, Box::new(move |b| { + 23..=25 | 89 => (4, Box::new(move |b| { let v = u32_at(b, 0); [(v & 0x3ff) as f32, (v >> 10 & 0x3ff) as f32, (v >> 20 & 0x3ff) as f32] })), @@ -353,7 +354,8 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option let v = u32_at(b, 0); [small_float(v & 0x7ff, 6), small_float(v >> 11 & 0x7ff, 6), small_float(v >> 22, 5)] })), - 9..=11 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])), + 9..=10 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])), + 11..=14 => (8, Box::new(move |b| [0, 1, 2].map(|i| f32::from(u16_at(b, i))))), 33..=34 => (4, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0])), 1..=2 => (16, Box::new(move |b| { [0, 1, 2].map(|i| f32::from_bits(u32_at(b, i))) @@ -522,4 +524,18 @@ mod tests { fn crc_matches_the_png_check_value() { assert_eq!(super::crc32(b"IEND"), 0xae42_6082); } + + /// R16G16B16A16_UNORM is integers, not half floats; 89 is 10:10:10:2, + /// not B8G8R8A8. + #[test] + fn unorm16_and_xr_bias_targets_decode_as_their_formats() { + // Red 0x8000 (a half-float -0), green 0x4000, blue 0. + let unorm16 = [0x00, 0x80, 0x00, 0x40, 0, 0, 0xff, 0xff]; + assert_eq!(super::to_rgba(11, 1, 1, 8, &unorm16), Some(vec![255, 127, 0, 255])); + // Red 0x3ff, green 0x1ff, blue 0, alpha 3. + let xr = (0x3ffu32 | 0x1ff << 10 | 3 << 30).to_le_bytes(); + assert_eq!(super::to_rgba(89, 1, 1, 4, &xr), Some(vec![255, 127, 0, 255])); + // B8G8R8A8 still swaps to RGBA. + assert_eq!(super::to_rgba(87, 1, 1, 4, &[1, 2, 3, 4]), Some(vec![3, 2, 1, 255])); + } } From ded334bb9172865a9be7acdb8a2047358a30e4db Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Mon, 23 Nov 2026 23:43:35 -0300 Subject: [PATCH 075/445] Shaders: lower v_cvt_norm_i16_f16 and v_cvt_norm_u16_f16 The f16 source (with abs/neg) is clamped to [-1, 1] or [0, 1], scaled by 32767 or 65535 and rounded to nearest even once from the exact product; NaN gives 0. The product is formed in integers from the f16's bits, because in f32 it has up to 26 significant bits and would round first. --- crates/victory-shader/src/emit/lower.rs | 81 ++++++++++++++++++++ crates/victory-shader/src/emit/valu_tests.rs | 46 +++++++++++ 2 files changed, 127 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..2147ce4 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4213,6 +4213,8 @@ impl<'a> Lower<'a> { "v_min_i16", "v_cvt_u16_f16", "v_cvt_i16_f16", + "v_cvt_norm_i16_f16", + "v_cvt_norm_u16_f16", ]; let all = [FLOAT1, FLOAT2, FLOAT3, INT]; if !all.iter().any(|l| l.contains(&name)) @@ -4351,6 +4353,13 @@ impl<'a> Lower<'a> { }; return float_result(self, r); } + if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") { + if v.clamp || v.omod != 0 { + return Err("modifiers on a 16-bit integer operation"); + } + let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?; + return self.write_half(inst, r, guard); + } // 16-bit integers: computed on the low halves, the low 16 bits kept. if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 { return Err("modifiers on a 16-bit integer operation"); @@ -4415,6 +4424,78 @@ impl<'a> Lower<'a> { self.write_half(inst, r, guard) } + /// `v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`: the f16 source (with its + /// abs/neg modifiers) clamped to [-1, 1] or [0, 1], times 32767 or 65535, + /// rounded to nearest even once from the exact product; NaN gives 0. + /// Worked on the f16's bits in integers, because in f32 the product + /// (up to 26 significant bits) would round before the rounding to an + /// integer. + fn cvt_norm16(&mut self, inst: &Inst, signed: bool) -> Result { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let c = self.cur; + let k = |l: &mut Self, x: u32| l.s.m.i32(x); + let mut h = self.half_src(inst, 0)?; + if v.abs & 1 != 0 { + let m = k(self, 0x7FFF); + h = self.s.m.bin(c, Bin::And, h, m); + } + if v.neg & 1 != 0 { + let m = k(self, 0x8000); + h = self.s.m.bin(c, Bin::Xor, h, m); + } + let scale = if signed { 0x7FFF } else { 0xFFFF }; + let (k0, k1, k10) = (k(self, 0), k(self, 1), k(self, 10)); + let mag_mask = k(self, 0x7FFF); + let mag = self.s.m.bin(c, Bin::And, h, mag_mask); + let k15 = k(self, 15); + let neg = self.s.m.bin(c, Bin::LShr, h, k15); + let neg = self.s.m.cmp(c, pred::NE, neg, k0); + // |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24. + let exp = self.s.m.bin(c, Bin::LShr, mag, k10); + let man_mask = k(self, 0x3FF); + let man = self.s.m.bin(c, Bin::And, mag, man_mask); + let implicit = k(self, 0x400); + let normal = self.s.m.bin(c, Bin::Or, man, implicit); + let sub = self.s.m.cmp(c, pred::EQ, exp, k0); + let m = self.s.m.select(c, sub, man, normal); + let k25 = k(self, 25); + let s_norm = self.s.m.bin(c, Bin::Sub, k25, exp); + let k24 = k(self, 24); + let sh = self.s.m.select(c, sub, k24, s_norm); + let ks = k(self, scale); + let p = self.s.m.bin(c, Bin::Mul, m, ks); + let q = self.s.m.bin(c, Bin::LShr, p, sh); + let one_s = self.s.m.bin(c, Bin::Shl, k1, sh); + let low_mask = self.s.m.bin(c, Bin::Sub, one_s, k1); + let rem = self.s.m.bin(c, Bin::And, p, low_mask); + let half = self.s.m.bin(c, Bin::LShr, one_s, k1); + let above = self.s.m.cmp(c, pred::IUGT, rem, half); + let tie = self.s.m.cmp(c, pred::EQ, rem, half); + let odd = self.s.m.bin(c, Bin::And, q, k1); + let odd = self.s.m.cmp(c, pred::NE, odd, k0); + let tie_up = self.s.m.bin(c, Bin::And, tie, odd); + let up = self.s.m.bin(c, Bin::Or, above, tie_up); + let r = self.s.m.select(c, up, k1, k0); + let r = self.s.m.bin(c, Bin::Add, q, r); + // |x| >= 1 (and infinity) saturates; NaN gives 0. + let one_h = k(self, 0x3C00); + let big = self.s.m.cmp(c, pred::IUGE, mag, one_h); + let r = self.s.m.select(c, big, ks, r); + let inf = k(self, 0x7C00); + let nan = self.s.m.cmp(c, pred::IUGT, mag, inf); + let r = self.s.m.select(c, nan, k0, r); + let r = if signed { + let n = self.s.m.bin(c, Bin::Sub, k0, r); + self.s.m.select(c, neg, n, r) + } else { + self.s.m.select(c, neg, k0, r) + }; + let m16 = k(self, 0xFFFF); + Ok(self.s.m.bin(c, Bin::And, r, m16)) + } + /// Half `high` of source `k` of a packed (VOP3P) operation, in the low /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the /// half the high result reads. Inline float constants are f16 values. diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6..1cd4b16 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -420,6 +420,52 @@ fn v_fract_f16_never_returns_one() { }); } +/// RDNA2's flt16_to_snorm16 / flt16_to_unorm16: clamp, scale by 32767 or +/// 65535, round the exact product to nearest even; NaN gives 0. +fn cvt_norm16_reference(bits: u16, signed: bool) -> u16 { + let x = f16_to_f32(bits); + if x.is_nan() { + return 0; + } + let (lo, scale) = if signed { + (-1.0, 32767.0) + } else { + (0.0, 65535.0) + }; + // f64 holds the product of an f16 and a 16-bit scale exactly. + let p = f64::from(x.clamp(lo, 1.0)) * scale; + p.round_ties_even() as i32 as u16 +} + +#[test] +fn v_cvt_norm_i16_and_u16_f16_round_the_exact_product() { + // Every 251st f16 pattern, plus the values where an f32 product would + // round before the rounding to an integer, ties, and the edges. + let mut bits: Vec = (0..=u16::MAX).step_by(251).collect(); + bits.extend([ + 0x0000, 0x8000, 0x0001, 0x8001, 0x03FF, 0x0400, 0x3800, 0xB800, 0x3801, 0xB801, 0x37FF, + 0x3BFF, 0xBBFF, 0x3C00, 0xBC00, 0x3C01, 0x7BFF, 0x7C00, 0xFC00, 0x7E00, 0xFE00, 0x7C01, + 0x3A9B, 0xBA9B, 0x2E66, 0x1400, + ]); + for (op, signed, what) in [ + (0x063u16, true, "v_cvt_norm_i16_f16"), + (0x064, false, "v_cvt_norm_u16_f16"), + ] { + // v_cvt_norm_*16_f16 v0, v1 (VOP1); v0's high half starts at 0. + let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]); + let inputs: Vec<[u32; 4]> = bits.iter().map(|&b| [u32::from(b), 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, _, got| { + let want = cvt_norm16_reference(bits[i], signed); + assert_eq!( + got, + u32::from(want), + "{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}", + bits[i], + ); + }); + } +} + #[test] fn v_sin_and_v_cos_f32_reduce_large_turns() { let sin_shader = build_valu_cs(&[vop1(0x035, 0, vgpr(1))]); From 404d7fd9bd9ee4f1d1a54eca9e8fed369ae29f83 Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:38:51 +0100 Subject: [PATCH 076/445] Shaders: PSV0 says a pixel shader runs per sample when an input does The pipeline state validation part left PSInfo.SampleFrequency at 0. DXC sets it when a pixel input is interpolated per sample (modes 6 and 7, which our lowering gives to PERSP_SAMPLE and LINEAR_SAMPLE barycentrics) or is SV_SampleIndex, and the validator compares the whole runtime info with what it derives from the module. The flag is now set for such pixel shaders. --- crates/victory-shader/src/emit/container.rs | 9 +++ crates/victory-shader/src/emit/mod.rs | 76 +++++++++++++++++++++ 2 files changed, 85 insertions(+) diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index b0d30f9..8b05b12 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -161,6 +161,15 @@ pub(crate) fn psv(p: &Psv) -> Vec { u32s(&mut out, &[48]); let mut info = [0u8; 48]; info[0] = u8::from(p.flag); + if p.stage == 0 { + // PSInfo.SampleFrequency: an input interpolated per sample, or the + // sample index. + info[1] = u8::from( + p.inputs + .iter() + .any(|e| matches!(e.interp, 6 | 7) || e.kind == 12), + ); + } let (min, max) = p.wave_size.map_or((0, u32::MAX), |n| (n, n)); info[16..20].copy_from_slice(&min.to_le_bytes()); info[20..24].copy_from_slice(&max.to_le_bytes()); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0df1233..88cae3e 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -540,6 +540,82 @@ mod tests { assert_eq!(c[4..20], ours[..], "our hash differs from the validator's"); } + /// A pixel shader interpolating at sample positions (PERSP_SAMPLE + /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency: + /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1) + /// whenever an input is interpolated per sample. + #[test] + fn sample_interpolated_inputs_set_psv_sample_frequency() { + let words = [ + 0xC808_0000u32, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + 0xF800_180F, + 0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm + 0xBF81_0000, + ]; + let psv_of = |input_addr: u32| { + let native = super::NativeProgram { + stage: super::HwStage::Ps, + wave64: false, + vgprs: 4, + layout: vec![], + used: vec![], + io: crate::native::StageIo::Ps { + inputs: vec![crate::native::PsInput { + usage: crate::native::Usage::Generic, + row: 0, + mask: 0b1111, + attr: 0, + flat: false, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let el = |name: &str, kind, usage| SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage, + half: false, + }; + let isg1 = super::container::signature(&[el("TEXCOORD", 0, 0)], true); + let osg1 = super::container::signature(&[el("SV_Target", 16, 15)], false); + let bytes = + crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]); + let c = super::Container::parse(&bytes).unwrap(); + let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap(); + // dxil.dll, where there is one, checks PSV0 against the module. + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut out.dxil.clone()).unwrap(); + } + let host = super::Container::parse(&out.dxil).unwrap(); + host.part(super::FourCC::PSV0).unwrap().data.to_vec() + }; + // Runtime info starts after its size; PSInfo is {DepthOutput, SampleFrequency}. + let center = psv_of(1 << 1); + assert_eq!(center[4 + 1], 0, "center interpolation is per pixel"); + let sample = psv_of(1 << 0); + assert_eq!(sample[4 + 1], 1, "PSInfo.SampleFrequency"); + } + /// A pixel shader reading channel z of an input whose element starts at /// w. Looking the channel up subtracted the element's first channel /// before checking the channel lies in it, so in a build with overflow From c2f60d6bddc228c5be5feb6e08daccbf6c4e7f94 Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:39:58 +0100 Subject: [PATCH 077/445] Shaders: a pixel shader writing SV_StencilRef declares StencilRef exp mrtz's channel y is lowered to an SV_StencilRef output, but the module's shader flags never had StencilRef (bit 11) and SFI0 never had D3D_SHADER_FEATURE_STENCIL_REF (0x200). DXC sets both for a pixel shader whose output signature has the stencil reference, and the validator checks the flags against the module. Both are now set when a pixel shader outputs SV_StencilRef. --- crates/victory-shader/src/emit/mod.rs | 62 ++++++++++++++++++++++++ crates/victory-shader/src/emit/shader.rs | 8 +++ 2 files changed, 70 insertions(+) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0df1233..a882f42 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -411,6 +411,68 @@ mod tests { use super::*; use crate::native::{ComputeIo, StageIo}; + /// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`). + /// DXC sets ShaderFlags.StencilRef (bit 11) for a pixel shader whose + /// output signature has SV_StencilRef, and the feature bit + /// D3D_SHADER_FEATURE_STENCIL_REF (0x200) in SFI0; the validator checks + /// both against the module. + #[test] + fn a_stencil_export_declares_the_stencil_ref_feature() { + let words = [ + 0x7E00_02F2u32, // v_mov_b32 v0, 1.0 + 0x7E02_0285, // v_mov_b32 v1, 5 + 0xF800_1883, + 0x0000_0100, // exp mrtz v0, v1, off, off done vm + 0xBF81_0000, + ]; + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 2, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let el = |name: &str, kind, comp| SigElement { + name: name.into(), + index: 0, + kind, + comp, + interp: 0, + row: None, + col: 0, + cols: 1, + usage: 1, + half: false, + }; + let osg1 = + container::signature(&[el("SV_Depth", 17, 9), el("SV_StencilRef", 20, 5)], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + let out = emit(&c, &native, &p, &st, &io, &res).unwrap(); + // dxil.dll, where there is one, checks the flags against the module. + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut out.dxil.clone()).unwrap(); + } + let host = Container::parse(&out.dxil).unwrap(); + let sfi0 = host.part(FourCC::SFI0).unwrap().data; + let features = u64::from_le_bytes(sfi0.try_into().unwrap()); + assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef"); + } + /// A wave64 compute program that writes only EXEC's high dword /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask is /// opaque and keyed by the unchanged low dword, so building its lane bit diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 8389c17..44a315a 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -16,6 +16,7 @@ pub const ROOT_CBV_SPACE: u32 = 1; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { pub const RAW_BUFFERS: u64 = 1 << 4; + pub const STENCIL_REF: u64 = 1 << 11; pub const TYPED_UAV_LOADS: u64 = 1 << 13; pub const WAVE_OPS: u64 = 1 << 19; pub const INT64: u64 = 1 << 20; @@ -471,6 +472,10 @@ impl Shader { } else { None }; + // A pixel shader with an SV_StencilRef output (as DXC collects it). + if self.pixel && self.outputs.iter().any(|o| o.kind == 20) { + self.flags |= flags::STENCIL_REF; + } // Entry properties: shader flags (tag 0), thread-group size (4), // wave size (11). let mut props = Vec::new(); @@ -549,6 +554,9 @@ impl Shader { dxil.extend(&bitcode); let mut features = 0u64; + if self.flags & flags::STENCIL_REF != 0 { + features |= 0x200; + } if self.flags & flags::TYPED_UAV_LOADS != 0 { features |= 0x800; } From 2af66ff1d8dbd7ccd7d87488a57e2caf37d065a1 Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Mon, 23 Nov 2026 23:49:01 -0300 Subject: [PATCH 078/445] Shaders: v_cvt_u16_f16 and v_cvt_i16_f16 saturate at 16 bits They went through a 32-bit conversion, so an f16 past the i16 range (32768 up to 65504) wrapped, and infinities and NaN were undefined. The value is now clamped in f32 to the 16-bit range first (every f16 is exact there) and NaN gives 0, as the hardware's conversions do. --- crates/victory-shader/src/emit/lower.rs | 19 +++++++--- crates/victory-shader/src/emit/valu_tests.rs | 40 ++++++++++++++++++++ 2 files changed, 53 insertions(+), 6 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..c6ee447 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4357,15 +4357,22 @@ impl<'a> Lower<'a> { } let r = match name { "v_cvt_u16_f16" | "v_cvt_i16_f16" => { - // shortcut: converted through 32 bits, so out-of-range values - // wrap instead of saturating at 16 bits. + // Toward zero, saturating at the 16-bit range (infinities + // included); NaN gives 0. Clamped in f32 first, where every + // f16 is exact, so the conversion never leaves i32's range. let a = self.half_fsrc(inst, 0)?; - let op = if name == "v_cvt_u16_f16" { - Cast::FpToUi + let (lo, hi) = if name == "v_cvt_u16_f16" { + (0.0f32, 65535.0f32) } else { - Cast::FpToSi + (-32768.0, 32767.0) }; - self.s.m.cast(c, op, a, i32t) + let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits())); + let t = self.binary(35, a, lo); + let t = self.binary(36, t, hi); + let r = self.s.m.cast(c, Cast::FpToSi, t, i32t); + let nan = self.s.m.cmp(c, pred::UNO, a, a); + let z = self.s.m.i32(0); + self.s.m.select(c, nan, z, r) } _ => { let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6..d5882c1 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -520,6 +520,46 @@ fn v_sin_and_v_cos_f32_reduce_large_turns() { }); } +#[test] +fn v_cvt_u16_and_i16_f16_saturate() { + // v_mov_b32 v0, 0; v_cvt_u16_f16 / v_cvt_i16_f16 v0, v1 (VOP1 0x052 / 0x053). + let cases: &[(u16, u16, u16)] = &[ + // (f16 input, u16 result, i16 result) + (0x0000, 0, 0), // 0 + (0x8000, 0, 0), // -0 + (0x3E00, 1, 1), // 1.5 -> 1 (toward zero) + (0xBE00, 0, 0xFFFF), // -1.5 -> 0 / -1 + (0x57D0, 125, 125), // 125.0 + (0x7800, 32768, 32767), // 32768 saturates i16 + (0x77FF, 32752, 32752), // 32752, the largest f16 below 32768 + (0xF800, 0, 0x8000), // -32768 fits i16 + (0xF801, 0, 0x8000), // -32800 saturates i16 + (0x7BFF, 65504, 32767), // max finite f16 + (0xFBFF, 0, 0x8000), // -65504 + (0x7C00, 0xFFFF, 32767), // +inf + (0xFC00, 0, 0x8000), // -inf + (0x7E00, 0, 0), // NaN + (0xFE00, 0, 0), // -NaN + (0x0001, 0, 0), // smallest subnormal + ]; + for (op, what, pick) in [ + (0x052u16, "v_cvt_u16_f16", 0usize), + (0x053, "v_cvt_i16_f16", 1), + ] { + let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| [u32::from(c.0), 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, _, got| { + let want = if pick == 0 { cases[i].1 } else { cases[i].2 }; + assert_eq!( + got, + u32::from(want), + "{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}", + cases[i].0, + ); + }); + } +} + #[test] fn v_sin_and_v_cos_f16_reduce_large_turns() { let sin_shader = build_valu_cs(&[vop1(0x060, 0, vgpr(1))]); From ff8694a69a3444bbbbdc37668181708a87d5b5cc Mon Sep 17 00:00:00 2001 From: itsRevela Date: Mon, 23 Nov 2026 20:56:27 -0600 Subject: [PATCH 079/445] Window: keep Alt and F10 from freezing the title in menu mode Alt or F10 sends WM_SYSCOMMAND SC_KEYMENU, and the default handling runs a modal menu loop on the thread that owns the window, which is the title's. The title stops drawing and reading input until a key ends the loop, with nothing on screen to say so, and Grand Theft Auto VI aborts itself about half a minute later (the deliberate write to 0 at +0x23cf683). The window procedure now drops SC_KEYMENU, next to its SC_CLOSE handling. The mouse can still open the window menu. Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/lifecycle.rs | 69 +++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs index 3e5e00f..4eb9649 100644 --- a/crates/victory-hle/src/modules/lifecycle.rs +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -174,6 +174,15 @@ extern "system" fn window_proc( end_title("window closed", Box::new(|| {})); return 0; } + // Alt or F10 puts a window into menu mode: the system runs a modal menu + // loop on the thread that owns the window, which is the title's. The + // title then stops (no frames, no input) until a key ends the loop, and + // nothing shows it, since the window has no menu bar; Grand Theft Auto + // VI aborts itself about half a minute later. A console has no window + // menu. The mouse still opens it from the title bar. + if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_KEYMENU as usize { + return 0; + } // SAFETY: the procedure `hook` stored, called the way the system would. unsafe { let title = wm::GetPropW(hwnd, TITLE_PROC); @@ -366,4 +375,64 @@ mod tests { wm::DestroyWindow(hwnd); } } + + thread_local! { + /// The system commands `recording` received, low four bits cleared. + static COMMANDS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + + /// Stands in for a title's procedure: notes system commands and acts + /// on none of them (no menu loop, no minimising). + extern "system" fn recording( + hwnd: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, + ) -> LRESULT { + if message == wm::WM_SYSCOMMAND { + COMMANDS.with(|c| c.borrow_mut().push(wparam & 0xFFF0)); + return 0; + } + // SAFETY: the system's default procedure, called as the system would. + unsafe { wm::DefWindowProcW(hwnd, message, wparam, lparam) } + } + + #[test] + fn the_keyboard_menu_never_reaches_the_title() { + let null = std::ptr::null_mut(); + let hwnd = CreateWindowExW( + 0, + w!("STATIC"), + w!("menu"), + 0, + 0, + 0, + 10, + 10, + null, + null, + null, + std::ptr::null(), + ); + assert!(!hwnd.is_null()); + // SAFETY: our window, owned by this thread, so each message is + // handled before SendMessageW returns. `recording` stands in for the + // title's procedure and the original is put back before the window + // is destroyed. + unsafe { + let title = wm::GetPropW(hwnd, TITLE_PROC); + wm::SetPropW(hwnd, TITLE_PROC, recording as *const () as *mut c_void); + let command = |c: u32, key: u8| { + wm::SendMessageW(hwnd, wm::WM_SYSCOMMAND, c as usize, LPARAM::from(key)) + }; + command(wm::SC_KEYMENU, 0); // Alt or F10 + command(wm::SC_KEYMENU, b' '); // Alt+Space + command(wm::SC_KEYMENU | 1, 0); // the low bits are the system's + command(wm::SC_MINIMIZE, 0); + wm::SetPropW(hwnd, TITLE_PROC, title); + wm::DestroyWindow(hwnd); + } + let seen = COMMANDS.with(|c| c.borrow().clone()); + assert_eq!(seen, [wm::SC_MINIMIZE as usize]); + } } From eb30a0d9f4f8aee0a287563406adc9de06377cfb Mon Sep 17 00:00:00 2001 From: Enzo Souza Duarte Date: Tue, 24 Nov 2026 00:09:56 -0300 Subject: [PATCH 080/445] GPU: write half subnormals from f32 rectangle outputs --- crates/victory-gpu/src/primitive.rs | 31 ++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index c11c647..68ca037 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -127,7 +127,19 @@ fn f32_to_half(v: f32) -> u16 { return sign | 0x7c00; // too large: infinity } if exp <= 0 { - return sign; // too small: zero + if exp < -10 { + return sign; // below half the smallest subnormal: zero + } + // Half subnormals are `m * 2^-24`. An f32 in this range is still + // normal (exponent field >= 1), so its significand has the implicit + // leading 1; shift it into the half mantissa, rounding to even. + let sig = (1u32 << 23) | man; + let shift = (14 - exp) as u32; + let halfway = 1u32 << (shift - 1); + let q = sig >> shift; + let r = sig & ((1u32 << shift) - 1); + let m = q + u32::from(r > halfway || (r == halfway && (q & 1) != 0)); + return sign | m as u16; } sign | (exp as u16) << 10 | ((man + 0x1000) >> 13) as u16 } @@ -178,4 +190,21 @@ mod tests { assert_eq!(dst[..40], [&src[..], &src[..8], &src[16..]].concat()[..]); assert_eq!(dst[40..], vertex(4.0, 6.0)[..]); } + + /// `half_to_f32` reads subnormals, so an f16 rectangle output must be + /// able to write them back instead of flushing every one to zero. + #[test] + fn half_subnormals_convert_in_both_directions() { + assert_eq!(f32_to_half(2f32.powi(-24)), 0x0001); + assert_eq!(f32_to_half(-2f32.powi(-24)), 0x8001); + assert_eq!(f32_to_half(2f32.powi(-23)), 0x0002); + assert_eq!(f32_to_half(1023.0 * 2f32.powi(-24)), 0x03ff); + // Ties go to an even mantissa: 0/1 and 1/2. + assert_eq!(f32_to_half(2f32.powi(-25)), 0x0000); + assert_eq!(f32_to_half(3.0 * 2f32.powi(-25)), 0x0002); + // Below half the smallest subnormal, and normal values, are unchanged. + assert_eq!(f32_to_half(2f32.powi(-26)), 0x0000); + assert_eq!(f32_to_half(1.5), 0x3e00); + assert_eq!(half_to_f32(0x0001), 2f32.powi(-24)); + } } From 28c1b0735ce4230303e75c366dbd019934c0e1ce Mon Sep 17 00:00:00 2001 From: marquezini Date: Tue, 24 Nov 2026 00:12:40 -0300 Subject: [PATCH 081/445] XGameSave: a read result into a small buffer is E_GS_PROVIDED_BUFFER_TOO_SMALL XGameSaveReadBlobDataResult lists E_GS_PROVIDED_BUFFER_TOO_SMALL among its errors, and the synchronous read already returns it; the result passed on XAsyncGetResult's E_NOT_SUFFICIENT_BUFFER instead. --- crates/victory-hle/src/modules/xgamesave.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs index 7282284..001c4b8 100644 --- a/crates/victory-hle/src/modules/xgamesave.rs +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -786,6 +786,11 @@ extern "system" fn read_result( ) -> HRESULT { let mut used = 0; let hr = xasync::XAsyncGetResult(block, (&raw const READ).cast(), size, out.cast(), &mut used); + // The documented error for a small buffer; the result stays for a + // retry with a larger one. + if hr == xasync::E_NOT_SUFFICIENT_BUFFER { + return BUFFER_TOO_SMALL; + } if hr < 0 { return hr; } @@ -1209,6 +1214,10 @@ mod tests { ); let mut buffer = vec![0u64; size.div_ceil(8)]; let mut count = 0; + assert_eq!( + read_result(this, &mut b, 8, buffer.as_mut_ptr().cast(), &mut count), + BUFFER_TOO_SMALL + ); assert_eq!( read_result(this, &mut b, size, buffer.as_mut_ptr().cast(), &mut count), S_OK From d5704aaac67201c0b3c47512b955a83526bb54bd Mon Sep 17 00:00:00 2001 From: Pedro Fortunato Date: Tue, 24 Nov 2026 00:13:10 -0300 Subject: [PATCH 082/445] fix(shader): lower dynamic v_perm_b32 without INT64 --- crates/victory-shader/src/emit/lower.rs | 107 +++++++++++++++++++++--- 1 file changed, 94 insertions(+), 13 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..84c1272 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4770,24 +4770,22 @@ impl<'a> Lower<'a> { _ => { // A computed selector: each byte picked at run time. let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); - let i64t = self.s.m.int(64); - self.s.flags |= flags::INT64; - let wa = self.s.m.cast(c, Cast::ZExt, a, i64t); - let wb = self.s.m.cast(c, Cast::ZExt, b, i64t); - let k32 = self.s.m.int_const(i64t, 32); - let wa = self.s.m.bin(c, Bin::Shl, wa, k32); - let both = self.s.m.bin(c, Bin::Or, wa, wb); let mut r = k(self, 0); for i in 0..4u32 { let (sh, ff) = (k(self, 8 * i), k(self, 0xFF)); let sel = self.s.m.bin(c, Bin::LShr, sv, sh); let sel = self.s.m.bin(c, Bin::And, sel, ff); - // Bytes 0-7 of {src0, src1}. - let k3 = k(self, 3); - let bits = self.s.m.bin(c, Bin::Shl, sel, k3); - let bits = self.s.m.cast(c, Cast::ZExt, bits, i64t); - let x = self.s.m.bin(c, Bin::LShr, both, bits); - let x = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32); + // Select a dword and a byte within it. + // Later selects handle codes 8 and above. + let four = k(self, 4); + let zero = k(self, 0); + let high = self.s.m.bin(c, Bin::And, sel, four); + let high = self.s.m.cmp(c, pred::NE, high, zero); + let word = self.s.m.select(c, high, a, b); + let three = k(self, 3); + let index = self.s.m.bin(c, Bin::And, sel, three); + let bits = self.s.m.bin(c, Bin::Shl, index, three); + let x = self.s.m.bin(c, Bin::LShr, word, bits); let mut byte = self.s.m.bin(c, Bin::And, x, ff); // 8-11: the sign of bytes 1, 3 of src1, then of src0. for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)] @@ -6630,6 +6628,89 @@ mod tests { } } + + fn perm_features(selector: u32) -> u64 { + // Synthetic compute shader: + // v0 is the thread ID and can supply a dynamic selector. + // Store the result in LDS to keep the permutation live. + let words = [ + 0x7E02_02FFu32, + 0x817F_34AB, + 0x7E04_02FF, + 0xFE01_56CD, + 0xD744_0003, + 257 | (258 << 9) | (selector << 18), + 0x3408_0082, + 0xD834_0000, + 0x0000_0304, + S_ENDPGM, + ]; + + let code: Vec = words.iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 15, + threads: [64, 1, 1], + }), + code, + }; + + let p = ir::build(&native.code, false, 256).unwrap(); + + assert!(p.blocks.iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "v_perm_b32")); + + let res = resource::track( + &p, &native.layout, native.stage + ).unwrap(); + + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + + let emitted = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }).unwrap(); + + let container = + crate::Container::parse(&emitted.dxil).unwrap(); + + let features = + container.part(crate::FourCC::SFI0).unwrap(); + + u64::from_le_bytes(features.data.try_into().unwrap()) + } + + #[test] + fn perm_constant_selector_needs_no_int64() { + assert_eq!(perm_features(128) & 0x8000, 0); + } + + #[test] + fn perm_dynamic_selector_needs_no_int64() { + assert_eq!( + perm_features(256) & 0x8000, + 0, + "dynamic v_perm_b32 must not require INT64" + ); + } + #[test] fn buffer_formats_by_number() { // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, From f0ee35e9dfc700faa528ee48d3d31dd0ef101315 Mon Sep 17 00:00:00 2001 From: marquezini Date: Tue, 24 Nov 2026 00:13:26 -0300 Subject: [PATCH 083/445] XGameSave: a full host disk is E_GS_OUT_OF_LOCAL_STORAGE, not the quota An update that fit the user's 256 MB quota but not the host disk failed with E_GS_QUOTA_EXCEEDED, which tells the player to delete saves. The documentation keeps the two apart: E_GS_OUT_OF_LOCAL_STORAGE is the device out of room and can come before the quota is reached. The disk check also no longer credits the blobs an update replaces, since the new version is written before the old one is removed. --- crates/victory-hle/src/modules/xgamesave.rs | 31 +++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs index 001c4b8..ebf0968 100644 --- a/crates/victory-hle/src/modules/xgamesave.rs +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -393,6 +393,21 @@ fn remaining(root: &Path) -> u64 { .min(storage::disk_free(root)) } +/// Why an update writing `written` bytes, `replaced` of them over blobs it +/// replaces, does not fit: past the per-user quota (`used` bytes kept), or +/// past the host disk's `free` bytes, which is not the user's quota (the +/// new version is written before the old one goes, so nothing it replaces +/// counts there). +fn no_room(written: u64, replaced: u64, used: u64, free: u64) -> Option { + if written > QUOTA.saturating_sub(used) + replaced { + Some(QUOTA_EXCEEDED) + } else if written > free { + Some(OUT_OF_LOCAL_STORAGE) + } else { + None + } +} + fn io_error(dir: &Path, e: &std::io::Error) -> HRESULT { tracing::warn!(dir = %dir.display(), %e, "game save"); if e.kind() == std::io::ErrorKind::StorageFull { @@ -446,8 +461,9 @@ impl Update { changed.map(|(_, size)| size).sum() }); let root = self.dir.parent().unwrap_or(&self.dir); - if written as u64 > remaining(root) + replaced { - return QUOTA_EXCEEDED; + let free = storage::disk_free(root); + if let Some(hr) = no_room(written as u64, replaced, used_bytes(root), free) { + return hr; } let display = self.display.as_deref(); let display = display.or(current.as_ref().map(|v| v.display.as_str())); @@ -950,6 +966,17 @@ mod tests { } } + /// The per-user quota and the host disk fail with their own errors. + #[test] + fn a_full_disk_is_not_the_quota() { + let mb = 1 << 20; + assert_eq!(no_room(2 * mb, 0, 0, mb), Some(OUT_OF_LOCAL_STORAGE)); + assert_eq!(no_room(2 * mb, 0, QUOTA - mb, 100 * mb), Some(QUOTA_EXCEEDED)); + // Replacing a blob of the same size fits a full quota. + assert_eq!(no_room(mb, mb, QUOTA, 100 * mb), None); + assert_eq!(no_room(mb, 0, 0, mb), None); + } + fn update(root: &Path, display: &str, changes: &[(&str, Option<&str>)]) -> HRESULT { Update { name: "Slot".into(), From f4438b38f435bcd0434bb2352128b7482fb223a9 Mon Sep 17 00:00:00 2001 From: local Date: Mon, 23 Nov 2026 22:16:27 -0500 Subject: [PATCH 084/445] Shaders: reads of uninitialized SGPRs read as zero, as VGPRs do Compute programs read SGPRs the hardware does not initialize when two branches make the paths look like they allow a read before a write, even though the branch that skips the write does not reach the read. That stops translation with 'a hardware SGPR input is not supported' and drops the program's dispatches. ComputeIo::initialized_sgprs() counts the user SGPRs, the enabled system ones and the scratch wave offset. A read of a general SGPR (0..=105) at or above that count holds whatever the previous wave left, so no program can depend on its value: read it as zero, as unset VGPRs already are. Reserved registers (VCC, trap temporaries, M0, EXEC) keep their current handling. --- crates/victory-shader/src/emit/lower.rs | 10 +++++++- crates/victory-shader/src/io.rs | 7 ++++++ crates/victory-shader/src/native.rs | 31 +++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..f90a252 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -908,8 +908,16 @@ impl<'a> Lower<'a> { for &(reg, v) in &self.x.p.inputs { let val = match reg { Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use - Reg::S(_) => match io_inputs.get(&v) { + Reg::S(n) => match io_inputs.get(&v) { Some(&input) => self.input(input), + // Above the SGPRs the hardware initializes, a register + // holds what the last wave left, so no program depends + // on it: a read the paths only seem to allow (a branch + // past the write, taken only with one past the read) + // reads zero, as VGPRs do. + None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => { + Val::I32(self.s.m.i32(0)) + } None => Val::Missing("a hardware SGPR input"), }, Reg::Scc => Val::Missing("SCC on entry"), diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index 0b7f45b..e3cbd60 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -182,6 +182,9 @@ pub struct Io { pub inputs: Vec<(Value, Input)>, pub interps: Vec<(Site, Interp)>, pub exports: Vec, + /// Compute: how many SGPRs the hardware initializes + /// ([`ComputeIo::initialized_sgprs`](crate::native::ComputeIo::initialized_sgprs)). + pub initialized_sgprs: Option, } /// Raises the I/O of `p`, built from `native`'s patched code. Fails for @@ -287,6 +290,10 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { let mut io = Io { inputs: inputs.clone(), + initialized_sgprs: match &native.io { + StageIo::Cs(cs) => Some(cs.initialized_sgprs()), + _ => None, + }, ..Io::default() }; let defs: std::collections::HashMap = p diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index dd62c2f..4bdd39b 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -319,6 +319,15 @@ impl ComputeIo { (ids, take(10)) } + /// SGPRs the hardware initializes: the user SGPRs, the enabled system + /// ones, then the scratch wave offset when scratch is enabled (bit 0). + /// The ones above hold whatever the previous wave left. + pub fn initialized_sgprs(&self) -> u8 { + let (ids, info) = self.system_sgprs(); + let end = ids.into_iter().chain([info]).flatten().map(|s| s + 1).max(); + end.unwrap_or(0).max(self.user_sgprs()) + (self.rsrc2 & 1) as u8 + } + /// Thread id components in v0, v1, v2 (1 to 3). pub fn thread_id_vgprs(&self) -> u8 { (self.rsrc2 >> 11 & 3) as u8 + 1 @@ -948,6 +957,28 @@ mod tests { assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (3, 0)); } + #[test] + fn initialized_sgprs_covers_user_system_and_scratch() { + // 5 user SGPRs, group ids x and y (s5, s6), no scratch: s0..=s6. + let cs = ComputeIo { + rsrc2: 0x1098A, + threads: [16, 16, 1], + }; + assert_eq!(cs.initialized_sgprs(), 7); + // All three group ids after 6 user SGPRs, plus the info SGPR: s0..=s9. + let cs = ComputeIo { + rsrc2: 0x78C, + threads: [8, 8, 1], + }; + assert_eq!(cs.initialized_sgprs(), 10); + // The same with scratch enabled adds the wave offset: s0..=s10. + let cs = ComputeIo { + rsrc2: 0x78D, + threads: [8, 8, 1], + }; + assert_eq!(cs.initialized_sgprs(), 11); + } + #[test] fn reads_every_native_blob() { let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)])); From 1106f43efee58f3b218b9e9d1f0ca65da4b41b72 Mon Sep 17 00:00:00 2001 From: "r4." <192970269+r4tedx@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:18:27 +0200 Subject: [PATCH 085/445] Shader tests: run the VALU GPU tests one at a time `cargo test` now and then never finishes: the seven emit::valu_tests that run on the hardware adapter and on WARP start together on the test threads, none of their dispatches completes, and the test binary keeps one core busy until it is killed (the waits spin on the fence). Any other GPU test running at that moment is stuck with them. On an RTX 5070 with a Radeon iGPU, `valu_tests` alone in a loop on main d2a4bae: 3 of 30 runs hang. With `run_cases` behind a process-wide lock: 0 of 60, and the seven tests take under 7 s. The lock is poison-tolerant, so one failing test does not fail the rest. Co-Authored-By: Claude Fable 5.2 --- crates/victory-shader/src/emit/valu_tests.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6..b717c47 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -166,6 +166,11 @@ fn run_cases( cases: &[[u32; 4]], mut check: impl FnMut(&str, usize, [u32; 4], u32), ) { + // One test at a time: with these tests on the hardware adapter and WARP + // from several test threads at once, now and then none of their + // dispatches ever completes and the test binary hangs. + static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let mut ran = 0; for (label, warp) in [("hardware", false), ("warp", true)] { let Ok(host) = Host::new(warp) else { From 077ec8b28a01358558e6d3761f76ae68b72d69b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 03:24:44 +0000 Subject: [PATCH 086/445] translate: count per-lane fetched descriptors as loaded The resource tally in `victory translate` matched every `Source` variant by hand, so the new `Select`, `Fetched` and `Lanes` kinds left it non-exhaustive and `cargo check -p victory` failed. A fetched descriptor is counted with the loaded ones; selections and per-lane choices are never leaves. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66 --- apps/victory/src/translate.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index dcaf924..8e9c6e2 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -547,7 +547,7 @@ fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) { let mut traced = HashSet::new(); for leaf in r.descriptors.iter().flat_map(|d| d.source.leaves()) { let a = match *leaf { - resource::Source::Loaded { load, .. } => { + resource::Source::Loaded { load, .. } | resource::Source::Fetched { load, .. } => { t.loaded += 1; address(load) } @@ -560,7 +560,11 @@ fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) { t.constant += 1; None } - resource::Source::Phi { .. } => unreachable!("leaves are no phis"), + resource::Source::Phi { .. } + | resource::Source::Select { .. } + | resource::Source::Lanes { .. } => { + unreachable!("leaves are no phis, selects or per-lane choices") + } }; // Heaps hold dynamic resources, which no used entry lists; code // tables are no root parameter. From bf84134b2be663608ad29abeae2fb05705c8fb39 Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:25:27 +0100 Subject: [PATCH 087/445] Shaders: maximums and minimums order -0 below +0, as RDNA2 does v_max_f32, v_min_f32, their three-operand and f16 forms and the packed v_pk_max_f16/v_pk_min_f16 were lowered to DXIL's FMax and FMin. DXIL specifies those as a compare and select, so with a -0 and a +0 either zero can come out, depending on the operand order and the host; RDNA2 orders -0 below +0, so max(-0, +0) is +0 and min(-0, +0) is -0 in either order. A -0 that should have been +0 then turns, say, a following reciprocal square root's +inf into -inf. A new helper keeps FMax/FMin for everything but two zeros, which it resolves by their sign bits. --- crates/victory-shader/src/emit/lower.rs | 47 ++++++++++++++------ crates/victory-shader/src/emit/valu_tests.rs | 26 +++++++++++ 2 files changed, 59 insertions(+), 14 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..2cbc0f3 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1337,6 +1337,25 @@ impl<'a> Lower<'a> { ) } + /// The hardware's maximum (`max`) or minimum of two floats: as DXIL's + /// FMax/FMin, but -0 orders below +0 (RDNA2 ISA, `v_max_f32`), where + /// the compare and select DXIL specifies gives either zero. + fn max_min(&mut self, max: bool, a: V, b: V) -> V { + let c = self.cur; + let r = self.binary(if max { 35 } else { 36 }, a, b); + let (ia, ib) = (self.as_int(a), self.as_int(b)); + let either = self.s.m.bin(c, Bin::Or, ia, ib); + let magnitude = self.s.m.i32(0x7FFF_FFFF); + let either = self.s.m.bin(c, Bin::And, either, magnitude); + let zero = self.s.m.i32(0); + let zeros = self.s.m.cmp(c, pred::EQ, either, zero); + // Of two zeros, +0 unless both are -0 (max), -0 unless neither (min). + let op = if max { Bin::And } else { Bin::Or }; + let sign = self.s.m.bin(c, op, ia, ib); + let signed = self.as_float(sign); + self.s.m.select(c, zeros, signed, r) + } + fn fmad(&mut self, a: V, b: V, c: V) -> V { self.s.op( self.cur, @@ -3673,8 +3692,8 @@ impl<'a> Lower<'a> { "v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a), "v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb), "v_mul_legacy_f32" => self.legacy_mul(a, bb), - "v_max_f32" => self.binary(35, a, bb), - _ => self.binary(36, a, bb), + "v_max_f32" => self.max_min(true, a, bb), + _ => self.max_min(false, a, bb), }; float(self, r) } @@ -3724,12 +3743,12 @@ impl<'a> Lower<'a> { let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); let r = match name { "v_max3_f32" => { - let t = self.binary(35, a, bb); - self.binary(35, t, cc) + let t = self.max_min(true, a, bb); + self.max_min(true, t, cc) } "v_min3_f32" => { - let t = self.binary(36, a, bb); - self.binary(36, t, cc) + let t = self.max_min(false, a, bb); + self.max_min(false, t, cc) } _ => self.med3(a, bb, cc), }; @@ -4265,8 +4284,8 @@ impl<'a> Lower<'a> { "v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b), "v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a), "v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b), - "v_max_f16" => self.binary(35, a, b), - _ => self.binary(36, a, b), + "v_max_f16" => self.max_min(true, a, b), + _ => self.max_min(false, a, b), }; return float_result(self, r); } @@ -4296,12 +4315,12 @@ impl<'a> Lower<'a> { // product is exact; the sum rounds twice). "v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc), "v_max3_f16" => { - let t = self.binary(35, a, b); - self.binary(35, t, acc) + let t = self.max_min(true, a, b); + self.max_min(true, t, acc) } "v_min3_f16" => { - let t = self.binary(36, a, b); - self.binary(36, t, acc) + let t = self.max_min(false, a, b); + self.max_min(false, t, acc) } _ => self.med3(a, b, acc), }; @@ -4487,8 +4506,8 @@ impl<'a> Lower<'a> { let mut f = match op { "add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]), "mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]), - "min_f16" => self.binary(36, xs[0], xs[1]), - "max_f16" => self.binary(35, xs[0], xs[1]), + "min_f16" => self.max_min(false, xs[0], xs[1]), + "max_f16" => self.max_min(true, xs[0], xs[1]), // shortcut: FMad in f32, as v_fma_f16. _ => self.fmad(xs[0], xs[1], xs[2]), }; diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6..70d7530 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -279,6 +279,32 @@ fn v_med3_f32_matches_rdna2_with_nan() { }); } +/// RDNA2 orders -0 below +0 in its maximums and minimums; DXIL's FMax and +/// FMin compare and select, which can give either zero. +#[test] +fn max_and_min_order_negative_zero_below_positive_zero() { + let (pz, nz) = (0_u32, 0x8000_0000_u32); + // Each case has a -0 and a +0 among its first two operands. + let cases = [ + [nz, pz, nz, 0], + [pz, nz, nz, 0], + [nz, pz, pz, 0], + [pz, nz, pz, 0], + ]; + let ops = [ + ("v_max_f32", 0x110, pz), + ("v_min_f32", 0x10F, nz), + ("v_max3_f32", 0x154, pz), + ("v_min3_f32", 0x151, nz), + ]; + for (name, op, want) in ops { + let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); + run_cases(&shader, &cases, |backend, _, inp, got| { + assert_eq!(got, want, "{backend}: {name} {inp:x?}"); + }); + } +} + #[test] fn v_med3_f16_matches_rdna2_with_nan() { // v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357) From e8d3b6432e0db114dd100a0c47e5d78741c938a2 Mon Sep 17 00:00:00 2001 From: hophaver <86059649+hophaver@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:55:13 +0200 Subject: [PATCH 088/445] GPU: the larger dynamic range only where the heap still fits A host that refuses the title's slots plus 2^18 dynamic ones (NVIDIA's 1,000,000-view cap) now gets 2^16 dynamic slots, as before, instead of losing mirrored title slots to the larger range: at the cap, 2^18 left 737,856 title slots against 934,464, and titles were seen to index slots up to 917,140. The cap itself is unchanged. Hosts that take the larger heap (RX 9070 XT) keep 2^18. --- crates/victory-gpu/src/descriptor/host.rs | 61 +++++++++++++++-------- 1 file changed, 41 insertions(+), 20 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 7315840..672901a 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -17,8 +17,11 @@ pub(crate) struct HostHeap { pub(crate) heap: ID3D12DescriptorHeap, cpu: usize, step: u32, - /// Slots mirroring the title's; view heaps have [`DYNAMIC`] more. + /// Slots mirroring the title's; view heaps have `dynamic` more. count: u32, + /// Dynamic slots past `count` (none in sampler heaps): [`DYNAMIC`] + /// where the host takes them, else [`MIN_DYNAMIC`]. + dynamic: u32, sampler: bool, /// The record (view index and generation) each slot was last made from. made: Mutex>, @@ -66,6 +69,10 @@ const PORTABLE_VIEWS: u32 = 1_000_000; /// each a device removal shortly after; #59). const DYNAMIC: u32 = 1 << 18; +/// The dynamic slots of a heap whose host would not take [`DYNAMIC`] more +/// (a capped heap, NVIDIA): the title's slots keep their room first. +const MIN_DYNAMIC: u32 = 1 << 16; + impl HostHeap { pub(crate) fn new(sampler: bool, count: u32) -> Option { let host = host()?; @@ -86,18 +93,31 @@ impl HostHeap { }) } }; - let extra = if sampler { 0 } else { DYNAMIC }; - let (heap, count) = match make(count + extra) { - Ok(heap) => (heap, count), - Err(e) if !sampler && count + extra > PORTABLE_VIEWS => { - // shortcut: descriptors past the host's limit are left out; - // a title that reaches them needs remapping. - tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}"); - (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - extra) + // The larger dynamic range only where the host takes it on top of + // every title slot; else the smaller one, and the cap after that. + let (heap, count, extra) = if sampler { + match make(count) { + Ok(heap) => (heap, count, 0), + Err(e) => { + tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); + return None; + } } - Err(e) => { - tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); - return None; + } else if let Ok(heap) = make(count + DYNAMIC) { + (heap, count, DYNAMIC) + } else { + match make(count + MIN_DYNAMIC) { + Ok(heap) => (heap, count, MIN_DYNAMIC), + Err(e) if count + MIN_DYNAMIC > PORTABLE_VIEWS => { + // shortcut: descriptors past the host's limit are left + // out; a title that reaches them needs remapping. + tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}"); + (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC) + } + Err(e) => { + tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); + return None; + } } }; // SAFETY: a live heap. @@ -121,10 +141,11 @@ impl HostHeap { cpu, step, count, + dynamic: extra, sampler, made: Mutex::new(vec![0; count as usize]), kept: Mutex::new(vec![None; (count + extra) as usize]), - next: Mutex::new((0, vec![false; DYNAMIC as usize])), + next: Mutex::new((0, vec![false; extra as usize])), }; // A slot never written is undefined: shaders reading one (a slot // the title wrote in a way we do not know, or a table entry no @@ -203,14 +224,14 @@ impl HostHeap { /// `n` consecutive free dynamic slots (view heaps only), taken until /// [`HostHeap::release`]: the first's index. pub(crate) fn dynamic(&self, n: u32) -> Option { - if self.sampler || n == 0 || n > DYNAMIC { + if self.sampler || n == 0 || n > self.dynamic { return None; } let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); let (next, taken) = &mut *guard; let n = n as usize; // Search from `next` on, then from the start. - let starts = (*next as usize..DYNAMIC as usize).chain(0..*next as usize); + let starts = (*next as usize..self.dynamic as usize).chain(0..*next as usize); let mut run = 0; let mut found = None; let mut last = usize::MAX; @@ -232,7 +253,7 @@ impl HostHeap { return None; }; taken[first..first + n].fill(true); - *next = ((first + n) % DYNAMIC as usize) as u32; + *next = ((first + n) % self.dynamic as usize) as u32; Some(self.count + first as u32) } @@ -251,7 +272,7 @@ impl HostHeap { return; }; let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); - let end = (at + n).min(DYNAMIC) as usize; + let end = (at + n).min(self.dynamic) as usize; if let Some(slots) = guard.1.get_mut(at as usize..end) { slots.fill(false); } @@ -864,13 +885,13 @@ mod tests { let Some(heap) = HostHeap::new(false, 4) else { return; // no host GPU }; - let a = heap.dynamic(DYNAMIC - 100).unwrap(); + let a = heap.dynamic(heap.dynamic - 100).unwrap(); let b = heap.dynamic(60).unwrap(); - assert_eq!((a, b), (4, 4 + DYNAMIC - 100)); + assert_eq!((a, b), (4, 4 + heap.dynamic - 100)); // 40 left at the end: 50 do not fit until something is given back. assert_eq!(heap.dynamic(50), None); heap.release(a, 50); assert_eq!(heap.dynamic(50), Some(4)); - assert_eq!(heap.dynamic(40), Some(4 + DYNAMIC - 40)); + assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); } } From 6285e19a8a4a36ae9d93e12a9f43b24b37a939c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 04:05:43 +0000 Subject: [PATCH 089/445] Shaders: take the first lane's descriptor as each lane's own only in a waterfall loop A descriptor read with v_readfirstlane_b32 was traced to each lane's own dwords wherever it was, so a first-lane read outside a loop, or one without the v_cmp_eq that hands every lane its turn, sampled for lanes the program skipped (reported on the PR with the back edge of the fetched waterfall test replaced by s_nop). Now: - a compare counts only when it and the v_readfirstlane it reads are in one loop (each block reaches the other); - every descriptor read from the first lane needs each of its dwords compared that way, or translation stops with "a descriptor read from the first lane outside a waterfall loop". Two tests cover the missing back edge and the missing compare. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66 --- crates/victory-shader/src/resource.rs | 81 ++++++++++++++++++++++++++- 1 file changed, 80 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index c7a522f..6bc273d 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -140,6 +140,8 @@ pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result = Vec::new(); + // Per descriptor read from the first lane: where, and those results. + let mut first_lane_at: Vec<(usize, Vec)> = Vec::new(); for (b, block) in p.blocks.iter().enumerate() { for (i, inst) in block.insts.iter().enumerate() { let site = (b, i); @@ -149,7 +151,11 @@ pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result Result<(), ShaderError> { let source = t.descriptor(inst, op).map_err(fail)?; - first_lane.extend(t.first_lane_words(inst, op).unwrap_or_default()); + let words = t.first_lane_words(inst, op).unwrap_or_default(); + if !words.is_empty() { + first_lane_at.push((inst.machine.offset, words.clone())); + } + first_lane.extend(words); out.descriptors.push(Descriptor { site, role, source }); Ok(()) }; @@ -189,6 +195,17 @@ pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result Tracer<'a> { return None; }; let lane = inst.read(Reg::V(reg + k))?; + let (d, _) = self.defs[x.0 as usize]?; let same = reads.contains(&x) + && self.same_loop(b, d) && self.lane_term(Term::Value(self.first_lane_source(x)?)) == self.lane_term(Term::Value(lane)); same.then_some(x) @@ -1180,6 +1199,26 @@ impl<'a> Tracer<'a> { out } + /// Whether blocks `a` and `b` are in one loop: each reaches the other + /// (a block reaches itself only through a back edge). + fn same_loop(&self, a: usize, b: usize) -> bool { + let reaches = |from: usize, to: usize| { + let mut seen = vec![false; self.p.blocks.len()]; + let mut stack = self.p.blocks[from].exit.successors(); + while let Some(x) = stack.pop() { + if x == to { + return true; + } + if std::mem::replace(&mut seen[x], true) { + continue; + } + stack.extend(self.p.blocks[x].exit.successors()); + } + false + }; + reaches(a, b) && reaches(b, a) + } + /// Consecutive dwords of one scalar load. fn loaded(&self, words: &[Term]) -> Option { let Term::Value(v0) = words[0] else { @@ -1847,6 +1886,46 @@ pub(crate) mod tests { assert_eq!(r.waterfall.compares.len(), 4); } + #[test] + fn a_first_lane_read_outside_a_loop_is_no_waterfall() { + // The waterfall without its back edge: the s_cbranch_execnz is an + // s_nop, so lanes the first one does not match never get a pass. + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + let back = words.iter().position(|&w| w == 0xBF89_FFE6).unwrap(); + words[back] = 0xBF80_0000; + let err = waterfall(&words, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane outside a waterfall loop", + .. + } + ), + "{err:?}" + ); + } + + #[test] + fn a_first_lane_read_without_its_compare_is_no_waterfall() { + // The loop without the compare of dwords 0 and 1: nothing makes + // the first lane's dwords the lane's own there. + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + let cmp = words.iter().position(|&w| w == 0x0002_080C).unwrap(); + words[cmp - 1..=cmp].copy_from_slice(&[0xBF80_0000, 0xBF80_0000]); + let err = waterfall(&words, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane outside a waterfall loop", + .. + } + ), + "{err:?}" + ); + } + #[test] fn descriptors_read_from_the_first_lane_of_lds_fail_naming_it() { // The waterfall over descriptors each lane read from LDS: From 6638098ceec122fd8ac19bbf141835d3b9a149cc Mon Sep 17 00:00:00 2001 From: "r4." <192970269+r4tedx@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:59:38 +0200 Subject: [PATCH 090/445] Shaders: per-lane descriptors chosen by control flow A waterfall loop whose descriptor dwords are VGPR phis stopped with "a descriptor read from the first lane of a phi" (294 programs of the title on #307, all at if/else joins of two s_load_dwordx4 descriptors copied into VGPRs). An EXEC if/else leaves two phis per dword: the flow block's joins an arm's dwords with what lanes that skipped the arm held before (inputs, unrelated loads and arithmetic in the title), the join after the other arm picks per path. Only lanes that never read the descriptor bring those other values, so tracing every edge fails. Tracing (resource::track now takes the program's per-lane form): - per-lane phis of one block are traced on each edge into it that the lanes accessing the descriptor can take, from structure's lane conditions (new Structured::reach, the exits' conditions, and Bools::meet, a read-only satisfiability check); the trace starts from what holds in the access's block. Edges no such lane takes are None in the new Source::LanePhi { block, args }; - every per-lane write it follows (v_mov_b32 copies, v_cndmask_b32, global_load_dword*) must run in all those lanes: a guarded one fails with "a per-lane descriptor written where some lanes may keep the old one". On #307 an else arm without its s_cbranch_execz traced as the second descriptor for every lane; - a loop header's phi fails with "a descriptor read from the first lane of a phi at a loop header", words defined after the join with "a descriptor partly joined by control flow"; without the per-lane form (structurisation failed) the join is refused. Lowering computes each traced edge's heap index at its predecessor's end (through lane_heap_index, so loads, per-lane loads, choices and nested joins work), joins them with a phi (0 on untaken edges) and makes the handle non-uniform. The waterfall compares need no change. Tests: the if/else of two loaded image descriptors, a join of a per-lane load and a v_cndmask choice, nested arms choosing a buffer descriptor with lanes that skip both and do not load (pruned only by the access's condition), a loop header phi, and an unskipped else arm. On #307's head the three join programs fail with "...of a phi" and the unskipped arm is traced as one descriptor for all lanes. On an RTX 5070 and WARP, each lane reads its own arm's texture or buffer; the shaders pass dxil.dll 1.8.2502.11. Reversing the phi's inputs fails validation, flipping the heap index fails the GPU check. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/translate.rs | 11 +- crates/victory-shader/src/emit/lower.rs | 74 +- crates/victory-shader/src/emit/mod.rs | 17 +- crates/victory-shader/src/emit/valu_tests.rs | 5 +- .../src/emit/waterfall_tests.rs | 215 +++++ crates/victory-shader/src/resource.rs | 814 +++++++++++++++++- crates/victory-shader/src/structure.rs | 38 + docs/architecture.md | 6 +- 8 files changed, 1114 insertions(+), 66 deletions(-) create mode 100644 crates/victory-shader/src/emit/waterfall_tests.rs diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 8e9c6e2..4ea1f14 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -333,7 +333,11 @@ fn translate( Ok(program) => { t.translated += 1; t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::(); - let res = match resource::track(&program, &p.layout, p.stage) { + // Per-lane descriptors are traced on the per-lane form; its + // failure is listed after the resources' and I/O's. + let structured = structure::structure(&program); + let lanes = structured.as_ref().ok(); + let res = match resource::track(&program, &p.layout, p.stage, lanes) { Ok(r) => { tally_resources(&p, &r, t); Some(r) @@ -368,7 +372,7 @@ fn translate( Err(e) => t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)), } } - let structured = match structure::structure(&program) { + let structured = match structured { Ok(s) => { tally_structured(&program, &s, t); Some(s) @@ -562,7 +566,8 @@ fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) { } resource::Source::Phi { .. } | resource::Source::Select { .. } - | resource::Source::Lanes { .. } => { + | resource::Source::Lanes { .. } + | resource::Source::LanePhi { .. } => { unreachable!("leaves are no phis, selects or per-lane choices") } }; diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index a255d8b..135ba57 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -3183,6 +3183,9 @@ impl<'a> Lower<'a> { { return self.used_kind(args.first()?); } + if let Source::LanePhi { args, .. } = src { + return args.iter().flatten().find_map(|a| self.used_kind(a)); + } if let Source::Built { address, .. } = src { let rp = self.x.native.layout.get(address.param)?; return self @@ -3317,7 +3320,7 @@ impl<'a> Lower<'a> { let index = self.s.m.select(self.cur, cond, set, clear); Ok(self.s.heap_handle(self.cur, index, sampler, false, props)) } - Source::Fetched { .. } | Source::Lanes { .. } => { + Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => { // A descriptor each lane has its own of (a waterfall loop // reads it from the first active lane): each lane's heap // index, non-uniform. @@ -3328,7 +3331,8 @@ impl<'a> Lower<'a> { } /// The heap index of a descriptor that may differ between lanes, - /// computed in the current block. + /// computed in the current block (or, chosen by control flow, at the + /// join). fn lane_heap_index(&mut self, src: &Source, sampler: bool) -> Result { match src { Source::Loaded { load, first } => self.heap_index(*load, *first, sampler), @@ -3355,6 +3359,36 @@ impl<'a> Lower<'a> { let clear = self.lane_heap_index(b, sampler)?; Ok(self.s.m.select(self.cur, cond, set, clear)) } + Source::LanePhi { block, args } => { + // Each predecessor computes its heap index at its end (what + // it reads is there: the dwords are, on that edge); the join + // picks the one of the edge the lane came by. An edge no + // lane reading it takes gives index 0. + let join = + self.block[*block].ok_or("a per-lane descriptor chosen by control flow")?; + let mut incoming = Vec::new(); + for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let tail = + self.tail[q].ok_or("a per-lane descriptor joined from a later block")?; + let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); + let index = match arg { + Some(arg) => { + let here = std::mem::replace(&mut self.cur, at); + let index = self.lane_heap_index(arg, sampler); + self.cur = here; + index? + } + None => self.s.m.i32(0), + }; + incoming.push((index, at)); + } + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) + } _ => Err("a per-lane descriptor from neither a heap load nor a choice of them"), } } @@ -6710,9 +6744,9 @@ mod tests { code, }; let p = ir::build(&native.code, false, 256).unwrap(); - let res = resource::track(&p, &native.layout, native.stage).unwrap(); - let io = io::raise(&p, &native).unwrap(); let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); lower(&Parts { native: &native, p: &p, @@ -6760,9 +6794,9 @@ mod tests { code, }; let p = ir::build(&native.code, wave64, 256).unwrap(); - let res = resource::track(&p, &native.layout, native.stage)?; - let io = io::raise(&p, &native).unwrap(); let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native).unwrap(); lower(&Parts { native: &native, p: &p, @@ -6898,6 +6932,34 @@ mod tests { } } + /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. + pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { + let (layout, mut used) = texture_tables(); + used.push(UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 16, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }); + (layout, used) + } + + #[test] + fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { + use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; + for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { + let (layout, used) = texture_and_uav_tables(); + let l = lower_wave(words, layout, used, false).unwrap(); + // One image handle, from the join's per-lane heap index. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } + } + #[test] fn buffer_formats_by_number() { // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0df1233..6e0b13c 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -88,6 +88,8 @@ mod shader; pub mod validator; #[cfg(all(test, windows))] mod valu_tests; +#[cfg(all(test, windows))] +mod waterfall_tests; mod wave; use crate::dxbc::{Container, FourCC}; @@ -203,9 +205,12 @@ pub fn translate(container: &[u8]) -> Result { what: "a container without a vertex, pixel, compute or mesh program", })?; let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; - let res = resource::track(&p, &native.layout, native.stage)?; + // Structurisation first: tracing per-lane descriptors needs it (its + // failure is reported after the earlier stages'). + let st = structure::structure(&p); + let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?; let io = io::raise(&p, &native)?; - let st = structure::structure(&p)?; + let st = st?; emit(&c, &native, &p, &st, &io, &res) } @@ -436,9 +441,9 @@ mod tests { code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), }; let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); - let res = resource::track(&p, &native.layout, native.stage).unwrap(); - let io = io::raise(&p, &native).unwrap(); let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); let container = crate::dxbc::build(&[]); let c = Container::parse(&container).unwrap(); if let Err(e) = emit(&c, &native, &p, &st, &io, &res) { @@ -588,9 +593,9 @@ mod tests { let bytes = crate::dxbc::build(&[(super::FourCC::ISG1, &isg1)]); let c = super::Container::parse(&bytes).unwrap(); let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); - let res = crate::resource::track(&p, &native.layout, native.stage).unwrap(); - let io = crate::io::raise(&p, &native).unwrap(); let st = crate::structure::structure(&p).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); // Translated or refused with a reason; it must not panic. let _ = super::emit(&c, &native, &p, &st, &io, &res); } diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6..2417c7a 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -123,9 +123,10 @@ fn build_valu_cs(body: &[u32]) -> HostShader { }; let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - let res = resource::track(&p, &native.layout, native.stage).expect("resource::track"); - let io = io::raise(&p, &native).expect("io::raise"); let st = structure::structure(&p).expect("structure"); + let res = + resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); let lowered = lower::lower(&lower::Parts { native: &native, p: &p, diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs new file mode 100644 index 0000000..c6514b0 --- /dev/null +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -0,0 +1,215 @@ +//! End-to-end tests of waterfall loops over per-lane descriptors: the +//! synthetic GFX10 programs of `resource::tests` lowered to DXIL, validated +//! by `dxil.dll` when present, and run on the host GPU and WARP, each lane +//! reading the resource its own descriptor names. + +use windows::Win32::Graphics::Direct3D12::*; + +use super::host::{Dispatch, Host, Root, Stride, View}; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, ir, resource, structure}; + +/// Lowers a wave32 compute program of 32 threads with the table of views at +/// s0 (textures, or with `buffers` structured buffers of dwords, at entries +/// 0 and 1, a raw UAV at entry 2) and the table of samplers at s1. +fn build(words: &[u32], buffers: bool) -> HostShader { + let table = |user_data: u8| RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data, + slot: user_data, + }; + let range = |kind, table_offset_dwords, dwords, stride, user_data| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: 0, + stride, + dwords, + user_data, + slot: user_data, + }; + let views = if buffers { + range(ResourceType::Srv, 0, 4, 4, 0) + } else { + range(ResourceType::Srv, 0, 8, 0, 0) + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 32, + layout: vec![table(0), table(1)], + used: vec![ + views, + range(ResourceType::Uav, 16, 4, 0, 0), + range(ResourceType::Sampler, 0, 4, 0, 1), + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, + threads: [32, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + 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)).expect("track"); + let io = io::raise(&p, &native).expect("io::raise"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + // One access with each lane's own heap index, no wave operation. + assert_eq!(lowered.nonuniform_handles, 1); + assert!(!lowered.wave_ops); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } else { + eprintln!("no dxil.dll; validation skipped"); + } + shader +} + +/// Runs `shader` with `views` at heap indices 0.. (the UAV last) on the +/// hardware GPU and on WARP (each skipped without a device) and returns, +/// per one that ran, the UAV's 32 dwords. +fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { + let samplers = [D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxAnisotropy: 1, + MaxLOD: f32::MAX, + ..Default::default() + }]; + let mut out = Vec::new(); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = match host.compute_pipeline(shader) { + Ok(p) => p, + Err(e) => panic!("{label}: compute_pipeline failed: {e}"), + }; + // Both tables start at heap index 0. + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + assert_eq!(u.root, RootType::Table, "{u:?}"); + ud[u.index as usize] = 0; + } + let words = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views, + samplers: &samplers, + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + out.push((label, words[0].clone())); + } + out +} + +/// The red channel each lane sampled from two 1x1 textures, red 1.0 at +/// heap index 0 and 2.0 at 1. +fn sampled(shader: &HostShader) -> Vec<(&'static str, Vec)> { + let first = [[1.0f32, 0.0, 0.0, 1.0]]; + let second = [[2.0f32, 0.0, 0.0, 1.0]]; + let views = [ + View::Texture(1, 1, &first), + View::Texture(1, 1, &second), + View::RawUav(32), + ]; + run(shader, &views) + .into_iter() + .map(|(label, words)| (label, words.into_iter().map(f32::from_bits).collect())) + .collect() +} + +#[test] +fn lanes_sample_the_texture_their_if_else_arm_chose() { + use crate::resource::tests::WATERFALL_JOINED_WAVE32; + let shader = build(WATERFALL_JOINED_WAVE32, false); + for (label, red) in sampled(&shader) { + // Lanes below 16 took the first texture, the others the second. + let want: Vec = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect(); + assert_eq!(red, want, "{label}"); + } +} + +#[test] +fn lanes_sample_the_texture_their_arm_loaded_or_picked() { + use crate::resource::tests::WATERFALL_JOINED_MIXED_WAVE32; + let shader = build(WATERFALL_JOINED_MIXED_WAVE32, false); + for (label, red) in sampled(&shader) { + // Lanes below 16 loaded entry (lane & 1); of the others, lanes + // below 24 picked the first, the rest the second. + let want: Vec = (0..32) + .map(|l| match l { + 0..16 => [1.0, 2.0][l & 1], + 16..24 => 1.0, + _ => 2.0, + }) + .collect(); + assert_eq!(red, want, "{label}"); + } +} + +#[test] +fn lanes_load_from_the_buffer_their_nested_arms_chose() { + use crate::resource::tests::WATERFALL_JOINED_BUFFER_WAVE32; + let shader = build(WATERFALL_JOINED_BUFFER_WAVE32, true); + let first: Vec = (0..32).map(|i| 100 + i).collect(); + let second: Vec = (0..32).map(|i| 200 + i).collect(); + let views = [ + View::Buffer { + data: &first, + stride: Stride::Structured(4), + }, + View::Buffer { + data: &second, + stride: Stride::Structured(4), + }, + View::RawUav(32), + ]; + for (label, got) in run(&shader, &views) { + // Dword `lane` of the first buffer below 16, of the second from 16 + // to 23; lanes from 24 on load and store nothing. + let want: Vec = (0..32) + .map(|l| match l { + 0..16 => 100 + l, + 16..24 => 200 + l, + _ => 0, + }) + .collect(); + assert_eq!(got, want, "{label}"); + } +} diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 6bc273d..ecd1b23 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -16,6 +16,7 @@ use crate::ShaderError; use crate::gfx10::{Fields, NULL, Operand}; use crate::ir::{Inst, Program, Reg, Value}; use crate::native::{HwStage, RootParam, RootType}; +use crate::structure::{Bool, LaneExit, Structured}; /// An instruction: block and index in [`crate::ir::Block::insts`]. pub type Site = (usize, usize); @@ -66,6 +67,15 @@ pub enum Source { /// dword is `mask`: the source where the lane's bit is set, then where it /// is clear. Lanes { mask: Value, args: Vec }, + /// Per-lane dwords chosen by control flow (VGPRs joined where lanes + /// that took different paths meet): one source per predecessor of + /// `block`, in [`crate::ir::Block::preds`] order, `None` on an edge no + /// lane that accesses the descriptor takes. A descriptor that differs + /// between lanes. + LanePhi { + block: usize, + args: Vec>, + }, } impl Source { @@ -75,6 +85,9 @@ impl Source { Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } => { args.iter().flat_map(Source::leaves).collect() } + Source::LanePhi { args, .. } => { + args.iter().flatten().flat_map(Source::leaves).collect() + } s => vec![s], } } @@ -124,9 +137,17 @@ pub struct Waterfall { /// Traces every descriptor and scalar address of `p`, which runs as /// `stage`, to the root parameters in `layout`. Fails on the first one it -/// cannot trace. -pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result { - let t = Tracer::new(p, layout, stage)?; +/// cannot trace. `lanes`, `p` as one lane runs it, tells which paths the +/// lanes that access a per-lane descriptor took and which writes they ran; +/// without it, per-lane descriptors chosen by control flow are refused and +/// per-lane writes are taken to run in every lane. +pub fn track( + p: &Program, + layout: &[RootParam], + stage: HwStage, + lanes: Option<&Structured>, +) -> Result { + let t = Tracer::new(p, layout, stage, lanes)?; let mut out = Resources { params: p .inputs @@ -150,7 +171,7 @@ pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result Result<(), ShaderError> { - let source = t.descriptor(inst, op).map_err(fail)?; + let source = t.descriptor(inst, op, b).map_err(fail)?; let words = t.first_lane_words(inst, op).unwrap_or_default(); if !words.is_empty() { first_lane_at.push((inst.machine.offset, words.clone())); @@ -235,13 +256,25 @@ struct Tracer<'a> { /// Register per input value. inputs: Vec>, origin: Vec, + lanes: Option<&'a Structured>, + /// Reverse-postorder index per block. + rpo: Vec, } +/// What lanes are known to satisfy: each [`Bool`] where its flag is set, +/// its negation where not. +type Known = Vec<(Bool, bool)>; + const MAX_ROUNDS: usize = 64; const MAX_JOINS: usize = 8; impl<'a> Tracer<'a> { - fn new(p: &'a Program, layout: &'a [RootParam], stage: HwStage) -> Result { + fn new( + p: &'a Program, + layout: &'a [RootParam], + stage: HwStage, + lanes: Option<&'a Structured>, + ) -> Result { let all = || { p.inputs .iter() @@ -270,6 +303,13 @@ impl<'a> Tracer<'a> { } } } + let mut rpo = vec![usize::MAX; p.blocks.len()]; + for (n, b) in crate::ir::reverse_postorder(&p.blocks) + .into_iter() + .enumerate() + { + rpo[b] = n; + } let mut t = Tracer { p, layout, @@ -278,6 +318,8 @@ impl<'a> Tracer<'a> { phis, inputs, origin: Vec::new(), + lanes, + rpo, }; t.origin = t.propagate_copies(n)?; Ok(t) @@ -679,7 +721,8 @@ impl<'a> Tracer<'a> { self.address(lo, hi, extra) } - fn descriptor(&self, inst: &Inst, op: &Operand) -> Result { + /// The source of the descriptor operand `op` of `inst`, in block `at`. + fn descriptor(&self, inst: &Inst, op: &Operand, at: usize) -> Result { let Operand::Scalar { code, dwords } = *op else { return Err("a descriptor not in SGPRs"); }; @@ -687,16 +730,23 @@ impl<'a> Tracer<'a> { .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v))) .collect::>>() .ok_or("a descriptor not in SGPRs")?; - self.classify(&words, &mut Vec::new()) + // Only the lanes that reach the access read the descriptor. + let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true))); + self.classify(&words, &mut Vec::new(), &mut known) } /// The source of a descriptor's words; `joins` are the phi blocks - /// being resolved. - fn classify(&self, words: &[Term], joins: &mut Vec) -> Result { - if let Some(source) = self.phi(words, joins)? { + /// being resolved, `known` holds in every lane that reads them. + fn classify( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result { + if let Some(source) = self.phi(words, joins, known)? { return Ok(source); } - if let Some(source) = self.select(words, joins)? { + if let Some(source) = self.select(words, joins, known)? { return Ok(source); } let read = |w: &Term| match *w { @@ -706,11 +756,8 @@ impl<'a> Tracer<'a> { if let Some(sources) = words.iter().map(read).collect::>>() { // Read from the first active lane, as a waterfall loop does: the // dwords each lane holds. - let lanes: Vec = sources - .into_iter() - .map(|v| self.lane_term(Term::Value(v))) - .collect(); - return self.per_lane(&lanes, joins); + let lanes: Vec = sources.into_iter().map(Term::Value).collect(); + return self.per_lane(&lanes, joins, known); } if words.iter().any(|w| read(w).is_some()) { return Err("a descriptor partly read from the first lane"); @@ -763,7 +810,12 @@ impl<'a> Tracer<'a> { /// Words that phis of one block join, traced per predecessor (words /// defined before the join hold on every edge). - fn phi(&self, words: &[Term], joins: &mut Vec) -> Result, &'static str> { + fn phi( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result, &'static str> { let phi_of = |w: &Term| match *w { Term::Value(v) => self.phis[v.0 as usize], Term::Const(_) => None, @@ -792,7 +844,7 @@ impl<'a> Tracer<'a> { None => *w, }) .collect(); - self.classify(&edge, joins) + self.classify(&edge, joins, known) }) .collect::>(); joins.pop(); @@ -805,6 +857,7 @@ impl<'a> Tracer<'a> { &self, words: &[Term], joins: &mut Vec, + known: &mut Known, ) -> Result, &'static str> { let picks: Vec<_> = words .iter() @@ -843,7 +896,7 @@ impl<'a> Tracer<'a> { }; let args = [true, false] .into_iter() - .map(|set| self.classify(&side(set), joins)) + .map(|set| self.classify(&side(set), joins, known)) .collect::>(); joins.pop(); Ok(Some(Source::Select { scc, args: args? })) @@ -969,18 +1022,95 @@ impl<'a> Tracer<'a> { matches!(reg, Some(Reg::V(_))) } + /// [`Self::lane_term`], where every lane in `known` runs each VGPR copy + /// it follows. + fn lane_value(&self, mut t: Term, known: &Known) -> Result { + for _ in 0..MAX_JOINS * 2 { + let Term::Value(v) = t else { break }; + let next = self.vstep(v); + if next == t { + break; + } + if self.varies(t) + && let Some(site) = self.defs[v.0 as usize] + { + self.runs(site, known)?; + } + t = next; + } + Ok(t) + } + + /// One copy of [`Self::vorigin`]: what the `v_mov_b32` writing `v` + /// reads, or `v`'s origin. + fn vstep(&self, v: Value) -> Term { + if let Some(inst) = self.def(v) + && inst.name() == "v_mov_b32" + && let Fields::Valu(f) = &inst.fields + && f.abs == 0 + && f.neg == 0 + && f.sdwa.is_none() + && f.dpp.is_none() + && let Some(t) = f.src.first().and_then(|s| self.raw(inst, s)) + { + return t; + } + self.origin(v) + } + + /// A VALU operand as `inst` reads it: a VGPR's value itself, other + /// operands' origins. + fn raw(&self, inst: &Inst, op: &Operand) -> Option { + match *op { + Operand::Vector { reg, .. } => Some(Term::Value(inst.read(Reg::V(reg))?)), + op => self.term(inst, &op), + } + } + + /// Fails unless every lane in `known` that reaches the vector + /// instruction at `site` runs it: one with its EXEC bit clear there + /// keeps what the registers held before. + fn runs(&self, site: Site, known: &Known) -> Result<(), &'static str> { + let Some(lanes) = self.lanes else { + return Ok(()); + }; + let Some(&Some(guard)) = lanes.guards.get(site.0).and_then(|g| g.get(site.1)) else { + return Ok(()); + }; + let mut skips = known.clone(); + skips.extend([(lanes.reach[site.0], true), (guard, false)]); + if lanes.bools.meet(&skips) { + return Err("a per-lane descriptor written where some lanes may keep the old one"); + } + Ok(()) + } + /// The source of descriptor dwords each lane holds its own of (a /// waterfall loop reads them from the first active lane): the same in /// every lane, loaded per lane from memory a heap address points to, or - /// picked per lane between such sources. - fn per_lane(&self, words: &[Term], joins: &mut Vec) -> Result { + /// picked per lane between such sources, by a lane mask or by the path + /// the lane took. `known` holds in every lane that accesses them. + fn per_lane( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result { + let words = words + .iter() + .map(|&w| self.lane_value(w, known)) + .collect::, _>>()?; + let words = &words[..]; let Some(&lane) = words.iter().find(|&&w| self.varies(w)) else { - return self.classify(words, joins); + return self.classify(words, joins, known); }; - if let Some(source) = self.fetched(words)? { + if let Some(source) = self.fetched(words, known)? { return Ok(source); } - if let Some(source) = self.lane_select(words, joins)? { + if let Some(source) = self.lane_select(words, joins, known)? { + return Ok(source); + } + if let Some(source) = self.lane_phi(words, joins, known)? { return Ok(source); } let Term::Value(v) = lane else { unreachable!() }; @@ -1006,7 +1136,7 @@ impl<'a> Tracer<'a> { /// Dwords of `global_load_dword*` that line up: `first..` of one load, /// then the bytes that follow (an image descriptor takes two /// `global_load_dwordx4`). - fn fetched(&self, words: &[Term]) -> Result, &'static str> { + fn fetched(&self, words: &[Term], known: &Known) -> Result, &'static str> { let at = |w: &Term| -> Option<(Site, usize)> { let Term::Value(v) = *w else { return None }; let site = self.defs[v.0 as usize]?; @@ -1040,6 +1170,7 @@ impl<'a> Tracer<'a> { let (load, first) = sites[0]; let a0 = address(load)?; for (k, &(site, dword)) in sites.iter().enumerate() { + self.runs(site, known)?; let a = address(site)?; let want = a0.offset.wrapping_add(4 * (first + k) as u32); if (a.param, a.dynamic) != (a0.param, a0.dynamic) @@ -1060,6 +1191,7 @@ impl<'a> Tracer<'a> { &self, words: &[Term], joins: &mut Vec, + known: &mut Known, ) -> Result, &'static str> { let picks: Vec<_> = words .iter() @@ -1074,10 +1206,19 @@ impl<'a> Tracer<'a> { if picks.iter().flatten().any(|p| p.0 != mask) { return Err("a descriptor chosen per lane by several masks"); } + for (w, p) in words.iter().zip(&picks) { + if let (Term::Value(v), Some(_)) = (*w, p) + && let Some(site) = self.defs[v.0 as usize] + { + self.runs(site, known)?; + } + } if joins.len() >= MAX_JOINS { return Err("a descriptor joined too often"); } joins.push(usize::MAX); + // Each side holds where the lane's bit of the mask is set, or clear. + let bit = self.lanes.and_then(|l| l.masks.get(&mask).copied()); let side = |set: bool| -> Vec { words .iter() @@ -1096,7 +1237,13 @@ impl<'a> Tracer<'a> { }; let args = [true, false] .into_iter() - .map(|set| self.per_lane(&side(set), joins)) + .map(|set| { + let n = known.len(); + known.extend(bit.map(|b| (b, set))); + let arg = self.per_lane(&side(set), joins, known); + known.truncate(n); + arg + }) .collect::>(); joins.pop(); Ok(Some(Source::Lanes { mask, args: args? })) @@ -1128,8 +1275,113 @@ impl<'a> Tracer<'a> { return None; }; let mask = inst.read(Reg::S(code))?; - let side = |op: &Operand| self.vterm(inst, op).map(|t| self.lane_term(t)); - Some((mask, side(&set)?, side(&clear)?)) + Some((mask, self.raw(inst, &set)?, self.raw(inst, &clear)?)) + } + + /// Per-lane words that phis of one block join, as an if/else on a + /// per-lane condition leaves them: traced on each edge into the block + /// that lanes in `known` can take (other words hold on every edge). + /// Lanes take their own paths ([`Structured`]), so each gets the value + /// of the edge it came by; an edge they cannot take is `None` (a flow + /// block's phi joins an arm's dwords with what lanes that skipped the + /// arm held before, which only they read). + fn lane_phi( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result, &'static str> { + let phi_of = |w: &Term| match *w { + Term::Value(v) => self.phis[v.0 as usize], + Term::Const(_) => None, + }; + let Some((block, _)) = words.iter().find_map(phi_of) else { + return Ok(None); + }; + if words.iter().filter_map(phi_of).any(|(b, _)| b != block) { + return Err("a descriptor joined in several blocks"); + } + if joins.contains(&block) { + return Err("a descriptor that changes in a loop"); + } + let preds = &self.p.blocks[block].preds; + if preds.iter().any(|&q| self.rpo[q] >= self.rpo[block]) { + // shortcut: what a lane holds after some passes is not traced. + return Err("a descriptor read from the first lane of a phi at a loop header"); + } + let Some(lanes) = self.lanes else { + return Err("a descriptor read from the first lane of a phi, without the lanes' paths"); + }; + // The other words must be there before the join: defined in a + // block that dominates it, which (both dominating the access) is + // one the join does not reach. + for w in words { + if let Term::Value(v) = *w + && phi_of(w).is_none() + && let Some((d, _)) = self.defs[v.0 as usize] + && (d == block || self.reaches(block, d)) + { + return Err("a descriptor partly joined by control flow"); + } + } + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(block); + let phis = &self.p.blocks[block].phis; + let mut args = Vec::new(); + for (j, &q) in preds.iter().enumerate() { + let n = known.len(); + known.push((lanes.reach[q], true)); + if let LaneExit::Branch { + when, + taken, + not_taken, + } = lanes.exits[q] + && taken != not_taken + { + known.push((when, taken == block)); + } + let arg = if lanes.bools.meet(known) { + let edge: Vec = words + .iter() + .map(|w| match phi_of(w) { + Some((_, i)) => Term::Value(phis[i].args[j]), + None => *w, + }) + .collect(); + self.per_lane(&edge, joins, known).map(Some) + } else { + Ok(None) + }; + known.truncate(n); + match arg { + Ok(a) => args.push(a), + Err(e) => { + joins.pop(); + return Err(e); + } + } + } + joins.pop(); + Ok(Some(Source::LanePhi { block, args })) + } + + /// Whether a path leads from block `from` to block `to` (to `from` + /// itself only through a back edge). + fn reaches(&self, from: usize, to: usize) -> bool { + let mut seen = vec![false; self.p.blocks.len()]; + let mut stack = self.p.blocks[from].exit.successors(); + while let Some(x) = stack.pop() { + if x == to { + return true; + } + if std::mem::replace(&mut seen[x], true) { + continue; + } + stack.extend(self.p.blocks[x].exit.successors()); + } + false } /// The waterfall loops over descriptors read from the first lane (the @@ -1202,21 +1454,7 @@ impl<'a> Tracer<'a> { /// Whether blocks `a` and `b` are in one loop: each reaches the other /// (a block reaches itself only through a back edge). fn same_loop(&self, a: usize, b: usize) -> bool { - let reaches = |from: usize, to: usize| { - let mut seen = vec![false; self.p.blocks.len()]; - let mut stack = self.p.blocks[from].exit.successors(); - while let Some(x) = stack.pop() { - if x == to { - return true; - } - if std::mem::replace(&mut seen[x], true) { - continue; - } - stack.extend(self.p.blocks[x].exit.successors()); - } - false - }; - reaches(a, b) && reaches(b, a) + self.reaches(a, b) && self.reaches(b, a) } /// Consecutive dwords of one scalar load. @@ -1381,7 +1619,13 @@ pub(crate) mod tests { fn track_words(words: &[u32], layout: &[RootParam], stage: HwStage) -> Resources { let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - track(&crate::ir::build(&code, false, 256).unwrap(), layout, stage).unwrap() + let p = crate::ir::build(&code, false, 256).unwrap(); + track(&p, layout, stage, lanes(&p).as_ref()).unwrap() + } + + /// `p` as one lane runs it, if it structures. + fn lanes(p: &Program) -> Option { + crate::structure::structure(p).ok() } fn param(root: RootType, user_data: u8, sgprs: u32) -> RootParam { @@ -1629,7 +1873,7 @@ pub(crate) mod tests { .flat_map(|w: &u32| w.to_le_bytes()) .collect(); let p = crate::ir::build(&code, false, 256).unwrap(); - let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps).unwrap_err(); + let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps, lanes(&p).as_ref()).unwrap_err(); assert_eq!( err, ShaderError::Unsupported { @@ -1646,7 +1890,7 @@ pub(crate) mod tests { .flat_map(|w: &u32| w.to_le_bytes()) .collect(); let p = crate::ir::build(&code, false, 256).unwrap(); - let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps).unwrap_err(); + let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps, lanes(&p).as_ref()).unwrap_err(); assert_eq!( err, ShaderError::Unsupported { @@ -1826,10 +2070,309 @@ pub(crate) mod tests { 0xBF81_0000, // s_endpgm ]; + /// The waterfall loop of [`WATERFALL_PICKED_WAVE32`] over one of two + /// image descriptors loaded from the table at s0, chosen by control flow + /// as the compiler lowers an if/else on a per-lane condition: lanes below + /// 16 move the first into v[4:11], the others the second, each arm + /// skipped when no lane takes it. The sample goes to the buffer at dword + /// 16 of the table, at lane * 4. + pub(crate) const WATERFALL_JOINED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo + 0x8914_147E, // s_xor_b32 s20, exec_lo, s20 + 0xBF88_0008, // s_cbranch_execz -> 0x70 + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x7E16_021F, // v_mov_b32 v11, s31 + 0xBE94_3D14, // 0x70: s_or_saveexec_b32 s20, s20 + 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88_0008, // s_cbranch_execz -> 0x9c + 0x7E08_0220, // v_mov_b32 v4, s32 + 0x7E0A_0221, // v_mov_b32 v5, s33 + 0x7E0C_0222, // v_mov_b32 v6, s34 + 0x7E0E_0223, // v_mov_b32 v7, s35 + 0x7E10_0224, // v_mov_b32 v8, s36 + 0x7E12_0225, // v_mov_b32 v9, s37 + 0x7E14_0226, // v_mov_b32 v10, s38 + 0x7E16_0227, // v_mov_b32 v11, s39 + 0x887E_147E, // 0x9c: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0x7E18_0504, // 0xa4: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0xa4 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + + /// [`WATERFALL_JOINED_WAVE32`] with other sources on each path: lanes + /// below 16 load table entry (lane & 1) with two `global_load_dwordx4`, + /// the others pick per lane with `v_cndmask_b32` (lanes below 24 the + /// first entry, the rest the second). + pub(crate) const WATERFALL_JOINED_MIXED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x3602_0081, // v_and_b32 v1, 1, v0 + 0x3402_0285, // v_lshlrev_b32 v1, 5, v1 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo + 0x8914_147E, // s_xor_b32 s20, exec_lo, s20 + 0xBF88_0004, // s_cbranch_execz -> 0x68 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xBE94_3D14, // 0x68: s_or_saveexec_b32 s20, s20 + 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88_0011, // s_cbranch_execz -> 0xb8 + 0x7D88_0098, // v_cmp_gt_u32 vcc_lo, 24, v0 + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x0208_0820, // v_cndmask_b32 v4, s32, v4, vcc_lo + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x020A_0A21, // v_cndmask_b32 v5, s33, v5, vcc_lo + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x020C_0C22, // v_cndmask_b32 v6, s34, v6, vcc_lo + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0x020E_0E23, // v_cndmask_b32 v7, s35, v7, vcc_lo + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x0210_1024, // v_cndmask_b32 v8, s36, v8, vcc_lo + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x0212_1225, // v_cndmask_b32 v9, s37, v9, vcc_lo + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x0214_1426, // v_cndmask_b32 v10, s38, v10, vcc_lo + 0x7E16_021F, // v_mov_b32 v11, s31 + 0x0216_1627, // v_cndmask_b32 v11, s39, v11, vcc_lo + 0x887E_147E, // 0xb8: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x7E18_0504, // 0xc4: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0xc4 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + + /// A waterfall loop whose descriptor changes on each pass: v[4:11] holds + /// the first table entry on entry and the second after every pass, so + /// the first lane's dwords are phis of the loop header. + pub(crate) const WATERFALL_LOOPED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x7E16_021F, // v_mov_b32 v11, s31 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0x7E18_0504, // 0x64: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0x7E08_0220, // v_mov_b32 v4, s32 + 0x7E0A_0221, // v_mov_b32 v5, s33 + 0x7E0C_0222, // v_mov_b32 v6, s34 + 0x7E0E_0223, // v_mov_b32 v7, s35 + 0x7E10_0224, // v_mov_b32 v8, s36 + 0x7E12_0225, // v_mov_b32 v9, s37 + 0x7E14_0226, // v_mov_b32 v10, s38 + 0x7E16_0227, // v_mov_b32 v11, s39 + 0xBF89_FFDE, // s_cbranch_execnz -> 0x64 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + + /// A waterfall loop over one of two buffer descriptors (four dwords) + /// loaded from the table at s0, chosen by nested if/else: lanes below 16 + /// move the first into v[4:7], lanes from 16 to 23 the second, and the + /// others keep what v[4:7] held. Only lanes below 24 (the same mask) + /// run the loop, which loads dword `lane` of the chosen buffer, and + /// store it to the buffer at dword 16 of the table. + pub(crate) const WATERFALL_JOINED_BUFFER_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0602, + 0xFA00_0000, // s_load_dwordx4 s[24:27], s[4:5], 0x0 + 0xF408_0802, + 0xFA00_0020, // s_load_dwordx4 s[32:35], s[4:5], 0x20 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xD4C4_001E, + 0x0002_0098, // v_cmp_gt_u32_e64 s30, 24, v0 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo + 0x8914_147E, // s_xor_b32 s20, exec_lo, s20 + 0xBF88_0004, // s_cbranch_execz -> 0x50 + 0x7E08_0218, // 0x40: v_mov_b32 v4, s24 + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0xBE94_3D14, // 0x50: s_or_saveexec_b32 s20, s20 + 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88_0007, // s_cbranch_execz -> 0x78 + 0xBE9F_3C1E, // s_and_saveexec_b32 s31, s30 + 0xBF88_0004, // s_cbranch_execz -> 0x74 + 0x7E08_0220, // 0x64: v_mov_b32 v4, s32 + 0x7E0A_0221, // v_mov_b32 v5, s33 + 0x7E0C_0222, // v_mov_b32 v6, s34 + 0x7E0E_0223, // v_mov_b32 v7, s35 + 0x887E_1F7E, // 0x74: s_or_b32 exec_lo, exec_lo, s31 + 0x887E_147E, // 0x78: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97_3C1E, // s_and_saveexec_b32 s23, s30 + 0xBF88_0013, // s_cbranch_execz -> 0xd0 + 0xBE9D_037E, // s_mov_b32 s29, exec_lo + 0x7E18_0504, // 0x88: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xE030_1000, + 0x8003_0C10, // buffer_load_dword v12, v16, s[12:15], 0 offen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFF1, // s_cbranch_execnz -> 0x88 + 0xBEFE_031D, // s_mov_b32 exec_lo, s29 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0x887E_177E, // 0xd0: s_or_b32 exec_lo, exec_lo, s23 + 0xBF81_0000, // s_endpgm + ]; + fn waterfall(words: &[u32], wave64: bool) -> Result { let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let p = crate::ir::build(&code, wave64, 256).unwrap(); - track(&p, &[param(Table, 0, 1), param(Table, 1, 1)], HwStage::Cs) + let layout = [param(Table, 0, 1), param(Table, 1, 1)]; + track(&p, &layout, HwStage::Cs, lanes(&p).as_ref()) } #[test] @@ -1945,4 +2488,181 @@ pub(crate) mod tests { "{err:?}" ); } + + /// The block of `p` at byte `offset`. + fn block_at(words: &[u32], offset: usize) -> usize { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + p.blocks.iter().position(|b| b.offset == offset).unwrap() + } + + /// The table offset of what the scalar load of `s` reads. + fn table_offset(r: &Resources, s: &Source) -> u32 { + match *s { + Source::Loaded { load, first: 0 } => { + r.scalar.iter().find(|x| x.0 == load).unwrap().1.offset + } + ref s => panic!("{s:?}"), + } + } + + #[test] + fn descriptors_read_from_the_first_lane_of_an_if_else_join_are_traced_per_path() { + let words = WATERFALL_JOINED_WAVE32; + let r = waterfall(words, false).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| matches!(d.source, Source::LanePhi { .. })) + .unwrap(); + // The join after the else arm: lanes that ran it (lanes from 16 on) + // take the second entry (0x20); the others come through the flow + // block, whose join gives lanes that ran the then arm the first one + // (0). No lane that skipped the then arm comes that way, so the + // dwords they held before (the inputs) are not traced. + let Source::LanePhi { block, args } = &image.source else { + unreachable!() + }; + assert_eq!(*block, block_at(words, 0x9c)); + let [Some(flow), Some(other)] = &args[..] else { + panic!("{args:?}") + }; + assert_eq!(table_offset(&r, other), 0x20); + let Source::LanePhi { block, args } = flow else { + panic!("{flow:?}") + }; + assert_eq!(*block, block_at(words, 0x70)); + let [None, Some(then)] = &args[..] else { + panic!("{args:?}") + }; + assert_eq!(table_offset(&r, then), 0); + // The loop's compares are of the joined dwords; still recognised. + assert_eq!(r.waterfall.compares.len(), 4); + assert_eq!(r.waterfall.reads.len(), 8); + // Without the lanes' paths the join is refused. + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let layout = [param(Table, 0, 1), param(Table, 1, 1)]; + let err = track(&p, &layout, HwStage::Cs, None).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane of a phi, without the lanes' paths", + .. + } + ), + "{err:?}" + ); + } + + #[test] + fn descriptors_joined_from_a_per_lane_load_and_a_per_lane_choice_are_traced_per_path() { + let words = WATERFALL_JOINED_MIXED_WAVE32; + let r = waterfall(words, false).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| matches!(d.source, Source::LanePhi { .. })) + .unwrap(); + let Source::LanePhi { block, args } = &image.source else { + unreachable!() + }; + assert_eq!(*block, block_at(words, 0xb8)); + let [ + Some(Source::LanePhi { args: flow, .. }), + Some(Source::Lanes { args: picked, .. }), + ] = &args[..] + else { + panic!("{args:?}") + }; + // The then arm loads each lane's entry from the table at s0. + let [None, Some(Source::Fetched { load, first: 0 })] = flow[..] else { + panic!("{flow:?}") + }; + let a = r.scalar.iter().find(|s| s.0 == load).unwrap().1; + assert_eq!((a.param, a.offset), (0, 0)); + assert!(a.dynamic.is_some()); + // The else arm picks the first entry where vcc is set. + let offsets: Vec = picked.iter().map(|s| table_offset(&r, s)).collect(); + assert_eq!(offsets, [0, 0x20]); + assert_eq!(r.waterfall.compares.len(), 4); + } + + #[test] + fn a_descriptor_read_from_the_first_lane_of_a_loop_phi_fails_naming_it() { + let err = waterfall(WATERFALL_LOOPED_WAVE32, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane of a phi at a loop header", + .. + } + ), + "{err:?}" + ); + } + + #[test] + fn a_per_lane_descriptor_some_lanes_do_not_write_fails() { + // The else arm of WATERFALL_JOINED_WAVE32 not skipped (its + // s_cbranch_execz an s_nop): it runs with EXEC clear in the lanes + // of the then arm, which keep the first entry; the second is not + // every lane's. + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let skip = words.iter().rposition(|&w| w == 0xBF88_0008).unwrap(); + words[skip] = 0xBF80_0000; + let err = waterfall(&words, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a per-lane descriptor written where some lanes may keep the old one", + .. + } + ), + "{err:?}" + ); + } + + #[test] + fn a_buffer_descriptor_joined_per_lane_is_traced_on_the_paths_of_lanes_that_load() { + let words = WATERFALL_JOINED_BUFFER_WAVE32; + let r = waterfall(words, false).unwrap(); + let buffer = r + .descriptors + .iter() + .find(|d| matches!(d.source, Source::LanePhi { .. })) + .unwrap(); + // The outer join: lanes from the else arm's inner join, or (below + // 16) through the flow block. + let Source::LanePhi { block, args } = &buffer.source else { + unreachable!() + }; + assert_eq!(*block, block_at(words, 0x78)); + let [ + Some(Source::LanePhi { args: flow, .. }), + Some(Source::LanePhi { + block: inner, + args: nested, + }), + ] = &args[..] + else { + panic!("{args:?}") + }; + let [None, Some(then)] = &flow[..] else { + panic!("{flow:?}") + }; + assert_eq!(table_offset(&r, then), 0); + // Lanes from 24 on skip the inner arm and keep the inputs, but do + // not load: that edge is not traced. + assert_eq!(*inner, block_at(words, 0x74)); + let [None, Some(other)] = &nested[..] else { + panic!("{nested:?}") + }; + assert_eq!(table_offset(&r, other), 0x20); + assert_eq!(r.waterfall.compares.len(), 2); + assert_eq!(r.waterfall.reads.len(), 4); + } } diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index c557a03..dd5cccf 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -99,6 +99,8 @@ impl Hasher for Fx { const TERMINAL: u32 = u32::MAX; const MAX_NODES: usize = 1 << 21; +/// Case splits [`Bools::meet`] makes before it gives up. +const MAX_MEET: usize = 1 << 16; impl Bools { fn new() -> Self { @@ -221,6 +223,38 @@ impl Bools { self.ite(a, nb, b) } + /// Whether some lane can satisfy every `(b, holds)` of `all` at once: + /// `b` where `holds`, its negation where not. Yes when the search grows + /// too large to finish. + pub fn meet(&self, all: &[(Bool, bool)]) -> bool { + let mut budget = MAX_MEET; + self.meet_in(all.to_vec(), &mut budget) + } + + fn meet_in(&self, mut all: Vec<(Bool, bool)>, budget: &mut usize) -> bool { + let fails = |&(b, holds): &(Bool, bool)| b == if holds { Bool::FALSE } else { Bool::TRUE }; + if all.iter().any(fails) { + return false; + } + all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE); + if all.is_empty() || *budget == 0 { + return true; + } + *budget -= 1; + let top = |b: Bool| self.nodes[b.0 as usize].0; + let v = all.iter().map(|&(b, _)| top(b)).min().expect("not empty"); + [false, true].into_iter().any(|value| { + let next = all + .iter() + .map(|&(b, holds)| { + let (lo, hi) = self.split(b, v); + (if value { hi } else { lo }, holds) + }) + .collect(); + self.meet_in(next, budget) + }) + } + fn implies(&mut self, a: Bool, b: Bool) -> bool { let nb = self.not(b); self.and(a, nb) == Bool::FALSE @@ -306,6 +340,9 @@ pub struct Structured { /// enough (lanes outside EXEC then never get there, so a VGPR write /// needs no old value). Always `None` for scalar instructions. pub guards: Vec>>, + /// Per block: what holds in every lane that enters it (over forward + /// edges; a loop header forgets what its loop redefines). + pub reach: Vec, /// The lane's bit of each lane-mask value, by its low dword's value. pub masks: HashMap, /// Wave64 masks: low dword's value by the high dword's. @@ -587,6 +624,7 @@ impl<'a> Lanes<'a> { bools: self.b, exits, guards, + reach: cond.to_vec(), }) } diff --git a/docs/architecture.md b/docs/architecture.md index 50c9338..4952df3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -91,7 +91,9 @@ a lane can reach them with its EXEC bit clear. `victory_shader::resource` traces each descriptor and scalar memory address to the root parameter it comes from (table, heap, root descriptor or constant). A descriptor a waterfall loop reads from the first lane (`v_readfirstlane_b32`) is traced -to the per-lane load or choice that gives each lane its own, and accessed -with a non-uniform heap index in one pass. `victory translate` +to the per-lane load or choice that gives each lane its own (a mask's +`v_cndmask_b32`, or an if/else whose arms each set it: traced on the paths +the lanes take, from structurisation), and accessed with a non-uniform heap +index in one pass. `victory translate` runs every shader it finds (containers, SGD5 files) through these and lists what they cannot handle yet. From c249f02dd5d933537195c668d8082d82a9e50efa Mon Sep 17 00:00:00 2001 From: Saitken91 <98485913+SAitken91@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:01:02 -0600 Subject: [PATCH 091/445] Shaders: centroid position with conservative depth Pixel programs that write SV_DepthLessEqual or SV_DepthGreaterEqual failed validation: "Interpolation mode for PS input position must be linear_noperspective_centroid or linear_noperspective_sample when outputting oDepthGE or oDepthLE". The position is now declared linear_noperspective_centroid in those programs, as DXC declares it; without multisampling the value is the same. translate --validate on shaders.rpf: vertex/pixel 12172 -> 12186 validated; the error is gone from the list. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/mod.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0df1233..66466eb 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -241,6 +241,13 @@ pub fn emit( _ => 0, }; } + // With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL + // wants the position centroid (or per sample), as DXC declares it then. + if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) { + for e in inputs.iter_mut().filter(|e| e.kind == 3) { + e.interp = 5; + } + } // Per-primitive outputs are constant. The console never exports a // primitive id or cull flag a mesh shader writes (it culls with the // primitive export), so those rows are left out. From 9a8908c3786206a669d5fbc3bbdbe2d534354fe2 Mon Sep 17 00:00:00 2001 From: Advait Palve Date: Tue, 24 Nov 2026 10:56:01 +0530 Subject: [PATCH 092/445] core: show data_dir in config and check its asset policy 'victory config' displays game_dir, cache_dir, and test_titles, but omitted data_dir (where saves, persistent local storage, and crashes.log are stored). It also omitted data_dir from the runtime asset-policy check loop in show_config(). Include data_dir in the output and policy check, and add a unit test in victory-core asserting that a data_dir inside the repository is refused. --- apps/victory/src/main.rs | 3 ++- crates/victory-core/src/config.rs | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index 31392ff..4cf7c31 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -180,6 +180,7 @@ fn show_config() -> Result<()> { ); println!("game_dir : {}", status(&cfg.game_dir)); println!("cache_dir : {}", cfg.cache_dir.display()); + println!("data_dir : {}", cfg.data_dir.display()); for t in &cfg.test_titles { println!("test_title : {}", status(&Some(t.clone()))); } @@ -187,7 +188,7 @@ fn show_config() -> Result<()> { .game_dir .iter() .chain(&cfg.test_titles) - .chain([&cfg.cache_dir]) + .chain([&cfg.cache_dir, &cfg.data_dir]) { if let Err(e) = victory_core::ensure_outside_repo(p) { println!("POLICY VIOLATION: {e}"); diff --git a/crates/victory-core/src/config.rs b/crates/victory-core/src/config.rs index 596aa43..9e55eb8 100644 --- a/crates/victory-core/src/config.rs +++ b/crates/victory-core/src/config.rs @@ -181,4 +181,14 @@ mod tests { }; assert!(cfg.cache_subdir("x").is_err()); } + + #[test] + fn data_inside_repo_is_refused() { + let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("data"); + let cfg = Config { + data_dir: inside, + ..Default::default() + }; + assert!(cfg.data_subdir("x").is_err()); + } } From 25b0f888cab67fc3653c7e17257075ff4c8e932a Mon Sep 17 00:00:00 2001 From: Dathinel <221246794+Dathinel@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:25:14 -0500 Subject: [PATCH 093/445] Test probe: compare direct and joined reads of a shader timestamp (cherry picked from commit 4b2ea70f0940a4317dc934000d249dce0fce50f6) --- crates/victory-shader/src/emit/lower.rs | 37 ++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..8b8302a 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6565,8 +6565,8 @@ mod tests { const S_ENDPGM: u32 = 0xBF81_0000; - /// Lowers a compute program of constants: whether it translates. - fn lowers(words: &[u32]) -> Result<(), crate::ShaderError> { + /// Whether a synthetic compute program translates with these input registers. + fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let native = NativeProgram { stage: HwStage::Cs, @@ -6575,7 +6575,7 @@ mod tests { layout: vec![], used: vec![], io: StageIo::Cs(ComputeIo { - rsrc2: 0, + rsrc2, threads: [1, 1, 1], }), code, @@ -6626,10 +6626,39 @@ mod tests { S_ENDPGM, ]; for words in [add, sub] { - lowers(&words).unwrap(); + lowers(&words, 0).unwrap(); } } + #[test] + fn a_missing_value_stays_missing_through_two_live_joins() { + let mut words = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0001, // skip the first overwrite + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) + 0xBF85_0001, // skip the second overwrite + 0xBE86_0381, // s_mov_b32 s6, 1 + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // use the result to branch + 0xBE83_0380, + S_ENDPGM, + ]; + let group_ids_xy = 3 << 7; + // Compare to a direct read so future timestamp support works in both cases. + let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let direct = [&words[..2], &words[8..]].concat(); + assert_eq!(refusal(&words), refusal(&direct)); + words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead + lowers(&words, group_ids_xy).expect("dead timestamp"); + } + #[test] fn buffer_formats_by_number() { // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, From 3dd467ccee8d6612fa41aa17537c0b182477ceac Mon Sep 17 00:00:00 2001 From: KoLolX3 <94136289+KoLolX3@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:36:08 -0800 Subject: [PATCH 094/445] Shaders: a phi that only another read phi consumes is live too fill_phis treats a phi no one read directly as dead and fills a value with no DXIL form (an unsupported s_memtime result, say) with zero. When that value reaches a read through two joins, the first phi is only read by the second, so it was never marked read: the read lowered with a zero where the same value read directly is refused with "a scalar memory read as data". Mark the incoming phis of every read phi as read, transitively, before the phis are filled. The reproducer from #604 now agrees for the direct and the joined read, and the dead control (the timestamp replaced by a group id) still lowers. --- crates/victory-shader/src/emit/lower.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 8b8302a..c22339d 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6508,6 +6508,20 @@ impl<'a> Lower<'a> { fn fill_phis(&mut self) -> Result<(), Stop> { let p = self.x.p; + // A phi that only another read phi consumes is live too. Without this, a value with no DXIL form that + // reaches a read through two joins is taken for dead at the first join and replaced by zero below, and the + // lowering accepts what it refuses when the same value is read directly. + let mut work: Vec = self.read_phis.iter().copied().collect(); + while let Some(v) = work.pop() { + let Some(&(b, i)) = self.phi_at.get(&v) else { + continue; + }; + for &arg in &p.blocks[b].phis[i].args { + if self.phi_at.contains_key(&arg) && self.read_phis.insert(arg) { + work.push(arg); + } + } + } for (v, b, i) in std::mem::take(&mut self.data_phis) { let phi = &p.blocks[b].phis[i]; let bit = phi.reg == Reg::Scc; From 260611acaaf5ea33748e4d74986aee500e254353 Mon Sep 17 00:00:00 2001 From: Saitken91 <98485913+SAitken91@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:58:14 -0600 Subject: [PATCH 095/445] Shaders: image_sample_o with constant offsets image_sample_o was refused by name. Its offset dword (x in bits 0-5, y in 8-13, z in 16-21, signed) becomes sample's immediate offsets when it is a constant within DXIL's -8..7; a computed or wider offset is still refused, now saying so. Module::int_value reads an integer constant. translate --validate on shaders.rpf: vertex/pixel 12172 -> 12176 validated (all four). Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/bitcode.rs | 11 +++++++++++ crates/victory-shader/src/emit/lower.rs | 21 ++++++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 8b555ad..c96fefa 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -291,6 +291,17 @@ impl Module { self.constant(ty, Const::Aggregate(ids)) } + /// The value of an integer constant; `None` for anything else. + pub fn int_value(&self, v: V) -> Option { + match v { + V::Const(i) => match self.consts[i as usize].1 { + Const::Int(x) => Some(x), + _ => None, + }, + _ => None, + } + } + /// Gives constant `old` the content of `new` (both stay valid). pub fn replace_const(&mut self, old: V, new: V) { if let (V::Const(o), V::Const(n)) = (old, new) { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..0c3b903 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5425,7 +5425,7 @@ impl<'a> Lower<'a> { return Ok(()); } let (op, sample) = match name { - "image_sample" => (60, true), + "image_sample" | "image_sample_o" => (60, true), "image_sample_lz" | "image_sample_l" => (62, true), "image_sample_b" => (61, true), "image_sample_c_lz" => (65, true), @@ -5570,6 +5570,25 @@ impl<'a> Lower<'a> { args.extend(&cs); match op { 60 => { + if offset_word { + // DXIL takes immediate offsets in -8..=7; the + // console's are 6-bit and may be computed. + let w = addr_val(self, 0)?; + let w = self + .s + .m + .int_value(w) + .ok_or("a sample offset that is not constant")? + as u32; + for (k, o) in os.iter_mut().enumerate().take(offsets) { + let x = (w >> (8 * k) & 0x3F) as i32; + let x = if x >= 32 { x - 64 } else { x }; + if !(-8..=7).contains(&x) { + return Err("a sample offset past -8..7"); + } + *o = self.s.m.i32(x as u32); + } + } args.extend(&os); args.push(fu); self.s From a0efd2d37709f9e7c3774b64a3a06ab616a643ba Mon Sep 17 00:00:00 2001 From: AlanQiang0418 Date: Tue, 24 Nov 2026 01:01:55 -0500 Subject: [PATCH 096/445] Shaders: decode GFX10 packed inline constants by operand type --- crates/victory-shader/src/emit/lower.rs | 45 +++++++++++--------- crates/victory-shader/src/emit/valu_tests.rs | 21 +++++++++ 2 files changed, 45 insertions(+), 21 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..673a1ce 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1210,6 +1210,19 @@ impl<'a> Lower<'a> { } } + /// GFX10 puts an inline f16 constant in the low half of the operand. + fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result { + match *op { + Operand::Const(c @ 240..=248) => { + let h = [ + 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, + ][usize::from(c - 240)]; + Ok(self.s.m.i32(h)) + } + _ => self.operand(inst, op), + } + } + fn as_float(&mut self, x: V) -> V { self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32) } @@ -4078,15 +4091,9 @@ impl<'a> Lower<'a> { _ => return Err("a byte select on a 16-bit operation"), } } - let x = match (op, self.src0) { - (_, Some(x)) if k == 0 => x, - (Operand::Const(c @ 240..=248), _) => { - let h = [ - 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, - ][usize::from(c - 240)]; - self.s.m.i32(h) - } - _ => self.operand(inst, &op)?, + let x = match self.src0 { + Some(x) if k == 0 => x, + _ => self.f16_operand(inst, &op)?, }; let c = self.cur; let x = if high { @@ -4417,22 +4424,18 @@ impl<'a> Lower<'a> { /// Half `high` of source `k` of a packed (VOP3P) operation, in the low /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the - /// half the high result reads. Inline float constants are f16 values. - fn packed_src(&mut self, inst: &Inst, k: usize, high: bool) -> Result { + /// half the high result reads. Packed integer instructions see the f32 + /// bits of an inline float constant. + fn packed_src(&mut self, inst: &Inst, k: usize, high: bool, float: bool) -> Result { let Fields::Valu(v) = &inst.fields else { unreachable!() }; let op = *v.src.get(k).ok_or("a missing operand")?; let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0; - let x = match op { - Operand::Const(c @ 240..=248) => { - let h = [ - 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, - ][usize::from(c - 240)]; - // shortcut: taken to fill both halves. - self.s.m.i32(h | h << 16) - } - _ => self.operand(inst, &op)?, + let x = if float { + self.f16_operand(inst, &op)? + } else { + self.operand(inst, &op)? }; let c = self.cur; let x = if sel { @@ -4468,7 +4471,7 @@ impl<'a> Lower<'a> { for high in [false, true] { let mut xs = Vec::new(); for k in 0..n { - let h = self.packed_src(inst, k, high)?; + let h = self.packed_src(inst, k, high, float)?; if float { let mut f = self .s diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6..6c5e09c 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -231,6 +231,27 @@ fn f16_to_f32(bits: u16) -> f32 { f32::from_bits(f32_bits) } +#[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. + // The same GFX10 source field (248) has a different bit pattern for a + // packed floating-point and a packed integer instruction. + let cases = [ + // v_pk_add_f16 v0, 0x3118, v1 + ([0xcc0f4000, 0x1a0202f8], 0x0000_3118), + // v_pk_add_f16 v0, 0x3118, v1 op_sel_hi:[0,1] (use low twice) + ([0xcc0f4000, 0x120202f8], 0x3118_3118), + // v_pk_add_u16 v0, 0x3e22f983, v1 + ([0xcc0a4000, 0x1a0202f8], 0x3e22_f983), + ]; + for (words, expected) in cases { + let shader = build_valu_cs(&words); + run_cases(&shader, &[[0; 4]], |backend, _, _, got| { + assert_eq!(got, expected, "{backend}: {words:08x?}"); + }); + } +} + #[test] fn v_med3_f32_matches_rdna2_with_nan() { // v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157) From b1c83069db62ff3513ab1b5209df42842991cfd0 Mon Sep 17 00:00:00 2001 From: fuzeofficial Date: Tue, 24 Nov 2026 14:38:36 +0900 Subject: [PATCH 097/445] Shaders: prove EXEC selection before collapsing a waterfall --- crates/victory-shader/src/resource.rs | 277 +++++++++++++++++-------- crates/victory-shader/src/structure.rs | 13 ++ 2 files changed, 209 insertions(+), 81 deletions(-) diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index ecd1b23..e54b348 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -14,7 +14,7 @@ use crate::ShaderError; use crate::gfx10::{Fields, NULL, Operand}; -use crate::ir::{Inst, Program, Reg, Value}; +use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; use crate::native::{HwStage, RootParam, RootType}; use crate::structure::{Bool, LaneExit, Structured}; @@ -159,10 +159,9 @@ pub fn track( .collect(), ..Resources::default() }; - // `v_readfirstlane_b32` results descriptors are read from. - let mut first_lane: Vec = Vec::new(); - // Per descriptor read from the first lane: where, and those results. - let mut first_lane_at: Vec<(usize, Vec)> = Vec::new(); + // Group accesses in the same loop so a shared mask can select several + // descriptors together. + let mut first_lane_at = std::collections::BTreeMap::, Vec)>::new(); for (b, block) in p.blocks.iter().enumerate() { for (i, inst) in block.insts.iter().enumerate() { let site = (b, i); @@ -170,13 +169,10 @@ pub fn track( offset: inst.machine.offset, what, }; + let mut first_lane = Vec::new(); let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> { let source = t.descriptor(inst, op, b).map_err(fail)?; - let words = t.first_lane_words(inst, op).unwrap_or_default(); - if !words.is_empty() { - first_lane_at.push((inst.machine.offset, words.clone())); - } - first_lane.extend(words); + first_lane.extend(t.first_lane_words(inst, op).unwrap_or_default()); out.descriptors.push(Descriptor { site, role, source }); Ok(()) }; @@ -213,19 +209,24 @@ pub fn track( } _ => {} } + if !first_lane.is_empty() { + let (accesses, reads) = first_lane_at.entry(b).or_default(); + accesses.push(i); + reads.extend(first_lane); + } } } - out.waterfall = t.waterfall(&first_lane); - // Taking the first lane's descriptor as each lane's own holds only in - // a waterfall loop: one whose compare of the first lane's dwords with - // the lane's own repeats the access until every lane has had its turn. - for (offset, words) in first_lane_at { - if words.iter().any(|w| !out.waterfall.reads.contains(w)) { - return Err(ShaderError::Unsupported { - offset, - what: "a descriptor read from the first lane outside a waterfall loop", - }); - } + for (block, (accesses, mut reads)) in first_lane_at { + reads.sort_unstable(); + reads.dedup(); + let proof = + t.waterfall(block, &accesses, &reads) + .ok_or_else(|| ShaderError::Unsupported { + offset: t.inst((block, accesses[0])).machine.offset, + what: "a descriptor read from the first lane outside a waterfall loop", + })?; + out.waterfall.compares.extend(proof.compares); + out.waterfall.reads.extend(proof.reads); } Ok(out) } @@ -1384,77 +1385,128 @@ impl<'a> Tracer<'a> { false } - /// The waterfall loops over descriptors read from the first lane (the - /// `v_readfirstlane_b32` results `reads`): the `v_cmp_eq` of those - /// results with the dwords they read. - fn waterfall(&self, reads: &[Value]) -> Waterfall { - let mut out = Waterfall::default(); - if reads.is_empty() { - return out; + /// Prove a single-block waterfall at the descriptor access. In each + /// iteration the access serves exactly the matching lanes, and the + /// back edge keeps exactly the other lanes active. + fn waterfall(&self, b: usize, accesses: &[usize], reads: &[Value]) -> Option { + let access = accesses[0]; + let block = &self.p.blocks[b]; + let lanes = self.lanes?; + let exit = block.insts.last()?; + if !matches!(block.exit, Exit::Branch { taken, not_taken } if taken == b && not_taken != b) + || exit.name() != "s_cbranch_execnz" + { + return None; } - for (b, block) in self.p.blocks.iter().enumerate() { - for (i, inst) in block.insts.iter().enumerate() { - let Fields::Valu(f) = &inst.fields else { - continue; - }; - let Some(ty) = inst - .name() - .strip_prefix("v_cmp_eq_") - .or(inst.name().strip_prefix("v_cmpx_eq_")) + let mask = |low: Option, high: Option| { + let high = if self.p.wave64 { Some(high?) } else { None }; + lanes.mask_bits(low?, high) + }; + let exec = |inst: &Inst| mask(inst.read(Reg::S(EXEC)), inst.read(Reg::S(EXEC + 1))); + let selected = exec(&block.insts[access])?; + if accesses + .iter() + .any(|&i| exec(&block.insts[i]) != Some(selected)) + { + return None; + } + let retry = exec(exit)?; + let first = self.defs[reads[0].0 as usize]?; + let remaining = exec(self.inst(first))?; + if reads.iter().any(|v| { + self.defs[v.0 as usize].is_none_or(|at| { + at.0 != b || at.1 >= access || exec(self.inst(at)) != Some(remaining) + }) + }) { + return None; + } + let reach = (lanes.reach[b], true); + let meet = |conditions: &[(Bool, bool)]| lanes.bools.meet(conditions); + let mut out = Waterfall::default(); + let mut required = vec![(remaining, true)]; + for (i, inst) in block.insts[..access].iter().enumerate() { + let Fields::Valu(f) = &inst.fields else { + continue; + }; + let Some(ty) = inst + .name() + .strip_prefix("v_cmp_eq_") + .or(inst.name().strip_prefix("v_cmpx_eq_")) + else { + continue; + }; + let dwords = match ty { + "u32" | "i32" => 1, + "u64" | "i64" => 2, + _ => continue, + }; + if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + continue; + } + // The first lane's dwords on one side, the lane's own on the + // other. + let pair = |first: &Operand, own: &Operand| -> Option> { + let (&Operand::Scalar { code, .. }, &Operand::Vector { reg, .. }) = (first, own) else { + return None; + }; + (0..dwords) + .map(|k| { + let Term::Value(x) = self.origin(inst.read(Reg::S(code + k))?) else { + return None; + }; + let lane = inst.read(Reg::V(reg + k))?; + let (_, read) = self.defs[x.0 as usize]?; + let same = reads.contains(&x) + && read < i + && self.lane_term(Term::Value(self.first_lane_source(x)?)) + == self.lane_term(Term::Value(lane)); + same.then_some(x) + }) + .collect() + }; + let (Some(a), Some(c)) = (f.src.first(), f.src.get(1)) else { + continue; + }; + if let Some(xs) = pair(a, c).or_else(|| pair(c, a)) { + let code = if inst.name().starts_with("v_cmpx_") { + EXEC + } else if let Some(Operand::Scalar { code, .. }) = f.dst { + code + } else { continue; }; - let dwords = match ty { - "u32" | "i32" => 1, - "u64" | "i64" => 2, - _ => continue, + let Some(matched) = mask(inst.write(Reg::S(code)), inst.write(Reg::S(code + 1))) else { + continue; }; - if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + if meet(&[reach, (selected, true), (matched, false)]) { continue; } - // The first lane's dwords on one side, the lane's own on the - // other. - let pair = |first: &Operand, own: &Operand| -> Option> { - let (&Operand::Scalar { code, .. }, &Operand::Vector { reg, .. }) = - (first, own) - else { - return None; - }; - (0..dwords) - .map(|k| { - let Term::Value(x) = self.origin(inst.read(Reg::S(code + k))?) else { - return None; - }; - let lane = inst.read(Reg::V(reg + k))?; - let (d, _) = self.defs[x.0 as usize]?; - let same = reads.contains(&x) - && self.same_loop(b, d) - && self.lane_term(Term::Value(self.first_lane_source(x)?)) - == self.lane_term(Term::Value(lane)); - same.then_some(x) - }) - .collect() - }; - let (Some(a), Some(c)) = (f.src.first(), f.src.get(1)) else { - continue; - }; - if let Some(xs) = pair(a, c).or_else(|| pair(c, a)) { - out.compares.push((b, i)); - for x in xs { - if !out.reads.contains(&x) { - out.reads.push(x); - } + required.push((matched, true)); + out.compares.push((b, i)); + for x in xs { + if !out.reads.contains(&x) { + out.reads.push(x); } } } } - out - } - - /// Whether blocks `a` and `b` are in one loop: each reaches the other - /// (a block reaches itself only through a back edge). - fn same_loop(&self, a: usize, b: usize) -> bool { - self.reaches(a, b) && self.reaches(b, a) + if reads.iter().any(|v| !out.reads.contains(v)) + || meet(&[reach, (selected, true), (remaining, false)]) + { + return None; + } + // The access must take every match. The retry must keep exactly + // the lanes that were eligible but did not perform the access. + required.extend([reach, (selected, false)]); + if meet(&required) + || meet(&[reach, (retry, true), (remaining, false)]) + || meet(&[reach, (retry, true), (selected, true)]) + || meet(&[reach, (remaining, true), (selected, false), (retry, false)]) + { + return None; + } + Some(out) } /// Consecutive dwords of one scalar load. @@ -2469,6 +2521,69 @@ pub(crate) mod tests { ); } + #[test] + fn a_compare_that_does_not_mask_the_access_is_no_waterfall() { + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let save = words.iter().position(|&w| w == 0xBE95_3C15).unwrap(); + words[save] = 0xBE95_037E; // s_mov_b32 s21, exec_lo + let err = waterfall(&words, false).unwrap_err(); + assert!(matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane outside a waterfall loop", + .. + } + )); + } + + #[test] + fn a_loop_that_drops_unmatched_lanes_is_no_waterfall() { + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let retry = words.iter().position(|&w| w == 0x897E_157E).unwrap(); + words[retry] = 0xBEFE_0380; // s_mov_b32 exec_lo, 0 + let err = waterfall(&words, false).unwrap_err(); + assert!(matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane outside a waterfall loop", + .. + } + )); + } + + #[test] + fn a_descriptor_used_after_exec_is_restored_is_no_waterfall() { + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let sample = words.iter().position(|&w| w == 0xF09C_0F08).unwrap(); + let restore = words.iter().position(|&w| w == 0xBEFE_0317).unwrap(); + let image = [words[sample], words[sample + 1]]; + words[sample..sample + 2].fill(0xBF80_0000); // Keep the branch offsets. + words.splice(restore + 1..restore + 1, image); + let err = waterfall(&words, false).unwrap_err(); + assert!(matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane outside a waterfall loop", + .. + } + )); + } + + #[test] + fn a_wave64_access_with_exec_hi_overwritten_is_no_waterfall() { + let mut words = WATERFALL_FETCHED_WAVE64.to_vec(); + let save = words.iter().position(|&w| w == 0xBE96_2416).unwrap(); + words[save + 1] = 0xBEFF_03C1; // s_mov_b32 exec_hi, -1 + let err = waterfall(&words, true).unwrap_err(); + assert!(matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane outside a waterfall loop", + .. + } + )); + } + #[test] fn descriptors_read_from_the_first_lane_of_lds_fail_naming_it() { // The waterfall over descriptors each lane read from LDS: diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index dd5cccf..ae70179 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -345,6 +345,8 @@ pub struct Structured { pub reach: Vec, /// The lane's bit of each lane-mask value, by its low dword's value. pub masks: HashMap, + /// Exact Wave64 pairs for checking masks at their uses. + paired_masks: Map, /// Wave64 masks: low dword's value by the high dword's. pub highs: HashMap, /// Masks (low dwords) set only in lanes whose EXEC bit is set where @@ -353,6 +355,16 @@ pub struct Structured { pub active: HashSet, } +impl Structured { + pub(crate) fn mask_bits(&self, low: Value, high: Option) -> Option { + match high { + Some(high) => self.paired_masks.get(&(low, high)), + None => self.masks.get(&low), + } + .copied() + } +} + /// Builds the per-lane form of `program`. pub fn structure(program: &Program) -> Result { let mut l = Lanes::new(program)?; @@ -620,6 +632,7 @@ impl<'a> Lanes<'a> { .filter(|(lo, hi)| lo != hi) .map(|&(lo, hi)| (hi, lo)) .collect(), + paired_masks: if self.p.wave64 { self.masks } else { Map::default() }, active: self.active, bools: self.b, exits, From 6c63deaa89a28286b1248ed9cdd9f49bf49e32e8 Mon Sep 17 00:00:00 2001 From: "r4." <192970269+r4tedx@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:13:15 +0200 Subject: [PATCH 098/445] Shaders: name why a loop is no waterfall, and test the shapes found in review The previous commit proves that a loop's compares select the lanes of the access and that its retry keeps exactly the lanes still waiting. Every failure of that proof was reported with one reason. They now say which part failed: - the access is in no single-block loop ending in s_cbranch_execnz; - the loop is nested in another or split over blocks; - the compares do not select the access's lanes; - the retry does not keep the lanes still waiting. Without the per-lane form the proof cannot run. Nothing is emitted then, and that failure is the one reported, as before. Tests, all hand-assembled: - the case ifBars reported on upstream PR #566 (the compares never narrow EXEC), an access under a further mask, a retry that keeps other lanes than those waiting, a wave64 retry of one half: refused, each with its reason; - the waterfall LLVM writes for GFX10 and later (a v_cmpx_eq chain, the retry as todo & !EXEC, also folded into s_andn2_wrexec) is accepted in wave32 and wave64, and each lane samples its own texture on the GPU; - one loop per operand, the sampler's inside the resource's, is refused by name. The console gives each lane its own pair there; following the outer loop's reads into the inner block is left for later. Other per-lane work in a waterfall loop is still taken to run once for each lane; marked as a shortcut. Co-Authored-By: Claude Fable 5.2 --- .../src/emit/waterfall_tests.rs | 15 + crates/victory-shader/src/resource.rs | 328 ++++++++++++++---- 2 files changed, 268 insertions(+), 75 deletions(-) diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index c6514b0..a2949e5 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -213,3 +213,18 @@ fn lanes_load_from_the_buffer_their_nested_arms_chose() { assert_eq!(got, want, "{label}"); } } + +#[test] +fn lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx() { + use crate::resource::tests::cmpx_waterfall; + // Lanes below 16 hold the first descriptor, the others the second. + let want: Vec = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect(); + for folded in [false, true] { + let shader = build(&cmpx_waterfall(false, folded), false); + let results = sampled(&shader); + assert!(!results.is_empty()); + for (label, red) in results { + assert_eq!(red, want, "{label}, folded {folded}"); + } + } +} diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index e54b348..0276aa3 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -216,15 +216,20 @@ pub fn track( } } } + // The proof needs the per-lane form. Without it nothing is emitted, and + // its failure is the one to report, so the reads stay unproven here. + if t.lanes.is_none() { + return Ok(out); + } for (block, (accesses, mut reads)) in first_lane_at { reads.sort_unstable(); reads.dedup(); - let proof = - t.waterfall(block, &accesses, &reads) - .ok_or_else(|| ShaderError::Unsupported { - offset: t.inst((block, accesses[0])).machine.offset, - what: "a descriptor read from the first lane outside a waterfall loop", - })?; + let proof = t + .waterfall(block, &accesses, &reads) + .map_err(|what| ShaderError::Unsupported { + offset: t.inst((block, accesses[0])).machine.offset, + what, + })?; out.waterfall.compares.extend(proof.compares); out.waterfall.reads.extend(proof.reads); } @@ -1387,38 +1392,61 @@ impl<'a> Tracer<'a> { /// Prove a single-block waterfall at the descriptor access. In each /// iteration the access serves exactly the matching lanes, and the - /// back edge keeps exactly the other lanes active. - fn waterfall(&self, b: usize, accesses: &[usize], reads: &[Value]) -> Option { + /// back edge keeps exactly the other lanes active. Otherwise, why not. + /// + // shortcut: only the accesses are proven. Any other per-lane work in the + // loop is taken to run once for each lane, as the access does; a body + // whose effect adds up over the passes a lane waits through (a counter + // before the mask is narrowed) would differ. Compilers put nothing but + // the reads, the compares and the access in these loops. + fn waterfall( + &self, + b: usize, + accesses: &[usize], + reads: &[Value], + ) -> Result { + const LOOP: &str = "a descriptor read from the first lane outside a waterfall loop"; + const SPLIT: &str = "a waterfall loop nested in another or split over blocks"; + const SELECT: &str = "a waterfall loop whose compares do not select the access's lanes"; + const RETRY: &str = "a waterfall loop whose retry does not keep the lanes still waiting"; let access = accesses[0]; let block = &self.p.blocks[b]; - let lanes = self.lanes?; - let exit = block.insts.last()?; + let lanes = self.lanes.ok_or(LOOP)?; + let exit = block.insts.last().ok_or(LOOP)?; if !matches!(block.exit, Exit::Branch { taken, not_taken } if taken == b && not_taken != b) || exit.name() != "s_cbranch_execnz" { - return None; + return Err(LOOP); } let mask = |low: Option, high: Option| { let high = if self.p.wave64 { Some(high?) } else { None }; lanes.mask_bits(low?, high) }; let exec = |inst: &Inst| mask(inst.read(Reg::S(EXEC)), inst.read(Reg::S(EXEC + 1))); - let selected = exec(&block.insts[access])?; + // The reads belong to this loop's own block: a loop around this one + // (one per operand, as LLVM nests them for a per-lane image and + // sampler) is not followed. + if reads + .iter() + .any(|v| self.defs[v.0 as usize].is_none_or(|at| at.0 != b)) + { + return Err(SPLIT); + } + let selected = exec(&block.insts[access]).ok_or(SELECT)?; if accesses .iter() .any(|&i| exec(&block.insts[i]) != Some(selected)) { - return None; + return Err(SELECT); } - let retry = exec(exit)?; - let first = self.defs[reads[0].0 as usize]?; - let remaining = exec(self.inst(first))?; + let retry = exec(exit).ok_or(RETRY)?; + let first = self.defs[reads[0].0 as usize].ok_or(LOOP)?; + let remaining = exec(self.inst(first)).ok_or(SELECT)?; if reads.iter().any(|v| { - self.defs[v.0 as usize].is_none_or(|at| { - at.0 != b || at.1 >= access || exec(self.inst(at)) != Some(remaining) - }) + self.defs[v.0 as usize] + .is_none_or(|at| at.1 >= access || exec(self.inst(at)) != Some(remaining)) }) { - return None; + return Err(SELECT); } let reach = (lanes.reach[b], true); let meet = |conditions: &[(Bool, bool)]| lanes.bools.meet(conditions); @@ -1494,19 +1522,22 @@ impl<'a> Tracer<'a> { if reads.iter().any(|v| !out.reads.contains(v)) || meet(&[reach, (selected, true), (remaining, false)]) { - return None; + return Err(SELECT); } - // The access must take every match. The retry must keep exactly - // the lanes that were eligible but did not perform the access. + // The access must take every match. required.extend([reach, (selected, false)]); - if meet(&required) - || meet(&[reach, (retry, true), (remaining, false)]) + if meet(&required) { + return Err(SELECT); + } + // The retry must keep exactly the lanes that were eligible but did + // not perform the access. + if meet(&[reach, (retry, true), (remaining, false)]) || meet(&[reach, (retry, true), (selected, true)]) || meet(&[reach, (remaining, true), (selected, false), (retry, false)]) { - return None; + return Err(RETRY); } - Some(out) + Ok(out) } /// Consecutive dwords of one scalar load. @@ -2501,87 +2532,234 @@ pub(crate) mod tests { ); } + /// Why resource tracking refuses `words`. + fn refusal(words: &[u32], wave64: bool) -> &'static str { + match waterfall(words, wave64) { + Err(ShaderError::Unsupported { what, .. }) => what, + other => panic!("not refused: {other:?}"), + } + } + + const NO_LOOP: &str = "a descriptor read from the first lane outside a waterfall loop"; + const NOT_SELECTED: &str = "a waterfall loop whose compares do not select the access's lanes"; + const BAD_RETRY: &str = "a waterfall loop whose retry does not keep the lanes still waiting"; + const SPLIT: &str = "a waterfall loop nested in another or split over blocks"; + + /// The index of `word` in `words`. + fn word_at(words: &[u32], word: u32) -> usize { + words.iter().position(|&w| w == word).unwrap() + } + #[test] fn a_first_lane_read_without_its_compare_is_no_waterfall() { // The loop without the compare of dwords 0 and 1: nothing makes // the first lane's dwords the lane's own there. let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); - let cmp = words.iter().position(|&w| w == 0x0002_080C).unwrap(); + let cmp = word_at(&words, 0x0002_080C); words[cmp - 1..=cmp].copy_from_slice(&[0xBF80_0000, 0xBF80_0000]); - let err = waterfall(&words, false).unwrap_err(); - assert!( - matches!( - err, - ShaderError::Unsupported { - what: "a descriptor read from the first lane outside a waterfall loop", - .. - } - ), - "{err:?}" - ); + assert_eq!(refusal(&words, false), NOT_SELECTED); } #[test] fn a_compare_that_does_not_mask_the_access_is_no_waterfall() { + // The compares are all there, but their result never narrows EXEC: + // every lane samples with the first lane's descriptor (reported by + // ifBars on upstream PR #566). let mut words = WATERFALL_JOINED_WAVE32.to_vec(); - let save = words.iter().position(|&w| w == 0xBE95_3C15).unwrap(); + let save = word_at(&words, 0xBE95_3C15); words[save] = 0xBE95_037E; // s_mov_b32 s21, exec_lo - let err = waterfall(&words, false).unwrap_err(); - assert!(matches!( - err, - ShaderError::Unsupported { - what: "a descriptor read from the first lane outside a waterfall loop", - .. - } - )); + assert_eq!(refusal(&words, false), NOT_SELECTED); + } + + #[test] + fn an_access_under_a_further_mask_is_no_waterfall() { + // The access runs for the matching lanes that VCC also holds, yet + // the retry removes every matching lane. + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let nop = word_at(&words, 0xBE95_3C15) + 1; + assert_eq!(words[nop], 0xBF80_0000); + words[nop] = 0x877E_6A7E; // s_and_b32 exec_lo, exec_lo, vcc_lo + assert_eq!(refusal(&words, false), NOT_SELECTED); } #[test] fn a_loop_that_drops_unmatched_lanes_is_no_waterfall() { let mut words = WATERFALL_JOINED_WAVE32.to_vec(); - let retry = words.iter().position(|&w| w == 0x897E_157E).unwrap(); + let retry = word_at(&words, 0x897E_157E); words[retry] = 0xBEFE_0380; // s_mov_b32 exec_lo, 0 - let err = waterfall(&words, false).unwrap_err(); - assert!(matches!( - err, - ShaderError::Unsupported { - what: "a descriptor read from the first lane outside a waterfall loop", - .. - } - )); + assert_eq!(refusal(&words, false), BAD_RETRY); + } + + #[test] + fn a_retry_that_keeps_other_lanes_than_those_waiting_is_no_waterfall() { + // The retry keeps the lanes of VCC that did not just sample, not + // the waiting ones: lanes 16 and up never sample on the console. + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let retry = word_at(&words, 0x897E_157E); + words[retry] = 0x8A7E_7E6A; // s_andn2_b32 exec_lo, vcc_lo, exec_lo + assert_eq!(refusal(&words, false), BAD_RETRY); + } + + #[test] + fn a_wave64_retry_of_one_half_is_no_waterfall() { + // Only the low half of EXEC loses the lanes just served. + let mut words = WATERFALL_FETCHED_WAVE64.to_vec(); + let retry = word_at(&words, 0x89FE_167E); + words[retry] = 0x897E_167E; // s_xor_b32 exec_lo, exec_lo, s22 + assert_eq!(refusal(&words, true), BAD_RETRY); } #[test] fn a_descriptor_used_after_exec_is_restored_is_no_waterfall() { let mut words = WATERFALL_JOINED_WAVE32.to_vec(); - let sample = words.iter().position(|&w| w == 0xF09C_0F08).unwrap(); - let restore = words.iter().position(|&w| w == 0xBEFE_0317).unwrap(); + let sample = word_at(&words, 0xF09C_0F08); + let restore = word_at(&words, 0xBEFE_0317); let image = [words[sample], words[sample + 1]]; words[sample..sample + 2].fill(0xBF80_0000); // Keep the branch offsets. words.splice(restore + 1..restore + 1, image); - let err = waterfall(&words, false).unwrap_err(); - assert!(matches!( - err, - ShaderError::Unsupported { - what: "a descriptor read from the first lane outside a waterfall loop", - .. - } - )); + assert_eq!(refusal(&words, false), NO_LOOP); } #[test] fn a_wave64_access_with_exec_hi_overwritten_is_no_waterfall() { let mut words = WATERFALL_FETCHED_WAVE64.to_vec(); - let save = words.iter().position(|&w| w == 0xBE96_2416).unwrap(); + let save = word_at(&words, 0xBE96_2416); words[save + 1] = 0xBEFF_03C1; // s_mov_b32 exec_hi, -1 - let err = waterfall(&words, true).unwrap_err(); - assert!(matches!( - err, - ShaderError::Unsupported { - what: "a descriptor read from the first lane outside a waterfall loop", - .. + assert_eq!(refusal(&words, true), NOT_SELECTED); + } + + /// The waterfall with `v_cmpx_eq` narrowing EXEC itself, and the retry + /// as `todo & !EXEC` (`folded`: in one `s_andn2_wrexec`), as LLVM's + /// AMDGPU backend writes it for GFX10 and later. + pub(crate) fn cmpx_waterfall(wave64: bool, folded: bool) -> Vec { + let (base, todo, restore): (&[u32], u32, u32) = if wave64 { + (WATERFALL_FETCHED_WAVE64, 0xBE94_047E, 0xBEFE_0414) + } else { + (WATERFALL_JOINED_WAVE32, 0xBE97_037E, 0xBEFE_0317) + }; + let reads = word_at(base, 0x7E18_0504); + let sample = word_at(base, 0xF09C_0F08); + let mut w = base[..=word_at(base, todo)].to_vec(); + // s_mov_b32 s21, exec_lo / s_mov_b64 s[22:23], exec + w.push(if wave64 { 0xBE96_047E } else { 0xBE95_037E }); + w.extend(&base[reads..reads + 8]); // v_readfirstlane_b32 s12..s19 + w.extend([ + 0x7DE4_080C, // v_cmpx_eq_u64 s[12:13], v[4:5] + 0x7DE4_0C0E, // v_cmpx_eq_u64 s[14:15], v[6:7] + 0x7DE4_1010, // v_cmpx_eq_u64 s[16:17], v[8:9] + 0x7DE4_1412, // v_cmpx_eq_u64 s[18:19], v[10:11] + ]); + w.extend(&base[sample..sample + 2]); // image_sample_lz + match (wave64, folded) { + // s_andn2_wrexec_b32 s21, s21; s_cbranch_execnz + (false, true) => w.extend([0xBE95_4715, 0xBF89_FFF0]), + // s_andn2_b32 s21, s21, exec_lo; s_mov_b32 exec_lo, s21 + (false, false) => w.extend([0x8A15_7E15, 0xBEFE_0315, 0xBF89_FFEF]), + // s_andn2_wrexec_b64 s[22:23], s[22:23] + (true, true) => w.extend([0xBE96_3A16, 0xBF89_FFF0]), + // s_andn2_b64 s[22:23], s[22:23], exec; s_mov_b64 exec, s[22:23] + (true, false) => w.extend([0x8A96_7E16, 0xBEFE_0416, 0xBF89_FFEF]), + } + w.extend(&base[word_at(base, restore)..]); + w + } + + #[test] + fn a_waterfall_narrowed_by_v_cmpx_is_one() { + for wave64 in [false, true] { + for folded in [false, true] { + let r = waterfall(&cmpx_waterfall(wave64, folded), wave64) + .unwrap_or_else(|e| panic!("wave64 {wave64} folded {folded}: {e:?}")); + assert_eq!(r.waterfall.compares.len(), 4, "{wave64} {folded}"); + assert_eq!(r.waterfall.reads.len(), 8, "{wave64} {folded}"); } - )); + } + } + + #[test] + fn a_v_cmpx_waterfall_whose_retry_drops_lanes_is_none() { + let mut words = cmpx_waterfall(false, false); + let retry = word_at(&words, 0x8A15_7E15); + words[retry] = 0x8A15_7E6A; // s_andn2_b32 s21, vcc_lo, exec_lo + assert_eq!(refusal(&words, false), BAD_RETRY); + } + + #[test] + fn a_waterfall_nested_in_another_is_refused_by_name() { + // An image whose resource and sampler are both per lane, with one + // loop per operand, the one for the sampler inside the one for the + // resource (what the SelectionDAG legalisation in LLVM would give). + // The console gives each lane its own pair. Refused for now: the + // access of the inner loop reads the first-lane dwords of the outer + // loop, which another block holds. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x3602_0081, // v_and_b32 v1, 1, v0 + 0x3402_0285, // v_lshlrev_b32 v1, 5, v1 + 0x3622_0080, // v_and_b32 v17, 0, v0 + 0x3422_2284, // v_lshlrev_b32 v17, 4, v17 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xDC38_8000, + 0x1406_0011, // global_load_dwordx4 v[20:23], v17, s[6:7] + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94_037E, // s_mov_b32 s20, exec_lo + // L1, the loop over the resource: + 0x7E18_0504, // v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, + 0x7E1C_0506, + 0x7E1E_0507, + 0x7E20_0508, + 0x7E22_0509, + 0x7E24_050A, + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBE9A_037E, // s_mov_b32 s26, exec_lo + // L2, the loop over the sampler: + 0x7E10_0514, // v_readfirstlane_b32 s8, v20 + 0x7E12_0515, // v_readfirstlane_b32 s9, v21 + 0x7E14_0516, // v_readfirstlane_b32 s10, v22 + 0x7E16_0517, // v_readfirstlane_b32 s11, v23 + 0xD4E2_0018, + 0x0002_2808, // v_cmp_eq_u64_e64 s24, s[8:9], v[20:21] + 0xD4E2_0019, + 0x0002_2C0A, // v_cmp_eq_u64_e64 s25, s[10:11], v[22:23] + 0x8718_1918, // s_and_b32 s24, s24, s25 + 0xBE98_3C18, // s_and_saveexec_b32 s24, s24 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] + 0x897E_187E, // s_xor_b32 exec_lo, exec_lo, s24 + 0xBF89_FFF2, // s_cbranch_execnz L2 + 0xBEFE_031A, // s_mov_b32 exec_lo, s26 + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFDA, // s_cbranch_execnz L1 + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + assert_eq!(refusal(&words, false), SPLIT); } #[test] From d74558c4fc715d1be6731013e9644cbc43d70565 Mon Sep 17 00:00:00 2001 From: Carlos Sant'Anna Date: Tue, 24 Nov 2026 03:14:58 -0300 Subject: [PATCH 099/445] GPU diagnostics: describe a buffer UAV by its range, not as uav None describe looked only for a host texture, so every UAV over a buffer printed 'uav None' in device-removed reports and drop traces, though the view is made. It now prints the buffer's title range, as a buffer shader view does. --- crates/victory-gpu/src/draw.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index b6e043b..5b043a9 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1131,7 +1131,11 @@ fn describe(view: Option<&View>) -> String { None => "no view".into(), Some(v @ View::Shader(r, _)) => texture(*r as This) .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))), - Some(View::Unordered(r, ..)) => format!("uav {:?}", texture(*r as This)), + // A buffer has no host texture: its title range, as for a shader view. + Some(v @ View::Unordered(r, ..)) => texture(*r as This).map_or_else( + || format!("uav buffer {:?}", crate::descriptor::host::buffer_range(v)), + |t| format!("uav {t}"), + ), Some(View::Placed(u, r, d)) => format!( "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}", r[0], From 764fa19373e0e03cad31804a13290656465bcacc Mon Sep 17 00:00:00 2001 From: lameloball2813-ui <293005050+lameloball2813-ui@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:24:49 -0700 Subject: [PATCH 100/445] Loader tests: build the probe fixture under CARGO_TARGET_TMPDIR --- crates/victory-loader/tests/load_probe.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/victory-loader/tests/load_probe.rs b/crates/victory-loader/tests/load_probe.rs index 6d75d23..cf1111b 100644 --- a/crates/victory-loader/tests/load_probe.rs +++ b/crates/victory-loader/tests/load_probe.rs @@ -20,11 +20,12 @@ fn workspace_root() -> PathBuf { } /// Builds the fixture into its own target dir (the outer cargo holds the -/// lock on the main one while tests run). +/// lock on the main one while tests run), in the outer one's scratch folder +/// for tests, so that it follows `CARGO_TARGET_DIR` like the rest of the +/// build. fn build_probe() -> PathBuf { - let root = workspace_root(); - let manifest = root.join("tests/fixtures/hle-probe/Cargo.toml"); - let target = root.join("target/fixtures"); + let manifest = workspace_root().join("tests/fixtures/hle-probe/Cargo.toml"); + let target = Path::new(env!("CARGO_TARGET_TMPDIR")).join("hle-probe"); let status = Command::new(env!("CARGO")) .args(["build", "--quiet", "--manifest-path"]) .arg(&manifest) From 0064c088d216cc2ba24759b80ca63e90dcfbdcd9 Mon Sep 17 00:00:00 2001 From: fuzeofficial Date: Tue, 24 Nov 2026 15:30:02 +0900 Subject: [PATCH 101/445] GPU: upload CPU-written textures before CopyResource --- crates/victory-gpu/src/list.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 78d6d73..db13bfd 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -446,6 +446,9 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { crate::resource::host_resource(dst), crate::resource::host_resource(src), ) { + if crate::texture::title_written(from) { + crate::texture::upload(list, src, from); + } ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); crate::texture::host_written(dst); From af22e5d3a12c49a3fccc6812b06260715edcab70 Mon Sep 17 00:00:00 2001 From: EatCodeSleep2 <52021568+EatCodeSleep2@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:34:34 -0800 Subject: [PATCH 102/445] GPU: use the host upload path for texture staging copies Queue the list-owned D3D12 staging upload as a host fill so Wine does not skip it based on the title-memory VirtualQuery check. --- crates/victory-gpu/src/list.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 78d6d73..0d5d29b 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -522,7 +522,9 @@ extern "system" fn copy_texture_region( let Some((buffer, staging)) = list.upload(host, bytes) else { return; }; - list.defer_copy(staging, data, bytes as usize); + // The list owns this mapped D3D12 upload buffer. Wine can report + // its address as MEM_FREE, so use the host-upload path. + list.defer_fill(staging, data, bytes as usize); from.resource = buffer.as_raw().cast_const().cast(); from.footprint.offset = 0; #[cfg(feature = "diagnostics")] From 5864aaba28f2ef88d3e32c5710d43ce2b8ef5268 Mon Sep 17 00:00:00 2001 From: lameloball2813-ui <293005050+lameloball2813-ui@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:39:42 -0700 Subject: [PATCH 103/445] Docs: rustdoc builds the loader, GPU and shader crates without warnings --- crates/victory-gpu/src/list.rs | 2 +- crates/victory-gpu/src/shader_cache.rs | 2 +- crates/victory-loader/src/lib.rs | 2 +- crates/victory-shader/src/emit/validator.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 78d6d73..5dbf1a3 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -6,7 +6,7 @@ //! the table as a call. //! //! Each list records onto a host command list as its methods are called -//! (decision 0007); draw state lives in [`crate::draw`]. Methods not +//! (decision 0007); draw state lives in `crate::draw`. Methods not //! written yet log once with their caller, so a run lists what to do next. #![allow(clippy::not_unsafe_ptr_arg_deref)] diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 0cba938..998ec71 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -6,7 +6,7 @@ //! atomically; an entry that does not read back is translated again. //! //! The entry is our own encoding of [`HostShader`]: a field added to it -//! must be added to [`encode`] and [`decode`] too (entries of older builds +//! must be added to `encode` and `decode` too (entries of older builds //! are ignored anyway). use std::path::PathBuf; diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 5a98cae..233ca47 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -4,7 +4,7 @@ //! CPU, so the machine code needs no translation. What differs is the //! platform underneath, so the loader's job is to: //! -//! 1. [`prepare`] a lightly patched copy of the image (pure, portable): mark +//! 1. [`prepare()`] a lightly patched copy of the image (pure, portable): mark //! it as a DLL, remove its entry point and import directory, and detach //! its TLS callbacks, so the Windows loader maps it, relocates it, //! allocates its static TLS and registers its unwind tables, but runs diff --git a/crates/victory-shader/src/emit/validator.rs b/crates/victory-shader/src/emit/validator.rs index 2f4108a..32171c7 100644 --- a/crates/victory-shader/src/emit/validator.rs +++ b/crates/victory-shader/src/emit/validator.rs @@ -1,6 +1,6 @@ //! The DXIL validator in `dxil.dll` (`IDxcValidator`), for tests and the //! offline batch. Translated shaders do not need it: they carry the -//! container hash we compute ([`super::container::hash`]). +//! container hash we compute (`container::hash`). //! //! The DLL is found at `VICTORY_DXIL` if set, else the newest Windows SDK's //! `bin\\x64\dxil.dll`, else wherever `LoadLibrary` finds it. From 31ce30f16954ffdf22758c6f24757a0d8ae79c62 Mon Sep 17 00:00:00 2001 From: fuzeofficial Date: Tue, 24 Nov 2026 15:42:18 +0900 Subject: [PATCH 104/445] GPU: unbind vertex buffer slots for null view arrays --- crates/victory-gpu/src/draw.rs | 6 ++++++ crates/victory-gpu/src/list.rs | 6 +++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index b6e043b..042005b 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -242,6 +242,12 @@ impl State { } } + pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) { + for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) { + *slot = VertexView::default(); + } + } + pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) { self.index = view.copied().unwrap_or_default(); } diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 78d6d73..c52c0c7 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1007,7 +1007,11 @@ mod state { views: *const VertexView, ) { with_state(this, |_, s| { - s.set_vertex_buffers(start, items(views, count)) + if views.is_null() { + s.clear_vertex_buffers(start, count); + } else { + s.set_vertex_buffers(start, items(views, count)); + } }); } /// `(count, handles, one range, depth)`: with one range, the handles From ab3eb92941e9039b1e9bd90f6c51c64572fc425f Mon Sep 17 00:00:00 2001 From: Louis Faust Date: Mon, 23 Nov 2026 22:49:58 -0800 Subject: [PATCH 105/445] Shaders: gate the constant_color test helper to Windows Its only callers (stub_pipeline_is_created, constant_color_validates) are #[cfg(windows)], so on macOS/Linux the helper is dead code and cargo check --all-targets warns 'function constant_color is never used'. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-shader/src/emit/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0df1233..c460527 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -447,6 +447,7 @@ mod tests { } /// A pixel shader writing a constant colour. + #[cfg(windows)] fn constant_color() -> Vec { let mut s = Shader::new(true); s.outputs.push(SigElement { From 4f53d6f1f321de42f955c6e9787f577d5bc644dd Mon Sep 17 00:00:00 2001 From: fuzeofficial Date: Tue, 24 Nov 2026 15:56:38 +0900 Subject: [PATCH 106/445] GPU: upload CPU-written sources before texture region copies --- crates/victory-gpu/src/list.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index db13bfd..411430d 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -538,6 +538,9 @@ extern "system" fn copy_texture_region( let Some(texture) = crate::resource::host_resource(src.resource) else { return; }; + if crate::texture::title_written(texture) { + crate::texture::upload(list, src.resource, texture); + } ensure_state(list, src.resource, COPY_SOURCE); from.resource = texture.as_raw().cast_const().cast(); } From 0f0c872a8f55b356c166c9c6d4185a6bda578e88 Mon Sep 17 00:00:00 2001 From: Louis Faust Date: Mon, 23 Nov 2026 22:59:38 -0800 Subject: [PATCH 107/445] Docs: drop the private intra-doc link to MICRO in texture.rs rustdoc warns that the module docs link to the private const MICRO (rustdoc::private_intra_doc_links). Plain code formatting keeps the reference without the broken link. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-formats/src/texture.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 5d8926c..6a735b6 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -13,7 +13,7 @@ //! (`ComputeSurfaceInfoMacroTiled`, `ComputeThinBlockDimension`, //! `GetMipTailDim`, `GetMaxNumMipsInTail`, `HwlComputeSurfaceInfoLinear`, //! `ComputeSurfaceAddrFromCoordMacroTiled`), and the 256-byte micro tile -//! patterns in [`MICRO`] from `gfx10SwizzlePattern.h` (the RB+ tables, as on +//! patterns in `MICRO` from `gfx10SwizzlePattern.h` (the RB+ tables, as on //! RDNA2). addrlib carries this notice: //! //! Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved. From 51f1627d88dd2d1cc742f95a586ef1fb7ee41b27 Mon Sep 17 00:00:00 2001 From: Lyrnc <98659851+Lyrnc@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:07:26 +0300 Subject: [PATCH 108/445] Shaders: v_cmp_lg is ordered on AMD hosts too (olt | ogt, not fcmp one) v_cmp_lg_{f32,f16} ("less or greater") is ordered and not equal: false when either operand is a NaN, on RDNA2 hardware as in the ISA. It was lowered to `fcmp one`, which says the same, but the AMD D3D12 driver runs `fcmp one` as unordered and returns true for a NaN. NVIDIA and WARP get it right. It now lowers as `olt | ogt`, which all three run alike. New GPU test v_cmp_lg_is_false_for_nan covers both widths: NaN on either side, both NaN, a signalling NaN, +0 against -0, inf against inf and against -inf, and junk in the unread high halves for f16. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/bitcode.rs | 3 ++ crates/victory-shader/src/emit/lower.rs | 49 ++++++++++-------- crates/victory-shader/src/emit/valu_tests.rs | 52 ++++++++++++++++++++ 3 files changed, 84 insertions(+), 20 deletions(-) diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 8b555ad..a5b8af8 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -103,6 +103,9 @@ pub(crate) mod pred { pub const OGE: u8 = 3; pub const OLT: u8 = 4; pub const OLE: u8 = 5; + // Not emitted: the AMD D3D12 driver treats it as UNE, so `v_cmp_lg` + // lowers as OLT | OGT instead. + #[allow(dead_code)] pub const ONE: u8 = 6; pub const ORD: u8 = 7; pub const UNO: u8 = 8; diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..bd01538 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4989,26 +4989,35 @@ impl<'a> Lower<'a> { } else { (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?) }; - let p = match op { - "f" => pred::FALSE, - "lt" => pred::OLT, - "eq" => pred::OEQ, - "le" => pred::OLE, - "gt" => pred::OGT, - "lg" => pred::ONE, - "ge" => pred::OGE, - "o" => pred::ORD, - "u" => pred::UNO, - "nge" => pred::ULT, - "nlg" => pred::UEQ, - "ngt" => pred::ULE, - "nle" => pred::UGT, - "neq" => pred::UNE, - "nlt" => pred::UGE, - "tru" => pred::TRUE, - _ => return Err(inst.name()), - }; - self.s.m.cmp(c, p, a, b) + if op == "lg" { + // Ordered and not equal, false for a NaN, as `olt | ogt`. + // `fcmp one` means the same, but the AMD D3D12 driver + // runs it as unordered (true for a NaN) where NVIDIA + // and WARP do not; olt and ogt agree on all three. + let lt = self.s.m.cmp(c, pred::OLT, a, b); + let gt = self.s.m.cmp(c, pred::OGT, a, b); + self.s.m.bin(c, Bin::Or, lt, gt) + } else { + let p = match op { + "f" => pred::FALSE, + "lt" => pred::OLT, + "eq" => pred::OEQ, + "le" => pred::OLE, + "gt" => pred::OGT, + "ge" => pred::OGE, + "o" => pred::ORD, + "u" => pred::UNO, + "nge" => pred::ULT, + "nlg" => pred::UEQ, + "ngt" => pred::ULE, + "nle" => pred::UGT, + "neq" => pred::UNE, + "nlt" => pred::UGE, + "tru" => pred::TRUE, + _ => return Err(inst.name()), + }; + self.s.m.cmp(c, p, a, b) + } } "u64" | "i64" => { let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6..7a8db43 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -320,6 +320,58 @@ fn v_med3_f16_matches_rdna2_with_nan() { }); } +/// `v_cmp_lg_*` is "less or greater": ordered and not equal, so false when +/// either operand is a NaN (RDNA2 ISA; the same on gfx1036 hardware). +#[test] +fn v_cmp_lg_is_false_for_nan() { + // v_cmp_lg_{f32,f16}_e64 s20, v1, v2 (VOPC 0x005 / 0x0cd in VOP3); + // v_cndmask_b32_e64 v0, 0, 1, s20 (VOP3 0x101) + let nan = f32::NAN.to_bits(); + let (inf, ninf) = (f32::INFINITY.to_bits(), f32::NEG_INFINITY.to_bits()); + let f = f32::to_bits; + let f32_cases: &[([u32; 4], u32)] = &[ + ([f(1.0), f(2.0), 0, 0], 1), + ([f(2.0), f(1.0), 0, 0], 1), + ([f(1.0), f(1.0), 0, 0], 0), + ([f(0.0), f(-0.0), 0, 0], 0), + ([inf, ninf, 0, 0], 1), + ([inf, inf, 0, 0], 0), + ([nan, f(1.0), 0, 0], 0), + ([f(1.0), nan, 0, 0], 0), + ([nan, nan, 0, 0], 0), + ([0x7F80_0001, f(0.0), 0, 0], 0), // a signalling NaN + ]; + let f16_cases: &[([u32; 4], u32)] = &[ + ([0x3C00, 0x4000, 0, 0], 1), + ([0x4000, 0x3C00, 0, 0], 1), + ([0x3C00, 0x3C00, 0, 0], 0), + ([0x0000, 0x8000, 0, 0], 0), + ([0x7C00, 0xFC00, 0, 0], 1), + ([0x7E00, 0x3C00, 0, 0], 0), + ([0x3C00, 0x7E00, 0, 0], 0), + ([0x7E00, 0x7E00, 0, 0], 0), + ([0x7C01, 0x0000, 0, 0], 0), // a signalling NaN + ([0xABCD_3C00, 0x1234_7E00, 0, 0], 0), // only the low halves are read + ]; + for (op, what, cases) in [ + (0x005u16, "v_cmp_lg_f32", f32_cases), + (0x0cd, "v_cmp_lg_f16", f16_cases), + ] { + let mut body = vop3(op, 20, vgpr(1), vgpr(2), 0x80).to_vec(); + body.extend_from_slice(&vop3(0x101, 0, 0x80, 0x81, sgpr(20))); + let shader = build_valu_cs(&body); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!( + got, want, + "{backend}: {what}({:#010x}, {:#010x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + } +} + #[test] fn v_fract_f32_never_returns_one() { // v_fract_f32 v0, v1 (VOP1 opcode 0x020) From 3e39eac1c5dc5a66ac0c98464acd18b06bcc598c Mon Sep 17 00:00:00 2001 From: quaternion Date: Mon, 23 Nov 2026 23:25:18 -0500 Subject: [PATCH 109/445] fix(hle): return XAsync payloads for nonnegative results GetResultSize and GetResult only treated S_OK as success, so a provider finishing with S_FALSE and a payload left the caller's buffers untouched and the call registered forever. Any nonnegative HRESULT is a success code; return the size, let the provider write the result, report bytes used, and release the call. Add a regression completing with S_FALSE and an eight-byte payload. --- crates/victory-hle/src/modules/xasync.rs | 57 ++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 3 deletions(-) diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index 6795057..e603f3d 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -627,7 +627,9 @@ pub fn XAsyncGetResultSize(block: *mut AsyncBlock, out: *mut usize) -> HRESULT { return E_INVALIDARG; } let hr = status(block); - if hr == S_OK { + // Any nonnegative completion carries a result, not just S_OK: S_FALSE + // is a success code too and a provider may return data with it. + if hr >= 0 { // SAFETY: checked non-null. unsafe { out.write(words(block).1.load(Ordering::Acquire)) }; } @@ -656,8 +658,8 @@ pub fn XAsyncGetResult( } let hr = status(block); let size = words(block).1.load(Ordering::Acquire); - if hr != S_OK || size == 0 { - if hr == S_OK && !used.is_null() { + if hr < 0 || size == 0 { + if hr >= 0 && !used.is_null() { // SAFETY: checked non-null. unsafe { used.write(0) }; } @@ -1124,6 +1126,55 @@ mod tests { XTaskQueueCloseHandle(q); } + #[test] + fn a_nonnegative_completion_still_returns_its_payload() { + const S_FALSE: HRESULT = 1; + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data. + let data = unsafe { &*data }; + match op { + OP_BEGIN => XAsyncSchedule(data.block, 0), + OP_DO_WORK => { + XAsyncComplete(data.block, S_FALSE, 8); + S_OK + } + OP_GET_RESULT => { + // SAFETY: the caller checked eight bytes. + unsafe { data.buffer.cast::().write(0x1234) }; + S_OK + } + _ => S_OK, + } + } + let mut q = std::ptr::null(); + assert_eq!(XTaskQueueCreate(0, 0, &mut q), S_OK); + let mut block = AsyncBlock { + queue: q, + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + let identity = 0x77 as *const c_void; + assert_eq!( + XAsyncBegin(&mut block, std::ptr::null_mut(), identity, std::ptr::null(), Some(provider)), + S_OK + ); + assert!(XTaskQueueDispatch(q, WORK, 0)); + assert_eq!(XAsyncGetStatus(&mut block, false), S_FALSE); + let mut size = 0; + assert_eq!(XAsyncGetResultSize(&mut block, &mut size), S_FALSE); + assert_eq!(size, 8); + let mut value = 0u64; + let mut used = 0; + assert_eq!( + XAsyncGetResult(&mut block, identity, 8, (&mut value as *mut u64).cast(), &mut used), + S_OK + ); + assert_eq!((value, used), (0x1234, 8)); + assert!(call((&raw mut block)).is_none(), "the call ends with its result"); + XTaskQueueCloseHandle(q); + } + #[test] fn run_returns_the_work_result() { extern "system" fn work(_: *mut AsyncBlock) -> HRESULT { From 8e79c80e4b71e252bcd271e0587aa662c4770008 Mon Sep 17 00:00:00 2001 From: Marvis Date: Tue, 24 Nov 2026 09:55:29 +0100 Subject: [PATCH 110/445] CI: clippy and tests on pull requests and main A Windows job on the pinned toolchain: clippy with -D warnings on the default and the --all-features (diagnostics) build, then cargo test --workspace, which includes the asset-policy test. main did not build its tests: scalar_bit_tests_lower called lowers() without the rsrc2 argument a parallel change added (0, no input registers). Also drops a double parenthesis clippy flagged in an xasync test. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 33 ++++++++++++++++++++++++ crates/victory-hle/src/modules/xasync.rs | 2 +- crates/victory-shader/src/emit/lower.rs | 2 +- 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..80e6a35 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,33 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + CARGO_TERM_COLOR: always + +jobs: + check: + runs-on: windows-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v5 + # The version and components pinned in rust-toolchain.toml. + - run: rustup toolchain install + - uses: Swatinem/rust-cache@v2 + - name: Clippy + run: cargo clippy --workspace --all-targets --locked -- -D warnings + - name: Clippy, diagnostics build + run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings + # Includes xtask's repository_passes_policy, the asset-policy check. + - name: Tests + run: cargo test --workspace --locked diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index 08234ac..068d75f 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -1179,7 +1179,7 @@ mod tests { S_OK ); assert_eq!((value, used), (0x1234, 8)); - assert!(call((&raw mut block)).is_none(), "the call ends with its result"); + assert!(call(&raw mut block).is_none(), "the call ends with its result"); XTaskQueueCloseHandle(q); } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 7b933c1..211da17 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6960,7 +6960,7 @@ mod tests { ]; for head in bit_tests { let words: Vec = head.iter().chain(&tail).copied().collect(); - lowers(&words).unwrap(); + lowers(&words, 0).unwrap(); } } From 74a9d3316de69b65eb64b2fa5c06089d8979ed6f Mon Sep 17 00:00:00 2001 From: "r4." <192970269+r4tedx@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:26:39 +0200 Subject: [PATCH 111/445] Shader tests: the waterfall tests take the GPU one at a time, with the VALU tests The four tests of emit/waterfall_tests.rs each dispatch on the hardware adapter and on WARP. Run in parallel, the test process sometimes died of an access violation (7 of 24 runs of these four tests on an integration branch; an image test beside a VALU test does the same on WARP). They now take the VALU tests' lock, which moves out of `run_cases` to be shared. With it: 340 workspace tests pass with VICTORY_WARP=1, as on a CI runner, and the shader tests pass on the RTX 5070. Co-Authored-By: Claude Fable 5.2 --- crates/victory-shader/src/emit/valu_tests.rs | 11 +++++++---- crates/victory-shader/src/emit/waterfall_tests.rs | 6 ++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 6ebd5c0..b4ee77d 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -160,6 +160,13 @@ fn build_valu_cs(body: &[u32]) -> HostShader { shader } +/// One GPU test at a time. With these tests on the hardware adapter and WARP +/// from several test threads at once, now and then none of their dispatches +/// ever completes and the test binary hangs; and two GPU tests at once on +/// WARP can end the test process with an access violation. Other GPU test +/// modules take this lock too. +pub(super) static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(()); + /// Runs `shader` on every available SM 6.6 host (hardware GPU and WARP) for /// each 4-dword input set and invokes `check(backend, case_index, inputs, result_dword)`. fn run_cases( @@ -167,10 +174,6 @@ fn run_cases( cases: &[[u32; 4]], mut check: impl FnMut(&str, usize, [u32; 4], u32), ) { - // One test at a time: with these tests on the hardware adapter and WARP - // from several test threads at once, now and then none of their - // dispatches ever completes and the test binary hangs. - static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(()); let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let mut ran = 0; for (label, warp) in [("hardware", false), ("warp", true)] { diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index a2949e5..72e0b95 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -106,6 +106,12 @@ fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { ..Default::default() }]; let mut out = Vec::new(); + // One GPU test at a time, with the VALU tests: in parallel on the + // hardware adapter and WARP the test process sometimes died of an + // access violation (7 of 24 runs of these four tests). + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); for (label, warp) in [("hardware", false), ("warp", true)] { let Ok(host) = Host::new(warp) else { eprintln!("no SM 6.6 {label} device; skipped"); From ffe310eb2098e52169f4c44db5ffdabf43a72622 Mon Sep 17 00:00:00 2001 From: Marvis Date: Tue, 24 Nov 2026 10:53:38 +0100 Subject: [PATCH 112/445] Shaders: the console's waterfall loop over a first-lane table offset The console compiler loops over a per-lane descriptor by reading the first active lane's table offset (v_readfirstlane_b32), narrowing EXEC to the lanes with the same one (v_cmpx_eq_u32), loading that entry (s_load_dwordx8) and dropping those lanes (s_andn2_wrexec). Such a load now goes through the waterfall proof; when it holds, each lane loads its own entry through a non-uniform handle. Unproven, the offset stays the first lane's, as before. Translation census over the title's 26,096 programs: none lost, 108 get past these loops to a later refusal. The 249 programs behind #736 also need per-lane size queries in loops without an access. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 9 +- .../src/emit/waterfall_tests.rs | 13 +++ crates/victory-shader/src/resource.rs | 92 +++++++++++++++++++ 3 files changed, 112 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 26f4d56..c5fbd80 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -3313,7 +3313,12 @@ impl<'a> Lower<'a> { return Ok(h); } let index = self.heap_index(*load, *first, sampler)?; - let h = self.s.heap_handle(self.cur, index, sampler, false, props); + // A waterfall loop's load at the first lane's offset reads + // each lane's own entry (see `resource::Waterfall`). + let per_lane = self.x.res.waterfall.loads.contains(load); + let h = self + .s + .heap_handle(self.cur, index, sampler, per_lane, props); self.handles.insert(key, h); Ok(h) } @@ -7071,12 +7076,12 @@ mod tests { 0xBE83_0380, // s_mov_b32 s3, 0 S_ENDPGM, ]; + for words in [add, sub] { lowers(&words, 0).unwrap(); } } - fn perm_features(selector: u32) -> u64 { // Synthetic compute shader: // v0 is the thread ID and can supply a dynamic selector. diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 72e0b95..104fc6d 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -220,6 +220,19 @@ fn lanes_load_from_the_buffer_their_nested_arms_chose() { } } +#[test] +fn lanes_sample_the_entry_their_offset_names_in_the_console_waterfall() { + use crate::resource::tests::WATERFALL_INDEXED_WAVE32; + let shader = build(WATERFALL_INDEXED_WAVE32, false); + let results = sampled(&shader); + assert!(!results.is_empty()); + for (label, red) in results { + // Even lanes hold entry 0's offset, odd lanes entry 1's. + let want: Vec = (0..32).map(|l| [1.0, 2.0][l & 1]).collect(); + assert_eq!(red, want, "{label}"); + } +} + #[test] fn lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx() { use crate::resource::tests::cmpx_waterfall; diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 0276aa3..62ddd5d 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -133,6 +133,9 @@ pub struct Waterfall { /// The `v_readfirstlane_b32` results they compare, each the lane's own /// source dword. pub reads: Vec, + /// Descriptor loads at a table offset among `reads` (the console + /// compiler's form): each lane loads its own entry. + pub loads: Vec, } /// Traces every descriptor and scalar address of `p`, which runs as @@ -162,6 +165,10 @@ pub fn track( // Group accesses in the same loop so a shared mask can select several // descriptors together. let mut first_lane_at = std::collections::BTreeMap::, Vec)>::new(); + // The console compiler's waterfall reads the first lane's table offset + // and loads that entry: accesses, offset reads and loads by block. + let mut offset_at = + std::collections::BTreeMap::, Vec, Vec)>::new(); for (b, block) in p.blocks.iter().enumerate() { for (i, inst) in block.insts.iter().enumerate() { let site = (b, i); @@ -170,9 +177,17 @@ pub fn track( what, }; let mut first_lane = Vec::new(); + let mut offset = Vec::new(); let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> { let source = t.descriptor(inst, op, b).map_err(fail)?; first_lane.extend(t.first_lane_words(inst, op).unwrap_or_default()); + if let Source::Loaded { load, .. } = source + && let Some((_, a)) = out.scalar.iter().find(|s| s.0 == load) + && let Some(Term::Value(v)) = a.dynamic.map(|d| t.origin(d)) + && t.first_lane_source(v).is_some() + { + offset.push((v, load)); + } out.descriptors.push(Descriptor { site, role, source }); Ok(()) }; @@ -214,6 +229,14 @@ pub fn track( accesses.push(i); reads.extend(first_lane); } + if !offset.is_empty() { + let (accesses, reads, loads) = offset_at.entry(b).or_default(); + accesses.push(i); + for (v, load) in offset { + reads.push(v); + loads.push(load); + } + } } } // The proof needs the per-lane form. Without it nothing is emitted, and @@ -233,6 +256,17 @@ pub fn track( out.waterfall.compares.extend(proof.compares); out.waterfall.reads.extend(proof.reads); } + // Unproven, an offset read stays the first lane's (one uniform entry), + // which is what the hardware reads outside a waterfall loop. + for (block, (accesses, mut reads, loads)) in offset_at { + reads.sort_unstable(); + reads.dedup(); + if let Ok(proof) = t.waterfall(block, &accesses, &reads) { + out.waterfall.compares.extend(proof.compares); + out.waterfall.reads.extend(proof.reads); + out.waterfall.loads.extend(loads); + } + } Ok(out) } @@ -2233,6 +2267,64 @@ pub(crate) mod tests { 0xBF81_0000, // s_endpgm ]; + /// The console compiler's waterfall (Grand Theft Auto VI's ray-tracing + /// resolve and others): each lane holds its entry's byte offset in the + /// table at s0 (v7 = (lane & 1) * 32); the loop reads the first active + /// lane's offset, narrows EXEC to the lanes with the same one + /// (`v_cmpx_eq_u32`), loads that entry with `s_load_dwordx8` and samples, + /// then drops those lanes (`s_andn2_wrexec_b32`). The sample goes to the + /// buffer at dword 16 of the table, at lane * 4. + pub(crate) const WATERFALL_INDEXED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x360E_0081, // v_and_b32 v7, 1, v0 + 0x340E_0E85, // v_lshlrev_b32 v7, 5, v7 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0xBE95_037E, // s_mov_b32 s21, exec_lo + 0x7E28_0507, // 0x40: v_readfirstlane_b32 s20, v7 + 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7 + 0xF40C_0302, + 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21 + 0xBF89_FFF6, // s_cbranch_execnz -> 0x40 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + + #[test] + fn the_console_waterfall_over_a_first_lane_offset_is_one() { + let r = waterfall(WATERFALL_INDEXED_WAVE32, false).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| d.role == Role::Resource) + .unwrap(); + let Source::Loaded { load, first: 0 } = image.source else { + panic!("{:?}", image.source) + }; + let (_, address) = r.scalar.iter().find(|s| s.0 == load).unwrap(); + assert!(address.dynamic.is_some(), "{address:?}"); + assert_eq!(r.waterfall.compares.len(), 1); + assert_eq!(r.waterfall.reads.len(), 1); + assert_eq!(r.waterfall.loads, [load]); + } + /// [`WATERFALL_JOINED_WAVE32`] with other sources on each path: lanes /// below 16 load table entry (lane & 1) with two `global_load_dwordx4`, /// the others pick per lane with `v_cndmask_b32` (lanes below 24 the From 578d459c344aa44753e9a61ea6ba10a8c68f6ea6 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:02:18 -0500 Subject: [PATCH 113/445] victory-gta6: this fork's changes on top of VIctory main (ffe310e) World rendering, lighting, frame-rate and memory work for Grand Theft Auto VI (Xbox Series X profile) on one Windows PC with an NVIDIA RTX 4070. The README describes the state, the changes and the credits. Based on VIctory by Marvisak and contributors (GPL-3.0-or-later); XCL by ivall and contributors was used as a reference. No game files are included. Co-Authored-By: Claude Fable 5.2 --- README.md | 76 + apps/victory/src/main.rs | 12 +- apps/victory/src/run.rs | 6 + apps/victory/src/translate.rs | 55 +- crates/victory-formats/src/bcpack.rs | 21 +- crates/victory-formats/src/texture.rs | 28 +- crates/victory-gpu/src/capture.rs | 200 +- crates/victory-gpu/src/copystat.rs | 1162 ++++- crates/victory-gpu/src/descriptor.rs | 469 +- crates/victory-gpu/src/descriptor/host.rs | 1571 +++++- crates/victory-gpu/src/device.rs | 55 + crates/victory-gpu/src/draw.rs | 1671 +++++- crates/victory-gpu/src/dxgi.rs | 26 +- crates/victory-gpu/src/fence.rs | 24 +- crates/victory-gpu/src/frame.rs | 22 +- crates/victory-gpu/src/host.rs | 4617 ++++++++++++++++- crates/victory-gpu/src/indirect.rs | 1131 +++- crates/victory-gpu/src/inplace.rs | 1170 +++++ crates/victory-gpu/src/lib.rs | 10 +- crates/victory-gpu/src/list.rs | 834 ++- crates/victory-gpu/src/memory.rs | 319 ++ crates/victory-gpu/src/pipeline.rs | 246 +- crates/victory-gpu/src/pipeline/host.rs | 291 +- crates/victory-gpu/src/pipeline/library.rs | 680 ++- crates/victory-gpu/src/pipeline/make.rs | 213 +- crates/victory-gpu/src/primitive.rs | 6 + crates/victory-gpu/src/queue.rs | 557 +- crates/victory-gpu/src/resource.rs | 1618 +++++- crates/victory-gpu/src/shader_cache.rs | 39 +- crates/victory-gpu/src/shadow.rs | 2895 ++++++++++- crates/victory-gpu/src/texture.rs | 859 ++- crates/victory-gpu/src/watch.rs | 767 ++- crates/victory-hle/src/modules/audio.rs | 5 + crates/victory-hle/src/modules/dstorage.rs | 10 + crates/victory-hle/src/modules/gameinput.rs | 16 +- crates/victory-hle/src/modules/xmem.rs | 82 + crates/victory-loader/Cargo.toml | 1 + crates/victory-loader/src/console_insn.rs | 249 + .../victory-loader/src/console_insn_decode.rs | 237 + crates/victory-loader/src/crash.rs | 9 + crates/victory-loader/src/lib.rs | 1 + crates/victory-shader/src/bvh.rs | 696 +++ crates/victory-shader/src/emit/container.rs | 34 +- crates/victory-shader/src/emit/host.rs | 75 +- crates/victory-shader/src/emit/intersect.rs | 557 ++ .../src/emit/intersect_tests.rs | 690 +++ crates/victory-shader/src/emit/lower.rs | 4328 +++++++++++++-- crates/victory-shader/src/emit/mod.rs | 838 ++- crates/victory-shader/src/emit/rect.rs | 484 ++ crates/victory-shader/src/emit/shader.rs | 201 +- crates/victory-shader/src/emit/threading.rs | 218 + crates/victory-shader/src/emit/valu_tests.rs | 336 +- .../src/emit/waterfall_tests.rs | 2 + crates/victory-shader/src/emit/wave.rs | 319 +- crates/victory-shader/src/gfx10/fields.rs | 4 +- crates/victory-shader/src/io.rs | 162 +- crates/victory-shader/src/ir.rs | 451 +- crates/victory-shader/src/lib.rs | 2 + crates/victory-shader/src/resource.rs | 863 ++- crates/victory-shader/src/spill.rs | 380 ++ crates/victory-shader/src/structure.rs | 633 ++- 61 files changed, 32259 insertions(+), 1274 deletions(-) create mode 100644 crates/victory-gpu/src/inplace.rs create mode 100644 crates/victory-gpu/src/memory.rs create mode 100644 crates/victory-loader/src/console_insn.rs create mode 100644 crates/victory-loader/src/console_insn_decode.rs create mode 100644 crates/victory-shader/src/bvh.rs create mode 100644 crates/victory-shader/src/emit/intersect.rs create mode 100644 crates/victory-shader/src/emit/intersect_tests.rs create mode 100644 crates/victory-shader/src/emit/rect.rs create mode 100644 crates/victory-shader/src/emit/threading.rs create mode 100644 crates/victory-shader/src/spill.rs diff --git a/README.md b/README.md index 36b77e4..6dacbed 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,79 @@ +# victory-gta6 + +A work-in-progress fork of [VIctory](https://github.com/Marvisak/VIctory), the +compatibility layer that runs the Xbox Series build of Grand Theft Auto VI +natively on Windows from files the user supplies. This fork follows upstream +`main` and adds fixes aimed at one goal: getting the game's world to render +correctly and playably on one particular PC. + +**This repository contains no game files, code or assets.** You need your own +copy of the game. It is not affiliated with or endorsed by Rockstar Games or +Take-Two Interactive. + +## Credits + +- **[VIctory](https://github.com/Marvisak/VIctory)** by Marvisak and its + contributors is the base of everything here: the loader, the runtime + services, the Direct3D 12 back end and the shader recompiler. Licensed + GPL-3.0-or-later; so is this fork. Upstream's history is kept intact below + the single commit that carries this fork's changes. +- **[XCL](https://github.com/ivall/xcl)** by ivall and its contributors + (GPL-2.0-only) was used as a reference for how the same title behaves under + another layer. Fixes inspired by it were written anew in VIctory's code. +- This fork's changes were developed with [Claude Code](https://claude.com/claude-code). + +## Status of this fork (2026-11-25) + +**Not playable yet: about 3 frames per second, and shadowed areas are black.** +Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, +32 GB RAM. The Series X profile is used throughout. + +| Stage | State in this fork | +|-------|--------------------| +| Boot, menus, start screen | works, 30 fps (as upstream) | +| Opening cutscene | plays from start to finish, in order, lit: title cards, credits cards, night and dusk shots | +| Saves | the game autosaves a checkpoint and loads it again | +| First gameplay scene (the prologue) | renders: characters, textures, sky, sunlit exterior; HUD, pause menu and pad input work | +| Light in shadow | missing: the game's ray-traced bounce light and ray-traced lamp and sun shadows do not run yet, so anything the sun does not hit directly is black | +| Frame rate in the world | 2-3.5 fps (270-450 ms per frame), from 3-6 seconds per frame at the start | +| Stability | no driver hang or device loss in normal runs | + +### What this fork changed (summary) + +Rendering: +- Meshlet culling read its scene buffers as the wrong kind of view, so the world drew almost nothing; fixed. +- Per-draw descriptor tables could run out, after which draws used slots never made for them and the card hung; fixed. +- Light packed by the game's compute shaders was read back through empty copies (sky, probes, fog); fixed for every mip level and layer. +- The fog reconstruction, shadow-mask, hair, blend-shape skinning, fire and several material programs did not translate; fixed. +- Gathers at a named mip level (with and without an offset) read level 0; fixed. +- Implicit-level samples outside pixel shaders produced invalid DXIL in 730 compute programs; fixed. +- Rectangle lists, depth and stencil twins for depth textures written by compute, texture read-backs. +- Ray tracing, in progress and off by default: the game's own structure-builder programs translate, title memory can be read by raw address from shaders, and the hardware ray/box and ray/triangle test is emulated in DXIL (checked against a reference on the GPU). + +Speed and memory: +- Waits for memory values, write-watch queries and page queries no longer walk page tables per call. +- Large title buffers get a copy in card memory, with shader writes found by hashing on the card. +- Submissions can be sent ahead of the wait for the card (`VICTORY_LATE_WAIT`), with a relay thread that lands results as the card finishes (`VICTORY_RELAY`, new and untested in the game). +- The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory. +- An intermittent device loss was traced to the pipeline library file being replaced while mapped; fixed. + +Most of the newer speed changes sit behind environment switches that are off +by default (`VICTORY_LATE_WAIT`, `VICTORY_RELAY`, `VICTORY_WIDE_BACK`, +`VICTORY_CARD_BUFFERS_MIN_MB`, `VICTORY_INPLACE`, `VICTORY_BVH_BUILDER`, ...). +Each is described in a comment where it is read. + +### Known problems + +- Everything in shadow is black (see above). +- The interior of the first gameplay room is sometimes not drawn after the cutscene hands over to gameplay. +- Around 24 GB of memory is in use during play. +- Many changes here are specific to this title and this GPU, and some are marked `shortcut:` in the code where they approximate what the console does. + +Everything below this line is upstream VIctory's own README, unchanged; its +status section describes upstream, not this fork. + +--- + # VIctory Runs Grand Theft Auto VI (Xbox Series X|S) natively on Windows, from files diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index 4cf7c31..842ce77 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -152,7 +152,17 @@ fn main() -> Result<()> { pipelines, list, jobs, - } => translate::run(paths, validate, pipelines, list, jobs), + } => { + // `VICTORY_VIEW_LIMIT=`: translate as on a host whose view heap is capped + if let Some(n) = std::env::var("VICTORY_VIEW_LIMIT").ok().and_then(|v| v.parse().ok()) { + victory_shader::emit::set_view_heap_limit(n); + } + // `VICTORY_HOST_WAVE=32`: translate as for a GPU whose waves are at most 32 lanes + if let Some(n) = std::env::var("VICTORY_HOST_WAVE").ok().and_then(|v| v.parse().ok()) { + victory_shader::emit::set_host_max_wave(n); + } + translate::run(paths, validate, pipelines, list, jobs) + } Command::Run { exe, unimplemented, diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 5213147..a73aecb 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -30,6 +30,12 @@ pub fn run( let images = cfg.cache_subdir("images")?; victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); let image = victory_loader::load(&prepared, &images)?; + // The program is mapped from the copy `load` wrote: the file's bytes + // and their patched copy are not read again, and were held for the + // whole run (two blocks of 114.7 MB each for Grand Theft Auto VI, in + // physical memory: run 65's memory map). + drop(prepared); + drop(original); victory_hle::runtime::set_main_image(image.base()); victory_hle::runtime::set_image_path(image.base(), exe); println!( diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 4ea1f14..f03af00 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -312,6 +312,10 @@ fn translate( let Some(bytes) = source.bytes() else { return t.fail("corrupt record".into(), example); }; + // The hash a run's log names the shader by (`hash=` in "first bind", + // "shader does not translate", "host pipeline refused"). + let hash = blake3::hash(&bytes).to_hex()[..16].to_owned(); + let example = || format!("{}{} #{hash}", path.display(), source.label()); t.containers += 1; let Ok(container) = Container::parse(&bytes) else { return t.fail("no DXIL part (SM5 or older)".into(), example); @@ -319,17 +323,61 @@ fn translate( let Some(dxil) = container.part(FourCC::DXIL).map(|p| p.data) else { return t.fail("no DXIL part (SM5 or older)".into(), example); }; - if !lock(seen).insert(blake3::hash(dxil)) { + // `~`: the hash of the code alone; containers that differ only around + // it are translated once, the others listed as duplicates of it. + let code = blake3::hash(dxil); + let code8 = code.to_hex()[..8].to_owned(); + let example = || format!("{} ~{code8}", example()); + // `VICTORY_DUMP_MATCH=;|...`: the containers whose + // line holds one of the texts (a name, `#hash`), as the title has them. + if let Ok(spec) = std::env::var("VICTORY_DUMP_MATCH") + && let Some((dir, texts)) = spec.split_once(';') + { + let line = example(); + if texts.split('|').any(|text| !text.is_empty() && line.contains(text)) { + let name: String = source + .label() + .chars() + .skip_while(|c| *c != ' ') + .filter(|c| c.is_ascii_alphanumeric() || *c == '_') + .take(70) + .collect(); + let _ = std::fs::create_dir_all(dir); + let _ = std::fs::write(std::path::Path::new(dir).join(format!("{name}.{hash}.cdxil")), &bytes[..]); + } + } + if !lock(seen).insert(code) { t.duplicates += 1; + if t.list { + t.lines.push(format!("{} duplicate", example())); + } return; } let programs = match native_programs(dxil) { Ok(p) => p, Err(e) => return t.fail(e.to_string(), example), }; + // `VICTORY_FAIL_DUMP=`: the first 3 containers of each failure reason, as the title + // has them (`.cdxil`), to work on a translator gap offline + let dump = std::env::var_os("VICTORY_FAIL_DUMP"); + let before: Option> = dump.as_ref().map(|_| t.failed.iter().map(|(k, v)| (k.clone(), v.0)).collect()); + translate_programs(&container, programs, &example, t, checks); + if let (Some(dir), Some(before)) = (dump, before) { + for (reason, (n, _)) in &t.failed { + let was = before.get(reason).copied().unwrap_or(0); + if *n > was && was < 3 { + let stem: String = reason.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).take(60).collect(); + let _ = std::fs::create_dir_all(&dir); + let _ = std::fs::write(std::path::Path::new(&dir).join(format!("{stem}_{was}.cdxil")), &bytes[..]); + } + } + } +} + +fn translate_programs(container: &Container, programs: Vec, example: &dyn Fn() -> String, t: &mut Tally, checks: &mut Checks) { for p in programs { t.programs += 1; - match ir::build(&p.patched_code(), p.wave64, p.vgprs) { + match victory_shader::spill::build(&p) { Ok(program) => { t.translated += 1; t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::(); @@ -390,7 +438,7 @@ fn translate( if let (Some(r), Some(i), Some(s)) = (res, raised, structured) { let label = || format!("{} {:?}", example(), p.stage); *counter(t, p.stage, 0) += 1; - match emit::emit(&container, &p, &program, &s, &i, &r) { + match emit::emit(container, &p, &program, &s, &i, &r) { Ok(shader) => { *counter(t, p.stage, 1) += 1; check(shader, t, checks, label); @@ -525,6 +573,7 @@ fn tally_io(r: &io::Io, t: &mut Tally) { match i { io::Interp::Interpolated { .. } => t.interpolated += 1, io::Interp::Vertex { .. } => t.vertex_values += 1, + io::Interp::Weighted { .. } => t.interpolated += 1, } } for e in &r.exports { diff --git a/crates/victory-formats/src/bcpack.rs b/crates/victory-formats/src/bcpack.rs index 360dce1..c8d3537 100644 --- a/crates/victory-formats/src/bcpack.rs +++ b/crates/victory-formats/src/bcpack.rs @@ -129,8 +129,8 @@ impl Tables { /// alpha 64 B and colour 256 B, BC4 64 B, BC5 64 B), 512 u16 BC7 control /// words, then 255 dictionary entries per format in format order: BC1 /// 6 + 16 B, BC3 8 + 32 B, BC4 2 + 16 B, BC5 4 + 32 B, BC6H (u8 mode, - /// 12 u16, u8 mode, 16 i16), BC7 (u16 control, 24 u16, 2 u8, 32 i16). - /// Little-endian, no padding. Every model must tile 65536. + /// 12 u16, u8 mode, 16 i16), BC7 (u16 control, 24 u16, 2 u8, 2 B, + /// 16 + 15 i16). Little-endian, no padding. Every model must tile 65536. pub fn parse(bytes: &[u8]) -> Result { if bytes.len() != TABLES_SIZE { return Err(Error("table file has the wrong size")); @@ -222,7 +222,10 @@ impl Tables { bits: [r.u8(), r.u8()], ..Default::default() }; - for v in ix.ix.as_flattened_mut() { + // Unused: the widths again in all entries but the first. + r.u16(); + // Only 15 slots for set 1, which no entry uses (0 bits). + for v in &mut ix.ix.as_flattened_mut()[..31] { *v = r.u16() as i16; } (ep, ix) @@ -1590,4 +1593,16 @@ mod tests { } assert!(n > 0); } + + /// A dictionary entry stands in for a block the decoder made: a set with + /// 0 index bits holds no indices, and pixel 0 is the anchor (top bit clear). + #[test] + fn bc7_dictionary_indices_line_up() { + let t = Tables::builtin().unwrap(); + for (k, (_, ix)) in t.bc7.iter().enumerate() { + let anchor = 0..1 << (ix.bits[0] - 1); + let ok = (ix.bits[1] != 0 || ix.ix[1] == [0; 16]) && anchor.contains(&ix.ix[0][0]); + assert!(ok, "entry {k}: {:?}", ix.ix); + } + } } diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 6a735b6..a1f72e4 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -671,6 +671,13 @@ impl Layout { } runs.push((first_tiled, first_linear, bytes - first_linear)); } + // A mip can end partway through the last run. Check the other runs + // once so each row can copy them with a compile-time length. + let (body, last) = runs.split_at(runs.len().saturating_sub(1)); + let run_len = body + .first() + .map(|run| run.2) + .filter(|&len| body.iter().all(|run| run.2 == len)); for z in 0..depth { let (s, inner) = self.split(first + z); let base = u64::from(s) * self.slice_size + m.offset; @@ -681,9 +688,13 @@ impl Layout { copy(tiled_row as usize, linear_row, bytes); } else { let tiled_row = (base + self.row(m, y, inner)) as usize; - for &(tiled, linear, len) in &runs { - copy(tiled_row + tiled, linear_row + linear, len); + match run_len { + Some(8) => copy_runs::<8>(body, tiled_row, linear_row, &mut copy), + Some(16) => copy_runs::<16>(body, tiled_row, linear_row, &mut copy), + Some(32) => copy_runs::<32>(body, tiled_row, linear_row, &mut copy), + _ => copy_runs::<0>(body, tiled_row, linear_row, &mut copy), } + copy_runs::<0>(last, tiled_row, linear_row, &mut copy); } } } @@ -691,6 +702,19 @@ impl Layout { } } +/// Copy micro-tile runs inline at a known width, or use each run's length for N = 0. +fn copy_runs( + runs: &[(usize, usize, usize)], + tiled_row: usize, + linear_row: usize, + copy: &mut impl FnMut(usize, usize, usize), +) { + for &(tiled, linear, len) in runs { + let len = if N == 0 { len } else { N }; + copy(tiled_row + tiled, linear_row + linear, len); + } +} + /// What a DXGI format stores per element: bytes, texels per element side /// (4 for block compression), and whether its stencil is a second plane /// (the GPU keeps depth and stencil apart). diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index e91cf62..df610fe 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -20,18 +20,139 @@ pub(crate) fn folder() -> Option<&'static PathBuf> { /// too, and their draws traced at debug level. pub(crate) fn listed(n: u64) -> bool { static LIST: std::sync::OnceLock> = std::sync::OnceLock::new(); - LIST.get_or_init(|| { - let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default(); + let named = LIST + .get_or_init(|| { + let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default(); + list.split(',') + .filter_map(|f| f.trim().parse().ok()) + .collect() + }) + .contains(&n); + // `VICTORY_CAPTURE_WORLD`: also the 2nd and the 6th frame after the first + // one that ran 500 draws or more (a title's first 3D frames: their + // numbers depend on how long the menus were shown), and the 30th and + // the 80th (Grand Theft Auto VI opens with a cutscene made in the + // engine: later shots of it, in case the first is dark by design). + // + // `VICTORY_CAPTURE_WORLD_ALSO` (comma-separated): more frames counted + // from that first one (Grand Theft Auto VI's blue patches show from + // about the 118th frame on, when the window's model has arrived and + // the reflections hold values: none of the four above has them). + static ALSO: std::sync::OnceLock> = std::sync::OnceLock::new(); + let also = ALSO.get_or_init(|| { + let list = std::env::var("VICTORY_CAPTURE_WORLD_ALSO").unwrap_or_default(); list.split(',') .filter_map(|f| f.trim().parse().ok()) .collect() - }) - .contains(&n) + }); + let first = WORLD.load(std::sync::atomic::Ordering::Relaxed); + let after = n.wrapping_sub(first); + named || first != u64::MAX && ([2, 6, 30, 80].contains(&after) || also.contains(&after)) +} + +/// With a capture folder, for the frames [`listed`]: `what` is added to +/// the frame's `frame--ops.txt`, one line per draw, dispatch, copy or +/// drop in the order recorded (the title records on several threads, so +/// lines of different lists interleave; each names its list). The file +/// says which pass writes which target, to find the pass whose output +/// stays empty. +#[cfg(feature = "diagnostics")] +pub(crate) fn op(list: usize, what: impl FnOnce() -> String) { + use std::io::Write; + let frame = crate::queue::presented() + 1; + if !listed(frame) { + // Before the world: the last lines are kept, and written out when + // it starts (`before-world-ops.txt`): what the title drew just + // before (Grand Theft Auto VI shows a title card there, whose text + // did not show). + if world_on() && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX { + // At most 300 lines of a frame: the world's first frame alone + // (thousands of operations, recorded before it is known to be + // the world's) pushed everything before it out. + static IN_FRAME: std::sync::Mutex<(u64, u32)> = std::sync::Mutex::new((0, 0)); + { + let mut in_frame = IN_FRAME.lock().unwrap_or_else(|e| e.into_inner()); + if in_frame.0 != frame { + *in_frame = (frame, 0); + } + in_frame.1 += 1; + if in_frame.1 > 300 { + return; + } + } + let what = what(); + let mut ring = RING.lock().unwrap_or_else(|e| e.into_inner()); + if ring.len() >= RING_LINES { + ring.pop_front(); + } + ring.push_back(format!("frame {frame} list {list:#x} {what}")); + } + return; + } + let Some(folder) = folder() else { + return; + }; + static FILE: std::sync::Mutex> = std::sync::Mutex::new(None); + let what = what(); + let mut file = FILE.lock().unwrap_or_else(|e| e.into_inner()); + if file.as_ref().is_none_or(|f| f.0 != frame) { + let Ok(made) = std::fs::File::create(folder.join(format!("frame-{frame}-ops.txt"))) else { + return; + }; + *file = Some((frame, 0, made)); + } + if let Some((_, n, f)) = file.as_mut() { + *n += 1; + let _ = writeln!(f, "{n} list {list:#x} {what}"); + } +} + +/// The last lines of [`op`] before the world. +#[cfg(feature = "diagnostics")] +static RING: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::VecDeque::new()); +#[cfg(feature = "diagnostics")] +const RING_LINES: usize = 6000; + +/// Whether `VICTORY_CAPTURE_WORLD` is set. +fn world_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CAPTURE_WORLD").is_some()) +} + +/// The first frame that ran 500 draws or more (`VICTORY_CAPTURE_WORLD`). +static WORLD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX); + +/// At the present of `frame`: the draws run on the host so far. +pub(crate) fn frame_drew(frame: u64, drawn: u64) { + use std::sync::atomic::Ordering::Relaxed; + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let before = LAST.swap(drawn, Relaxed); + if world_on() + && drawn.saturating_sub(before) >= 500 + && WORLD.compare_exchange(u64::MAX, frame, Relaxed, Relaxed).is_ok() + { + tracing::info!(frame, "the first frame of 500 draws or more: frames {} and {} are captured", frame + 2, frame + 6); + #[cfg(feature = "diagnostics")] + if let Some(folder) = folder() { + let lines: Vec = std::mem::take(&mut *RING.lock().unwrap_or_else(|e| e.into_inner())).into(); + let _ = std::fs::write(folder.join("before-world-ops.txt"), lines.join(" +")); + } + } } /// Whether frame `n` is saved. pub(crate) fn wanted(n: u64) -> bool { - folder().is_some() && (n.is_power_of_two() || listed(n)) + // Before the world, with `VICTORY_CAPTURE_WORLD`: every 16th frame too + // (small pictures of menus, loading screens and title cards). + let before_world = world_on() && n % 16 == 0 && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX; + // In the world: every 8th frame's picture, a timeline of the opening + // cutscene (its shots do not fall on the same frame numbers from run to + // run, so single frames cannot be compared between runs). + let first = WORLD.load(std::sync::atomic::Ordering::Relaxed); + let in_world = world_on() && first != u64::MAX && n > first && (n - first) % 8 == 0; + folder().is_some() && (n.is_power_of_two() || listed(n) || before_world || in_world) } /// Saves 8-bit RGBA or BGRA rows (`pitch` bytes apart) as frame `n`. @@ -281,6 +402,26 @@ fn dump_one( } let pitch = f.RowPitch as usize; let rows = std::slice::from_raw_parts(data.cast::(), pitch * f.Height as usize); + // A 24-bit depth plane comes back as 32-bit words: which depth values + // (low 24 bits) and which top bytes it holds, the most common first. + if matches!(d.Format.0, 44..=47) { + let mut depths = std::collections::HashMap::::new(); + let mut tops = std::collections::HashMap::::new(); + for y in 0..f.Height as usize { + for x in 0..f.Width as usize { + let at = y * pitch + x * 4; + let w = u32::from_le_bytes(rows[at..at + 4].try_into().unwrap_or([0; 4])); + *depths.entry(w & 0xff_ffff).or_default() += 1; + *tops.entry(w >> 24).or_default() += 1; + } + } + let most = |m: std::collections::HashMap| { + let mut v: Vec<(u32, u32)> = m.into_iter().collect(); + v.sort_by_key(|e| std::cmp::Reverse(e.1)); + (v.len(), v.into_iter().take(12).collect::>()) + }; + tracing::info!(?resource, depths = ?most(depths), top_bytes = ?most(tops), "24-bit depth plane values (value, texels)"); + } if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) { let name = format!( "frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}", @@ -384,9 +525,54 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option (0.0, finite.fold(0.0f32, f32::max)) }; let range = (high - low).max(1e-20); - tracing::info!(format, low, high, "target values"); + // How much of the target holds anything: a lit scene and one bright + // lamp on black have the same highest value. + let above = values.iter().filter(|v| v.iter().any(|c| c.is_finite() && *c > low)).count(); + let nonzero_percent = above as f32 * 100.0 / values.len().max(1) as f32; + tracing::info!(format, low, high, nonzero_percent, "target values"); + // Small float colour targets (the 1x1 luminance and exposure targets): + // every texel's four channels as numbers. The picture has no alpha and + // eight bits a channel. + if matches!(format, 1..=2 | 9..=10) && w * h <= 16 { + for y in 0..h { + for x in 0..w { + let b = px(x, y, n); + let texel: [f32; 4] = if n == 16 { + [0, 1, 2, 3].map(|i| f32::from_bits(u32_at(b, i))) + } else { + [0, 1, 2, 3].map(|i| half(u16_at(b, i))) + }; + tracing::info!(format, x, y, ?texel, "target texel"); + } + } + } + // R32_UINT targets hold packed light (the title reads them back as + // R9G9B9E5): as floats their low, high and share above the lowest say + // nothing. How many texels hold any bit, and the highest channel value + // of the packed reading. + if format == 42 { + let (mut set, mut packed_high) = (0usize, 0f32); + for y in 0..h { + for x in 0..w { + let v = u32_at(px(x, y, 4), 0); + set += usize::from(v != 0); + let scale = 2f32.powi((v >> 27) as i32 - 24); + for k in 0..3 { + packed_high = packed_high.max((v >> (9 * k) & 0x1ff) as f32 * scale); + } + } + } + let nonzero_bits_percent = set as f32 * 100.0 / (w * h).max(1) as f32; + tracing::info!(format, nonzero_bits_percent, packed_high, "target values as packed light"); + } + // Float colours (scene light) go through a cube root: scaled linearly, + // a night scene under one lamp of 50 units came out all black. + let curved = matches!(format, 1..=2 | 9..=10 | 26); for v in values { - let c = v.map(|c| (((c - low) / range).clamp(0.0, 1.0) * 255.0) as u8); + let c = v.map(|c| { + let t = ((c - low) / range).clamp(0.0, 1.0); + ((if curved { t.cbrt() } else { t }) * 255.0) as u8 + }); out.extend([c[0], c[1], c[2], 255]); } Some(out) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 8b7d13d..6abd41b 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -37,8 +37,98 @@ pub(crate) enum C { TexWatched, TexHashed, TexChanged, + /// Frames presented since the last line (what the line divides by). + Frames, + /// Calls of list methods that record into a host list, and the + /// nanoseconds they took, summed over the title's recording threads. + RecordCalls, + RecordNs, + /// Waiting for host pipelines being made (`pipeline::make`). + PipelineWaitUs, + /// Dynamic descriptor slots: tables asked for, refused (no free run), + /// and the nanoseconds of the searches. + DynamicAsked, + DynamicRefused, + DynamicNs, + /// Marker texts for device-removed data (`HostList::note`). + NoteNs, + /// Ranges given to shaders (steps), their snapshots, and the bytes + /// compared after the submission. + GpuWrites, + SnapshotUs, + BackCompared, + /// Reading around unmapped pages after a failed bulk read. + SparseUs, + /// Guarding view memory (part of the write-watch askings' time). + GuardUs, + /// Bytes copied whole because their memory is neither write-watched + /// nor a view (`Shadow::update_free`). + WholeBytes, + /// Submissions with ranges shaders write (they need the GPU's results + /// before they return). + BackSubmissions, + /// The title's frame waits (`frame::wait`) and the time slept in them, + /// over all its threads. + PaceWaits, + PaceUs, + /// After a present: until the title's first list call and until its + /// first submission; and from its last submission to its next present. + UntilRecordUs, + UntilSubmitUs, + TailUs, + /// Resetting host lists (`HostList::reset`). + ResetNs, + /// What shaders wrote: finding the 64 KiB pieces that differ, how many + /// do, and putting them into title memory. + BackScanUs, + BackDiffer, + BackSyncUs, + /// Texture uploads recorded, and left out as unchanged. + TexUploads, + TexSkipped, + /// Held submissions a present ran although their waits were not met. + Forced, + /// Ranges named through unordered access views by shaders that cannot + /// store to buffers, not given to shaders as written, and their bytes. + GpuWritesLeftOut, + GpuWritesLeftOutBytes, + /// Waits for memory values looked at (`list::ValueWait::met`) and the + /// nanoseconds the looks took, on every thread. + WaitChecks, + WaitCheckNs, + /// Host lists made (`Host::new_list`: for the lists a queue holds and + /// for the parts of lists cut at waits) and the nanoseconds that took. + HostLists, + HostListNs, + /// Parts of held submissions that ran while the part behind them could + /// have run with them (its waits were met already). + PartsTogether, + /// Microseconds of the copies counted in `WholeBytes`. + WholeUs, + /// Submissions by how long the card was waited for (under 2 ms, 2-8, + /// 8-32, longer), and the microseconds waited in each class. + CardUnder2, + Card2To8, + Card8To32, + CardOver32, + CardUnder2Us, + Card2To8Us, + Card8To32Us, + CardOver32Us, + /// Submissions that hand nothing back to the title (no range shaders + /// write, no value written when done), and the microseconds the card + /// was waited for them. + NothingBack, + NothingBackUs, + /// Waits for every earlier shader write recorded into host lists: for + /// the title's barrier groups, for its barriers on buffers, and the + /// indirect commands bounded (each a dispatch of ours between two such + /// waits). + WaitsForGroups, + WaitsForBuffers, + IndirectBounded, } -const COUNTERS: usize = 22; +const COUNTERS: usize = 80; static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; pub(crate) fn add(c: C, n: u64) { @@ -59,6 +149,112 @@ pub(crate) fn mode() -> u8 { type Ranges = HashMap<(usize, usize), (u64, u64, u64, u32)>; static RANGES: Mutex> = Mutex::new(None); +/// Per range copied whole because its memory is not watched (start, +/// length): copies and microseconds. +static WHOLE: Mutex>> = Mutex::new(None); + +/// `len` bytes at `src`, memory that is not watched, were copied whole in +/// `us`. +pub(crate) fn whole(src: usize, len: usize, us: u64) { + add(C::WholeUs, us); + let mut map = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); + let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0)); + e.0 += 1; + e.1 += us; +} + +/// The longest wait for the card since the last line: microseconds, and +/// what ran (lists and pipelines). +static LONGEST: Mutex<(u64, String)> = Mutex::new((0, String::new())); + +/// The waits for the card since the last line by what ran (lists and +/// pipelines): how many, and their microseconds. +static WAITS_BY_WORK: Mutex>> = Mutex::new(None); + +/// With `VICTORY_GPU_TIMING`: the commands' time on the card since the last +/// line by what they ran (a pipeline, or the kind of command): how many, +/// their microseconds, and the longest one's. +static COMMANDS_BY_WORK: Mutex>> = Mutex::new(None); + +/// A command took `ms` on the card (timing run). `op` is its note: the +/// kind and size first, then the pipeline in brackets, then what it binds. +pub(crate) fn command_took(op: &str, ms: f64) { + let us = (ms * 1e3) as u64; + let mut by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let e = by.get_or_insert_with(HashMap::new).entry(command_key(op)).or_insert((0, 0, 0)); + e.0 += 1; + e.1 += us; + e.2 = e.2.max(us); +} + +/// What a command's note is summed under: its pipeline (`[compute ...]`, +/// `[mesh ..., pixel ...]`) with the command's first word, or without a +/// pipeline its first two words. +fn command_key(op: &str) -> String { + let head = op.split(" | ").next().unwrap_or(op); + let word = head.split(' ').next().unwrap_or(""); + match (head.find('['), head.find(']')) { + (Some(a), Some(b)) if a < b => format!("{word} {}", &head[a..=b]), + _ => head.split(' ').take(2).collect::>().join(" "), + } +} + +/// The card was waited for `us` for a submission; `what` names it if it is +/// the longest since the last line. +pub(crate) fn card_waited(us: u64, what: impl FnOnce() -> String) { + let (n, t) = match us { + 0..2_000 => (C::CardUnder2, C::CardUnder2Us), + 2_000..8_000 => (C::Card2To8, C::Card2To8Us), + 8_000..32_000 => (C::Card8To32, C::Card8To32Us), + _ => (C::CardOver32, C::CardOver32Us), + }; + add(n, 1); + add(t, us); + // Every submission is named (some forty a frame): the same lists run + // every frame, and the eight longest waits of a line were one list + // eight times. + let text = what(); + { + let mut by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let e = by.get_or_insert_with(HashMap::new).entry(text.clone()).or_insert((0, 0)); + e.0 += 1; + e.1 += us; + } + let mut longest = LONGEST.lock().unwrap_or_else(|e| e.into_inner()); + if us > longest.0 { + *longest = (us, text); + } +} + +/// Whether an experiment on barriers is on (`VICTORY_BARRIER_TEST`): bit 0 +/// for `groups` (the title's barrier groups record no wait for earlier +/// shader writes), bit 1 for `indirect` (the pass that bounds an indirect +/// command runs without its two such waits; its state changes stay), both +/// bits for `both`. For timing only: without the waits a shader may read +/// what another has not finished writing. +pub(crate) fn barrier_test() -> u8 { + static TEST: std::sync::OnceLock = std::sync::OnceLock::new(); + *TEST.get_or_init(|| match std::env::var("VICTORY_BARRIER_TEST").as_deref() { + Ok("groups") => 1, + Ok("indirect") => 2, + Ok("both") => 3, + _ => 0, + }) +} + +/// Per range compared after a submission (start, length): times, and the +/// bytes of it written back to the title. +static COMPARED: Mutex>> = Mutex::new(None); + +/// `len` bytes at `src` were compared after a submission and `written` of +/// them put back into title memory. +pub(crate) fn compared(src: usize, len: usize, written: usize) { + let mut map = COMPARED.lock().unwrap_or_else(|e| e.into_inner()); + let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0)); + e.0 += 1; + e.1 += written as u64; +} + /// A copy of `len` bytes from `src` (memory type `kind`) took `us`. pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) { let mut map = RANGES.lock().unwrap_or_else(|e| e.into_inner()); @@ -71,6 +267,763 @@ pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) { e.2 += us; } +/// Our own allocations alive now, by size of block (under 4 KiB, to 64 KiB, +/// to 1 MiB, larger): bytes, then blocks. "Our own" is the Rust code of +/// every crate in the process: in diagnostics builds [`Counting`] stands in +/// front of the system's heap. The memory map's "process heap segments" +/// hold the blocks under about half a megabyte of ours, of the graphics +/// runtime and of the driver alike (3.5 GB in run 60's gameplay, growing by +/// some 2 MB a frame, and nothing said whose): this says which part is +/// ours. Bigger blocks are allocations of their own in the map. +static OWN: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + +/// The class of [`OWN`] a block of `size` bytes counts in. +fn block_class(size: usize) -> usize { + match size { + 0..0x1000 => 0, + 0x1000..0x1_0000 => 1, + 0x1_0000..0x10_0000 => 2, + _ => 3, + } +} + +fn own(size: usize, made: bool) { + let class = block_class(size); + if made { + OWN[class].fetch_add(size as u64, Relaxed); + OWN[4 + class].fetch_add(1, Relaxed); + } else { + OWN[class].fetch_sub(size as u64, Relaxed); + OWN[4 + class].fetch_sub(1, Relaxed); + } +} + +/// Our own blocks of [`BIG`] bytes and more alive now: where each is (0: +/// none) and its bytes. The memory map lists the process's big allocations +/// by size without saying whose they are (run 65: one of 544 MB, one of +/// 401 MB, two of 174 MB, two of 115 MB); the sizes here say which of them +/// are ours. +static BIG_AT: [std::sync::atomic::AtomicUsize; 64] = [const { std::sync::atomic::AtomicUsize::new(0) }; 64]; +static BIG_BYTES: [AtomicU64; 64] = [const { AtomicU64::new(0) }; 64]; +const BIG: usize = 32 << 20; + +/// A block of [`BIG`] bytes or more was made at `at`, or released there. +fn big(at: *mut u8, size: usize, made: bool) { + if size < BIG { + return; + } + for (place, bytes) in BIG_AT.iter().zip(&BIG_BYTES) { + if made { + if place.compare_exchange(0, at as usize, Relaxed, Relaxed).is_ok() { + bytes.store(size as u64, Relaxed); + return; + } + } else if place.load(Relaxed) == at as usize { + bytes.store(0, Relaxed); + place.store(0, Relaxed); + return; + } + } +} + +/// The sizes of our own big blocks alive, largest first, in MB. +fn big_blocks() -> String { + let mut sizes: Vec = BIG_BYTES.iter().map(|b| b.load(Relaxed)).filter(|&b| b != 0).collect(); + sizes.sort_unstable_by(|a, b| b.cmp(a)); + let text: Vec = sizes.iter().map(|b| format!("{:.2}", *b as f64 / (1 << 20) as f64)).collect(); + if text.is_empty() { "none".into() } else { text.join(", ") } +} + +/// The system's allocator with every block counted in [`OWN`] (two atomic +/// additions per allocation and per release: diagnostics builds only). +struct Counting; + +// SAFETY: every call goes to the system's allocator unchanged; only +// counters are kept beside it. +unsafe impl std::alloc::GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 { + // SAFETY: the caller's contract, passed on. + let at = unsafe { std::alloc::System.alloc(layout) }; + if !at.is_null() { + own(layout.size(), true); + big(at, layout.size(), true); + } + at + } + + unsafe fn alloc_zeroed(&self, layout: std::alloc::Layout) -> *mut u8 { + // SAFETY: the caller's contract, passed on. + let at = unsafe { std::alloc::System.alloc_zeroed(layout) }; + if !at.is_null() { + own(layout.size(), true); + big(at, layout.size(), true); + } + at + } + + unsafe fn dealloc(&self, at: *mut u8, layout: std::alloc::Layout) { + own(layout.size(), false); + big(at, layout.size(), false); + // SAFETY: the caller's contract, passed on. + unsafe { std::alloc::System.dealloc(at, layout) }; + } + + unsafe fn realloc(&self, at: *mut u8, layout: std::alloc::Layout, size: usize) -> *mut u8 { + // SAFETY: the caller's contract, passed on. + let moved = unsafe { std::alloc::System.realloc(at, layout, size) }; + if !moved.is_null() { + own(layout.size(), false); + own(size, true); + big(at, layout.size(), false); + big(moved, size, true); + } + moved + } +} + +#[global_allocator] +static HEAP: Counting = Counting; + +#[cfg(test)] +mod command_tests { + /// Commands are summed by pipeline and first word; those without a + /// pipeline by their first two words. + #[test] + fn commands_are_named_by_their_pipeline() { + use super::command_key; + assert_eq!( + command_key("dispatch 182x1x1 [compute 24f989b98dcb03f0] | 24f989b98dcb03f0: u4=0xa6b080 [heap 341380: x]"), + "dispatch [compute 24f989b98dcb03f0]" + ); + assert_eq!( + command_key("indirect kind 10 max 1 at 0xd9358fce0 [mesh 0750cb2d975c7563, pixel 085d374c5a795549] | t"), + "indirect [mesh 0750cb2d975c7563, pixel 085d374c5a795549]" + ); + assert_eq!(command_key("texture upload 0x271b61c28b0 (2048x2048x1 f99 mips 10) sub 0"), "texture upload"); + assert_eq!(command_key("alias copy of 0x26f66aca780 into 0x26fbdc93890"), "alias copy"); + } +} + +#[cfg(test)] +mod own_tests { + use super::{OWN, block_class}; + use std::sync::atomic::Ordering::Relaxed; + + #[test] + fn blocks_count_in_their_size_class() { + assert_eq!(block_class(0), 0); + assert_eq!(block_class(4095), 0); + assert_eq!(block_class(4096), 1); + assert_eq!(block_class(65535), 1); + assert_eq!(block_class(65536), 2); + assert_eq!(block_class((1 << 20) - 1), 2); + assert_eq!(block_class(1 << 20), 3); + } + + /// A block of 32 MiB or more is listed by its size while it lives. + #[test] + fn big_blocks_are_listed_while_they_live() { + let size = (48usize << 20) + 4096; + let listed = |at: usize| { + super::BIG_AT + .iter() + .zip(&super::BIG_BYTES) + .any(|(place, bytes)| place.load(Relaxed) == at && bytes.load(Relaxed) == size as u64) + }; + let block = vec![0u8; size]; + let at = block.as_ptr() as usize; + assert!(listed(at)); + assert!(super::big_blocks().contains("48.00")); + drop(block); + assert!(!listed(at)); + } + + /// A big block shows in the counters while it lives (other tests + /// allocate small blocks meanwhile: only the big class is looked at, + /// and only for at least this block). + #[test] + fn a_block_is_counted_while_it_lives() { + let block = vec![1u8; 8 << 20]; + assert!(OWN[3].load(Relaxed) >= 8 << 20); + assert!(OWN[7].load(Relaxed) >= 1); + drop(block); + assert!(OWN[7].load(Relaxed) < u64::MAX / 2, "no count below zero"); + } +} + +/// The process's memory in bytes: in physical memory, and committed +/// (private bytes). +fn process_memory() -> (u64, u64) { + use windows_sys::Win32::System::ProcessStatus::{ + K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { + cb: size_of::() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + (c.WorkingSetSize as u64, c.PagefileUsage as u64) +} + +/// The PC's memory in bytes: physical memory free, and what is left to +/// commit. +fn system_memory() -> (u64, u64) { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = size_of::() as u32; + // SAFETY: a sized structure. + unsafe { GlobalMemoryStatusEx(&mut m) }; + (m.ullAvailPhys, m.ullAvailPageFile) +} + +/// Whether the address space is walked for the memory map line +/// ([`log_memory_map`]). On by default (this module is in diagnostics +/// builds only); `VICTORY_MEMORY_MAP=0` leaves the walk out. +fn memory_map() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_MEMORY_MAP").is_none_or(|v| v != "0")) +} + +/// Asks which of the pages in `asked` (address, answer) are in physical +/// memory and adds the bytes each stands for (kind, bytes) to its kind. +fn in_memory(asked: &mut Vec<[usize; 2]>, stands: &mut Vec<(usize, u64)>, present: &mut [u64; 10]) { + use windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: our own process; `asked` holds that many entries of two + // words each, as the call fills them in. + let ok = unsafe { + K32QueryWorkingSetEx(GetCurrentProcess(), asked.as_mut_ptr().cast(), (asked.len() * 16) as u32) + } != 0; + if ok { + for (a, &(kind, bytes)) in asked.iter().zip(stands.iter()) { + // Bit 0 of the answer: the page is in the process's memory. + if a[1] & 1 != 0 { + present[kind] += bytes; + } + } + } + asked.clear(); + stands.clear(); +} + +/// Logs what the process has committed by kind, from a walk of its address +/// space, and how much of each kind is in physical memory (one page in +/// sixteen is asked about). The kinds tell the title's own memory from +/// ours: the title's heaps and page views lie at console addresses (below +/// 1 TiB), everything the host allocates lies far above. Run 30, seen +/// from outside at 18.0 GB private: 4.6 GB the title's heaps, 2.6 GB in +/// 162 segments of the process heap, 2.7 GB in 707 allocations of 4 MiB +/// (windows of title memory), 0.46 GB the pipeline library's file; mapped +/// and so not private: 6.2 GB the title's page pool, 2.0 GB the driver's +/// shader cache file. +/// shortcut: the walk takes about 0.6 s on a thread of its own, and a +/// query of a region of gigabytes holds up other threads' memory calls +/// for its length (89 ms for the 6.2 GB pool), so it runs with every +/// sixth memory line only. +fn log_memory_map() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_FREE, MEM_IMAGE, MEM_MAPPED, MEMORY_BASIC_INFORMATION, PAGE_WRITECOMBINE, + VirtualQuery, + }; + const KINDS: [&str; 10] = [ + "the title's heaps (private, console addresses)", + "views of the title's pages (mapped, console addresses)", + "the title's page pool (mapped, 1 GB and more)", + "process heap segments (private, 15.8 MB each)", + "windows of title memory and other 4 MiB allocations", + "write-combined (buffers shared with the card)", + "other private allocations of 1 MB and more", + "other private allocations under 1 MB", + "files and other mappings at host addresses", + "programs and libraries", + ]; + /// Console addresses lie below this. + const HOST: usize = 1 << 40; + /// One page asked about stands for this much. + const STEP: usize = 64 << 10; + let started = std::time::Instant::now(); + // Allocation, start, bytes, committed, type, protection. + type Region = (usize, usize, usize, bool, u32, u32); + let mut regions: Vec = Vec::new(); + let mut at = 0usize; + loop { + // SAFETY: plain data filled in by the query. + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + if unsafe { VirtualQuery(at as *const _, &mut m, size_of_val(&m)) } == 0 { + break; + } + if m.State != MEM_FREE { + regions.push(( + m.AllocationBase as usize, + m.BaseAddress as usize, + m.RegionSize, + m.State == MEM_COMMIT, + m.Type, + m.Protect, + )); + } + let next = (m.BaseAddress as usize).saturating_add(m.RegionSize); + if next <= at { + break; + } + at = next; + } + // Each allocation's whole size, reserved parts included. + let mut whole: HashMap = HashMap::new(); + for r in ®ions { + *whole.entry(r.0).or_default() += r.2; + } + let kind = |r: &Region| -> usize { + let size = whole.get(&r.0).copied().unwrap_or(0); + let console = r.0 < HOST; + if r.4 == MEM_IMAGE { + 9 + } else if r.4 == MEM_MAPPED { + match (console, size >= 1 << 30) { + (false, _) => 8, + (true, true) => 2, + (true, false) => 1, + } + } else if console { + 0 + } else if size == 0xfd_0000 { + 3 + } else if size == 4 << 20 { + 4 + } else if r.5 & PAGE_WRITECOMBINE != 0 { + 5 + } else if size >= 1 << 20 { + 6 + } else { + 7 + } + }; + let mut committed = [0u64; 10]; + let mut present = [0u64; 10]; + let mut asked: Vec<[usize; 2]> = Vec::with_capacity(4096); + let mut stands: Vec<(usize, u64)> = Vec::with_capacity(4096); + for r in regions.iter().filter(|r| r.3) { + let k = kind(r); + committed[k] += r.2 as u64; + let mut offset = 0; + while offset < r.2 { + asked.push([r.1 + offset, 0]); + stands.push((k, STEP.min(r.2 - offset) as u64)); + if asked.len() == 4096 { + in_memory(&mut asked, &mut stands, &mut present); + } + offset += STEP; + } + } + if !asked.is_empty() { + in_memory(&mut asked, &mut stands, &mut present); + } + let text: Vec = (0..KINDS.len()) + .filter(|&k| committed[k] > 0) + .map(|k| format!("{} {} MB ({} MB in memory)", KINDS[k], committed[k] >> 20, present[k] >> 20)) + .collect(); + tracing::info!( + "memory map ({} regions, {} ms): {}", + regions.len(), + started.elapsed().as_millis(), + text.join("; ") + ); + // The private allocations the kinds above leave as "other" (and the + // write-combined ones), grouped by their size: the sizes name their + // owners (the pipeline library's file to the byte, a snapshot buffer + // of a title heap's size, the driver's blocks). Committed bytes by + // allocation first, then allocations by (kind, whole size). + let mut by_allocation: HashMap = HashMap::new(); + for r in regions.iter().filter(|r| r.3) { + let k = kind(r); + if k == 5 || k == 6 { + by_allocation.entry(r.0).or_insert((k, 0)).1 += r.2 as u64; + } + } + let mut groups: HashMap<(usize, usize), (u64, u64)> = HashMap::new(); + for (base, &(k, bytes)) in &by_allocation { + let group = groups.entry((k, whole.get(base).copied().unwrap_or(0))).or_default(); + group.0 += 1; + group.1 += bytes; + } + let mut groups: Vec<((usize, usize), (u64, u64))> = groups.into_iter().collect(); + groups.sort_by_key(|g| std::cmp::Reverse(g.1.1)); + let biggest: Vec = groups + .iter() + .take(20) + .map(|&((k, size), (n, bytes))| { + format!( + "{n} of {:.2} MB{}: {} MB", + size as f64 / (1 << 20) as f64, + if k == 5 { " write-combined" } else { "" }, + bytes >> 20 + ) + }) + .collect(); + tracing::info!( + "memory map, other private allocations by size, the {} biggest groups of {} (committed): {}", + biggest.len(), + groups.len(), + biggest.join("; ") + ); +} + +/// Logs where the memory is: the process and the PC, then what this crate +/// holds by kind (alive now), then the host buffers made since the start. +fn log_memory() { + use std::sync::atomic::Ordering::Relaxed; + let mb = |v: u64| v as f64 / (1 << 20) as f64; + let (working, private) = process_memory(); + let (free, left) = system_memory(); + let copies = crate::shadow::memory(); + let staged = crate::texture::memory(); + let textures = [0, 1].map(|i| crate::resource::HOST_TEXTURES[i].load(Relaxed)); + let made: Vec = crate::host::MADE.iter().map(|m| m.load(Relaxed)).collect(); + let windows = crate::shadow::windows(); + let stagings = crate::texture::let_go(); + let census = crate::resource::census(); + let kinds: Vec = crate::resource::KINDS.iter().map(|k| k.load(Relaxed)).collect(); + let card = crate::host::host() + .and_then(|h| h.video_memory()) + .unwrap_or_default(); + // What else holds memory: the map, on a thread of its own, with every + // sixth line; and what the shader table and the pipeline library keep. + static LINES: AtomicU64 = AtomicU64::new(0); + static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if memory_map() && LINES.fetch_add(1, Relaxed) % 6 == 5 && !WALKING.swap(true, Relaxed) { + let walk = std::thread::Builder::new().name("victory-memory-map".into()).spawn(|| { + log_memory_map(); + WALKING.store(false, Relaxed); + }); + if walk.is_err() { + WALKING.store(false, Relaxed); + } + } + let kept = crate::pipeline::kept(); + tracing::info!( + "memory kept beside the lines below: {} shader containers {:.0} MB, {} translations \ + {:.0} MB; the pipeline library's file {:.0} MB (its last save wrote {:.0} MB)", + kept[0], + mb(kept[1]), + kept[2], + mb(kept[3]), + mb(kept[4]), + mb(kept[5]), + ); + tracing::info!( + "memory of textures: {} title textures have no host copy yet ({:.0} MB of title memory); \ + host copies the host renders to or writes: {} alive {:.0} MB; host copies the title \ + fills: {} alive {:.0} MB ({} of them placed), {} let go {:.0} MB and {} made again \ + {:.0} MB since the start; {} host copies made in all; passes that made none for lack of \ + room: {}; the card: {:.0} MB in use of a budget of {:.0} MB, {:.0} MB of the PC's memory \ + shared with it in use", + census[2], + mb(census[3]), + census[0], + mb(census[1]), + census[4], + mb(census[5]), + census[6], + kinds[2], + mb(kinds[3]), + kinds[4], + mb(kinds[5]), + kinds[6], + crate::draw::HEAP_TEXTURES_FULL.load(Relaxed), + mb(card[1]), + mb(card[0]), + mb(card[3]), + ); + tracing::info!( + "memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \ + {:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \ + asked for in each", + windows[0], + mb(windows[1]), + stagings[0], + mb(stagings[1]), + mb(windows[2]), + ); + tracing::info!( + "memory: {:.0} MB private ({:.0} MB of it in memory; the PC has {:.0} MB free and {:.0} MB \ + left to commit); host copies of title memory: {} alive {:.0} MB, of them {} windows \ + outside buffers {:.0} MB; snapshot buffers kept: {} reserving {:.0} MB; staging of \ + textures: {} alive {:.0} MB, {} kept by their texture; host textures: {} alive {:.0} MB, \ + {} placed in title memory; made so far: {} upload buffers {:.0} MB, {} shared buffers \ + {:.0} MB, {} card buffers {:.0} MB", + mb(private), + mb(working), + mb(free), + mb(left), + copies[0], + mb(copies[1]), + copies[2], + mb(copies[3]), + copies[4], + mb(copies[5]), + staged[0], + mb(staged[1]), + staged[2], + textures[0], + mb(textures[1]), + crate::resource::placed_textures(), + made[0], + mb(made[1]), + made[2], + mb(made[3]), + made[4], + mb(made[5]), + ); + // What the line above leaves open: what is alive of the buffers "made + // so far", what the windows hold and what holds them, and what our own + // code has allocated. + let alive: Vec = crate::host::ALIVE.iter().map(|a| a.load(Relaxed)).collect(); + let window = crate::shadow::window_use(); + let views = crate::descriptor::views_kept(); + let own: Vec = OWN.iter().map(|o| o.load(Relaxed)).collect(); + tracing::info!( + "memory, what holds it: {} host lists alive; their scratch memory: {} chunks {:.0} MB, of them {} chunks {:.0} MB spare ({} taken from the spare ones so far); their other upload buffers: {} alive {:.0} MB; windows outside buffers (grid {} KiB): {:.0} MB of their pages ever copied, {} shown by descriptor slots {:.0} MB, {} held by lists or the pass over the heap {:.0} MB, {} asked for without a length {:.0} MB; buffer views of the heap whose slot showed another copy than the one brought up to date: {}; distinct views kept: {} ({} free) {:.0} MB; our own allocations: {:.0} MB in {} blocks (under 4 KiB {:.0} MB in {}, to 64 KiB {:.0} MB in {}, to 1 MiB {:.0} MB in {}, larger {:.0} MB in {})", + alive[0], + alive[1], + mb(alive[2]), + alive[3], + mb(alive[4]), + alive[5], + alive[6], + mb(alive[7]), + window[7] >> 10, + mb(window[0]), + window[1], + mb(window[2]), + window[3], + mb(window[4]), + window[5], + mb(window[6]), + crate::draw::HEAP_VIEWS_ELSEWHERE.load(Relaxed), + views[0], + views[1], + mb(views[2]), + mb(own[..4].iter().sum()), + own[4..].iter().sum::(), + mb(own[0]), + own[4], + mb(own[1]), + own[5], + mb(own[2]), + own[6], + mb(own[3]), + own[7], + ); + // Round 2: what the view table still holds and what goes around it, + // what host lists cost, the card's share that is the layer's own or + // the title's no more, and which big blocks are ours. + let lists: Vec = crate::host::LISTS.iter().map(|l| l.load(Relaxed)).collect(); + tracing::info!( + "memory, more: views named whole in their records since the start: {} constant buffer \ + views, {} views of placed memory; of the view table's entries {} are constant buffer \ + views and {} views of placed memory; shapes of placed views kept: {}; host lists: {} \ + made by the host, {} preludes made for them, private bytes grew {:.0} MB while \ + lists were made; twins of depth textures: {:.0} MB; host copies of \ + placed textures whose title memory is not mapped any more (estimate): {:.0} MB, of \ + them still shown by a descriptor slot {:.0} MB; the pipeline library's mapped file \ + let go from memory so far: {:.0} MB; our own blocks of 32 MB and more, in MB: {}", + views[6], + views[7], + views[3], + views[4], + views[5], + lists[0], + lists[1], + lists[2] as i64 as f64 / (1 << 20) as f64, + mb(census[7]), + mb(census[8]), + mb(census[9]), + mb(kept[6]), + big_blocks(), + ); + // Round 3: whether windows hold the same memory more than once (they + // can, once they are cut finer than 4 MiB), and how many host lists + // the title made and never used. + tracing::info!( + "memory, windows: the {:.0} MB of windows lie over {:.0} MB of title memory (the rest is \ + memory that is in more than one window, and is copied once for each); host lists never \ + reset since they were made: {}", + mb(copies[3]), + mb(crate::shadow::window_cover()), + lists[3], + ); +} + +/// Microseconds since the first call. +fn now_us() -> u64 { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 +} + +/// When the last frame was presented and when the last submission returned +/// ([`now_us`]), and whether a list call and a submission followed that +/// present yet. +static PRESENTED_AT: AtomicU64 = AtomicU64::new(0); +static SUBMITTED_AT: AtomicU64 = AtomicU64::new(0); +static RECORDED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); +static SUBMITTED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + +/// What a thread that submits did between its submissions and in them +/// (microseconds; list calls in nanoseconds). +#[derive(Default, Clone, Copy)] +struct Submitter { + submissions: u64, + /// From a submission's return to the next one's call: wall time, of it + /// the thread running (user, kernel), and inside our list calls. + between: u64, + between_user: u64, + between_kernel: u64, + between_ours: u64, + /// Waiting for the submission lock; running inside submissions. + lock: u64, + inside_user: u64, + inside_kernel: u64, +} + +/// By thread: the submitting threads, and list-call time (nanoseconds, +/// calls) of every recording thread. +static SUBMITTERS: Mutex> = Mutex::new(Vec::new()); +static RECORDERS: Mutex> = Mutex::new(Vec::new()); + +thread_local! { + /// This thread's last submission: when it returned ([`now_us`]) and the + /// thread's processor time then (user, kernel). + static LEFT: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// The thread's processor time when its running submission was called. + static ENTERED: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; + /// List-call nanoseconds of this thread since its last submission. + static OURS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// List-call time not yet added to `RECORDERS` (nanoseconds, calls). + static UNSENT: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; +} + +fn thread_id() -> u32 { + // SAFETY: a plain query. + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() } +} + +fn micros(t: windows_sys::Win32::Foundation::FILETIME) -> u64 { + (u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime)) / 10 +} + +/// This thread's processor time so far (user, kernel), in microseconds. +fn thread_times() -> (u64, u64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; + let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own thread and four valid out pointers. + unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) }; + (micros(user), micros(kernel)) +} + +/// The process's processor time so far (user, kernel), in microseconds. +fn process_times() -> (u64, u64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; + let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own process and four valid out pointers. + unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) }; + (micros(user), micros(kernel)) +} + +fn submitter(all: &mut Vec<(u32, Submitter)>, id: u32) -> &mut Submitter { + let at = match all.iter().position(|s| s.0 == id) { + Some(at) => at, + None => { + all.push((id, Submitter::default())); + all.len() - 1 + } + }; + &mut all[at].1 +} + +/// A list call on this thread that began at `started` has returned. +pub(crate) fn recorded(started: std::time::Instant) { + let ns = started.elapsed().as_nanos() as u64; + add(C::RecordCalls, 1); + add(C::RecordNs, ns); + if !RECORDED_SINCE.load(Relaxed) && !RECORDED_SINCE.swap(true, Relaxed) { + let began = now_us().saturating_sub(ns / 1000); + add(C::UntilRecordUs, began.saturating_sub(PRESENTED_AT.load(Relaxed))); + } + OURS.with(|o| o.set(o.get() + ns)); + let (unsent, calls) = UNSENT.with(|u| u.get()); + let (unsent, calls) = (unsent + ns, calls + 1); + // By thread, a couple of milliseconds at a time. + if unsent < 2_000_000 { + UNSENT.with(|u| u.set((unsent, calls))); + return; + } + UNSENT.with(|u| u.set((0, 0))); + let id = thread_id(); + let mut all = RECORDERS.lock().unwrap_or_else(|e| e.into_inner()); + match all.iter_mut().find(|r| r.0 == id) { + Some(r) => (r.1, r.2) = (r.1 + unsent, r.2 + calls), + None => all.push((id, unsent, calls)), + } +} + +/// A submission is called on this thread (before it waits for the +/// submission lock). +pub(crate) fn submission_begins() { + let now = now_us(); + if !SUBMITTED_SINCE.load(Relaxed) && !SUBMITTED_SINCE.swap(true, Relaxed) { + add(C::UntilSubmitUs, now.saturating_sub(PRESENTED_AT.load(Relaxed))); + } + let (user, kernel) = thread_times(); + ENTERED.with(|e| e.set((user, kernel))); + let ours = OURS.with(|o| o.replace(0)); + if let Some((left, u, k)) = LEFT.with(|l| l.get()) { + let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner()); + let s = submitter(&mut all, thread_id()); + s.between += now.saturating_sub(left); + s.between_user += user.saturating_sub(u); + s.between_kernel += kernel.saturating_sub(k); + s.between_ours += ours; + } +} + +/// The submission returns; it waited `lock` microseconds for the +/// submission lock. +pub(crate) fn submission_ends(lock: u64) { + let now = now_us(); + SUBMITTED_AT.store(now, Relaxed); + let (user, kernel) = thread_times(); + let (u, k) = ENTERED.with(|e| e.get()); + LEFT.with(|l| l.set(Some((now, user, kernel)))); + OURS.with(|o| o.set(0)); + let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner()); + let s = submitter(&mut all, thread_id()); + s.submissions += 1; + s.lock += lock; + s.inside_user += user.saturating_sub(u); + s.inside_kernel += kernel.saturating_sub(k); +} + +/// The title calls its present (before our own copy to the window runs). +pub(crate) fn present_begins() { + add(C::TailUs, now_us().saturating_sub(SUBMITTED_AT.load(Relaxed))); +} + +/// A frame was presented. +pub(crate) fn presented() { + add(C::Frames, 1); + PRESENTED_AT.store(now_us(), Relaxed); + RECORDED_SINCE.store(false, Relaxed); + SUBMITTED_SINCE.store(false, Relaxed); +} + fn page_faults() -> u64 { use windows_sys::Win32::System::ProcessStatus::{ K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, @@ -85,9 +1038,14 @@ fn page_faults() -> u64 { u64::from(c.PageFaultCount) } -/// Logs the counters per frame over `frames` frames, and the ranges that -/// took most bytes. +/// Logs the counters per frame, and the ranges that took most bytes. The +/// counters run from line to line, so they are divided by the frames +/// presented since the last line, not by `frames` (the frames of the last +/// second or more: a 4 s frame after an unlogged 4 s frame showed two +/// frames' counts as one's). pub(crate) fn log(frames: f64) { + let counted = COUNT[C::Frames as usize].swap(0, Relaxed); + let frames = if counted > 0 { counted as f64 } else { frames }; static FAULTS: AtomicU64 = AtomicU64::new(0); let faults = page_faults(); let faults = faults - FAULTS.swap(faults, Relaxed).min(faults); @@ -127,6 +1085,204 @@ pub(crate) fn log(frames: f64) { mb(c[C::TexHashed as usize]), mb(c[C::TexChanged as usize]), ); + tracing::info!( + "recording per frame ({frames:.0} frames): {:.0} list calls {:.1} ms (all recording \ + threads); {:.1} ms waiting for pipelines; dynamic slots: {:.0} tables asked, {:.0} \ + refused, {:.1} ms searching; notes {:.1} ms; shader-written ranges: {:.0} steps in \ + {:.1} submissions, snapshots {:.1} ms, {:.1} MB compared back; sparse reads {:.1} ms; \ + guards {:.1} ms; {:.1} MB copied whole (memory not watched); {:.1} frame waits \ + sleeping {:.1} ms (all threads); ranges of shaders that cannot store to buffers: \ + {:.0} steps {:.1} MB left out", + c[C::RecordCalls as usize], + c[C::RecordNs as usize] / 1e6, + ms(c[C::PipelineWaitUs as usize]), + c[C::DynamicAsked as usize], + c[C::DynamicRefused as usize], + c[C::DynamicNs as usize] / 1e6, + c[C::NoteNs as usize] / 1e6, + c[C::GpuWrites as usize], + c[C::BackSubmissions as usize], + ms(c[C::SnapshotUs as usize]), + mb(c[C::BackCompared as usize]), + ms(c[C::SparseUs as usize]), + ms(c[C::GuardUs as usize]), + mb(c[C::WholeBytes as usize]), + c[C::PaceWaits as usize], + ms(c[C::PaceUs as usize]), + c[C::GpuWritesLeftOut as usize], + mb(c[C::GpuWritesLeftOutBytes as usize]), + ); + // 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. + static CPU: Mutex<(u64, u64)> = Mutex::new((0, 0)); + let (user, kernel) = process_times(); + let (user, kernel) = { + let mut last = CPU.lock().unwrap_or_else(|e| e.into_inner()); + let spent = (user.saturating_sub(last.0), kernel.saturating_sub(last.1)); + *last = (user, kernel); + (spent.0 as f64 / 1e3 / frames, spent.1 as f64 / 1e3 / frames) + }; + tracing::info!( + "frame account per frame: after a present {:.1} ms until the first list call and {:.1} ms \ + until the first submission; {:.1} ms from the last submission to the present call; \ + lists reset in {:.1} ms; the process ran {user:.0} ms user + {kernel:.0} ms kernel on \ + all threads; what shaders wrote: {:.1} ms finding {:.0} pieces that differ, {:.1} ms \ + putting them back; texture uploads: {:.0} recorded, {:.0} left out; {:.1} held \ + submissions run at the present with their waits not met; waits for memory values: \ + {:.0} looks {:.1} ms; {:.0} host lists made {:.1} ms; {:.0} parts of held submissions \ + ran alone that the next part could have run with", + ms(c[C::UntilRecordUs as usize]), + ms(c[C::UntilSubmitUs as usize]), + ms(c[C::TailUs as usize]), + c[C::ResetNs as usize] / 1e6, + ms(c[C::BackScanUs as usize]), + c[C::BackDiffer as usize], + ms(c[C::BackSyncUs as usize]), + c[C::TexUploads as usize], + c[C::TexSkipped as usize], + c[C::Forced as usize], + c[C::WaitChecks as usize], + c[C::WaitCheckNs as usize] / 1e6, + c[C::HostLists as usize], + c[C::HostListNs as usize] / 1e6, + c[C::PartsTogether as usize], + ); + // What is copied whole, largest first: memory nobody tells us about. + let whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut whole: Vec<_> = whole.into_iter().flatten().collect(); + whole.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); + tracing::info!( + " copied whole (memory not watched): {:.1} ms per frame in {} ranges; the largest follow", + ms(c[C::WholeUs as usize]), + whole.len() + ); + for ((src, len), (n, us)) in whole.into_iter().take(6) { + tracing::info!( + " copied whole from {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame", + n as f64 / frames, + (len as u64 * n) as f64 / 1e6 / frames, + us as f64 / 1e3 / frames + ); + } + // The waiting for the card: many short waits or a few long ones, how + // much of it is for submissions the title gets nothing back from, and + // the longest one. + let longest = std::mem::take(&mut *LONGEST.lock().unwrap_or_else(|e| e.into_inner())); + tracing::info!( + " waiting for the card per frame: {:.1} submissions under 2 ms ({:.1} ms), {:.1} of 2-8 ms \ + ({:.1} ms), {:.1} of 8-32 ms ({:.1} ms), {:.1} longer ({:.1} ms); {:.1} submissions hand \ + nothing back to the title ({:.1} ms of the waiting); the longest since the last line: \ + {:.1} ms, {}", + c[C::CardUnder2 as usize], + ms(c[C::CardUnder2Us as usize]), + c[C::Card2To8 as usize], + ms(c[C::Card2To8Us as usize]), + c[C::Card8To32 as usize], + ms(c[C::Card8To32Us as usize]), + c[C::CardOver32 as usize], + ms(c[C::CardOver32Us as usize]), + c[C::NothingBack as usize], + ms(c[C::NothingBackUs as usize]), + longest.0 as f64 / 1e3, + longest.1 + ); + let by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut by: Vec<_> = by.into_iter().flatten().collect(); + by.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); + for (what, (n, us)) in by.into_iter().take(12) { + tracing::info!( + " the card's time by what ran: {:.1} ms a frame in {:.1} submissions a frame: {}", + us as f64 / 1e3 / frames, + n as f64 / frames, + what.chars().take(700).collect::() + ); + } + let by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut by: Vec<_> = by.into_iter().flatten().collect(); + by.sort_by_key(|&(_, (_, us, _))| std::cmp::Reverse(us)); + // All of them together, and by their first word: the forty lines below + // are the heaviest only (100 of 226 ms waited in run 102), and what the + // commands do not account for is the layer's own lists (the card + // copies' passes, preludes) and the waits themselves. + if !by.is_empty() { + let mut kinds: Vec<(String, u64, u64)> = Vec::new(); + for (what, (n, us, _)) in &by { + let word = what.split(' ').next().unwrap_or("").to_owned(); + match kinds.iter_mut().find(|k| k.0 == word) { + Some(k) => (k.1, k.2) = (k.1 + n, k.2 + us), + None => kinds.push((word, *n, *us)), + } + } + kinds.sort_by_key(|k| std::cmp::Reverse(k.2)); + let all: u64 = kinds.iter().map(|k| k.2).sum(); + let text: Vec = + kinds.iter().map(|(word, n, us)| format!("{word} {:.1} ms in {:.0}", *us as f64 / 1e3 / frames, *n as f64 / frames)).collect(); + tracing::info!( + " the card's time by command (timing run), all {} kinds together: {:.1} ms a frame; by first word: {}", + by.len(), + all as f64 / 1e3 / frames, + text.join(", ") + ); + } + for (what, (n, us, longest)) in by.into_iter().take(40) { + tracing::info!( + " the card's time by command (timing run): {:.2} ms a frame in {:.1} commands a frame, the longest {:.2} ms: {what}", + us as f64 / 1e3 / frames, + n as f64 / frames, + longest as f64 / 1e3 + ); + } + tracing::info!( + " waits for every earlier shader write, per frame: {:.0} for the title's barrier groups, {:.0} \ + for its barriers on buffers; {:.0} indirect commands bounded (a dispatch of ours between two \ + such waits each); barrier experiment {}", + c[C::WaitsForGroups as usize], + c[C::WaitsForBuffers as usize], + c[C::IndirectBounded as usize], + barrier_test() + ); + // What is compared after submissions, largest first, and how much of + // it shaders had written. + let compared = COMPARED.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut compared: Vec<_> = compared.into_iter().flatten().collect(); + compared.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); + tracing::info!(" compared after submissions: {} ranges; the largest follow", compared.len()); + for ((src, len), (n, written)) in compared.into_iter().take(8) { + tracing::info!( + " compared {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.3} MB/frame of it written back", + n as f64 / frames, + (len as u64 * n) as f64 / 1e6 / frames, + written as f64 / 1e6 / frames + ); + } + let mut submitters = std::mem::take(&mut *SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner())); + submitters.sort_by_key(|s| std::cmp::Reverse(s.1.submissions)); + for (id, s) in submitters.into_iter().take(4) { + let per = |v: u64| v as f64 / 1e3 / frames; + tracing::info!( + " thread {id} submitted {:.1}x/frame: between its submissions {:.1} ms (running \ + {:.1} ms user + {:.1} ms kernel; {:.1} ms in list calls), in them running {:.1} ms \ + user + {:.1} ms kernel, {:.1} ms waiting for the submission lock", + s.submissions as f64 / frames, + per(s.between), + per(s.between_user), + per(s.between_kernel), + s.between_ours as f64 / 1e6 / frames, + per(s.inside_user), + per(s.inside_kernel), + per(s.lock), + ); + } + let mut recorders = std::mem::take(&mut *RECORDERS.lock().unwrap_or_else(|e| e.into_inner())); + recorders.sort_by_key(|r| std::cmp::Reverse(r.1)); + let busiest: Vec = recorders + .iter() + .take(6) + .map(|r| format!("thread {} {:.0} ms in {:.0} calls", r.0, r.1 as f64 / 1e6 / frames, r.2 as f64 / frames)) + .collect(); + tracing::info!(" list calls by thread: {} threads; {}", recorders.len(), busiest.join(", ")); + log_memory(); let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut ranges: Vec<_> = ranges.into_iter().flatten().collect(); ranges.sort_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes)); diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 20b33fb..ab2875a 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -99,6 +99,13 @@ impl Heap { .as_ref() } + /// The handle of descriptor `index` of this heap. + #[cfg(windows)] + pub(crate) fn handle(&self, index: u32) -> Option { + let step = u64::from(increment(self.desc.kind)?); + (index < self.desc.count).then(|| self.start + u64::from(index) * step) + } + /// The descriptor index of `handle` in this heap, if it lies in it. pub(crate) fn index(&self, handle: u64) -> Option { let step = u64::from(increment(self.desc.kind)?); @@ -231,7 +238,8 @@ impl RtvRecord { 0, ] }; - words[0] = crate::resource::pc_format(words[0]); + // A target or depth view: of a target, in its stand-in format. + words[0] = crate::resource::target_format(crate::resource::pc_format(words[0])); // SAFETY: both host view descriptions are 24 bytes in this layout. Some(unsafe { (&raw const words).cast::().read_unaligned() }) } @@ -318,9 +326,21 @@ impl View { /// generation, so descriptors (and host slots made from them) naming the /// old one go stale instead of naming whatever is made at the same address /// next. -/// shortcut: views without a resource object (constant buffers, memory -/// views, samplers) are kept for the run; they are bounded by the title's -/// memory and sampler states. +/// +/// Views without a resource object have nothing that releases them, and a +/// title copies descriptors as bytes, so nothing says when the last +/// descriptor naming an entry is gone: such entries were kept for the run. +/// Grand Theft Auto VI writes some 14,000 constant buffer views a frame, +/// each at the address its constants have that frame: 2,450,139 entries +/// after four minutes of play, 1,047 MB with the index, and 11,000 more +/// every second (run 65). So the two kinds that carry an address are not +/// entries any more: their records name them whole ([`constant_words`], +/// [`placed_words`]), and the table holds only what is bounded: views of +/// resource objects (freed with the resource), samplers (as many as there +/// are sampler states), and the shapes of placed views (their descriptions +/// without the address: as many as the title has kinds of textures and +/// buffers, however often it moves them). +/// `VICTORY_VIEW_INLINE=0`: every view is an entry, as before. struct Views { /// Each entry's view and generation. list: Vec<(View, u32)>, @@ -328,6 +348,9 @@ struct Views { /// Entries naming each resource. by_resource: std::collections::BTreeMap>, free: Vec, + /// The shapes of views of placed memory, and where each is. + shapes: Vec, + shape_index: std::collections::BTreeMap, } static VIEWS: std::sync::Mutex = std::sync::Mutex::new(Views { @@ -335,9 +358,220 @@ static VIEWS: std::sync::Mutex = std::sync::Mutex::new(Views { index: std::collections::BTreeMap::new(), by_resource: std::collections::BTreeMap::new(), free: Vec::new(), + shapes: Vec::new(), + shape_index: std::collections::BTreeMap::new(), }); const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE"); +/// A record is the tag and two words, `i` and `generation` (the host keeps +/// them as one 64-bit key per slot). The top two bits of `generation` say +/// what the other 62 bits are: 0, entry `i` of the table at that +/// generation; [`CONSTANT`], a constant buffer view, whole; [`PLACED`], a +/// view of placed memory: its address and the number of its shape. +const KIND_SHIFT: u32 = 30; +/// Table generations stay below the kind bits (and above 0). +const GENERATIONS: u32 = (1 << KIND_SHIFT) - 1; +const CONSTANT: u32 = 1; +const PLACED: u32 = 2; +/// Bits of a constant buffer view's address in its record: any address a +/// program can have. The 15 bits above them are its size. +const CONSTANT_ADDRESS_BITS: u32 = 47; +/// Bits of a placed view's address in its record: placed memory is title +/// memory, which lies below 1 TiB. The 22 bits above them number its shape. +const PLACED_ADDRESS_BITS: u32 = 40; +const SHAPES: usize = 1 << (62 - PLACED_ADDRESS_BITS); + +/// A view of placed memory without its address: whether it is unordered +/// access, the resource description, and the view's words but the two that +/// hold the address (10 and 11). +type Shape = (bool, [u32; 14], [u32; 14]); + +/// Whether constant buffer views and views of placed memory are named whole +/// in their records ([`Views`]). On by default; `VICTORY_VIEW_INLINE=0` +/// makes every view a table entry, as before. +fn inline() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_INLINE").is_none_or(|v| v != "0")) +} + +/// Views named whole in their records since the start: constant buffer +/// views, views of placed memory (for the memory line). +static NAMED_WHOLE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The two record words of the 62 bits `payload` of kind `kind`. +fn kind_words(kind: u32, payload: u64) -> [u32; 2] { + [payload as u32, kind << KIND_SHIFT | (payload >> 32) as u32] +} + +/// The 62 bits two record words carry beside their kind. +fn payload(i: u32, generation: u32) -> u64 { + u64::from(generation & GENERATIONS) << 32 | u64::from(i) +} + +/// The record words that name the constant buffer view of `size` bytes at +/// `address` whole; `None` if they cannot: an address past 47 bits, or a +/// size of 16 KiB or more that is no multiple of 256 or reaches 4 MiB (the +/// size has 15 bits: bytes below 16 KiB, else units of 256 bytes). Such a +/// view is a table entry. +fn constant_words(address: u64, size: u32) -> Option<[u32; 2]> { + if address >> CONSTANT_ADDRESS_BITS != 0 { + return None; + } + let code = if size < 1 << 14 { + u64::from(size) + } else if size.is_multiple_of(256) && size >> 8 < 1 << 14 { + 1 << 14 | u64::from(size >> 8) + } else { + return None; + }; + Some(kind_words(CONSTANT, code << CONSTANT_ADDRESS_BITS | address)) +} + +/// The constant buffer view [`constant_words`] named. +fn constant_of(i: u32, generation: u32) -> View { + let payload = payload(i, generation); + let code = (payload >> CONSTANT_ADDRESS_BITS) as u32; + let size = if code >> 14 == 0 { code } else { (code & 0x3fff) << 8 }; + View::Constant(payload & ((1 << CONSTANT_ADDRESS_BITS) - 1), size) +} + +/// A placed view's shape and its address. +fn shape_of(unordered: bool, resource: &[u32; 14], desc: &[u32; 16]) -> (Shape, u64) { + let mut rest = [0u32; 14]; + rest[..10].copy_from_slice(&desc[..10]); + rest[10..].copy_from_slice(&desc[12..]); + ( + (unordered, *resource, rest), + u64::from(desc[10]) | u64::from(desc[11]) << 32, + ) +} + +/// The record words that name the view of placed memory at `address` with +/// shape number `shape`. +fn placed_words(shape: u32, address: u64) -> [u32; 2] { + kind_words(PLACED, u64::from(shape) << PLACED_ADDRESS_BITS | address) +} + +impl Views { + /// The number of `shape`, a new one if it is not there yet; `None` when + /// the shapes are full (the view is then a table entry). + fn shape(&mut self, shape: Shape) -> Option { + if let Some(&at) = self.shape_index.get(&shape) { + return Some(at); + } + if self.shapes.len() >= SHAPES { + return None; + } + let at = self.shapes.len() as u32; + self.shapes.push(shape); + self.shape_index.insert(shape, at); + Some(at) + } + + /// The view of placed memory [`placed_words`] named. + fn placed_of(&self, i: u32, generation: u32) -> Option { + let payload = payload(i, generation); + let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1); + let &(unordered, resource, rest) = self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?; + let mut desc = [0u32; 16]; + desc[..10].copy_from_slice(&rest[..10]); + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + desc[12..].copy_from_slice(&rest[10..]); + Some(View::Placed(unordered, resource, desc)) + } + + /// The record words of `view` as a table entry: its entry (a new or a + /// freed one if the view is not there yet) and that entry's generation. + fn entry(&mut self, view: View) -> [u32; 2] { + let i = match self.index.get(&view) { + Some(&i) => i, + None => { + let i = match self.free.pop() { + Some(i) => { + self.list[i as usize].0 = view.clone(); + i + } + None => { + self.list.push((view.clone(), 1)); + self.list.len() as u32 - 1 + } + }; + for r in view.resources().into_iter().filter(|&r| r != 0) { + self.by_resource.entry(r).or_default().push(i); + } + self.index.insert(view, i); + i + } + }; + [i, self.list[i as usize].1] + } +} + +/// The two words that name `view` in a record: the view itself where its +/// kind allows ([`Views`]), else its table entry. +fn words_for(view: View) -> [u32; 2] { + use std::sync::atomic::Ordering::Relaxed; + if inline() { + match &view { + View::Constant(address, size) => { + if let Some(words) = constant_words(*address, *size) { + NAMED_WHOLE[0].fetch_add(1, Relaxed); + return words; + } + } + View::Placed(unordered, resource, desc) => { + let (shape, address) = shape_of(*unordered, resource, desc); + if address >> PLACED_ADDRESS_BITS == 0 { + let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(shape) = views.shape(shape) { + NAMED_WHOLE[1].fetch_add(1, Relaxed); + return placed_words(shape, address); + } + } + } + _ => {} + } + } + VIEWS.lock().unwrap_or_else(|e| e.into_inner()).entry(view) +} + +/// For the memory line: the distinct views kept ([`Views`]), those of them +/// free for reuse, and the bytes the table and its index hold for them (an +/// estimate: an entry of the table, and one of the index with its share of +/// a tree node; the shapes likewise); then the entries that are constant +/// buffer views and views of placed memory (those that did not fit a +/// record, or all of them with `VICTORY_VIEW_INLINE=0`), the shapes of +/// placed views kept, and the views named whole in their records since the +/// start: constant buffer views, views of placed memory. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn views_kept() -> [u64; 8] { + use std::sync::atomic::Ordering::Relaxed; + let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let each = size_of::<(View, u32)>() as u64; + let shape = size_of::() as u64; + let (mut constants, mut placed) = (0, 0); + for (view, _) in &views.list { + match view { + View::Constant(..) => constants += 1, + View::Placed(..) => placed += 1, + _ => {} + } + } + [ + views.list.len() as u64, + views.free.len() as u64, + views.list.capacity() as u64 * each + + views.index.len() as u64 * each * 3 / 2 + + views.shapes.capacity() as u64 * shape + + views.shape_index.len() as u64 * shape * 3 / 2, + constants, + placed, + views.shapes.len() as u64, + NAMED_WHOLE[0].load(Relaxed), + NAMED_WHOLE[1].load(Relaxed), + ] +} + impl View { /// The resource objects the view names. fn resources(&self) -> [usize; 2] { @@ -347,43 +581,122 @@ impl View { _ => [0, 0], } } + + /// The texture object the view is of, if that texture has no host copy + /// yet (`crate::resource::host_waits`): a slot written with such a + /// view is left null until the texture is first used. + #[cfg(windows)] + fn waiting_texture(&self) -> Option { + match *self { + View::Shader(r, _) | View::Unordered(r, _, _) + if crate::resource::host_waits(r as This) => + { + Some(r) + } + _ => None, + } + } +} + +/// Title slots (their handles) written with a view of a texture object +/// that had no host copy then, by texture. A title texture gets its host +/// copy on first use (`resource.rs` `Hosted`), and Grand Theft Auto VI +/// writes each texture's views into its view heap when it creates the +/// texture: making those host slots would make every host copy at once. +/// They are made when the texture is: translated shaders index the heap +/// directly, so a slot is not always made again by the draw that reads it. +#[cfg(windows)] +static WAITING: std::sync::Mutex>> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// Textures given their host copy since [`make_waiting`] last ran. +#[cfg(windows)] +static MADE_LATE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Title texture `resource` was given its host copy (called under that +/// texture's own lock: nothing else is locked here). +#[cfg(windows)] +pub(crate) fn texture_made(resource: usize) { + MADE_LATE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(resource); +} + +/// The slot at `handle` was written with a view of texture `resource`, +/// which has no host copy: it waits for one. +#[cfg(windows)] +fn wait_for(resource: usize, handle: u64) { + /// A texture with more slots waiting than this is in use for all we + /// know (its views are being copied about): its host copy is made. + const MOST: usize = 64; + let many = { + let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()); + let slots = waiting.entry(resource).or_default(); + if !slots.contains(&handle) { + slots.push(handle); + } + slots.len() > MOST + }; + if many { + // Makes it, and notes it made. + let _ = crate::resource::host_copy(resource as This); + } else if !crate::resource::host_waits(resource as This) { + // Made by another thread since the slot was looked at: that making + // may have been taken by `make_waiting` before this slot was noted. + texture_made(resource); + } +} + +/// Makes the host slots that waited for a texture's host copy, for the +/// textures made since the last call. Called before a submission runs, by +/// the thread that submits: a slot is read when a list runs. +#[cfg(windows)] +pub(crate) fn make_waiting() { + let made = std::mem::take(&mut *MADE_LATE.lock().unwrap_or_else(|e| e.into_inner())); + for resource in made { + let handles = WAITING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&resource); + for handle in handles.into_iter().flatten() { + // Only if the slot still holds a view of that texture: the + // title may have written it since (and a view of another + // texture without a host copy must go on waiting). + // (Looked up first: the handle is read only while its heap is + // there.) + let Some((heap, index)) = shader_slot(handle) else { + continue; + }; + let same = match view(handle) { + Some(View::Shader(r, _) | View::Unordered(r, _, _)) => r == resource, + _ => false, + }; + if same && let Some(Some(host)) = heap.host.get() { + host.mirror(index, handle, true); + } + } + } } fn record(handle: u64, view: View) { if handle == 0 { return; } - let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); - let i = match views.index.get(&view) { - Some(&i) => i, - None => { - let i = match views.free.pop() { - Some(i) => { - views.list[i as usize].0 = view.clone(); - i - } - None => { - views.list.push((view.clone(), 1)); - views.list.len() as u32 - 1 - } - }; - for r in view.resources().into_iter().filter(|&r| r != 0) { - views.by_resource.entry(r).or_default().push(i); - } - views.index.insert(view, i); - i - } - }; - let generation = views.list[i as usize].1; + let [i, generation] = words_for(view); // SAFETY: the handle is a descriptor slot, at least 16 bytes. unsafe { (handle as *mut [u32; 3]).write_unaligned([VIEW_TAG, i, generation]) }; - drop(views); #[cfg(windows)] mirror(handle); } /// The title released `resource`: the views naming it go stale. pub(crate) fn forget(resource: usize) { + #[cfg(windows)] + WAITING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&resource); let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); let Some(entries) = views.by_resource.remove(&resource) else { return; @@ -396,19 +709,27 @@ pub(crate) fn forget(resource: usize) { continue; } views.index.remove(&view); - views.list[i as usize].1 = generation.wrapping_add(1).max(1); + // (Below the bits that say a record is no table entry.) + views.list[i as usize].1 = ((generation + 1) & GENERATIONS).max(1); // The view's other resource (a counter) keeps a stale entry, which // `forget` of that resource skips. views.free.push(i); } } -/// The view of entry `i` if `generation` is still its own. -#[cfg(windows)] +/// The view the record words `i` and `generation` name: the one they hold +/// whole, or the view of entry `i` if `generation` is still its own. fn view_at(i: u32, generation: u32) -> Option { - let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); - let (view, current) = views.list.get(i as usize)?; - (*current == generation).then(|| view.clone()) + match generation >> KIND_SHIFT { + 0 => { + let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let (view, current) = views.list.get(i as usize)?; + (*current == generation).then(|| view.clone()) + } + CONSTANT => Some(constant_of(i, generation)), + PLACED => VIEWS.lock().unwrap_or_else(|e| e.into_inner()).placed_of(i, generation), + _ => None, + } } /// The view recorded at `handle`, if one is (and its resource is alive). @@ -418,9 +739,10 @@ pub(crate) fn view(handle: u64) -> Option { } // SAFETY: the handle is a descriptor slot the title passes back. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; - let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); - let (view, current) = views.list.get(i as usize)?; - (tag == VIEW_TAG && *current == generation).then(|| view.clone()) + if tag != VIEW_TAG { + return None; + } + view_at(i, generation) } /// A description of `N` words, if the title passes one. @@ -741,6 +1063,81 @@ mod tests { heap[0] = 0; } + /// Constant buffer views are named whole in their records: any address + /// a program can have, any size below 16 KiB, multiples of 256 bytes + /// up to 4 MiB; what does not fit says so. + #[test] + fn constant_views_fit_their_records() { + let top = (1u64 << CONSTANT_ADDRESS_BITS) - 1; + for address in [0u64, 0x100, 0x2602_0000, 0xd_6b60_0000, 0x7ffd_a34f_0000, top] { + for size in [0u32, 1, 255, 256, 4000, (1 << 14) - 1, 1 << 14, 65536, (1 << 22) - 256] { + let [i, generation] = constant_words(address, size).expect("fits"); + assert_eq!(generation >> KIND_SHIFT, CONSTANT); + assert_eq!(view_at(i, generation), Some(View::Constant(address, size)), "{address:#x} {size}"); + } + } + assert_eq!(constant_words(top + 1, 256), None, "an address past 47 bits"); + assert_eq!(constant_words(0x1000, (1 << 14) + 1), None, "16 KiB or more, no multiple of 256"); + assert_eq!(constant_words(0x1000, 1 << 22), None, "4 MiB"); + // Different views never share their words. + assert_ne!(constant_words(0x1000, 256), constant_words(0x1000, 512)); + assert_ne!(constant_words(0x1000, 256), constant_words(0x1100, 256)); + assert_ne!(constant_words(0x1000, 1 << 14), constant_words(0x1000, 64)); + } + + /// The leak of run 65: a title that writes constant buffer views and + /// views of placed memory at ever new addresses adds nothing to the + /// table; one shape stands for all the placed views alike. + #[test] + fn views_at_new_addresses_add_no_entries() { + if !inline() { + return; + } + let null = std::ptr::null(); + let slots = [0u64; 4]; + let at = slots.as_ptr() as u64; + // A resource description and a view no other test uses. + let resource: [u32; 14] = std::array::from_fn(|k| 0x5ee0_0000 + k as u32); + let mut desc: [u32; 16] = std::array::from_fn(|k| 0x7a70_0000 + k as u32); + let mine = |v: &View| match v { + View::Constant(address, _) => (0x6_0000_0000..0x6_1000_0000).contains(address), + View::Placed(_, r, _) => *r == resource, + _ => false, + }; + let entries = || VIEWS.lock().unwrap().list.iter().filter(|(v, _)| mine(v)).count(); + let shapes = || VIEWS.lock().unwrap().shapes.iter().filter(|s| s.1 == resource).count(); + for n in 0..20_000u64 { + let address = 0x6_0000_0000 + n * 0x100; + create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at); + assert_eq!(view(at), Some(View::Constant(address, 512))); + let placed = 0xd_4940_0000 + n * 0x1_0000; + (desc[10], desc[11]) = (placed as u32, (placed >> 32) as u32); + create_placed_srv(null, &resource, &desc, at); + assert_eq!(view(at), Some(View::Placed(false, resource, desc))); + } + assert_eq!(entries(), 0, "no table entries"); + assert_eq!(shapes(), 1, "one shape for 20,000 placed views"); + // The same shape, unordered: another shape. + create_placed_uav(null, &resource, &desc, at); + assert_eq!(view(at), Some(View::Placed(true, resource, desc))); + assert_eq!(shapes(), 2); + // Placed memory past 1 TiB (not title memory) is a table entry. + (desc[10], desc[11]) = (0, 0x100); + create_placed_srv(null, &resource, &desc, at); + assert_eq!(view(at), Some(View::Placed(false, resource, desc))); + assert_eq!(entries(), 1); + // A record's words are the same for the same view (the host knows + // a slot's view by them), and differ with the address. + // SAFETY: both handles are slots of 32 bytes above. + let words = |handle: u64| unsafe { *(handle as *const [u32; 3]) }; + let other = [0u64; 4]; + create_cbv(null, &[0x40, 6, 512, 0], at); + create_cbv(null, &[0x40, 6, 512, 0], other.as_ptr() as u64); + assert_eq!(words(at), words(other.as_ptr() as u64)); + create_cbv(null, &[0x140, 6, 512, 0], other.as_ptr() as u64); + assert_ne!(words(at), words(other.as_ptr() as u64)); + } + /// A released resource's views go stale; the same view of a new /// resource at the same address is a new record. #[test] diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 582f234..8bff3f1 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -19,8 +19,9 @@ pub(crate) struct HostHeap { step: u32, /// Slots mirroring the title's; view heaps have `dynamic` more. count: u32, - /// Dynamic slots past `count` (none in sampler heaps): [`DYNAMIC`] - /// where the host takes them, else [`MIN_DYNAMIC`]. + /// Dynamic slots past `count`: [`DYNAMIC`] in view heaps, none in + /// sampler heaps. (Upstream falls back to 2^16 on a capped host heap; + /// ours keeps 2^18 there: 2^16 and 2^17 both ran out in this title.) dynamic: u32, sampler: bool, /// The record (view index and generation) each slot was last made from. @@ -33,6 +34,452 @@ pub(crate) struct HostHeap { /// Where the search for free dynamic slots starts, and which are taken /// (by lists not yet reset). next: Mutex<(u32, Vec)>, + /// How many dynamic slots are free (changed under `next`'s lock): with + /// fewer than a table needs, the search is not made. Once the world + /// had taken them all, every later table of the frame searched every + /// slot before it was refused. + free: std::sync::atomic::AtomicU32, + /// The shortest table that found no run of free slots since slots were + /// last given back (changed under `next`'s lock; `u32::MAX`: none). + /// Until something is given back the free runs only shrink, so a table + /// of that length or longer is refused without the search. Enough + /// slots were free, but in pieces, and every such table walked the + /// whole ring before it was refused: 0.33 ms each with 131,072 slots, + /// 1.0 s of the recording threads in a frame that refused 3,143 (run + /// 45), under the lock all of them need. (A free run that lies across + /// the place the search starts from is seen by neither.) + too_long: std::sync::atomic::AtomicU32, + /// View heaps: the bytes per element of the buffer view at each title + /// slot, for shaders that pick a buffer by an index they compute + /// (`victory_shader::emit::SLOT_STRIDES`): an upload buffer of + /// `SLOT_STRIDES_COUNT` dwords, its GPU address and its mapping. + strides: Option<(ID3D12Resource, u64, usize)>, + /// Title slots holding buffer views. Such a view gets its host slot + /// (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>, + /// Of those and of the slots that left the set: the ones written since + /// [`HostHeap::buffer_changes`] last took them. + changed: Mutex>, + /// 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 + /// table; one a shader picks by a computed index is brought up to date + /// from here ([`HostHeap::texture_slots_due`]). + textures: Mutex, + /// Per title slot, the frame (plus one; 0: never) in which a draw last + /// read it through a table, or made a table it lies in (with + /// [`TABLED_READ`] set if the draw read it). The draw that + /// reads such a slot brings its texture up to date itself and the slot + /// then leaves `textures`; a write of a slot that was a table's within + /// the last [`TABLED_FRAMES`] frames is due only [`TABLED_GRACE`] + /// frames later, by when its draw has read it. A title that builds a + /// table per draw writes thousands of texture views a frame into slots + /// only tables read (Grand Theft Auto VI: some 2,500 a frame in its + /// opening cutscene, a few hundred textures over and over), and every + /// one of them stood in the queue of textures picked by index, ahead + /// of or behind the ones shaders do pick by index. + tabled: Vec, + /// The title memory each placed texture view of this heap describes, + /// by slot and by address ([`Spans`]): which slots a newer view of + /// other memory there makes stale, and which to look at again when the + /// runtime maps, unmaps or writes memory ([`remapped`]). + placed: Mutex, +} + +/// Title memory by the placed texture views that describe it: per span of +/// memory (its start, its end) the title slots holding a view of a +/// texture that takes exactly that span. Spans never overlap: a console +/// title need not clear a descriptor when it streams a texture out, so a +/// view written over memory that older views describe otherwise (another +/// start or another length: another texture) is all that says the older +/// ones are stale. Views of one span with different descriptions (the +/// formats of one family, say) are one texture's. +/// No host heap is needed, so it is tested without one. +#[derive(Default)] +pub(crate) struct Spans { + by_start: std::collections::BTreeMap)>, + by_slot: std::collections::HashMap, + /// The bytes a placed texture takes, by resource description: worked + /// out once for each (a title writes the views of a few thousand + /// descriptions, thousands of times a frame). + sizes: std::collections::HashMap<[u32; 14], Option>, +} + +impl Spans { + /// The bytes of title memory a placed texture with the resource + /// description `desc` takes (`crate::resource::placed_bytes`). + fn bytes(&mut self, desc: &[u32; 14]) -> Option { + if let Some(&known) = self.sizes.get(desc) { + return known; + } + let bytes = crate::resource::placed_bytes(desc); + self.sizes.insert(*desc, bytes); + bytes + } + + /// The starts of the spans that overlap `[start, end)`. + fn overlapping(&self, start: u64, end: u64) -> Vec { + let before = self + .by_start + .range(..start) + .next_back() + .filter(|(_, span)| span.0 > start) + .map(|(at, _)| *at); + before.into_iter().chain(self.by_start.range(start..end).map(|(at, _)| *at)).collect() + } + + /// Slot `index` holds a view of a texture in `[start, end)`. `newer`: + /// the title wrote it now, so the slots whose views describe that + /// memory otherwise are stale: they are returned, and forgotten. + /// Otherwise (a draw made the slot from what it held) a view that + /// overlaps other spans is left out. + fn note(&mut self, index: u32, start: u64, end: u64, newer: bool) -> Vec { + let same = |span: Option<&(u64, std::collections::BTreeSet)>| span.is_some_and(|s| s.0 == end); + if self.by_slot.get(&index) == Some(&start) && same(self.by_start.get(&start)) { + return Vec::new(); + } + self.forget(index); + if end <= start { + return Vec::new(); + } + let mut stale = Vec::new(); + for at in self.overlapping(start, end) { + if at == start && same(self.by_start.get(&at)) { + continue; + } + if !newer { + return stale; + } + if let Some((_, slots)) = self.by_start.remove(&at) { + for slot in slots { + self.by_slot.remove(&slot); + stale.push(slot); + } + } + } + self.by_start.entry(start).or_insert_with(|| (end, Default::default())).1.insert(index); + self.by_slot.insert(index, start); + stale + } + + /// Slot `index` holds no placed texture view any more. + fn forget(&mut self, index: u32) { + let Some(start) = self.by_slot.remove(&index) else { + return; + }; + if let Some(span) = self.by_start.get_mut(&start) { + span.1.remove(&index); + if span.1.is_empty() { + self.by_start.remove(&start); + } + } + } + + /// The slots whose texture's memory overlaps `[start, end)`. + fn slots_in(&self, start: u64, end: u64) -> Vec { + self.overlapping(start, end) + .iter() + .filter_map(|at| self.by_start.get(at)) + .flat_map(|span| span.1.iter().copied()) + .collect() + } +} + +/// Title memory the runtime mapped, unmapped or is about to write since a +/// texture pass last took the ranges ([`remapped`]). +static REMAPPED: Mutex> = Mutex::new(Vec::new()); + +/// The lowest start and the highest end of any span of [`Spans`] so far +/// (the start is `u64::MAX` until there is one): what the runtime does to +/// memory outside is none of the texture pass's business. +static SPANNED: [std::sync::atomic::AtomicU64; 2] = [ + std::sync::atomic::AtomicU64::new(u64::MAX), + std::sync::atomic::AtomicU64::new(0), +]; + +/// Since the start: slots whose view a newer view of other memory there +/// made stale; ranges of memory noted as mapped, unmapped or written; +/// ranges dropped because no pass took them; slots made due by such +/// ranges; and made slots whose memory was found unmapped (made null). +pub(crate) static STALE: [std::sync::atomic::AtomicU64; 5] = + [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// Whether a view written over memory that older views describe otherwise +/// makes those stale; `VICTORY_STALE_TEXTURES=0` leaves them as they are. +fn stale_out() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_STALE_TEXTURES").is_none_or(|v| v != "0")) +} + +/// The runtime mapped or unmapped title memory `[at, at + len)`, or is +/// about to write it through the kernel (`crate::watch`): the placed +/// textures there may have arrived, gone, or changed with no descriptor +/// written. The range is kept for the next texture pass +/// ([`HostHeap::texture_slots_remapped`]). Called with the runtime's own +/// locks held: this locks one mutex of its own and calls nothing. +pub(crate) fn remapped(at: usize, len: usize) { + use std::sync::atomic::Ordering::Relaxed; + /// Ranges kept until a pass takes them. + const MOST: usize = 1 << 15; + let (start, end) = (at as u64, at.saturating_add(len) as u64); + if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) { + return; + } + let mut ranges = REMAPPED.lock().unwrap_or_else(|e| e.into_inner()); + STALE[1].fetch_add(1, Relaxed); + // Pages are mapped one after the other. + if let Some(last) = ranges.last_mut() + && last.1 == start + { + last.1 = end; + return; + } + if ranges.len() >= MOST { + // No pass runs (no shader that picks textures by index is bound): + // the slots there are looked at when they are due, as before. + STALE[2].fetch_add(ranges.len() as u64, Relaxed); + ranges.clear(); + } + ranges.push((start, end)); +} + +/// Frames for which a slot a draw read through a table counts as a table's +/// slot ([`HostHeap::tabled`]). +const TABLED_FRAMES: u64 = 240; + +/// Frames a write of a table's slot waits in the queue for the draw that +/// reads it, before the slot is taken for one shaders pick by index. +/// Frames as `crate::frame::current` counts them: in its opening cutscene +/// Grand Theft Auto VI begins two or three of them per frame it presents +/// (435 begun in the 353 s of run 52's, for some 140 presented). +const TABLED_GRACE: u64 = 8; + +/// In [`HostHeap::tabled`]: a draw read the slot in that frame. +const TABLED_READ: u32 = 1 << 31; + +/// Since the start: writes of texture views into slots that count as a +/// table's (due later), and slots that left the queue because a draw read +/// them through a table. +pub(crate) static TABLED_WRITES: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether slots draws read through tables leave the queue of textures +/// picked by index; `VICTORY_TABLED_TEXTURES=1` keeps them in it as +/// before. +fn tabled_out() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TABLED_TEXTURES").is_none_or(|v| v != "1")) +} + +/// What the queue of textures picked by index knows of a title slot. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Waiting { + /// The frame from which the slot is due. + due: u64, + /// The frame it was written in. + written: u64, + /// Which write of the queue put it here: the pass hands it back with + /// what it did, so a slot written again meanwhile stays as written. + write: u64, + /// Looks in a row that found nothing to upload (its memory not mapped, + /// or no more of it than at the last upload). + looks: u8, + /// Bytes of its memory that were mapped when it was last uploaded + /// without all of it there; 0: not uploaded yet. + mapped: u64, +} + +/// The queue of title slots whose texture view waits to be brought up to +/// date for shaders that pick textures by index: which are due, and in +/// which order (no host heap needed, so it is tested without one). +#[derive(Default)] +pub(crate) struct TextureQueue { + slots: std::collections::BTreeMap, + writes: u64, +} + +impl TextureQueue { + /// A texture view was written into slot `index` in `frame`, due from + /// frame `due`. `seen`: it was not written, a draw or the pass made + /// the host slot from a view the queue may hold already, which then + /// stays as it is. + fn written(&mut self, index: u32, frame: u64, due: u64, seen: bool) { + if seen && self.slots.contains_key(&index) { + return; + } + self.writes += 1; + let write = self.writes; + self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0 }); + } + + fn remove(&mut self, index: u32) { + self.slots.remove(&index); + } + + /// Up to `max` slots due at `frame`, each with its write number, in + /// the order to serve them: + /// - first the ones looked at before (their memory was not mapped, or + /// only part of it): the look is a query, and memory that has + /// arrived since is what the title streamed in last; + /// - then the others, the newest write first and the oldest next, in + /// turns: slot order served the low slots of a backlog of + /// 25,000-40,000 while the textures of the shot on screen waited + /// (run 52: 98% of the drawn pixels had no colour texture in the + /// first 3D frames). + fn due(&self, frame: u64, max: usize) -> Vec<(u32, u64)> { + let mut again: Vec<(u64, u32, u64)> = Vec::new(); + let mut fresh: Vec<(u64, u32, u64)> = Vec::new(); + for (&index, w) in self.slots.iter().filter(|(_, w)| w.due <= frame) { + let class = if w.looks > 0 || w.mapped > 0 { &mut again } else { &mut fresh }; + class.push((w.written, index, w.write)); + } + // By the number of the write, counted over the run. + let newest_first = |a: &(u64, u32, u64), b: &(u64, u32, u64)| b.2.cmp(&a.2); + again.sort_unstable_by(newest_first); + fresh.sort_unstable_by(newest_first); + let mut order: Vec<(u32, u64)> = again.iter().map(|&(_, index, write)| (index, write)).collect(); + let (mut new, mut old) = (0, fresh.len()); + while new < old && order.len() < max { + order.push((fresh[new].1, fresh[new].2)); + new += 1; + if new < old && order.len() < max { + old -= 1; + order.push((fresh[old].1, fresh[old].2)); + } + } + order.truncate(max); + order + } + + /// The entry of `index` if it is still the write the pass was handed. + fn same(&mut self, index: u32, write: u64) -> Option<&mut Waiting> { + self.slots.get_mut(&index).filter(|w| w.write == write) + } + + /// Slot `index` is up to date: out of the queue until written again. + fn done(&mut self, index: u32, write: u64) { + if self.same(index, write).is_some() { + self.slots.remove(&index); + } + } + + /// Nothing to upload at slot `index` now: looked at again after 1, 2, + /// 4, ... frames, at most `most`. + fn later(&mut self, index: u32, write: u64, frame: u64, most: u64) { + if let Some(w) = self.same(index, write) { + w.due = frame + (1u64 << w.looks.min(16)).min(most.max(1)); + w.looks = w.looks.saturating_add(1); + } + } + + /// Slot `index` was uploaded with `mapped` bytes of its memory there, + /// not all of it: looked at again from frame `due`. + fn partly(&mut self, index: u32, write: u64, due: u64, mapped: u64) { + if let Some(w) = self.same(index, write) { + (w.due, w.looks, w.mapped) = (due, 0, mapped.max(1)); + } + } + + /// The memory slot `index`'s texture lies in was mapped, unmapped or + /// written in `frame`: the slot is looked at from frame `due` as one + /// written now, whatever was known of it (a pass at work on it does + /// not take it out). + fn changed(&mut self, index: u32, frame: u64, due: u64) { + self.writes += 1; + let write = self.writes; + let due = self.slots.get(&index).map_or(due, |w| w.due.min(due)); + self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0 }); + } + + /// Bytes of slot `index`'s memory that were mapped at its last upload + /// (0: not uploaded, or all of it was). + fn mapped(&self, index: u32) -> u64 { + self.slots.get(&index).map_or(0, |w| w.mapped) + } + + /// For the frame line: slots in the queue; of them due at `frame`; + /// waiting for their memory (looked at, never uploaded); uploaded in + /// part; and the frames the oldest due one has waited since its write. + fn census(&self, frame: u64) -> [u64; 5] { + let mut c = [self.slots.len() as u64, 0, 0, 0, 0]; + for w in self.slots.values() { + if w.mapped > 0 { + c[3] += 1; + } else if w.looks > 0 { + c[2] += 1; + } + if w.due <= frame { + c[1] += 1; + c[4] = c[4].max(frame.saturating_sub(w.written)); + } + } + c + } +} + +/// Whether `view` is of a texture the title may fill itself: a texture it +/// placed in memory, or a texture object. +pub(crate) fn is_texture_view(view: &View) -> bool { + match view { + View::Placed(false, resource, _) => resource[0] != 1, + View::Shader(r, _) => crate::resource::buffer_bytes(*r as crate::object::This).is_none(), + _ => false, + } +} + +/// Buffer views left null because the host would refuse them +/// ([`buffer_view_ok`]), since the start. +pub(crate) static REFUSED_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether the host device is gone, and why (the first time it is asked +/// after that): for passes that make many views, to name the one that did +/// it. +pub(crate) fn device_removed() -> Option { + let host = host()?; + // SAFETY: a plain query. + let reason = unsafe { host.device.GetDeviceRemovedReason() }; + reason.err().map(|e| e.to_string()) +} + +/// Writes of title view-heap slots with a placed texture view and with a +/// view of a texture object, since the start (diagnostic counts). +pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Bytes per element of a buffer view, as the console's descriptor holds +/// them for indexed reads (structured: the stride; raw: 1, the index is the +/// byte; typed: the format's); `None` if `view` is not a buffer view. +fn view_stride(view: &View) -> Option { + const BUFFER: u32 = 1; + let (words, unordered): (&[u32; 10], bool) = match view { + View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false), + View::Unordered(_, _, Some(d)) if d[1] == BUFFER => (d, true), + View::Placed(unordered, resource, d) if resource[0] == BUFFER => { + (d[..10].try_into().ok()?, *unordered) + } + _ => return None, + }; + // SAFETY: buffer views' union members. + let (stride, raw, format) = unsafe { + if unordered { + let d = uav_desc(words); + let b = d.Anonymous.Buffer; + (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, d.Format) + } else { + let d = srv_desc(words); + let b = d.Anonymous.Buffer; + (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, d.Format) + } + }; + Some(if stride > 0 { + stride + } else if raw { + 1 + } else { + crate::resource::element(format.0 as u32).map_or(0, |(bytes, _)| bytes as u32) + }) } /// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for @@ -62,16 +509,49 @@ pub(crate) fn near_heaps(va: u64) -> String { /// tiers 1 and 2; tier 3 hardware may take more. const PORTABLE_VIEWS: u32 = 1_000_000; +/// Asks the host, once, whether it caps view heaps at [`PORTABLE_VIEWS`], +/// and if so tells the translator now (`set_view_heap_limit`) instead of +/// when the title's heap is made: a shader keeps the limit it was +/// translated with, and Grand Theft Auto VI makes 25 pipelines (their +/// shaders translated at once) before it makes its view heap. Those would +/// read a view index past the heap unclamped, the read that hangs NVIDIA. +/// Called before a shader is translated. +/// shortcut: the limit is the capped heap's last slot whatever size the +/// title's heap turns out to have; a heap that fits is not capped and +/// keeps no null slot there (an index past it is as undefined as before). +pub(crate) fn probe_view_limit() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let Some(host) = host() else { return }; + // SAFETY: plain heap creation; the heap is released at once. + let made: windows::core::Result = unsafe { + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: PORTABLE_VIEWS + 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + }; + if made.is_err() { + tracing::info!("the host caps view heaps at {PORTABLE_VIEWS}: view indices are clamped from the first shader on"); + victory_shader::emit::set_view_heap_limit(PORTABLE_VIEWS - 1); + } + }); +} + /// Slots past the title's in a view heap, for tables a draw needs made /// afresh (constant buffers copied per draw). A list holds the slots it /// took until it is reset (its submissions have run) or released. -/// 2^16 ran out seconds into the world (every world run on an RX 9070 XT, -/// each a device removal shortly after; #59). -const DYNAMIC: u32 = 1 << 18; - -/// The dynamic slots of a heap whose host would not take [`DYNAMIC`] more -/// (a capped heap, NVIDIA): the title's slots keep their room first. -const MIN_DYNAMIC: u32 = 1 << 16; +/// 2^16 ran out in the world ("no free dynamic descriptor slots", run 11; +/// upstream PR #336 takes 2^18). On a host heap capped at 1,000,000 views +/// (NVIDIA) these come out of the title's slots, whose highest seen is +/// about 720,000: 2^17 left 868,000 of them, and ran out in the opening +/// cutscene (a frame asks for up to 16,000 tables while the frame before +/// still holds its own; a draw refused its table read slots never made +/// for it, and the card stopped within frames). 2^18 leaves 737,000; a +/// table past them is made afresh in these slots like any other. +pub(crate) const DYNAMIC: u32 = 1 << 18; impl HostHeap { pub(crate) fn new(sampler: bool, count: u32) -> Option { @@ -93,31 +573,21 @@ impl HostHeap { }) } }; - // The larger dynamic range only where the host takes it on top of - // every title slot; else the smaller one, and the cap after that. - let (heap, count, extra) = if sampler { - match make(count) { - Ok(heap) => (heap, count, 0), - Err(e) => { - tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); - return None; - } + let extra = if sampler { 0 } else { DYNAMIC }; + let (heap, count, size) = match make(count + extra) { + Ok(heap) => (heap, count, count + extra), + Err(e) if !sampler && count + extra > PORTABLE_VIEWS => { + // shortcut: descriptors past the host's limit are left out; a title that reaches + // them needs remapping. The heap's last slot stays null, and shaders read it for + // any view index from there on (`set_view_heap_limit`): a read past the heap's + // end hung NVIDIA's GPU (the title's heap is a little over 1 000 000 views). + tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}; views past it read a null slot"); + victory_shader::emit::set_view_heap_limit(PORTABLE_VIEWS - 1); + (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - extra - 1, PORTABLE_VIEWS) } - } else if let Ok(heap) = make(count + DYNAMIC) { - (heap, count, DYNAMIC) - } else { - match make(count + MIN_DYNAMIC) { - Ok(heap) => (heap, count, MIN_DYNAMIC), - Err(e) if count + MIN_DYNAMIC > PORTABLE_VIEWS => { - // shortcut: descriptors past the host's limit are left - // out; a title that reaches them needs remapping. - tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}"); - (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC) - } - Err(e) => { - tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); - return None; - } + Err(e) => { + tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); + return None; } }; // SAFETY: a live heap. @@ -136,6 +606,19 @@ impl HostHeap { u64::from(step), sampler, )); + let strides = (!sampler) + .then(|| { + let bytes = u64::from(victory_shader::emit::SLOT_STRIDES_COUNT) * 4; + let (buffer, data) = host.upload_buffer(bytes)?; + // SAFETY: the buffer's whole mapping; a live buffer. + let gpu = unsafe { + std::ptr::write_bytes(data, 0, bytes as usize); + buffer.GetGPUVirtualAddress() + }; + crate::host::name(&buffer, || "element strides by view heap slot".to_owned()); + Some((buffer, gpu, data as usize)) + }) + .flatten(); let h = HostHeap { heap, cpu, @@ -145,14 +628,24 @@ impl HostHeap { sampler, made: Mutex::new(vec![0; count as usize]), kept: Mutex::new(vec![None; (count + extra) as usize]), - next: Mutex::new((0, vec![false; extra as usize])), + next: Mutex::new((0, vec![false; DYNAMIC as usize])), + free: std::sync::atomic::AtomicU32::new(DYNAMIC), + too_long: std::sync::atomic::AtomicU32::new(u32::MAX), + strides, + buffers: Mutex::default(), + changed: Mutex::default(), + textures: Mutex::default(), + tabled: (0..if sampler { 0 } else { count }) + .map(|_| std::sync::atomic::AtomicU32::new(0)) + .collect(), + placed: Mutex::default(), }; // A slot never written is undefined: shaders reading one (a slot // the title wrote in a way we do not know, or a table entry no // used-resource entry names) read a wild address. Every slot starts // null instead. let started = std::time::Instant::now(); - if let Err(e) = h.fill_null(kind, count + extra) { + if let Err(e) = h.fill_null(kind, size) { tracing::warn!(error = %e, "host descriptor heap not made null"); } tracing::debug!(ms = started.elapsed().as_millis(), "host descriptor heap made null"); @@ -227,15 +720,21 @@ impl HostHeap { if self.sampler || n == 0 || n > self.dynamic { return None; } + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::DynamicAsked, 1); let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); let (next, taken) = &mut *guard; + let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n + && n < self.too_long.load(std::sync::atomic::Ordering::Relaxed); let n = n as usize; // Search from `next` on, then from the start. let starts = (*next as usize..self.dynamic as usize).chain(0..*next as usize); let mut run = 0; let mut found = None; let mut last = usize::MAX; - for at in starts { + for at in starts.take(if enough { DYNAMIC as usize } else { 0 }) { // A run cannot wrap past the end. if at != last.wrapping_add(1) { run = 0; @@ -248,12 +747,24 @@ impl HostHeap { } } let Some(first) = found else { + if enough { + self.too_long.fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed); + } static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made")); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::DynamicRefused, 1); + add(C::DynamicNs, started.elapsed().as_nanos() as u64); + } return None; }; + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64); taken[first..first + n].fill(true); - *next = ((first + n) % self.dynamic as usize) as u32; + self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed); + *next = ((first + n) % DYNAMIC as usize) as u32; Some(self.count + first as u32) } @@ -263,6 +774,291 @@ impl HostHeap { self.count } + /// The GPU address of the table of element strides by title slot (view + /// heaps). + pub(crate) fn strides_gpu(&self) -> Option { + self.strides.as_ref().map(|s| s.1) + } + + /// The table's buffer, for a list to hold. + pub(crate) fn strides_buffer(&self) -> Option<&ID3D12Resource> { + self.strides.as_ref().map(|s| &s.0) + } + + /// Up to `max` title slots whose texture view is due at `frame`, each + /// with its write number, in the order to serve them + /// ([`TextureQueue::due`]), and the queue's counts + /// ([`TextureQueue::census`]). + pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 5]) { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + (if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame)) + } + + /// The texture view of title slot `index` (as handed out with `write`) + /// was brought up to date: due again from frame `again` (uploaded with + /// that many bytes of its memory there, not all), or not until the + /// slot is written again. + pub(crate) fn texture_slot_done(&self, index: u32, write: u64, again: Option<(u64, u64)>) { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + match again { + Some((frame, mapped)) => textures.partly(index, write, frame, mapped), + None => textures.done(index, write), + } + } + + /// Nothing to upload at title slot `index` now (its memory is not + /// mapped, or no more of it than before): looked at again after 1, 2, + /// 4, ... frames, at most `most`. + pub(crate) fn texture_slot_later(&self, index: u32, write: u64, frame: u64, most: u64) { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + textures.later(index, write, frame, most); + } + + /// Bytes of title slot `index`'s memory that were mapped when it was + /// last uploaded in part (0: not uploaded, or whole). + pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).mapped(index) + } + + /// Takes the ranges of title memory the runtime mapped, unmapped or + /// wrote since the last call ([`remapped`]) and makes the slots whose + /// placed texture lies there due from the next frame (by when a write + /// under way has landed): memory that arrived is uploaded, memory that + /// went makes the slot null ([`HostHeap::texture_slot_gone`]), and a + /// texture streamed into the place of another of the same description + /// is uploaded although no descriptor says so. Slots tables read are + /// left to their draws. Returns how many slots it made due. + /// shortcut: the ranges are kept in one place for all heaps; the heap + /// whose pass runs first takes them (a title has one view heap). + pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize { + use std::sync::atomic::Ordering::Relaxed; + let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner())); + if ranges.is_empty() { + return 0; + } + 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() + }; + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + for &slot in &slots { + textures.changed(slot, frame, frame + 1); + } + STALE[3].fetch_add(slots.len() as u64, Relaxed); + slots.len() + } + + /// The memory of the texture title slot `index` views is not mapped + /// (any more): a host slot made from it becomes null again, so that + /// the host copy can be let go (`crate::resource::let_go_idle`; a slot + /// keeps what it views). True if the slot was made. + pub(crate) fn texture_slot_gone(&self, index: u32) -> bool { + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + if made.get(index as usize).is_none_or(|&key| key == 0) { + return false; + } + self.unmake(&mut made, index); + STALE[4].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + true + } + + /// 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) { + let Some(key) = made.get_mut(index as usize).map(std::mem::take) else { + return; + }; + if key == 0 { + return; + } + match view_at(key as u32, (key >> 32) as u32) { + Some(view) => null_for(&view, self.cpu(index)), + None => null_view(self.cpu(index)), + } + self.keep(index, None); + } + + /// 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 + /// caller makes the host slot in place ([`HostHeap::mirror`]), as the + /// pass would have, for a shader that picks it by index all the same. + pub(crate) fn texture_slot_tabled(&self, index: u32, read: bool) { + self.tabled_in(index, read, crate::frame::current()); + } + + /// [`HostHeap::texture_slot_tabled`] in frame `frame`. + fn tabled_in(&self, index: u32, read: bool, frame: u64) { + use std::sync::atomic::Ordering::Relaxed; + let Some(stamp) = self.tabled.get(index as usize) else { + return; + }; + let now = (frame as u32).wrapping_add(1) & !TABLED_READ; + let old = stamp.load(Relaxed); + if !read { + if old & !TABLED_READ != now { + stamp.store(now, Relaxed); + } + return; + } + // Once per slot and frame: tables are read by every draw. + if old != now | TABLED_READ { + stamp.store(now | TABLED_READ, Relaxed); + if tabled_out() { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + if textures.slots.remove(&index).is_some() { + TABLED_WRITES[1].fetch_add(1, Relaxed); + } + } + } + } + + /// Whether title slot `index` was a table's within the last + /// [`TABLED_FRAMES`] frames before `frame` (never, if such slots are + /// to be queued as any other). + fn tabled_lately(&self, index: u32, frame: u64) -> bool { + let stamp = self.tabled_stamp(index) & !TABLED_READ; + let now = (frame as u32).wrapping_add(1) & !TABLED_READ; + tabled_out() && stamp != 0 && u64::from(now.wrapping_sub(stamp)) <= TABLED_FRAMES + } + + /// What `tabled` holds for title slot `index`; 0: never a table's. + fn tabled_stamp(&self, index: u32) -> u32 { + self.tabled + .get(index as usize) + .map_or(0, |s| s.load(std::sync::atomic::Ordering::Relaxed)) + } + + /// The queue's part of a write of title slot `index` in `frame`: + /// `texture`, whether it now holds a view of a texture the title may + /// fill; `seen` as for [`HostHeap::note_buffer`]. + fn queue_texture(&self, index: u32, texture: bool, seen: bool, frame: u64) { + let stamp = if tabled_out() { self.tabled_stamp(index) } else { 0 }; + let now = (frame as u32).wrapping_add(1) & !TABLED_READ; + // A table's slot lately: the draw that reads it uploads its + // texture, so its write waits for that draw. + let lately = stamp != 0 && u64::from(now.wrapping_sub(stamp & !TABLED_READ)) <= TABLED_FRAMES; + // Made now by a draw of this frame that read it through a table: + // up to date. + let read_now = seen && stamp == now | TABLED_READ; + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + if texture && !read_now { + let due = if lately && !seen { + TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + frame + TABLED_GRACE + } else { + 0 + }; + textures.written(index, frame, due, seen); + } else { + textures.remove(index); + } + } + + /// 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() + } + + /// 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() + } + + /// Records what title slot `index` now holds for shaders that pick + /// buffers from the heap: its element stride in the table, and whether + /// it is a buffer view at all. + /// `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 { + if self.sampler { + return Vec::new(); + } + // Measured for the texture side of the same gap (textures a shader + // picks by a computed index are neither made, if placed, nor + // uploaded): slots written with a placed texture view, and with a + // view of a texture object. + let texture = match view { + Some(View::Placed(false, resource, _)) if resource[0] != 1 => { + PLACED_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + true + } + Some(View::Shader(r, _)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => { + OBJECT_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + true + } + _ => false, + }; + self.queue_texture(index, texture, seen, crate::frame::current()); + // The memory a placed texture view describes. Not for a slot + // tables read (thousands of writes a frame, each read by its + // draw): no pass looks at it, and the same texture's view in a + // slot shaders pick by index says what it says. + let placed_view = match view { + Some(View::Placed(false, resource, desc)) + if resource[0] != 1 && !self.tabled_lately(index, crate::frame::current()) => + { + Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32)) + } + _ => None, + }; + let stale = { + use std::sync::atomic::Ordering::Relaxed; + let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + let span = placed_view + .and_then(|(resource, start)| Some((start, start.saturating_add(placed.bytes(resource)?)))); + match span { + Some((start, end)) => { + SPANNED[0].fetch_min(start, Relaxed); + SPANNED[1].fetch_max(end, Relaxed); + placed.note(index, start, end, !seen && stale_out()) + } + None => { + placed.forget(index); + Vec::new() + } + } + }; + 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 { + textures.remove(slot); + } + } + let stride = view.and_then(view_stride); + 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)) }; + } + let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); + let was = if stride.is_some() { + buffers.insert(index); + true + } else { + buffers.remove(&index) + }; + if was { + self.changed + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(index); + } + stale + } + /// Gives back `n` dynamic slots from `first` (an index [`dynamic`] /// returned). /// @@ -274,6 +1070,9 @@ impl HostHeap { let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); let end = (at + n).min(self.dynamic) as usize; if let Some(slots) = guard.1.get_mut(at as usize..end) { + let given = slots.iter().filter(|taken| **taken).count() as u32; + self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed); + self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed); slots.fill(false); } } @@ -302,7 +1101,114 @@ impl HostHeap { fn keep(&self, index: u32, resource: Option) { let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); if let Some(slot) = kept.get_mut(index as usize) { - *slot = resource; + // A running submission may still read the old resource through + // this slot. + if let Some(old) = std::mem::replace(slot, resource) { + crate::host::retire(old); + } + } + } + + /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes + /// of `buffer` from byte `offset` (a multiple of 16): a root SRV with a + /// size, whose reads past it return zeros instead of reaching whatever + /// the host placed after the buffer. + pub(crate) fn raw_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) { + let Some(host) = host() else { return }; + let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: offset / 4, + NumElements: elements, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }, + }, + }; + // SAFETY: a slot of our heap and a live buffer covering the range. + unsafe { + host.device + .CreateShaderResourceView(buffer, Some(&desc), self.cpu(index)) + }; + self.keep(index, Some(buffer.clone())); + } + + /// Makes slot `index` (a dynamic one) a raw buffer view that reads + /// zeros. + pub(crate) fn null_raw_at(&self, index: u32) { + null_buffer_view(self.cpu(index)); + self.keep(index, None); + } + + /// Makes slot `index` (a dynamic one) a raw unordered access view of + /// `len` bytes of `buffer` from byte `offset` (a multiple of 16): a + /// root UAV with a size, whose accesses past it do nothing instead of + /// reaching whatever the host placed after the buffer. + pub(crate) fn raw_uav_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) { + let Some(host) = host() else { return }; + let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32; + let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + FirstElement: offset / 4, + NumElements: elements, + StructureByteStride: 0, + CounterOffsetInBytes: 0, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + }, + }, + }; + // SAFETY: a slot of our heap and a live buffer covering the range. + unsafe { + host.device.CreateUnorderedAccessView( + buffer, + None::<&ID3D12Resource>, + Some(&desc), + self.cpu(index), + ) + }; + self.keep(index, Some(buffer.clone())); + } + + /// Makes slot `index` (a dynamic one) a raw unordered access view of + /// nothing: reads give zeros, writes are dropped. + pub(crate) fn null_raw_uav_at(&self, index: u32) { + self.keep(index, None); + let Some(host) = host() else { return }; + let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: 1, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + ..Default::default() + }, + }, + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&desc), + self.cpu(index), + ) + }; + } + + /// The shader-visible handle of slot `index`. + pub(crate) fn gpu_handle(&self, index: u32) -> D3D12_GPU_DESCRIPTOR_HANDLE { + // SAFETY: a live shader-visible heap. + let start = unsafe { self.heap.GetGPUDescriptorHandleForHeapStart().ptr }; + D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: start + u64::from(index) * u64::from(self.step), } } @@ -359,11 +1265,46 @@ impl HostHeap { if made[index as usize] != 0 { made[index as usize] = 0; self.make_null(index); + let _ = self.note_buffer(index, None, false); + } else if for_draw { + // Left for later and stale since: out of the sets and the stride table. + let _ = self.note_buffer(index, None, false); } return None; }; if made[index as usize] != key { - let later = !for_draw && view.is_buffer(); + // 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); + } + } + // 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 + // here when a draw reads the slot through a table. + let waiting = if for_draw { None } else { view.waiting_texture() }; + if let Some(texture) = waiting { + super::wait_for(texture, handle); + } + let later = !for_draw && (view.is_buffer() || waiting.is_some()); + // Another view of the placed texture the slot shows already (a + // title that streams a texture in writes its view again with + // more mips each time some arrive): the slot goes on showing + // the old view until a draw or the texture pass makes the new + // 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. + 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)) + { + KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return Some(view); + } made[index as usize] = if later { 0 } else { key }; let kept = if later { None @@ -378,6 +1319,16 @@ impl HostHeap { Some(view) } + /// Whether host slot `index` shows `buffer`; `None` if it shows no + /// resource (diagnostics: a buffer view's slot must show the host copy + /// that is brought up to date for it). + #[cfg(feature = "diagnostics")] + pub(crate) fn shows(&self, index: u32, buffer: &ID3D12Resource) -> Option { + let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + let shown = kept.get(index as usize)?.as_ref()?; + Some(windows::core::Interface::as_raw(shown) == windows::core::Interface::as_raw(buffer)) + } + /// The view host slot `index` was made from, in a few words, with the /// title and host addresses of a buffer view (diagnostics). "null" for /// a slot never made or left null. @@ -475,6 +1426,60 @@ pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> { )) } +/// The title memory the host slot of buffer view `view` is made on +/// (address, bytes): the whole buffer the view is of, which is what +/// [`make`] finds the host copy by. [`buffer_range`] is the part of it the +/// view reads. +pub(crate) fn buffer_extent(view: &View) -> Option<(u64, u64)> { + match view { + View::Shader(r, Some(_)) | View::Unordered(r, _, Some(_)) => { + let (data, len) = crate::resource::buffer_bytes(*r as crate::object::This)?; + Some((data as u64, len)) + } + View::Placed(_, resource, desc) if resource[0] == 1 => Some(( + u64::from(desc[10]) | u64::from(desc[11]) << 32, + u64::from(resource[4]) | u64::from(resource[5]) << 32, + )), + _ => None, + } +} + +/// Whether a buffer view is brought up to date in the host copy its slot +/// shows ([`buffer_copy`]). On by default; `VICTORY_VIEW_EXTENT=0` looks the +/// copy up by the view's range alone, as before. +fn view_extent() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_EXTENT").is_none_or(|v| v != "0")) +} + +/// The host copy buffer view `view` reads, and the title range (address, +/// bytes) it reads there; `None` for other views and empty ranges. +/// +/// The copy is the one the view's slot shows: [`make`] finds it by the +/// whole buffer the view is of ([`buffer_extent`]). Looked up by the range +/// the view reads, as it was, the copy is another one wherever the two +/// lookups differ: for memory outside buffer objects, a view of a part of a +/// buffer that crosses a window line (the buffer's window is two cells, the +/// part's one), and for buffer objects, a part that also lies in a smaller +/// buffer object. The slot then showed a copy nothing brought up to date, +/// and what shaders wrote through it was looked for in the other copy. +pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc, u64, u64)> { + let (address, len) = buffer_range(view)?; + if len == 0 { + return None; + } + if view_extent() + && let Some((base, width)) = buffer_extent(view) + // (The console is lax: a view may begin past its buffer's end.) + && address >= base + && address - base < width.max(1) + && let Some(shadow) = crate::shadow::find(base, width) + { + return Some((shadow, address, len)); + } + crate::shadow::find(address, len).map(|shadow| (shadow, address, len)) +} + /// [`buffer_range`] of an unordered access view of memory at `base`. fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { let desc = uav_desc(words); @@ -496,6 +1501,64 @@ fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { /// The host resource a slot made by [`make`] views, if any. type Kept = Option; +/// A structured buffer view (`first`, `count` elements of `stride` bytes, +/// `offset` bytes into its host copy) as a raw view of the same bytes: +/// its first dword and its dwords. Translated shaders read untyped buffers +/// as raw bytes at `element * stride + offset` (the stride from the +/// used-resource entry, or from the table by heap slot for a buffer picked +/// by index), and a raw read through a structured view gives zeros on +/// NVIDIA (reported upstream with PR #193; structured reads through raw +/// views were right there). So the host's view is raw whenever it can be: +/// the bytes must start on 16 (the host's raw view alignment) and be whole +/// dwords. A view that cannot stays structured. +fn raw_window(offset: u64, first: u64, count: u32, stride: u32) -> Option<(u64, u32)> { + if stride == 0 { + return None; + } + let start = first.checked_mul(u64::from(stride))?.checked_add(offset)?; + let bytes = u64::from(count) * u64::from(stride); + (start % 16 == 0 && bytes % 4 == 0) + .then(|| u32::try_from(bytes / 4).ok().map(|dwords| (start / 4, dwords))) + .flatten() +} + +/// Whether the host accepts a buffer view with these fields of a buffer of +/// `width` bytes. It removes the device for one it does not (view creation +/// returns nothing), and the console is laxer: the title's heap holds +/// views past their memory's end, of no elements, of typeless formats +/// without the raw flag, with strides the host has no structured buffers +/// for. Since every buffer view of the heap is made for shaders that pick +/// them by index, one such view ended the run (2026-11-24, run 10). +fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> bool { + use crate::resource::family; + let f = format.0 as u32; + let element = if raw { + // raw: R32 typeless, counted in dwords, starting on 16 bytes + if format != DXGI_FORMAT_R32_TYPELESS || stride != 0 || first % 4 != 0 { + return false; + } + 4 + } else if stride > 0 { + // structured: no format, a stride the host takes + if format != DXGI_FORMAT_UNKNOWN || stride > 2048 || stride % 4 != 0 { + return false; + } + u64::from(stride) + } else { + // typed: a format with a size that is not typeless + let typeless = family(f) == f && family(f + 1) == f; + match crate::resource::element(f) { + Some((bytes, 1)) if f != 0 && !typeless && bytes > 0 => bytes, + _ => return false, + } + }; + count > 0 + && first + .checked_add(u64::from(count)) + .and_then(|end| end.checked_mul(element)) + .is_some_and(|end| end <= width) +} + fn buffer_srv( address: u64, len: u64, @@ -503,19 +1566,57 @@ fn buffer_srv( at: D3D12_CPU_DESCRIPTOR_HANDLE, ) -> Option { let shadow = crate::shadow::find(address, len)?; + let offset = shadow.offset(address); + // A structured view as a raw view of the same bytes (see `raw_window`). + // SAFETY: a buffer view's union member. + let structured = unsafe { desc.Anonymous.Buffer }; + let window = (desc.Format == DXGI_FORMAT_UNKNOWN) + .then(|| raw_window(offset, structured.FirstElement, structured.NumElements, structured.StructureByteStride)) + .flatten(); + if let Some((first, count)) = window { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Anonymous.Buffer = D3D12_BUFFER_SRV { + FirstElement: first, + NumElements: count, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }; + } let element = element_size(&desc); // SAFETY: a buffer view's union member. let buffer = unsafe { &mut desc.Anonymous.Buffer }; - let offset = shadow.offset(address); - if element == 0 || offset % element != 0 { + if window.is_none() { + if element == 0 || offset % element != 0 { + once!( + offset, + element, + "buffer view not on an element of its host copy" + ); + return None; + } + buffer.FirstElement += offset / element; + } + let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); + let raw = buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; + // SAFETY: a live buffer. + let width = unsafe { shadow.buffer.GetDesc() }.Width; + if !buffer_view_ok(desc.Format, first, count, stride, raw, width) { + REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); once!( - offset, - element, - "buffer view not on an element of its host copy" + format = desc.Format.0, + first, + count, + stride, + raw, + width, + "buffer view the host would refuse left null" ); return None; } - buffer.FirstElement += offset / element; + // The console has no component mapping; one the host does not know is the default's. + if desc.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING { + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + } let host = host()?; // SAFETY: a live buffer and a slot of our heap. unsafe { @@ -553,12 +1654,45 @@ fn buffer_uav( crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) }; let offset = shadow.offset(address); - if element == 0 || offset % element != 0 { - once!(offset, element, "unordered buffer view not on an element of its host copy"); + // A structured view as a raw view of the same bytes (see `raw_window`). + let window = (desc.Format == DXGI_FORMAT_UNKNOWN) + .then(|| raw_window(offset, buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride)) + .flatten(); + if let Some((first, count)) = window { + buffer.FirstElement = first; + buffer.NumElements = count; + buffer.StructureByteStride = 0; + buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + } else { + if element == 0 || offset % element != 0 { + once!(offset, element, "unordered buffer view not on an element of its host copy"); + return None; + } + buffer.FirstElement += offset / element; + } + buffer.CounterOffsetInBytes = 0; + let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); + let raw = buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; + if window.is_some() { + // (Left out at first: every structured unordered access view was then + // refused by `buffer_view_ok` and left null, runs 15 and 16.) + desc.Format = DXGI_FORMAT_R32_TYPELESS; + } + // SAFETY: a live buffer. + let width = unsafe { shadow.buffer.GetDesc() }.Width; + if !buffer_view_ok(desc.Format, first, count, stride, raw, width) { + REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + once!( + format = desc.Format.0, + first, + count, + stride, + raw, + width, + "unordered buffer view the host would refuse left null" + ); return None; } - buffer.FirstElement += offset / element; - buffer.CounterOffsetInBytes = 0; let host = host()?; // SAFETY: a live buffer and a slot of our heap. unsafe { @@ -587,6 +1721,9 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere }; let own = d.Format.0 as u32; if !allowed || DEPTH_FORMATS.iter().any(|&(typed, _)| typed == own) { + if unordered { + crate::resource::DEPTH_UNORDERED[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } once!( unordered, format = own, @@ -609,6 +1746,14 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere if view == 0 { return !typeless; } + // A view of a target whose format the host refuses, in the title's + // format: in the stand-in the host copy has. + if view != own && crate::resource::target_format(view) == own { + if let Some(format) = format { + *format = d.Format; + } + return true; + } if family(view) != family(own) { once!(view, own, "view format of another family"); return false; @@ -621,6 +1766,73 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere true } +/// The title's unordered access view of a depth texture, as a view of the +/// texture's colour twin `twin` ([`crate::resource::Twin`]): the same mip +/// and slices, in the colour format of the twin's family for a depth or +/// typeless format (R16_UNORM for 16-bit depth, R32_FLOAT for 32-bit; the +/// bits are the same). Without a description: mip 0 of every slice. +/// The twin of a stencil plane (R8) stands for the views of that plane +/// only, which become R8_UINT views of its one plane; `None` for a view of +/// the depth plane, which the twin does not stand for. The depth plane has +/// a twin of its own, viewed as a depth texture's without stencil: a view +/// in the format of the depth plane of a depth-stencil format (21, 46) +/// takes the twin's colour format too. +fn twin_uav( + twin: &ID3D12Resource, + desc: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>, +) -> Option { + // SAFETY: a live resource. + let d = unsafe { twin.GetDesc() }; + let mut desc = desc.cloned().unwrap_or_else(|| { + let mut all = D3D12_UNORDERED_ACCESS_VIEW_DESC { + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + if d.DepthOrArraySize > 1 { + all.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + all.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { + ArraySize: u32::from(d.DepthOrArraySize), + ..Default::default() + }; + } + all + }); + // A stencil plane's twin (R8 typeless, 60): the title's view is of the + // stencil plane if it names plane 1 or a stencil view format (22, 47). + if d.Format.0 == 60 { + let mut plane = 0; + match desc.ViewDimension { + D3D12_UAV_DIMENSION_TEXTURE2D => { + // SAFETY: the member the dimension names. + let mut view = unsafe { desc.Anonymous.Texture2D }; + plane = std::mem::take(&mut view.PlaneSlice); + desc.Anonymous.Texture2D = view; + } + D3D12_UAV_DIMENSION_TEXTURE2DARRAY => { + // SAFETY: the member the dimension names. + let mut view = unsafe { desc.Anonymous.Texture2DArray }; + plane = std::mem::take(&mut view.PlaneSlice); + desc.Anonymous.Texture2DArray = view; + } + _ => {} + } + if plane != 1 && !matches!(desc.Format.0, 22 | 47) { + return None; + } + desc.Format.0 = 62; + return Some(desc); + } + // None, typeless and depth formats (R16: 0, 53, 55; R32: 0, 39, 40), + // and those of a depth-stencil format's depth plane (19 to 21, 44 to + // 46), for the twin of such a plane. + desc.Format.0 = match (desc.Format.0, d.Format.0) { + (0 | 53 | 55 | 19..=21 | 44..=46, 53) => 56, + (0 | 39 | 40 | 19..=21 | 44..=46, 39) => 41, + (other, _) => other, + }; + Some(desc) +} + /// Makes the host descriptor for `view` at `at`: the host resource it /// views, or `None` if it cannot. fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { @@ -679,7 +1891,37 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { _ => None, }; }; + // The first such views of depth textures are logged as the + // title describes them (format, dimension, then mip, slices and + // plane): they say which planes shaders write, and as what. + if crate::resource::depth_and_unordered(resource) { + static LOGGED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if LOGGED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 512 { + tracing::info!( + ?resource, + view = ?desc, + "unordered access view of a depth texture" + ); + } + } let mut desc = desc.as_ref().map(uav_desc); + // A depth texture's unordered access is its colour twin's: the + // host gives a depth texture none. + let twin = crate::resource::twin_resource(resource) + .and_then(|twin| Some((twin, twin_uav(twin, desc.as_ref())?))) + // A view of the depth plane of a texture with a stencil + // plane: of that plane's own twin. + .or_else(|| { + let twin = crate::resource::twin_plane_resource(resource)?; + Some((twin, twin_uav(twin, desc.as_ref())?)) + }); + let texture = match twin { + Some((twin, view)) => { + desc = Some(view); + twin + } + None => texture, + }; if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) { return None; } @@ -736,6 +1978,30 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { } } +/// Writes of a slot with another view of the placed texture it showed, +/// since the start: the slot kept showing the old view. +pub(crate) static KEPT_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether a slot written with another view of the placed texture it +/// shows keeps showing the old one until the new is made; +/// `VICTORY_KEEP_VIEWS=0` makes it null at once, as before. +fn keep_views() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0")) +} + +/// Whether both are shader views of one texture the title placed in +/// memory: the same address and the same resource description, whatever +/// part of it each shows. +fn same_placed_texture(a: &View, b: &View) -> bool { + match (a, b) { + (View::Placed(false, resource, desc), View::Placed(false, other, other_desc)) => { + resource[0] != 1 && resource == other && desc[10..12] == other_desc[10..12] + } + _ => false, + } +} + /// A shader view of a texture the title placed in memory itself, as a view /// of the resource made for that memory (on first use). pub(crate) fn placed_texture(view: &View) -> Option { @@ -943,6 +2209,32 @@ mod tests { assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D); } + /// Views of one placed texture are told from views of others by the + /// address and the resource description, not by what they show. + #[test] + fn views_of_one_placed_texture_are_told_by_address_and_description() { + let texture = [3, 0, 0, 0, 512, 0, 512, 0x8_0001, 98, 1, 0, 0x105, 0, 0]; + let view = |resource: [u32; 14], first_mip: u32, address: u32| { + let mut desc = [0u32; 16]; + (desc[0], desc[1], desc[4], desc[5], desc[10], desc[11]) = (98, 4, first_mip, 8 - first_mip, address, 0xb); + View::Placed(false, resource, desc) + }; + let low = view(texture, 3, 0x1000_0000); + // more mips of the same texture + assert!(same_placed_texture(&low, &view(texture, 0, 0x1000_0000))); + // another address, another description, a buffer, an unordered view + assert!(!same_placed_texture(&low, &view(texture, 3, 0x2000_0000))); + let mut wider = texture; + wider[4] = 1024; + assert!(!same_placed_texture(&low, &view(wider, 3, 0x1000_0000))); + let mut buffer = texture; + buffer[0] = 1; + assert!(!same_placed_texture(&view(buffer, 3, 0x1000_0000), &view(buffer, 3, 0x1000_0000))); + let View::Placed(_, resource, desc) = low.clone() else { unreachable!() }; + assert!(!same_placed_texture(&low, &View::Placed(true, resource, desc))); + assert!(!same_placed_texture(&low, &View::Shader(0, None))); + } + /// A null 3D UAV made on the real device leaves it alive. #[test] fn null_3d_uav_is_accepted_by_the_device() { @@ -959,6 +2251,187 @@ mod tests { } /// Dynamic slots stay taken until given back, and runs do not wrap. + #[test] + fn a_structured_view_made_raw_passes_the_host_check() { + // 100 elements of 20 bytes from element 8, in a copy that starts 32 + // bytes before the view's memory: bytes 192..2192. + let (first, count) = raw_window(32, 8, 100, 20).unwrap(); + assert_eq!((first, count), (48, 500)); + assert!(buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 4096)); + // the format a raw view must name; the structured one's is refused + assert!(!buffer_view_ok(DXGI_FORMAT_UNKNOWN, first, count, 0, true, 4096)); + // past the buffer, not on 16 bytes, no elements + assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 2000)); + assert!(raw_window(4, 0, 100, 20).is_none()); + assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, 0, 0, 0, true, 4096)); + // a structured view the host takes as it is + assert!(buffer_view_ok(DXGI_FORMAT_UNKNOWN, 1, 10, 12, false, 4096)); + } + + /// The queue of textures picked by index serves the slots looked at + /// before first, then the newest write and the oldest in turns; a + /// slot whose memory is not there is looked at again after + /// 1, 2, 4 frames up to the limit; and what the pass reports about a + /// slot written again meanwhile is dropped. + #[test] + fn the_texture_queue_serves_the_newest_writes_first() { + let mut q = TextureQueue::default(); + // Slots 10..18 written in frames 1..9, slot 5 last. + for i in 0..8u32 { + q.written(10 + i, u64::from(i) + 1, 0, false); + } + q.written(5, 9, 0, false); + let order: Vec = q.due(9, 100).into_iter().map(|d| d.0).collect(); + // newest, oldest, newest, oldest, and so on + assert_eq!(order, [5, 10, 17, 11, 16, 12, 15, 13, 14]); + assert_eq!(q.due(9, 2).len(), 2); + assert_eq!(q.census(9), [9, 9, 0, 0, 8]); + // Slot 17's memory is not mapped: again next frame, then in 2, 4, 4. + let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1; + let w17 = write(&q, 17); + let mut frame = 9; + for wait in [1, 2, 4, 4] { + q.later(17, w17, frame, 4); + assert!(!q.due(frame + wait - 1, 100).iter().any(|d| d.0 == 17)); + frame += wait; + // Due again, and ahead of every slot never looked at. + assert_eq!(q.due(frame, 100)[0].0, 17); + } + assert_eq!(q.census(9)[2], 1); + q.done(17, w17); + assert!(!q.due(u64::MAX, 100).iter().any(|d| d.0 == 17)); + // Uploaded with part of its memory there: kept, with what was there. + let w16 = write(&q, 16); + q.partly(16, w16, 12, 4096); + assert_eq!(q.mapped(16), 4096); + assert_eq!(q.due(12, 100)[0].0, 16); + // The title writes slot 16 again while the pass works on it: what + // the pass then says about the old write changes nothing. + q.written(16, 13, 0, false); + q.done(16, w16); + q.later(16, w16, 13, 4); + assert_eq!(q.mapped(16), 0); + assert_eq!(q.due(13, 100)[0].0, 16); + // A draw that makes the host slot (`seen`) keeps what the queue knows, + let w15 = write(&q, 15); + q.partly(15, w15, 20, 8192); + q.written(15, 14, 0, true); + assert_eq!(q.mapped(15), 8192); + // and queues a slot the queue did not hold. + q.written(99, 14, 0, true); + assert!(q.due(14, 100).iter().any(|d| d.0 == 99)); + // A write due later (a table's slot) is not handed out before. + q.written(98, 14, 16, false); + assert!(!q.due(15, 100).iter().any(|d| d.0 == 98)); + assert!(q.due(16, 100).iter().any(|d| d.0 == 98)); + } + + /// A view written over memory that older views describe otherwise + /// makes those stale; views of the same span are one texture's. + #[test] + fn a_newer_view_of_other_memory_makes_the_older_stale() { + let mut spans = Spans::default(); + // Three textures side by side, the first in two slots. + assert!(spans.note(1, 0x1000, 0x3000, true).is_empty()); + assert!(spans.note(2, 0x1000, 0x3000, true).is_empty()); + assert!(spans.note(3, 0x3000, 0x4000, true).is_empty()); + assert!(spans.note(4, 0x8000, 0x9000, true).is_empty()); + // The same slot written with the same span again: nothing changes. + assert!(spans.note(2, 0x1000, 0x3000, true).is_empty()); + assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]); + assert_eq!(spans.slots_in(0x4000, 0x8000), [] as [u32; 0]); + // A draw makes a slot whose view overlaps them: left out, nothing stale. + assert!(spans.note(9, 0x2000, 0x3800, false).is_empty()); + assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]); + // The title writes a texture over the end of the first and all of + // the second: their three slots are stale. + let mut stale = spans.note(5, 0x2000, 0x4000, true); + stale.sort_unstable(); + assert_eq!(stale, [1, 2, 3]); + assert_eq!(spans.slots_in(0, u64::MAX), [5, 4]); + // Another start in the same memory: stale in turn. Another length + // from the same start too. + assert_eq!(spans.note(6, 0x2800, 0x3000, true), [5]); + assert_eq!(spans.note(7, 0x2800, 0x2c00, true), [6]); + // A slot that moves to another texture leaves its span behind. + assert!(spans.note(7, 0x8000, 0x9000, true).is_empty()); + assert_eq!(spans.slots_in(0x2800, 0x2c00), [] as [u32; 0]); + assert_eq!(spans.slots_in(0x8000, 0x8001), [4, 7]); + spans.forget(4); + spans.forget(7); + assert!(spans.by_start.is_empty() && spans.by_slot.is_empty()); + } + + /// Memory the runtime maps under a slot's texture makes the slot due + /// again from the next frame; a stale slot leaves the queue. + #[test] + fn remapped_memory_makes_its_texture_slots_due() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + // 64x64 BC7, one mip, at an address no test and no title uses. + let at = 0x7fee_0000_0000u64; + let view = |address: u64, width: u32| { + let mut desc = [0u32; 16]; + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + View::Placed(false, [3, 0, 0, 0, width, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc) + }; + let len = crate::resource::placed_bytes(&[3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0]).unwrap(); + assert!(heap.note_buffer(1, Some(&view(at, 64)), false).is_empty()); + let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0]; + assert_eq!(queued, 1); + heap.texture_slot_done(1, write, None); + assert_eq!(slots(u64::MAX), []); + // Memory elsewhere: nothing. Under the texture: due from the next frame. + remapped((at + 2 * len) as usize, 0x1000); + remapped(at as usize, 0x1000); + assert_eq!(heap.texture_slots_remapped(50), 1); + 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!(slots(u64::MAX), [2]); + } + + /// 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. + #[test] + fn slots_read_through_tables_leave_the_texture_queue() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + let frame = 100; + let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + let texture = View::Placed(false, [3, 0, 0, 0, 4, 0, 4, 0x1_0001, 28, 1, 0, 0x105, 0, 0], [0; 16]); + assert!(is_texture_view(&texture)); + heap.queue_texture(2, true, false, frame); + heap.queue_texture(3, true, false, frame); + assert_eq!(slots(frame), [3, 2]); + heap.tabled_in(3, true, frame); + assert_eq!(slots(frame), [2]); + // Made in place by the draw that read it: still out. + heap.queue_texture(3, true, true, frame); + assert_eq!(slots(frame), [2]); + // Written again in the next frame: due once the grace frames have + // passed without a draw that reads it. + heap.queue_texture(3, true, false, frame + 1); + assert_eq!(slots(frame + TABLED_GRACE), [2]); + assert_eq!(slots(frame + 1 + TABLED_GRACE), [3, 2]); + // The draw comes after all: out again. + heap.tabled_in(3, true, frame + 1); + assert_eq!(slots(u64::MAX), [2]); + // A slot of a table no draw read stays queued; its next write waits. + heap.tabled_in(2, false, frame + 1); + assert_eq!(slots(frame + 1), [2]); + heap.queue_texture(2, true, false, frame + 2); + assert_eq!(slots(frame + 2), []); + // Long after the last table, a write is due at once. + heap.queue_texture(2, true, false, frame + 3 + TABLED_FRAMES); + assert_eq!(slots(frame + 3 + TABLED_FRAMES), [2]); + } + #[test] fn dynamic_slots_are_held_until_released() { let Some(heap) = HostHeap::new(false, 4) else { diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index cce7ed2..0de7f02 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -346,6 +346,59 @@ fn feature_levels(data: *mut c_void) -> HRESULT { } } +/// Device methods 0x1c8 and 0x218 (`SLOT`). Grand Theft Auto VI calls both +/// (title+0x2477578 and title+0x24800d5) as `(this, description, interface +/// id, out)`, asks for `ID3D12PipelineState`, and on success keeps the +/// object `out` names and draws with it; on failure it goes without that +/// pipeline, silently. What the descriptions hold is not known: the calls +/// fail as they always did, with `out` null, and the first ones log the +/// description's words and what its first word points at, so that the two +/// methods can be written. +/// shortcut: not implemented. Answering `S_OK` here without making the +/// pipeline would hand the title whatever its stack held as an object. +extern "system" fn unknown_pipeline( + _: This, + desc: *const u8, + _iid: *const Iid, + out: *mut This, +) -> HRESULT { + use std::sync::atomic::{AtomicU32, Ordering}; + static CALLS: [AtomicU32; 2] = [const { AtomicU32::new(0) }; 2]; + let calls = CALLS[usize::from(SLOT == 0x218)].fetch_add(1, Ordering::Relaxed) + 1; + if !out.is_null() { + // SAFETY: the title's out pointer (a local of its own). + unsafe { *out = std::ptr::null() }; + } + if calls <= 4 || calls.is_power_of_two() { + // Sixteen 64-bit words at `at`, read through the kernel: neither + // pointer is known to be mapped. + #[cfg(windows)] + let words = |at: usize| -> Option> { + let mut bytes = [0u8; 128]; + (at != 0 && crate::host::read_into(at as *const u8, &mut bytes)).then(|| { + bytes + .chunks_exact(8) + .map(|c| c.iter().rev().fold(0u64, |v, &b| v << 8 | u64::from(b))) + .collect() + }) + }; + #[cfg(not(windows))] + let words = |_: usize| None::>; + let description = words(desc as usize); + let first = description + .as_ref() + .and_then(|w| words(w[0] as usize)); + tracing::warn!( + slot = format_args!("{:#x}", SLOT), + calls, + description = format_args!("{description:x?}"), + first_points_at = format_args!("{first:x?}"), + "a pipeline creation method that is not implemented: the title goes without this pipeline" + ); + } + E_NOTIMPL +} + /// IUnknown 3, object methods 4, device methods 76 (0x18-0x290), then the /// methods `ID3D12Device1` to `ID3D12Device8` add, in order: 3, 1, 3, 6, 9, /// 1, 2, 9 (0x298-0x3a0, the console's own among them), then those of @@ -382,8 +435,10 @@ static FUNCTIONS: Table<160> = { f[39] = query::create as *const (); // 0x138 f[41] = signature::create as *const (); // 0x148 f[48] = queue::create_x as *const (); // 0x180 + f[57] = unknown_pipeline::<0x1c8> as *const (); // 0x1c8 f[61] = descriptor::create_sampler_x as *const (); // 0x1e8 f[62] = pipeline::create_compute_x as *const (); // 0x1f0 + f[67] = unknown_pipeline::<0x218> as *const (); // 0x218 f[69] = object::ignore as *const (); // 0x228 debug error filter f[70] = descriptor::create_placed_srv as *const (); // 0x230 f[71] = descriptor::create_placed_uav as *const (); // 0x238 diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index d2537cc..f9937b1 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -10,6 +10,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; +use victory_shader::resource::RootIndexedView; use victory_shader::{ResourceType, RootType, UsedResource}; use crate::descriptor::View; @@ -51,6 +52,100 @@ pub(crate) struct IndexView { format: u32, } +/// Host states of a depth target, and of a texture shaders read. +const DEPTH_WRITE: u32 = 0x10; +const DEPTH_READ: u32 = 0x20; +const SHADER_RESOURCE: u32 = 0x40 | 0x80; + +thread_local! { + /// While a draw is prepared (`State::bind`, then its targets' states): + /// the depth target the draw only tests (0: none, or one it writes), + /// and whether a view its shaders read is of that same texture. + static TESTED_DEPTH: std::cell::Cell<(usize, bool)> = + const { std::cell::Cell::new((0, false)) }; + /// While a stage's tables are walked (`State::tables`): whether that + /// stage's shader can store to buffers (`Translated::stores`). + static STORES: std::cell::Cell = const { std::cell::Cell::new(true) }; +} + +/// Whether a buffer range a shader names through an unordered access view +/// is given to shaders as written (snapshot before the submission, compare +/// and write back after) only if that shader's code can store to buffers. +/// The title binds buffers its shaders only read through such views, and +/// every range declared costs a snapshot and a compare of its bytes: 3.97 +/// GB a frame in 31 submissions, 0.49 s of snapshots and 0.28 s of +/// comparing (run 28). On by default; `VICTORY_WRITE_SKIP=0` declares +/// every such range, as before. +fn write_skip() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WRITE_SKIP").is_none_or(|v| v != "0")) +} + +/// A run of indirect records clamped in one pass ([`windows`]): the host +/// copy they came from (its number), their kind and stride, the offset of +/// the first in that copy, how many, and the list's scratch buffer that +/// holds them clamped, record `i` at `i * step`. +#[derive(Clone)] +struct Window { + copy: u64, + kind: u32, + stride: u32, + /// How far apart the records are in the copy, and in the scratch + /// buffer: what the title walks them by ([`windows`]). + step: u32, + base: u64, + records: u32, + scratch: ID3D12Resource, +} + +/// The most records clamped in one pass ([`windows`]). +const WINDOW_MOST: u64 = 64; + +/// Whether indirect draws that read record after record of one argument +/// buffer are clamped a window at a time (`VICTORY_INDIRECT_WINDOW=1`; off +/// by default). +/// +/// The title issues its mesh draws one record per call, each from the next +/// slot of the same argument buffer: 3,460 a frame in gameplay, and before +/// each our clamp ran as a compute dispatch of its own between two waits, +/// so the card went from drawing to compute and back for every record. In +/// the timing run of the lit scene (run 79) a shadow draw of next to +/// nothing cost 14-16 microseconds, 4,126 records a frame. +/// +/// With the switch, when a draw asks for a record a short step after the +/// one drawn before, the clamp takes that record and the ones that step +/// apart after it (16, then twice as many each time, [`WINDOW_MOST`] at +/// most, never past the buffer) into +/// the list's scratch buffer in one pass, and the draws that follow read +/// their record there with no pass of ours, until one of these: a compute +/// dispatch, a direct draw, an indirect call with a count buffer or more +/// than one record, a draw whose shaders can store to buffers, a record +/// outside the window, another host list. +/// +/// The step is the one the title is seen to take, not the stride its +/// command signature names: it draws one record a call, for which the +/// stride means nothing, and Grand Theft Auto VI names 12 bytes (the three +/// words of a mesh dispatch) for records it keeps 32 bytes apart (2,173 of +/// a frame's 3,349 mesh records in run 87's listed frame; 283 are 16 +/// apart, which ends a window). Walked by the named stride the window +/// never opened: run 87, with the switch, still clamped 5,068 records a +/// frame one at a time. +/// +/// What it costs the guard against garbage records: nothing against a +/// hang (every record is bounded as before and charged to the list's +/// budget as before), but the budget is charged when a window is clamped, +/// so also for records of the window's tail that are never drawn. Those +/// hold garbage in this title (slots of all ones: run 93 spent lists' +/// budgets on them and emptied the draws after), so in a window a record +/// that asks for more than can run is left empty and charges nothing +/// (`crate::indirect::bound_ahead`); a tail record that looks real is +/// charged what it asks, a few thousand of 2^27. And arguments the title's CPU side changes are seen as +/// before, at the next submission. +fn windows() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1")) +} + /// What one title list has set, and what its host list was last given. #[derive(Default)] pub(crate) struct State { @@ -64,21 +159,45 @@ pub(crate) struct State { /// Bound render target and depth resources, for their host states. targets: Vec, depth: usize, + /// The host state the bound depth view needs ([`depth_state`]). + depth_state: u32, /// The title's primitive topology (the host's may differ). topology: u32, + /// What the title set that goes straight onto the host list, kept for + /// the host list that continues this one after a cut ([`State::replay`]): + /// whether a topology was set, the render target and depth handles, the + /// viewports, the scissors, the blend factor and the stencil reference. + topology_set: bool, + target_handles: Vec, + depth_handle: u64, + targets_set: bool, + viewports: Vec, + scissors: Vec, + blend: Option<[f32; 4]>, + stencil: Option, + /// The indirect records clamped last, if later draws may still read + /// them ([`windows`]). + window: Option, /// What the host list has: pipeline, root signature, heaps. host_pipeline: usize, /// Graphics, compute. host_roots: [usize; 2], host_heaps: [usize; 2], - /// Tables made afresh in this list: (table, what it holds) → first + /// Tables made afresh in this list: (table, slot count, contents) → first /// dynamic slot. - fresh_tables: std::collections::HashMap<(u64, u64), u32>, + fresh_tables: std::collections::HashMap<(u64, u32, u64), u32>, /// The dynamic slots the list holds: title heap, first, count; given - /// back when the list is reset or released. + /// back when the list has run, is reset or released. dynamic: Vec<(usize, u32, u32)>, - /// A fresh table of the stage being bound could not be made. - table_failed: bool, + /// Root SRVs bound as one-view tables in this list: (title heap, title + /// address; 0 for none) → dynamic slot, and the host copy the slot + /// shows: later draws of the list bring that one up to date, whatever + /// copy the address would find by then (`shadow.rs` `tails`). + root_srv_slots: std::collections::HashMap<(usize, u64), RootSlot>, + /// Root UAVs bound as one-view tables in this list, likewise. + root_uav_slots: std::collections::HashMap<(usize, u64), RootSlot>, + /// The list ran and its dynamic slots were given back. + tables_gone: bool, } impl Drop for State { @@ -89,6 +208,84 @@ impl Drop for State { } } +impl State { + /// The list's submission has run (submissions are waited for): the + /// dynamic slots its tables were made in are given back, not kept + /// until the title resets the list. A frame of the opening cutscene + /// asks for 12,500 tables; held until the resets they ran the 131,072 + /// slots out, and up to 4,900 draws a frame went without their tables. + /// shortcut: a list the title runs a second time without a reset then + /// reads slots others may have taken (logged once). + pub(crate) fn tables_done(&mut self) { + if self.tables_gone && self.dynamic.is_empty() { + return; + } + if self.tables_gone { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("a list ran again after its descriptor tables were given back")); + } + for (heap, first, n) in self.dynamic.drain(..) { + crate::descriptor::release_dynamic(heap, first, n); + } + self.fresh_tables.clear(); + self.root_srv_slots.clear(); + self.root_uav_slots.clear(); + self.tables_gone = true; + } +} + +/// An experiment on the title's scissor rectangles (`VICTORY_SCISSOR_TEST=full`): +/// they are all widened to the whole target. Grand Theft Auto VI's room at +/// the start of the prologue lost its walls in five runs of seven, and in +/// those runs the player's body and the world outside were cut by one +/// rectangle around the window (run 85, frame 2046): one run with this on +/// says whether the walls are drawn and cut away by such a rectangle, or +/// not drawn at all. Off by default: a rectangle the title sets is part of +/// its picture. +fn scissor_test() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_SCISSOR_TEST").as_deref() == Ok("full")) +} + +/// An experiment on mesh draws (`VICTORY_MESH_TEST`): 1 for `skip` (none +/// is issued), 2 for `scissor` (each runs its shaders but rasterises one +/// pixel), 0 otherwise. It tells a card hung by a mesh shader from one hung +/// by what the shader's triangles cover. +fn mesh_test() -> u8 { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var("VICTORY_MESH_TEST").as_deref() { + Ok("skip") => 1, + Ok("scissor") => 2, + _ => 0, + }) +} + +/// `VICTORY_MESH_TEST=keep:[:]`: only the mesh +/// draws whose mesh shader's hash ends in one of the first digits (and +/// whose digit before it is one of the second, if given) are issued: a +/// search for the shaders that stop the card. +fn mesh_kept(pipeline: usize) -> bool { + static KEEP: std::sync::OnceLock> = std::sync::OnceLock::new(); + let Some((last, before)) = KEEP.get_or_init(|| { + let value = std::env::var("VICTORY_MESH_TEST").ok()?; + let mut parts = value.strip_prefix("keep:")?.split(':'); + Some((parts.next()?.to_owned(), parts.next().unwrap_or("").to_owned())) + }) else { + return true; + }; + let Some(p) = crate::pipeline::host_pipeline(pipeline as This) else { + return true; + }; + let Some(at) = p.name.find("mesh ") else { + return true; + }; + let hash = p.name[at + 5..].as_bytes(); + if hash.len() < 16 { + return true; + } + last.as_bytes().contains(&hash[15]) && (before.is_empty() || before.as_bytes().contains(&hash[14])) +} + /// Draws recorded on the host GPU since the last frame line. static DRAWN: AtomicU64 = AtomicU64::new(0); @@ -113,6 +310,44 @@ pub(crate) fn take_frame() -> Vec { pub(crate) fn take_dropped() -> u64 { DROPPED.swap(0, Ordering::Relaxed) } +/// A root SRV's dynamic slot in a list, and the host copy it shows. +type RootSlot = (u32, Option>); + +/// Buffer views of the heap whose slot showed another host buffer than +/// the copy the pass brought up to date for them, since the start +/// (diagnostics; for the memory line). It stays 0 while the pass and the +/// slots agree; with `VICTORY_VIEW_EXTENT=0` it counts the views that were +/// read stale. +#[cfg(feature = "diagnostics")] +pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0); +/// Passes over the view heap's buffer views for shaders that pick them by +/// index ([`State::heap_buffers`]), and the microseconds they took. +pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0); +pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0); +/// Textures brought up to date for shaders that pick them by index +/// ([`State::heap_textures`]), the bytes of their memory, and the slots +/// still waiting. +pub(crate) static HEAP_TEXTURES: AtomicU64 = AtomicU64::new(0); +pub(crate) static HEAP_TEXTURE_BYTES: AtomicU64 = AtomicU64::new(0); +pub(crate) static HEAP_TEXTURES_WAITING: AtomicU64 = AtomicU64::new(0); +/// Passes that made no texture because the card had no room +/// (`crate::resource::room`), for the memory line. +pub(crate) static HEAP_TEXTURES_FULL: AtomicU64 = AtomicU64::new(0); +/// Times a placed texture's slot was passed over because its memory is not +/// mapped. +pub(crate) static HEAP_TEXTURES_AWAY: AtomicU64 = AtomicU64::new(0); +/// Slots the pass found up to date already: their texture is uploaded by +/// the draws that read it through a table (it has a staging buffer). +pub(crate) static HEAP_TEXTURES_TABLED: AtomicU64 = AtomicU64::new(0); +/// The queue of textures picked by index at the last pass +/// (`TextureQueue::census`): slots in it, due, waiting for their memory, +/// uploaded in part, and the frames the oldest due one has waited. +pub(crate) static HEAP_TEXTURES_QUEUE: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; +/// Since the start: looks at a slot uploaded in part that found no more of +/// its memory mapped; uploads of textures not all mapped; and of those, +/// the ones whose first page was not there (asked by the first page alone, +/// as before, they counted as not there at all). +pub(crate) static HEAP_TEXTURES_PARTLY: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; static DROPPED: AtomicU64 = AtomicU64::new(0); /// Marks the last traced draw as not run on the host. @@ -134,13 +369,24 @@ pub(crate) fn dispatched() -> u64 { /// The host address of a root view: its buffer's host copy, or for a /// constant buffer not 256-byte aligned there (the console needs 16) a /// copy in upload memory. -/// shortcut: a root view has no size; constant buffers are taken as 64 KiB, -/// other views as 1 MiB (both cut at their buffer's end). +/// shortcut: a root view has no size; constant buffers are taken as 64 KiB +/// (cut at their buffer's end), other views as all that is left of their +/// buffer. (They were taken as 1 MiB: 1,452 of the 2,021 mesh vertex +/// streams of a cutscene frame reach further, and what lay past the first +/// megabyte was never brought up to date - meshes without bodies, exploded +/// triangles. `VICTORY_ROOT_VIEW_MB` sets a limit again.) fn root_view(list: &HostList, address: u64, srv: bool) -> Option { + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + std::env::var("VICTORY_ROOT_VIEW_MB") + .ok() + .and_then(|v| v.parse::().ok()) + .map_or(u64::MAX, |mb| mb << 20) + }); let shadow = crate::shadow::find(address, 1)?; let len = shadow .left(address) - .min(if srv { 1 << 20 } else { 1 << 16 }); + .min(if srv { limit } else { 1 << 16 }); let gpu = shadow.gpu(address); if srv || gpu % 256 == 0 { shadow.refresh(list, address, len); @@ -176,6 +422,7 @@ impl State { /// [`crate::primitive`]). pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) { self.topology = topology; + self.topology_set = true; let host = match topology { RECTANGLES => 4, TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => { @@ -259,6 +506,10 @@ impl State { let Some(host) = crate::host::host() else { return; }; + self.target_handles.clear(); + self.target_handles.extend_from_slice(handles); + self.depth_handle = depth; + self.targets_set = true; self.targets.clear(); let mut rtvs = Vec::new(); for &h in handles { @@ -270,17 +521,34 @@ impl State { continue; }; let Some(texture) = crate::resource::host_resource(record.resource) else { + // A typed null view (or a target without a host copy) still + // takes its slot: left out, the next live target would move + // into it and the pixel shader's outputs reach the wrong + // targets. + // shortcut: a view without a description or a format has no + // null view to stand for it and is left out, as before. + let null = record + .desc() + .filter(|d| d.Format.0 != 0 && d.ViewDimension.0 != 0); + if let Some(desc) = null { + rtvs.push(host.rtv(None, Some(&desc))); + } continue; }; self.targets.push(record.resource as usize); #[cfg(feature = "diagnostics")] crate::capture::note_target(record.resource); - rtvs.push(host.rtv(texture, record.desc().as_ref())); + rtvs.push(host.rtv(Some(texture), record.desc().as_ref())); } self.depth = 0; + self.depth_state = DEPTH_WRITE; let dsv = crate::descriptor::dsv_record(depth).and_then(|record| { let texture = crate::resource::host_resource(record.resource)?; self.depth = record.resource as usize; + self.depth_state = depth_state(texture, record.depth_desc().as_ref()); + if crate::resource::depth_and_unordered(record.resource) { + crate::resource::DEPTH_UNORDERED[1].fetch_add(1, Ordering::Relaxed); + } #[cfg(feature = "diagnostics")] crate::capture::note_target(record.resource); Some(host.dsv(texture, record.depth_desc().as_ref())) @@ -296,6 +564,81 @@ impl State { }; } + /// Viewports, scissors, the blend factor and the stencil reference: set + /// on the host list at once, and kept for [`State::replay`]. + pub(crate) fn set_viewports(&mut self, list: &HostList, viewports: &[D3D12_VIEWPORT]) { + self.viewports.clear(); + self.viewports.extend_from_slice(viewports); + crate::draw::viewports(list, viewports); + } + + pub(crate) fn set_scissors(&mut self, list: &HostList, rects: &[RECT]) { + self.scissors.clear(); + self.scissors.extend_from_slice(rects); + if scissor_test() { + // The experiment: every rectangle the title sets is widened to + // the largest target there is, so nothing is cut by one. What + // the listing shows (`op_text`) stays the title's own. + let full = RECT { + left: 0, + top: 0, + right: 16384, + bottom: 16384, + }; + crate::draw::scissors(list, &vec![full; rects.len()]); + return; + } + crate::draw::scissors(list, rects); + } + + pub(crate) fn set_blend_factor(&mut self, list: &HostList, factor: Option<&[f32; 4]>) { + self.blend = factor.copied(); + crate::draw::blend_factor(list, factor); + } + + pub(crate) fn set_stencil_ref(&mut self, list: &HostList, reference: u32) { + self.stencil = Some(reference); + crate::draw::stencil_ref(list, reference); + } + + /// `list` is a new host list that continues the title's list (it was + /// cut at a wait for a memory value, `crate::list::cut`): a new host + /// list has nothing set, so what the title set so far is set again. + /// The pipeline, the root signatures and the heaps are set by the next + /// draw or dispatch (`bind`, which is told here that the host list has + /// none); root arguments, vertex and index buffers are set by every + /// draw anyway. The dynamic descriptor slots and the tables made in + /// them stay: the parts before the cut have not run yet, and they are + /// given back when the title's list is reset. + /// shortcut: the render target views are made again from the handles' + /// descriptors as they are now, not as they were when the title set + /// the targets (a descriptor rewritten in between names another view). + pub(crate) fn replay(&mut self, list: &HostList) { + self.host_pipeline = 0; + self.host_roots = [0; 2]; + self.host_heaps = [0; 2]; + if self.topology_set { + self.set_topology(list, self.topology); + } + if self.targets_set { + let handles = std::mem::take(&mut self.target_handles); + self.set_targets(list, &handles, self.depth_handle); + } + if !self.viewports.is_empty() { + crate::draw::viewports(list, &self.viewports); + } + if !self.scissors.is_empty() { + let rects = std::mem::take(&mut self.scissors); + self.set_scissors(list, &rects); + } + if let Some(factor) = self.blend { + crate::draw::blend_factor(list, Some(&factor)); + } + if let Some(reference) = self.stencil { + crate::draw::stencil_ref(list, reference); + } + } + /// The user-data value of a root argument, as translated shaders read /// it: a table's byte offset in its heap, a constant's value. fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 { @@ -313,6 +656,8 @@ impl State { (Some(Root::Constants(c)), RootType::Constants) => { c.get(dword as usize).copied().unwrap_or(0) } + // The host's own ([`Self::host_word`]): no root argument. + (_, RootType::Other(_)) => 0, _ => { once!( slot, @@ -324,6 +669,73 @@ impl State { } } + /// A user-data dword the host computes for a translated shader + /// (`victory_shader::emit::USER_MEMORY_BASE`, `USER_VIEW_ADDRESS`). + fn host_word( + &self, + compute: bool, + kind: u32, + slot: u8, + dword: u32, + memory: Option<&crate::memory::Ready>, + ) -> u32 { + use victory_shader::emit::{USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS}; + if kind == USER_MEMORY_BASE { + return memory.map_or(0, |m| m.base); + } + if kind == USER_VIEW_BIAS { + // The view begins on 16 bytes of the copy the address finds + // (`root_uav`, `root_srv_table`). + // shortcut: found again here, not taken from the list's slot. + return match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::View(address)) => crate::shadow::find(address, 1).map_or(0, |s| { + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + ((s.gpu(address) - base) & 15) as u32 + }), + _ => 0, + }; + } + if kind != USER_VIEW_ADDRESS && kind != USER_VIEW_ADDRESS + 1 { + once!(kind, "a shader reads a host value this build does not know"); + return 0; + } + // The title address of the buffer view at that dword of the table. + let address = match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4) + .and_then(|view| crate::descriptor::host::buffer_range(&view)) + .map_or(0, |range| range.0), + _ => 0, + }; + if address == 0 { + once!(slot, dword, "a shader takes the address of a buffer view that is not there: it reads 0"); + } + if kind == USER_VIEW_ADDRESS { + address as u32 + } else { + (address >> 32) as u32 + } + } + + /// For a shader that reads title memory by address + /// ([`crate::memory`]): its directory, fault notes and view slots, + /// with the pages of the root views the list has set made ready. + fn memory_ready(&self, list: &HostList, compute: bool, writes: bool) -> Option { + let heap = match self.heaps[0] { + 0 => None, + h => crate::descriptor::heap(h as This).host(), + }?; + let (mut addresses, mut constants) = (Vec::new(), Vec::new()); + for root in self.roots_ref(compute) { + match root { + Root::View(address) => addresses.push(*address), + Root::Constants(values) => constants.extend_from_slice(values), + _ => {} + } + } + crate::memory::ready(list, heap, &addresses, &constants, writes) + } + /// The bound heap holding `handle`. fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> { self.heaps @@ -352,6 +764,10 @@ impl State { once!(mesh, "a draw or mesh dispatch with another kind of pipeline"); return false; } + if p.rects && self.topology != RECTANGLES { + // Its geometry stage would turn each triangle into a rectangle. + once!("a rectangle pipeline drawn with another topology"); + } if !self.bind(list, p, false) { return false; } @@ -367,7 +783,7 @@ impl State { if v.address == 0 || v.size == 0 { continue; } - let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else { + let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else { continue; }; shadow.refresh(list, v.address, u64::from(v.size)); @@ -385,7 +801,7 @@ impl State { } if indexed { let v = self.index; - let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else { + let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else { return false; }; shadow.refresh(list, v.address, u64::from(v.size)); @@ -398,12 +814,28 @@ impl State { unsafe { l.IASetIndexBuffer(Some(&view)) }; } const RENDER_TARGET: u32 = 0x4; - const DEPTH_WRITE: u32 = 0x10; for &t in &self.targets { crate::list::ensure_state(list, t as This, RENDER_TARGET); } if self.depth != 0 { - crate::list::ensure_state(list, self.depth as This, DEPTH_WRITE); + // A depth texture shaders also write: what they wrote, first. + list.twin_use(self.depth as This, false, true); + // A view that writes neither plane keeps the texture readable: + // the depth read state, together with the shader read states + // if this draw's shaders read the same texture (the write state + // put it out of the state those views need, and a move to it + // and back for every such draw). + let state = if self.depth_state == DEPTH_READ { + let (tested, read) = TESTED_DEPTH.get(); + if read && tested == self.depth { + DEPTH_READ | SHADER_RESOURCE + } else { + DEPTH_READ + } + } else { + DEPTH_WRITE + }; + crate::list::ensure_state(list, self.depth as This, state); } true } @@ -413,9 +845,9 @@ impl State { /// What draws and dispatches share: heaps, our root signature, the /// pipeline, and per stage the user data, root views and the /// descriptors its tables hold. - /// False if the draw or dispatch must not run: a table it reads could - /// not be made. - fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { + /// False if the draw or dispatch must not run: a root SRV it reads + /// could not be given a view. + pub(crate) fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { let l = &list.list; // Heaps first: a root signature with directly indexed heaps must be // set after them. @@ -433,6 +865,14 @@ impl State { self.host_heaps = self.heaps; self.host_roots = [0; 2]; } + // The depth target a draw only tests, for the views of it that the + // draw's shaders read (`readable`). + let tested = if !compute && self.depth_state == DEPTH_READ { + self.depth + } else { + 0 + }; + TESTED_DEPTH.set((tested, false)); let root = p.root.as_raw() as usize; if self.host_roots[usize::from(compute)] != root { // SAFETY: an open list and a live root signature. @@ -458,22 +898,35 @@ impl State { } for stage in &p.stages { let t = stage.translated(); - self.table_failed = false; - let made = self.tables(list, &t.used, compute); - if self.table_failed { - static DROPPED_TABLES: AtomicU64 = AtomicU64::new(0); - let n = DROPPED_TABLES.fetch_add(1, Ordering::Relaxed) + 1; - if n.is_power_of_two() { - tracing::warn!( - dropped = n, - "a draw or dispatch dropped: no dynamic slots for its tables" - ); - } + STORES.set(t.stores); + let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute); + STORES.set(true); + if made.iter().any(|m| m.1 == u32::MAX) { + once!("a draw whose descriptor table found no free slots is dropped"); return false; } + // What the shader stores through root views and raw addresses is + // copied back into title memory afterwards. + let writes = (t.stores || !write_skip()) + && !crate::pipeline::builder_quarantined(self.pipeline as This); + // Title memory by address: what the shader finds it by. + let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) { + let Some(ready) = self.memory_ready(list, compute, writes) else { + once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped"); + return false; + }; + Some(ready) + } else { + None + }; if let Some((param, dwords)) = stage.user_data { let mut values = vec![0u32; dwords as usize]; for u in &t.host.user_data { + if let RootType::Other(kind) = u.root { + values[u.index as usize] = + self.host_word(compute, kind, u.slot, u.dword, memory.as_ref()); + continue; + } let fresh = made .iter() .find(|m| m.0 == u.slot && u.root == RootType::Table); @@ -493,14 +946,72 @@ impl State { } for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] { for &(slot, param) in views { - let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) + if srv && slot == victory_shader::emit::SLOT_MEMORY { + // Ours: the directory of title memory by address. + if let Some(m) = &memory { + // SAFETY: an open list; the directory lives as + // long as the process and the list holds it. + unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, m.directory); + } else { + l.SetGraphicsRootShaderResourceView(param, m.directory); + } + } + } + continue; + } + if srv && slot == victory_shader::emit::SLOT_STRIDES { + // Ours, not the title's: the shader picks buffers + // from the view heap by an index it computes. + match self.heap_buffers(list) { + // SAFETY: an open list; the table lives as long + // as the heap the list holds. + Some(gpu) => unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, gpu); + } else { + l.SetGraphicsRootShaderResourceView(param, gpu); + } + }, + None => once!("a shader picks buffers from a view heap that is not set"), + } + continue; + } + let tabled = srv && crate::pipeline::host::bounded_root_srvs(); + let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) else { once!(slot, "a shader reads a root view the title did not set"); + // A table left unset is undefined: a null view. + if tabled && !self.root_srv_table(list, None, param, compute, false) { + return false; + } continue; }; - let Some(gpu) = root_view(list, *address, srv) else { + // The shader adds the bytes a raw view begins early by. + let biased = srv + && t.host.user_data.iter().any(|u| { + u.slot == slot + && u.root == RootType::Other(victory_shader::emit::USER_VIEW_BIAS) + }); + if tabled { + if !self.root_srv_table(list, Some(address), param, compute, biased) { + return false; + } + continue; + } + let Some(mut gpu) = root_view(list, address, srv) else { continue; }; + if biased { + gpu -= u64::from(self.host_word( + compute, + victory_shader::emit::USER_VIEW_BIAS, + slot, + 0, + None, + )); + } // SAFETY: an open list; the address is in live memory. unsafe { match (compute, srv) { @@ -512,18 +1023,666 @@ impl State { } } } + for &(slot, param) in &stage.root_uavs { + if slot == victory_shader::emit::SLOT_FAULTS { + // Ours: where shaders note the pages they found empty. + if let Some(m) = &memory { + // SAFETY: an open list; the buffer lives as long as + // the process and the list holds it. + unsafe { + if compute { + l.SetComputeRootUnorderedAccessView(param, m.faults); + } else { + l.SetGraphicsRootUnorderedAccessView(param, m.faults); + } + } + } + continue; + } + let address = match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::View(address)) => Some(address), + _ => { + once!(slot, "a shader writes through a root view the title did not set"); + None + } + }; + if !self.root_uav(list, address, param, compute, writes) { + return false; + } + } + } + // Depth textures it writes through unordered access: their colour + // twins hold what they lack from here on. + list.twins_written(); + true + } + + /// Binds a root UAV: a raw unordered access view of the title buffer's + /// host copy from `address` on, as a one-view table (a null view + /// without an address, without a host copy shaders can write, or at an + /// address not on 16 bytes), or as a root descriptor with + /// `VICTORY_ROOT_SRV_DIRECT=1` (the dispatch is dropped then if there + /// is nothing to bind). With `writes`, what the shader stored is copied + /// back into title memory when the list has run. False if the draw + /// must be dropped. + /// shortcut: a root view has no size: the view, the refresh and the + /// copy back cover all that is left of the title's buffer + /// (`VICTORY_ROOT_UAV_MB` sets a limit for all three). + fn root_uav( + &mut self, + list: &HostList, + address: Option, + param: u32, + compute: bool, + writes: bool, + ) -> bool { + const UNORDERED: i32 = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0; + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + std::env::var("VICTORY_ROOT_UAV_MB") + .ok() + .and_then(|v| v.parse::().ok()) + .map_or(u64::MAX, |mb| mb << 20) + }); + let find = |a: u64| { + let s = crate::shadow::find(a, 1)?; + // SAFETY: a live buffer. + let flags = unsafe { s.buffer.GetDesc() }.Flags; + if flags.0 & UNORDERED == 0 { + once!("a root UAV of a buffer whose host copy shaders cannot write"); + return None; + } + Some(s) + }; + let ready = |a: u64, s: &std::sync::Arc| { + let len = s.left(a).min(limit); + s.refresh(list, a, len); + if writes { + s.gpu_writes(list, a, len); + } + }; + if !crate::pipeline::host::bounded_root_srvs() { + let Some((a, s)) = address.and_then(|a| Some((a, find(a)?))) else { + once!("a root UAV with nothing to bind: the draw is dropped"); + return false; + }; + ready(a, &s); + // From the 16 bytes below: the shader adds the rest. + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + let gpu = base + ((s.gpu(a) - base) & !15); + // SAFETY: an open list; the address is in a live buffer. + unsafe { + if compute { + list.list.SetComputeRootUnorderedAccessView(param, gpu); + } else { + list.list.SetGraphicsRootUnorderedAccessView(param, gpu); + } + } + return true; + } + let heap = match self.heaps[0] { + 0 => None, + h => Some(crate::descriptor::heap(h as This)), + }; + let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else { + once!("a root UAV without a bound view heap: the draw is dropped"); + return false; + }; + let key = (std::ptr::from_ref(heap) as usize, address.unwrap_or(0)); + let (index, shadow) = match self.root_uav_slots.get(&key) { + Some((index, shadow)) => (*index, address.zip(shadow.clone())), + None => { + let shadow = address.and_then(|a| find(a).map(|s| (a, s))); + let Some(index) = host.dynamic(1) else { + return false; + }; + self.dynamic.push((key.0, index, 1)); + if let Some((a, s)) = &shadow { + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + let offset = s.gpu(*a) - base; + // Raw views start on 16 bytes: from the 16 bytes + // below, and the shader adds the rest to its offsets + // (`victory_shader::emit::USER_VIEW_BIAS`). (An address + // not on 16 bytes got a null view at first: the + // builder's counters are at such addresses.) + let bias = offset & 15; + host.raw_uav_at(index, &s.buffer, offset - bias, s.left(*a).min(limit) + bias); + } + if shadow.is_none() { + host.null_raw_uav_at(index); + } + self.root_uav_slots + .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone()))); + (index, shadow) + } + }; + if let Some((a, s)) = &shadow { + ready(*a, s); + } + let handle = host.gpu_handle(index); + // SAFETY: an open list; the slot is in the bound view heap. + unsafe { + if compute { + list.list.SetComputeRootDescriptorTable(param, handle); + } else { + list.list.SetGraphicsRootDescriptorTable(param, handle); + } } true } + /// Binds a root SRV as a one-view table + /// ([`crate::pipeline::host::bounded_root_srvs`]): a raw view of the + /// title buffer's host copy from `address` to the copy's end, or a null + /// view (no address, no host copy, or an address not on 16 bytes). One + /// dynamic slot per address per list, given back with the list's + /// others. False if no slot could be had or no view heap is bound. + fn root_srv_table( + &mut self, + list: &HostList, + address: Option, + param: u32, + compute: bool, + biased: bool, + ) -> bool { + let heap = match self.heaps[0] { + 0 => None, + h => Some(crate::descriptor::heap(h as This)), + }; + let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else { + once!("a root SRV without a bound view heap: the draw is dropped"); + return false; + }; + // A view that begins early is another view than one that does not + // (title addresses stay below bit 63). + let key = ( + std::ptr::from_ref(heap) as usize, + address.unwrap_or(0) | u64::from(biased) << 63, + ); + let (index, shadow) = match self.root_srv_slots.get(&key) { + Some((index, shadow)) => (*index, address.zip(shadow.clone())), + None => { + let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s))); + let Some(index) = host.dynamic(1) else { + return false; + }; + self.dynamic.push((key.0, index, 1)); + self.root_srv_slots + .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone()))); + match &shadow { + Some((a, s)) => { + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + let offset = s.gpu(*a) - base; + if biased { + // From the 16 bytes below; the shader adds the + // rest (`victory_shader::emit::USER_VIEW_BIAS`). + let bias = offset & 15; + host.raw_at(index, &s.buffer, offset - bias, s.left(*a) + bias); + } else if offset.is_multiple_of(16) { + host.raw_at(index, &s.buffer, offset, s.left(*a)); + } else { + // Raw views start on 16 bytes; one from the + // aligned start would shift every read. + once!( + address = format_args!("{a:#x}"), + "a root SRV not on 16 bytes reads zeros" + ); + host.null_raw_at(index); + } + } + None => host.null_raw_at(index), + } + (index, shadow) + } + }; + // As for root descriptors (`root_view`): all that is left of the + // buffer is brought up to date. The first 1 MiB only left what lay + // past it stale (most mesh vertex streams reach further). + if let Some((a, s)) = &shadow { + s.refresh(list, *a, s.left(*a)); + } + let handle = host.gpu_handle(index); + // SAFETY: an open list; the slot is in the bound view heap. + unsafe { + if compute { + list.list.SetComputeRootDescriptorTable(param, handle); + } else { + list.list.SetGraphicsRootDescriptorTable(param, handle); + } + } + true + } + + /// For a shader that picks buffers from the view heap by an index it + /// computes (SM 6.6 dynamic resources): the GPU address of the heap's + /// table of element strides, with every buffer view of the heap given + /// its host slot and its memory brought up to date when `list` is + /// submitted. Tables tell us which views a draw reads; nothing tells + /// us which of the heap's a computed index names, so all of them are + /// made ready, once per list. + /// shortcut: the buffers are read, not written: what such a shader + /// writes through a picked unordered access view stays in the host + /// copy. A list refreshes them where it first runs such a shader; + /// title writes recorded later in the same list are not seen. + fn heap_buffers(&self, list: &HostList) -> Option { + let heap = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers())?; + let host = heap.host()?; + let gpu = host.strides_gpu()?; + // One key per list, as textures have: no title resource is there. + const ONCE: usize = usize::MAX - 0x5e; + if !list.first_use(ONCE) { + return Some(gpu); + } + // The list may outlive the title's heap object, which owns the table. + if let Some(buffer) = host.strides_buffer() { + list.keep(buffer); + } + // The pass itself once per frame: per list it ran up to 51 times a + // frame over 81,000 views and 4,100 host copies, 18 s of every + // frame (2026-11-24, run 11). + // shortcut: what the title writes into such buffers between lists + // of one frame is seen a frame late. + static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + let frame = crate::frame::current(); + if FRAME.swap(frame, Ordering::Relaxed) == frame { + return Some(gpu); + } + let started = std::time::Instant::now(); + // Per host heap: the host copy and range each slot's buffer view + // reads, kept from pass to pass. Only the slots written since the + // last pass are looked at again (83,000 slots a pass otherwise, 0.1 s + // at best); all of them every 16 passes, because a view of a + // released resource goes stale without a write, and a slot written + // before its memory had a host copy is only made then. + type Ranges = std::collections::HashMap, u64, u64)>; + static RANGES: std::sync::Mutex>> = + std::sync::Mutex::new(None); + let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); + let (passes, ranges) = kept + .get_or_insert_with(Default::default) + .entry(std::ptr::from_ref(host) as usize) + .or_insert_with(|| (0, Ranges::new())); + let changed = host.buffer_changes(); + let slots = if *passes % 16 == 0 { + ranges.clear(); + host.buffer_slots() + } else { + changed + }; + *passes += 1; + // 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(); + for (n, &index) in slots.iter().enumerate() { + ranges.remove(&index); + 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(); + } + // 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; + }; + #[cfg(feature = "diagnostics")] + if host.shows(index, &shadow.buffer) == Some(false) { + HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed); + } + ranges.insert(index, (shadow, address, address + len)); + } + let views = ranges.len() as u32; + // Per host copy, the span its picked views cover. + let mut spans: std::collections::HashMap, u64, u64)> = + std::collections::HashMap::new(); + for (shadow, from, to) in ranges.values() { + let key = std::sync::Arc::as_ptr(shadow) as usize; + let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to)); + span.1 = span.1.min(*from); + span.2 = span.2.max(*to); + } + drop(kept); + let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum(); + // Memory that is not write-watched is copied whole by every refresh. + // It was once refreshed only every 120 frames (unmapped pages read + // one by one cost 14 GB a frame in run 11, before they were + // remembered): streamed geometry then drew from stale buffers, and + // the garbage ended runs (the card stopped answering 14-90 frames + // into the opening cutscene; with every frame it ran on). The pass + // costs some 30 ms a frame this way. + static WHOLE: std::sync::Mutex>> = std::sync::Mutex::new(None); + let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); + let whole = whole.get_or_insert_with(Default::default); + for (shadow, from, to) in spans.values() { + if shadow.unwatched() { + // By the copy's number: a copy made where one let go was + // (`shadow::let_go_idle`) has never been refreshed. + let key = shadow.id() as usize; + // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame). + static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); + let every = *EVERY.get_or_init(|| { + std::env::var("VICTORY_UNWATCHED_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1) + }); + match whole.get(&key) { + Some(&last) if frame < last + every => continue, + _ => { + whole.insert(key, frame); + } + } + } + shadow.refresh(list, *from, to - from); + } + self.heap_textures(list, heap, host); + HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); + HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + static LOGGED: AtomicU64 = AtomicU64::new(0); + // The first pass and every growth of the set by half. + let seen = LOGGED.load(Ordering::Relaxed); + if u64::from(views) > seen + seen / 2 { + LOGGED.store(u64::from(views), Ordering::Relaxed); + tracing::info!( + slots = slots.len(), + views, + copies = spans.len(), + mb = bytes >> 20, + ms = started.elapsed().as_millis(), + "buffer views of the heap made ready for shaders that pick them by index" + ); + } + Some(gpu) + } + + /// The texture side of [`State::heap_buffers`]: textures the title fills + /// itself (streamed pages, layout-library copies) whose views sit in the + /// view heap are created (placed textures have no host texture until + /// something reads them) and uploaded, as a table read would do, for + /// shaders that pick them by a computed index. Within a budget of bytes + /// per frame and in all; the rest waits for later lists and frames. + /// The most recently written slots first (`TextureQueue::due`); slots + /// draws read through tables are not in the queue. + /// shortcut: uploaded once, and again only when the title rewrites the + /// slot. A placed texture not all mapped yet is uploaded with what is + /// there and looked at again (1, 2, 4, ... frames later, at most about + /// a second): uploaded again when more of it is mapped. Pages mapped + /// in place of others, and contents changed with no descriptor write, + /// are missed (hook the page-mapping events for those). + /// `VICTORY_HEAP_TEXTURES=0` turns it off. + fn heap_textures( + &self, + list: &HostList, + heap: &crate::descriptor::Heap, + host: &crate::descriptor::host::HostHeap, + ) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) { + return; + } + /// Bytes of texture memory staged per frame. + const PER_FRAME: u64 = 192 << 20; + static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + static SPENT: AtomicU64 = AtomicU64::new(0); + let frame = crate::frame::current(); + if FRAME.swap(frame, Ordering::Relaxed) != frame { + SPENT.store(0, Ordering::Relaxed); + } + // No more of them are made while the card has no room + // (`resource::room`): by what is alive now, not by what was ever + // staged (4 GB in all, after which later textures stayed empty for + // the run). The ones nothing names any more are let go, which + // makes room again: so the slots are still looked at (the pass + // returned here, and a slot whose texture had been streamed out + // kept its host copy for as long as the card was full). + let room = crate::resource::room(); + if !room { + HEAP_TEXTURES_FULL.fetch_add(1, Ordering::Relaxed); + once!("textures picked by index: the card has no room for more; they wait"); + } + let mut refused = 0; + // Slots whose texture's memory the runtime mapped, unmapped or + // wrote since the last pass are due again. + host.texture_slots_remapped(frame); + let (due, census) = host.texture_slots_due(frame, 4096); + HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed); + for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) { + count.store(now, Ordering::Relaxed); + } + // The frames in about four seconds, between 16 and 256: how long a + // slot with nothing to upload waits at most for its next look. In + // frames alone it was 120: four minutes at the opening cutscene's + // half a frame per second, while the title streams by the clock. + // (About a second before the runtime told of the memory it maps: + // the looks are now only for what that does not tell.) + static PASSED: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms(); + let took = now.saturating_sub(PASSED.swap(now, Ordering::Relaxed)).max(1); + let most = (4000 / took).clamp(16, 256); + // What a table entry of a texture a shader samples says. + let sampled = UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }; + // Also within a time per pass: the pass runs on a thread that + // records the frame, and making and staging 192 MB of textures took + // 1.6-2.2 s of each of the world's first twenty frames (run 20). + // The rest waits for the next frames, as it does past the bytes. + const SPAN: std::time::Duration = std::time::Duration::from_millis(250); + let began = std::time::Instant::now(); + for (index, write) in due { + if SPENT.load(Ordering::Relaxed) >= PER_FRAME || began.elapsed() > SPAN { + break; + } + // A placed texture whose memory is not mapped (not streamed in + // yet, or streamed out again: the heap keeps tens of thousands + // of such views) gets no host texture; looked at again soon (a + // title writes a texture's view before its pages are mapped, + // and the pass runs early in a frame). One of which some is + // mapped (a texture streaming in: its smaller mips lie at the + // start of its memory and arrive first) is uploaded with what + // is there, and again when more is. (It was uploaded again + // every 120 frames, changed or not; and asked by its first + // page alone, one whose first page is the one missing counted + // as not there.) + let mut partly = None; + if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) { + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let len = crate::resource::placed_bytes(&resource).unwrap_or(1); + let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize); + if mapped == 0 { + HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed); + // Streamed out: what the slot showed is let go. + host.texture_slot_gone(index); + host.texture_slot_later(index, write, frame, most); + continue; + } + if mapped < len { + if mapped <= host.texture_slot_mapped(index) { + HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed); + host.texture_slot_later(index, write, frame, most); + continue; + } + if !crate::texture::committed(address as *const u8, 1) { + HEAP_TEXTURES_PARTLY[2].fetch_add(1, Ordering::Relaxed); + } + partly = Some(mapped); + } + } + // A texture object the host renders to or writes holds the + // host's own contents: nothing to bring up to date, and this + // pass is no use of it (its host copy is made when something + // uses it, and its slots then: `descriptor::make_waiting`). + if let Some(View::Shader(object, _)) = heap.handle(index).and_then(crate::descriptor::view) + && crate::resource::buffer_bytes(object as This).is_none() + && !crate::resource::title_fills(object as This) + { + host.texture_slot_done(index, write, None); + continue; + } + // From here on a host texture is made: not without room. The + // slot stays due. + if !room { + refused += 1; + if refused > 256 { + break; + } + continue; + } + let view = heap.handle(index).and_then(|handle| host.mirror(index, handle, true)); + let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); + let resource = match placed.as_ref().or(view.as_ref()) { + Some(&View::Shader(resource, _)) => resource as This, + _ => { + host.texture_slot_done(index, write, None); + continue; + } + }; + let title_fills = crate::resource::host_resource(resource).is_some_and(crate::texture::title_written); + if !title_fills { + // a render target, a depth or unordered access texture: the host's own + host.texture_slot_done(index, write, None); + continue; + } + // A texture that has a staging buffer now is one draws read + // through a table: they upload it, and check it at every + // submission that samples it. + let tabled = crate::texture::is_staged(resource); + if let Some(view) = &view { + readable(list, sampled.kind, view); + } + // A texture view the host refuses removes the device: name it. + static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !GONE.load(Ordering::Relaxed) + && let Some(why) = crate::descriptor::host::device_removed() + { + GONE.store(true, Ordering::Relaxed); + let text: String = format!("{view:?}").chars().take(300).collect(); + tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}"); + crate::host::log_removal_context(); + return; + } + let (bytes, whole) = crate::texture::staged(resource).unwrap_or((0, true)); + // Not all of it there: looked at again next frame, and from + // then on as a slot with nothing new (a placed texture: until + // more of it is mapped; a texture object at an address the + // title mapped: again in 120 frames, as before). + let again = match partly { + Some(mapped) => Some((frame + 1, mapped)), + None => (!whole).then_some((frame + 120, 0)), + }; + if again.is_some() { + HEAP_TEXTURES_PARTLY[1].fetch_add(1, Ordering::Relaxed); + } + if tabled { + // Nothing was staged here, so nothing is counted or spent, + // and the staging buffer stays: taking it away made the + // next draw that reads the texture through a table stage, + // detile and upload all of it once more. + HEAP_TEXTURES_TABLED.fetch_add(1, Ordering::Relaxed); + host.texture_slot_done(index, write, again); + continue; + } + // Uploaded: the list holds the staging buffer until it has run; + // a table read, or the next look at a texture not all mapped + // yet, makes it anew. (Kept for those until now: every partly + // streamed texture of the heap held a staging buffer of its full + // size for good.) + crate::texture::unstage(resource); + SPENT.fetch_add(bytes, Ordering::Relaxed); + HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed); + HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed); + host.texture_slot_done(index, write, again); + } + } + + /// For the frame listing, after a dropped dispatch's line: its group + /// counts and the compute root arguments it was recorded with (root + /// constants as hex dwords, root views with the title buffer they + /// point into). A program that does not translate has no bindings to + /// list; these say which memory it would have read and written (the + /// ray-tracing structure builder passes its buffers this way). + #[cfg(feature = "diagnostics")] + fn list_dropped_roots(&self, groups: [u32; 3]) { + crate::capture::op(0, || { + use std::fmt::Write; + let [x, y, z] = groups; + let mut text = format!(" its roots ({x}x{y}x{z}):"); + for (slot, root) in self.compute.iter().enumerate() { + match root { + Root::None => {} + Root::Table(a) => { + let _ = write!(text, " {slot}=table {a:#x}"); + } + Root::Constants(v) => { + let _ = write!(text, " {slot}=constants {:x?}", &v[..v.len().min(48)]); + } + Root::View(a) => { + let _ = write!(text, " {slot}=view {a:#x}"); + match crate::shadow::extent(*a) { + Some((start, len)) => { + let _ = write!(text, " in buffer {start:#x}+{len:#x}"); + } + None => text.push_str(" in no buffer"), + } + } + } + } + text + }); + } + /// Runs a dispatch on the host. pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) { + // It may write the arguments a window holds clamped. + self.window = None; #[cfg(feature = "diagnostics")] if crate::pipeline::is_skipped(self.pipeline as This) { DROPPED.fetch_add(1, Ordering::Relaxed); crate::pipeline::note_drop(self.pipeline as This); return; } + // The ray-tracing structure builder's stages run all or none. + if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + { + crate::pipeline::note_why("a stage of the ray-tracing structure builder, which is off".to_owned()); + self.list_dropped_roots([x, y, z]); + } + return; + } let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { once!( pipeline = format_args!("{:#x}", self.pipeline), @@ -531,7 +1690,10 @@ impl State { ); DROPPED.fetch_add(1, Ordering::Relaxed); #[cfg(feature = "diagnostics")] - crate::pipeline::note_drop(self.pipeline as This); + { + crate::pipeline::note_drop(self.pipeline as This); + self.list_dropped_roots([x, y, z]); + } return; }; if !p.compute { @@ -540,6 +1702,11 @@ impl State { } if !self.bind(list, p, true) { DROPPED.fetch_add(1, Ordering::Relaxed); + // A stage of the structure builder that cannot be bound is a + // dropped stage: the others stop too. + if crate::pipeline::is_builder(self.pipeline as This) { + crate::pipeline::builder_off("one of its dispatches could not be bound"); + } return; } #[cfg(feature = "diagnostics")] @@ -560,6 +1727,32 @@ impl State { return kind; }; let mut text = format!("{kind} {}", p.name); + // What it draws into (a dispatch writes through its views below). + if !compute { + let described = |t: usize| { + crate::resource::host_made(t as This).map(|r| { + // SAFETY: a live resource. + let d = unsafe { r.GetDesc() }; + format!("{t:#x} {}x{} f{}", d.Width, d.Height, d.Format.0) + }) + }; + let targets: Vec = self.targets.iter().filter_map(|&t| described(t)).collect(); + let _ = write!(text, " targets {targets:?} depth {:?} state [{}]", described(self.depth), p.state); + // The title's scissor and viewport at this draw (the first of + // each): Grand Theft Auto VI draws what it sees through a + // portal (a window, from inside a room) under the portal's + // rectangle, and the listing did not say which draws those are. + if let Some(r) = self.scissors.first() { + let _ = write!(text, " scissor [{} {} {} {}]", r.left, r.top, r.right, r.bottom); + } + if let Some(v) = self.viewports.first() { + let _ = write!( + text, + " viewport [{} {} {} {} depth {}..{}]", + v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth + ); + } + } let views = (self.heaps[0] != 0) .then(|| crate::descriptor::heap(self.heaps[0] as This).host()) .flatten(); @@ -567,14 +1760,17 @@ impl State { let t = stage.translated(); let _ = write!(text, " | {}:", stage.shader.hash); for u in &t.host.user_data { - let v = self.user_value(compute, u.slot, u.root, u.dword); + let v = match u.root { + RootType::Other(kind) => self.host_word(compute, kind, u.slot, u.dword, None), + _ => self.user_value(compute, u.slot, u.root, u.dword), + }; let _ = write!(text, " u{}={v:#x}", u.index); let index = if u.root == RootType::Table { v / 32 } else { v }; if let Some(slot) = views.and_then(|h| h.describe_slot(index)) { let _ = write!(text, " [heap {index}: {slot}]"); } } - for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs) { + for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs).chain(&stage.root_uavs) { if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) { let host = crate::shadow::find(*address, 1) .map(|s| (s.gpu(*address), s.left(*address))); @@ -586,18 +1782,37 @@ impl State { text } + /// A mesh draw under `VICTORY_MESH_TEST=scissor` rasterises one pixel: + /// the scissors before it (`on`), the title's after it. + fn mesh_scissor(&self, list: &HostList, on: bool) { + if mesh_test() != 2 { + return; + } + if on { + let one = RECT { left: 0, top: 0, right: 1, bottom: 1 }; + crate::draw::scissors(list, &vec![one; self.scissors.len().max(1)]); + } else if !self.scissors.is_empty() { + crate::draw::scissors(list, &self.scissors); + } + } + /// Runs a mesh dispatch of `x` groups on the host (the title's mesh /// programs are one-dimensional). pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) { + self.window = None; #[cfg(feature = "diagnostics")] self.trace("mesh", x, 0); - let ran = self.prepare_for(list, false, true) + let ran = mesh_test() != 1 + && mesh_kept(self.pipeline) + && self.prepare_for(list, false, true) && match list.list.cast::() { Ok(l6) => { #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("mesh {x}"), false)); + self.mesh_scissor(list, true); // SAFETY: an open list with everything set. unsafe { l6.DispatchMesh(x, 1, 1) }; + self.mesh_scissor(list, false); DRAWN.fetch_add(1, Ordering::Relaxed); true } @@ -630,7 +1845,11 @@ impl State { return; }; if let Some(view) = host.mirror(index, handle, true) { - readable(list, u, &view); + readable(list, u.kind, &view); + // Up to date by this draw: not the texture pass's to make. + if crate::descriptor::host::is_texture_view(&view) { + host.texture_slot_tabled(index, true); + } } } @@ -645,7 +1864,13 @@ impl State { /// once: its constant data is copied at submission either way, and the /// big tables the world binds would otherwise take hundreds of slots per /// draw, wrapping the dynamic slots onto lists not yet submitted. - fn tables(&mut self, list: &HostList, used: &[UsedResource], compute: bool) -> Vec<(u8, u32)> { + pub(crate) fn tables( + &mut self, + list: &HostList, + used: &[UsedResource], + indexed: &[RootIndexedView], + compute: bool, + ) -> Vec<(u8, u32)> { let tables = |u: &&UsedResource| u.root == RootType::Table; let mut fresh: Vec = used .iter() @@ -694,14 +1919,42 @@ impl State { let Some(heap) = self.heap_of(table) else { continue; }; + if heap.samplers() || (table - heap.start) % 32 != 0 { + continue; + } let Some(host) = heap.host() else { continue; }; + let mut selected: Vec = indexed + .iter() + .filter(|index| index.table_slot == slot) + .map(|index| { + let constant = self.user_value( + compute, + index.constant_slot, + RootType::Constants, + index.constant_dword, + ); + // The shader adds i32 byte offsets and shifts by 5. + index.byte_offset.wrapping_add(constant << index.shift) / 32 + }) + .collect(); + selected.sort_unstable(); + selected.dedup(); let n = entries .iter() - .map(|u| u.table_offset_dwords / 8 + 1) + .map(|u| u.table_offset_dwords / 8) + .chain(selected.last().copied()) .max() - .unwrap_or(1); + .unwrap_or(0) + + 1; + let last = table.checked_add(u64::from(n - 1) * 32); + if n > crate::descriptor::host::DYNAMIC + || last.and_then(|handle| heap.index(handle)).is_none() + { + once!(slot, n, "fresh descriptor table exceeds the available span"); + continue; + } // The table and what its entries hold (record words). let key = { use std::hash::{Hash, Hasher}; @@ -711,30 +1964,41 @@ impl State { // SAFETY: a descriptor slot in title memory. unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h); } - (table, h.finish()) + (table, n, h.finish()) }; if let Some(&first) = self.fresh_tables.get(&key) { for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { let handle = table + u64::from(u.table_offset_dwords) * 4; if let Some(view) = crate::descriptor::view(handle) { - readable(list, u, &view); + readable(list, u.kind, &view); + } + } + for k in selected { + if entries.iter().any(|u| u.table_offset_dwords / 8 == k) { + continue; + } + let handle = table + u64::from(k) * 32; + if let Some(view) = crate::descriptor::view(handle) + && let Some(kind) = view_kind(&view) + { + readable(list, kind, &view); } } made.push((slot, first * 32)); continue; } let Some(first) = host.dynamic(n) else { - // Without its fresh table the shader would read the title's - // slots, which for constant buffer tables hold no constant - // view: a texture or null descriptor read as a buffer gives - // a wild address on AMD and the device is removed (#59). - // The draw or dispatch is dropped instead. - self.table_failed = true; + // No room: the draw must not run with the title's own + // offsets (slots never made for it); `bind` drops it. + made.push((slot, u32::MAX)); continue; }; self.fresh_tables.insert(key, first); self.dynamic .push((std::ptr::from_ref(heap) as usize, first, n)); + // The title's own slots of this table: what the draw reads of + // them it brings up to date here, in the dynamic slots. + let title_first = heap.index(table).filter(|first| first + n <= host.count()); // The whole range: a shader may index past the entries its // used-resource list names (descriptor arrays). for k in 0..n { @@ -751,8 +2015,24 @@ impl State { } Some(view) => { host.make_at(index, &view); - if let Some(u) = used { - readable(list, u, &view); + let kind = used.map(|u| u.kind).or_else(|| { + selected.binary_search(&k).ok().and_then(|_| view_kind(&view)) + }); + if let Some(kind) = kind { + readable(list, kind, &view); + } + // The title's slot is a table's: out of the queue + // of textures picked by index if the draw read it + // (its texture is up to date now), and made in + // place as the texture pass would have made it, + // for a shader that picks it by index all the same. + if let Some(title) = title_first + && crate::descriptor::host::is_texture_view(&view) + { + host.texture_slot_tabled(title + k, kind.is_some()); + if kind.is_some() { + host.mirror(title + k, table + u64::from(k) * 32, true); + } } } None => { @@ -781,7 +2061,7 @@ impl State { let targets: Vec = self .targets .iter() - .filter_map(|&t| crate::resource::host_resource(t as This)) + .filter_map(|&t| crate::resource::host_made(t as This)) .map(|t| { // SAFETY: a live resource. let d = unsafe { t.GetDesc() }; @@ -842,10 +2122,14 @@ impl State { first: u32, first_instance: u32, ) { + self.window = None; #[cfg(feature = "diagnostics")] self.trace("draw", vertices, first); - let rects = self.topology == RECTANGLES; - let ran = self.prepare(list, false) && (!rects || self.rectangles(list, vertices, first)); + let ready = self.prepare(list, false); + // A pipeline with the rectangle geometry stage draws the title's + // vertices as they are; any other gets its rectangles expanded. + let rects = self.topology == RECTANGLES && !self.completes_rects(); + let ran = ready && (!rects || self.rectangles(list, vertices, first)); if ran { // Rectangles were expanded into their own vertex buffers. let (count, from) = if rects { @@ -869,6 +2153,12 @@ impl State { } } + /// Whether the bound pipeline completes rectangles itself, in the + /// geometry stage rectangle pipelines get (`HostPipeline::rects`). + fn completes_rects(&self) -> bool { + crate::pipeline::host_pipeline(self.pipeline as This).is_some_and(|p| p.rects) + } + /// Binds vertex buffers holding the rectangles of vertices `first..first /// + count` as triangles, made when the list is submitted. fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool { @@ -903,6 +2193,10 @@ impl State { let (from, to, stride) = (from as usize, to as usize, stride as usize); let n = rects as usize; list.defer_host(move || { + // The vertices are read in place, at submission: no change + // of mapping under the read (see + // `crate::watch::title_memory_reading`). + let _mapped = crate::watch::title_memory_reading(); // SAFETY: the vertices lie in a title buffer (checked when // recorded) and the scratch memory is the list's. let (src, dst) = unsafe { @@ -933,12 +2227,16 @@ impl State { base: i32, first_instance: u32, ) { + self.window = None; #[cfg(feature = "diagnostics")] self.trace("indexed", indices, first); - if self.topology == RECTANGLES { + // Indexed rectangles are drawn by the rectangle geometry stage + // alone (nothing expands them on the CPU). + let lost = self.topology == RECTANGLES && !self.completes_rects(); + if lost { once!("indexed rectangles not drawn"); } - let ran = self.topology != RECTANGLES && self.prepare(list, true); + let ran = !lost && self.prepare(list, true); if ran { #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false)); @@ -977,6 +2275,9 @@ impl State { crate::pipeline::note_drop(self.pipeline as This); return false; } + if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() { + return false; + } const DRAW: u32 = 0; const INDEXED: u32 = 1; const DISPATCH: u32 = 2; @@ -985,13 +2286,48 @@ impl State { let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}")); #[cfg(not(feature = "diagnostics"))] let why = |_: &str| {}; + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + #[cfg(feature = "diagnostics")] + crate::pipeline::note_drop(self.pipeline as This); + return false; + }; + // Indirect rectangles (Grand Theft Auto VI's tiled lighting, 256 + // indirect draws a frame, makes their corners from the vertex + // number) are completed by the pipeline's geometry stage: the + // arguments stay the title's, three vertices a rectangle. They + // cannot be expanded on the CPU, which does not know their count. + // shortcut: in a pipeline without that stage, a rectangle with no + // per-vertex inputs is drawn as its first triangle (three vertices, + // half of it), and one with vertex buffers is not drawn. + let made_rects = !p.rects + && kind == DRAW + && self.topology == RECTANGLES + && !p.inputs.iter().any(|e| !e.per_instance); + if made_rects { + once!("indirect rectangles without vertex inputs drawn as their first triangle"); + } + let matches_kind = match kind { + DRAW | INDEXED => { + (self.topology != RECTANGLES || made_rects || p.rects) && !p.compute && !p.mesh + } + MESH => !p.compute && p.mesh, + DISPATCH => p.compute, + _ => false, + }; + if !matches_kind { + why(&format!( + "pipeline mismatch (compute {}, mesh {}, topology {})", + p.compute, p.mesh, self.topology + )); + return false; + } let len = u64::from(stride) * u64::from(max.max(1)); - let Some(args) = crate::shadow::find(arguments, len) else { + let Some(args) = crate::shadow::find_any(arguments, len) else { why("arguments outside title buffers"); return false; }; let counter = match count { - Some(at) => match crate::shadow::find(at, 4) { + Some(at) => match crate::shadow::find_any(at, 4) { Some(s) => Some((s, at)), None => { why("count outside title buffers"); @@ -1007,52 +2343,125 @@ impl State { why("no host signature"); return false; }; - args.refresh(list, arguments, len); - if let Some((s, at)) = &counter { - s.refresh(list, *at, 4); - } - // Bounded first: the clamp binds a compute pipeline of its own. - if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) { - why("not bounded (no clamp, or arguments not 4-byte aligned)"); + if kind == MESH && (mesh_test() == 1 || !mesh_kept(self.pipeline)) { + why("mesh draws are switched off (VICTORY_MESH_TEST=skip)"); return false; } - self.host_pipeline = 0; - self.host_roots[1] = 0; + // A window of records clamped in one pass (`windows`): for single + // records without a count buffer, drawn by shaders that store to no + // buffer. Anything else ends the window: it uses the scratch buffer + // or may write the arguments. + const WINDOW_USE: usize = usize::MAX - 0x77; + let offset = args.offset(arguments); + let windowed = windows() + && kind != DISPATCH + && max == 1 + && count.is_none() + && !p.stages.iter().any(|stage| stage.translated().stores); + // Another host list (a new one after a cut, or this one after its + // reset) has another scratch buffer, or this one's with old bytes. + if !windowed || list.first_use(WINDOW_USE) { + self.window = None; + } + let same = |w: &Window| w.copy == args.id() && w.kind == kind && w.stride == stride; + let hit = self + .window + .as_ref() + .filter(|w| same(w) && offset >= w.base) + .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records)) + .map(|w| (w.scratch.clone(), offset - w.base)); + let (bounded, at) = match hit { + Some(hit) => hit, + None => { + // A record a short step after the last window's last one + // (the same step as that window's, if it had one): the + // title walks the buffer, so the ones that step apart + // after it are clamped with it. + let (step, records) = match &self.window { + Some(w) if windowed && same(w) => { + let last = w.base + u64::from(w.records - 1) * u64::from(w.step); + let step = offset.saturating_sub(last); + let walks = step >= u64::from(stride) + && step <= 256 + && step % 4 == 0 + && (w.records == 1 || step == u64::from(w.step)); + if walks { + let fit = (args.left(arguments) / step).min(WINDOW_MOST) as u32; + (step as u32, (if w.records == 1 { 16 } else { w.records * 2 }).min(fit).max(1)) + } else { + (stride, max) + } + } + _ => (stride, max), + }; + args.refresh(list, arguments, len.max(u64::from(step) * u64::from(records))); + if let Some((s, at)) = &counter { + s.refresh(list, *at, 4); + } + // Bounded first: the clamp binds a compute pipeline of its + // own and copies clamped active records into a scratch + // buffer at offset 0. + let count_arg = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); + // More than the record asked for: a window clamped ahead, + // whose unfilled slots must not spend the list's budget. + let bounded = if windowed && records > 1 { + crate::indirect::bound_ahead(list, (&args.buffer, offset), (kind, step, records)) + } else { + crate::indirect::bound(list, (&args.buffer, offset), count_arg, (kind, step, records)) + }; + let Some(bounded) = bounded else { + self.window = None; + why("not bounded (no clamp, or arguments not 4-byte aligned)"); + return false; + }; + self.host_pipeline = 0; + self.host_roots[1] = 0; + self.window = windowed.then(|| Window { + copy: args.id(), + kind, + stride, + step, + base: offset, + records, + scratch: bounded.clone(), + }); + (bounded, 0) + } + }; let ran = match kind { - DRAW | INDEXED => self.topology != RECTANGLES && self.prepare(list, kind == INDEXED), + DRAW | INDEXED => self.prepare(list, kind == INDEXED), MESH => self.prepare_for(list, false, true), - DISPATCH => match crate::pipeline::host_pipeline(self.pipeline as This) { - Some(p) if p.compute => self.bind(list, p, true), - _ => false, - }, + DISPATCH => self.bind(list, p, true), _ => false, }; if !ran { - crate::indirect::done(list, &args.buffer); - #[cfg(feature = "diagnostics")] - match crate::pipeline::host_pipeline(self.pipeline as This) { - None => crate::pipeline::note_drop(self.pipeline as This), - Some(p) => why(&format!("prepare failed (compute {}, mesh {})", p.compute, p.mesh)), - } + crate::indirect::done(list, &bounded); + why("prepare failed"); return false; } #[cfg(feature = "diagnostics")] list.note_op(|| { self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) }); - // SAFETY: an open list with everything set; the buffers are host - // copies the list keeps alive (refresh), the signature is cached. + if kind == MESH { + self.mesh_scissor(list, true); + } + // SAFETY: an open list with everything set; the scratch buffer and + // host copies are kept alive by the list, and the signature is cached. unsafe { list.list.ExecuteIndirect( &signature, max, - &args.buffer, - args.offset(arguments), + &bounded, + at, counter.as_ref().map(|(s, _)| &s.buffer), counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), ) }; - crate::indirect::done(list, &args.buffer); + if kind == MESH { + self.mesh_scissor(list, false); + } + crate::indirect::done(list, &bounded); if kind == DISPATCH { DISPATCHED.fetch_add(1, Ordering::Relaxed); } else { @@ -1102,30 +2511,89 @@ fn host_signature(kind: u32, stride: u32) -> Option { /// Gets what a shader reads or writes through a view ready: buffer data /// copied, textures moved to the state they need. -fn readable(list: &HostList, u: &UsedResource, view: &View) { - const SHADER_RESOURCE: u32 = 0x40 | 0x80; +fn view_kind(view: &View) -> Option { + match view { + View::Shader(..) | View::Placed(false, ..) => Some(ResourceType::Srv), + View::Unordered(..) | View::Placed(true, ..) => Some(ResourceType::Uav), + _ => None, + } +} + +/// The host state a depth view needs of its texture: the read state if the +/// view writes no plane the format has (the title's read-only flags), else +/// the write state. +/// shortcut: whole textures have one state, so a view that writes one of +/// two planes counts as writing. +fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>) -> u32 { + // D16_UNORM and D32_FLOAT: depth formats without a stencil plane. + const ONE_PLANE: [i32; 2] = [55, 40]; + let Some(desc) = desc else { + return DEPTH_WRITE; + }; + let format = if desc.Format.0 == 0 { + // SAFETY: a live texture; a view without a format has its own. + unsafe { texture.GetDesc() }.Format.0 + } else { + desc.Format.0 + }; + let mut needed = D3D12_DSV_FLAG_READ_ONLY_DEPTH.0; + if !ONE_PLANE.contains(&format) { + needed |= D3D12_DSV_FLAG_READ_ONLY_STENCIL.0; + } + if desc.Flags.0 & needed == needed { + DEPTH_READ + } else { + DEPTH_WRITE + } +} + +fn readable(list: &HostList, kind: ResourceType, view: &View) { const UNORDERED_ACCESS: u32 = 0x8; let placed = crate::descriptor::host::placed_texture(view); let view = placed.as_ref().unwrap_or(view); // Buffer views read title memory: their range is copied at submission; // what shaders write through unordered access goes back to it after. - if let Some((address, len)) = crate::descriptor::host::buffer_range(view) - && len > 0 - && let Some(shadow) = crate::shadow::find(address, len) - { + if let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(view) { shadow.refresh(list, address, len); - if u.kind == ResourceType::Uav { - shadow.gpu_writes(list, address, len); + if kind == ResourceType::Uav { + // A shader that cannot store to buffers leaves the range as + // the title has it: nothing to find afterwards. + if STORES.get() || !write_skip() { + shadow.gpu_writes(list, address, len); + } else { + #[cfg(feature = "diagnostics")] + { + crate::copystat::add(crate::copystat::C::GpuWritesLeftOut, 1); + crate::copystat::add(crate::copystat::C::GpuWritesLeftOutBytes, len); + } + } } } - match (view, u.kind) { + match (view, kind) { (View::Shader(resource, _), ResourceType::Srv) => { - if let Some(t) = crate::resource::host_resource(*resource as This) + // A view the title placed, in another format, in the memory of + // a texture the host writes: that texture's texels, copied on + // the host (title memory does not have them). + let aliased = crate::resource::alias_of(*resource as This) + .is_some_and(|source| crate::texture::alias(list, *resource as This, source)); + if !aliased + && let Some(t) = crate::resource::host_resource(*resource as This) && crate::texture::title_written(t) { crate::texture::upload(list, *resource as This, t); } - crate::list::ensure_state(list, *resource as This, SHADER_RESOURCE); + // A depth texture shaders also write: what they wrote, first. + list.twin_use(*resource as This, false, false); + // The depth target the draw only tests is read in both ways at + // once: both read states, which its preparation asks for too. + let (tested, _) = TESTED_DEPTH.get(); + let state = if tested != 0 && tested == *resource { + TESTED_DEPTH.set((tested, true)); + DEPTH_READ | SHADER_RESOURCE + } else { + SHADER_RESOURCE + }; + crate::list::ensure_state(list, *resource as This, state); #[cfg(feature = "diagnostics")] if let Some(t) = crate::resource::host_resource(*resource as This) { // SAFETY: a live resource. @@ -1142,7 +2610,10 @@ fn readable(list: &HostList, u: &UsedResource, view: &View) { (View::Unordered(resource, _, _), ResourceType::Uav) => { #[cfg(feature = "diagnostics")] crate::capture::note_target(*resource as This); - crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS); + // Unordered access to a depth texture is its colour twin's. + if !list.twin_use(*resource as This, true, true) { + crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS); + } } _ => {} } @@ -1152,21 +2623,23 @@ fn readable(list: &HostList, u: &UsedResource, view: &View) { #[cfg(feature = "diagnostics")] fn describe(view: Option<&View>) -> String { let texture = |r: This| { - crate::resource::host_resource(r).map(|t| { + crate::resource::host_made(r).map(|t| { // SAFETY: a live resource. let d = unsafe { t.GetDesc() }; - format!("{}x{} f{} flags {:#x}", d.Width, d.Height, d.Format.0, d.Flags.0) + format!("{}x{} f{} flags {:#x} of {r:?}", d.Width, d.Height, d.Format.0, d.Flags.0) }) }; match view { None => "no view".into(), Some(v @ View::Shader(r, _)) => texture(*r as This) .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))), - // A buffer has no host texture: its title range, as for a shader view. - Some(v @ View::Unordered(r, ..)) => texture(*r as This).map_or_else( - || format!("uav buffer {:?}", crate::descriptor::host::buffer_range(v)), - |t| format!("uav {t}"), - ), + Some(v @ View::Unordered(r, ..)) => match texture(*r as This) { + Some(t) => format!("uav texture {t}"), + None => format!( + "uav resource {r:#x} buffer {:?}", + crate::descriptor::host::buffer_range(v) + ), + }, Some(View::Placed(u, r, d)) => format!( "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}", r[0], @@ -1212,6 +2685,8 @@ pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) { } pub(crate) fn stencil_ref(list: &HostList, reference: u32) { + #[cfg(feature = "diagnostics")] + crate::capture::op(std::ptr::from_ref(list) as usize, || format!("STENCIL REF {reference:#x}")); // SAFETY: an open list. unsafe { list.list.OMSetStencilRef(reference) }; } diff --git a/crates/victory-gpu/src/dxgi.rs b/crates/victory-gpu/src/dxgi.rs index c7f7c45..58640ac 100644 --- a/crates/victory-gpu/src/dxgi.rs +++ b/crates/victory-gpu/src/dxgi.rs @@ -219,6 +219,27 @@ struct Mode { } const _: () = assert!(size_of::() == 32); +/// The size of the display the console reports: `VICTORY_DISPLAY_MODE=WxH` +/// if set (as a console reports the television it is plugged into: a +/// Series X on a 1080p set lists a 1080p mode), else 3840x2160. +/// shortcut: not yet the host display's own size by default; make it so +/// once a title is seen to render for the mode it is given. +fn display_size() -> (u32, u32) { + static SIZE: std::sync::OnceLock<(u32, u32)> = std::sync::OnceLock::new(); + *SIZE.get_or_init(|| { + let asked = std::env::var("VICTORY_DISPLAY_MODE").ok().and_then(|v| { + let (w, h) = v.trim().split_once(['x', 'X'])?; + Some((w.trim().parse::().ok()?, h.trim().parse::().ok()?)) + }); + let size = match asked { + Some((w, h)) if (640..=7680).contains(&w) && (360..=4320).contains(&h) => (w, h), + _ => (3840, 2160), + }; + tracing::info!(width = size.0, height = size.1, "display mode reported to the title"); + size + }) +} + /// The console's mode list: one 4K mode at 60 Hz (Grand Theft Auto VI looks /// for a 120 Hz one to allow 120 Hz frame intervals). /// shortcut: fixed mode, not the host display's; report the host's rates if @@ -242,9 +263,10 @@ extern "system" fn modes( return MORE_DATA; } *count = 1; + let (width, height) = display_size(); let mode = Mode { - width: 3840, - height: 2160, + width, + height, refresh: [60, 1], format: 0, scanlines: 1, // progressive diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 285e7bd..7712461 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -75,7 +75,7 @@ extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT extern "system" fn release(this: This) -> u32 { object::release_boxed::(this) } -extern "system" fn completed(this: This) -> u64 { +pub(crate) extern "system" fn completed(this: This) -> u64 { fence(this).value.load(Ordering::Acquire) } extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT { @@ -88,6 +88,19 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c return S_OK; } if event.is_null() { + // With submissions sent to the card and not waited for + // (`crate::host::late`) the signal may be behind them: they are + // settled, which sets it. + #[cfg(windows)] + if crate::host::late() { + drop(waiters); + crate::host::settle_for_fence(); + if fence.value.load(Ordering::Acquire) >= value { + return S_OK; + } + tracing::warn!(value, "blocking fence wait not implemented"); + return E_NOTIMPL; + } // shortcut: a null event means "block until reached"; nothing can // reach it while no GPU work runs, so fail instead of hanging. tracing::warn!(value, "blocking fence wait not implemented"); @@ -96,7 +109,8 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c waiters.push((value, event as usize)); S_OK } -pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { +/// Moves the fence to `value` and sets the events that waited for it. +pub(crate) fn set(this: This, value: u64) { let fence = fence(this); let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); fence.value.store(value, Ordering::Release); @@ -107,6 +121,12 @@ pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { } !reached }); +} +pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { + set(this, value); + // A queue may have waited for it: what it held runs now. + #[cfg(windows)] + crate::queue::release_held(false); S_OK } diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 837dfbc..0b591d9 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -126,8 +126,22 @@ pub(crate) extern "system" fn wait( token: *mut u64, ) -> HRESULT { let origin = kind == ORIGIN; - let (tick, wait) = next_tick(kind); + let (mut tick, mut wait) = next_tick(kind); let limit = Duration::from_millis(u64::from(timeout_ms)); + // A blocking wait for an event that has happened since the last wait + // for it ended (a frame took longer than a tick) ends at once, on the + // tick that passed: sleeping on to the next one cost 17 ms of every + // 730 ms frame (run 58: "2.0 frame waits sleeping 16.8 ms"). Polls (a + // time-out shorter than a tick) answer as before. + // `VICTORY_LATE_WAITS=1` sleeps to the next tick, as before. + static SLEEP: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*SLEEP.get_or_init(|| std::env::var_os("VICTORY_LATE_WAITS").is_some_and(|v| v == "1")) + && limit >= wait + && tick > last(kind).load(Ordering::Relaxed) + 1 + { + tick -= 1; + wait = Duration::ZERO; + } let hr = if wait > limit { std::thread::sleep(limit); TIMEOUT @@ -136,6 +150,12 @@ pub(crate) extern "system" fn wait( last(kind).fetch_max(tick, Ordering::Relaxed); S_OK }; + #[cfg(all(windows, feature = "diagnostics"))] + { + use crate::copystat::{C, add}; + add(C::PaceWaits, 1); + add(C::PaceUs, wait.min(limit).as_micros() as u64); + } // A frame begun on a time-out takes no tick: its flip still does. if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) { // Tokens count frames (consecutive), not ticks. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6672c1e..9ecf3be 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1,7 +1,8 @@ //! The host GPU: one D3D12 device and direct queue (decision 0007), and a //! window to present on. //! -//! shortcut: every submission is waited for, so CPU and GPU never overlap; +//! shortcut: every submission is waited for, so CPU and GPU never overlap +//! (unless `VICTORY_LATE_WAIT=1`, see [`late`]); //! overlap them with per-submission fences once more than clears run. use std::sync::atomic::{AtomicU32, Ordering}; @@ -53,6 +54,9 @@ pub(crate) struct Host { messages: Option, next_rtv: AtomicU32, presenter: Mutex>, + /// The adapter the device is on, for its memory budget + /// ([`Host::video_memory`]); `None` if the system does not name it. + adapter: Option, } // SAFETY: D3D12 devices, queues, fences and descriptor heaps are @@ -61,6 +65,223 @@ unsafe impl Send for Host {} // SAFETY: as above. unsafe impl Sync for Host {} +/// Host objects the title let go of while a submission may still use them +/// (a texture its descriptors name, a descriptor slot's old resource), by +/// the submission count they wait for. The title's descriptor writes and +/// releases reach the host at once, from its own threads, while the host +/// runs a submission: freeing there is a GPU page fault on the freed +/// texture (a device hang). +static RETIRED: Mutex> = Mutex::new(Vec::new()); +/// Submissions started and finished (waited for). +static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A retired object, dropped on whatever thread finishes the submission. +struct Retired(#[allow(dead_code)] Box); +// SAFETY: what is retired is D3D12 objects (free-threaded) and the +// reference-counted wrappers holding them, dropped once. +unsafe impl Send for Retired {} + +/// Milliseconds since the first call. +pub(crate) fn now_ms() -> u64 { + static EPOCH: OnceLock = OnceLock::new(); + EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + +/// This moment, for telling later how long ago it was ([`long_ago`]): the +/// frames begun so far (high half, `crate::frame::current`) and tenths of a +/// second since the start. Host copies of title memory, staging buffers and +/// host textures note when they were last used with it. +pub(crate) fn moment() -> u64 { + (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff) +} + +/// Whether `moment` lies at least `ms` milliseconds and `frames` frames +/// back. Both: at seconds per frame, what every frame uses is not touched +/// for seconds, and at many frames per second not for many frames. (A title +/// that never waits for frames has no frame count: nothing is then idle.) +pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool { + let now = self::moment(); + let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff); + (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms +} + +/// How many references are held on a host object (its COM count): ours +/// all, since the host's views and commands hold none. A buffer or texture +/// with one is held by its owner alone: no descriptor slot keeps it +/// (`HostHeap::kept`) and no list (`HostList::keep`). +pub(crate) fn references(object: &impl Interface) -> u32 { + type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32; + let raw = object.as_raw(); + // SAFETY: a live COM object, whose first three methods are those of + // `IUnknown` (query, add a reference, release one); the pair leaves the + // count as it was, and the release returns it. The first is not called. + unsafe { + let methods = *raw.cast::<*const [Method; 3]>(); + ((*methods)[1])(raw); + ((*methods)[2])(raw) + } +} + +/// Once a second, before a submission starts: lets go of what nothing +/// names any more (copies of windows of title memory, staging buffers, +/// host copies of textures the title fills). +/// `VICTORY_SWEEP=0` keeps everything, as before. +fn sweep() { + // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`). + crate::inplace::tick(); + static ON: OnceLock = OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) { + return; + } + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let now = now_ms(); + let last = LAST.load(Ordering::Relaxed); + if now < last + 1000 + || LAST + .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed) + .is_err() + { + return; + } + crate::pipeline::trim_library(); + crate::shadow::let_go_idle(); + crate::texture::let_go_idle(); + crate::resource::let_go_idle(); +} + +/// Drops `object` once every submission running now has finished: at once +/// if none is. +pub(crate) fn retire(object: T) { + let started = STARTED.load(Ordering::Acquire); + if started <= FINISHED.load(Ordering::Acquire) { + RETIREMENTS[0].fetch_add(1, Ordering::Relaxed); + drop(object); + return; + } + RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); + RETIRED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((started, Retired(Box::new(object)))); +} + +/// Drops what waited for submissions up to `finished`. +fn bury(finished: u64) { + let done: Vec<(u64, Retired)> = { + let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner()); + if retired.is_empty() { + return; + } + let (done, keep) = std::mem::take(&mut *retired) + .into_iter() + .partition(|(at, _)| *at <= finished); + *retired = keep; + done + }; + drop(done); +} + +/// Objects [`retire`] dropped at once (no submission was running) and +/// kept until a running submission finished, since the start. +static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// What the layer did to the host's objects lately, newest last (sweeps +/// that let host copies go, pipeline library calls, saves and trims): said +/// once when the host device is removed ([`log_removal_context`]), with +/// what the submitting thread and the pipeline workers were doing at that +/// moment. A device the driver removes "internally" names no command, and +/// the pass that happens to notice first names only the view it was at: +/// the three such losses of runs 72, 73 and 82 each came within 5 ms of a +/// pipeline library call that no line of the log tied to them. +/// `VICTORY_TRAIL=0`: nothing is kept and nothing is said. +static TRAIL: Mutex> = Mutex::new(std::collections::VecDeque::new()); +/// The entries kept. +const TRAIL_MOST: usize = 96; + +fn trail_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0")) +} + +/// Microseconds since the first call. +pub(crate) fn now_us() -> u64 { + static EPOCH: OnceLock = OnceLock::new(); + EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 +} + +/// The calling thread, as the log's other lines name threads. +pub(crate) fn thread_id() -> u32 { + // SAFETY: a plain query. + unsafe { windows::Win32::System::Threading::GetCurrentThreadId() } +} + +/// Notes something done to the host's objects ([`TRAIL`]); `what` is only +/// run when the trail is kept. +pub(crate) fn trail(what: impl FnOnce() -> String) { + if !trail_on() { + return; + } + let entry = (now_us(), thread_id(), what()); + let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner()); + if trail.len() >= TRAIL_MOST { + trail.pop_front(); + } + trail.push_back(entry); +} + +/// What the submitting thread is doing (0 nothing: between submissions, +/// 1 preparing one, 2 waiting for the card to run it, 3 copying back what +/// it wrote), the lists of that submission, and since when ([`now_us`]). +static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +fn submitting(phase: u64, lists: usize) { + SUBMITTING[1].store(lists as u64, Ordering::Relaxed); + SUBMITTING[2].store(now_us(), Ordering::Relaxed); + SUBMITTING[0].store(phase, Ordering::Relaxed); +} + +/// What was going on when the host device went: whether a submission was +/// on the card, the pipeline library's state and the calls running in it, +/// and the trail. +pub(crate) fn removal_context() -> String { + use std::fmt::Write; + let now = now_us(); + let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0; + let phase = match SUBMITTING[0].load(Ordering::Relaxed) { + 0 => "between submissions (nothing of ours was running on the card)", + 1 => "preparing a submission (nothing of ours was running on the card)", + 2 => "waiting for the card to run a submission", + _ => "copying back what a submission wrote (nothing of ours was running on the card)", + }; + let mut text = format!( + "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}", + SUBMITTING[1].load(Ordering::Relaxed), + ms(SUBMITTING[2].load(Ordering::Relaxed)), + crate::pipeline::library_removal_note(), + RETIREMENTS[0].load(Ordering::Relaxed), + RETIREMENTS[1].load(Ordering::Relaxed), + STARTED.load(Ordering::Relaxed), + FINISHED.load(Ordering::Relaxed), + ); + let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner()); + let _ = write!(text, "; the last {} things done, newest last:", trail.len()); + for (at, thread, what) in trail.iter() { + let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at)); + } + text +} + +/// Says [`removal_context`] in the log, once: called by whoever finds the +/// host device removed. +pub(crate) fn log_removal_context() { + static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !trail_on() || SAID.swap(true, Ordering::Relaxed) { + return; + } + tracing::error!("when the host device went: {}", removal_context()); +} + /// Time spent in submissions since the last frame-rate line, in /// microseconds: preparing them on the CPU (title memory copies, texture /// detiling), then waiting for the GPU. @@ -73,6 +294,103 @@ static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] = static COPY_BACK: [std::sync::atomic::AtomicU64; 2] = [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; +/// The card's clock, for the frame line of every run, in microseconds since +/// the last one: how long the card had nothing of ours queued; how much of +/// that while the thread that holds the submission lock was working (the +/// card idle behind us: preparing and copying back are done with the card +/// standing); and how long that thread stood waiting for the card. +/// +/// Every send of lists to the queue is followed by a signal on a fence of +/// the clock's own ([`Host::card_sent`]). A thread of the clock waits for +/// the newest signal and notes the moment the card reached it with nothing +/// newer sent; the next send ends that idle stretch. +static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Of the thread that holds the submission lock: the microseconds it has +/// worked so far (preparing, copying back; not its waits for the card), and +/// since when it works now ([`now_us`] plus one; 0: it does not). +static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The thread that holds the submission lock starts (`on`) or stops +/// working; whether it worked until now. +fn working(on: bool) -> bool { + let now = now_us() + 1; + let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed); + if since != 0 { + WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed); + } + since != 0 +} + +/// [`WORKING`] as of now: microseconds worked so far. +fn worked() -> u64 { + let since = WORKING[1].load(Ordering::Relaxed); + let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 }; + WORKING[0].load(Ordering::Relaxed) + now +} + +/// The thread that holds the submission lock stood waiting for the card +/// from `since` until now ([`CARD_CLOCK_US`]). +fn stood(since: std::time::Instant) { + CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed); +} + +/// What [`CARD_CLOCK_US`] is measured with. +struct CardClock { + fence: ID3D12Fence, + /// Signals sent so far; and, while the card has reached the last of + /// them, since when and what [`worked`] said then. + state: Mutex<(u64, Option<(std::time::Instant, u64)>)>, + sent: std::sync::Condvar, +} + +// SAFETY: a fence (free-threaded) behind a lock. +unsafe impl Send for CardClock {} +// SAFETY: as above. +unsafe impl Sync for CardClock {} + +/// The clock's thread: waits for the newest signal sent and notes when the +/// card got there with nothing newer behind it. +fn card_clock_watch(clock: &'static CardClock) { + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + return; + }; + let mut seen = 0; + loop { + let target = { + let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner()); + while state.0 == seen { + state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner()); + } + state.0 + }; + // SAFETY: the clock's fence and this thread's event. + unsafe { + if clock.fence.SetEventOnCompletion(target, event).is_ok() { + WaitForSingleObject(event, INFINITE); + } + } + seen = target; + let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.0 == target && state.1.is_none() { + state.1 = Some((std::time::Instant::now(), worked())); + } + } +} + +/// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the +/// frame's time. +fn card_clock_line(frames: f64, ms: f64) { + let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); + tracing::info!( + "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \ + {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \ + had not submitted; the submitting thread stood waiting for the card {stood:.1} ms", + if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 } + ); +} + /// Of the preparing: title memory copies (microseconds, bytes) and texture /// refreshes (microseconds, bytes hashed), since the last frame-rate line. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [ @@ -82,6 +400,48 @@ pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [ std::sync::atomic::AtomicU64::new(0), ]; +/// Host buffers made since the start, as (count, bytes): in the upload heap +/// (staging, list scratch), shared with the processor (host copies of title +/// memory) and the graphics card's own (indirect arguments, twins' copies). +/// For the memory line: against what is alive, they show what was let go. +pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; + +/// What of that is alive now, for the memory line (`MADE` counts what was +/// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60, +/// and nothing said how many were alive): host lists; the lists' scratch +/// chunks and their bytes; of those, the chunks no list holds (kept for the +/// next list, [`Spare`]) and their bytes; chunks taken from those kept +/// instead of made, since the start; and the lists' other upload buffers +/// (texture data copied from buffers, scratch too big for a chunk) and +/// their bytes. +pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8]; + +/// About host lists, for the memory line: lists made by the host since the +/// start; preludes made (a list's second allocator and list, made when it +/// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the +/// bytes the process's private memory grew by while lists were being made +/// (what a list costs: host objects with the driver's command memory; 631 +/// lists were alive in run 65, each with a prelude it may never use). +/// Then the lists alive that were never reset since they were made: the +/// host sides of title lists the title made and has not used (a host list +/// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title +/// makes at its start). +pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// The process's private bytes (diagnostics: around the making of lists). +#[cfg(feature = "diagnostics")] +fn private_bytes() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { + cb: size_of::() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + c.PagefileUsage as u64 +} + /// What the runtime does when the host GPU fails for good: report it like a /// crash and end the run. The console has no such state, and carrying on /// draws nothing at seconds per frame. @@ -101,6 +461,7 @@ pub(crate) fn fail(what: std::fmt::Arguments) -> ! { // SAFETY: a plain query. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } { text.push_str(&format!("; device removed: {e}")); + log_removal_context(); } match host.log_messages() { Some(first) => text.push_str(&format!("; debug layer: {first}")), @@ -111,6 +472,9 @@ pub(crate) fn fail(what: std::fmt::Arguments) -> ! { } } tracing::error!("{text}"); + // Tests have no log: the reason goes to their output. + #[cfg(test)] + eprintln!("host GPU failure: {text}"); match ON_FAILURE.get() { Some(report) => report(&text), None => std::process::abort(), @@ -184,6 +548,35 @@ fn create() -> windows::core::Result { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; } let device = device.ok_or_else(windows::core::Error::empty)?; + // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the + // driver compiling shaders again on the "D3D Background Thread"s, + // for minutes after pipelines were made or loaded) is switched off. + // An experiment: while those threads ran, the same shot took + // 1,000-1,200 ms a frame, and 830-950 ms from the moment they + // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default: + // whether the card is slower with the shaders it then keeps is not + // known. + if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0") + && let Ok(device6) = device.cast::() + { + let set = device6.SetBackgroundProcessingMode( + D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK, + D3D12_MEASUREMENTS_ACTION_KEEP_ALL, + None, + None, + ); + tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)"); + } + // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose + // cross-lane code stays in 32-lane halves translated for waves of 32 + let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + if device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32) + .is_ok() + { + tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes"); + victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax); + } let messages = debug .then(|| device.cast::().ok()) .flatten(); @@ -207,6 +600,9 @@ fn create() -> windows::core::Result { ..Default::default() })?; let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); + let adapter = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|factory| factory.EnumAdapterByLuid::(device.GetAdapterLuid())) + .ok(); tracing::info!("host D3D12 device ready"); Ok(Host { device, @@ -222,6 +618,7 @@ fn create() -> windows::core::Result { messages, next_rtv: AtomicU32::new(0), presenter: Mutex::new(None), + adapter, }) } } @@ -250,6 +647,41 @@ fn warp_adapter() -> windows::core::Result { #[cfg(test)] mod tests { + #[test] + fn sparse_copies_preserve_islands_and_observe_remaps() { + use windows_sys::Win32::System::Memory::*; + const N: usize = 5 << 16; + // SAFETY: we reserve a private region, commit selected pages inside it, + // and only directly access the pages while they are writable. + unsafe { + let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::(); + assert!(!base.is_null()); + let mut expected = vec![0; N]; + for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] { + let at = base.add(offset); + assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast()); + at.write_bytes(value, 4096); + expected[offset..offset + 4096].fill(value); + } + for remap in [false, true] { + if remap { + let mut old = 0; + assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0); + expected[..4096].fill(0); + let at = base.add(1 << 16); + assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast()); + at.write_bytes(0xc7, 4096); + expected[1 << 16..(1 << 16) + 4096].fill(0xc7); + } + let mut out = vec![0xee; N]; + super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false); + assert_eq!(out[27..N - 27], expected[27..N - 27]); + assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee)); + } + assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0); + } + } + use super::*; #[test] @@ -294,13 +726,22 @@ pub(crate) struct HostList { /// list names alive until it is reset, even if the title releases the /// resource first. states: Mutex, - /// The list that runs those transitions just before this one. - prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), + /// What the list does with depth textures that have a colour twin, by + /// twin ([`TwinUse`]). + twins: Mutex>, + /// The list that runs those transitions just before this one, made + /// when the list first has such transitions ([`lazy_prelude`]). + prelude: OnceLock>, /// The pipelines the list binds, for reports of slow submissions. pipelines: Mutex>, /// The work its indirect executions may still do (`indirect`): a /// shader-writable word, zeroed when the list is submitted. budget: OnceLock>, + /// Device-local scratch buffer for clamped indirect arguments (`indirect`), + /// grown to the largest indirect execution recorded on the list. + indirect_args: Mutex>, + /// Counts the list in [`ALIVE`] while it lives. + _alive: Counted, /// The texts of the markers `note_op` set, in order (for device-removed /// data without marker texts), with the host GPU range a copy reads. #[cfg(feature = "diagnostics")] @@ -311,6 +752,20 @@ pub(crate) struct HostList { stamps: OnceLock>, } +/// A list's prelude: an allocator and a closed list. +type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList); + +/// Whether a host list's prelude is made when the list first needs one. A +/// prelude runs the texture transitions and twin copies a list needs before +/// it; lists that name no texture never have one, and every host list was +/// made with one all the same: twice the host objects per list, for the +/// title's 630 lists and for every list made anew. +/// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before. +fn lazy_prelude() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0")) +} + /// Timestamps per list (diagnostics); commands past them are not timed. #[cfg(feature = "diagnostics")] const STAMPS: u32 = 4096; @@ -324,6 +779,429 @@ type States = std::collections::HashMap< (u32, u32, std::sync::Arc), >; +/// What a list does with a depth texture that has a colour twin +/// ([`crate::resource::Twin`]). Lists are recorded on many threads and run +/// in submission order, so a list cannot know which side an earlier list +/// leaves behind: it notes which sides it uses as it finds them, and its +/// prelude copies one side into the other at submission if that side is +/// behind then. From its first use of a side on, the list knows. +struct TwinUse { + /// The depth texture (the title resource's host copy) and its twin. + depth: std::sync::Arc, + twin: std::sync::Arc, + /// The sides (depth texture, twin) the list uses as it finds them. + needs: [bool; 2], + /// Whether each side lacks what the other was written last, where the + /// list is now; `None`: as the list found it. + behind: [Option; 2], + /// The draw or dispatch being prepared writes the twin. + writing: bool, + /// The depth plane's twin holds what the plane lacks although the list + /// copied the twins since: the plane's pass waits for the list's close. + late: bool, +} + +/// The pass that draws the twin of a depth plane into the plane: one +/// triangle over each mip of each slice, its pixel shader writing the +/// twin's texel as the depth, with the depth test "always" and no stencil +/// (the stencil plane is copied through a buffer and not touched here). +/// +/// A 16-bit twin holds whole steps of 1/65535, and the depth written is +/// the step times the float nearest 1/65535 (0x37800080). That is how +/// Grand Theft Auto VI's tiled lighting computes the depth of the +/// rectangles it then draws with the test "equal", one class of materials +/// a draw (all six of its vertex shaders multiply the class number by that +/// constant), so the pass and the draw give the host the same float, and +/// the host turns the same float into the same 24 bits. The step divided +/// by 65535 is another float for 512 of the 65,536 steps (none under 257), +/// and lands in another 24-bit step for 127 of them (none under 385). +const PLANE_CORNERS: &str = r#" +float4 corner(uint i : SV_VertexID) : SV_Position { + return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0); +} +"#; +const PLANE_STEPS: &str = r#" +#define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)" +Texture2DArray twin : register(t0); +[RootSignature(RS)] +float plane(float4 p : SV_Position) : SV_Depth { + return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080); +} +"#; +const PLANE_FLOATS: &str = r#" +#define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)" +Texture2DArray twin : register(t0); +[RootSignature(RS)] +float plane(float4 p : SV_Position) : SV_Depth { + return twin.Load(int4(int2(p.xy), 0, 0)); +} +"#; + +/// Views of twins the pass reads, in a heap of ours used as a ring. +/// shortcut: a view must last until its list has run; with one or two +/// passes a frame the ring is far from coming round. +const PLANE_VIEWS: u32 = 256; + +/// What the pass draws with: the heap of its views of twins, and per kind +/// of twin (16-bit steps or floats) and depth format the root signature +/// and pipeline, made when first needed (`None`: the host refused). +struct PlanePass { + views: ID3D12DescriptorHeap, + cpu: usize, + gpu: u64, + step: u32, + next: AtomicU32, + made: Mutex)>>, +} + +/// The pass's root signature and pipeline for one kind of twin and one +/// depth format. +type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState); + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for PlanePass {} +// SAFETY: as above. +unsafe impl Sync for PlanePass {} + +fn plane_pass() -> Option<&'static PlanePass> { + static PASS: OnceLock> = OnceLock::new(); + PASS.get_or_init(|| { + let host = host()?; + let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + // SAFETY: plain heap creation and queries. + unsafe { + let views: ID3D12DescriptorHeap = host + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: PLANE_VIEWS, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .ok()?; + Some(PlanePass { + cpu: views.GetCPUDescriptorHandleForHeapStart().ptr, + gpu: views.GetGPUDescriptorHandleForHeapStart().ptr, + step: host.device.GetDescriptorHandleIncrementSize(kind), + views, + next: AtomicU32::new(0), + made: Mutex::default(), + }) + } + }) + .as_ref() +} + +/// Compiles function `entry` of `source` for `target` with the system's +/// compiler, as the indirect-argument clamp is (`crate::indirect`). +pub(crate) fn compile( + source: &str, + entry: windows::core::PCSTR, + target: windows::core::PCSTR, +) -> windows::core::Result> { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let mut code: Option = None; + let mut errors: Option = None; + // SAFETY: the source and names live through the call; out pointers ours. + let compiled = unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + windows::core::s!("victory"), + None, + None, + entry, + target, + 0, + 0, + &mut code, + Some(&mut errors), + ) + }; + if let Err(e) = compiled { + if let Some(errors) = errors { + // SAFETY: the blob's own bytes. + let text = unsafe { + std::slice::from_raw_parts( + errors.GetBufferPointer().cast::(), + errors.GetBufferSize(), + ) + }; + tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text)); + } + return Err(e); + } + let code = code.ok_or_else(windows::core::Error::empty)?; + // SAFETY: the blob's own bytes. + let bytes = unsafe { + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) + }; + Ok(bytes.to_vec()) +} + +impl PlanePass { + /// The root signature and pipeline for a twin of 16-bit steps (`steps`) + /// or of floats and the depth format `format`. + fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option { + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) { + return pipeline.clone(); + } + let pipeline = match Self::make(steps, format) { + Ok(pipeline) => Some(pipeline), + Err(e) => { + tracing::warn!( + error = %e, + steps, + format = format.0, + "no pipeline to draw a depth plane from its twin: such planes stay as they are" + ); + None + } + }; + made.push((steps, format.0, pipeline.clone())); + pipeline + } + + fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result { + use windows::core::s; + let device = &host().ok_or_else(windows::core::Error::empty)?.device; + let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?; + let source = if steps { PLANE_STEPS } else { PLANE_FLOATS }; + let ps = compile(source, s!("plane"), s!("ps_5_1"))?; + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + // SAFETY: the root signature is inside the pixel shader; the + // description points at live data and never releases its pointer. + unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?; + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: code(&vs[..]), + PS: code(&ps[..]), + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // Every texel is written; stencil stays off. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + DSVFormat: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?; + Ok((root, pipeline)) + } + } +} + +/// Records into `list` the pass that draws `plane`, the twin of the depth +/// plane of `depth`, into that plane: `depth` in the depth-write state, +/// `plane` readable by pixel shaders. The pass sets the list's descriptor +/// heap, graphics root signature, pipeline, depth target, viewport, +/// scissor and topology and puts none of them back: it is for a list that +/// records nothing of the title's after it. +fn record_plane_pass( + list: &ID3D12GraphicsCommandList, + depth: &ID3D12Resource, + plane: &ID3D12Resource, +) { + let (Some(host), Some(pass)) = (host(), plane_pass()) else { + return; + }; + // SAFETY: live resources. + let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) }; + // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32 + // typeless one floats, read as R32_FLOAT (41). The depth view names + // the depth-stencil format of the texture's family (44: 45, 19: 20). + let steps = twin.Format.0 == 53; + let format = DXGI_FORMAT(match of.Format.0 { + 44 => 45, + 19 => 20, + typed => typed, + }); + let Some((root, pipeline)) = pass.pipeline(steps, format) else { + return; + }; + for slice in 0..u32::from(of.DepthOrArraySize) { + for mip in 0..u32::from(of.MipLevels) { + let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS; + let view = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(if steps { 57 } else { 41 }), + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: mip, + MipLevels: 1, + FirstArraySlice: slice, + ArraySize: 1, + ..Default::default() + }, + }, + }; + let target = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: format, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_DSV { + MipSlice: mip, + FirstArraySlice: slice, + ArraySize: 1, + }, + }, + ..Default::default() + }; + let target = host.dsv(depth, Some(&target)); + let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1)); + let cpu = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: pass.cpu + (slot * pass.step) as usize, + }; + let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: pass.gpu + u64::from(slot * pass.step), + }; + // SAFETY: an open list; a slot of our heap; live resources and + // objects (the pass's own live as long as the process). + unsafe { + host.device + .CreateShaderResourceView(plane, Some(&view), cpu); + list.SetDescriptorHeaps(&[Some(pass.views.clone())]); + list.SetGraphicsRootSignature(&root); + list.SetPipelineState(&pipeline); + list.SetGraphicsRootDescriptorTable(0, gpu); + list.OMSetRenderTargets(0, None, false, Some(&target)); + list.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: width as f32, + Height: height as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + list.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }]); + list.IASetPrimitiveTopology( + windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4), + ); + list.DrawInstanced(3, 1, 0, 0); + } + crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed); + } + } +} + +/// Records into `list` the copy of a depth texture into its colour twin +/// (`colour`) or of the twin into the depth texture, both already in their +/// copy states: whole textures of one size in one format family, which the +/// host copies as they are; or, for the twin of a stencil plane, that plane +/// alone, through the twin's buffer. +fn record_twin_copy( + list: &ID3D12GraphicsCommandList, + depth: &ID3D12Resource, + twin: &crate::resource::Twin, + colour: bool, +) { + let (from, to) = if colour { + (depth, &twin.colour.texture) + } else { + (&twin.colour.texture, depth) + }; + crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed); + // shortcut: the depth plane's twin is not given the plane (that is a + // pass the other way: the plane read by a shader, the twin as its + // target). The twin then lacks what draws and clears wrote to the + // plane since shaders last wrote the twin. In Grand Theft Auto VI + // nothing writes that plane but the twin's pass (its 192 draws against + // it only test, run 29), so the twin lacks nothing. Counted. + if colour && twin.plane.is_some() { + crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed); + } + let Some(through) = &twin.through else { + // SAFETY: an open list and two live textures. + unsafe { list.CopyResource(to, from) }; + return; + }; + // A stencil plane and its twin: each mip and slice of the plane goes + // into the buffer, laid out as the host lays the plane out for copies, + // and from the buffer into the other texture, whole subresources both + // times. In the depth texture the stencil plane's subresources follow + // the depth plane's; the twin has the one plane. + let Some(host) = host() else { return }; + // SAFETY: a live texture. + let of = unsafe { depth.GetDesc() }; + let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize); + let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize]; + // SAFETY: a plain query writing `planes` footprints. + unsafe { + host.device.GetCopyableFootprints( + &of, + planes, + planes, + 0, + Some(rows.as_mut_ptr()), + None, + None, + None, + ); + } + let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) }; + let subresource = |texture: &ID3D12Resource, index: u32| 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: index, + }, + }; + let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(through) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: *row, + }, + }; + let (common, source, dest) = ( + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + // SAFETY: an open list and live resources; the buffer was made as big + // as these footprints, and rests in the common state between copies. + unsafe { + list.ResourceBarrier(&[transition(through, common, dest)]); + for (i, row) in rows.iter().enumerate() { + let index = first_from + i as u32; + list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None); + } + list.ResourceBarrier(&[transition(through, dest, source)]); + for (i, row) in rows.iter().enumerate() { + let index = first_to + i as u32; + list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None); + } + list.ResourceBarrier(&[transition(through, source, common)]); + } +} + /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics /// builds). pub(crate) fn dred_on() -> bool { @@ -333,6 +1211,11 @@ pub(crate) fn dred_on() -> bool { }) } +/// Indirect mesh dispatches since the last frame line: the largest group +/// count a record asked for, and the groups asked in all (from the lists' +/// budget buffers, a run late). +static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + /// Whether each list of a submission runs and is timed on its own, slow /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics /// builds; the commands are noted with `VICTORY_D3D12_DRED` on). @@ -353,11 +1236,54 @@ pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) { } } -/// Upload chunks handed out front to back: the chunks, the one in use and -/// the bytes used in it. +/// One in [`ALIVE`]`[0]` while it lives (a host list), and one in +/// [`LISTS`]`[3]` until it is first reset. +struct Counted { + /// Not reset since it was made. + fresh: std::sync::atomic::AtomicBool, +} + +impl Counted { + fn new() -> Counted { + ALIVE[0].fetch_add(1, Ordering::Relaxed); + LISTS[3].fetch_add(1, Ordering::Relaxed); + Counted { + fresh: std::sync::atomic::AtomicBool::new(true), + } + } + + /// The list is reset: it is in use. + fn used(&self) { + if self.fresh.swap(false, Ordering::Relaxed) { + LISTS[3].fetch_sub(1, Ordering::Relaxed); + } + } +} + +impl Drop for Counted { + fn drop(&mut self) { + ALIVE[0].fetch_sub(1, Ordering::Relaxed); + self.used(); + } +} + +/// A chunk of upload memory for lists' scratch data: the buffer, its +/// mapping and its host GPU address. +struct Chunk { + _buffer: ID3D12Resource, + data: usize, + gpu: u64, +} + +// SAFETY: a D3D12 resource (free-threaded) and its persistent mapping, +// written only by the list that holds the chunk. +unsafe impl Send for Chunk {} + +/// Upload chunks handed out front to back: the chunks (each with its +/// bytes), the one in use and the bytes used in it. #[derive(Default)] struct Scratch { - chunks: Vec<(ID3D12Resource, usize, u64)>, + chunks: Vec<(Chunk, u64)>, current: usize, used: u64, } @@ -365,7 +1291,263 @@ struct Scratch { // SAFETY: the chunk pointers are persistent mappings of upload buffers. unsafe impl Send for Scratch {} +impl Drop for Scratch { + fn drop(&mut self) { + give_chunks(std::mem::take(&mut self.chunks)); + } +} + const SCRATCH_CHUNK: u64 = 4 << 20; +/// A list's first chunk when the chunks are shared ([`scratch_pool`]): most +/// lists put a few constants or a rectangle's corners there, and every +/// list that did took 4 MiB of the PC's memory for it. +const SCRATCH_FIRST: u64 = 256 << 10; +/// The most bytes of chunks kept while no list holds them. +const SPARE_MOST: u64 = 128 << 20; + +/// Whether lists share their scratch chunks: a list takes a chunk when it +/// first needs one, a small one first, and gives all of them back when it +/// is reset or dropped, for the next list. Before, a list kept every chunk +/// it ever took (4 MiB each) for as long as it lived, used or not, and the +/// host lists of held submissions, which live for one submission, each +/// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and +/// freed per frame of gameplay (run 60). +/// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before. +fn scratch_pool() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0")) +} + +/// Things of some sizes that nothing holds now, kept for whoever next asks +/// for one of the same size. +struct Spare { + kept: Vec<(T, u64)>, + bytes: u64, +} + +impl Spare { + const fn new() -> Self { + Spare { kept: Vec::new(), bytes: 0 } + } + + /// A kept thing of `size` bytes, the one given last. + fn take(&mut self, size: u64) -> Option { + let at = self.kept.iter().rposition(|(_, s)| *s == size)?; + self.bytes -= size; + Some(self.kept.remove(at).0) + } + + /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past + /// `most`: then it comes back. + fn give(&mut self, thing: T, size: u64, most: u64) -> Option { + if self.bytes + size > most { + return Some(thing); + } + self.bytes += size; + self.kept.push((thing, size)); + None + } +} + +/// Scratch chunks no list holds. +static SPARE: Mutex> = Mutex::new(Spare::new()); + +/// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one. +fn take_chunk(host: &Host, size: u64) -> Option { + if scratch_pool() + && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size) + { + ALIVE[3].fetch_sub(1, Ordering::Relaxed); + ALIVE[4].fetch_sub(size, Ordering::Relaxed); + ALIVE[5].fetch_add(1, Ordering::Relaxed); + return Some(chunk); + } + let (buffer, data) = host.upload_buffer(size)?; + name(&buffer, || "list scratch".into()); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + ALIVE[1].fetch_add(1, Ordering::Relaxed); + ALIVE[2].fetch_add(size, Ordering::Relaxed); + Some(Chunk { + _buffer: buffer, + data: data as usize, + gpu, + }) +} + +/// A list is done with `chunks` (it was reset after its submissions ran, +/// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and +/// without the pool. +fn give_chunks(chunks: Vec<(Chunk, u64)>) { + if chunks.is_empty() { + return; + } + let mut freed = Vec::new(); + { + let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + for (chunk, size) in chunks { + let back = if scratch_pool() { + spare.give(chunk, size, SPARE_MOST) + } else { + Some(chunk) + }; + match back { + None => { + ALIVE[3].fetch_add(1, Ordering::Relaxed); + ALIVE[4].fetch_add(size, Ordering::Relaxed); + } + Some(chunk) => { + ALIVE[1].fetch_sub(1, Ordering::Relaxed); + ALIVE[2].fetch_sub(size, Ordering::Relaxed); + freed.push(chunk); + } + } + } + } + // Freed outside the lock. + drop(freed); +} + +/// What the host keeps for copies in the card's own memory +/// ([`crate::shadow::cards`]): three lists of ours and the compare. +struct CardWork { + /// Before a submission's lists: what changed on the copies' CPU side + /// goes to their card side. Those not in use: a plan takes one and + /// gives it back when its submission has run (`Host::card_done`), so + /// that submissions sent ahead ([`late`]) each have their own. + sync: Vec, + /// After them, in the same submission: the compare of the declared + /// ranges with their bytes from before. As `sync`. + check: Vec, + /// After it ran: the pieces that differ come down. + fetch: Prelude, + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// One dword per piece compared, set where the piece differs: PC + /// memory, mapped (buffer, mapping, bytes). + differs: (ID3D12Resource, usize, u64), + /// Where the pieces that differ are fetched to: PC memory, mapped. + fetched: Option<(ID3D12Resource, usize, u64)>, + /// The dwords of `differs` taken by plans whose results were not read + /// yet. + taken: u32, + /// Plans made and not done with (`Host::card_done`). + out: u32, +} + +// SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only +// under the submission lock. +unsafe impl Send for CardWork {} + +static CARD_WORK: Mutex> = Mutex::new(None); + +/// The compare of a declared range of a copy in the card's memory with +/// its bytes from before, one thread per 64 KiB piece (cut at multiples of +/// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs` +/// gets a dword per piece, 1 where a byte differs. The offsets are widened +/// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a +/// byte just outside the range costs a fetch that finds nothing. +pub(crate) const CARD_COMPARE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)" +cbuffer Span : register(b0) { + uint first; // the first piece + uint skew; // where the copy starts in its piece 0 + uint size; // the copy's buffer, in bytes (a multiple of 64 KiB) + uint pieces; + uint out_at; // the first piece's dword in `differs`, in bytes + uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored) +}; +ByteAddressBuffer now : register(t0); +// 16 bytes per piece of the copy: the hash of its bytes when they were +// last sent up (or hashed whole, the first time). +RWByteAddressBuffer hashes : register(u0); +RWByteAddressBuffer differs : register(u1); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= pieces) return; + uint piece = first + id.x; + uint lo = piece * 65536u; + lo = lo > skew ? lo - skew : 0u; + uint hi = min((piece + 1u) * 65536u - skew, size); + lo = lo & ~15u; + hi = (hi + 15u) & ~15u; + uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu); + [loop] + for (uint at = lo; at < hi; at += 16u) { + h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + } + if (compare != 0u) { + differs.Store(out_at + id.x * 4u, any(h != hashes.Load4(piece * 16u)) ? 1u : 0u); + // With the copy-back on its own thread: the next compare of the + // piece finds what is written from here on. + if (compare == 2u) hashes.Store4(piece * 16u, h); + } else { + hashes.Store4(piece * 16u, h); + } +} +"#; + +/// Whether the pieces hashed again after ranges were sent up to a copy in +/// the card's memory are hashed in runs of pieces that touch, each piece +/// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass +/// per range sent up. +/// +/// These passes are ours, they run on the card before every submission's +/// lists, and no timing so far names them: each walks its 64 KiB pieces +/// 16 bytes at a time, 4,096 steps one after the other, so a pass takes +/// the time of one piece however few its pieces are. Run 102 sent up 514 +/// ranges a frame: 514 such passes. The same pieces are hashed either way; +/// a piece hashed when it need not be, or not hashed when it should, costs +/// a fetch that finds nothing and loses no shader write. +fn rehash_runs() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1")) +} + +/// Since the last frame-rate line, of our own passes over copies in the +/// card's memory: hash passes after ranges were sent up, the pieces they +/// hashed, and compare passes after the lists. +static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Whether what shaders wrote to copies in the card's memory is merged +/// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by +/// default). The pieces the card's compare found differing come down in +/// one fetch and were then merged one after the other on the thread that +/// settles: about 630 pieces and 40 MB a frame (run 104), each compared +/// with the copy's CPU side byte by byte and put into title memory through +/// the kernel. A piece is its own bytes of its copy and of title memory, +/// so eight threads take an eighth of them each. +fn wide_merge() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1")) +} + +/// One declared range of a copy in the card's memory, in a submission. +struct CardRange { + shadow: std::sync::Arc, + /// As declared (title addresses), for the statistics. + declared: (usize, usize), + span: crate::shadow::CardSpan, + /// Its first piece's dword in the compare's results. + at: u32, + /// Whether the card compares it; else every piece is fetched. + compared: bool, +} + +/// What a submission does for copies in the card's memory. +struct CardPlan { + ranges: Vec, + /// The compare, run after the submission's lists. + check: Option, + /// The copies whose card side was brought up to date, alive until the + /// submission has run. + _synced: Vec>, + /// The lists of ours the plan recorded (whether the compare, the + /// list), given back by `Host::card_done`. + lists: Vec<(bool, Prelude)>, +} /// One piece of submission-time work, in recorded order. enum Step { @@ -397,6 +1579,8 @@ struct Deferred { /// Destination, source, bytes. copies: Vec, uploads: Vec, + /// The bytes of `uploads` (counted in [`ALIVE`] while they are held). + upload_bytes: u64, /// Host objects the list's commands name (pipelines, root signatures, /// descriptor heaps): the title may release its objects before it /// submits the list. @@ -409,10 +1593,1139 @@ struct Deferred { /// Bottom-of-pipe writes, done once the list has run: address, what, /// bytes. writes: Vec<(usize, crate::queue::Written, usize)>, + /// Textures read back (texture to buffer copies), done once the list + /// has run: the host buffer the list copies the texels into, the title + /// memory they go to, the bytes of a row, the rows, the title's row + /// pitch. + backs: Vec<(ID3D12Resource, usize, [usize; 3])>, /// Whether a step zeroes the indirect-work budget. budget_zeroed: bool, } +impl Deferred { + /// Holds `buffer` (`size` bytes of upload memory) until the list is + /// reset. + fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) { + ALIVE[6].fetch_add(1, Ordering::Relaxed); + ALIVE[7].fetch_add(size, Ordering::Relaxed); + self.upload_bytes += size; + self.uploads.push(buffer); + } +} + +impl Drop for Deferred { + fn drop(&mut self) { + ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed); + ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed); + } +} + +/// Whether a queue's submissions go to the card without a wait for each +/// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which +/// waits for every list on its own). +/// +/// Every submission was prepared, sent, waited for and copied back before +/// the next one was looked at, so the card stood idle while we prepared +/// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of +/// preparing, 194 ms of waiting and 78 ms of copying back, one after the +/// other, on the one thread that submits. +/// +/// With the switch a queue's submission is sent and joins a line of +/// "flights" ([`Flight`]); the thread goes on to the next one while the +/// card runs. The flights are settled together ([`Host::settle`]: one wait +/// for the card, what their shaders wrote copied back once per byte, then +/// their bottom-of-pipe writes and the fence signals behind them, in +/// order) at the next point where the title, or our own preparing, can +/// observe what they do. Those points, exactly: +/// +/// 1. a synchronous submission of ours ([`Host::execute`]): a present, a +/// read-back or map of a texture, a clear or upload run at once; +/// 2. the next submission reads title memory that a flight's shaders may +/// write: a title buffer copy, a fill of upload memory, a texture's +/// memory, any step that runs code of ours on title memory +/// ([`late_blocked`]); +/// 3. the next submission refreshes a range of a host copy that a flight's +/// shaders may write, and the title wrote a page of it since it was last +/// copied ([`stale_under_flights`]): the refresh leaves such a range +/// alone until the flight's writes are back, as it always did within a +/// submission; +/// 4. a queue stands at a wait for a memory value that no flight's +/// bottom-of-pipe write is known to satisfy, at an address a flight may +/// write ([`late_met`]); +/// 5. the title blocks on a fence without an event; +/// 6. the card has run every flight (a thread of ours waits for that: +/// [`late_helper`]), or the flights hold [`late_most`] host lists. +/// +/// What the title is told (bottom-of-pipe writes, fence values) is told +/// when the card has really run the work, later than before and never +/// earlier; a fence signalled on a queue while flights are in the air is +/// set behind them. A wait for a memory value that a flight's +/// bottom-of-pipe write satisfies counts as met: the waiting part goes to +/// the card behind that flight, which is the order the wait asks for. +/// +/// What it assumes beyond today: memory the title rewrites between two of +/// its submissions, without waiting for the first, may be seen by the +/// first's shaders (as on the console, where the card reads title memory +/// when it runs, not when the list is submitted). +pub(crate) fn late() -> bool { + late_stage() > 0 +} + +/// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]). +fn late_stage() -> u8 { + static STAGE: OnceLock = OnceLock::new(); + *STAGE.get_or_init(|| { + if std::env::var_os("VICTORY_GPU_TIMING").is_some() { + return 0; + } + match std::env::var("VICTORY_LATE_WAIT").as_deref() { + Ok("1") => 1, + Ok("2") => 2, + Ok("3") => 3, + // The relay alone: on top of stage 3. + Err(_) if crate::shadow::relay() => 3, + _ => 0, + } + }) +} + +/// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no +/// longer a point. Where the title wrote a page that lies in a range a +/// flight's shaders may write, the bytes the title changed are found (the +/// page as it is now against what the copy held when the flight was +/// prepared) and put into the copy, and only those: what the flight's +/// shaders write beside them stays (`Shadow::merge_under_writes`). The +/// flights are settled for it only where that cannot be done: memory that +/// is not write-watched, or a copy in the card's memory with more changed +/// runs than a submission should send up one by one. +/// +/// In run 92 (stage 1) this point settled the flights five times a frame +/// of twelve, each time with the card's work still to wait for: 172 ms a +/// frame of waiting were left of 200. +/// +/// What differs from settling first: a byte both the title and a flight's +/// shader wrote is the title's if the shader wrote it first, the shader's +/// if it wrote it afterwards; settled first it was always the shader's. +/// The title writing a byte a shader of its own is writing is a race on +/// the console too. +fn late_exact() -> bool { + late_stage() > 1 +} + +/// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is +/// no longer a point where flights are settled). The copy to the back +/// buffer is sent as a flight of its own (`Host::execute_own`, a list of +/// its own for each present in the air) and the swap chain is told to +/// present behind it; the queue's call returns, and the card finishes the +/// frame while the title records the next one. What the title is told +/// about the frame (bottom-of-pipe writes, fences) is told when the card +/// has run it, by the settling thread. +/// +/// What is left out with it: the look whether the presented frame is black +/// (diagnostics; it reads the frame back at once). A frame that is saved +/// or listed is presented the old way. Once every second and a half a +/// submission settles the flights all the same, for the sweep that lets +/// idle host objects go (it needs nothing in the air). +pub(crate) fn late_free_present() -> bool { + late_stage() > 2 +} + +/// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns +/// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage, +/// and is off with it, in the timing run and with kept snapshots). +/// +/// With [`late`] alone every settle does three things on the thread that +/// holds the submission lock: it waits for everything in the air, copies +/// back with the card standing, and only then goes on preparing. The frame +/// stays a relay: the card works about 242 ms of it and one thread +/// prepares, waits and copies back for about 220. +/// +/// With the switch a thread of its own ([`relay_worker`]) lands flights as +/// soon as the card has run them, in the order they were sent and without +/// the submission lock: it fetches and merges what their shaders wrote to +/// copies in the card's memory, compares and merges the other copies, +/// frees the flights' ranges, and then does their read-backs, their +/// bottom-of-pipe writes and the fence signals behind them, in the line's +/// order. The submitting thread meanwhile prepares and sends the next +/// submissions. [`Host::settle`] no longer settles anything: it waits until +/// that thread has landed everything in the air, at the same points as +/// before (the list in [`late`]), so whoever can observe title memory, a +/// fence or a present still does so only after the flights before it are +/// merged. +/// +/// What makes that safe is in `crate::shadow::relay` (ranges counted per +/// flight; a merge that never stores into memory the card may be writing; +/// sends to card copies numbered) and here: flights land in the order of +/// [`LINE`] by one thread, so a later flight's results never reach title +/// memory before an earlier flight's; the compare on the card stores the +/// hash it made, so each flight's compare flags exactly what changed since +/// the compare before it, however late the pieces are fetched; the fetch +/// goes to the queue under [`QUEUE_ORDER`], which says which sends of +/// title bytes the card had received when it ran. +pub(crate) fn relay() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay()) +} + +/// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads +/// title memory a flight's shaders may write (a title buffer copy, a fill +/// of upload memory, a texture) waits only until the flights that declared +/// that memory have landed, not for everything in the air; and at +/// [`late_most`] lists in the air it waits until there are fewer. At `1` +/// both wait for everything. +fn relay_exact() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_some_and(|v| v == "2")) +} + +/// Told when something joins [`LINE`], for the thread that lands flights +/// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at +/// what queues hold. +static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new(); + +/// Told when flights have landed ([`relay`]): who waits for that looks +/// again. +static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new(); + +/// With [`relay`], the order of what we put on the queue: the number of +/// sends of changed ranges to copies in the card's memory so far +/// (`Host::card_before`). Held from the taking of the ranges until their +/// list is on the queue, and while a fetch of pieces goes to the queue: a +/// fetch sent with the count at N ran behind sends 1..N and ahead of every +/// later one. +static QUEUE_ORDER: Mutex = Mutex::new(0); + +/// Since the last frame-rate line, of the thread that lands flights +/// ([`relay`]): landings, flights landed, microseconds it waited for the +/// card with nothing to land, microseconds it waited for fetches of card +/// copies' pieces, microseconds of landing in all. +static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// Of the line's things in order (a flight: the value signalled on the +/// host's fence behind it; a write or a signal behind a flight: `None`): +/// how many, from the front, can be landed when the card has reached +/// `completed`: everything ahead of the first flight it has not run. A +/// later flight never lands before an earlier one, and what follows a +/// flight (its bottom-of-pipe writes, signals) never before the flight. +fn landable(line: &[Option], completed: u64) -> usize { + line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len()) +} + +/// For one plan of copies in the card's memory, with [`relay`]: `flags` +/// holds, for every piece of every range of the plan, the copy, the +/// piece's number in the copy and whether the compare flagged it there (or +/// did not run). The pieces to fetch, under whichever range: all of them +/// flagged under any. Two ranges of a plan may hold parts of the same +/// 64 KiB piece; the compare hashes the whole piece for each and stores +/// the hash, so the second of them may find it stored already and not +/// flag it. +fn flagged_pieces(flags: &[(usize, u32, bool)]) -> std::collections::HashSet<(usize, u32)> { + flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect() +} + +#[cfg(test)] +mod relay_tests { + use super::{flagged_pieces, landable}; + + /// Two flights and what follows each: nothing of the second lands + /// before the card has run it, and nothing behind a flight lands + /// before the flight. + #[test] + fn flights_land_in_the_order_they_were_sent() { + // Flight (fence 5), its write, a signal, flight (fence 6), its write. + let line = [Some(5), None, None, Some(6), None]; + assert_eq!(landable(&line, 4), 0); + assert_eq!(landable(&line, 5), 3); + assert_eq!(landable(&line, 6), 5); + assert_eq!(landable(&line, u64::MAX), 5); + // Signals with no flight ahead land at once; behind one they wait. + assert_eq!(landable(&[None, None], 0), 2); + assert_eq!(landable(&[None, Some(9), None], 8), 1); + assert_eq!(landable(&[], 3), 0); + // After the first three landed, the rest when its turn comes. + assert_eq!(landable(&line[3..], 5), 0); + assert_eq!(landable(&line[3..], 6), 2); + } + + /// A piece flagged under one range of a plan is fetched under every + /// range that holds a part of it; pieces of other copies are not. + #[test] + fn a_piece_flagged_under_one_range_is_fetched_under_all() { + let (a, b) = (0x1000usize, 0x2000usize); + // Copy a: piece 3 under two ranges, flagged under the first only; + // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged. + let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)]; + let fetch = flagged_pieces(&flags); + assert!(fetch.contains(&(a, 3))); + assert!(!fetch.contains(&(a, 4))); + assert!(!fetch.contains(&(b, 3))); + assert!(fetch.contains(&(b, 9))); + assert_eq!(fetch.len(), 2); + } +} + +/// The most host lists in the air before the flights are settled +/// (`VICTORY_LATE_WAIT_LISTS`, 128; 32 settled the flights three times a +/// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables +/// asked and none refused; watch "tables asked, N refused"): their dynamic +/// descriptor slots, upload +/// memory and scratch chunks are held until then, and a frame's lists held +/// all at once ran the slots out before (run 45). +fn late_most() -> usize { + static MOST: OnceLock = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(128).max(1) + }) +} + +/// Whether a submission with bottom-of-pipe writes may fly +/// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so +/// the title is told at once, as before; for telling a title that polls +/// such a value from one that does not). +fn late_writes() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0")) +} + +/// Per host copy, the ranges a submission's shaders may write, as declared +/// (address, end). +type Declared = (std::sync::Arc, Vec<(usize, usize)>); + +/// What [`Host::submit`] hands back for a submission it sent and did not +/// wait for. +struct Sent { + /// Its number among the submissions started. + number: u64, + card: Option, + back: Vec, + /// Its bottom-of-pipe writes. + writes: Vec<(usize, crate::queue::Written, usize)>, +} + +/// A submission on the card that has not been waited for ([`late`]): its +/// host lists, taken from the title's (which it may reset meanwhile), and +/// what is to be done once it has run. +struct Flight { + number: u64, + /// The value signalled on the host's fence behind it. + fence: u64, + lists: Vec, + order: Vec, + card: Option, + back: Vec, +} + +/// One thing in the line of what waits for the card, in order. +enum Late { + Run(Flight), + /// A bottom-of-pipe write of the flight before it: address, what, bytes. + Write(usize, crate::queue::Written, usize), + /// A fence (its address) signalled behind the flights before it. + Signal(usize, u64), +} + +struct Line { + line: Vec, + /// The title memory the flights' shaders may write (address, end), in + /// order and joined. + written: Vec<(usize, usize)>, + /// Host lists in the flights. + lists: usize, + /// The value signalled on the host's fence behind the last flight. + target: u64, + /// A settle has taken the line and is not done: a signal still goes + /// behind it. + settling: bool, + /// Something was settled away from a queue's own calls: the helper + /// thread looks at what queues hold. + poke: bool, + /// Host lists of settled flights, reset and given back outside the + /// submission lock ([`land`]: a settle may run under a caller's own + /// locks). + landed: Vec<(Vec, Vec)>, + /// With [`relay`]: the bottom-of-pipe writes of the flights being + /// landed (taken out of `line`, not done yet), for [`late_met`]. + in_hand: Vec<(usize, crate::queue::Written, usize)>, +} + +// SAFETY: D3D12 objects (free-threaded) and host lists nothing records +// into; touched under the lock. +unsafe impl Send for Line {} + +static LINE: Mutex = Mutex::new(Line { + line: Vec::new(), + written: Vec::new(), + lists: 0, + target: 0, + settling: false, + poke: false, + landed: Vec::new(), + in_hand: Vec::new(), +}); +/// Told when a flight joins [`LINE`] or it is poked. +static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new(); + +fn line() -> std::sync::MutexGuard<'static, Line> { + LINE.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Why flights were settled ([`LATE_STATS`]' places from 2 on). +const WHY_SYNC: usize = 2; +const WHY_CARD_DONE: usize = 3; +const WHY_VALUE: usize = 4; +const WHY_STALE: usize = 5; +const WHY_READ: usize = 6; +const WHY_RUN: usize = 7; +const WHY_MOST: usize = 8; +const WHY_WRITES: usize = 9; +const WHY_FENCE: usize = 10; + +/// Since the last frame-rate line: submissions sent without a wait; +/// settles; settles by reason ([`WHY_SYNC`]..); flights settled; +/// microseconds settles waited for the card; value waits met by a flight's +/// bottom-of-pipe write; fence signals set behind flights. +/// Then: the settles for title memory read, by what read it (a buffer +/// copy, a fill of upload memory, a texture). +static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18]; + +/// Since the last frame-rate line: the microseconds settles waited for the +/// card, by why they settled (the `WHY_` places). +static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11]; + +/// Whether `[from, to)` touches one of `ranges` (in order, joined). +fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool { + if from >= to { + return false; + } + let at = ranges.partition_point(|r| r.1 <= from); + ranges.get(at).is_some_and(|r| r.0 < to) +} + +/// `ranges` with `more`, in order, joined where they overlap or touch. +fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator) { + ranges.extend(more.into_iter().filter(|r| r.0 < r.1)); + ranges.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); + for &(from, to) in ranges.iter() { + match out.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => out.push((from, to)), + } + } + *ranges = out; +} + +/// Whether anything is in the air. +fn flying() -> bool { + if !late() { + return false; + } + let line = line(); + // (With the relay: also while flights are being landed.) + line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_))) +} + +/// With flights in the air ([`late`]): why `runs` cannot be prepared +/// before they are settled, if so. Preparing reads title memory on the +/// CPU (the title's buffer copies, fills of upload memory, textures) and +/// runs steps of ours that may read or write it anywhere; what the +/// flights' shaders write is not there yet. +fn late_blocked(runs: &[&HostList]) -> Option { + let written = { + let line = line(); + if line.written.is_empty() { + return None; + } + line.written.clone() + }; + blocked_by(&written, runs, true) +} + +/// [`late_blocked`] against `written`, the title memory flights' shaders +/// may write (in order, joined); `count` whether the kind of read is +/// counted for the frame line. +fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option { + if written.is_empty() { + return None; + } + for list in runs { + for step in &list.deferred().copies { + match step { + &Step::Copy(dst, src, len) => { + if touches(written, src, src + len) || touches(written, dst, dst + len) { + if count { + LATE_STATS[15].fetch_add(1, Ordering::Relaxed); + } + return Some(WHY_READ); + } + } + &Step::Fill(_, src, len) => { + if touches(written, src, src + len) { + if count { + LATE_STATS[16].fetch_add(1, Ordering::Relaxed); + } + return Some(WHY_READ); + } + } + Step::Texture(staging) => { + let (at, len) = staging.memory(); + if touches(written, at, at + len) { + if count { + LATE_STATS[17].fetch_add(1, Ordering::Relaxed); + } + return Some(WHY_READ); + } + } + Step::Run(_) => return Some(WHY_RUN), + Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(_) => {} + } + } + } + None +} + +/// With flights in the air, after the submission's write-watch asking: +/// whether `runs` refresh a range of a host copy that a flight's shaders +/// may write and that the title wrote since it was last copied. The +/// refresh leaves ranges shaders are writing alone (`Shadow::update`), so +/// the title's bytes there would reach the card a submission late. +fn stale_under_flights(runs: &[&HostList]) -> bool { + use std::sync::Arc; + // Per copy, the span of what is refreshed (a flush brings that much + // up to date at most). + let mut spans: Vec<(Arc, usize, usize)> = Vec::new(); + for list in runs { + for step in &list.deferred().copies { + if let Step::Refresh(shadow, address, len) = step + && shadow.writes_pending() + { + match spans.iter_mut().find(|s| Arc::ptr_eq(&s.0, shadow)) { + Some(s) => (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len)), + None => spans.push((shadow.clone(), *address, *address + *len)), + } + } + } + } + if late_exact() { + // The title's bytes are put in beside the flights' writes; a + // settle is still due where that could not be done. At most this + // many changed runs go up to copies in the card's memory, each a + // copy of its own there. + let mut runs_left = 512; + return spans.iter().any(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left)); + } + spans.iter().any(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from)) +} + +/// 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. +pub(crate) fn late_signal(fence: usize, value: u64) -> bool { + if !late() { + return false; + } + let mut line = line(); + if line.line.is_empty() && !line.settling { + return false; + } + line.line.push(Late::Signal(fence, value)); + LATE_STATS[14].fetch_add(1, Ordering::Relaxed); + drop(line); + // A signal alone (behind a settle under way) has no flight to wake + // the helper thread for it. + LINE_MOVED.notify_one(); + RELAY_MOVED.notify_one(); + true +} + +/// A queue stands at `wait`, which memory does not meet now ([`late`]): +/// whether it is met once the flights in the air have run. A flight's +/// bottom-of-pipe write of a value that meets it says yes without a wait +/// for the card: the part behind the wait goes to the card behind that +/// flight, which is the order the wait asks for. If the flights may write +/// 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 { + let (address, bytes) = wait.place(); + { + let line = line(); + if line.line.is_empty() && line.in_hand.is_empty() { + return false; + } + let mut unsure = touches(&line.written, address, address + bytes); + // (With the relay: first the writes of flights being landed.) + let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item { + Late::Write(at, what, n) => Some((at, what, n)), + _ => None, + })); + for (at, what, n) in writes { + if *at >= address + bytes || address >= *at + *n { + continue; + } + match what { + 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; + } + } + _ => unsure = true, + } + } + if !unsure { + return false; + } + } + settle_now(WHY_VALUE); + wait.met() +} + +/// Settles the flights in the air, if any ([`Host::settle`]), for reason +/// `why` (one of the `WHY_` places). Not from inside a submission. +pub(crate) fn settle_now(why: usize) { + if !late() { + return; + } + let Some(host) = host() else { + return; + }; + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + host.settle(&mut submitted, why); +} + +/// [`settle_now`] at a present, and for a fence the title blocks on. +pub(crate) fn settle_for_present() { + settle_now(WHY_SYNC); +} +pub(crate) fn settle_for_fence() { + settle_now(WHY_FENCE); +} + +/// Resets the host lists of settled flights and keeps them for reuse, as +/// a queue does for the lists it ran (`crate::list::recycle`). +fn land() { + let landed = std::mem::take(&mut line().landed); + for (lists, order) in landed { + crate::list::recycle(lists, &order); + } +} + +/// The thread that settles the flights once the card has run them all +/// ([`late`]): without it a bottom-of-pipe write would reach the title only +/// at the next call that settles, and a title thread that polls such a +/// value while the submitting thread waits for that thread would never +/// see it. +fn late_helper() { + let Some(host) = host() else { + return; + }; + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + tracing::warn!("no event for the thread that settles submissions sent ahead"); + return; + }; + loop { + let target = { + let mut line = line(); + loop { + if line.poke { + line.poke = false; + break None; + } + // (With the relay the flights are another thread's.) + if !relay() && !line.line.is_empty() && !line.settling { + break Some(line.target); + } + line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner()); + } + }; + let Some(target) = target else { + land(); + crate::queue::release_held(false); + continue; + }; + // The card first, without the submission lock: the submitting + // thread prepares and sends meanwhile. + // SAFETY: our fence and event. + unsafe { + if host.fence.SetEventOnCompletion(target, event).is_ok() { + WaitForSingleObject(event, INFINITE); + } + } + { + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + // Something newer went up meanwhile: the card is waited for + // again, the submitting thread is not held up for it. + if line().target != target { + continue; + } + host.settle(&mut submitted, WHY_CARD_DONE); + } + land(); + crate::queue::release_held(false); + } +} + +/// Starts the threads of [`late`], once: the one that settles flights when +/// the card has run them and looks at what queues hold, and with [`relay`] +/// the one that lands flights. +fn late_threads() { + static HELPER: std::sync::Once = std::sync::Once::new(); + HELPER.call_once(|| { + if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) { + tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow"); + } + tracing::info!( + most = late_most(), + writes = late_writes(), + "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)" + ); + if relay() { + // Without it nothing would ever land. + if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) { + fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}")); + } + tracing::info!( + exact = relay_exact(), + "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)" + ); + } + }); +} + +/// With [`relay`]: waits until `done` says so of the line, looked at each +/// time flights have landed. Counted as a settle for `why`, and its time +/// as waiting for the card. The caller may hold the submission lock: the +/// thread that lands flights never takes it. +fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) { + let mut line = line(); + if done(&line) { + return; + } + LATE_STATS[1].fetch_add(1, Ordering::Relaxed); + LATE_STATS[why].fetch_add(1, Ordering::Relaxed); + let was_working = working(false); + let waiting = std::time::Instant::now(); + while !done(&line) { + line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner()); + } + drop(line); + stood(waiting); + working(was_working); + let us = waiting.elapsed().as_micros() as u64; + LATE_STATS[12].fetch_add(us, Ordering::Relaxed); + LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed); + SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed); +} + +/// What the thread that lands flights fetches card copies' pieces with +/// ([`relay`]): a list, a fence and an event of its own (the host's are +/// behind the submission lock), and the memory the pieces come down to. +struct RelayFetch { + list: Prelude, + fence: ID3D12Fence, + event: HANDLE, + /// The last value signalled on `fence`. + sent: u64, + /// Buffer, mapping, bytes. + buffer: Option<(ID3D12Resource, usize, u64)>, +} + +/// The thread that lands flights ([`relay`]): as soon as the card has run +/// the first flights of the line it takes them, with what follows them, +/// and does what they left to do ([`Host::relay_land`]); else it waits for +/// the card, or for a flight. It takes neither the submission lock nor +/// anything a caller of [`Host::settle`] may hold: resetting the landed +/// lists and looking at what queues hold are left to [`late_helper`]. +fn relay_worker() { + let Some(host) = host() else { + return; + }; + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)")); + }; + let mut fetch: Option = None; + loop { + let next = { + let mut line = line(); + loop { + if line.line.is_empty() { + line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner()); + continue; + } + let fences: Vec> = line + .line + .iter() + .map(|l| match l { + Late::Run(flight) => Some(flight.fence), + _ => None, + }) + .collect(); + // SAFETY: a plain query. + let completed = unsafe { host.fence.GetCompletedValue() }; + let n = landable(&fences, completed); + if n == 0 { + // The first thing is a flight the card has not run. + break Err(fences[0].unwrap_or(0)); + } + line.settling = true; + let items: Vec = line.line.drain(..n).collect(); + line.in_hand = items + .iter() + .filter_map(|l| match l { + Late::Write(at, what, bytes) => Some((*at, *what, *bytes)), + _ => None, + }) + .collect(); + break Ok(items); + } + }; + match next { + Ok(items) => host.relay_land(items, &mut fetch), + Err(target) => { + let waiting = std::time::Instant::now(); + // SAFETY: the host's fence and this thread's event. + let waited = unsafe { + host.fence.SetEventOnCompletion(target, event).map(|()| { + WaitForSingleObject(event, INFINITE); + }) + }; + if waited.is_err() { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + } + } + } +} + +/// [`relay`]: what shaders wrote to the declared ranges `back` of copies +/// in the PC's memory goes into title memory. As [`hand_back`], each byte +/// once, the pieces that differ found on several threads; but the merge is +/// `Shadow::relay_merge`, which does not write the copy, and the ranges +/// are not done with here (each flight's are, afterwards). +fn relay_hand_back(back: &[Declared]) { + let mut work: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); + for (shadow, declared) in back { + if shadow.carded() { + continue; + } + let mut spans: Vec<(usize, usize)> = Vec::new(); + join_ranges(&mut spans, declared.iter().copied()); + for &(from, to) in &spans { + shadow.relay_compared(from, to - from); + } + work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to))); + } + if work.is_empty() { + return; + } + #[cfg(feature = "diagnostics")] + let scanning = std::time::Instant::now(); + // Looked through without a lock: a piece that changes meanwhile (a + // later flight writing, the title's bytes going in) is found now or by + // that flight's landing, and the merge looks again under the lock. + let found = crate::shadow::find_all(&work); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64); + let (mut now, mut title) = (Vec::new(), Vec::new()); + for ((shadow, from, to), found) in work.iter().zip(found) { + let mut written = 0; + for (at, n) in found { + written += shadow.relay_merge(at, n, &mut now, &mut title); + } + COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::compared(*from, to - from, written); + let _ = (from, to); + } +} + +/// For the frame-rate line, with [`late`]: what the line of flights did +/// per frame since the last one. +fn late_line(frames: f64) { + if !late() { + return; + } + let s: Vec = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \ + settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \ + title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \ + a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \ + bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \ + {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights", + s[0], + s[1], + if s[1] > 0.0 { s[11] / s[1] } else { 0.0 }, + s[12] / 1000.0, + s[WHY_SYNC], + s[WHY_CARD_DONE], + s[WHY_VALUE], + s[WHY_STALE], + s[WHY_READ], + s[15], + s[16], + s[17], + s[WHY_RUN], + late_most(), + s[WHY_MOST], + s[WHY_WRITES], + s[WHY_FENCE], + s[13], + s[14], + ); + { + let w: Vec = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect(); + tracing::info!( + "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \ + the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \ + title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}", + w[WHY_SYNC], + w[WHY_CARD_DONE], + w[WHY_VALUE], + w[WHY_STALE], + w[WHY_READ], + w[WHY_RUN], + w[WHY_MOST], + w[WHY_WRITES], + w[WHY_FENCE], + ); + } + if relay() { + let r: Vec = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \ + beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \ + fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \ + \"settles\" above are waits of other threads for it)", + r[1], + r[0], + r[2] / 1000.0, + r[3] / 1000.0, + r[4] / 1000.0, + ); + } + if late_exact() { + let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames); + tracing::info!( + "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \ + {runs:.0} changed runs, {:.2} MB", + bytes / (1 << 20) as f64 + ); + } +} + +#[cfg(test)] +mod late_tests { + use super::{continues, join_ranges, touches}; + + /// Copies join only when both ends continue and the whole does not + /// overlap itself. + #[test] + fn copies_join_only_end_to_end_and_apart() { + // (destination, source, bytes) + assert!(continues((1000, 5000, 16), (1016, 5016, 32))); + assert!(continues((5000, 1000, 16), (5016, 1016, 32))); + // A gap, or only one side continues. + assert!(!continues((1000, 5000, 16), (1020, 5016, 32))); + assert!(!continues((1000, 5000, 16), (1016, 5020, 32))); + assert!(!continues((1000, 5000, 16), (1000, 5000, 16))); + // Together they would overlap: the second reads what the first wrote. + assert!(!continues((1000, 1016, 16), (1016, 1032, 16))); + assert!(!continues((1016, 1000, 16), (1032, 1016, 16))); + // They touch without overlapping. + assert!(continues((1000, 1032, 16), (1016, 1048, 16))); + assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8))); + } + + /// Ranges are found by what they hold, not by where they start, and a + /// range that only touches another's end does not touch it. + #[test] + fn ranges_touch_where_they_overlap() { + let mut ranges = Vec::new(); + join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]); + assert_eq!(ranges, [(10, 25), (40, 60)]); + join_ranges(&mut ranges, [(25, 40)]); + assert_eq!(ranges, [(10, 60)]); + let ranges = [(10usize, 25usize), (40, 60), (100, 101)]; + for (from, to, hit) in [ + (0, 10, false), + (0, 11, true), + (24, 25, true), + (25, 40, false), + (25, 41, true), + (59, 200, true), + (60, 100, false), + (100, 101, true), + (101, 500, false), + (30, 30, false), + (50, 50, false), + ] { + assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}"); + } + assert!(!touches(&[], 0, usize::MAX)); + } +} + +/// Whether a title buffer copy that continues the one recorded before it +/// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by +/// default). +/// +/// Each copy is done at submission through the kernel, which reports a +/// page that is not there instead of faulting (`copy_mapped`), tells the +/// write watch and the guards, and ends the refreshes gathered so far: a +/// call into the kernel for some 480 bytes, 14,042 times a frame in run 86 +/// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them +/// continue the one before is counted either way and said on its own line +/// with the frame rate; the switch is worth that many kernel calls. +/// +/// Joined, the same bytes move: [`continues`] joins only copies whose +/// ranges, taken together, do not overlap, and nothing is recorded between +/// two steps that follow each other. What differs: a page that is not +/// mapped now fails the joined copy as a whole (it then goes page by page, +/// zeros for what cannot be read, as a single copy does), where before +/// only the copy that held it did. +fn join_copies() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1")) +} + +/// Since the last frame-rate line: title buffer copies recorded, and those +/// that continue the one before ([`join_copies`]). +static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether the copy `next` (destination, source, bytes) goes on exactly +/// where `last` ended, source and destination both, and the two as one do +/// not overlap (source over destination): then one copy of both moves the +/// bytes the two would move in turn. +fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool { + let ((d, s, n), (dst, src, len)) = (last, next); + let Some(all) = n.checked_add(len) else { + return false; + }; + d.checked_add(n) == Some(dst) + && s.checked_add(n) == Some(src) + && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d)) +} + +/// The ranges the shaders of `runs` may write, per host copy, as declared. +/// One list's lock at a time: a submission may name a list twice. +fn declared_writes(runs: &[&HostList]) -> Vec { + let mut back: Vec = Vec::new(); + for list in runs { + for step in &list.deferred().copies { + if let Step::GpuWrite(shadow, address, len) = step { + let range = (*address, *address + *len); + match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + Some((_, ranges)) => { + if !ranges.contains(&range) { + ranges.push(range); + } + } + None => back.push((shadow.clone(), vec![range])), + } + } + } + } + back +} + +/// After `list` has run: the texels its read-backs copied into host +/// buffers of ours go to the title's memory (`HostList::defer_read_back`). +/// +/// A submission that is waited for did this itself. One sent ahead +/// ([`late`]) did not, at any stage: the flights' lists were settled +/// without it, so the title read a buffer nobody wrote, as before read-backs +/// were made (the exposure metering's two small float targets, every frame). +fn read_backs(list: &HostList) { + for (buffer, at, [row, rows, pitch]) in &list.deferred().backs { + let mut data = std::ptr::null_mut(); + // SAFETY: a read-back buffer of ours, written by the list that has + // run; the title's destination holds every row (checked when the + // copy was recorded). + unsafe { + if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() { + let from = data.cast::().cast_const(); + for line in 0..*rows { + std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row); + } + buffer.Unmap(0, None); + } + } + } +} + +/// After the card ran what declared `back`: what shaders wrote there goes +/// into title memory, and the ranges are done with. +fn hand_back(back: &[Declared]) { + if crate::shadow::wide_back() { + // Every range first (the pieces that differ, found on several + // threads), then the merges, in order, as below. + let mut work: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); + for (shadow, declared) in back { + if shadow.carded() { + continue; + } + let mut sorted = declared.clone(); + sorted.sort_unstable(); + let mut spans: Vec<(usize, usize)> = Vec::new(); + for (from, to) in sorted { + match spans.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => spans.push((from, to)), + } + } + work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to))); + } + #[cfg(feature = "diagnostics")] + let scanning = std::time::Instant::now(); + let found = crate::shadow::find_all(&work); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64); + for ((shadow, from, to), found) in work.iter().zip(found) { + let written = shadow.copy_back_with(*from, to - from, Some(found)); + COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::compared(*from, to - from, written); + } + for (shadow, declared) in back { + shadow.copy_back_done(declared); + } + return; + } + for (shadow, declared) in back { + if shadow.carded() { + // Done before (`Host::card_back`). + shadow.copy_back_done(declared); + continue; + } + // Each byte compared once: the world declares dozens of views + // of its 174 MB heap that overlap almost entirely, and comparing + // every one whole was gigabytes a frame (0.3-0.5 s) for the few + // MB shaders wrote. Only ranges that overlap or touch are + // joined: what lies between two was not given to shaders (the + // snapshot does not hold it). + let mut sorted = declared.clone(); + sorted.sort_unstable(); + let mut spans: Vec<(usize, usize)> = Vec::new(); + for (from, to) in sorted { + match spans.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => spans.push((from, to)), + } + } + for (from, to) in spans { + let written = shadow.copy_back(from, to - from); + COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::compared(from, to - from, written); + } + shadow.copy_back_done(declared); + } +} + impl Host { /// Whether the host runs mesh shaders at shader model 6.6 (translated /// mesh shaders need both); logged once. @@ -451,6 +2764,50 @@ impl Host { /// A new list, open for recording. pub(crate) fn new_list(&self) -> windows::core::Result { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + let before = private_bytes(); + let list = self.make_list(); + LISTS[0].fetch_add(1, Ordering::Relaxed); + // (May shrink while a list is made, on another thread's account: + // added as it is, the sum is what counts.) + #[cfg(feature = "diagnostics")] + LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::HostLists, 1); + add(C::HostListNs, started.elapsed().as_nanos() as u64); + } + list + } + + /// An allocator and a closed list for a prelude. + fn make_prelude(&self) -> Option { + // SAFETY: plain object creation. + let made: windows::core::Result = unsafe { + (|| { + let allocator: ID3D12CommandAllocator = + self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = + self.device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.Close()?; + Ok((allocator, list)) + })() + }; + LISTS[1].fetch_add(1, Ordering::Relaxed); + match made { + Ok(prelude) => Some(prelude), + Err(e) => { + tracing::warn!(error = %e, "no host list for a prelude"); + None + } + } + } + + fn make_list(&self) -> windows::core::Result { // SAFETY: plain object creation. unsafe { let allocator: ID3D12CommandAllocator = self @@ -462,25 +2819,22 @@ impl Host { &allocator, None, )?; - let prelude_allocator: ID3D12CommandAllocator = self - .device - .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let prelude: ID3D12GraphicsCommandList = self.device.CreateCommandList( - 0, - D3D12_COMMAND_LIST_TYPE_DIRECT, - &prelude_allocator, - None, - )?; - prelude.Close()?; + let prelude = OnceLock::new(); + if !lazy_prelude() { + let _ = prelude.set(self.make_prelude()); + } Ok(HostList { allocator, list, deferred: Mutex::default(), scratch: Mutex::default(), states: Mutex::default(), - prelude: (prelude_allocator, prelude), + twins: Mutex::default(), + prelude, pipelines: Mutex::default(), budget: OnceLock::new(), + indirect_args: Mutex::default(), + _alive: Counted::new(), #[cfg(feature = "diagnostics")] notes: Mutex::default(), #[cfg(feature = "diagnostics")] @@ -489,18 +2843,1108 @@ impl Host { } } - /// Runs closed lists and waits for them. + /// The card's clock ([`CARD_CLOCK_US`]), made at the first send. + fn card_clock(&self) -> Option<&'static CardClock> { + static CLOCK: OnceLock> = OnceLock::new(); + static WATCH: std::sync::Once = std::sync::Once::new(); + let clock = CLOCK + .get_or_init(|| { + // SAFETY: a plain fence on our device. + let fence = unsafe { self.device.CreateFence::(0, D3D12_FENCE_FLAG_NONE) }.ok()?; + Some(CardClock { + fence, + state: Mutex::new((0, None)), + sent: std::sync::Condvar::new(), + }) + }) + .as_ref()?; + WATCH.call_once(|| { + if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) { + tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0"); + } + }); + Some(clock) + } + + /// Lists of ours just went to the queue: the clock's signal goes + /// behind them, and an idle stretch of the card, if one was under way, + /// ends here ([`CARD_CLOCK_US`]). + fn card_sent(&self) { + let Some(clock) = self.card_clock() else { + return; + }; + let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner()); + state.0 += 1; + // SAFETY: our queue and the clock's fence. + let _ = unsafe { self.queue.Signal(&clock.fence, state.0) }; + if let Some((since, worked_then)) = state.1.take() { + CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed); + CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed); + } + drop(state); + clock.sent.notify_one(); + } + + /// Whether the host has what copies in the card's memory need (three + /// lists and the compare); made at the first ask. A copy goes to the + /// card's memory only if it has. + pub(crate) fn card_ready(&self) -> bool { + static READY: OnceLock = OnceLock::new(); + *READY.get_or_init(|| match self.make_card_work() { + Ok(work) => { + *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work); + true + } + Err(e) => { + tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made"); + false + } + }) + } + + fn make_card_work(&self) -> windows::core::Result { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let mut code: Option = None; + // SAFETY: the source and names live through the call; the out + // pointer is ours. + unsafe { + D3DCompile( + CARD_COMPARE.as_ptr().cast(), + CARD_COMPARE.len(), + windows::core::s!("card compare"), + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + } + let code = code.ok_or_else(windows::core::Error::empty)?; + let list = || self.make_prelude().ok_or_else(windows::core::Error::empty); + // A megabyte of results: 262,144 pieces, 16 GB of declared ranges + // in one submission. + const RESULTS: u64 = 1 << 20; + let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?; + name(&differs, || "card compare results".into()); + // SAFETY: the blob's own bytes; the root signature is inside the + // shader. + unsafe { + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + Ok(CardWork { + sync: vec![list()?], + check: vec![list()?], + fetch: list()?, + root, + pso, + differs: (differs, data as usize, RESULTS), + fetched: None, + taken: 0, + out: 0, + }) + } + } + + /// Before a submission's lists run, for copies in the card's memory + /// ([`crate::shadow::cards`]): what changed on their CPU side since + /// the last submission goes to their card side (a list of ours, run + /// now; the submission's lists follow it on the queue), and the ranges + /// this submission's shaders may write get a compare to run after its + /// lists. `None` if there is nothing to do. + /// + /// `flown`: the submission is sent ahead with [`relay`]. Its compare + /// then stores the hashes it makes (see [`flagged_pieces`] and + /// `relay`). + fn card_before(&self, runs: &[&HostList], 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])), + } + } + } + } + // With the relay: the order of the queue is held from here until + // what is taken is on the queue, and the taking is numbered. + let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); + let sent_as = match order.as_mut() { + Some(order) => { + **order += 1; + **order + } + None => 0, + }; + let mut dirty = crate::shadow::card_dirty(sent_as); + if declared.is_empty() && dirty.is_empty() { + return None; + } + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let work = work.as_mut()?; + // A copy whose shader writes are declared for the first time gets + // its bytes from before, whole. + let mut whole: Vec> = Vec::new(); + for (shadow, _) in &declared { + if shadow.card_make_before(|size| { + let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?; + name(&before, || "title buffer on the card, hashes of its pieces".into()); + Some(before) + }) { + whole.push(shadow.clone()); + if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) { + dirty.push((shadow.clone(), Vec::new())); + } + } + } + let mut used: Vec<(bool, Prelude)> = Vec::new(); + if !dirty.is_empty() { + let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else { + fail(format_args!("no host list to bring host copies in the card's memory up to date")); + }; + let (allocator, list) = &sync; + // SAFETY: the list's last run finished (it ran ahead of a + // submission that was waited for, and came back after that); + // live buffers, and the ranges lie in them. + let recorded = unsafe { + (|| -> windows::core::Result<()> { + allocator.Reset()?; + list.Reset(allocator, None)?; + for (shadow, ranges) in &dirty { + let Some((staging, before, size)) = shadow.card_sides() else { + continue; + }; + for &(a, b) in ranges { + list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64); + 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); + let Some(before) = before else { + continue; + }; + // No twin (it cost the card the copy's size again, + // 399 MB in run 75): `before` holds a 128-bit hash + // of each 64 KiB piece. The pieces just sent up are + // hashed again, all of them the first time; the + // compare after the lists hashes the declared + // pieces and flags those whose hash is another. + if !ranges.is_empty() { + list.ResourceBarrier(&[transition( + &shadow.buffer, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + } + list.SetComputeRootSignature(&work.root); + list.SetPipelineState(&work.pso); + list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); + let runs: Vec = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) { + vec![shadow.card_run(0, usize::MAX)] + } else { + ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect() + }; + // The same pieces in fewer passes (`rehash_runs`). + let runs = if rehash_runs() { crate::shadow::joined_piece_runs(runs) } else { runs }; + CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed); + CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::(), Ordering::Relaxed); + for run in runs { + let constants = [run.first, run.skew, size as u32, run.pieces, 0, 0]; + list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + list.Dispatch(run.pieces.div_ceil(64), 1, 1); + } + } + list.Close()?; + self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); + Ok(()) + })() + }; + if let Err(e) = recorded { + fail(format_args!("host copies in the card's memory could not be brought up to date ({e})")); + } + used.push((false, sync)); + } + drop(order); + let mut plan = CardPlan { + ranges: Vec::new(), + check: None, + _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(), + lists: used, + }; + // Each byte once, as the copy-back joins the declared ranges. The + // results go behind those of plans still in the air. + let mut at = work.taken; + for (shadow, ranges) in &declared { + let mut sorted = ranges.clone(); + sorted.sort_unstable(); + let mut spans: Vec<(usize, usize)> = Vec::new(); + for (from, to) in sorted { + match spans.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => spans.push((from, to)), + } + } + let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); + for (from, to) in spans { + let Some(span) = shadow.card_span(from, to) else { + continue; + }; + let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2; + plan.ranges.push(CardRange { + shadow: shadow.clone(), + declared: (from, to), + span, + at, + compared, + }); + if compared { + at += span.pieces; + } + } + } + work.taken = at; + if plan.ranges.iter().any(|r| r.compared) { + let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else { + fail(format_args!("no host list for the compare of host copies in the card's memory")); + }; + let (allocator, list) = ✓ + // SAFETY: the list's last run finished (its submission was + // waited for, and it came back after that); live buffers; the + // compare's own root signature. + let recorded = unsafe { + (|| -> windows::core::Result { + allocator.Reset()?; + list.Reset(allocator, None)?; + // What the submission's shaders wrote, first. + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + list.SetComputeRootSignature(&work.root); + list.SetPipelineState(&work.pso); + list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); + for r in plan.ranges.iter().filter(|r| r.compared) { + let Some((_, Some(before), size)) = r.shadow.card_sides() else { + continue; + }; + let constants = [r.span.first, r.span.skew, size as u32, r.span.pieces, r.at * 4, if flown { 2 } else { 1 }]; + list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); + list.Dispatch(r.span.pieces.div_ceil(64), 1, 1); + CARD_PASSES[2].fetch_add(1, Ordering::Relaxed); + } + list.Close()?; + list.cast() + })() + }; + match recorded { + Ok(list) => plan.check = Some(list), + Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")), + } + plan.lists.push((true, check)); + } + work.out += 1; + Some(plan) + } + + /// With [`relay`]: whether the compare's result area is half taken by + /// plans in the air. It starts from the beginning only when no plan is + /// out, so the caller lets the flights land first. + fn card_results_low(&self) -> bool { + CARD_WORK + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2) + } + + /// The plan's submission has run and its results were read + /// ([`Host::card_back`]): its lists are free for the next plan. Called + /// when nothing of ours is on the card, so the compare's results start + /// from the beginning again. + fn card_done(&self, plan: CardPlan) { + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(work) = work.as_mut() else { + return; + }; + for (check, list) in plan.lists { + if check { work.check.push(list) } else { work.sync.push(list) } + } + work.out = work.out.saturating_sub(1); + // With the relay other plans may be on the card, their results + // not read yet: the area starts again only when none is out. + if !relay() || work.out == 0 { + work.taken = 0; + } + } + + /// The relay's own list, fence, event for [`Host::relay_card_back`]. + fn make_relay_fetch(&self) -> Option { + let list = self.make_prelude()?; + // SAFETY: plain objects of our own. + unsafe { + let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + Some(RelayFetch { + list, + fence, + event, + sent: 0, + buffer: None, + }) + } + } + + /// [`relay`], on the thread that lands flights: for the plans of the + /// flights being landed (the card has run them), the pieces their + /// compares flagged are fetched, once each, with a list and a wait of + /// this thread's own, and what shaders wrote in them goes into title + /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but: + /// no submission lock; a piece flagged under one range of a plan is + /// fetched under all ([`flagged_pieces`]); the fetch runs behind + /// whatever was sent meanwhile, so it may bring a later flight's + /// bytes, which that flight's landing then finds merged already; and + /// nothing is sent back up. + fn relay_card_back(&self, plans: &[&CardPlan], fetch: &mut Option) { + let differs = { + let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize)) + }; + let mut pieces: Vec<(std::sync::Arc, usize, usize, u64)> = Vec::new(); + let mut total = 0u64; + if let Some((differs, dwords)) = differs { + // SAFETY: the mapping of the results. The compares of these + // plans have run, and their dwords are given to no other plan + // before these are done with (`card_done`). + let differs = unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) }; + let mut seen = std::collections::HashSet::new(); + for plan in plans { + let flags: Vec<(usize, u32, bool)> = plan + .ranges + .iter() + .flat_map(|r| { + (0..r.span.pieces).map(move |p| { + let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| d != 0); + (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, flagged) + }) + }) + .collect(); + let fetched = flagged_pieces(&flags); + for r in &plan.ranges { + let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; + for p in 0..r.span.pieces { + if !fetched.contains(&(copy, r.span.first + p)) { + continue; + } + let (lo, hi) = r.shadow.card_piece(&r.span, p); + if lo < hi && seen.insert((copy, lo, hi)) { + pieces.push((r.shadow.clone(), lo, hi, total)); + total += (hi - lo) as u64; + } + } + crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); + } + } + } + if pieces.is_empty() { + // Nothing to fetch: every send so far is older than the next fetch. + crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); + return; + } + if fetch.is_none() { + *fetch = self.make_relay_fetch(); + } + let Some(f) = fetch.as_mut() else { + fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)")); + }; + if f.buffer.as_ref().is_none_or(|b| b.2 < total) { + let size = total.next_multiple_of(16 << 20); + f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); + } + let Some((buffer, data, _)) = f.buffer.clone() else { + fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)")); + }; + f.sent += 1; + let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent); + let waiting = std::time::Instant::now(); + // SAFETY: the list's last run was waited for by this thread; live + // buffers (the copies are held by the plans); the fence and the + // event are this thread's. + let ran = unsafe { + (|| -> windows::core::Result { + allocator.Reset()?; + list.Reset(&allocator, None)?; + for (shadow, lo, hi, at) in &pieces { + list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64); + } + list.Close()?; + let lists = [Some(list.cast::()?)]; + // In the order of the queue: the sends of title bytes so + // far are ahead of this fetch, every later one behind it. + let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()); + self.queue.ExecuteCommandLists(&lists); + let after = *order; + drop(order); + self.card_sent(); + self.queue.Signal(&fence, sent)?; + fence.SetEventOnCompletion(sent, event)?; + WaitForSingleObject(event, INFINITE); + Ok(after) + })() + }; + let after = match ran { + Ok(after) => after, + Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")), + }; + let us = waiting.elapsed().as_micros() as u64; + RELAY_STATS[3].fetch_add(us, Ordering::Relaxed); + { + use crate::shadow::CARD_STATS; + CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed); + CARD_STATS[4].fetch_add(total, Ordering::Relaxed); + CARD_STATS[5].fetch_add(1, Ordering::Relaxed); + CARD_STATS[6].fetch_add(us, Ordering::Relaxed); + } + let mut title = Vec::new(); + let mut written = 0; + for (shadow, lo, hi, at) in &pieces { + // SAFETY: the mapping of the fetched bytes, `total` of them; + // the copy into it has run. + let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) }; + written += shadow.card_merge_relay(*lo, gpu, after, &mut title); + } + COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + // Sends up to `after` are of no use to any later merge. + crate::shadow::relay_fetched(after); + } + + /// [`relay`], on the thread that lands flights: `items` are the first + /// things of the line, flights the card has run and what follows them. + /// What their shaders wrote goes into title memory (copies in the + /// card's memory first, then the others, each byte once whichever + /// flights declared it); then every flight's ranges are done with; + /// then, in the line's order, each flight's read-backs, its + /// bottom-of-pipe writes and the fence signals behind it. Title memory + /// is complete before the title is told anything. + fn relay_land(&self, items: Vec, fetch: &mut Option) { + let landing = std::time::Instant::now(); + { + let flights: Vec<&Flight> = items + .iter() + .filter_map(|l| match l { + Late::Run(flight) => Some(flight), + _ => None, + }) + .collect(); + if !flights.is_empty() { + // SAFETY: a plain query. + if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { + let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect(); + fail(format_args!( + "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}", + flights.len(), + runs.len(), + self.removal_data(&runs), + last_notes(&runs) + )); + } + let plans: Vec<&CardPlan> = flights.iter().filter_map(|f| f.card.as_ref()).collect(); + self.relay_card_back(&plans, fetch); + let mut back: Vec = Vec::new(); + for flight in &flights { + for (shadow, ranges) in &flight.back { + match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + Some((_, all)) => { + for range in ranges { + if !all.contains(range) { + all.push(*range); + } + } + } + None => back.push((shadow.clone(), ranges.clone())), + } + } + } + relay_hand_back(&back); + // Only now, and flight by flight: a range another flight + // in the air declared too stays closed to refreshes. + for flight in &flights { + for (shadow, ranges) in &flight.back { + shadow.copy_back_done(ranges); + } + } + COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); + RELAY_STATS[0].fetch_add(1, Ordering::Relaxed); + RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed); + } + } + // In the order given: what tells the title the card is done. + let mut last = 0; + let mut landed = Vec::new(); + for item in items { + match item { + Late::Run(flight) => { + last = flight.number; + for &i in &flight.order { + read_backs(flight.lists[i].host()); + } + if let Some(card) = flight.card { + self.card_done(card); + } + landed.push((flight.lists, flight.order)); + } + Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), + Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value), + } + } + if last > 0 { + FINISHED.store(last, Ordering::Release); + bury(last); + } + self.log_messages(); + RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); + { + let mut line = line(); + let Line { + line: items, + written, + lists, + settling, + poke, + landed: kept, + in_hand, + .. + } = &mut *line; + kept.extend(landed); + in_hand.clear(); + // What is still in the air, from the flights that are. + written.clear(); + *lists = 0; + let mut ranges = Vec::new(); + for item in items.iter() { + if let Late::Run(flight) = item { + *lists += flight.order.len().max(1); + ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied())); + } + } + join_ranges(written, ranges); + *settling = false; + // The landed lists are reset, and what queues hold looked at, + // by the helper thread (they take locks a waiter may hold). + *poke = true; + } + LINE_MOVED.notify_all(); + LINE_LANDED.notify_all(); + } + + /// After a submission ran, for copies in the card's memory: the pieces + /// of the declared ranges that the compare found differing (all of a + /// range it did not compare) are fetched, with one more wait for the + /// card, and what shaders wrote in them goes into title memory. + /// `submitted` is the last value signalled on the fence. `seen` holds + /// the pieces fetched already since the card was last waited for + /// (several submissions settled together name the same ones). + fn card_back( + &self, + plan: &CardPlan, + submitted: &mut u64, + seen: &mut std::collections::HashSet<(usize, usize, usize)>, + ) { + if plan.ranges.is_empty() { + return; + } + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(work) = work.as_mut() else { + return; + }; + // SAFETY: the mapping of the results, which the compare (it has + // run) wrote. + let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) }; + // The pieces to fetch: the range, the offsets in its copy, and + // where the bytes come down. + let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new(); + let mut total = 0u64; + for (i, r) in plan.ranges.iter().enumerate() { + for p in 0..r.span.pieces { + if r.compared && differs[(r.at + p) as usize] == 0 { + continue; + } + let (lo, hi) = r.shadow.card_piece(&r.span, p); + if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) { + pieces.push((i, lo, hi, total)); + total += (hi - lo) as u64; + } + } + crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); + } + let mut written = vec![0usize; plan.ranges.len()]; + if !pieces.is_empty() { + if work.fetched.as_ref().is_none_or(|f| f.2 < total) { + let size = total.next_multiple_of(16 << 20); + work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); + } + let Some((fetched, data, _)) = &work.fetched else { + fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)")); + }; + let waiting = std::time::Instant::now(); + let (allocator, list) = &work.fetch; + // SAFETY: the list's last run was waited for; live buffers; the + // fence and event are ours, under the submission lock. + let ran = unsafe { + (|| -> windows::core::Result<()> { + allocator.Reset()?; + list.Reset(allocator, None)?; + for &(i, lo, hi, at) in &pieces { + list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64); + } + list.Close()?; + self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); + self.card_sent(); + *submitted += 1; + self.queue.Signal(&self.fence, *submitted)?; + self.fence.SetEventOnCompletion(*submitted, self.event)?; + let was_working = working(false); + WaitForSingleObject(self.event, INFINITE); + stood(waiting); + working(was_working); + Ok(()) + })() + }; + if let Err(e) = ran { + fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})")); + } + { + use crate::shadow::CARD_STATS; + CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed); + CARD_STATS[4].fetch_add(total, Ordering::Relaxed); + CARD_STATS[5].fetch_add(1, Ordering::Relaxed); + CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + } + if wide_merge() && pieces.len() >= 8 { + // The pieces are apart from one another (each its own bytes + // of its copy and of title memory): several at a time. + let fetched = *data; + let counts: std::sync::Arc> = + std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect()); + let each = pieces.len().div_ceil(8); + let jobs: Vec> = pieces + .chunks(each) + .map(|chunk| { + let chunk: Vec<(std::sync::Arc, usize, usize, usize, u64)> = + chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect(); + let counts = counts.clone(); + Box::new(move || { + let mut title = Vec::new(); + for (shadow, i, lo, hi, at) in chunk { + // SAFETY: the mapping of the fetched bytes; + // the copy into it has run, and the caller + // waits for this job. + let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) }; + counts[i].fetch_add(shadow.card_merge(lo, gpu, &mut title), Ordering::Relaxed); + } + }) as Box + }) + .collect(); + crate::shadow::wide_run(jobs); + for (written, count) in written.iter_mut().zip(counts.iter()) { + *written += count.load(Ordering::Relaxed); + } + } else { + let mut title = Vec::new(); + for &(i, lo, hi, at) in &pieces { + // SAFETY: the mapping of the fetched bytes, `total` of + // them; the copy into it has run. + let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) }; + written[i] += plan.ranges[i].shadow.card_merge(lo, gpu, &mut title); + } + } + } + for (r, written) in plan.ranges.iter().zip(written) { + COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + let (from, to) = r.declared; + #[cfg(feature = "diagnostics")] + crate::copystat::compared(from, to - from, written); + let _ = (from, to); + } + } + + /// Runs closed lists and waits for them, and with [`late`] for + /// everything sent to the card before them, which is settled first. pub(crate) fn execute(&self, runs: &[&HostList]) { + let _ = self.submit(runs, false); + } + + /// A queue's submission with [`late`]: the host lists `lists`, taken + /// from the title's, go to the card in `order` and are not waited for. + /// They join the line of flights and are settled, with the others in + /// the air, at the next point where what they do can be observed + /// ([`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) { + if order.is_empty() { + crate::list::recycle(lists, &order); + return; + } + late_threads(); + let sent = { + let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect(); + self.submit(&runs, true) + }; + let Some((mut submitted, sent)) = sent else { + // (Not reached: a submission sent ahead always comes back.) + crate::list::recycle(lists, &order); + return; + }; + let told = !sent.writes.is_empty(); + let most = { + let mut line = line(); + let Line { line: items, written, lists: flying, target, .. } = &mut *line; + join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied())); + *flying += order.len(); + *target = *submitted; + items.push(Late::Run(Flight { + number: sent.number, + fence: *target, + lists, + order, + card: sent.card, + back: sent.back, + })); + items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); + *flying >= late_most() + }; + LATE_STATS[0].fetch_add(1, Ordering::Relaxed); + RELAY_MOVED.notify_one(); + if told && !late_writes() { + self.settle(&mut submitted, WHY_WRITES); + } else if most && relay_exact() { + // Until there are fewer, not until there are none. + relay_wait(WHY_MOST, |line| line.lists < late_most()); + } else if most { + self.settle(&mut submitted, WHY_MOST); + } else { + LINE_MOVED.notify_one(); + } + drop(submitted); + land(); + } + + /// Sends `list`, a closed list of ours (the present's copy), as a + /// flight ([`late_free_present`]): not waited for, settled with the + /// others. The caller keeps the list and does not reset it before the + /// submission whose number comes back has finished ([`FINISHED`]); 0 if + /// 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 { + return 0; + }; + let number = sent.number; + { + let mut line = line(); + let Line { line: items, written, lists: flying, target, .. } = &mut *line; + join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied())); + *flying += 1; + *target = *submitted; + items.push(Late::Run(Flight { + number, + fence: *target, + lists: Vec::new(), + order: Vec::new(), + card: sent.card, + back: sent.back, + })); + items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); + } + LATE_STATS[0].fetch_add(1, Ordering::Relaxed); + LINE_MOVED.notify_one(); + RELAY_MOVED.notify_one(); + drop(submitted); + number + } + + /// Waits for the card to run every flight in the air ([`late`]) and + /// does what they left to do, as [`Host::execute`] does for one + /// submission after its wait: the pieces their shaders wrote in copies + /// in the card's memory are fetched and merged (each once), the ranges + /// they declared in the other copies are compared and copied back + /// (each byte once, whichever flights declared it), and then, in the + /// order they were given: their bottom-of-pipe writes and the fence + /// signals behind them. `submitted` is the submission lock's value; + /// `why` one of the `WHY_` places. Nothing happens if nothing flies. + /// + /// Everything in the air is settled, never the first flights alone: + /// the merge writes the copies' CPU side, which a flight still on the + /// card may be writing too. + fn settle(&self, submitted: &mut u64, why: usize) { + if !late() { + return; + } + if relay() { + // Nothing is settled here: the thread that lands flights does + // it, in order, and this waits until nothing is in the air and + // nothing is being landed. Every point that settled before + // comes here, so each still sees title memory, fences and + // bottom-of-pipe values as after a settle. + relay_wait(why, |line| line.line.is_empty() && !line.settling); + return; + } + let was_working = working(true); + let mut counted = false; + loop { + let items = { + let mut line = line(); + if line.line.is_empty() { + line.settling = false; + break; + } + line.settling = true; + line.written.clear(); + line.lists = 0; + std::mem::take(&mut line.line) + }; + let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count(); + if !counted { + counted = true; + LATE_STATS[1].fetch_add(1, Ordering::Relaxed); + LATE_STATS[why].fetch_add(1, Ordering::Relaxed); + } + LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed); + if flights > 0 { + submitting(2, flights); + let waiting = std::time::Instant::now(); + // SAFETY: the fence and event are ours, under the + // submission lock; `submitted` is the last value signalled. + unsafe { + match self.fence.SetEventOnCompletion(*submitted, self.event) { + Ok(()) => { + working(false); + WaitForSingleObject(self.event, INFINITE); + stood(waiting); + working(true); + } + Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"), + } + } + let gpu = waiting.elapsed(); + LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::card_waited(gpu.as_micros() as u64, || { + format!("{flights} submissions sent ahead, settled together") + }); + // SAFETY: a plain query. + if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { + let runs: Vec<&HostList> = items + .iter() + .filter_map(|i| match i { + Late::Run(f) => Some(f), + _ => None, + }) + .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())) + .collect(); + fail(format_args!( + "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}", + runs.len(), + self.removal_data(&runs), + last_notes(&runs) + )); + } + submitting(3, flights); + let copying = std::time::Instant::now(); + let mut seen = std::collections::HashSet::new(); + let mut back: Vec = Vec::new(); + for item in &items { + let Late::Run(flight) = item else { + continue; + }; + if let Some(card) = &flight.card { + self.card_back(card, submitted, &mut seen); + } + for (shadow, ranges) in &flight.back { + match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + Some((_, all)) => { + for range in ranges { + if !all.contains(range) { + all.push(*range); + } + } + } + None => back.push((shadow.clone(), ranges.clone())), + } + } + } + hand_back(&back); + COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed); + } + // In the order given: what tells the title the card is done. + let mut last = 0; + let mut landed = Vec::new(); + for item in items { + match item { + Late::Run(flight) => { + last = flight.number; + for &i in &flight.order { + read_backs(flight.lists[i].host()); + } + if let Some(card) = flight.card { + self.card_done(card); + } + landed.push((flight.lists, flight.order)); + } + Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), + Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value), + } + } + if last > 0 { + FINISHED.store(last, Ordering::Release); + bury(last); + } + line().landed.extend(landed); + } + if counted { + self.log_messages(); + submitting(0, 0); + // What was settled may be what a queue stands at, and the + // caller may not be one that looks (a read-back, a present). + if why != WHY_CARD_DONE { + line().poke = true; + LINE_MOVED.notify_one(); + } + } + working(was_working); + } + + /// [`Host::execute`], or with `late` the first half of + /// [`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)> { + #[cfg(feature = "diagnostics")] + let called = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + crate::copystat::submission_begins(); // One submission at a time from preparation to copy-back: snapshots // and the ranges shaders write are per host copy, not per submission. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); + let was_working = working(true); + submitting(1, runs.len()); + // Flights in the air ([`late`]): a submission that is waited for + // settles them first, one sent ahead only if preparing it reads + // what they write. + if !late { + self.settle(&mut submitted, WHY_SYNC); + } else if let Some(why) = late_blocked(runs) { + if relay_exact() && why == WHY_READ { + // Only until the flights that may write what is read have + // landed: their copy-back's end, not the card's other work. + relay_wait(why, |line| blocked_by(&line.written, runs, false).is_none()); + } else { + self.settle(&mut submitted, why); + } + } + let behind = late && flying(); + // Before this submission counts as started: what the sweep lets go + // of is named by no list, and nothing runs now (behind flights the + // sweep waits for a submission that finds none in the air: there is + // one at every present). + static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if !behind { + sweep(); + SWEPT.store(now_ms(), Ordering::Relaxed); + } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 { + // With the present sent ahead nothing else brings a moment + // with nothing in the air: one is made for the sweep. + self.settle(&mut submitted, WHY_SYNC); + sweep(); + SWEPT.store(now_ms(), Ordering::Relaxed); + } + let behind = late && flying(); + // The slots that waited for a texture's host copy, before the + // lists that may read them run. + crate::descriptor::make_waiting(); + let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1; + // The ranges shaders write are counted for it (with the relay). + crate::shadow::preparing(this_submission); let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] + let lock = (started - called).as_micros() as u64; + #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Submissions, 1); let mut lists: Vec> = Vec::with_capacity(2 * runs.len()); // Where each run's lists start in `lists`. let mut firsts = Vec::with_capacity(runs.len()); let mut batch = Batch::default(); + // The time a settle of flights takes inside this preparing: the + // wait for the card and the copy-back have their own places on the + // frame line (run 92 showed them twice, "preparing" 250 ms for 135). + let mut settled = std::time::Duration::ZERO; + // One write-watch asking for everything the submission refreshes + // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges. + if crate::watch::once() { + let mut spans: std::collections::HashMap = std::collections::HashMap::new(); + for list in runs { + for step in &list.deferred().copies { + if let Step::Refresh(shadow, address, len) = step + && !shadow.unwatched() + { + let span = spans + .entry(std::sync::Arc::as_ptr(shadow) as usize) + .or_insert((*address, *address + *len)); + *span = (span.0.min(*address), span.1.max(*address + *len)); + } + } + } + let ranges: Vec<(usize, usize)> = spans.into_values().collect(); + crate::watch::ask_once(&ranges); + // Behind flights: the title wrote memory that a flight's shaders + // may write too, and this submission refreshes it. The flights + // are settled, and the asking made again: the copy-back wrote + // title memory, which other copies of it must see. + if behind && stale_under_flights(runs) { + let settling = std::time::Instant::now(); + self.settle(&mut submitted, WHY_STALE); + settled += settling.elapsed(); + crate::watch::ask_once(&ranges); + } + } else if behind && stale_under_flights(runs) { + let settling = std::time::Instant::now(); + self.settle(&mut submitted, WHY_STALE); + settled += settling.elapsed(); + } for list in runs { list.run_deferred(&mut batch); firsts.push(lists.len()); @@ -510,7 +3954,57 @@ impl Host { lists.push(list.list.cast().ok()); } batch.flush(); + crate::watch::ask_once_end(); + // The snapshots of the ranges shaders may write, if they were left + // for now (`crate::shadow::wide_back`): the refreshes are done, the + // lists have not gone to the card. + { + #[cfg(feature = "diagnostics")] + let snapshots = std::time::Instant::now(); + crate::shadow::take_snapshots(); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64); + } + // Copies in the card's memory: what changed on their CPU side goes + // up ahead of the lists, and a compare of what the shaders may + // write follows them in the same submission. + let flown = late && relay(); + if flown && self.card_results_low() { + let settling = std::time::Instant::now(); + self.settle(&mut submitted, WHY_MOST); + settled += settling.elapsed(); + } + let card = self.card_before(runs, flown); + if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) { + lists.push(Some(check)); + } let prepared = std::time::Instant::now(); + if late { + *submitted += 1; + // SAFETY: closed lists; the fence is ours. + let signalled = unsafe { + self.queue.ExecuteCommandLists(&lists); + self.queue.Signal(&self.fence, *submitted) + }; + self.card_sent(); + if let Err(e) = signalled { + fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); + } + let back = declared_writes(runs); + 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); + #[cfg(feature = "diagnostics")] + crate::copystat::submission_ends(lock); + let sent = Sent { + number: this_submission, + card, + back, + writes, + }; + working(was_working); + return Some((submitted, sent)); + } // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`). #[cfg(feature = "diagnostics")] let groups: Vec<&[Option]> = if timing() { @@ -524,25 +4018,44 @@ impl Host { }; #[cfg(not(feature = "diagnostics"))] let groups = [&lists[..]]; + submitting(2, runs.len()); for (i, group) in groups.iter().enumerate() { *submitted += 1; let started = std::time::Instant::now(); // SAFETY: closed lists; the fence and event are ours. unsafe { self.queue.ExecuteCommandLists(group); + self.card_sent(); let waited = self .queue .Signal(&self.fence, *submitted) .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)); match waited { Ok(()) => { + working(false); WaitForSingleObject(self.event, INFINITE); + stood(started); + working(true); } Err(e) => tracing::warn!(error = %e, "host submission not waited for"), } } + // With timing on each group is one of `runs` (and the compare + // of copies in the card's memory, with the last): every + // command's time on the card goes to the sums by pipeline. #[cfg(feature = "diagnostics")] - if groups.len() > 1 && started.elapsed() > std::time::Duration::from_millis(50) { + if timing() { + // SAFETY: a plain query. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); + for (ms, op) in runs[i].slowest(frequency, usize::MAX) { + crate::copystat::command_took(&op, ms); + } + } + // A submission of one list was never named here (`groups.len() + // > 1` was the test): the two 50 ms lists of the gameplay + // frame, each a submission of its own, printed nothing. + #[cfg(feature = "diagnostics")] + if timing() && started.elapsed() > std::time::Duration::from_millis(50) { // SAFETY: a plain query. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len(); @@ -554,9 +4067,20 @@ impl Host { let _ = (i, started); } let _ = &firsts; + FINISHED.store(this_submission, Ordering::Release); + bury(this_submission); let gpu = prepared.elapsed(); SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed); SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::card_waited(gpu.as_micros() as u64, || { + let pipelines: std::collections::BTreeSet = runs + .iter() + .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone()) + .collect(); + let text = format!("{} lists, pipelines {pipelines:?}", runs.len()); + text.chars().take(1200).collect() + }); // The host resets a device whose submission runs for about 2 s. if gpu > std::time::Duration::from_millis(250) { let pipelines: std::collections::BTreeSet = runs @@ -574,36 +4098,56 @@ impl Host { last_notes(runs) )); } + submitting(3, runs.len()); // What shaders wrote goes back before the bottom-of-pipe writes, // which tell the title the GPU is done; each range once per // submission, however many dispatches declared it (the world's // passes declare the same big ranges dozens of times). let copying = std::time::Instant::now(); - // One list's lock at a time: a submission may name a list twice. - let mut back: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); - for list in runs { - for step in &list.deferred().copies { - if let Step::GpuWrite(shadow, address, len) = step - && !back - .iter() - .any(|(s, a, l)| std::sync::Arc::ptr_eq(s, shadow) && (*a, *l) == (*address, *len)) - { - back.push((shadow.clone(), *address, *len)); - } - } + // For copies in the card's memory the compare has run there: the + // pieces that differ are fetched and merged. + if let Some(card) = &card { + self.card_back(card, &mut submitted, &mut std::collections::HashSet::new()); } - for (shadow, address, len) in &back { - let (address, len) = (*address, *len); - let written = shadow.copy_back(address, len); - COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + let back = declared_writes(runs); + hand_back(&back); + if let Some(card) = card { + self.card_done(card); + } + #[cfg(feature = "diagnostics")] + if !back.is_empty() { + crate::copystat::add(crate::copystat::C::BackSubmissions, 1); + } + // Nothing of this submission goes back to the title: no range of + // shader writes, no value written when it is done. The wait for + // such a one is only for order and for what the card still holds. + #[cfg(feature = "diagnostics")] + if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) { + use crate::copystat::{C, add}; + add(C::NothingBack, 1); + add(C::NothingBackUs, gpu.as_micros() as u64); } COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed); for list in runs { + // Read backs first: a value written at the bottom of the pipe + // may be what tells the title that they are there. + read_backs(list); for &(at, what, bytes) in &list.deferred().writes { what.write(at as *mut u8, bytes); } } self.log_messages(); + submitting(0, 0); + #[cfg(feature = "diagnostics")] + crate::copystat::submission_ends(lock); + // With the relay: nothing is in the air now, so no fetch still to + // be merged is older than the sends to card copies so far, and + // their notes can go. + if relay() { + crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); + } + working(was_working); + None } /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations @@ -750,11 +4294,12 @@ impl Host { /// A host render target view of `resource`, valid until it is recorded. pub(crate) fn rtv( &self, - resource: &ID3D12Resource, + resource: Option<&ID3D12Resource>, desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>, ) -> D3D12_CPU_DESCRIPTOR_HANDLE { let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING; - // SAFETY: a slot of our heap and a live resource. + // SAFETY: a slot of our heap and a live resource, or none with a + // description (a typed null view). unsafe { let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart(); handle.ptr += (slot * self.rtv_size) as usize; @@ -860,6 +4405,7 @@ impl HostList { } pub(crate) fn close(&self) { + self.twins_to_depth(); #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); @@ -880,14 +4426,23 @@ impl HostList { /// Only after the list's last submission finished (every one is waited /// for). pub(crate) fn reset(&self) { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + self._alive.used(); *self.deferred() = Deferred::default(); self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); #[cfg(feature = "diagnostics")] self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); { let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); (scratch.current, scratch.used) = (0, 0); + // Every submission of the list has run: nothing reads its + // scratch memory any more, and the next list to ask takes it. + if scratch_pool() { + give_chunks(std::mem::take(&mut scratch.chunks)); + } } // SAFETY: the list is not executing. let reset = unsafe { @@ -898,6 +4453,8 @@ impl HostList { if let Err(e) = reset { fail(format_args!("a host command list did not reset ({e})")); } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64); } /// Moves a title texture's host copy to `wanted` (a host state) in this @@ -925,34 +4482,289 @@ impl HostList { } } - /// At submission: the list that moves each texture this list uses from - /// its real state to the one the list starts with; the textures' real - /// states become those the list ends with. - fn prelude(&self) -> Option { - let states = self.states.lock().unwrap_or_else(|e| e.into_inner()); - let barriers: Vec = states - .values() - .filter_map(|(first, last, copy)| { - let real = copy.state.swap(*last, Ordering::Relaxed); - (real != *first).then(|| { - transition( - ©.texture, - D3D12_RESOURCE_STATES(real as i32), - D3D12_RESOURCE_STATES(*first as i32), - ) - }) + /// Moves host texture `copy` to `wanted` (a host state) in this list, + /// as [`HostList::transition`] does a title resource's host copy, and + /// records the barrier: for textures that are not a title resource's + /// host copy (colour twins) and for the copies between the two. + fn settle(&self, copy: &std::sync::Arc, wanted: u32) { + let wanted = legal_state(©.texture, wanted); + let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); + let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) { + std::collections::hash_map::Entry::Vacant(v) => { + v.insert((wanted, wanted, copy.clone())); + None + } + std::collections::hash_map::Entry::Occupied(mut o) => { + let before = std::mem::replace(&mut o.get_mut().1, wanted); + (before != wanted).then_some(before) + } + }; + drop(states); + if let Some(before) = before { + let barrier = transition( + ©.texture, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(wanted as i32), + ); + // SAFETY: an open list and a live texture. + unsafe { self.list.ResourceBarrier(&[barrier]) }; + } + } + + /// A use of title texture `resource` about to be recorded, if it is a + /// depth texture with a colour twin (false if it is not): of the twin + /// (`colour`: unordered access) or of the depth texture (depth target, + /// clear, shader read, copy, resolve), writing it or only reading. The + /// side used is first brought up to date: by a copy recorded here if + /// this list wrote the other side since, by the list's prelude if the + /// list uses the side as it finds it. The twin is left in the + /// unordered access state; the caller moves the depth texture to the + /// state its use needs, as for any texture. A twin still ahead when the + /// list closes is copied then (`twins_to_depth`). + /// shortcut: every depth target bound for a draw counts as written + /// (also when the draw only tests), and every unordered access view a + /// shader names as written; views a shader picks from the heap by a + /// computed index are not seen here at all. + pub(crate) fn twin_use( + &self, + resource: crate::object::This, + colour: bool, + write: bool, + ) -> bool { + const UNORDERED_ACCESS: u32 = 0x8; + // Asked for every texture a draw reads: most have no twin. + let Some(twin) = crate::resource::twin(resource) else { + return false; + }; + let Some(depth) = crate::resource::host_copy(resource) else { + return false; + }; + let side = usize::from(colour); + let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + let u = twins + .entry(std::sync::Arc::as_ptr(&twin) as usize) + .or_insert_with(|| TwinUse { + depth: depth.clone(), + twin: twin.clone(), + needs: [false; 2], + behind: [None; 2], + writing: false, + late: false, + }); + let copy = match u.behind[side] { + Some(behind) => behind, + None => { + u.needs[side] = true; + false + } + }; + u.behind[side] = Some(false); + match (write, colour) { + // Shaders write the twin when the draw or dispatch runs: what + // the same one reads of the depth texture is prepared before + // (`twins_written`). + (true, true) => u.writing = true, + (true, false) => u.behind[1] = Some(true), + (false, _) => {} + } + // shortcut: the depth plane's twin is not drawn into the plane + // here: the pass sets a pipeline and a target of ours, which a list + // still recording the title's commands cannot take. This use sees + // the plane as it was; the pass runs when the list closes + // (`twins_to_depth`). Counted. + if copy && !colour && twin.plane.is_some() { + u.late = true; + crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed); + } + drop(twins); + if copy { + self.twin_copy(&depth, &twin, colour); + } else if colour { + self.settle(&twin.colour, UNORDERED_ACCESS); + } + // The depth plane's twin is written through unordered access too. + if colour && let Some(plane) = &twin.plane { + self.settle(plane, UNORDERED_ACCESS); + } + true + } + + /// Records the pass that draws the twin of the depth plane of `depth` + /// into the plane, if `twin` has one, with the moves to the states the + /// pass needs; the twin is left in the unordered access state. Only + /// for a list that records nothing of the title's afterwards + /// (`record_plane_pass`). + fn pass_plane( + &self, + depth: &std::sync::Arc, + twin: &crate::resource::Twin, + ) { + const UNORDERED_ACCESS: u32 = 0x8; + const DEPTH_WRITE: u32 = 0x10; + const PIXEL_SHADER_RESOURCE: u32 = 0x80; + let Some(plane) = &twin.plane else { return }; + self.settle(depth, DEPTH_WRITE); + self.settle(plane, PIXEL_SHADER_RESOURCE); + record_plane_pass(&self.list, &depth.texture, &plane.texture); + self.settle(plane, UNORDERED_ACCESS); + } + + /// Records the copy of a depth texture into its colour twin (`colour`) + /// or of the twin into the depth texture, with the moves to the copy + /// states. The twin is left in the unordered access state. + fn twin_copy( + &self, + depth: &std::sync::Arc, + twin: &crate::resource::Twin, + colour: bool, + ) { + const UNORDERED_ACCESS: u32 = 0x8; + const COPY_DEST: u32 = 0x400; + const COPY_SOURCE: u32 = 0x800; + let (from, to) = if colour { + (depth, &twin.colour) + } else { + (&twin.colour, depth) + }; + self.settle(from, COPY_SOURCE); + self.settle(to, COPY_DEST); + record_twin_copy(&self.list, &depth.texture, twin, colour); + self.settle(&twin.colour, UNORDERED_ACCESS); + } + + /// Before the list closes: the depth textures whose twins it wrote last + /// are given what was written, and left readable by shaders. Shaders + /// that pick a view from the heap by a computed index are not seen by + /// `twin_use` and read the depth texture in lists that never name it + /// (in a captured frame of Grand Theft Auto VI no table names a shadow + /// map for reading but the pass that fills the next one). + fn twins_to_depth(&self) { + const SHADER_RESOURCE: u32 = 0x40 | 0x80; + let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + let written: Vec<_> = twins + .values_mut() + .filter(|u| u.behind[0] == Some(true) || u.late) + .map(|u| { + // Not copied again if the list copied since the last write + // and only the depth plane's pass is left. + let copy = u.behind[0] == Some(true); + u.behind[0] = Some(false); + u.late = false; + (u.depth.clone(), u.twin.clone(), copy) }) .collect(); - if barriers.is_empty() { + drop(twins); + for (depth, twin, copy) in &written { + if *copy { + self.twin_copy(depth, twin, false); + } + // Nothing of the title's is recorded after this: the pass may + // leave its own pipeline and target set. + self.pass_plane(depth, twin); + self.settle(depth, SHADER_RESOURCE); + } + } + + /// The draw or dispatch just prepared is recorded: the twins it writes + /// now hold what their depth textures lack. + pub(crate) fn twins_written(&self) { + let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + for u in twins.values_mut().filter(|u| u.writing) { + u.writing = false; + u.behind[0] = Some(true); + } + } + + /// At submission: the list that moves each texture this list uses from + /// its real state to the one the list starts with; the textures' real + /// states become those the list ends with. For depth textures with a + /// colour twin it first copies the side the list uses as it finds it + /// from the other, if a list submitted earlier left it behind. + fn prelude(&self) -> Option { + const COPY_DEST: u32 = 0x400; + const COPY_SOURCE: u32 = 0x800; + let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32); + let states = self.states.lock().unwrap_or_else(|e| e.into_inner()); + // The copies (depth texture, twin, whether into the twin); the + // sides are then as this list leaves them. + let mut syncs = Vec::new(); + let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + for u in twins.values() { + let real = u.twin.behind.load(Ordering::Relaxed); + let mut behind = [real & 1 != 0, real & 2 != 0]; + for side in [0, 1] { + if u.needs[side] && behind[side] { + syncs.push((u.depth.clone(), u.twin.clone(), side == 1)); + behind = [false; 2]; + } + } + let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side])); + let left = u32::from(left[0]) | (u32::from(left[1]) << 1); + u.twin.behind.store(left, Ordering::Relaxed); + } + drop(twins); + // A copy runs with its textures in the copy states: each moves + // there from its real state, and from there to the state the list + // starts with (back to its real state if the list does not use it). + let mut to_copy = Vec::new(); + let mut barriers = Vec::new(); + let mut copying = std::collections::HashMap::new(); + for (depth, twin, colour) in &syncs { + let (from, to) = if *colour { + (depth, &twin.colour) + } else { + (&twin.colour, depth) + }; + for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] { + let key = std::sync::Arc::as_ptr(texture) as usize; + let real = texture.state.load(Ordering::Relaxed); + copying.insert(key, state); + if real != state { + to_copy.push(transition( + &texture.texture, + host_state(real), + host_state(state), + )); + if !states.contains_key(&key) { + barriers.push(transition( + &texture.texture, + host_state(state), + host_state(real), + )); + } + } + } + } + barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| { + let real = copy.state.swap(*last, Ordering::Relaxed); + let real = copying.get(key).copied().unwrap_or(real); + (real != *first) + .then(|| transition(©.texture, host_state(real), host_state(*first))) + })); + if barriers.is_empty() && syncs.is_empty() { return None; } - let (allocator, list) = &self.prelude; + let Some((allocator, list)) = self + .prelude + .get_or_init(|| host().and_then(|h| h.make_prelude())) + .as_ref() + else { + fail(format_args!("no host list for a state prelude")); + }; // SAFETY: the prelude is not executing (every submission is waited // for); the textures are live. let recorded = unsafe { allocator.Reset().and_then(|()| { list.Reset(allocator, None)?; - list.ResourceBarrier(&barriers); + if !to_copy.is_empty() { + list.ResourceBarrier(&to_copy); + } + for (depth, twin, colour) in &syncs { + record_twin_copy(list, &depth.texture, twin, *colour); + } + if !barriers.is_empty() { + list.ResourceBarrier(&barriers); + } list.Close() }) }; @@ -980,13 +4792,19 @@ impl HostList { #[cfg(feature = "diagnostics")] fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) { - if dred_on() { + if !dred_on() { + crate::capture::op(std::ptr::from_ref(self) as usize, what); + return; + } + { + let started = std::time::Instant::now(); let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32; if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 { // SAFETY: an open list and our query heap. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) }; } let what = what(); + crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone()); let text: Vec = what.encode_utf16().chain([0]).collect(); const UNICODE: u32 = 0; // SAFETY: an open list; the marker is copied when recorded. @@ -997,9 +4815,31 @@ impl HostList { .lock() .unwrap_or_else(|e| e.into_inner()) .push((what, range)); + crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64); } } + /// Whether nothing recorded since the list was opened does any work: + /// no draw or dispatch (the first keeps its pipeline), no copy, clear, + /// upload or resolve (they defer a step or move a texture's state), no + /// bottom-of-pipe write. State set on the list does not count. + pub(crate) fn untouched(&self) -> bool { + { + let deferred = self.deferred(); + if !(deferred.copies.is_empty() + && deferred.uploads.is_empty() + && deferred.kept.is_empty() + && deferred.textures.is_empty() + && deferred.writes.is_empty() + && deferred.backs.is_empty()) + { + return false; + } + } + self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + } + /// Notes a pipeline the list binds. pub(crate) fn used_pipeline(&self, name: &str) { let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner()); @@ -1015,6 +4855,19 @@ impl HostList { /// Copies `len` bytes from `src` to `dst` when the list is submitted. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) { let mut deferred = self.deferred(); + COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed); + // A copy that goes on where the one recorded just before it ended, + // source and destination both: with `join_copies` the two are one + // step. + if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut() + && continues((*d, *s, *n), (dst as usize, src as usize, len)) + { + COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed); + if join_copies() { + *n += len; + return; + } + } deferred .copies .push(Step::Copy(dst as usize, src as usize, len)); @@ -1060,6 +4913,14 @@ impl HostList { .push(Step::GpuWrite(shadow.clone(), address, len)); } + /// A read back: once the list has run, `rows` rows of `row` bytes go + /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`) + /// to title memory at `dst`, pitched `pitch`. The buffer lives until + /// the list is reset. + pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) { + self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch])); + } + /// Stores `what` (`bytes` of it) at `dst` once the list has run. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) { self.deferred().writes.push((dst as usize, what, bytes)); @@ -1072,7 +4933,7 @@ impl HostList { pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { let (buffer, data) = host.upload_buffer(size)?; name(&buffer, || format!("list upload {size:#x}")); - self.deferred().uploads.push(buffer.clone()); + self.deferred().hold_upload(buffer.clone(), size); Some((buffer, data)) } @@ -1087,26 +4948,37 @@ impl HostList { name(&buffer, || format!("list scratch {len:#x}")); // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - self.deferred().uploads.push(buffer); + self.deferred().hold_upload(buffer, len); return Some((gpu, data)); } - if s.used + len > SCRATCH_CHUNK && s.current < s.chunks.len() { + // The chunk in use while `len` fits in what is left of it, else the + // next one (a list's first chunk may be a small one). + while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 { (s.current, s.used) = (s.current + 1, 0); } if s.current == s.chunks.len() { - let (buffer, data) = host.upload_buffer(SCRATCH_CHUNK)?; - name(&buffer, || "list scratch".into()); - // SAFETY: a live buffer. - let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - s.chunks.push((buffer, data as usize, gpu)); + let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST { + SCRATCH_FIRST + } else { + SCRATCH_CHUNK + }; + let chunk = take_chunk(host, size)?; + s.chunks.push((chunk, size)); s.used = 0; } - let (_, data, gpu) = s.chunks[s.current]; + let (data, gpu) = (s.chunks[s.current].0.data, s.chunks[s.current].0.gpu); let at = s.used; s.used += len; Some((gpu + at, (data + at as usize) as *mut u8)) } + /// The bytes of scratch chunks the list holds now (after a reset: + /// none while lists share their chunks). + pub(crate) fn scratch_kept(&self) -> u64 { + let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); + scratch.chunks.iter().map(|c| c.1).sum() + } + /// The host address of the list's indirect-work budget, zeroed at each /// submission of the list from the first use after a reset on. pub(crate) fn budget(&self) -> Option { @@ -1121,15 +4993,51 @@ impl HostList { if !deferred.budget_zeroed { deferred.budget_zeroed = true; let at = *data; - // SAFETY: the list's own mapped word, written before it runs. - deferred - .copies - .push(Step::Host(Box::new(move || unsafe { (at as *mut u32).write_volatile(0) }))); + // SAFETY: the list's own mapped words, written before it runs. + // The words after the budget hold what the clamp noted about the + // list's last run (mesh dispatches: the largest group count + // asked for, the groups asked in all): taken, then zeroed. + deferred.copies.push(Step::Host(Box::new(move || unsafe { + let words = at as *mut u32; + let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile()); + MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed); + MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed); + for k in 0..3 { + words.add(k).write_volatile(0); + } + }))); } // SAFETY: a live buffer. Some(unsafe { buffer.GetGPUVirtualAddress() }) } + /// A device-local unordered-access buffer of at least `size` bytes for + /// clamped indirect arguments, reused across executions and resets of the + /// list. Smaller buffers replaced mid-list stay alive until + /// [`HostList::reset`]. + pub(crate) fn indirect_scratch(&self, size: u64) -> Option { + let needed = size.max(64 << 10); + let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((buffer, cap)) = &*slot + && *cap >= needed + { + return Some(buffer.clone()); + } + let prev = slot.as_ref().map_or(0, |(_, cap)| *cap); + let alloc = prev + .saturating_mul(2) + .max(needed) + .next_multiple_of(64 << 10); + let buffer = host()?.uav_buffer(alloc)?; + name(&buffer, || format!("indirect arguments {alloc:#x}")); + let old = slot.replace((buffer.clone(), alloc)); + drop(slot); + if let Some((old_buf, _)) = old { + self.keep(&old_buf); + } + Some(buffer) + } + /// Keeps `object` alive until the list is reset. pub(crate) fn keep(&self, object: &impl Interface) { if let Ok(object) = object.cast::() { @@ -1178,6 +5086,8 @@ impl HostList { } batch.title_written(); copy_mapped(dst as *mut u8, src as *const u8, len, true); + // With the submission's one asking: the journal learns it. + crate::watch::wrote(dst, len); len } &Step::Fill(dst, src, len) => { @@ -1203,6 +5113,11 @@ impl HostList { batch.title_written(); } work(); + // It wrote title memory, where is not known here: the + // submission's one asking ends, later refreshes ask anew. + if matches!(step, Step::Run(_)) { + crate::watch::ask_once_end(); + } #[cfg(feature = "diagnostics")] { add(C::Runs, 1); @@ -1211,9 +5126,20 @@ impl HostList { continue; } Step::GpuWrite(shadow, address, len) => { - // The shaders start from the title's data. - batch.flush(); + // The shaders start from the title's data: this copy's + // pending refresh first. The other copies' wait for + // the next flush of all (flushing all of them at every + // range a dispatch writes made thousands of write-watch + // askings a frame). + batch.flush_one(shadow); + #[cfg(feature = "diagnostics")] + let snapshot = std::time::Instant::now(); shadow.writing(*address, *len); + #[cfg(feature = "diagnostics")] + { + add(C::GpuWrites, 1); + add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64); + } continue; } Step::Texture(staging) => { @@ -1229,6 +5155,23 @@ impl HostList { } } +/// Whether a submission's refreshes of host copies run on several threads, +/// a copy to a thread (`VICTORY_WIDE_REFRESH=1`; off by default). +/// +/// A submission brings some sixty copies up to date, one after the other +/// on the submitting thread: for each, the pages the title wrote are asked +/// for and read through the kernel into the copy. That is the frame line's +/// "copies", 45-50 ms a frame, and the copies have nothing to do with one +/// another: each refresh writes its own copy and its own notes, and reads +/// title memory. With the switch the copies of a flush (four or more) are +/// spread over the threads kept for the snapshots (`crate::shadow::wide`). +/// The write-watch journal and the guards are behind their own locks, as +/// they are for the title's threads. +fn wide_refresh() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_REFRESH").is_some_and(|v| v == "1")) +} + /// A submission's refreshes not done yet, merged per buffer copy into the /// range that covers them: done before a step that writes title memory or /// gives a range to shaders, and before the lists run. @@ -1240,6 +5183,11 @@ impl HostList { #[derive(Default)] struct Batch { refreshes: Vec<(std::sync::Arc, usize, usize)>, + /// Where each copy (by address) is in `refreshes`: the list that makes + /// the heap's buffers ready adds some 4,100 copies, and searching them + /// for every refresh of a submission was tens of millions of + /// comparisons a frame. + index: std::collections::HashMap, /// Staging buffers (by address) refreshed since the last title write. textures: std::collections::HashSet, } @@ -1247,16 +5195,44 @@ struct Batch { impl Batch { fn add(&mut self, shadow: &std::sync::Arc, address: usize, len: usize) { let end = address + len; - match self - .refreshes - .iter_mut() - .find(|(s, ..)| std::sync::Arc::ptr_eq(s, shadow)) - { - Some((_, from, to)) => (*from, *to) = ((*from).min(address), (*to).max(end)), - None => self.refreshes.push((shadow.clone(), address, end)), + let key = std::sync::Arc::as_ptr(shadow) as usize; + match self.index.get(&key) { + Some(&at) => { + let r = &mut self.refreshes[at]; + (r.1, r.2) = (r.1.min(address), r.2.max(end)); + } + None => { + self.index.insert(key, self.refreshes.len()); + self.refreshes.push((shadow.clone(), address, end)); + } } } + /// 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) { + let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else { + return; + }; + let (shadow, from, to) = self.refreshes.swap_remove(at); + // The last entry took its place. + if let Some(moved) = self.refreshes.get(at) { + self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at); + } + Self::update(&shadow, from, to); + } + + /// Brings `[from, to)` of a copy up to date, timed. + fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) { + let started = std::time::Instant::now(); + let copied = shadow.update(from, to - from); + let us = started.elapsed().as_micros() as u64; + #[cfg(feature = "diagnostics")] + crate::copystat::range(from, to - from, us, 0); + PREPARING[0].fetch_add(us, Ordering::Relaxed); + PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + } + /// Whether `staging` is still to be refreshed in this submission (and /// notes it refreshed). fn texture_due(&mut self, staging: &std::sync::Arc) -> bool { @@ -1271,14 +5247,42 @@ impl Batch { } fn flush(&mut self) { - for (shadow, from, to) in self.refreshes.drain(..) { + self.index.clear(); + // One write-watch asking for the copies that lie close together, + // not one per copy. + let ahead = self.refreshes.len() > 1; + if ahead { let started = std::time::Instant::now(); - let copied = shadow.update(from, to - from); - let us = started.elapsed().as_micros() as u64; - #[cfg(feature = "diagnostics")] - crate::copystat::range(from, to - from, us, 0); - PREPARING[0].fetch_add(us, Ordering::Relaxed); - PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + let ranges: Vec<(usize, usize)> = self + .refreshes + .iter() + .filter(|r| !r.0.unwatched()) + .map(|r| (r.1, r.2)) + .collect(); + crate::watch::ask_ahead(&ranges); + PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + } + if wide_refresh() && self.refreshes.len() >= 4 { + // Each copy on its own, several at a time: a copy's refresh + // writes that copy and reads title memory, nothing of another's. + // The time counted is the time it took, not the threads' sum. + let started = std::time::Instant::now(); + let before = PREPARING[0].load(Ordering::Relaxed); + let jobs: Vec> = self + .refreshes + .drain(..) + .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box) + .collect(); + crate::shadow::wide_run(jobs); + let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before); + PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed); + } else { + for (shadow, from, to) in self.refreshes.drain(..) { + Self::update(&shadow, from, to); + } + } + if ahead { + crate::watch::ask_ahead_done(); } } } @@ -1303,7 +5307,20 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b 2 => return, _ => {} } - if len == 0 || title_dst && !crate::texture::committed(dst, len) { + if len == 0 { + return; + } + // A title destination that is not all mapped is left alone. Asking + // Windows first (`VirtualQuery`) walks the page tables to the end of + // the destination's region: in the title's big blocks that is + // milliseconds a copy, and it was a seventh of the submitting thread's + // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below + // says the same when it fails, so the question is only asked then. + // `VICTORY_COPY_ASK=1` asks first, as before. + static ASK: OnceLock = OnceLock::new(); + let ask_first = title_dst + && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1")); + if ask_first && !crate::texture::committed(dst, len) { return; } if title_dst { @@ -1318,8 +5335,59 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b if whole { return; } + // The copy failed: a source page is not there, or the destination is + // not all mapped. Then the destination stays as it is (the kernel may + // have written its first pages). + if title_dst && !ask_first && !crate::texture::committed(dst, len) { + return; + } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Fallbacks, 1); + #[cfg(feature = "diagnostics")] + let sparse = std::time::Instant::now(); + if !title_dst && len >= 64 << 10 { + read_sparse(src, dst, len); + } else { + read_pieces(src, dst, len); + } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64); +} + +/// After a failed bulk read into host memory, skip contiguous holes. Never +/// cache the query across copies: the title may remap the same address. +fn read_sparse(src: *const u8, dst: *mut u8, len: usize) { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery, + }; + let mut offset = 0; + while offset < len { + let at = src.wrapping_add(offset); + let to = dst.wrapping_add(offset); + let remaining = len - offset; + // SAFETY: the query inspects an address and fills a local structure. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) }; + let n = (info.BaseAddress as usize).saturating_add(info.RegionSize) + .saturating_sub(at as usize).min(remaining); + if size != size_of_val(&info) || n == 0 { + read_pieces(at, to, remaining); + break; + } + if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Unmapped, n as u64); + // SAFETY: this path is only used with a writable host destination. + unsafe { to.write_bytes(0, n) }; + } else if !read(at, to, n) { + // A mapping may change between query and read. + read_pieces(at, to, n); + } + offset += n; + } +} + +fn read_pieces(src: *const u8, dst: *mut u8, len: usize) { // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece // that fails), zeros for what cannot be read. for_pieces(src as usize, len, 64 << 10, |at, n| { @@ -1355,14 +5423,48 @@ fn read(src: *const u8, dst: *mut u8, len: usize) -> bool { unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 } } +#[link(name = "ntdll", kind = "raw-dylib")] +unsafe extern "system" { + /// The kernel's write into a process's memory, `(process, address, + /// bytes, length, written out)`: an NTSTATUS, negative when a page of + /// the range is not there or not writable. It changes no protection. + fn NtWriteVirtualMemory( + process: *mut std::ffi::c_void, + base: *mut std::ffi::c_void, + buffer: *const std::ffi::c_void, + size: usize, + written: *mut usize, + ) -> i32; +} + +/// Whether title memory is written with the kernel's own call +/// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks +/// what the pages are (as `VirtualQuery` does: about 2 ms a call in the +/// title's big pools, see [`copy_mapped`]): putting back what shaders wrote +/// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size +/// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before. +fn direct_writes() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0")) +} + /// Copies host memory into title memory after a submission (what shaders /// wrote), leaving pages that are not mapped alone. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; + let direct = direct_writes(); let write = |at: usize, n: usize| { let from = src.wrapping_add(at - dst as usize); let mut done = 0; + if direct { + // SAFETY: as below; the kernel checks the destination and + // writes nothing it cannot (the caller opened its guards: + // `crate::watch::writing`). + return unsafe { + NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0 + }; + } // SAFETY: the source is our mapped host copy; the kernel checks the // destination. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 } @@ -1393,7 +5495,50 @@ fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, us impl Host { /// A buffer in the upload heap, mapped for writing. + /// A buffer of `size` bytes the card writes and we read (a read back), + /// in the state copies into it need. + pub(crate) fn read_back_buffer(&self, size: u64) -> Option { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain creation of a read-back buffer. + let made = unsafe { + self.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut buffer, + ) + }; + match made { + Ok(()) => buffer, + Err(e) => { + tracing::warn!(error = %e, size, "no read-back buffer"); + None + } + } + } + pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + MADE[0].fetch_add(1, Ordering::Relaxed); + MADE[1].fetch_add(size, Ordering::Relaxed); let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() @@ -1459,6 +5604,10 @@ struct Presenter { height: u32, format: DXGI_FORMAT, copy: HostList, + /// With presents sent ahead ([`late_free_present`]): a list for each + /// present in the air, and the submission it last flew as (it is used + /// again once that one has finished). + ahead: Vec<(HostList, u64)>, hwnd: HWND, meter: Meter, } @@ -1494,6 +5643,8 @@ impl Meter { fn frame(&mut self, hwnd: HWND) { #[cfg(feature = "diagnostics")] tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present"); + #[cfg(feature = "diagnostics")] + crate::copystat::presented(); self.frames += 1; #[cfg(feature = "diagnostics")] { @@ -1522,18 +5673,149 @@ impl Meter { }); let dropped = crate::draw::take_dropped() as f64 / frames; let indirect = crate::list::take_indirect() as f64 / frames; + let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed); + let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames; + tracing::info!( + "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame" + ); + late_line(frames); + card_clock_line(frames, ms); + crate::shadow::back_line(frames); + { + let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); + if passes + compares > 0.0 { + tracing::info!( + "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \ + ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes", + if rehash_runs() { "on" } else { "off" } + ); + } + } + { + let [own, asking, still, all] = + [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); + if all >= 1.0 { + tracing::info!( + "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \ + is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \ + hold still (the runtime remapping it); the rest is reading, hashing and detiling" + ); + } + let [through, left] = [0, 1].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames); + if through + left > 0.0 { + tracing::info!( + "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \ + {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there)" + ); + } + } + { + let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames); + if copies > 0.0 { + tracing::info!( + "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \ + (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})", + if join_copies() { "on" } else { "off" } + ); + } + } + // Passes over the heap's buffer views for shaders that pick them by index. + let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames; + let picked_ms = + crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames; + // Copies between depth textures and their colour twins, each way. + let [twin_to_depth, twin_to_colour] = + [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames); + // Depth planes drawn from their twins. + let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames; + // Copies in the card's memory (`crate::shadow::cards`). + let card = crate::shadow::card_stats(); + #[cfg(feature = "diagnostics")] + let slow = crate::watch::slow_asks(); // Over the same frames as the counts above. #[cfg(feature = "diagnostics")] let drops = crate::pipeline::take_drops(); if self.logged.elapsed() >= std::time::Duration::from_secs(5) { self.logged = std::time::Instant::now(); + tracing::info!( + "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)", + crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed) + ); + { + let [queued, due, away, partly, oldest] = + [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed)); + let [same, parts, tails] = + [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed)); + tracing::info!( + "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \ + {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \ + the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \ + as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \ + {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \ + {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \ + {} made slots found unmapped and made null", + crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed), + crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed), + crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed), + crate::descriptor::host::STALE[0].load(Ordering::Relaxed), + crate::descriptor::host::STALE[1].load(Ordering::Relaxed), + crate::descriptor::host::STALE[2].load(Ordering::Relaxed), + crate::descriptor::host::STALE[3].load(Ordering::Relaxed), + crate::descriptor::host::STALE[4].load(Ordering::Relaxed) + ); + } + #[cfg(feature = "diagnostics")] + tracing::info!( + "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms", + slow[0] as f64 / frames, + slow[1] as f64 / 1e3 / frames, + slow[2] as f64 / 1e3 + ); + if crate::shadow::cards() { + let per_frame = |i: usize| card[i] as f64 / frames; + tracing::info!( + "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \ + {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \ + ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)", + card[7], + card[8] >> 20, + card[9] >> 20, + per_frame(0) / 1e6, + per_frame(1), + per_frame(2), + per_frame(3), + per_frame(4) / 1e6, + per_frame(5), + per_frame(6) / 1e3 + ); + } tracing::info!( "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \ {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \ GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \ dropped {dropped:.0} without a host pipeline ({making} being made) and \ - {indirect:.0} indirect", - making = crate::pipeline::making() + {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \ + textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \ + {picked_waiting} waiting, {picked_away} passed over unmapped; depth textures with unordered access: {du0} made, bound as depth {du1}x, cleared as depth {du2}x, unordered views refused {du3}x; buffer views left null as the host would refuse them: {refused}", + picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed), + picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20, + picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed), + picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed), + du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed), + du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed), + du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed), + du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed), + refused = format!( + "{}; depth twins: {} alive, {} depth textures left without one; twin copies per frame: {twin_to_depth:.1} into depth textures, {twin_to_colour:.1} into twins; depth planes: {planes:.1} drawn from their twins per frame, {} times not given back to a twin, {} times used before the pass", + crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed), + crate::resource::TWINS[0].load(Ordering::Relaxed), + crate::resource::TWINS[1].load(Ordering::Relaxed), + crate::resource::PLANES[1].load(Ordering::Relaxed), + crate::resource::PLANES[2].load(Ordering::Relaxed) + ), + making = crate::pipeline::making(), + placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed), + objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed) ); #[cfg(feature = "diagnostics")] { @@ -1607,6 +5889,8 @@ impl Host { } let p = presenter.as_mut()?; if (p.width, p.height, p.format) != (width, height, format) { + // Presents sent ahead hold back buffers until they have run. + settle_now(WHY_SYNC); // SAFETY: no back buffer is held; every submission was waited for. let resized = unsafe { p.swap_chain @@ -1627,8 +5911,30 @@ impl Host { let Ok(back) = p.swap_chain.GetBuffer::(index) else { return None; }; - p.copy.reset(); - let list = &p.copy.list; + // Sent ahead ([`late_free_present`]) unless the frame is to be + // read back at once (a saved or listed frame): then a list of + // its own, one whose last flight has finished or a new one. + #[cfg(feature = "diagnostics")] + let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame); + #[cfg(not(feature = "diagnostics"))] + let read_now = false; + let slot = if late_free_present() && !read_now { + let finished = FINISHED.load(Ordering::Acquire); + p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| { + let list = self.new_list().ok()?; + list.close(); + p.ahead.push((list, 0)); + Some(p.ahead.len() - 1) + }) + } else { + None + }; + let copy = match slot { + Some(i) => &p.ahead[i].0, + None => &p.copy, + }; + copy.reset(); + let list = ©.list; list.ResourceBarrier(&[ transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), transition( @@ -1643,7 +5949,7 @@ impl Host { .then(|| crate::capture::read_back(&self.device, list, texture)) .flatten(); #[cfg(feature = "diagnostics")] - let probe = crate::capture::probe(&self.device, list, texture); + let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) }; #[cfg(not(feature = "diagnostics"))] let _ = frame; list.ResourceBarrier(&[ @@ -1654,8 +5960,14 @@ impl Host { D3D12_RESOURCE_STATE_PRESENT, ), ]); - p.copy.close(); - self.execute(&[&p.copy]); + copy.close(); + match slot { + Some(i) => { + let flown = self.execute_own(copy); + p.ahead[i].1 = flown; + } + None => self.execute(&[copy]), + } #[cfg(feature = "diagnostics")] if let Some((buffer, footprint)) = capture { crate::capture::save_read_back(frame, &buffer, &footprint); @@ -1707,6 +6019,7 @@ impl Host { height, format, copy, + ahead: Vec::new(), hwnd, meter: Meter::new(), }) @@ -1762,11 +6075,33 @@ pub(crate) fn legal_for(flags: u32, state: u32) -> u32 { } impl Host { + /// The card's memory as the system accounts it to this process, in + /// bytes: the budget and the use of the card's own memory, then of the + /// PC's memory shared with the card (where the system moves what does + /// not fit on the card). + pub(crate) fn video_memory(&self) -> Option<[u64; 4]> { + let adapter = self.adapter.as_ref()?; + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: plain queries that fill our structures. + unsafe { + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) + .ok()?; + } + Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage]) + } + /// A buffer in system memory that the CPU maps (write-back, so reading /// it is fast too) and shaders read and write: for host copies of title /// memory that shaders write, which upload memory cannot be. Starts in /// the common state (buffers move out of it implicitly). pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + MADE[2].fetch_add(1, Ordering::Relaxed); + MADE[3].fetch_add(size, Ordering::Relaxed); let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, @@ -1813,6 +6148,50 @@ impl Host { } } } + + /// A device-local buffer shaders may write (unordered access) and indirect + /// execution may read, starting in the common state. + pub(crate) fn uav_buffer(&self, size: u64) -> Option { + MADE[4].fetch_add(1, Ordering::Relaxed); + MADE[5].fetch_add(size, Ordering::Relaxed); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain creation of a device-local buffer. + let made = unsafe { + self.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + }; + match made { + Ok(()) => buffer, + Err(e) => { + tracing::warn!(error = %e, size, "no unordered-access buffer"); + None + } + } + } } /// For adapters without device-removed data (the software one): the last @@ -1865,7 +6244,10 @@ fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], do .map_or(history.len(), |b| (done + b).max(done + 1)); let mut text = format!(", commands {from}..{to} between its barriers:"); let mut shown = 0; - for i in from..to { + // From just before the command the GPU had not finished: the first + // twelve after the barrier named draws long done when a list of 79 + // mesh draws stopped at its 45th (run 41). + for i in from.max(done.saturating_sub(4))..to { let op = history[i]; if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 { continue; @@ -1980,6 +6362,51 @@ fn pump() { } } +#[cfg(test)] +mod trail { + /// The trail keeps the newest things, and the report made when the + /// host device is removed says them and the pipeline library's state + /// (no card is asked for any of it). + #[test] + fn the_removal_report_says_the_newest_things_done() { + for n in 0..super::TRAIL_MOST + 5 { + super::trail(|| format!("thing {n} done")); + } + let text = super::removal_context(); + assert!(text.contains("the submitting thread was")); + assert!(text.contains("pipeline library: no call running")); + assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4))); + assert!(!text.contains("thing 4 done"), "the oldest entries are dropped"); + } +} + +#[cfg(test)] +mod spare { + use super::Spare; + + /// Kept things come back by size, the last given first, and nothing is + /// kept past the limit. + #[test] + fn kept_things_come_back_by_size_within_the_limit() { + let mut spare: Spare = Spare::new(); + assert_eq!(spare.take(4), None); + assert_eq!(spare.give(1, 4, 10), None); + assert_eq!(spare.give(2, 1, 10), None); + assert_eq!(spare.give(3, 4, 10), None); + assert_eq!(spare.bytes, 9); + // Past the limit: handed back, nothing changes. + assert_eq!(spare.give(4, 4, 10), Some(4)); + assert_eq!(spare.bytes, 9); + assert_eq!(spare.take(2), None, "no thing of that size"); + assert_eq!(spare.take(4), Some(3)); + assert_eq!(spare.take(4), Some(1)); + assert_eq!(spare.take(4), None); + assert_eq!(spare.take(1), Some(2)); + assert_eq!(spare.bytes, 0); + assert!(spare.kept.is_empty()); + } +} + #[cfg(test)] mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file use super::Batch; diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index c0236d8..8edcece 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -2,14 +2,18 @@ //! title's own compute passes write most of them; a pass we drop or //! translate wrongly leaves whatever the memory held, and a draw of four //! billion vertices or a dispatch past the host's limits runs until the -//! host resets the display driver. So every record is clamped on the GPU, -//! just before its execution, by a compute shader of ours (HLSL compiled by -//! the system's compiler; a 5.1 shader with its root signature inside). +//! host resets the display driver. So active records are copied and clamped +//! on the GPU into a device-local scratch buffer, just before execution, by a +//! compute shader of ours (HLSL compiled by the system's compiler; a 5.1 +//! shader with its root signature inside), leaving the title's argument and +//! count buffers untouched. //! -//! Each list also has a budget (2^27 vertex instances or threads, groups -//! counted as 64 threads, mesh groups as 128): records past it run empty, -//! so a list of thousands of garbage records cannot run for seconds -//! either. +//! When a count buffer is given, threads at or past `min(max, count)` return +//! immediately without charging the list's budget or reading uninitialized +//! tail slots. Each list has a budget (2^27 vertex instances or threads, +//! groups counted as 64 threads, mesh groups as 128): active records past it +//! run empty, saturating without 32-bit wraparound so a list of thousands of +//! garbage records cannot run for seconds either. //! //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535 //! groups per dimension and 2^20 per dispatch, one-dimensional mesh @@ -24,9 +28,21 @@ use windows::core::s; use crate::host::{HostList, host, transition}; const SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)" -cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; }; -RWByteAddressBuffer args : register(u0); +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer Record : register(b0) { + uint kind; + uint stride; + uint records; + uint args_offset; + // Bit 0: a count buffer bounds the records. Bit 1: the records are a + // window clamped ahead of their draws: one that asks for more than can + // run is left empty and costs nothing. + uint has_count; + uint count_offset; +}; +ByteAddressBuffer src_args : register(t0); +ByteAddressBuffer count_buf : register(t1); +RWByteAddressBuffer dst_args : register(u0); // The list's work so far (vertex instances, threads): past the budget, // records run empty. RWByteAddressBuffer budget : register(u1); @@ -36,35 +52,83 @@ static const uint GROUPS = 1u << 20; [RootSignature(RS)] [numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { - if (id.x >= records) return; - uint at = id.x * stride; + uint eff_count = records; + bool ahead = (has_count & 2u) != 0; + if ((has_count & 1u) != 0) { + eff_count = min(eff_count, count_buf.Load(count_offset)); + } + if (id.x >= eff_count) return; + uint src_at = args_offset + id.x * stride; + uint dst_at = id.x * stride; uint cost; + uint2 draw_counts = uint2(0, 0); + uint3 groups = uint3(0, 0, 0); if (kind <= 1) { // Draws: vertex or index count, then instances. - uint count = min(args.Load(at), 1u << 24); - uint instances = min(args.Load(at + 4), (1u << 26) / max(count, 1u)); + uint2 asked = src_args.Load2(src_at); + if (ahead && (asked.x > (1u << 24) || asked.y > (1u << 24))) { + asked = uint2(0, 0); + } + uint count = min(asked.x, 1u << 24); + uint instances = min(asked.y, (1u << 26) / max(count, 1u)); cost = count * instances; - args.Store2(at, uint2(count, instances)); + draw_counts = uint2(count, instances); } else if (kind == 2) { - uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535)); + uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u)); // x * y fits 32 bits; the whole count may not. if (g.z != 0 && g.x * g.y > GROUPS / g.z) { g = uint3(0, 0, 0); } - cost = g.x * g.y * g.z * 64; - args.Store3(at, g); + cost = g.x * g.y * g.z * 64u; + groups = g; } else { // Mesh dispatches: the console's are one-dimensional. - uint3 g = args.Load3(at); + uint3 g = src_args.Load3(src_at); + // Ahead of its draw, a record over the most a dispatch runs is a + // slot the title has not filled (Grand Theft Auto VI leaves all + // ones there): empty, and not counted below either. + if (ahead && g.x > 65535u) { + g = uint3(0, 0, 0); + } + // Diagnostics, in the budget buffer's next words: the largest + // group count a mesh record asked for, and the groups asked in all. + uint was; + budget.InterlockedMax(4, g.x, was); + budget.InterlockedAdd(8, min(g.x, 1u << 24), was); g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); - cost = g.x * g.y * g.z * 128; - args.Store3(at, g); + cost = g.x * g.y * g.z * 128u; + groups = g; } - uint before; - budget.InterlockedAdd(0, cost, before); - if (before >= BUDGET || before + cost > BUDGET) { - // Draws keep their layout with no vertices; groups become zero. - args.Store(at, 0); + bool over = false; + if (cost > 0) { + uint before; + budget.InterlockedOr(0, 0, before); + [allow_uav_condition] + while (before < BUDGET) { + uint next = (BUDGET - before <= cost) ? BUDGET : (before + cost); + uint prev; + budget.InterlockedCompareExchange(0, before, next, prev); + if (prev == before) break; + before = prev; + } + over = before >= BUDGET || BUDGET - before < cost; + } + if (kind <= 1) { + if (over) { + draw_counts = uint2(0, 0); + } + dst_args.Store2(dst_at, draw_counts); + for (uint off = 8; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } + } else { + if (over) { + groups = uint3(0, 0, 0); + } + dst_args.Store3(dst_at, groups); + for (uint off = 12; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } } } "#; @@ -94,6 +158,10 @@ fn clamp() -> Option<&'static Clamp> { fn make() -> windows::core::Result { let device = &host().ok_or_else(windows::core::Error::empty)?.device; + make_for(device) +} + +fn make_for(device: &ID3D12Device) -> windows::core::Result { let mut code: Option = None; let mut errors: Option = None; // SAFETY: the source and names live through the call; out pointers ours. @@ -116,7 +184,10 @@ fn make() -> windows::core::Result { if let Some(errors) = errors { // SAFETY: the blob's own bytes. let text = unsafe { - std::slice::from_raw_parts(errors.GetBufferPointer().cast::(), errors.GetBufferSize()) + std::slice::from_raw_parts( + errors.GetBufferPointer().cast::(), + errors.GetBufferSize(), + ) }; tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text)); } @@ -125,7 +196,8 @@ fn make() -> windows::core::Result { let code = code.ok_or_else(windows::core::Error::empty)?; // SAFETY: the blob's own bytes; the root signature is inside the shader. unsafe { - let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let bytes = + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), @@ -139,57 +211,199 @@ fn make() -> windows::core::Result { } } -/// Records, in `list`, the clamp of `records` records of `kind` (PC -/// argument numbering) `stride` bytes apart at host address `gpu` in -/// `buffer`, and leaves the buffer ready to be read as arguments. Replaces -/// the list's compute root signature and pipeline (callers bind theirs -/// after). False if the clamp is not available. +/// Minimum record byte stride for a supported PC indirect argument `kind`. +fn min_stride(kind: u32) -> Option { + match kind { + 0 => Some(16), + 1 => Some(20), + 2 | 10 => Some(12), + _ => None, + } +} + +/// Validates record alignment and returns the scratch byte size `stride * records`. +fn validate_layout( + (kind, stride, records): (u32, u32, u32), + src_offset: u64, + count_offset: Option, +) -> Option { + let min = min_stride(kind)?; + if stride < min || !stride.is_multiple_of(4) || !src_offset.is_multiple_of(4) { + return None; + } + if count_offset.is_some_and(|off| !off.is_multiple_of(4)) { + return None; + } + let bytes = u64::from(stride).checked_mul(u64::from(records))?; + (bytes <= u64::from(u32::MAX)).then_some(bytes) +} + +/// Records, in `list`, the non-destructive clamp of up to `records` records of +/// `kind` (PC argument numbering) `stride` bytes apart from `src` (and bounded +/// by the 32-bit count in `count` when given) into a device-local scratch +/// buffer, leaving that scratch buffer in `INDIRECT_ARGUMENT` at offset `0`. +/// Replaces the list's compute root signature and pipeline (callers bind +/// theirs after). `None` if the clamp or alignment is not available. pub(crate) fn bound( list: &HostList, - buffer: &ID3D12Resource, - gpu: u64, - (kind, stride, records): (u32, u32, u32), + src: (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + spec: (u32, u32, u32), +) -> Option { + let bytes = validate_layout(spec, src.1, count.map(|(_, off)| off))?; + let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?); + record_clamp(c, &list.list, &dst, budget, src, count, spec).then_some(dst) +} + +/// [`bound`] for a window of records clamped ahead of the draws that will +/// read them (`crate::draw`'s windows; no count buffer). The records past +/// the ones the title filled are whatever the buffer holds, and each +/// record clamped charges the list's budget when it is clamped: a slot of +/// all ones, clamped to the most a mesh dispatch runs (65,535 groups), +/// charged a sixteenth of the budget, so sixteen of them emptied every +/// draw of the list after them (run 93: "the largest group count asked for +/// 4294967295", 43 to 153 such records a frame). Here a record that asks +/// for more than can run is left empty and charges nothing; a record +/// clamped alone is clamped and charged as before. +pub(crate) fn bound_ahead( + list: &HostList, + src: (&ID3D12Resource, u64), + spec: (u32, u32, u32), +) -> Option { + let bytes = validate_layout(spec, src.1, None)?; + let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?); + record_clamp_as(c, &list.list, &dst, budget, src, None, spec, true).then_some(dst) +} + +fn record_clamp( + c: &Clamp, + l: &ID3D12GraphicsCommandList, + dst: &ID3D12Resource, + budget: u64, + src: (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + spec: (u32, u32, u32), ) -> bool { - let (Some(c), Some(budget)) = (clamp(), list.budget()) else { + record_clamp_as(c, l, dst, budget, src, count, spec, false) +} + +/// [`record_clamp`]; `ahead`: the records are a window clamped ahead of +/// their draws ([`bound_ahead`]). +#[allow(clippy::too_many_arguments)] +fn record_clamp_as( + c: &Clamp, + l: &ID3D12GraphicsCommandList, + dst: &ID3D12Resource, + budget: u64, + (src, src_offset): (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + (kind, stride, records): (u32, u32, u32), + ahead: bool, +) -> bool { + let Some(bytes) = validate_layout( + (kind, stride, records), + src_offset, + count.map(|(_, off)| off), + ) else { return false; }; - if !gpu.is_multiple_of(4) || !stride.is_multiple_of(4) { + // SAFETY: live D3D12 buffer resources. + let (src_base, dst_gpu) = unsafe { (src.GetGPUVirtualAddress(), dst.GetGPUVirtualAddress()) }; + if !src_base.is_multiple_of(4) || !dst_gpu.is_multiple_of(4) || !budget.is_multiple_of(4) { return false; } - let l = &list.list; - let constants = [kind, stride, records, 0]; - // SAFETY: an open list; our root signature, pipeline and a live buffer - // the caller's list holds. + let (src_gpu, args_offset) = match src_offset + .checked_add(bytes) + .filter(|&end| end <= u64::from(u32::MAX)) + { + Some(_) => (src_base, src_offset as u32), + None => { + let Some(rebased) = src_base.checked_add(src_offset) else { + return false; + }; + (rebased, 0) + } + }; + let (count_gpu, has_count, count_offset) = match count { + Some((buf, off)) => { + // SAFETY: a live D3D12 buffer resource. + let base = unsafe { buf.GetGPUVirtualAddress() }; + if !base.is_multiple_of(4) { + return false; + } + match off.checked_add(4).filter(|&end| end <= u64::from(u32::MAX)) { + Some(_) => (base, 1u32, off as u32), + None => { + let Some(rebased) = base.checked_add(off) else { + return false; + }; + (rebased, 1u32, 0u32) + } + } + } + None => (src_gpu, 0u32, 0u32), + }; + let constants = [kind, stride, records, args_offset, has_count | (u32::from(ahead) << 1), count_offset]; + // SAFETY: an open list; our root signature and pipeline; live source, + // count, scratch destination, and budget buffers. `src` and `count` stay + // in `COMMON` / `GENERIC_READ` via implicit buffer promotion while `dst` + // transitions `COMMON -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT`. + // Diagnostics: counted; `VICTORY_BARRIER_TEST=indirect` leaves the two + // waits for every earlier shader write out (the state changes stay). + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::IndirectBounded, 1); + #[cfg(feature = "diagnostics")] + let waits = crate::copystat::barrier_test() & 2 == 0; + #[cfg(not(feature = "diagnostics"))] + let waits = true; + let first = [ + uav_barrier(), + transition( + dst, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ), + ]; + let second = [ + uav_barrier(), + transition( + dst, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + ), + ]; + let skip = usize::from(!waits); unsafe { - // Earlier shader writes (the title's argument passes) first. - l.ResourceBarrier(&[uav_barrier()]); - l.SetComputeRootSignature(&c.root); - l.SetPipelineState(&c.pso); - l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); - l.SetComputeRootUnorderedAccessView(1, gpu); - l.SetComputeRootUnorderedAccessView(2, budget); - l.Dispatch(records.div_ceil(64), 1, 1); - l.ResourceBarrier(&[ - uav_barrier(), - transition( - buffer, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - ), - ]); + // Earlier shader writes (the title's argument and count passes) first. + l.ResourceBarrier(&first[skip..]); + if records > 0 { + l.SetComputeRootSignature(&c.root); + l.SetPipelineState(&c.pso); + l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + l.SetComputeRootShaderResourceView(1, src_gpu); + l.SetComputeRootShaderResourceView(2, count_gpu); + l.SetComputeRootUnorderedAccessView(3, dst_gpu); + l.SetComputeRootUnorderedAccessView(4, budget); + l.Dispatch(records.div_ceil(64), 1, 1); + } + l.ResourceBarrier(&second[skip..]); } true } -/// After the execution: the buffer back to unordered access, where the -/// title's passes keep using it. -pub(crate) fn done(list: &HostList, buffer: &ID3D12Resource) { - // SAFETY: an open list and a live buffer. +/// After indirect execution (or if preparation failed after [`bound`]): +/// returns the scratch buffer to the common state for the next call. +pub(crate) fn done(list: &HostList, scratch: &ID3D12Resource) { + done_on(&list.list, scratch); +} + +fn done_on(list: &ID3D12GraphicsCommandList, scratch: &ID3D12Resource) { + // SAFETY: an open list and a live scratch buffer in INDIRECT_ARGUMENT. unsafe { - list.list.ResourceBarrier(&[transition( - buffer, + list.ResourceBarrier(&[transition( + scratch, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COMMON, )]) }; } @@ -199,13 +413,313 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { - UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }), + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), }, } } #[cfg(test)] mod tests { + use super::*; + use windows::Win32::Foundation::HANDLE; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::*; + use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + use windows::core::Interface; + + const WORKER_CS: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer hits : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint prev; + hits.InterlockedAdd(0, 1, prev); +} +"#; + + struct WarpHarness { + device: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + submitted: u64, + event: HANDLE, + clamp: Clamp, + worker: Clamp, + } + + impl WarpHarness { + fn new() -> Option { + // SAFETY: plain DXGI WARP query and D3D12 test harness setup. + unsafe { + let factory: IDXGIFactory4 = + CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let desc = adapter.cast::().ok()?.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return None; + } + let mut device: Option = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .ok()?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + let clamp = make_for(&device).expect("clamp shader must compile on WARP"); + let worker = compile_cs(&device, WORKER_CS).expect("worker shader must compile"); + Some(Self { + device, + queue, + allocator, + list, + fence, + submitted: 0, + event, + clamp, + worker, + }) + } + } + + /// CPU-mapped L0 write-back buffer matching `Shadow`'s heap type. + fn shared_buffer(&self, size: u64) -> (ID3D12Resource, *mut u8, u64) { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(4), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain buffer creation and persistent CPU mapping. + unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .unwrap(); + let buffer = buffer.unwrap(); + buffer.Map(0, None, Some(&mut data)).unwrap(); + let gpu = buffer.GetGPUVirtualAddress(); + (buffer, data.cast(), gpu) + } + } + + /// Device-local `DEFAULT`-heap UAV scratch buffer. + fn default_uav(&self, size: u64) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(64 << 10), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain device-local buffer creation. + unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .unwrap(); + } + buffer.unwrap() + } + + fn signature(&self, kind: u32, stride: u32) -> ID3D12CommandSignature { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: stride, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + // SAFETY: valid single-argument command signature description. + unsafe { + self.device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + } + sig.unwrap() + } + + fn submit_and_wait(&mut self) { + self.submitted += 1; + // SAFETY: closing, executing, waiting on fence, and resetting our list. + unsafe { + self.list.Close().unwrap(); + let cmd: ID3D12CommandList = self.list.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(cmd)]); + self.queue.Signal(&self.fence, self.submitted).unwrap(); + self.fence + .SetEventOnCompletion(self.submitted, self.event) + .unwrap(); + WaitForSingleObject(self.event, INFINITE); + self.allocator.Reset().unwrap(); + self.list.Reset(&self.allocator, None).unwrap(); + } + } + } + + fn compile_cs(device: &ID3D12Device, source: &str) -> windows::core::Result { + let mut code: Option = None; + // SAFETY: source and entry names outlive `D3DCompile`. + unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + s!("worker"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + let code = code.unwrap(); + let bytes = std::slice::from_raw_parts( + code.GetBufferPointer().cast::(), + code.GetBufferSize(), + ); + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; + let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + Ok(Clamp { root, pso }) + } + } + + /// The compare of copies in the card's memory (`crate::host`), on the + /// software adapter. Told 1 it flags the pieces whose bytes are not + /// what was hashed last and leaves the hashes: a piece a shader changed + /// and a later one changed back then looks untouched, which is right + /// only if the piece was fetched after both. Told 2 (submissions sent + /// ahead with the relay, whose pieces are fetched flight by flight) it + /// stores the hash it made: each compare flags what changed since the + /// compare before it, also a change back. + #[test] + fn warp_card_compare_stores_the_hash_it_made_when_told() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + let compare = compile_cs(&warp.device, crate::host::CARD_COMPARE).expect("the card compare must compile on WARP"); + const PIECE: usize = 64 << 10; + const PIECES: u32 = 3; + let size = PIECE * PIECES as usize; + let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64); + let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES)); + let (_differs, differs_ptr, differs_gpu) = warp.shared_buffer(64); + let content: Vec = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); + // SAFETY: the mapping holds `size` bytes. + unsafe { std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size) }; + // One pass over the three pieces; what it left in `differs` (7s + // where it stored nothing). + let run = |warp: &mut WarpHarness, mode: u32| -> [u32; 3] { + // SAFETY: our open list, live buffers, the compare's own root + // signature; the mappings hold what is read and written. + unsafe { + for piece in 0..PIECES as usize { + differs_ptr.cast::().add(piece).write_volatile(7); + } + warp.list.SetComputeRootSignature(&compare.root); + warp.list.SetPipelineState(&compare.pso); + let constants = [0u32, 0, size as u32, PIECES, 0, mode]; + warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + warp.list.SetComputeRootShaderResourceView(1, now_gpu); + warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu); + warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu); + warp.list.Dispatch(PIECES.div_ceil(64), 1, 1); + } + warp.submit_and_wait(); + // SAFETY: as above. + [0, 1, 2].map(|piece| unsafe { differs_ptr.cast::().add(piece).read_volatile() }) + }; + let at = PIECE + 1234; + // SAFETY (each): inside the mapping. + let set = |value: u8| unsafe { now_ptr.add(at).write_volatile(value) }; + // 0: the hashes are stored, nothing is flagged. + assert_eq!(run(&mut warp, 0), [7, 7, 7]); + assert_eq!(run(&mut warp, 1), [0, 0, 0]); + // A change in the second piece: flagged, and with 1 flagged again + // (the hash stays the old one). + set(content[at] ^ 0x40); + assert_eq!(run(&mut warp, 1), [0, 1, 0]); + assert_eq!(run(&mut warp, 1), [0, 1, 0]); + // Changed back: with 1 the piece looks untouched. + set(content[at]); + assert_eq!(run(&mut warp, 1), [0, 0, 0]); + // With 2 the change is flagged once, and the hash is the new one. + set(content[at] ^ 0x40); + assert_eq!(run(&mut warp, 2), [0, 1, 0]); + assert_eq!(run(&mut warp, 2), [0, 0, 0]); + // Changed back: flagged, where 1 saw nothing. + set(content[at]); + assert_eq!(run(&mut warp, 2), [0, 1, 0]); + assert_eq!(run(&mut warp, 2), [0, 0, 0]); + } + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { @@ -214,4 +728,489 @@ mod tests { } assert!(super::clamp().is_some()); } + + #[test] + fn rejects_unaligned_or_undersized_layouts() { + assert_eq!(validate_layout((0, 16, 4), 0, None), Some(64)); + assert_eq!(validate_layout((1, 20, 4), 64, Some(128)), Some(80)); + assert_eq!(validate_layout((2, 12, 0), 0, Some(0)), Some(0)); + assert_eq!(validate_layout((10, 16, 2), 8, None), Some(32)); + // Undersized strides for each kind. + assert_eq!(validate_layout((0, 12, 1), 0, None), None); + assert_eq!(validate_layout((1, 16, 1), 0, None), None); + assert_eq!(validate_layout((2, 8, 1), 0, None), None); + assert_eq!(validate_layout((10, 8, 1), 0, None), None); + // Unknown kind. + assert_eq!(validate_layout((3, 16, 1), 0, None), None); + // Unaligned stride, source offset, or count offset. + assert_eq!(validate_layout((0, 18, 1), 0, None), None); + assert_eq!(validate_layout((0, 16, 1), 2, None), None); + assert_eq!(validate_layout((0, 16, 1), 0, Some(6)), None); + // Total byte size exceeding 32-bit ByteAddressBuffer indexing. + assert_eq!(validate_layout((1, 20, u32::MAX), 0, None), None); + } + + /// WARP D3D12 execution test proving: + /// (a) `countBuffer` with a small count (`3`) and `4,093` garbage tail slots + /// (`max = 4096`) does NOT blow `BUDGET` or zero valid dispatches in + /// this or subsequent `ExecuteIndirect` calls in the same list, + /// (b) `src_args` (and `count_buf`) are NOT mutated in-place, and + /// (c) full `stride` bytes (`stride = 24` > `12`) are copied for active + /// records into `dst_args` at offset `0`. + #[test] + fn warp_count_buffer_ignores_garbage_tail_and_preserves_source() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_DISPATCH: u32 = 2; + const STRIDE: u32 = 24; // 6 dwords: 3 dispatch group counts + 3 extra payload dwords + const MAX: u32 = 4096; + const ARGS_OFFSET: usize = 64; // non-zero offset with sentinel prefix + const COUNT_OFFSET_1: usize = 128; + const COUNT_OFFSET_2: usize = 192; + + let src_bytes = ARGS_OFFSET + (STRIDE as usize) * (MAX as usize) + 64; + let (src_buf, src_ptr, _) = warp.shared_buffer(src_bytes as u64); + let (count_buf, count_ptr, _) = warp.shared_buffer(512); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer((STRIDE * 8) as u64); + let dst_buf = warp.default_uav(u64::from(STRIDE) * u64::from(MAX)); + let sig = warp.signature(KIND_DISPATCH, STRIDE); + + // Fill the entire source buffer with non-zero sentinel bytes, then + // populate 3 valid records at `ARGS_OFFSET` and 4,093 huge garbage + // records in `3..MAX` that would exhaust `BUDGET` ~2,000x over if read. + let mut initial_src = vec![0xA5u8; src_bytes]; + let write_record = |buf: &mut [u8], idx: usize, words: [u32; 6]| { + let base = ARGS_OFFSET + idx * (STRIDE as usize); + for (w, val) in words.into_iter().enumerate() { + buf[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes()); + } + }; + write_record( + &mut initial_src, + 0, + [3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666], + ); + write_record( + &mut initial_src, + 1, + [5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC], + ); + // Record 2 exceeds 65,535 in X -> clamped to (65535, 1, 1). + write_record( + &mut initial_src, + 2, + [100_000, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567], + ); + for slot in 3..MAX as usize { + // Each garbage slot would clamp to 65535 * 16 * 1 = 1,048,560 groups + // (`cost = 67,107,840 ~= BUDGET / 2`), exhausting `BUDGET` immediately! + write_record( + &mut initial_src, + slot, + [0xFFFF_FFFF, 16, 1, 0xDEAD_BEEF, 0xBAD0_C0DE, slot as u32], + ); + } + + // Second indirect call's source records (at offset 0 of a second buffer, + // or later in `count_buf`): put 2 active records + garbage tail in a + // second range to run back-to-back in the SAME command list. + let mut initial_count = vec![0x5Au8; 512]; + initial_count[COUNT_OFFSET_1..COUNT_OFFSET_1 + 4].copy_from_slice(&3u32.to_le_bytes()); + initial_count[COUNT_OFFSET_2..COUNT_OFFSET_2 + 4].copy_from_slice(&2u32.to_le_bytes()); + + // SAFETY: buffers are mapped with exact capacities above. + unsafe { + std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, src_bytes); + std::ptr::copy_nonoverlapping(initial_count.as_ptr(), count_ptr, 512); + (budget_ptr as *mut u32).write_volatile(0); + (hits_ptr as *mut u32).write_volatile(0); + std::ptr::write_bytes(readback_ptr, 0, (STRIDE * 8) as usize); + } + + // Record Call #1 (`eff_count = 3` out of `MAX = 4096`), copy the first + // 5 records of `dst_buf` out for inspection, then record Call #2 + // (`eff_count = 2` out of `MAX = 4096`) reusing `dst_buf` in the same list! + assert!(record_clamp( + &warp.clamp, + &warp.list, + &dst_buf, + budget_gpu, + (&src_buf, ARGS_OFFSET as u64), + Some((&count_buf, COUNT_OFFSET_1 as u64)), + (KIND_DISPATCH, STRIDE, MAX), + )); + // SAFETY: open command list, valid worker PSO/root and buffers. + unsafe { + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + warp.list.ExecuteIndirect( + &sig, + MAX, + &dst_buf, + 0, + Some(&count_buf), + COUNT_OFFSET_1 as u64, + ); + } + done_on(&warp.list, &dst_buf); + + // Snapshot `dst_buf` after Call #1 (from `COMMON`, copy 5 * STRIDE bytes, + // then return `dst_buf` to `COMMON` before Call #2). + // SAFETY: open command list; `dst_buf` returned to `COMMON` by `done_on`. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list + .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, u64::from(STRIDE * 5)); + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + + // Call #2 in the SAME command list (`eff_count = 2` -> records 0 and 1: + // 6 + 5 = 11 groups). Would run empty if Call #1's tail blew `BUDGET`! + assert!(record_clamp( + &warp.clamp, + &warp.list, + &dst_buf, + budget_gpu, + (&src_buf, ARGS_OFFSET as u64), + Some((&count_buf, COUNT_OFFSET_2 as u64)), + (KIND_DISPATCH, STRIDE, MAX), + )); + // SAFETY: open command list, valid worker PSO/root and buffers. + unsafe { + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + warp.list.ExecuteIndirect( + &sig, + MAX, + &dst_buf, + 0, + Some(&count_buf), + COUNT_OFFSET_2 as u64, + ); + } + done_on(&warp.list, &dst_buf); + + warp.submit_and_wait(); + + // SAFETY: GPU execution finished; read mapped host results. + let (hits, spent, after_src, after_count, clamped_words) = unsafe { + let hits = (hits_ptr as *const u32).read_volatile(); + let spent = (budget_ptr as *const u32).read_volatile(); + let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), src_bytes).to_vec(); + let after_count = std::slice::from_raw_parts(count_ptr.cast_const(), 512).to_vec(); + let words = std::slice::from_raw_parts( + readback_ptr.cast::().cast_const(), + (STRIDE as usize / 4) * 5, + ) + .to_vec(); + (hits, spent, after_src, after_count, words) + }; + + // Call #1: (3*2*1) + (5*1*1) + (65535*1*1) = 65,546 groups. + // Call #2: (3*2*1) + (5*1*1) = 11 groups. + let expected_groups = (6 + 5 + 65_535) + (6 + 5); + assert_eq!( + hits, expected_groups, + "valid indirect dispatches must all execute" + ); + assert_eq!( + spent, + expected_groups * 64, + "budget must reflect only active records below countBuffer" + ); + assert_eq!( + after_src, initial_src, + "src_args must never be mutated in-place" + ); + assert_eq!( + after_count, initial_count, + "count_buf must never be mutated" + ); + + // Check `dst_args` records 0..3: clamped group counts + preserved extra stride words. + assert_eq!( + &clamped_words[0..6], + &[3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666] + ); + assert_eq!( + &clamped_words[6..12], + &[5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC] + ); + assert_eq!( + &clamped_words[12..18], + &[65_535, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567] + ); + // Inactive slot 3 was never copied from `src_args`. + assert_ne!(clamped_words[21], 0xDEAD_BEEF); + } + + /// WARP D3D12 test proving `BUDGET` saturates without 32-bit unsigned + /// wraparound across >64 huge indexed-draw records (`count = None`), while + /// preserving `StartIndexLocation`, `BaseVertexLocation`, + /// `StartInstanceLocation`, and custom stride padding, and leaving + /// `src_args` untouched. + /// A window of mesh records clamped ahead: the filled ones come out as + /// they are and are charged, the slots of all ones come out empty and + /// charge nothing; clamped as single records the same slots are clamped + /// to the most and spend the budget. + #[test] + fn warp_window_leaves_unfilled_slots_empty_and_uncharged() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_MESH: u32 = 10; + const STRIDE: u32 = 32; + const RECORDS: u32 = 16; + let filled = [5u32, 0, 519]; + let total = (STRIDE * RECORDS) as usize; + let mut src = vec![0xffu8; total]; + for (i, groups) in filled.into_iter().enumerate() { + let words = [groups, 1, 1, 0xAB00 + i as u32]; + for (w, word) in words.into_iter().enumerate() { + let at = i * STRIDE as usize + w * 4; + src[at..at + 4].copy_from_slice(&word.to_le_bytes()); + } + } + for ahead in [true, false] { + let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64); + let dst_buf = warp.default_uav(total as u64); + // SAFETY: mapped buffers of these sizes. + unsafe { + std::ptr::copy_nonoverlapping(src.as_ptr(), src_ptr, total); + std::ptr::write_bytes(budget_ptr, 0, 256); + std::ptr::write_bytes(readback_ptr, 0, total); + } + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + &dst_buf, + budget_gpu, + (&src_buf, 0), + None, + (KIND_MESH, STRIDE, RECORDS), + ahead, + )); + done_on(&warp.list, &dst_buf); + // SAFETY: an open list; the scratch buffer is copied for the check. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64); + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + warp.submit_and_wait(); + // SAFETY: the work is done; mapped buffers. + let (spent, largest, out) = unsafe { + ( + (budget_ptr as *const u32).read_volatile(), + (budget_ptr as *const u32).add(1).read_volatile(), + std::slice::from_raw_parts(readback_ptr.cast::().cast_const(), total / 4).to_vec(), + ) + }; + for (i, groups) in filled.into_iter().enumerate() { + let rec = &out[i * 8..i * 8 + 4]; + assert_eq!(rec, [groups, u32::from(groups > 0).max(1).min(1), 1, 0xAB00 + i as u32], "filled record {i}, ahead {ahead}"); + } + let charged_filled = (5 + 519) * 128; + if ahead { + for i in filled.len()..RECORDS as usize { + assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty"); + assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are"); + } + assert_eq!(spent, charged_filled, "unfilled slots charge nothing"); + assert_eq!(largest, 519, "and are not counted as asked for"); + } else { + // Thirteen slots at 65,535 groups: sixteen would be all of it. + assert_eq!(spent, charged_filled + 13 * 65535 * 128, "clamped one by one, each slot is charged the most"); + assert_eq!(largest, u32::MAX); + } + } + } + + #[test] + fn warp_budget_saturates_without_wraparound_and_preserves_draw_fields() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_INDEXED: u32 = 1; + const STRIDE: u32 = 24; // 5 indexed-draw words + 1 trailing custom word + const RECORDS: u32 = 128; // 2 waves of 64: old InterlockedAdd wrapped 2^32 at 64! + const BUDGET_CAP: u32 = 1 << 27; + + let total_bytes = (STRIDE * RECORDS) as usize; + let (src_buf, src_ptr, _) = warp.shared_buffer(total_bytes as u64); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(total_bytes as u64); + let dst_buf = warp.default_uav(total_bytes as u64); + + let mut initial_src = vec![0u8; total_bytes]; + for i in 0..RECORDS as usize { + let words: [u32; 6] = [ + u32::MAX, // IndexCount -> clamps to 1 << 24 + u32::MAX, // InstanceCount -> clamps to 4 (cost = 1 << 26) + 1000 + i as u32, // StartIndexLocation + (-200i32 + i as i32) as u32, // BaseVertexLocation + 5000 + i as u32, // StartInstanceLocation + 0xCAFE_0000 | (i as u32), // Extra stride word + ]; + let base = i * (STRIDE as usize); + for (w, val) in words.into_iter().enumerate() { + initial_src[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes()); + } + } + + // SAFETY: mapped buffers have sufficient capacity. + unsafe { + std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, total_bytes); + (budget_ptr as *mut u32).write_volatile(0); + std::ptr::write_bytes(readback_ptr, 0, total_bytes); + } + + assert!(record_clamp( + &warp.clamp, + &warp.list, + &dst_buf, + budget_gpu, + (&src_buf, 0), + None, + (KIND_INDEXED, STRIDE, RECORDS), + )); + done_on(&warp.list, &dst_buf); + + // SAFETY: open command list; copy clamped scratch buffer for verification. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list + .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total_bytes as u64); + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + warp.submit_and_wait(); + + // SAFETY: GPU work completed. + let (spent, after_src, out_words) = unsafe { + let spent = (budget_ptr as *const u32).read_volatile(); + let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), total_bytes).to_vec(); + let out_words = std::slice::from_raw_parts( + readback_ptr.cast::().cast_const(), + total_bytes / 4, + ) + .to_vec(); + (spent, after_src, out_words) + }; + + assert_eq!( + spent, BUDGET_CAP, + "budget must saturate at BUDGET without wrapping" + ); + assert_eq!(after_src, initial_src, "src_args must remain untouched"); + + let mut kept = 0usize; + let mut zeroed = 0usize; + for i in 0..RECORDS as usize { + let rec = &out_words[i * 6..(i + 1) * 6]; + if rec[0] == (1 << 24) && rec[1] == 4 { + kept += 1; + } else { + assert_eq!((rec[0], rec[1]), (0, 0), "excess draw must be zeroed"); + zeroed += 1; + } + assert_eq!(rec[2], 1000 + i as u32); + assert_eq!(rec[3], (-200i32 + i as i32) as u32); + assert_eq!(rec[4], 5000 + i as u32); + assert_eq!(rec[5], 0xCAFE_0000 | (i as u32)); + } + assert_eq!((kept, zeroed), (2, (RECORDS as usize) - 2)); + } + + /// Exercises `HostList::indirect_scratch`, `bound`, `done`, `Host::execute`, + /// and `HostList::reset` end-to-end on the host device. + #[test] + fn host_list_reuses_and_grows_scratch_across_submissions() { + let Some(host) = super::host() else { + return; + }; + let Ok(list) = host.new_list() else { + return; + }; + let Some((src_buf, src_ptr)) = host.shared_buffer(256 << 10) else { + return; + }; + let Some((count_buf, count_ptr)) = host.shared_buffer(256) else { + return; + }; + // SAFETY: mapped host buffers. + unsafe { + std::ptr::write_bytes(src_ptr, 0x7F, 256 << 10); + (count_ptr as *mut u32).write_volatile(2); + } + + // First two calls fit inside the initial 64 KiB scratch buffer and + // must reuse the exact same `ID3D12Resource`. + let b1 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (0, 16, 64)).unwrap(); + done(&list, &b1); + let b2 = bound(&list, (&src_buf, 64), Some((&count_buf, 0)), (1, 20, 128)).unwrap(); + done(&list, &b2); + assert_eq!( + b1.as_raw(), + b2.as_raw(), + "scratch buffer within capacity must be reused" + ); + + // A call needing >64 KiB grows the scratch buffer mid-list while keeping + // `b1` alive until reset. + let b3 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 5000)).unwrap(); + done(&list, &b3); + assert_ne!( + b3.as_raw(), + b1.as_raw(), + "larger request must grow scratch buffer" + ); + + list.close(); + host.execute(&[&list]); + list.reset(); + + // After reset, requests up to the grown high-water mark reuse `b3` with + // zero new allocations. + let b4 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 4096)).unwrap(); + done(&list, &b4); + assert_eq!( + b4.as_raw(), + b3.as_raw(), + "grown scratch buffer must persist across reset" + ); + list.close(); + host.execute(&[&list]); + list.reset(); + } } diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs new file mode 100644 index 0000000..25461df --- /dev/null +++ b/crates/victory-gpu/src/inplace.rs @@ -0,0 +1,1170 @@ +//! Title memory as the card's own memory: a host heap opened on memory +//! the title already has, and a buffer placed in it, so that shaders read +//! and write the title's bytes themselves and no host copy stands between +//! (the console's one memory). This file holds the two openings Direct3D +//! has, a probe that says what this PC's driver makes of them +//! (`VICTORY_INPLACE_PROBE`), and a census of which title memory could be +//! opened. +//! +//! What the Direct3D runtime and the kernel answer, measured on this PC +//! with the software adapter (the rules are theirs, not the adapter's; +//! what the card's driver adds is what the probe is for): +//! +//! - `OpenExistingHeapFromAddress` takes the base address of a whole +//! `VirtualAlloc` allocation and nothing inside it; every page must be +//! committed and have one protection. Opening locks every page into the +//! PC's memory at once (256 MiB never touched: 70 ms and 256 MB of +//! working set). +//! - `OpenExistingHeapFromAddress1` (`ID3D12Device13`) takes any committed +//! part of an allocation, with the same rule for its pages; parts may +//! overlap, and the whole may be opened beside them. It also takes a +//! committed view of a section. +//! - `OpenExistingHeapFromFileMapping` takes a section made with +//! `SEC_COMMIT` and refuses one made with `SEC_RESERVE` (how `xmem` +//! makes the title's page pool today). The heap is the section, not a +//! view of it: views may be unmapped, mapped elsewhere or made +//! read-only, and the section's handle closed, with the heap alive. +//! Opening it locks nothing (256 MiB: 0.2 ms, no working set). +//! - The heap is a custom heap in the PC's memory (write-back pages, pool +//! L0), shared and cross-adapter shared, 64 KiB aligned. A buffer in it +//! must have `ALLOW_CROSS_ADAPTER`; unordered access beside it is taken. +//! A texture must be row-major with one level. Tile mappings into such +//! a heap are refused and REMOVE THE DEVICE: never call them. +//! - While a heap opened from an address stands, the title cannot +//! decommit, release or protect the pages in it (`VirtualFree` and +//! `VirtualProtect` fail with error 87), nor unmap a view in it. Pages +//! outside the opened part are free to change. + +use std::collections::BTreeMap; +use std::ffi::c_void; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use windows::Win32::Foundation::HANDLE; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; +use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; +use windows::core::{Interface, s}; +use windows_sys::Win32::System::Memory as mem; + +/// The unit heaps and placed buffers are cut on, and the console's page. +const K64: usize = 64 << 10; +/// The host's write watching (not in windows-sys' memory module). +const MEM_WRITE_WATCH: u32 = 0x20_0000; + +/// `VICTORY_INPLACE_PROBE`: 0 (unset) nothing; 1 the probe on memory of +/// its own at the first sweep, and the census 30 and 150 seconds later; +/// 2 also opens one part of the title's own memory for a moment at the +/// first census. +pub(crate) fn probe_level() -> u8 { + static LEVEL: std::sync::OnceLock = std::sync::OnceLock::new(); + *LEVEL.get_or_init(|| std::env::var("VICTORY_INPLACE_PROBE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) +} + +/// `VICTORY_INPLACE`: 0 (unset) off. 1: a window of title memory outside +/// buffers that lies in private memory committed whole is not copied: a +/// part of the title's allocation is opened as a host heap and the window +/// is a buffer placed over it ([`place_for`]). 2: title buffers too, +/// except the big ones in the card's memory. +/// +/// What stage 1 covers is private memory (`XMemVirtualAlloc`'s). View +/// memory (the page pool) is turned down here: its section is made +/// reserved, which the host refuses, and what a view shows changes when +/// the title maps pages. +/// +/// What it assumes, for 2: nothing reads title memory that a submission +/// not yet run writes through such a buffer. With every submission waited +/// for (the default) that holds; with `VICTORY_LATE_WAIT` it does not, +/// since the flights' rules know shader writes only by the ranges copies +/// declare. Do not combine 2 with late wait. +/// +/// shortcut: while a window is in place the title cannot decommit, free +/// or protect its pages (the call fails with error 87; the probe shows +/// it). The title's heaps are allocated once and kept, and nothing of the +/// kind was seen; [`title_memory_freeing`] is there for the runtime to +/// call before such a call once it takes them over. +pub(crate) fn level() -> u8 { + static LEVEL: std::sync::OnceLock = std::sync::OnceLock::new(); + *LEVEL.get_or_init(|| std::env::var("VICTORY_INPLACE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) +} + +/// The most title memory in place at once, in bytes +/// (`VICTORY_INPLACE_MB`, 4096): opening locks the pages into the PC's +/// memory, also those the title never touched. +fn most() -> u64 { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| std::env::var("VICTORY_INPLACE_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(4096) << 20) +} + +/// In place now: windows and their bytes, title buffers and their bytes; +/// then, since the start: asks turned down because the memory is a view +/// or not private memory committed whole, because the host refused, +/// because of [`most`]; and what was let go because its memory changed. +static STATS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + +/// A buffer placed over title memory, and its heap. +pub(crate) struct Placed { + pub(crate) buffer: ID3D12Resource, + pub(crate) heap: ID3D12Heap, + /// The host GPU address of the title memory's first byte. + pub(crate) gpu: u64, + /// Bytes from the buffer's first byte to the title memory's first. + pub(crate) bias: u64, +} + +/// Opens the 64 KiB pages that hold title memory `[start, start + len)` +/// as a heap of their own and places one buffer over all of them. `Err` +/// with nothing if the memory is not private memory committed whole +/// (nothing was asked of the host), with the host's error if it refused. +pub(crate) fn place_part(device: &ID3D12Device, start: u64, len: u64) -> Result> { + let at = start & !(K64 as u64 - 1); + let bytes = (start + len.max(1)).next_multiple_of(K64 as u64) - at; + if !private_whole(at as usize, bytes as usize) { + return Err(None); + } + let heap = open(device, From::Part(at as usize, bytes as usize)).map_err(Some)?; + let buffer = place(device, &heap, 0, bytes).map_err(Some)?; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() } + (start - at); + Ok(Placed { buffer, heap, gpu, bias: start - at }) +} + +/// Title memory `[start, start + len)` in place, for a window outside +/// buffers or a title buffer, if [`level`] asks for it and the memory can +/// be opened; `None` leaves the caller to make a copy, as before. +pub(crate) fn place_for(start: u64, len: u64, window: bool) -> Option { + if level() < if window { 1 } else { 2 } { + return None; + } + // View memory: known from the runtime without asking Windows. + if cover(start as usize, len as usize) != Cover::None { + STATS[4].fetch_add(1, Ordering::Relaxed); + return None; + } + if STATS[1].load(Ordering::Relaxed) + STATS[3].load(Ordering::Relaxed) + len > most() { + STATS[6].fetch_add(1, Ordering::Relaxed); + return None; + } + let host = crate::host::host()?; + match place_part(&host.device, start, len) { + Ok(placed) => { + let at = if window { 0 } else { 2 }; + STATS[at].fetch_add(1, Ordering::Relaxed); + STATS[at + 1].fetch_add(len, Ordering::Relaxed); + Some(placed) + } + Err(None) => { + STATS[4].fetch_add(1, Ordering::Relaxed); + None + } + Err(Some(e)) => { + if STATS[5].fetch_add(1, Ordering::Relaxed) < 8 { + tracing::warn!(start = format_args!("{start:#x}"), len, error = %e, "title memory not opened in place: a copy instead"); + } + None + } + } +} + +/// What [`place_for`] gave is gone. +pub(crate) fn gone(window: bool, bytes: u64) { + let at = if window { 0 } else { 2 }; + STATS[at].fetch_sub(1, Ordering::Relaxed); + STATS[at + 1].fetch_sub(bytes, Ordering::Relaxed); +} + +/// Title memory `[at, at + len)` is about to show something else, or the +/// title is about to decommit, free or protect it: what is in place there +/// is let go (the tables forget it; its heap goes when the last list and +/// slot that hold it do). Called for memory the runtime maps anew; for +/// the runtime to call before the title's own `VirtualFree` once it takes +/// that call over. +pub fn title_memory_freeing(at: usize, len: usize) { + if STATS[0].load(Ordering::Relaxed) + STATS[2].load(Ordering::Relaxed) == 0 { + return; + } + let gone = crate::shadow::in_place_let_go(at as u64, len as u64); + STATS[7].fetch_add(gone, Ordering::Relaxed); +} + +/// The line of what is in place, every ten seconds while [`level`] is on. +fn say() { + static LAST: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms(); + let last = LAST.load(Ordering::Relaxed); + if now < last + 10_000 || LAST.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + let s: Vec = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); + tracing::info!( + "title memory in place: {} windows {} MB, {} title buffers {} MB (no copy, no refresh, no copy-back); turned down: {} view memory or not private memory committed whole, \ + {} refused by the host, {} over VICTORY_INPLACE_MB; {} let go because their memory changed", + s[0], + s[1] >> 20, + s[2], + s[3] >> 20, + s[4], + s[5], + s[6], + s[7] + ); +} + +/// What a heap is opened on. +pub(crate) enum From { + /// A whole `VirtualAlloc` allocation, by its base address. + Region(usize), + /// A committed part of one: address and bytes. + Part(usize, usize), + /// A section made with `SEC_COMMIT`, by its handle. + Section(usize), +} + +/// Opens a heap on memory the process has. +pub(crate) fn open(device: &ID3D12Device, from: From) -> windows::core::Result { + // SAFETY: the calls take an address or a handle and check both + // themselves; a refusal is an error code. + unsafe { + match from { + From::Region(at) => device.cast::()?.OpenExistingHeapFromAddress(at as *const c_void), + From::Part(at, bytes) => device.cast::()?.OpenExistingHeapFromAddress1(at as *const c_void, bytes), + From::Section(handle) => device.cast::()?.OpenExistingHeapFromFileMapping(HANDLE(handle as *mut c_void)), + } + } +} + +fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + } +} + +/// A buffer of `size` bytes at `offset` (a multiple of 64 KiB) of an +/// opened heap, which shaders may read and write, in the common state. +pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size: u64) -> windows::core::Result { + let mut placed: Option = None; + // The heap is cross-adapter shared, so the buffer must say so too. + let flags = D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + // SAFETY: plain creation in a live heap. + unsafe { device.CreatePlacedResource(heap, offset, &buffer_desc(size, flags), D3D12_RESOURCE_STATE_COMMON, None, &mut placed)? }; + placed.ok_or_else(windows::core::Error::empty) +} + +// The title's views of its physical pages, as the runtime maps them: the +// census needs them to say which view memory is one run of a section (one +// placed buffer could show it) and which is scattered pages. + +struct Views { + /// By address: bytes, the section's handle, the offset in it. + views: BTreeMap, + /// Sections by handle: bytes, and whether made committed. + sections: Vec<(usize, u64, bool)>, +} + +static VIEWS: Mutex = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new() }); + +fn views() -> std::sync::MutexGuard<'static, Views> { + VIEWS.lock().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(); + v.sections.retain(|s| s.0 != section); + v.sections.push((section, bytes, committed)); +} + +/// The runtime mapped `[at, at + len)` as a view of `section` from +/// `offset` on. Call after [`crate::title_memory_remapped`] of the range. +pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { + views().views.insert(at, (len, section, offset)); +} + +/// What `[at, at + len)` showed is gone ([`crate::title_memory_remapped`]): +/// 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(); + if v.views.is_empty() { + return; + } + let end = at.saturating_add(len); + let first = v.views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at).map(|(base, _)| *base); + let gone: Vec = first.into_iter().chain(v.views.range(at.saturating_add(1)..end).map(|(base, _)| *base)).collect(); + for base in gone { + v.views.remove(&base); + } +} + +/// How the views cover `[at, at + len)`. +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub(crate) enum Cover { + /// No view holds its first byte. + None, + /// Views hold a part of it only. + Holes, + /// Views hold all of it, from more than one place. + Scattered, + /// All of it is one run of one section: the section and the offset of + /// `at` in it. + Run(usize, u64), +} + +fn cover_in(views: &BTreeMap, at: usize, len: usize) -> Cover { + let end = at + len.max(1); + let Some((&base, &(bytes, section, offset))) = views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at) else { + return Cover::None; + }; + let first = (section, offset + (at - base) as u64); + let (mut reached, mut one) = (base + bytes, true); + while reached < end { + let Some(&(bytes, s, o)) = views.get(&reached) else { + return Cover::Holes; + }; + one &= s == first.0 && o == first.1 + (reached - at) as u64; + reached += bytes; + } + if one { Cover::Run(first.0, first.1) } else { Cover::Scattered } +} + +/// [`Cover`] of `[at, at + len)` by the title's views as they are now. +pub(crate) fn cover(at: usize, len: usize) -> Cover { + cover_in(&views().views, at, len) +} + +/// 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 +/// one's state: a millisecond in the title's big blocks, so ask when a +/// copy is made, not when it is used). +pub(crate) fn private_whole(at: usize, len: usize) -> bool { + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; + n != 0 + && info.State == mem::MEM_COMMIT + && info.Type == mem::MEM_PRIVATE + && info.Protect == mem::PAGE_READWRITE + && (info.BaseAddress as usize).saturating_add(info.RegionSize) >= at.saturating_add(len) +} + +fn hr(result: &windows::core::Result) -> String { + match result { + Ok(_) => "ok".to_owned(), + Err(e) => format!("REFUSED {:#010x} ({})", e.code().0, e.message().trim()), + } +} + +/// A queue, a list and a fence of the probe's own on `device`: nothing of +/// the host's submissions is touched. +struct Rig { + device: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + done: u64, + event: HANDLE, +} + +impl Drop for Rig { + fn drop(&mut self) { + // SAFETY: our event. + unsafe { + let _ = windows::Win32::Foundation::CloseHandle(self.event); + } + } +} + +impl Rig { + fn new(device: &ID3D12Device) -> windows::core::Result { + // SAFETY: plain creation of objects of our own. + unsafe { + let queue: ID3D12CommandQueue = + device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })?; + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.Close()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = CreateEventW(None, false, false, None)?; + Ok(Rig { device: device.clone(), queue, allocator, list, fence, done: 0, event }) + } + } + + /// Records with `record`, runs it and waits (ten seconds at most). + fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> windows::core::Result<()> { + // SAFETY: our own list and queue, one run at a time. + unsafe { + self.allocator.Reset()?; + self.list.Reset(&self.allocator, None)?; + record(&self.list); + self.list.Close()?; + self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]); + self.done += 1; + self.queue.Signal(&self.fence, self.done)?; + self.fence.SetEventOnCompletion(self.done, self.event)?; + if WaitForSingleObject(self.event, 10_000).0 != 0 { + return Err(windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL)); + } + self.device.GetDeviceRemovedReason() + } + } + + fn committed(&self, kind: D3D12_HEAP_TYPE, size: u64, state: D3D12_RESOURCE_STATES) -> windows::core::Result { + let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }; + let mut buffer: Option = None; + // SAFETY: plain creation. + unsafe { + self.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(size, D3D12_RESOURCE_FLAG_NONE), state, None, &mut buffer)? + }; + buffer.ok_or_else(windows::core::Error::empty) + } + + /// What the GPU reads of `size` bytes of `resource` from `offset`. + fn fetch(&mut self, resource: &ID3D12Resource, offset: u64, size: usize) -> windows::core::Result> { + let back = self.committed(D3D12_HEAP_TYPE_READBACK, size as u64, D3D12_RESOURCE_STATE_COPY_DEST)?; + // SAFETY: two live buffers, the range inside both. + self.run(|list| unsafe { list.CopyBufferRegion(&back, 0, resource, offset, size as u64) })?; + let mut data = std::ptr::null_mut(); + // SAFETY: the mapping holds `size` bytes until unmapped. + unsafe { + back.Map(0, None, Some(&mut data))?; + let bytes = std::slice::from_raw_parts(data.cast::(), size).to_vec(); + back.Unmap(0, None); + Ok(bytes) + } + } + + /// The GPU writes `bytes` at `offset` of `resource` (a copy). + fn store(&mut self, resource: &ID3D12Resource, offset: u64, bytes: &[u8]) -> windows::core::Result<()> { + let up = self.committed(D3D12_HEAP_TYPE_UPLOAD, bytes.len() as u64, D3D12_RESOURCE_STATE_GENERIC_READ)?; + let mut data = std::ptr::null_mut(); + // SAFETY: the mapping holds the buffer's bytes until unmapped. + unsafe { + up.Map(0, None, Some(&mut data))?; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), data.cast::(), bytes.len()); + up.Unmap(0, None); + } + // SAFETY: two live buffers, the range inside both. + self.run(|list| unsafe { list.CopyBufferRegion(resource, offset, &up, 0, bytes.len() as u64) }) + } + + /// A compute shader stores, through a root unordered-access view at + /// `gpu`, the sum of the buffer's first two words in its third. + fn shade(&mut self, gpu: u64) -> windows::core::Result<()> { + const SOURCE: &str = "#define RS \"UAV(u0)\"\nRWByteAddressBuffer b : register(u0);\n[RootSignature(RS)]\n[numthreads(1, 1, 1)]\nvoid main() { b.Store(8, b.Load(0) + b.Load(4)); }\n"; + let mut code: Option = None; + // SAFETY: the source and names live through the call; then the + // blob's own bytes, which hold the root signature too. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("inplace"), None, None, s!("main"), s!("cs_5_1"), 0, 0, &mut code, None)?; + let code = code.ok_or_else(windows::core::Error::empty)?; + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }, + ..Default::default() + })?; + (root, pso) + }; + // SAFETY: an open list of ours; the view names a live buffer. + self.run(|list| unsafe { + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, gpu); + list.Dispatch(1, 1, 1); + }) + } + + /// Milliseconds the card takes to copy `bytes` of `from` into its own + /// memory, the best of three. + fn copy_ms(&mut self, from: &ID3D12Resource, bytes: u64) -> windows::core::Result { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut to: Option = None; + // SAFETY: plain creation. + unsafe { + self.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_COMMON, None, &mut to)? + }; + let to = to.ok_or_else(windows::core::Error::empty)?; + let mut best = f64::MAX; + for _ in 0..3 { + let started = std::time::Instant::now(); + // SAFETY: two live buffers of `bytes` bytes or more. + self.run(|list| unsafe { list.CopyBufferRegion(&to, 0, from, 0, bytes) })?; + best = best.min(started.elapsed().as_secs_f64() * 1000.0); + } + Ok(best) + } +} + +fn fill(at: *mut u8, len: usize, seed: u8) { + for i in 0..len { + // SAFETY: the caller's own committed memory of `len` bytes. + unsafe { at.add(i).write((i as u8).wrapping_mul(31).wrapping_add(seed)) }; + } +} + +fn same(at: *const u8, bytes: &[u8]) -> bool { + // SAFETY: the caller's own committed memory of that length. + unsafe { std::slice::from_raw_parts(at, bytes.len()) == bytes } +} + +/// The process's working set in MB. +fn working_set_mb() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + let mut counters = PROCESS_MEMORY_COUNTERS { cb: size_of::() as u32, ..Default::default() }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut counters, counters.cb) }; + counters.WorkingSetSize as u64 >> 20 +} + +/// What the probe found. The lines are the whole account; the flags are +/// what the stages build on. +#[derive(Default)] +pub(crate) struct Probe { + pub(crate) lines: Vec, + /// A part of private, write-watched memory opens, a buffer in it shows + /// the memory's bytes to the GPU, also those the CPU wrote afterwards. + pub(crate) part_reads: bool, + /// What the GPU writes there (a copy, and a shader through unordered + /// access) the CPU reads at the memory's address. + pub(crate) part_writes: bool, + /// The same two for a committed section, through a view of it. + pub(crate) section_reads: bool, + pub(crate) section_writes: bool, + /// The section's heap outlives the view: the GPU's write with no view + /// mapped shows in a view mapped afterwards. + pub(crate) section_outlives_views: bool, + /// A section made with `SEC_RESERVE` (as `xmem` makes the page pool) + /// was refused. + pub(crate) reserved_section_refused: bool, +} + +/// Tries the openings on memory of the probe's own, made the way `xmem` +/// makes title memory, with a queue of its own on `device`; `memory` +/// gives the card's memory account (`Host::video_memory`) where there is +/// one. Nothing of the title's is touched. `mb` is the size of the cost +/// measurement (0 leaves it out). +pub(crate) fn probe(device: &ID3D12Device, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) -> Probe { + let mut p = Probe::default(); + let mut rig = match Rig::new(device) { + Ok(rig) => rig, + Err(e) => { + p.lines.push(format!("no queue of its own: {e}")); + return p; + } + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + // SAFETY: a plain query that fills our structure. + let _ = unsafe { device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, (&raw mut options).cast(), size_of_val(&options) as u32) }; + p.lines.push(format!( + "the device: ID3D12Device3 {}, ID3D12Device13 {} (parts of an allocation); cross-adapter row-major textures {}; heap tier {}", + device.cast::().is_ok(), + device.cast::().is_ok(), + options.CrossAdapterRowMajorTextureSupported.as_bool(), + options.ResourceHeapTier.0 + )); + // SAFETY: memory of the probe's own, made and released here; every + // address used lies inside it. + unsafe { + private(&mut p, &mut rig); + section(&mut p, &mut rig); + if mb > 0 { + cost(&mut p, &mut rig, memory, mb); + } + } + p.lines.push(format!( + "VERDICT: private memory in place: reads {}, writes {}; the page pool's section in place: reads {}, writes {}, whatever the views do {}; \ + a reserved section is refused {} (the pool must be made committed to be opened)", + p.part_reads, p.part_writes, p.section_reads, p.section_writes, p.section_outlives_views, p.reserved_section_refused + )); + p +} + +fn describe(heap: &ID3D12Heap) -> String { + // SAFETY: a plain query. + let d = unsafe { heap.GetDesc() }; + format!( + "heap of {} KiB: type {} (4 = custom), CPU pages {} (3 = write-back), pool {} (1 = the PC's memory), alignment {}, flags {:#x} (0x1 shared, 0x20 cross-adapter, 0x200 write watch, 0x400 shader atomics)", + d.SizeInBytes >> 10, + d.Properties.Type.0, + d.Properties.CPUPageProperty.0, + d.Properties.MemoryPoolPreference.0, + d.Alignment, + d.Flags.0 + ) +} + +/// Private memory, reserved as `xmem` reserves the title's heaps +/// (committed, read-write, write-watched): a part of it opened. +unsafe fn private(p: &mut Probe, rig: &mut Rig) { + const SIZE: usize = 64 * K64; + // SAFETY (the whole function): the allocation below, `SIZE` bytes. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::(); + if base.is_null() { + p.lines.push("private memory: none to try with".to_owned()); + return; + } + // The part: 16 pages from the 16th on. + let (at, bytes) = (base.add(16 * K64), 16 * K64); + let whole = open(&rig.device, From::Region(base as usize)); + p.lines.push(format!("private memory, the whole allocation (OpenExistingHeapFromAddress): {}", hr(&whole))); + drop(whole); + let opened = open(&rig.device, From::Part(at as usize, bytes)); + p.lines.push(format!("private memory, a part of it (OpenExistingHeapFromAddress1): {}", hr(&opened))); + if let Ok(heap) = &opened { + p.lines.push(format!(" {}", describe(heap))); + let placed = place(&rig.device, heap, K64 as u64, 4 * K64 as u64); + p.lines.push(format!(" a buffer placed in it (cross-adapter, unordered access): {}", hr(&placed))); + if let Ok(buffer) = &placed { + let memory = at.add(K64); + fill(memory, 4 * K64, 1); + let first = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); + fill(memory, 4 * K64, 77); + let second = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); + p.part_reads = first && second; + p.lines.push(format!(" the GPU reads the memory's bytes: {first}; and those the CPU wrote afterwards, with no call in between: {second}")); + mem::ResetWriteWatch(base.cast(), SIZE); + let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x5a).collect(); + let copied = rig.store(buffer, 4096, &new).is_ok() && same(memory.add(4096), &new); + let (mut found, mut count, mut granularity) = ([0usize; 64], 64usize, 0u32); + let watched = mem::GetWriteWatch(0, base.cast(), SIZE, found.as_mut_ptr().cast(), &mut count, &mut granularity) == 0; + memory.cast::<[u32; 3]>().write([40, 2, 0]); + let shaded = rig.shade(buffer.GetGPUVirtualAddress()); + let shader = shaded.is_ok() && memory.cast::<[u32; 3]>().read()[2] == 42; + p.part_writes = copied && shader; + p.lines.push(format!( + " the CPU reads at the memory's address what the GPU wrote: by a copy {copied}; by a shader through unordered access {shader} ({}); \ + write watching saw {} of the copy's 16 pages{}", + hr(&shaded), + if watched { count } else { 0 }, + if watched { "" } else { " (the asking failed)" } + )); + } + // What the title can still do with the pages while the heap stands. + let mut old = 0; + let protect_in = mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READONLY, &mut old) != 0; + if protect_in { + mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READWRITE, &mut old); + } + let decommit_in = mem::VirtualFree(at.add(9 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + let decommit_out = mem::VirtualFree(base.add(40 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + p.lines.push(format!( + " with the heap standing, the title's own calls: read-only inside the part {protect_in}, decommit inside {decommit_in}, decommit outside {decommit_out} \ + (false inside means the heap must go before the title frees or guards those pages)" + )); + drop(placed); + } + drop(opened); + let freed = mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE) != 0; + p.lines.push(format!(" released after the heap went: {freed}")); + } +} + +/// A section and a view of it in a placeholder, as `xmem` maps physical +/// pages: reserved (as it is made today) and committed. +unsafe fn section(p: &mut Probe, rig: &mut Rig) { + const SIZE: usize = 32 * K64; + // SAFETY (the whole function): the sections, placeholder and views + // made below. + unsafe { + let process = windows_sys::Win32::System::Threading::GetCurrentProcess(); + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let reserved = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_RESERVE, 0, SIZE as u32, std::ptr::null()); + if !reserved.is_null() { + let opened = open(&rig.device, From::Section(reserved as usize)); + p.reserved_section_refused = opened.is_err(); + p.lines.push(format!("a section made reserved, as the page pool is today (OpenExistingHeapFromFileMapping): {}", hr(&opened))); + drop(opened); + windows_sys::Win32::Foundation::CloseHandle(reserved); + } + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, 0, SIZE as u32, std::ptr::null()); + let hole = mem::VirtualAlloc2(process, std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_RESERVE_PLACEHOLDER, mem::PAGE_NOACCESS, std::ptr::null_mut(), 0).cast::(); + if handle.is_null() || hole.is_null() { + p.lines.push("a committed section: none to try with".to_owned()); + return; + } + // Pages 4..12 of the section at the placeholder's start. + mem::VirtualFree(hole.cast(), 8 * K64, mem::MEM_RELEASE | mem::MEM_PRESERVE_PLACEHOLDER); + let view = mem::MapViewOfFile3(handle, process, hole.cast(), (4 * K64) as u64, 8 * K64, mem::MEM_REPLACE_PLACEHOLDER, mem::PAGE_READWRITE, std::ptr::null_mut(), 0); + let opened = open(&rig.device, From::Section(handle as usize)); + p.lines.push(format!("a section made committed (OpenExistingHeapFromFileMapping): {}", hr(&opened))); + let mut unmapped = false; + if let (Ok(heap), false) = (&opened, view.Value.is_null()) { + p.lines.push(format!(" {}", describe(heap))); + // The section's page 5 is the view's second page. + let placed = place(&rig.device, heap, 5 * K64 as u64, 2 * K64 as u64); + p.lines.push(format!(" a buffer placed at the section's offset of a view's pages: {}", hr(&placed))); + if let Ok(buffer) = &placed { + let memory = hole.add(K64); + fill(memory, 2 * K64, 3); + p.section_reads = rig.fetch(buffer, 0, 2 * K64).is_ok_and(|got| same(memory, &got)); + let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x33).collect(); + p.section_writes = rig.store(buffer, 0, &new).is_ok() && same(memory, &new); + // The guard of `watch.rs`: the view read-only. + let mut old = 0; + let guarded = mem::VirtualProtect(memory.cast(), K64, mem::PAGE_READONLY, &mut old) != 0; + let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x44).collect(); + let through = rig.store(buffer, 0, &new).is_ok() && same(memory, &new); + // The view goes; the GPU writes; another view shows it. + unmapped = mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER) != 0; + let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x55).collect(); + let stored = rig.store(buffer, 0, &new).is_ok(); + let other = mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, (5 * K64) as u32, K64); + p.section_outlives_views = unmapped && stored && !other.Value.is_null() && same(other.Value.cast(), &new); + p.lines.push(format!( + " the GPU reads the view's bytes {}; the CPU reads through the view what the GPU wrote {}; the view made read-only under the heap {guarded}, \ + and the GPU writes it all the same {through}; the view unmapped under the heap {unmapped}, the GPU's write then shows in a view mapped afterwards {}", + p.section_reads, p.section_writes, p.section_outlives_views + )); + if !other.Value.is_null() { + mem::UnmapViewOfFile(other); + } + } + } + drop(opened); + if !unmapped && !view.Value.is_null() { + mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER); + } + windows_sys::Win32::Foundation::CloseHandle(handle); + // The placeholder was split in two: each half is released. + mem::VirtualFree(hole.cast(), 0, mem::MEM_RELEASE); + mem::VirtualFree(hole.add(8 * K64).cast(), 0, mem::MEM_RELEASE); + } +} + +/// What opening costs, on `mb` MB each of private memory never touched +/// and of a committed section never touched: the time, the working set, +/// the card's account of the PC's memory shared with it; and how fast the +/// card copies out of such a heap against a shared buffer of today's kind. +unsafe fn cost(p: &mut Probe, rig: &mut Rig, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) { + let bytes = mb << 20; + let shared = || memory().map_or(0, |m| m[3] >> 20); + let ms = |speed: Option| speed.map_or("?".to_owned(), |ms| format!("{ms:.1}")); + // SAFETY (the whole function): the allocation and the section below. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), bytes, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::(); + if !base.is_null() { + let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now()); + let opened = open(&rig.device, From::Part(base as usize, bytes)); + let took = started.elapsed().as_secs_f64() * 1000.0; + let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok()); + let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok()); + p.lines.push(format!( + "cost, {mb} MB of private memory never touched: {}; opened in {took:.1} ms; working set {set} -> {} MB; shared with the card {account} -> {} MB; \ + the card copies it out in {} ms", + hr(&opened), + working_set_mb(), + shared(), + ms(speed) + )); + drop((placed, opened)); + mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + } + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, (bytes as u64 >> 32) as u32, bytes as u32, std::ptr::null()); + if !handle.is_null() { + let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now()); + let opened = open(&rig.device, From::Section(handle as usize)); + let took = started.elapsed().as_secs_f64() * 1000.0; + let (set_opened, account_opened) = (working_set_mb(), shared()); + let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok()); + let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok()); + p.lines.push(format!( + "cost, {mb} MB of a committed section never touched: {}; opened in {took:.1} ms; working set {set} -> {set_opened} -> after the card read all of it {} MB; \ + shared with the card {account} -> {account_opened} -> {} MB; the card copies it out in {} ms", + hr(&opened), + working_set_mb(), + shared(), + ms(speed) + )); + drop((placed, opened)); + windows_sys::Win32::Foundation::CloseHandle(handle); + } + // Today's kind of host copy, for the comparison. + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let mut buffer: Option = None; + let made = rig.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &buffer_desc(bytes as u64, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ); + if let (Ok(()), Some(buffer)) = (made, buffer) { + let speed = rig.copy_ms(&buffer, bytes as u64).ok(); + p.lines.push(format!("cost, for comparison: the card copies {mb} MB out of a shared buffer of today's kind in {} ms", ms(speed))); + } + } +} + +// The census: which of the title memory that has host copies today could +// be opened, and by which opening. + +/// Counts and bytes by kind, in the order of [`KINDS`]. +#[derive(Default, Clone, Copy)] +struct Tally([(u64, u64); 6]); + +const KINDS: [&str; 6] = [ + "private, committed whole (a part can be opened)", + "view memory, one run of a section (one placed buffer)", + "view memory, scattered pages", + "view memory with unmapped pages", + "private but not committed whole, or guarded", + "other", +]; + +fn kind_of(at: usize, len: usize, known: &mut Vec<(usize, usize)>) -> usize { + match cover(at, len) { + Cover::Run(..) => return 1, + Cover::Scattered => return 2, + Cover::Holes => return 3, + Cover::None => {} + } + let end = at + len; + if known.iter().any(|&(from, to)| from <= at && end <= to) { + return 0; + } + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; + if n == 0 { + return 5; + } + let reach = (info.BaseAddress as usize).saturating_add(info.RegionSize); + if info.Type == mem::MEM_PRIVATE && info.State == mem::MEM_COMMIT && info.Protect == mem::PAGE_READWRITE { + known.push((info.BaseAddress as usize, reach)); + return if reach >= end { 0 } else { 4 }; + } + match info.Type { + mem::MEM_PRIVATE => 4, + mem::MEM_MAPPED => 3, + _ => 5, + } +} + +/// The census lines for `spans` (start, bytes, whether a window outside +/// buffers). +fn census_of(spans: &[(u64, u64, bool)]) -> Vec { + let mut known = Vec::new(); + let (mut buffers, mut windows) = (Tally::default(), Tally::default()); + for &(start, len, window) in spans { + let kind = kind_of(start as usize, len as usize, &mut known); + let tally = if window { &mut windows } else { &mut buffers }; + tally.0[kind].0 += 1; + tally.0[kind].1 += len; + } + let mut lines = Vec::new(); + for (name, tally) in [("title buffers", buffers), ("windows outside buffers", windows)] { + let all = tally.0.iter().fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1)); + lines.push(format!("census, {name}: {} of {} MB", all.0, all.1 >> 20)); + for (kind, &(n, bytes)) in KINDS.iter().zip(&tally.0) { + if n > 0 { + lines.push(format!("census, {kind}: {n} of {} MB", bytes >> 20)); + } + } + } + let v = views(); + let (count, bytes) = (v.views.len(), v.views.values().map(|view| view.0 as u64).sum::()); + let pages = v.views.values().filter(|view| view.0 == K64).count(); + let big = v.views.values().map(|view| view.0).max().unwrap_or(0); + lines.push(format!( + "census, the title's views of physical pages: {count} of {} MB; {pages} of them one 64 KiB page; the longest {} MB", + bytes >> 20, + big >> 20 + )); + for &(_, bytes, committed) in &v.sections { + lines.push(format!( + "census, a section of {} MB, {}", + bytes >> 20, + if committed { "committed: it can be opened as one heap" } else { "reserved: refused as a heap until it is made with SEC_COMMIT" } + )); + } + lines +} + +/// With [`probe_level`] 2: one part of the title's own private memory +/// (the start of the biggest such title buffer, 4 MiB at most) is opened +/// for a moment, a buffer placed, 64 KiB read by the GPU and compared +/// with what the CPU reads there (the title may be writing it meanwhile: +/// the count of equal bytes is given), and all of it released. While the +/// heap stands (milliseconds) a `VirtualFree` of the title's on those +/// pages would fail. +fn real_part(spans: &[(u64, u64, bool)]) -> Vec { + let Some(host) = crate::host::host() else { + return Vec::new(); + }; + let mut known = Vec::new(); + let found = spans + .iter() + .filter(|s| !s.2 && s.1 >= 2 * K64 as u64) + .filter(|s| kind_of(s.0 as usize, s.1 as usize, &mut known) == 0) + .max_by_key(|s| s.1); + let Some(&(start, len, _)) = found else { + return vec!["the title's memory: no title buffer in private, committed memory to try".to_owned()]; + }; + let at = (start as usize).next_multiple_of(K64); + let bytes = ((start + len) as usize).saturating_sub(at).min(4 << 20) & !(K64 - 1); + if bytes == 0 || !private_whole(at, bytes) { + return vec!["the title's memory: the buffer found holds no whole 64 KiB page that is still committed".to_owned()]; + } + let mut lines = Vec::new(); + let (set, started) = (working_set_mb(), std::time::Instant::now()); + let opened = open(&host.device, From::Part(at, bytes)); + lines.push(format!( + "the title's memory, {} KiB at {at:#x} (of the title buffer {start:#x}+{len:#x}): {}; in {:.1} ms; working set {set} -> {} MB", + bytes >> 10, + hr(&opened), + started.elapsed().as_secs_f64() * 1000.0, + working_set_mb() + )); + if let Ok(heap) = &opened { + let placed = place(&host.device, heap, 0, bytes as u64); + lines.push(format!(" a buffer placed over it: {}", hr(&placed))); + if let (Ok(buffer), Ok(mut rig)) = (&placed, Rig::new(&host.device)) { + let mut before = vec![0u8; K64]; + crate::host::copy_mapped(before.as_mut_ptr(), at as *const u8, K64, false); + let got = rig.fetch(buffer, 0, K64); + let mut after = vec![0u8; K64]; + crate::host::copy_mapped(after.as_mut_ptr(), at as *const u8, K64, false); + match got { + Ok(got) => { + let equal = (0..K64).filter(|&i| got[i] == before[i] || got[i] == after[i]).count(); + let zeros = got.iter().filter(|&&b| b == 0).count(); + lines.push(format!( + " the GPU read 64 KiB of the title's own bytes: {equal} of {K64} equal to what the CPU read just before or just after ({zeros} of them zero)" + )); + } + Err(e) => lines.push(format!(" the GPU's read failed: {e}")), + } + } + } + lines +} + +/// Called once a second by the thread that submits, before a submission +/// (`host::sweep`): with [`probe_level`], the probe at the first call, the +/// census (on a thread of its own: it asks Windows about every copy) 30 +/// and 150 seconds later. +pub(crate) fn tick() { + if level() > 0 { + say(); + } + if probe_level() == 0 { + return; + } + static STARTED: AtomicU64 = AtomicU64::new(0); + static DONE: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms().max(1); + let started = match STARTED.compare_exchange(0, now, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => { + let Some(host) = crate::host::host() else { + return; + }; + let mb = std::env::var("VICTORY_INPLACE_PROBE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64usize); + let took = std::time::Instant::now(); + let probe = probe(&host.device, &|| host.video_memory(), mb.min(1024)); + for line in &probe.lines { + tracing::info!("in place probe: {line}"); + } + tracing::info!("in place probe: took {:.0} ms", took.elapsed().as_secs_f64() * 1000.0); + now + } + Err(started) => started, + }; + let due = match DONE.load(Ordering::Relaxed) { + 0 => now >= started + 30_000, + 1 => now >= started + 150_000, + _ => false, + }; + if due { + let which = DONE.fetch_add(1, Ordering::Relaxed); + std::thread::spawn(move || { + let spans = crate::shadow::spans(); + for line in census_of(&spans) { + tracing::info!("in place {line}"); + } + if which == 0 && probe_level() >= 2 { + for line in real_part(&spans) { + tracing::info!("in place probe: {line}"); + } + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Views as the runtime tells them: a range inside one view, or over + /// views that continue each other in one section, is one run; over + /// views from elsewhere it is scattered; over a gap it has holes. + #[test] + fn views_say_what_one_placed_buffer_could_show() { + let mut views = BTreeMap::new(); + let at = 0x7_0000_0000usize; + views.insert(at, (4 * K64, 9, 16 * K64 as u64)); + // Continues the first in the section. + views.insert(at + 4 * K64, (2 * K64, 9, 20 * K64 as u64)); + // Follows in address, from elsewhere in the section. + views.insert(at + 6 * K64, (K64, 9, 3 * K64 as u64)); + // After a gap of one page. + views.insert(at + 8 * K64, (K64, 9, 4 * K64 as u64)); + assert_eq!(cover_in(&views, at + K64, 2 * K64), Cover::Run(9, 17 * K64 as u64)); + assert_eq!(cover_in(&views, at + K64, 5 * K64), Cover::Run(9, 17 * K64 as u64)); + assert_eq!(cover_in(&views, at, 7 * K64), Cover::Scattered); + assert_eq!(cover_in(&views, at + 6 * K64, 3 * K64), Cover::Holes); + assert_eq!(cover_in(&views, at + 7 * K64, K64), Cover::None); + assert_eq!(cover_in(&views, at - K64, 2 * K64), Cover::None); + } + + /// What the runtime forgets when memory is mapped anew. + #[test] + fn remapped_memory_forgets_its_views() { + let at = 0x7_4000_0000usize; + title_memory_view(at, 4 * K64, 77, 0); + title_memory_view(at + 4 * K64, K64, 77, 4 * K64 as u64); + assert_eq!(cover(at, 5 * K64), Cover::Run(77, 0)); + // One page inside the first view goes: the whole view is forgotten + // (the runtime maps and tells again what stays of it). + views_gone(at + K64, K64); + assert_eq!(cover(at, K64), Cover::None); + assert_eq!(cover(at + 4 * K64, K64), Cover::Run(77, 4 * K64 as u64)); + views_gone(at + 4 * K64, K64); + assert_eq!(cover(at + 4 * K64, K64), Cover::None); + } + + /// Only private memory committed whole, read-write, is taken for a part. + #[test] + fn only_private_memory_committed_whole_is_a_part() { + // SAFETY: an allocation of the test's own. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE, mem::PAGE_NOACCESS).cast::(); + assert!(!base.is_null()); + assert!(!private_whole(base as usize, K64), "reserved only"); + mem::VirtualAlloc(base.cast(), 4 * K64, mem::MEM_COMMIT, mem::PAGE_READWRITE); + assert!(private_whole(base as usize, 4 * K64)); + assert!(private_whole(base as usize + K64, 2 * K64)); + assert!(!private_whole(base as usize, 5 * K64), "reaches into the reserved half"); + let mut old = 0; + mem::VirtualProtect(base.cast(), K64, mem::PAGE_READONLY, &mut old); + assert!(!private_whole(base as usize, 2 * K64), "a guarded page"); + mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + } + } + + pub(crate) fn warp() -> Option { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::*; + // SAFETY: plain DXGI queries and device creation on the software + // adapter; a card is never opened. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let desc = adapter.cast::().ok()?.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return None; + } + let mut device: Option = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + device + } + } + + /// The probe, whole, on the software adapter: the same calls the card + /// gets. The runtime's and the kernel's rules hold there; the card's + /// driver is what a run with `VICTORY_INPLACE_PROBE=1` adds. + #[test] + fn warp_probe_opens_title_like_memory_and_the_gpu_sees_its_bytes() { + let Some(device) = warp() else { return }; + if device.cast::().is_err() { + eprintln!("no ID3D12Device13 here: parts of an allocation cannot be opened"); + return; + } + let probe = probe(&device, &|| None, 4); + for line in &probe.lines { + eprintln!("in place probe: {line}"); + } + assert!(probe.part_reads, "the GPU reads private memory in place"); + assert!(probe.part_writes, "GPU writes land in private memory"); + assert!(probe.section_reads && probe.section_writes, "a committed section in place"); + assert!(probe.section_outlives_views, "the section's heap does not depend on views"); + assert!(probe.reserved_section_refused, "a reserved section is refused"); + } + + /// Stage 1's own call on the software adapter: a title buffer that + /// begins and ends off the 64 KiB lines is placed over its pages, the + /// GPU reads the buffer's bytes at the offset the views use, and its + /// write lands at the title's address. Memory that is not committed + /// whole is turned down without asking the host. + #[test] + fn warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset() { + let Some(device) = warp() else { return }; + if device.cast::().is_err() { + return; + } + // SAFETY: an allocation of the test's own. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::(); + let (start, len) = (base as u64 + K64 as u64 + 0x1230, 2 * K64 as u64 + 5); + let placed = place_part(&device, start, len).unwrap_or_else(|e| panic!("not placed: {e:?}")); + assert_eq!(placed.bias, 0x1230); + assert_eq!(placed.gpu, placed.buffer.GetGPUVirtualAddress() + 0x1230); + assert_eq!(placed.buffer.GetDesc().Width, 3 * K64 as u64, "the pages that hold the buffer"); + let mut rig = Rig::new(&device).unwrap(); + fill(start as *mut u8, len as usize, 7); + let got = rig.fetch(&placed.buffer, placed.bias, len as usize).unwrap(); + assert!(same(start as *const u8, &got), "the GPU reads the title buffer's bytes"); + rig.store(&placed.buffer, placed.bias + 16, &[0xa5; 64]).unwrap(); + assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address"); + drop(placed); + // Half of it decommitted: turned down, the host not asked. + assert_ne!(mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT), 0); + assert!(matches!(place_part(&device, start, len), Err(None))); + mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + } + } + + /// The census names each kind of memory. + #[test] + fn census_tells_private_memory_from_views() { + // SAFETY: an allocation of the test's own. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as u64; + let view = 0x7_8000_0000u64; + title_memory_view(view as usize, 2 * K64, 5, 0); + title_memory_view(view as usize + 2 * K64, K64, 5, 9 * K64 as u64); + let lines = census_of(&[(base, 2 * K64 as u64, false), (base + 4 * K64 as u64, K64 as u64, true), (view, K64 as u64, true), (view, 3 * K64 as u64, false)]); + let text = lines.join("\n"); + assert!(text.contains("census, title buffers: 2 of"), "{text}"); + assert!(text.contains("census, private, committed whole (a part can be opened): 1 of"), "{text}"); + assert!(text.contains("census, view memory, scattered pages: 1 of"), "{text}"); + assert!(text.contains("census, view memory, one run of a section (one placed buffer): 1 of"), "{text}"); + views_gone(view as usize, 3 * K64); + mem::VirtualFree(base as *mut c_void, 0, mem::MEM_RELEASE); + } + } +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index f91782d..db53f11 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -31,6 +31,8 @@ pub mod frame; mod host; #[cfg(windows)] mod indirect; +#[cfg(windows)] +mod inplace; pub mod list; pub mod object; pub mod pipeline; @@ -45,6 +47,8 @@ mod sampler; #[cfg(windows)] pub mod shader_cache; #[cfg(windows)] +mod memory; +#[cfg(windows)] mod shadow; pub mod signature; #[cfg(windows)] @@ -55,4 +59,8 @@ mod watch; #[cfg(windows)] pub use host::on_failure; #[cfg(windows)] -pub use watch::{title_memory_remapped, writing as kernel_will_write}; +pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; +#[cfg(windows)] +pub use watch::{ + title_memory_reading, title_memory_remapped, title_memory_remapping, writing as kernel_will_write, +}; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 7adb4e4..f5bf7b9 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -119,6 +119,22 @@ struct List { host: Option, #[cfg(windows)] state: std::sync::Mutex, + /// The parts of the recording before `host`, in order, each closed: the + /// list is cut at its waits for memory values ([`cut`]). + #[cfg(windows)] + earlier: Vec, + /// The waits recorded before the first work of `host`: the queue stands + /// at them before it runs `host`. + #[cfg(windows)] + gate: Vec, +} + +/// One part of a title list cut at its waits: the waits the queue stands +/// at, then the host list that runs once they are met. +#[cfg(windows)] +struct Part { + waits: Vec, + host: crate::host::HostList, } const _: () = assert!(offset_of!(List, put) == 0x18); const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560); @@ -128,9 +144,30 @@ const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560); #[cfg(windows)] fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::draw::State)) { let Some(list) = host_list(this) else { return }; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); // SAFETY: the title passes one of our lists. let state = unsafe { &(*this.cast::()).state }; f(list, &mut state.lock().unwrap_or_else(|e| e.into_inner())); + #[cfg(feature = "diagnostics")] + crate::copystat::recorded(started); +} + +/// The submission of `lists` has run: each gives its descriptor tables' +/// slots back ([`crate::draw::State::tables_done`]). A list cut at waits +/// keeps them: its state goes with its last part. +#[cfg(windows)] +pub(crate) fn tables_done(lists: &[This]) { + for &this in lists { + if this.is_null() { + continue; + } + // SAFETY: the title passes our lists. + let list = unsafe { &*this.cast::() }; + if list.earlier.is_empty() { + list.state.lock().unwrap_or_else(|e| e.into_inner()).tables_done(); + } + } } /// The host list behind a title list, if there is a host GPU. @@ -143,6 +180,317 @@ pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> { unsafe { (*this.cast::()).host.as_ref() } } +/// The host side of a submitted list, taken from it: a queue that waits +/// for a fence runs it later, and the title may reset the list meanwhile. +/// With it go the upload memory and the dynamic descriptor slots its +/// commands name, kept until it has run. +#[cfg(windows)] +pub(crate) struct Detached { + host: crate::host::HostList, + _uploads: Vec>, + _state: crate::draw::State, +} + +#[cfg(windows)] +impl Detached { + pub(crate) fn host(&self) -> &crate::host::HostList { + &self.host + } +} + +/// A host list that has run and waits to be used again, and the bytes of +/// upload memory it keeps. +#[cfg(windows)] +struct Idle(crate::host::HostList, u64); + +// SAFETY: D3D12 objects are free-threaded, and an idle list is touched by +// nobody until it is taken out again. +#[cfg(windows)] +unsafe impl Send for Idle {} + +/// Host lists that have run, reset and ready to record: the host side of +/// a list a queue held, or of a part of a list cut at a wait, is taken +/// from the title's list at its submission, and the title's list needs +/// another. Each was made new and thrown away after its run: a hundred a +/// frame in gameplay, each two command allocators and two lists, and for +/// four in ten a budget and an argument buffer (run 61: "104 host lists +/// made 21.2 ms" a frame, and the graphics kernel's time to free them). +#[cfg(windows)] +static IDLE: std::sync::Mutex<(Vec, u64)> = std::sync::Mutex::new((Vec::new(), 0)); + +/// The most host lists kept idle, and the most upload memory they may keep +/// between them (a list keeps scratch chunks over a reset only while lists +/// do not share them, `VICTORY_SCRATCH_POOL=0`). +#[cfg(windows)] +const IDLE_MOST: (usize, u64) = (128, 256 << 20); + +/// Whether host lists that have run are used again (on by default; +/// `VICTORY_LIST_POOL=0`: each is made new and thrown away, as before). +#[cfg(windows)] +fn pools() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LIST_POOL").is_none_or(|v| v != "0")) +} + +/// A host list open for recording: one that has run, as a title's list is +/// after its reset, or a new one. +#[cfg(windows)] +fn fresh_list() -> Option { + let idle = { + let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + let taken = idle.0.pop(); + if let Some(Idle(_, bytes)) = &taken { + idle.1 -= bytes; + } + taken + }; + match idle { + Some(Idle(list, _)) => Some(list), + None => crate::host::host().and_then(|h| h.new_list().ok()), + } +} + +/// The host sides of lists whose submission has run (submissions are +/// waited for; `ran` names the ones it ran, by their place in `lists`): +/// what they held is let go, as before, and the host lists are reset and +/// kept for [`fresh_list`]. +#[cfg(windows)] +pub(crate) fn recycle(lists: Vec, ran: &[usize]) { + if !pools() { + return; + } + for (i, Detached { host, _uploads, _state }) in lists.into_iter().enumerate() { + // The descriptor slots and the upload memory its commands named. + drop(_state); + drop(_uploads); + if !ran.contains(&i) || IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= IDLE_MOST.0 { + continue; + } + // As the title's reset does: what the list kept for its commands + // goes, its allocators stay. + host.reset(); + let bytes = host.scratch_kept(); + let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + if idle.0.len() < IDLE_MOST.0 && idle.1 + bytes <= IDLE_MOST.1 { + idle.0.push(Idle(host, bytes)); + idle.1 += bytes; + } + } +} + +/// A wait for a memory value recorded into list `this`, with waits cut +/// into lists (`crate::queue::cuts`). On the console the queue runs the +/// list up to the wait, stands there until the value is in memory, and +/// runs on; the list's bottom-of-pipe writes before the wait are done by +/// then, and other queues may be waiting for exactly those. So the +/// recording is cut here: the host list so far is closed and kept as a +/// part of its own ([`Part`]), the title's calls record into a new host +/// list from here on, and the wait stands before that one. A submission +/// then gives the queue the parts in order ([`detach_parts`]). +/// +/// A wait before any work (the first call after a reset, or a wait right +/// after another) cuts nothing: it joins the waits before the current +/// host list. +/// shortcut: a bottom-of-pipe write is done when its part has run, not at +/// its place in the part: a queue waiting for it starts later than on the +/// console, never earlier, and nothing can wait for itself that way (a +/// part has no wait after its first work). +#[cfg(windows)] +fn cut(this: This, wait: ValueWait) { + if this.is_null() { + return; + } + // SAFETY: the title passes one of our lists; a list is recorded by one + // thread at a time and is not submitted while it records. + let list = unsafe { &mut *this.cast_mut().cast::() }; + let Some(current) = list.host.as_ref() else { + return; + }; + if current.untouched() { + list.gate.push(wait); + return; + } + let Some(fresh) = fresh_list() else { + // shortcut: without a new host list the wait stands before the part + // it was recorded in. + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("no host list for the part after a wait: the wait moves to the part's start")); + list.gate.push(wait); + return; + }; + current.close(); + static CUTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if CUTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + tracing::info!(parts = list.earlier.len() + 2, "a list is cut at a wait for a memory value"); + } + if let Some(done) = list.host.replace(fresh) { + let waits = std::mem::replace(&mut list.gate, vec![wait]); + list.earlier.push(Part { waits, host: done }); + } + // What the title set so far, on the new host list. + if let Some(host) = list.host.as_ref() { + list.state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .replay(host); + } +} + +/// Whether list `this` recorded a wait for a memory value (with waits cut +/// into lists). +#[cfg(windows)] +pub(crate) fn cut_list(this: This) -> bool { + if this.is_null() { + return false; + } + // SAFETY: one of our lists, closed and submitted: nothing records + // into it. + let list = unsafe { &*this.cast::() }; + !list.earlier.is_empty() || !list.gate.is_empty() +} + +/// What a queue is given for submitted lists that were cut at their waits: +/// the waits it stands at, the host lists it runs once they are met, and +/// the order those run in. +#[cfg(windows)] +pub(crate) type Parts = Vec<(Vec, Vec, Vec)>; + +/// Takes the host sides of the submitted `lists`, part by part ([`cut`]), +/// and leaves each list a new, closed host list for its next reset, as +/// [`detach`] does. What comes back is in the order the queue runs it: a +/// new entry starts at every part that has waits; host lists without +/// waits join the entry before them. The list's upload memory and draw +/// state (its dynamic descriptor slots) go with its last part, which runs +/// last. +/// shortcut: a list the submission names a second time runs again only if +/// it has one part and that part is in the entry being filled; otherwise +/// the second naming is dropped (logged once). +#[cfg(windows)] +pub(crate) fn detach_parts(lists: &[This]) -> Parts { + let mut parts: Parts = vec![(Vec::new(), Vec::new(), Vec::new())]; + // The lists taken: where its one host list is (entry, place), or none + // for a list of several parts. + let mut seen: Vec<(This, Option<(usize, usize)>)> = Vec::new(); + for &this in lists { + if this.is_null() { + continue; + } + if let Some(&(_, at)) = seen.iter().find(|(t, _)| *t == this) { + match at { + Some((entry, place)) if entry + 1 == parts.len() => parts[entry].2.push(place), + _ => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!("a list named twice by a submission that waits for memory values runs once") + }); + } + } + continue; + } + let Some(fresh) = fresh_list() else { + continue; + }; + // A new host list is open; the title's next call on its list is a + // reset, which wants it closed. + fresh.close(); + // SAFETY: one of our lists, closed and submitted: nothing records + // into it until the title resets it. + let list = unsafe { &mut *this.cast_mut().cast::() }; + let Some(host) = list.host.replace(fresh) else { + continue; + }; + let earlier = std::mem::take(&mut list.earlier); + let gate = std::mem::take(&mut list.gate); + let uploads = std::mem::take(&mut *list.uploads.lock().unwrap_or_else(|e| e.into_inner())); + let state = std::mem::take(&mut *list.state.lock().unwrap_or_else(|e| e.into_inner())); + let single = earlier.is_empty() && gate.is_empty(); + let mut pieces: Vec<(Vec, Detached)> = earlier + .into_iter() + .map(|part| { + ( + part.waits, + Detached { + host: part.host, + _uploads: Vec::new(), + _state: Default::default(), + }, + ) + }) + .collect(); + pieces.push(( + gate, + Detached { + host, + _uploads: uploads, + _state: state, + }, + )); + let mut last = None; + for (waits, detached) in pieces { + if !waits.is_empty() { + parts.push((waits, Vec::new(), Vec::new())); + } + let entry = parts.len() - 1; + let (_, taken, order) = &mut parts[entry]; + let place = taken.len(); + order.push(place); + taken.push(detached); + last = Some((entry, place)); + } + seen.push((this, if single { last } else { None })); + } + // (The first entry is empty if the first list begins with a wait.) + parts.retain(|(_, taken, _)| !taken.is_empty()); + parts +} + +/// Takes the host sides of submitted lists (each once, however often the +/// submission names it) and leaves each list a new, closed host list for +/// its next reset: what was taken, and which of them run in what order. +#[cfg(windows)] +pub(crate) fn detach(lists: &[This]) -> (Vec, Vec) { + let mut taken: Vec<(This, Detached)> = Vec::new(); + let mut order = Vec::new(); + for &this in lists { + if this.is_null() { + continue; + } + if let Some(i) = taken.iter().position(|(t, _)| *t == this) { + order.push(i); + continue; + } + let Some(fresh) = fresh_list() else { + continue; + }; + // A new host list is open; the title's next call on its list is a + // reset, which wants it closed. + fresh.close(); + let list = this.cast_mut().cast::(); + // SAFETY: one of our lists, closed and submitted: nothing records + // into it until the title resets it. + let (host, uploads, state) = unsafe { + let Some(host) = (*list).host.replace(fresh) else { + continue; + }; + let uploads = + std::mem::take(&mut *(*list).uploads.lock().unwrap_or_else(|e| e.into_inner())); + let state = + std::mem::take(&mut *(*list).state.lock().unwrap_or_else(|e| e.into_inner())); + (host, uploads, state) + }; + order.push(taken.len()); + taken.push(( + this, + Detached { + host, + _uploads: uploads, + _state: state, + }, + )); + } + (taken.into_iter().map(|(_, d)| d).collect(), order) +} + pub(crate) extern "system" fn create_allocator( _: This, kind: u32, @@ -162,11 +510,11 @@ pub(crate) extern "system" fn create_list( _nodes: u32, kind: u32, allocator: This, - _pipeline: This, + pipeline: This, iid: *const Iid, out: *mut This, ) -> HRESULT { - new_list(kind, allocator, iid, out) + new_list(kind, allocator, pipeline, iid, out) } /// The console's list creation: type, flags, node mask and barrier batch @@ -184,7 +532,7 @@ pub(crate) extern "system" fn create_list_x( _: This, desc: *const ListDesc, allocator: This, - _pipeline: This, + pipeline: This, iid: *const Iid, out: *mut This, ) -> HRESULT { @@ -193,10 +541,18 @@ pub(crate) extern "system" fn create_list_x( return E_INVALIDARG; }; tracing::debug!(?desc, "console command list"); - new_list(desc.kind, allocator, iid, out) + new_list(desc.kind, allocator, pipeline, iid, out) } -fn new_list(kind: u32, allocator: This, iid: *const Iid, out: *mut This) -> HRESULT { +/// `pipeline` is the list's initial pipeline (null: none), bound until the +/// title sets another, as after a reset. +fn new_list( + kind: u32, + allocator: This, + pipeline: This, + iid: *const Iid, + out: *mut This, +) -> HRESULT { if allocator.is_null() { return E_INVALIDARG; } @@ -224,8 +580,18 @@ fn new_list(kind: u32, allocator: This, iid: *const Iid, out: *mut This) -> HRES } }), #[cfg(windows)] - state: Default::default(), + state: { + let mut state = crate::draw::State::default(); + state.set_pipeline(pipeline); + std::sync::Mutex::new(state) + }, + #[cfg(windows)] + earlier: Vec::new(), + #[cfg(windows)] + gate: Vec::new(), }); + #[cfg(not(windows))] + let _ = pipeline; object::hand_out(LIST, list, iid, &LIST_IIDS, out) } @@ -262,10 +628,25 @@ extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT if allocator.is_null() { return E_INVALIDARG; } + // A wait recorded and never submitted goes with the recording. + VALUE_WAITS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|&(list, _)| list != this as usize); // Every submission of the list has run (submissions are waited for). // SAFETY: the title passes one of our lists. let uploads = unsafe { &(*this.cast::()).uploads }; uploads.lock().unwrap_or_else(|e| e.into_inner()).clear(); + // The parts of a recording that was cut and never submitted go with it + // (a submission takes the parts it runs). + #[cfg(windows)] + { + // SAFETY: the title passes one of our lists, and neither records + // into it nor submits it during its reset. + let list = unsafe { &mut *this.cast_mut().cast::() }; + list.earlier.clear(); + list.gate.clear(); + } #[cfg(windows)] with_state(this, |host, state| { host.reset(); @@ -331,7 +712,13 @@ fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option { first: if b.first.is_null() { b.first } else { - host(b.first)? + // A depth texture's unordered access is its colour twin's + // (the host gives the depth texture none): the barrier is + // on the texture shaders write. + match crate::resource::twin_resource(b.first) { + Some(twin) => twin.as_raw().cast_const().cast(), + None => host(b.first)?, + } }, ..*b }), @@ -367,6 +754,8 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some() }) { host.push(UAV_BARRIER); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::WaitsForBuffers, 1); } if !host.is_empty() { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; @@ -436,6 +825,21 @@ extern "system" fn copy_buffer_region( let _ = (this, dst, dst_offset, src, src_offset, len); } +/// Whether one of two resources is a target in a stand-in format and the +/// other is not ([`crate::resource::target_format`]): their texels differ +/// in size, so the host cannot copy between them (logged once). +#[cfg(windows)] +fn unlike(dst: This, src: This) -> bool { + let unlike = crate::resource::stands_in(dst) != crate::resource::stands_in(src); + if unlike { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(?dst, ?src, "copy between a stand-in target and title-format texels skipped") + }); + } + unlike +} + extern "system" fn copy_resource(this: This, dst: This, src: This) { #[cfg(windows)] { @@ -446,9 +850,17 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { crate::resource::host_resource(dst), crate::resource::host_resource(src), ) { + if unlike(dst, src) { + return; + } + // A source the title fills itself is uploaded first (upstream + // PR #671): a copy read whatever the host texture held. if crate::texture::title_written(from) { crate::texture::upload(list, src, from); } + // Depth textures shaders also write: what they wrote, first. + list.twin_use(dst, false, true); + list.twin_use(src, false, false); ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); crate::texture::host_written(dst); @@ -507,10 +919,42 @@ extern "system" fn copy_texture_region( return; }; let Some(to) = crate::resource::host_resource(dst.resource) else { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!("texture to buffer copies not implemented")); + // Texture to buffer: a read back. The list copies the texels + // into a host buffer of ours; once it has run they go to the + // title's buffer (`HostList::defer_read_back`). Grand Theft + // Auto VI reads two tiny float targets back every frame (5x1 + // and 1x1 RGBA32F, 80 and 16 bytes: run 90), and read a buffer + // nobody wrote. `VICTORY_READ_BACK=0` leaves them unmade, as + // before. + static COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let made = read_back(list, dst, x, y, z, src, source_box); + if n <= 16 || n % 4096 == 0 || made.is_err() { + static REFUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if made.is_err() && REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 16 { + return; + } + let source = crate::resource::host_resource(src.resource).map(|r| { + // SAFETY: a live resource. + let d = unsafe { r.GetDesc() }; + format!("{}x{} f{} mips {}", d.Width, d.Height, d.Format.0, d.MipLevels) + }); + tracing::info!( + copies = n, + made = ?made, + source = ?source, + source_kind = src.kind, + destination_kind = dst.kind, + destination_offset = dst.footprint.offset, + destination_bytes = ?dst.footprint.bytes(), + "a texture to buffer copy (a read back)" + ); + } return; }; + if unlike(dst.resource, src.resource) { + return; + } let mut from = src; let _upload; // keeps the source alive while this call records it #[cfg(feature = "diagnostics")] @@ -540,12 +984,16 @@ extern "system" fn copy_texture_region( let Some(texture) = crate::resource::host_resource(src.resource) else { return; }; + list.twin_use(src.resource, false, false); if crate::texture::title_written(texture) { crate::texture::upload(list, src.resource, texture); } ensure_state(list, src.resource, COPY_SOURCE); from.resource = texture.as_raw().cast_const().cast(); } + // A depth texture shaders also write: what they wrote, first (the + // source above too). + list.twin_use(dst.resource, false, true); ensure_state(list, dst.resource, COPY_DEST); crate::texture::host_written(dst.resource); let mut to_location = dst; @@ -592,6 +1040,70 @@ extern "system" fn copy_texture_region( let _ = (this, dst, x, y, z, src, source_box); } +/// Records a texture to buffer copy (a read back) of [`copy_texture_region`] +/// into `list`, or says why not. +#[cfg(windows)] +#[allow(clippy::too_many_arguments)] // the method's own arguments +fn read_back( + list: &crate::host::HostList, + dst: CopyLocation, + x: u32, + y: u32, + z: u32, + src: CopyLocation, + source_box: *const [u32; 6], +) -> Result<(), &'static str> { + use windows::Win32::Graphics::Direct3D12::D3D12_BOX; + use windows::core::Interface; + const FOOTPRINT: u32 = 1; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_READ_BACK").is_none_or(|v| v != "0")) { + return Err("switched off"); + } + if dst.kind != FOOTPRINT || src.kind == FOOTPRINT { + return Err("not a texture subresource into a placed footprint"); + } + if (x, y, z) != (0, 0, 0) { + return Err("a destination corner other than the footprint's"); + } + let host = crate::host::host().ok_or("no host")?; + let (footprint, [size, row, rows, pitch]) = dst.footprint.host_rows().ok_or("an unknown format")?; + // The title's buffer holds every row at its own pitch. + let bytes = pitch * (rows - 1) + row; + let data = buffer_range(dst.resource, dst.footprint.offset, bytes).ok_or("a destination outside its buffer")?; + let texture = crate::resource::host_resource(src.resource).ok_or("no host texture")?; + let buffer = host.read_back_buffer(size).ok_or("no read-back buffer")?; + // As a texture source of any copy: what shaders wrote to a depth twin + // and what the title wrote itself first, then the state. + list.twin_use(src.resource, false, false); + if crate::texture::title_written(texture) { + crate::texture::upload(list, src.resource, texture); + } + ensure_state(list, src.resource, COPY_SOURCE); + let mut from = src; + from.resource = texture.as_raw().cast_const().cast(); + let mut to = dst; + to.resource = buffer.as_raw().cast_const().cast(); + to.footprint = footprint; + let host_box = (!source_box.is_null()).then(|| source_box.cast::()); + #[cfg(feature = "diagnostics")] + list.note_op(|| { + format!( + "read back of {:?} sub {} into buffer {:?}+{:#x}: {rows} rows of {row} bytes", + src.resource, src.footprint.offset as u32, dst.resource, dst.footprint.offset + ) + }); + // SAFETY: an open list; both locations in the host's layout (asserted + // in `copy_texture_region`), naming a live texture and our buffer, which + // the list keeps until it is reset; the box is the title's. + unsafe { + list.list + .CopyTextureRegion((&raw const to).cast(), 0, 0, 0, (&raw const from).cast(), host_box) + }; + list.defer_read_back(buffer, data, [row as usize, rows as usize, pitch as usize]); + Ok(()) +} + #[allow(clippy::too_many_arguments)] // the method's own arguments extern "system" fn copy_texture_region_x( this: This, @@ -629,6 +1141,12 @@ extern "system" fn resolve( use windows::core::Interface; const RESOLVE_DEST: u32 = 0x1000; const RESOLVE_SOURCE: u32 = 0x2000; + if unlike(dst, src) { + return; + } + // Depth textures shaders also write: what they wrote, first. + list.twin_use(dst, false, true); + list.twin_use(src, false, false); ensure_state(list, dst, RESOLVE_DEST); ensure_state(list, src, RESOLVE_SOURCE); crate::texture::host_written(dst); @@ -637,7 +1155,7 @@ extern "system" fn resolve( // SAFETY: an open list and live textures; the region is inside both. unsafe { let (a, b) = (to.GetDesc(), from.GetDesc()); - let format = DXGI_FORMAT(format as i32); + let format = if crate::resource::stands_in(dst) { a.Format } else { DXGI_FORMAT(format as i32) }; if (a.Width, a.Height) == (b.Width, b.Height) { list.list .ResolveSubresource(to, dst_sub, from, src_sub, format); @@ -703,7 +1221,7 @@ extern "system" fn clear_rtv( unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } }); const RENDER_TARGET: u32 = 0x4; - let rtv = host.rtv(texture, record.desc().as_ref()); + let rtv = host.rtv(Some(texture), record.desc().as_ref()); // SAFETY: an open list, a fresh view of a live texture. unsafe { if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) { @@ -750,7 +1268,13 @@ extern "system" fn clear_dsv( unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } }); const DEPTH_WRITE: u32 = 0x10; + // A depth texture shaders also write: what they wrote, first (the + // clear may be of one slice or of some rectangles). + list.twin_use(record.resource, false, true); ensure_state(list, record.resource, DEPTH_WRITE); + if crate::resource::depth_and_unordered(record.resource) { + crate::resource::DEPTH_UNORDERED[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } let dsv = host.dsv(texture, record.depth_desc().as_ref()); // SAFETY: an open list, a fresh view of a live texture. unsafe { @@ -905,15 +1429,26 @@ extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mu } /// Draw state the host has no use for (root signatures: ours come with -/// the pipeline; depth bounds, depth order and shading rate hints): any -/// arguments, nothing returned. +/// the pipeline; depth order and shading rate hints): any arguments, +/// nothing returned. extern "system" fn ignored_state(_: This) {} +/// Depth bounds `(min, max)`. +/// shortcut: not set on the host list (no host pipeline of ours enables +/// the test, `pipeline::host`); the first values are logged, so a run +/// shows whether the title uses the test at all. +extern "system" fn depth_bounds(_: This, min: f32, max: f32) { + static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 8 { + tracing::info!(min, max, "the title sets depth bounds, which the host is not given"); + } +} + /// The title's draw state (decision 0007, step 3), kept for its draws or /// set on the host list at once. Without a host GPU these do nothing. #[cfg(windows)] mod state { - use super::{This, host_list, with_state}; + use super::{This, with_state}; use crate::draw::{IndexView, VertexView}; use windows::Win32::Foundation::RECT; use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT; @@ -935,25 +1470,21 @@ mod state { count: u32, viewports: *const D3D12_VIEWPORT, ) { - if let Some(list) = host_list(this) { - crate::draw::viewports(list, items(viewports, count)); - } + // (Through the draw state, which keeps them for the host list + // that continues this one after a cut: `State::replay`.) + with_state(this, |list, s| s.set_viewports(list, items(viewports, count))); } pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) { - if let Some(list) = host_list(this) { - crate::draw::scissors(list, items(rects, count)); - } + with_state(this, |list, s| s.set_scissors(list, items(rects, count))); } pub(super) extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) { - if let Some(list) = host_list(this) { + with_state(this, |list, s| { // SAFETY: the title passes four floats or null. - crate::draw::blend_factor(list, unsafe { factor.as_ref() }); - } + s.set_blend_factor(list, unsafe { factor.as_ref() }) + }); } pub(super) extern "system" fn stencil_ref(this: This, reference: u32) { - if let Some(list) = host_list(this) { - crate::draw::stencil_ref(list, reference); - } + with_state(this, |list, s| s.set_stencil_ref(list, reference)); } pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) { with_state(this, |_, s| s.set_heaps(items(heaps, count))); @@ -1224,10 +1755,181 @@ pub(crate) fn take_counts() -> (u64, u64) { (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed)) } -/// A GPU wait for a memory value `(address, comparison, reference, ...)`. -/// Lists run one after another and to completion, so a value another queue -/// or the CPU has to write first cannot be waited for; nothing to do. -extern "system" fn wait_value(_: This, _address: u64, _comparison: u32, _reference: u64) {} +/// A GPU wait for a memory value: the list's commands after it run when +/// the 32 or 64 bits at `address` compare as asked with `reference`. +#[derive(Clone, Copy, Debug)] +pub(crate) struct ValueWait { + address: u64, + comparison: u32, + reference: u64, + wide: bool, +} + +impl ValueWait { + /// Whether the memory holds what is waited for now. + /// shortcut: the comparison codes are taken to be the comparison + /// functions' (1 never .. 8 always, value against reference); one not + /// known counts as met, and so does memory that is not mapped. + /// + /// The value is read through the kernel, which reports memory that is + /// not there instead of faulting (as the copies of title memory are + /// read, `crate::host::copy_mapped`). Asking Windows first whether the + /// memory is committed (`VirtualQuery`) walks the page tables to the + /// end of the region: the title keeps these values in a 1.1 GB + /// allocation (0xd00000000), where one question took about 8 ms, and a + /// queue asks at every submission and every signal, for each queue that + /// stands at a wait (Grand Theft Auto VI has five queues). That was + /// 1.0-2.2 s of every cutscene frame on the thread that submits (runs + /// 36-49: "between its submissions ... kernel"; 47 of 110 looks at + /// that thread in run 49 found it in this question). + /// `VICTORY_WAIT_ASK=1` asks first, as before. + pub(crate) fn met(&self) -> bool { + #[cfg(all(windows, feature = "diagnostics"))] + let started = std::time::Instant::now(); + let met = self.holds(); + #[cfg(all(windows, feature = "diagnostics"))] + { + use crate::copystat::{C, add}; + add(C::WaitChecks, 1); + add(C::WaitCheckNs, started.elapsed().as_nanos() as u64); + } + met + } + + fn holds(&self) -> bool { + let bytes = if self.wide { 8 } else { 4 }; + if self.address == 0 { + return true; + } + static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); + if *ASK.get_or_init(|| std::env::var_os("VICTORY_WAIT_ASK").is_some_and(|v| v == "1")) + && !crate::texture::committed(self.address as *const u8, bytes) + { + return true; + } + // The low `bytes` bytes; the rest stays zero. + let mut raw = [0u8; 8]; + if !crate::host::read_into(self.address as *const u8, &mut raw[..bytes]) { + return true; + } + self.holds_for(u64::from_le_bytes(raw)) + } + + /// Where the value waited for is: address and bytes. + #[cfg(windows)] + pub(crate) fn place(&self) -> (usize, usize) { + (self.address as usize, if self.wide { 8 } else { 4 }) + } + + /// Whether the wait is met with `value` at its address (its low half + /// for a 32-bit wait). + pub(crate) fn holds_for(&self, value: u64) -> bool { + let (value, reference) = if self.wide { + (value, self.reference) + } else { + (value & 0xFFFF_FFFF, self.reference & 0xFFFF_FFFF) + }; + match self.comparison { + 1 => false, + 2 => value < reference, + 3 => value == reference, + 4 => value <= reference, + 5 => value > reference, + 6 => value != reference, + 7 => value >= reference, + _ => true, + } + } +} + +/// The waits lists recorded since their last reset, by list. +static VALUE_WAITS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// The waits of the submitted `lists` that are not met yet (taken from +/// them): what the console's GPU would stop at. The title orders work +/// between its queues this way (Grand Theft Auto VI: the compute queue's +/// lighting passes wait for a value the graphics queue's depth pass writes +/// at the bottom of the pipe; run at once, they read a cleared depth +/// buffer and nothing was lit). +/// shortcut: a wait holds its whole list (and submission) back, not only +/// the commands after it. +pub(crate) fn unmet_waits(lists: &[This]) -> Vec { + let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner()); + let mut unmet = Vec::new(); + waits.retain(|&(list, wait)| { + if !lists.iter().any(|&l| l as usize == list) { + return true; + } + if !wait.met() { + unmet.push(wait); + } + false + }); + unmet +} + +/// The waits each of the submitted `lists` recorded (taken from them), +/// met or not, at the list's first place in the submission. +#[cfg(windows)] +pub(crate) fn waits_by_list(lists: &[This]) -> Vec> { + let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner()); + let mut by = vec![Vec::new(); lists.len()]; + waits.retain(|&(list, wait)| { + match lists.iter().position(|&l| l as usize == list) { + Some(i) => { + by[i].push(wait); + false + } + None => true, + } + }); + by +} + +fn wait_for(this: This, address: u64, comparison: u32, reference: u64, wide: bool) { + let wait = ValueWait { + address, + comparison, + reference, + wide, + }; + static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 12 { + tracing::info!( + address = format_args!("{address:#x}"), + comparison, + reference, + wide, + met = wait.met(), + "a list waits for a memory value" + ); + } + #[cfg(all(windows, feature = "diagnostics"))] + if let Some(host) = host_list(this) { + crate::capture::op(std::ptr::from_ref(host) as usize, || { + format!( + "WAIT VALUE at {address:#x} comparison {comparison} reference {reference:#x} wide {wide} met {}", + wait.met() + ) + }); + } + // The list is cut here, and the wait stands before what follows. + #[cfg(windows)] + if crate::queue::cuts() { + cut(this, wait); + return; + } + VALUE_WAITS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((this as usize, wait)); +} +extern "system" fn wait_value(this: This, address: u64, comparison: u32, reference: u64) { + wait_for(this, address, comparison, reference, false); +} +extern "system" fn wait_value64(this: This, address: u64, comparison: u32, reference: u64) { + wait_for(this, address, comparison, reference, true); +} /// The enhanced barriers `(group count, groups)`: buffer, texture and /// global barriers with layouts instead of states. Every host use of a @@ -1235,6 +1937,14 @@ extern "system" fn wait_value(_: This, _address: u64, _comparison: u32, _referen /// first, so only their ordering matters: one barrier on every shader /// write (the title's buffer barriers order compute passes). extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { + // Diagnostics: counted, and left out under `VICTORY_BARRIER_TEST=groups`. + #[cfg(all(windows, feature = "diagnostics"))] + if count > 0 { + crate::copystat::add(crate::copystat::C::WaitsForGroups, 1); + if crate::copystat::barrier_test() & 1 != 0 { + return; + } + } #[cfg(windows)] if count > 0 && let Some(list) = host_list(this) @@ -1254,6 +1964,7 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { /// GPU timestamp instead (64-bit form), flag 2 the system timestamp. extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) { defer_write(this, address, Written::Value(u64::from(value)), 4); + value_written(this, address, u64::from(value)); } extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) { const GPU_TIMESTAMP: u32 = 1; @@ -1264,6 +1975,65 @@ extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, fl _ => Written::Value(value), }; defer_write(this, address, what, 8); + if let Written::Value(value) = what { + value_written(this, address, value); + } +} + +/// The title wrote a value at the bottom of the pipe (not a timestamp, not +/// a query result): listed (diagnostics), and with `VICTORY_CUT_WRITES=1` +/// the host list is cut right behind it, so that the value is stored when +/// the card has run the list up to there, as on the console, and not when +/// the whole list has run. Lists of other queues wait for these values +/// (Grand Theft Auto VI: the compute list that builds the depth pyramid +/// waits for one, and the meshlet culling of the same frame reads that +/// pyramid). Off by default: every such write then ends a host list, and +/// each part is a submission of its own. +fn value_written(this: This, address: u64, value: u64) { + #[cfg(windows)] + { + if address == 0 || this.is_null() { + return; + } + #[cfg(not(feature = "diagnostics"))] + let _ = value; + #[cfg(feature = "diagnostics")] + if let Some(host) = host_list(this) { + crate::capture::op(std::ptr::from_ref(host) as usize, || { + format!("WRITE VALUE at {address:#x} value {value:#x}") + }); + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WRITES").is_some_and(|v| v == "1")) + || !crate::queue::cuts() + { + return; + } + // SAFETY: the title passes one of our lists; a list is recorded by + // one thread at a time and is not submitted while it records. + let list = unsafe { &mut *this.cast_mut().cast::() }; + let Some(current) = list.host.as_ref() else { + return; + }; + let Some(fresh) = fresh_list() else { + return; + }; + current.close(); + if let Some(done) = list.host.replace(fresh) { + // The part so far keeps its waits; nothing stands before the + // next one but this part itself. + let waits = std::mem::take(&mut list.gate); + list.earlier.push(Part { waits, host: done }); + } + if let Some(host) = list.host.as_ref() { + list.state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .replay(host); + } + } + #[cfg(not(windows))] + let _ = (this, address, value); } fn defer_write(this: This, address: u64, what: Written, bytes: usize) { @@ -1327,11 +2097,11 @@ const METHODS: [(usize, *const ()); 52] = [ (52, clear_rtv as *const ()), // 0x1a0 (59, execute_indirect as *const ()), // 0x1d8 indirect (60, copy_memory as *const ()), // 0x1e0 - (68, ignored_state as *const ()), // 0x220 depth bounds + (68, depth_bounds as *const ()), // 0x220 depth bounds (69, write32 as *const ()), // 0x228 (70, write64 as *const ()), // 0x230 (71, wait_value as *const ()), // 0x238, 32 bits - (72, wait_value as *const ()), // 0x240, 64 bits + (72, wait_value64 as *const ()), // 0x240, 64 bits (73, ignored_state as *const ()), // 0x248 pixel shader depth order (83, copy_texture_region_x as *const ()), // 0x298 (84, copy_resource_x as *const ()), // 0x2a0 diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs new file mode 100644 index 0000000..c256367 --- /dev/null +++ b/crates/victory-gpu/src/memory.rs @@ -0,0 +1,319 @@ +//! Title memory by address, for translated shaders that read and write +//! through raw 40-bit addresses (`victory_shader::emit::SLOT_MEMORY`: the +//! console's ray-tracing structure builder and the programs that walk its +//! structures; the structures themselves lie in plain title memory, in no +//! buffer object). +//! +//! The copies are the ones every other access uses ([`crate::shadow`]: a +//! title buffer's copy, or the 4 MiB window of memory outside buffers), so +//! a root view and a raw address reach the same host bytes. This module +//! keeps what a shader needs to find them: +//! +//! - the **directory**: per 64 KiB page of title address space the number +//! of the copy that holds the page (0: none) and the page's byte offset +//! in it; one buffer for all lists, entries only ever go from empty to +//! filled; +//! - per view heap a run of slots with a raw unordered access view of each +//! numbered copy (slot 0 of the run: a null view, for pages without a +//! copy); +//! - the **faults**: the page numbers shaders found empty, read back here +//! once a frame, so the copies exist from the next frame on. A pointer a +//! shader takes out of memory cannot be known before it runs; the +//! addresses a dispatch is given as root views are made ready before it. +//! +//! **A page that is not there when a shader touches it is a lost access**: +//! the read gives 0, the store is dropped, and the fault note only helps +//! the next frame. For the structure builder that is the same as a dropped +//! stage, so before a dispatch the host makes ready everything it can see +//! the dispatch name: the whole copy around each root view, around each +//! pair of root constants that is a title address and around each root +//! constant that is one in 256-byte units (the builder passes structures +//! all three ways), and the 4 MiB after each (a structure may cross a +//! window's end). +//! shortcut: what a stage reaches only through pointers it reads out of +//! memory (InitHeaders' table of structure addresses, LoadInstances' +//! instance records) is not made ready unless something else named it; +//! the fault count in the log says whether that happens. The whole answer +//! is the extent of the title's allocation around an address, which the +//! memory module of the layer knows and this one does not ask yet. +//! +//! shortcut: a copy that is numbered is kept for the rest of the run, and +//! there are at most [`COPIES`] of them (4 MiB windows mostly: 4 GiB at +//! most). Every dispatch of such a shader brings all numbered copies up to +//! date and, if it can store, declares all of them written (the bytes are +//! compared on the CPU afterwards, as for any unordered access view): a +//! dirty-page mask written by the shader would bound both. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use victory_shader::emit::{MEMORY_FAULTS, MEMORY_PAGES}; +use windows::Win32::Graphics::Direct3D12::*; + +use crate::descriptor::host::HostHeap; +use crate::host::{HostList, host}; +use crate::shadow::Shadow; + +/// Copies that can be numbered (the run of heap slots is one longer). A +/// listed frame of the opening cutscene names about 50 windows. +const COPIES: u32 = 1023; +/// A window of memory outside buffers (`shadow.rs`). +const CELL: u64 = 4 << 20; +/// A directory page. +const PAGE: u64 = 1 << 16; + +struct Memory { + /// Buffer, its mapping, its GPU address. + directory: (ID3D12Resource, *mut u32, u64), + faults: (ID3D12Resource, *mut u32, u64), + /// Copy `n` is `copies[n - 1]`. + copies: Vec>, + /// Per host view heap (by address): the first slot of its run, and how + /// many copies have their view there. + heaps: HashMap, + /// The frame the faults were last read in. + frame: u64, + /// Pages asked for this frame that are not the title's memory. + refused: std::collections::HashSet, +} + +// SAFETY: the mappings are of buffers the struct owns; all access is under +// the mutex. +unsafe impl Send for Memory {} + +static MEMORY: Mutex> = Mutex::new(None); + +/// What a draw binds. +pub(crate) struct Ready { + pub(crate) directory: u64, + pub(crate) faults: u64, + /// The view heap slot of the null view; copy `n`'s view is `n` further. + pub(crate) base: u32, +} + +impl Memory { + fn new() -> Option { + let host = host()?; + let make = |dwords: u64, what: &str| { + let (buffer, data) = host.shared_buffer(dwords * 4)?; + crate::host::name(&buffer, || format!("title memory by address: {what}")); + // SAFETY: a fresh mapping of at least that many bytes. + unsafe { std::ptr::write_bytes(data, 0, (dwords * 4) as usize) }; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + Some((buffer, data.cast::(), gpu)) + }; + tracing::info!("title memory by address: a shader reads or writes through raw addresses"); + Some(Memory { + directory: make(u64::from(MEMORY_PAGES) * 2, "directory")?, + faults: make(u64::from(MEMORY_FAULTS), "faults")?, + copies: Vec::new(), + heaps: HashMap::new(), + frame: u64::MAX, + refused: Default::default(), + }) + } + + /// Gives the page of `address` its copy, if it has none and the memory + /// is the title's. + fn map(&mut self, address: u64) { + let page = address / PAGE; + // The last entry stays empty: addresses past the directory read it. + if page >= u64::from(MEMORY_PAGES) - 1 { + return; + } + // SAFETY: inside the directory's mapping. + let entry = unsafe { self.directory.1.add(page as usize * 2) }; + // SAFETY: as above. + if unsafe { entry.read() } != 0 { + return; + } + let start = page * PAGE; + // A shader's pointer, or a constant taken for an address, may be + // anything: only memory the title has. + if self.refused.contains(&page) { + return; + } + if !crate::texture::committed(start as *const u8, PAGE as usize) { + self.refused.insert(page); + return; + } + // The copy a root view at that address would get; a buffer that + // ends inside the page is passed over for what holds all of it. + let whole = |s: &Arc| s.offset_in(start).is_some_and(|_| s.left(start) >= PAGE); + let Some(shadow) = crate::shadow::find(start, 1) + .filter(whole) + .or_else(|| crate::shadow::find(start, PAGE).filter(whole)) + else { + return; + }; + // SAFETY: a live buffer. + let flags = unsafe { shadow.buffer.GetDesc() }.Flags; + if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { + return; + } + let n = match self.copies.iter().position(|c| Arc::ptr_eq(c, &shadow)) { + Some(n) => n, + None if self.copies.len() < COPIES as usize => { + self.copies.push(shadow.clone()); + let n = self.copies.len() - 1; + // Every page the copy holds whole, not only the one asked + // for: a structure is more than 64 KiB. + // shortcut: a page of a title buffer inside this one that + // has a copy of its own is given this copy too. + let (first, len) = shadow.span(); + let mut at = first.next_multiple_of(PAGE); + while at + PAGE <= first + len && at / PAGE < u64::from(MEMORY_PAGES) - 1 { + // SAFETY: inside the directory's mapping. + let other = unsafe { self.directory.1.add((at / PAGE) as usize * 2) }; + // SAFETY: as above; the offset first, as below. + unsafe { + if other.read() == 0 { + other.add(1).write_volatile((at - first) as u32); + other.write_volatile(n as u32 + 1); + } + } + at += PAGE; + } + n + } + None => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros") + }); + return; + } + }; + let offset = shadow.offset_in(start).unwrap_or(0); + // The offset first: a shader that sees the number sees it too. + // SAFETY: inside the directory's mapping. + unsafe { + entry.add(1).write_volatile(offset as u32); + entry.write_volatile(n as u32 + 1); + } + } + + /// The pages shaders found empty since the last frame. + fn take_faults(&mut self) { + let mut pages = Vec::new(); + for i in 1..MEMORY_FAULTS as usize { + // SAFETY: inside the faults' mapping; the GPU may be writing, + // a number missed now is written again next frame. + let at = unsafe { self.faults.1.add(i) }; + // SAFETY: as above. + let page = unsafe { at.read_volatile() }; + if page != 0 { + pages.push(page); + // SAFETY: as above. + unsafe { at.write_volatile(0) }; + } + } + if !pages.is_empty() { + // Each is an access that read 0 or was dropped. + static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 50 { + tracing::warn!( + pages = pages.len(), + first = format_args!("{:#x}", u64::from(pages[0]) * PAGE), + "title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); the copies are made now" + ); + } + } + for page in pages { + self.map(u64::from(page) * PAGE); + } + } + + /// What a dispatch names: the copy around `address` and the 4 MiB + /// after it. + fn name(&mut self, address: u64) { + self.map(address); + self.map((address & !(CELL - 1)) + CELL); + } +} + +/// Before a draw whose shader reads title memory by address: what its +/// root arguments name gets its copies (`addresses`: its root views; +/// `constants`: its root constants, see the module), every numbered copy +/// has its view in `heap`'s run and is brought up to date when `list` is +/// submitted (and, with `writes`, copied back after). None if the host +/// cannot hold it; the draw is then dropped. +pub(crate) fn ready( + list: &HostList, + heap: &HostHeap, + addresses: &[u64], + constants: &[u32], + writes: bool, +) -> Option { + let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); + if guard.is_none() { + *guard = Memory::new(); + } + let m = guard.as_mut()?; + let frame = crate::frame::current(); + if m.frame != frame { + m.frame = frame; + m.refused.clear(); + m.take_faults(); + } + let numbered = m.copies.len(); + for &address in addresses { + m.name(address); + } + // A title address in two constants (low dword, then bits 32 to 39), or + // in one in 256-byte units. A constant that only looks like one names + // memory nothing reads; one that is not the title's memory is refused. + for (i, &c) in constants.iter().enumerate() { + if let Some(&high) = constants.get(i + 1) + && (1..=0xFF).contains(&high) + && c >= 0x1_0000 + { + m.name(u64::from(c) | u64::from(high) << 32); + } + if c >= 0x0100_0000 { + m.name(u64::from(c) << 8); + } + } + let key = std::ptr::from_ref(heap) as usize; + let (base, made) = match m.heaps.get(&key) { + Some(&run) => run, + None => { + // Held for the heap's life: not given back with a list's slots. + let base = heap.dynamic(COPIES + 1)?; + heap.null_raw_uav_at(base); + (base, 0) + } + }; + for (n, shadow) in m.copies.iter().enumerate().skip(made as usize) { + let (_, len) = shadow.span(); + heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len); + } + m.heaps.insert(key, (base, m.copies.len() as u32)); + // Once per list, and for copies numbered since: the builder alone + // dispatches hundreds of times a frame. + // shortcut: a copy another list numbers meanwhile is brought up to date + // by that list's submission, which may run after this one's. + const READ: usize = usize::MAX - 0x6d; + const WRITE: usize = usize::MAX - 0x6e; + let first_read = list.first_use(READ); + let first_write = writes && list.first_use(WRITE); + for (n, shadow) in m.copies.iter().enumerate() { + let (start, len) = shadow.span(); + if first_read || n >= numbered { + shadow.refresh(list, start, len); + } + if writes && (first_write || n >= numbered) { + shadow.gpu_writes(list, start, len); + } + } + if first_read { + list.keep(&m.directory.0); + list.keep(&m.faults.0); + } + Some(Ready { + directory: m.directory.2, + faults: m.faults.2, + base, + }) +} diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index b1dc393..832f236 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -74,6 +74,28 @@ impl std::fmt::Debug for Shader { /// Every container seen, by full content hash. static SHADERS: Mutex>>> = Mutex::new(None); +/// For the memory lines: containers kept and their bytes, translations +/// 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]; + +/// 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 +/// last save wrote. +#[cfg(windows)] +pub(crate) fn kept() -> [u64; 7] { + use std::sync::atomic::Ordering::Relaxed; + [ + KEPT[0].load(Relaxed), + KEPT[1].load(Relaxed), + KEPT[2].load(Relaxed), + KEPT[3].load(Relaxed), + library::BLOB.load(Relaxed), + library::SAVED.load(Relaxed), + library::TRIMMED_BYTES.load(Relaxed), + ] +} + /// The shared container for `bytes`. fn shader(stage: &'static str, bytes: &[u8]) -> Arc { let full = blake3::hash(bytes); @@ -82,6 +104,8 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc { .get_or_insert_with(HashMap::new) .entry(*full.as_bytes()) .or_insert_with(|| { + KEPT[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + KEPT[1].fetch_add(bytes.len() as u64, std::sync::atomic::Ordering::Relaxed); Arc::new(Shader { stage, hash: full.to_hex()[..16].to_owned(), @@ -98,6 +122,9 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc { pub(crate) struct Translated { pub(crate) host: victory_shader::emit::HostShader, pub(crate) used: Vec, + /// Whether the shader's code can store to buffer memory ([`stores`]); + /// true when its code is not known. + pub(crate) stores: bool, } #[cfg(windows)] @@ -108,6 +135,21 @@ impl Shader { self.translated .get_or_init(|| { let done = translate(&self.container); + // `VICTORY_SHADER_SAVE=`: each shader as the title gave it (`.cdxil`) and as + // translated (`.dxil`), by the hash crash reports name it with + if let Some(dir) = std::env::var_os("VICTORY_SHADER_SAVE") { + let dir = std::path::PathBuf::from(dir); + let _ = std::fs::create_dir_all(&dir); + let stem = format!("{}.{}", self.hash, self.stage); + let _ = std::fs::write(dir.join(format!("{stem}.cdxil")), &self.container); + if let Ok(t) = &done { + let _ = std::fs::write(dir.join(format!("{stem}.dxil")), &t.host.dxil); + } + } + if let Ok(t) = &done { + 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); + } match &done { Ok(t) => tracing::info!( stage = self.stage, @@ -132,23 +174,170 @@ impl Shader { #[cfg(windows)] fn translate(container: &[u8]) -> Result { use victory_shader::{Container, FourCC, HwStage}; - let host = crate::shader_cache::host_shader(container)?; + // The translation depends on it (a view index past a capped heap). + crate::descriptor::host::probe_view_limit(); let c = Container::parse(container).map_err(|e| e.to_string())?; - let used = match c.part(FourCC::DXIL) { - Some(part) => victory_shader::native_programs(part.data) - .map_err(|e| e.to_string())? - .into_iter() - .find(|p| { - matches!( - p.stage, - HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs - ) - }) - .map(|p| p.used) - .unwrap_or_default(), + let programs = match c.part(FourCC::DXIL) { + Some(part) => victory_shader::native_programs(part.data).map_err(|e| e.to_string())?, None => Vec::new(), }; - Ok(Translated { host, used }) + let host = crate::shader_cache::host_shader(container)?; + let stores = programs.is_empty() || programs.iter().any(stores); + let used = programs + .into_iter() + .find(|p| { + matches!( + p.stage, + HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs + ) + }) + .map(|p| p.used) + .unwrap_or_default(); + Ok(Translated { host, used, stores }) +} + +/// The compute pipelines of the console's ray-tracing structure builder +/// (`XboxBvhBuilder.dll`; its programs are the ones with a spilled +/// user-data table) run **all or none**. Its stages feed each other +/// through memory: a stage that runs on what a dropped stage never wrote +/// computes its store offsets from garbage. The structures lie in plain +/// title memory, between the title's own objects, and a root view has no +/// size, so those stores land on the neighbours (run 98, with 14 of 35 +/// stages translated: the title died within a second of the first builder +/// submission, on pointers that had become bounding-box bit patterns). +/// +/// So a builder dispatch runs only while every builder pipeline the title +/// has created has a host pipeline; the first builder dispatch makes them +/// all on the spot instead of over the next frames (a stage "still being +/// made" would be a dropped stage). One that cannot be made turns the +/// builder off for the rest of the run. +/// +/// shortcut: and only with `VICTORY_BVH_BUILDER=1`, until a run has shown +/// the whole builder and the host side of title memory by address +/// (`memory.rs`) working on a card; nothing reads the structures before +/// the programs that walk them translate. +#[cfg(windows)] +struct Builder { + pipelines: Vec>, + /// Every one of `pipelines` has a host pipeline. + whole: bool, + /// One could not be made. + off: bool, +} + +#[cfg(windows)] +static BUILDER: Mutex = Mutex::new(Builder { + pipelines: Vec::new(), + whole: false, + off: false, +}); + +/// Whether `shaders` are a pipeline of the structure builder. +#[cfg(windows)] +fn of_builder(shaders: &[Arc]) -> bool { + use victory_shader::{Container, FourCC}; + let [shader] = shaders else { return false }; + if shader.stage != "compute" { + return false; + } + let Ok(c) = Container::parse(&shader.container) else { + return false; + }; + c.part(FourCC::DXIL) + .and_then(|part| victory_shader::native_programs(part.data).ok()) + .is_some_and(|programs| programs.iter().any(victory_shader::spill::is_spilled)) +} + +/// `VICTORY_BVH_QUARANTINE=1`: what the structure builder's stages store +/// stays in the host's copies and is not copied back into title memory. A +/// check for a first run of the whole builder: a stage that stores where +/// it should not can then not reach the title's own objects (run 98), and +/// the programs that walk the structures read the host's copies anyway. +/// shortcut: not a way to run: the title also reads results back (sizes, +/// counters) and gets none, and a copy's pages are overwritten from title +/// memory when the title writes them. +#[cfg(windows)] +pub(crate) fn builder_quarantined(this: This) -> bool { + static ON: OnceLock = OnceLock::new(); + is_builder(this) && *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_QUARANTINE").is_some_and(|v| v == "1")) +} + +/// Whether the title's pipeline `this` is one of the structure builder's. +#[cfg(windows)] +pub(crate) fn is_builder(this: This) -> bool { + !this.is_null() && pipeline(this).builder +} + +/// A stage of the builder was dropped after all: none runs from here on. +#[cfg(windows)] +pub(crate) fn builder_off(why: &'static str) { + let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); + if !b.off { + b.off = true; + tracing::warn!(why, "the ray-tracing structure builder is turned off for the rest of the run: its stages run all or none"); + } +} + +/// At a dispatch of a builder pipeline: whether the builder runs (see +/// [`Builder`]). +#[cfg(windows)] +pub(crate) fn builder_runs() -> bool { + static ALLOWED: OnceLock = OnceLock::new(); + if !*ALLOWED.get_or_init(|| std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1")) { + return false; + } + let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); + if b.off { + return false; + } + if b.whole { + return true; + } + let missing = b.pipelines.iter().filter(|p| !make::now(p)).count(); + if missing > 0 { + b.off = true; + tracing::warn!( + missing, + of = b.pipelines.len(), + "the ray-tracing structure builder stays off: not all of its programs have a host pipeline, and its stages run all or none" + ); + return false; + } + tracing::info!( + pipelines = b.pipelines.len(), + "the ray-tracing structure builder runs: all of its programs have host pipelines" + ); + b.whole = true; + true +} + +/// Whether a console program can store to buffer memory: it has a buffer, +/// typed-buffer, scalar-memory, flat or global store or atomic, or code +/// that is not all known (an instruction of those kinds outside our table, +/// an indirect jump, code that does not decode). Stores to textures +/// (image instructions) and to the program's own scratch memory do not +/// count: neither reaches a buffer's host copy. After upstream #413, +/// which leaves scalar-memory stores out and counts image stores. +#[cfg(windows)] +fn stores(program: &victory_shader::NativeProgram) -> bool { + use victory_shader::gfx10::{Encoding, decode}; + let Ok(code) = decode(&program.code) else { + return true; + }; + code.iter().any(|i| { + let name = i.name(); + match i.encoding { + Encoding::Mubuf + | Encoding::Mtbuf + | Encoding::Smem + | Encoding::Flat + | Encoding::Global => name.is_none_or(|n| { + (n.contains("store") || n.contains("atomic")) && !n.contains("scratch") + }), + Encoding::Sop1 => name.is_none_or(|n| matches!(n, "s_setpc_b64" | "s_swappc_b64")), + _ => false, + } + }) } #[repr(C)] @@ -163,6 +352,9 @@ struct Pipeline { /// (by a worker: the title may release the pipeline meanwhile). #[cfg(windows)] host: Arc, + /// One of the ray-tracing structure builder's ([`Builder`]). + #[cfg(windows)] + builder: bool, } const _: () = assert!(offset_of!(Pipeline, packet) == 0x10); @@ -274,6 +466,7 @@ pub(crate) fn note_drop(this: This) { /// Counts a draw or dispatch dropped for `why` (diagnostics). #[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn note_why(why: String) { + crate::capture::op(0, || format!("DROPPED {why}")); let mut drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()); *drops.get_or_insert_with(HashMap::new).entry(why).or_default() += 1; } @@ -311,11 +504,22 @@ fn hand_out( let host = Arc::new(make::Pending::new(shaders.clone(), graphics)); #[cfg(windows)] make::early(&host); + #[cfg(windows)] + let builder = of_builder(&shaders); + #[cfg(windows)] + if builder { + // Another stage: the group is looked at again at its next dispatch. + let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); + b.pipelines.push(host.clone()); + b.whole = false; + } let pipeline = Box::new(Pipeline { object: Object::new(&FUNCTIONS), packet: [0; 8], #[cfg(windows)] host, + #[cfg(windows)] + builder, shaders, bound: std::sync::atomic::AtomicBool::new(false), }); @@ -490,6 +694,20 @@ mod library; #[cfg(windows)] mod make; +/// Lets the pipeline library's mapped file go from memory when no pipeline +/// has loaded for a while (`library::trim`); called by the host's sweep. +#[cfg(windows)] +pub(crate) fn trim_library() { + library::trim(); +} + +/// The pipeline library's part of the report when the host device is +/// removed (`library::removal_note`). +#[cfg(windows)] +pub(crate) fn library_removal_note() -> String { + library::removal_note() +} + /// Keeps compiled host pipelines, and the list of title pipelines to start /// early, in `dir` (a folder of the cache) across runs. #[cfg(windows)] diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 00aa9aa..838044e 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -109,6 +109,15 @@ impl GraphicsState { // pipeline uses the plain description); bring it back // with a stream if a title enables it. let d = data.cast::().read_unaligned(); + if d.DepthBoundsTestEnable.as_bool() { + static SEEN: std::sync::atomic::AtomicU64 = + std::sync::atomic::AtomicU64::new(0); + if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + tracing::warn!( + "a pipeline enables the depth bounds test, which its host pipeline leaves out: its draws pass at every depth" + ); + } + } self.depth = D3D12_DEPTH_STENCIL_DESC { DepthEnable: d.DepthEnable, DepthWriteMask: d.DepthWriteMask, @@ -156,7 +165,9 @@ impl GraphicsState { 15 => { self.targets = data.cast::().read_unaligned(); for f in &mut self.targets.RTFormats { - f.0 = crate::resource::pc_format(f.0 as u32) as i32; + f.0 = crate::resource::target_format(crate::resource::pc_format( + f.0 as u32, + )) as i32; } } 16 => { @@ -243,6 +254,17 @@ pub(crate) struct Input { const RECTANGLES: i32 = 19; const QUADS: i32 = 32; +/// Whether the title's root SRVs are bound as one-view tables of the +/// buffer's host copy, whose reads past its end return zeros, rather than +/// as root descriptors, which have no size: a mesh shader's vertex fetch +/// has no record limit, and a read past the copy reaches whatever the host +/// placed after it (memory it has freed: the device is removed, upstream +/// PR #493). `VICTORY_ROOT_SRV_DIRECT=1` goes back to root descriptors. +pub(crate) fn bounded_root_srvs() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_ROOT_SRV_DIRECT").is_none()) +} + /// One stage of a host pipeline and where its bindings go. pub(crate) struct Stage { pub(crate) shader: Arc, @@ -251,6 +273,9 @@ pub(crate) struct Stage { /// Root parameters of its root views: (title root parameter, ours). pub(crate) root_cbvs: Vec<(u8, u32)>, pub(crate) root_srvs: Vec<(u8, u32)>, + /// Root UAVs: one-view tables like the SRVs (or root descriptors with + /// `VICTORY_ROOT_SRV_DIRECT=1`). + pub(crate) root_uavs: Vec<(u8, u32)>, } impl Stage { @@ -273,8 +298,15 @@ pub(crate) struct HostPipeline { /// The vertex buffer slots it reads (bit per slot). pub(crate) slots: u32, pub(crate) inputs: Vec, + /// Has the geometry stage that completes the console's rectangles + /// (`victory_shader::emit::rect_list_gs`): its rectangle draws go out + /// as the title gives them, three vertices a rectangle. + pub(crate) rects: bool, /// Its shaders, for reports of slow submissions. pub(crate) name: String, + /// Its depth, stencil, cull and blend state in short, for the frame + /// listing (empty for compute). + pub(crate) state: String, } /// Logs a pipeline that gets no host pipeline, once per reason. @@ -292,6 +324,9 @@ impl HostPipeline { /// A host pipeline for vertex and pixel shaders with the graphics /// state `g`, or for one compute shader. pub(crate) fn new(shaders: &[Arc], g: Option<&GraphicsState>) -> Option { + // For the report when the host device is removed: what this thread + // has in the library from here on. + super::library::label(format!("{shaders:?}")); let find = |stage| shaders.iter().find(|s| s.stage == stage); let compute = match shaders { [cs] if cs.stage == "compute" => Some(cs), @@ -330,6 +365,9 @@ impl HostPipeline { // The root signature the translated shaders' bindings define. let mut params: Vec = Vec::new(); + // The ranges table parameters point at, alive until the root + // signature is made. + let mut ranges: Vec> = Vec::new(); let mut samplers = Vec::new(); let mut bound = Vec::new(); for &(shader, visibility) in &stages { @@ -339,6 +377,7 @@ impl HostPipeline { user_data: None, root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), }; let dwords = t.user_data_dwords(); if dwords > 0 { @@ -366,8 +405,55 @@ impl HostPipeline { D3D12_ROOT_PARAMETER_TYPE_SRV, &mut stage.root_srvs, ), + ( + &t.root_uavs, + D3D12_ROOT_PARAMETER_TYPE_UAV, + &mut stage.root_uavs, + ), ] { for &slot in slots { + let uav = kind == D3D12_ROOT_PARAMETER_TYPE_UAV; + // Ours, not the title's, stay root descriptors: the + // table of strides, the directory of title memory by + // address and its fault notes. + let ours = if uav { + slot == victory_shader::emit::SLOT_FAULTS + } else { + slot == victory_shader::emit::SLOT_STRIDES + || slot == victory_shader::emit::SLOT_MEMORY + }; + if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() { + // A one-view table: the view's size bounds the + // reads (and a root UAV's writes), which a root + // descriptor leaves unbounded. + // (Our own table of strides stays a descriptor.) + ranges.push(Box::new(D3D12_DESCRIPTOR_RANGE1 { + RangeType: if uav { + D3D12_DESCRIPTOR_RANGE_TYPE_UAV + } else { + D3D12_DESCRIPTOR_RANGE_TYPE_SRV + }, + NumDescriptors: 1, + BaseShaderRegister: u32::from(slot), + RegisterSpace: ROOT_CBV_SPACE, + Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE + | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, + OffsetInDescriptorsFromTableStart: 0, + })); + let range: *const D3D12_DESCRIPTOR_RANGE1 = &**ranges.last()?; + out.push((slot, params.len() as u32)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 { + NumDescriptorRanges: 1, + pDescriptorRanges: range, + }, + }, + ShaderVisibility: visibility, + }); + continue; + } out.push((slot, params.len() as u32)); params.push(D3D12_ROOT_PARAMETER1 { ParameterType: kind, @@ -451,6 +537,8 @@ impl HostPipeline { name: format!("{shaders:?}"), slots: 0, inputs: Vec::new(), + rects: false, + state: String::new(), }); } let Some(g) = g else { @@ -458,8 +546,12 @@ impl HostPipeline { }; let state = g.describe(); if mesh.is_some() { + // "triangles": the stream names its topology since it did not + // load from the library without one (see `mesh_pipeline`); a + // new name keeps such entries, stored before, from being + // looked up again. let name = super::library::name( - "mesh", + "mesh triangles", &root_blob, &[&code_bytes(&code(0)), &code_bytes(&code(1))], &state, @@ -483,14 +575,35 @@ impl HostPipeline { name: format!("{shaders:?}"), slots: 0, inputs: Vec::new(), + rects: false, + state: String::new(), }); } - let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // A pipeline the title makes for rectangles gets a geometry stage + // that completes each one from the three vertices the vertex + // shader made. Without it (refused here or by the host) the draws + // fall back on what `draw` does for rectangles. + let mut rect_gs = None; + if g.topology.0 == RECTANGLES { + let ps = stages.get(1).and_then(|(s, _)| s.translated()); + let vs = &stages[0].0.translated()?.host.dxil; + match victory_shader::emit::rect_list_gs(vs, ps.map(|t| &t.host.dxil[..])) { + Ok(gs) => rect_gs = Some(gs), + Err(e) => tracing::warn!(error = %e, ?shaders, "no rectangle geometry stage"), + } + } + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { // SAFETY: a borrowed pointer the description never releases. pRootSignature: unsafe { std::mem::transmute_copy(&root) }, VS: code(0), PS: code(1), + GS: rect_gs.as_ref().map_or(D3D12_SHADER_BYTECODE::default(), |gs| { + D3D12_SHADER_BYTECODE { + pShaderBytecode: gs.as_ptr().cast(), + BytecodeLength: gs.len(), + } + }), BlendState: g.blend, SampleMask: g.sample_mask, RasterizerState: g.rasterizer, @@ -512,19 +625,40 @@ impl HostPipeline { SampleDesc: g.samples, ..Default::default() }; - let name = super::library::name( - "graphics", - &root_blob, - &[&code_bytes(&code(0)), &code_bytes(&code(1))], - &state, - ); - let made = super::library::pipeline( - &name, - // SAFETY: the description points at live data. - |library, name| unsafe { library.LoadGraphicsPipeline(name, &desc) }, - // SAFETY: as above. - || unsafe { host.device.CreateGraphicsPipelineState(&desc) }, - ); + // A pipeline with the geometry stage has a name of its own in the + // library; the others keep theirs. + let name = |gs: Option<&Vec>| match gs { + Some(gs) => super::library::name( + "graphics rectangles", + &root_blob, + &[&code_bytes(&code(0)), &code_bytes(&code(1)), &gs[..]], + &state, + ), + None => super::library::name( + "graphics", + &root_blob, + &[&code_bytes(&code(0)), &code_bytes(&code(1))], + &state, + ), + }; + let make = |desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, name: &str| { + super::library::pipeline( + name, + // SAFETY: the description points at live data. + |library, name| unsafe { library.LoadGraphicsPipeline(name, desc) }, + // SAFETY: as above. + || unsafe { host.device.CreateGraphicsPipelineState(desc) }, + ) + }; + let mut made = make(&desc, &name(rect_gs.as_ref())); + if made.is_err() && rect_gs.is_some() { + // The host refused the geometry stage: once more without it. + tracing::warn!(?shaders, "host pipeline refused with the rectangle geometry stage"); + host.log_messages(); + desc.GS = D3D12_SHADER_BYTECODE::default(); + rect_gs = None; + made = make(&desc, &name(None)); + } let pso = match made { Ok(pso) => pso, Err(e) => { @@ -553,12 +687,49 @@ impl HostPipeline { name: format!("{shaders:?}"), slots: g.slots(), inputs: g.elements(), + rects: rect_gs.is_some(), + state: { + let (d, r, b) = (&g.depth, &g.rasterizer, &g.blend.RenderTarget[0]); + let face = |f: &D3D12_DEPTH_STENCILOP_DESC| { + format!( + "fail {} depth-fail {} pass {} func {}", + f.StencilFailOp.0, f.StencilDepthFailOp.0, f.StencilPassOp.0, f.StencilFunc.0 + ) + }; + format!( + "depth {} write {} func {}; stencil {} read {:#x} write {:#x} front [{}] back [{}]; cull {} front-ccw {}; blend {} src {} dst {} op {} mask {:#x}", + d.DepthEnable.as_bool(), + d.DepthWriteMask.0, + d.DepthFunc.0, + d.StencilEnable.as_bool(), + d.StencilReadMask, + d.StencilWriteMask, + face(&d.FrontFace), + face(&d.BackFace), + r.CullMode.0, + r.FrontCounterClockwise.as_bool(), + b.BlendEnable.as_bool(), + b.SrcBlend.0, + b.DestBlend.0, + b.BlendOp.0, + b.RenderTargetWriteMask + ) + }, }) } } /// A mesh pipeline from the title's graphics state: the pipeline-state -/// stream form (no input layout or topology). +/// stream form (no input layout). +/// +/// The stream names a triangle topology, which D3D12 does not need for a +/// mesh shader: without it the pipeline library refuses to load a stored +/// pipeline with the very stream it was made from (`E_INVALIDARG`; debug +/// layer message 972, "does not match the one used to create the PSO"), so +/// every mesh pipeline was compiled again, and its store then refused (970, +/// "already exists"). The translation makes triangle mesh shaders only +/// (`mesh_prologue` refuses others), and the debug layer wants the two to +/// agree (1323). fn mesh_pipeline( device: &ID3D12Device, root: &ID3D12RootSignature, @@ -583,6 +754,7 @@ fn mesh_pipeline( targets: Sub, dsv: Sub, samples: Sub, + topology: Sub, } let mut stream = Stream { root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), @@ -595,6 +767,10 @@ fn mesh_pipeline( targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets), dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format), samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples), + topology: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + ), }; let desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: size_of::(), @@ -665,3 +841,84 @@ fn root_signature( Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec())) } } + +#[cfg(test)] +mod tests { + use std::path::{Path, PathBuf}; + use std::sync::atomic::Ordering; + + use super::*; + + /// A triangle mesh shader of our own and a pixel shader for it. + const MS: &str = "struct V { float4 p : SV_Position; }; + [outputtopology(\"triangle\")] [numthreads(1, 1, 1)] + void main(out vertices V v[3], out indices uint3 t[1]) { + SetMeshOutputCounts(3, 1); + v[0].p = float4(0, 0, 0, 1); + v[1].p = float4(1, 0, 0, 1); + v[2].p = float4(0, 1, 0, 1); + t[0] = uint3(0, 1, 2); + }"; + const PS: &str = "float4 main() : SV_Target { return 1; }"; + + /// The PC `dxc.exe` (`VICTORY_PC_DXC`, else the newest Windows SDK's). + fn dxc() -> Option { + let dxc = match std::env::var_os("VICTORY_PC_DXC") { + Some(p) => PathBuf::from(p), + None => victory_shader::emit::validator::Validator::default_path()? + .with_file_name("dxc.exe"), + }; + dxc.exists().then_some(dxc) + } + + fn compile(dxc: &Path, dir: &Path, src: &str, profile: &str) -> Vec { + let (hlsl, out) = ( + dir.join(format!("{profile}.hlsl")), + dir.join(format!("{profile}.dxil")), + ); + std::fs::write(&hlsl, src).unwrap(); + let status = std::process::Command::new(dxc) + .args(["-nologo", "-T", profile, "-E", "main", "-Fo"]) + .arg(&out) + .arg(&hlsl) + .status() + .unwrap(); + assert!(status.success(), "dxc failed for {profile}"); + std::fs::read(out).unwrap() + } + + fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE { + D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + } + } + + /// A mesh pipeline made once is loaded from the library the next time, + /// not compiled again (a stream without a topology never loads). + #[test] + fn a_mesh_pipeline_loads_from_the_library() { + let Some(host) = host() else { + return; // no host GPU here + }; + let Some(dxc) = dxc() else { + eprintln!("no PC dxc.exe; skipped"); + return; + }; + let dir = tempfile::tempdir().unwrap(); + let ms = compile(&dxc, dir.path(), MS, "ms_6_5"); + let ps = compile(&dxc, dir.path(), PS, "ps_6_5"); + let (root, root_blob) = root_signature(&host.device, &[], &[], false).unwrap(); + let mut g = GraphicsState::default(); + g.targets.NumRenderTargets = 1; + g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let name = super::super::library::name("mesh test", &root_blob, &[&ms, &ps], &g.describe()); + mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, &name).expect("made"); + let loaded = super::super::library::LOADED.load(Ordering::Relaxed); + mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, &name).expect("made again"); + assert!( + super::super::library::LOADED.load(Ordering::Relaxed) > loaded, + "the mesh pipeline was compiled again instead of loaded from the library" + ); + } +} diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index aa611e2..6f122dd 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -12,13 +12,45 @@ //! graphics state); the next run hands those to the workers at //! creation, during loading. //! -//! All library calls are serialised: the interface does not promise that -//! stores, loads and serialising may overlap. +//! Library calls overlap: the host documents the library as safe to use +//! from several threads ("The pipeline library is thread-safe to use, and +//! will internally synchronize as necessary", `CreatePipelineLibrary`, +//! Thread Safety), with one exception kept here: two loads of the same +//! pipeline are made one after the other ([`same_name`]). Under one lock of +//! ours for every call, the eight workers made pipelines one at a time: +//! 87 to 96 of 110 looks at each worker found it waiting for that lock +//! (run 49), and an earlier run's 2,300 pipelines, all in the library, were +//! still being loaded 46 s into the opening cutscene. +//! `VICTORY_LIBRARY_LOCK=1`: one call at a time, as before. +//! +//! The library's file is mapped, not read into memory ([`Blob`]): the host +//! keeps pointing into the bytes it was made from for as long as it lives, +//! and read into a buffer they were 1,352 MB of the process's own memory +//! for the whole run (run 60), all of it in physical memory. Mapped, the +//! pages are the file's: only those the host reads are in memory, and the +//! system can drop them without writing them anywhere. A save writes the +//! new library through a mapping of the new file in the same way (a buffer +//! of the library's size was made, filled and written out at each save). +//! `VICTORY_LIBRARY_MAP=0`: read and written through buffers, as before. +//! +//! The mapped file's handle stays open for as long as the mapping lives +//! ([`holds`]). A save renames the new library over the file this run has +//! mapped, and with the handle closed Windows then gives up the old file's +//! contents: every page of the mapping that is not in memory at that +//! moment, or leaves memory later (the trim below, or Windows taking pages +//! back), reads as zeros from then on. The host's library reads such pages +//! as stored pipelines; the driver, handed a pipeline of zeros, removes the +//! device with DXGI_ERROR_DRIVER_INTERNAL_ERROR (runs 72, 73 and 82, each +//! within 5 ms of the first library call after a save and a trim; and the +//! library run 77 saved from such pages was refused by run 78). Measured +//! with a 64 MB file written past the system's cache, mapped and replaced: +//! 16,352 of 16,384 pages read zeros with the handle closed, none with it +//! open (the test below). `VICTORY_LIBRARY_HANDLE=0`: closed, as before. use std::collections::HashSet; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Mutex, OnceLock}; +use std::sync::{Mutex, MutexGuard, OnceLock, RwLock}; use windows::Win32::Graphics::Direct3D12::*; use windows::core::{HSTRING, Interface, PCWSTR}; @@ -35,64 +67,430 @@ pub fn use_pipeline_cache(dir: PathBuf) { pub(crate) static MADE: AtomicU64 = AtomicU64::new(0); pub(crate) static LOADED: AtomicU64 = AtomicU64::new(0); pub(crate) static EARLY: AtomicU64 = AtomicU64::new(0); +/// For the memory lines: the bytes of the library's file, kept in memory +/// while the library lives, and the bytes the last save wrote (a buffer of +/// that size is made, filled and written every time pipelines were added, +/// at most every 20 s). +pub(crate) static BLOB: AtomicU64 = AtomicU64::new(0); +pub(crate) static SAVED: AtomicU64 = AtomicU64::new(0); + +/// Whether the library's file is mapped ([`Blob`]) and saved through a +/// mapping. On by default; `VICTORY_LIBRARY_MAP=0` uses buffers, as before. +fn mapped() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_MAP").is_none_or(|v| v != "0")) +} + +/// Whether the mapped library file's handle is kept open while it is +/// mapped (see the module's notes: without it a save in the same run turns +/// the mapping's pages into zeros as they leave memory). On by default; +/// `VICTORY_LIBRARY_HANDLE=0` closes it after mapping, as before. +fn holds() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_HANDLE").is_none_or(|v| v != "0")) +} + +/// A whole file mapped into memory: read-only (the library's file) or +/// writable (the file a save fills). Unmapped when dropped. +struct Mapped { + at: windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS, + len: usize, + /// The file, for a mapping made by [`Mapped::open`] ([`holds`]): open + /// until after the view is unmapped, so that the file a rename took + /// the name from keeps its contents for the view. + _file: Option, +} + +impl Mapped { + /// Maps `file` (`len` bytes, not zero) for reading, or for reading and + /// writing. + fn map(file: &std::fs::File, len: usize, write: bool) -> Option { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_READ, FILE_MAP_WRITE, MapViewOfFile, PAGE_READONLY, PAGE_READWRITE, + }; + if len == 0 { + return None; + } + // SAFETY: a file we hold open; the view keeps the file's pages + // after the mapping object and the file are closed. + let at = unsafe { + let mapping = CreateFileMappingW( + file.as_raw_handle(), + std::ptr::null(), + if write { PAGE_READWRITE } else { PAGE_READONLY }, + 0, + 0, + std::ptr::null(), + ); + if mapping.is_null() { + return None; + } + let at = MapViewOfFile(mapping, if write { FILE_MAP_WRITE } else { FILE_MAP_READ }, 0, 0, 0); + CloseHandle(mapping); + at + }; + (!at.Value.is_null()).then_some(Mapped { at, len, _file: None }) + } + + /// The file at `path`, mapped for reading; `None` if it is not there, + /// is empty or cannot be mapped. + fn open(path: &std::path::Path) -> Option { + Mapped::open_holding(path, holds()) + } + + /// As [`Mapped::open`]; `hold` says whether the file stays open with + /// the mapping. + fn open_holding(path: &std::path::Path, hold: bool) -> Option { + // Opened as the standard library opens a file to read: others may + // read, write, rename and delete it meanwhile, so a save still + // renames the new library over this one. + let file = std::fs::File::open(path).ok()?; + let len = usize::try_from(file.metadata().ok()?.len()).ok()?; + let mut mapped = Mapped::map(&file, len, false)?; + if hold { + mapped._file = Some(file); + } + Some(mapped) + } + + /// A new file of `len` bytes at `path` (replacing what is there), + /// mapped for writing. + fn create(path: &std::path::Path, len: usize) -> Option { + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(path) + .ok()?; + file.set_len(len as u64).ok()?; + Mapped::map(&file, len, true) + } + + fn bytes(&self) -> &[u8] { + // SAFETY: the view holds `len` readable bytes until dropped. + unsafe { std::slice::from_raw_parts(self.at.Value.cast(), self.len) } + } + + /// Only for a view made by [`Mapped::create`]. + fn bytes_mut(&mut self) -> &mut [u8] { + // SAFETY: a writable view of `len` bytes, ours alone. + unsafe { std::slice::from_raw_parts_mut(self.at.Value.cast(), self.len) } + } +} + +impl Drop for Mapped { + fn drop(&mut self) { + // SAFETY: our view. + unsafe { windows_sys::Win32::System::Memory::UnmapViewOfFile(self.at) }; + } +} + +/// The bytes a library is made from: the host reads them for as long as +/// the library lives, so they are kept beside it. +enum Blob { + /// No file (an empty library). + None, + /// The file read into memory (`VICTORY_LIBRARY_MAP=0`, tests, or a file + /// that could not be mapped). + Held(Vec), + /// The file itself, mapped. + Mapped(Mapped), +} + +impl Blob { + /// The library file in `dir`: a library a save left beside it + /// ([`NEXT_FILE`]) takes its place first. + fn of(dir: &std::path::Path) -> Blob { + let path = dir.join(LIBRARY_FILE); + let next = dir.join(NEXT_FILE); + if next.exists() && std::fs::rename(&next, &path).is_err() { + tracing::warn!("the host pipeline library saved last could not take the old one's place"); + } + if mapped() + && let Some(file) = Mapped::open(&path) + { + return Blob::Mapped(file); + } + match std::fs::read(&path) { + Ok(bytes) if !bytes.is_empty() => Blob::Held(bytes), + _ => Blob::None, + } + } + + fn bytes(&self) -> &[u8] { + match self { + Blob::None => &[], + Blob::Held(bytes) => bytes, + Blob::Mapped(file) => file.bytes(), + } + } +} + +/// The mapped library file's view (address, bytes; 0: not mapped), when a +/// pipeline was last loaded from the library (`crate::host::now_ms`), and +/// whether the view's pages were let go since ([`trim`]). +static VIEW: [std::sync::atomic::AtomicUsize; 2] = [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; +static LOADED_AT: AtomicU64 = AtomicU64::new(0); +static TRIMMED: AtomicBool = AtomicBool::new(false); +/// The bytes of the view let go so far, for the memory line. +pub(crate) static TRIMMED_BYTES: AtomicU64 = AtomicU64::new(0); +/// When the view's pages were last let go (`crate::host::now_ms`), and how +/// often and when a save of this run last renamed a new library over the +/// mapped file: for [`removal_note`]. +static TRIMMED_AT: AtomicU64 = AtomicU64::new(0); +static REPLACED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// The library calls running now: thread, what (load, make, store, +/// serialise), the pipeline, and since when (`crate::host::now_us`). +static CALLS: Mutex> = Mutex::new(Vec::new()); + +thread_local! { + /// The pipeline this thread is making (its shaders), for [`CALLS`]. + static LABEL: std::cell::RefCell = const { std::cell::RefCell::new(String::new()) }; +} + +/// Names the pipeline this thread makes next. +pub(crate) fn label(text: String) { + LABEL.with(|l| *l.borrow_mut() = text); +} + +/// A library call of this thread, listed in [`CALLS`] until dropped. +struct Call(u32, u64); + +fn call(what: &'static str, name: &str) -> Call { + let (thread, since) = (crate::host::thread_id(), crate::host::now_us()); + let label = LABEL.with(|l| l.borrow().clone()); + CALLS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((thread, what, format!("{name} {label}"), since)); + Call(thread, since) +} + +impl Drop for Call { + fn drop(&mut self) { + CALLS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|c| (c.0, c.3) != (self.0, self.1)); + } +} + +/// For the report when the host device is removed: the library calls +/// running at that moment, whether this run replaced the mapped file and +/// let its pages go, and how many pages of the mapping read as zeros now. +/// A library holds no page of zeros (the 259 MB one of run 83 has no run of +/// 2,048 zero bytes): each such page is one whose contents were lost (see +/// the module's notes), and a pipeline stored there is what the driver was +/// handed. +pub(crate) fn removal_note() -> String { + use std::fmt::Write; + let now = crate::host::now_us(); + let mut text = String::from("pipeline library: "); + { + let calls = CALLS.lock().unwrap_or_else(|e| e.into_inner()); + if calls.is_empty() { + text.push_str("no call running"); + } + for (i, (thread, what, name, since)) in calls.iter().enumerate() { + let _ = write!( + text, + "{}{what} of {name} running for {:.1} ms on thread {thread}", + if i == 0 { "" } else { ", " }, + now.saturating_sub(*since) as f64 / 1000.0 + ); + } + } + let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed)); + if at == 0 { + text.push_str("; its file is not mapped"); + return text; + } + let ago = |ms: u64| crate::host::now_ms().saturating_sub(ms) as f64 / 1000.0; + let _ = write!( + text, + "; its file is mapped ({len} bytes), the handle {}", + if holds() { "kept open" } else { "closed (VICTORY_LIBRARY_HANDLE=0)" } + ); + match REPLACED[0].load(Ordering::Relaxed) { + 0 => text.push_str("; this run has not replaced the file"), + n => { + let _ = write!( + text, + "; this run replaced the file under the mapping {n} times, last {:.1} s ago", + ago(REPLACED[1].load(Ordering::Relaxed)) + ); + } + } + if TRIMMED_BYTES.load(Ordering::Relaxed) > 0 { + let _ = write!(text, "; its pages were last let go {:.1} s ago", ago(TRIMMED_AT.load(Ordering::Relaxed))); + } + // Within two seconds: pages not in memory come from the disk. + let started = std::time::Instant::now(); + // SAFETY: the view lives as long as the library, which is never dropped. + let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, len) }; + let (mut zero, mut looked, mut first) = (0u64, 0u64, None); + for (n, page) in bytes.chunks(4096).enumerate() { + if n % 4096 == 0 && started.elapsed() > std::time::Duration::from_secs(2) { + break; + } + looked += 1; + if page.iter().all(|&b| b == 0) { + zero += 1; + if first.is_none() { + first = Some(n); + } + } + } + let _ = write!(text, "; {zero} of the {looked} pages looked at read as zeros now"); + if let Some(first) = first { + let _ = write!(text, " (the first is page {first}): the library's contents were lost there"); + } + text +} + +/// Lets the mapped library file's pages go from the process's memory once +/// no pipeline has been loaded for ten seconds. The host reads nearly the +/// whole file while the early pipelines load (run 65: all 1,490 MB of it +/// were in the process's memory a minute in, and 1,300 MB still at the +/// end, on a PC with 2 GB free); after that it reads the file again only +/// when a new pipeline loads. Pages let go stay in Windows' file cache +/// while nothing else wants the memory, and come back on the next read. +/// Called once a second by the sweep; does its work on a thread of its own +/// (hundreds of thousands of pages), once after each burst of loads. +/// `VICTORY_LIBRARY_TRIM=0`: the pages stay until Windows takes them. +pub(crate) fn trim() { + const QUIET_MS: u64 = 10_000; + static ON: OnceLock = OnceLock::new(); + let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed)); + if at == 0 + || TRIMMED.load(Ordering::Relaxed) + || crate::host::now_ms() < LOADED_AT.load(Ordering::Relaxed) + QUIET_MS + || !*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_TRIM").is_none_or(|v| v != "0")) + || TRIMMED.swap(true, Ordering::Relaxed) + { + return; + } + let work = move || { + // SAFETY: the view lives as long as the library, which is never + // dropped. Unlocking pages that are not locked fails, as expected, + // and takes them out of the working set: the documented way to let + // pages of a mapped file go. + unsafe { windows_sys::Win32::System::Memory::VirtualUnlock(at as *const _, len) }; + TRIMMED_BYTES.fetch_add(len as u64, Ordering::Relaxed); + TRIMMED_AT.store(crate::host::now_ms(), Ordering::Relaxed); + crate::host::trail(|| format!("pipeline library: the mapped file's pages let go from memory ({len} bytes)")); + }; + if std::thread::Builder::new().name("victory-library-trim".into()).spawn(work).is_err() { + TRIMMED.store(false, Ordering::Relaxed); + } +} struct Library { library: ID3D12PipelineLibrary1, /// The blob the library was made from: it must outlive the library. - _blob: Vec, + _blob: Blob, /// Pipelines stored since the last save. - added: u64, + added: AtomicU64, + /// Stores share it and a save takes it alone: the size the library + /// asks for must still be its size when it is written out. + saving: RwLock<()>, } -// SAFETY: D3D12 objects are free-threaded; every call is made under the -// mutex that holds the library. +// SAFETY: D3D12 objects are free-threaded, and the library synchronises +// its own calls (see the module's notes); what it does not, two loads of +// one name, is serialised by `same_name`. unsafe impl Send for Library {} +// SAFETY: as above; the other fields are an atomic and a lock. +unsafe impl Sync for Library {} + +/// Held by a load of the pipeline named `name`: loads of the same name +/// wait for each other (the host's one exception to the library's thread +/// safety: such a load may change that pipeline's entry). Names share 64 +/// locks, so two different names seldom wait. +fn same_name(name: &str) -> MutexGuard<'static, ()> { + static LOADING: [Mutex<()>; 64] = [const { Mutex::new(()) }; 64]; + let at = name.bytes().fold(0usize, |h, b| h.wrapping_mul(31).wrapping_add(usize::from(b))); + LOADING[at % LOADING.len()].lock().unwrap_or_else(|e| e.into_inner()) +} + +/// With `VICTORY_LIBRARY_LOCK=1`: held by every library call, as before. +fn one_call() -> Option> { + static ON: OnceLock = OnceLock::new(); + static CALLING: Mutex<()> = Mutex::new(()); + ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_LOCK").is_some_and(|v| v == "1")) + .then(|| CALLING.lock().unwrap_or_else(|e| e.into_inner())) +} const LIBRARY_FILE: &str = "host-pipelines.bin"; +/// A saved library that could not replace [`LIBRARY_FILE`] while this run +/// had it mapped (a system that refuses to replace a mapped file): the next +/// start renames it over the library first ([`Blob::of`]). +const NEXT_FILE: &str = "host-pipelines.next"; const EARLY_FILE: &str = "early-pipelines.txt"; /// Title pipelines listed for an early start, at most. const EARLY_MAX: usize = 8192; -fn library() -> Option<&'static Mutex> { - static LIBRARY: OnceLock>> = OnceLock::new(); +fn library() -> Option<&'static Library> { + static LIBRARY: OnceLock> = OnceLock::new(); LIBRARY .get_or_init(|| { let device = crate::host::host()?.device.cast::().ok()?; - let blob = DIR - .get() - .and_then(|d| std::fs::read(d.join(LIBRARY_FILE)).ok()) - .unwrap_or_default(); + let blob = DIR.get().map_or(Blob::None, |d| Blob::of(d)); let library = open(&device, blob); if library.is_none() { tracing::warn!("no host pipeline library: pipelines are not kept"); } - library.map(Mutex::new) + library }) .as_ref() } /// The library in `blob`, or an empty one if the host rejects the blob (an /// adapter or driver change, damage). -fn open(device: &ID3D12Device1, blob: Vec) -> Option { +fn open(device: &ID3D12Device1, blob: Blob) -> Option { let make = |bytes: &[u8]| -> windows::core::Result { // SAFETY: the bytes outlive the library (kept beside it). unsafe { device.CreatePipelineLibrary::(bytes)?.cast() } }; - if !blob.is_empty() { - match make(&blob) { + if !blob.bytes().is_empty() { + match make(blob.bytes()) { Ok(library) => { - tracing::info!(bytes = blob.len(), "host pipeline library loaded"); - return Some(Library { library, _blob: blob, added: 0 }); + let bytes = blob.bytes().len(); + BLOB.store(bytes as u64, Ordering::Relaxed); + tracing::info!(bytes, mapped = matches!(blob, Blob::Mapped(_)), "host pipeline library loaded"); + if let Blob::Mapped(file) = &blob { + VIEW[1].store(file.len, Ordering::Relaxed); + VIEW[0].store(file.at.Value as usize, Ordering::Relaxed); + LOADED_AT.store(crate::host::now_ms(), Ordering::Relaxed); + } + return Some(Library { + library, + _blob: blob, + added: AtomicU64::new(0), + saving: RwLock::new(()), + }); } Err(e) => tracing::info!(error = %e, "host pipeline library rejected; starting an empty one"), } } else { tracing::info!("no host pipeline library yet; starting an empty one"); } + // The rejected bytes are let go (a mapped file is unmapped) before the + // empty library is made: nothing reads them any more. + drop(blob); let library = make(&[]).ok()?; - Some(Library { library, _blob: Vec::new(), added: 0 }) + Some(Library { + library, + _blob: Blob::None, + added: AtomicU64::new(0), + saving: RwLock::new(()), + }) } /// A pipeline's name in the library: the hash of what its host @@ -118,18 +516,47 @@ pub(crate) fn pipeline( MADE.fetch_add(1, Ordering::Relaxed); return create(); }; - if let Ok(pso) = load(&library.lock().unwrap_or_else(|e| e.into_inner()).library, PCWSTR(wide.as_ptr())) { - LOADED.fetch_add(1, Ordering::Relaxed); - return Ok(pso); - } - // Compiled outside the lock: compiles take up to seconds. - let pso = create()?; + let began = std::time::Instant::now(); + let loaded = { + let _all = one_call(); + let _one = same_name(name); + let _call = call("load", name); + load(&library.library, PCWSTR(wide.as_ptr())) + }; + // The load read the library's file (see `trim`). + LOADED_AT.store(crate::host::now_ms(), Ordering::Relaxed); + TRIMMED.store(false, Ordering::Relaxed); + let refused = match loaded { + Ok(pso) => { + LOADED.fetch_add(1, Ordering::Relaxed); + crate::host::trail(|| { + let label = LABEL.with(|l| l.borrow().clone()); + format!("pipeline library: loaded {label} in {:.1} ms", began.elapsed().as_secs_f64() * 1e3) + }); + return Ok(pso); + } + Err(e) => e, + }; + // Compiled outside any lock: compiles take up to seconds. + let pso = { + let _call = call("make", name); + create()? + }; MADE.fetch_add(1, Ordering::Relaxed); - let mut l = library.lock().unwrap_or_else(|e| e.into_inner()); + crate::host::trail(|| { + let label = LABEL.with(|l| l.borrow().clone()); + format!( + "pipeline library: made {label} in {:.1} ms (the library did not load it: {refused})", + began.elapsed().as_secs_f64() * 1e3 + ) + }); + let _all = one_call(); + let _stores = library.saving.read().unwrap_or_else(|e| e.into_inner()); + let _call = call("store", name); // SAFETY: a live pipeline; a name already stored (a description that // differs) is refused, which leaves the library as it was. - if unsafe { l.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() { - l.added += 1; + if unsafe { library.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() { + library.added.fetch_add(1, Ordering::Relaxed); } Ok(pso) } @@ -147,34 +574,60 @@ pub(crate) fn save(now: bool) { } *last = Some(std::time::Instant::now()); } - let blob = { - let mut l = library.lock().unwrap_or_else(|e| e.into_inner()); - if l.added == 0 && !USED_CHANGED.swap(false, Ordering::Relaxed) { + if let Err(e) = std::fs::create_dir_all(dir) { + tracing::warn!(error = %e, "host pipeline library not saved"); + return; + } + let tmp = dir.join(LIBRARY_FILE).with_extension("tmp"); + // The bytes of the library written to `tmp`; 0 when no pipeline was + // added: the library on disk is then what it was, and only the early + // list is written (a title pipeline first drawn with wrote all 1,352 MB + // of the library again: run 60's second save). + let bytes = { + let _all = one_call(); + // No store between asking the size and writing; loads go on. + let _alone = library.saving.write().unwrap_or_else(|e| e.into_inner()); + let added = library.added.load(Ordering::Relaxed); + if !USED_CHANGED.swap(false, Ordering::Relaxed) && added == 0 { return; } - // SAFETY: a buffer of the size the library asks for. - let bytes = unsafe { - let mut bytes = vec![0u8; l.library.GetSerializedSize()]; - l.library.Serialize(&mut bytes).map(|()| bytes) - }; - match bytes { - Ok(bytes) => { - l.added = 0; - bytes - } - Err(e) => { + if added == 0 { + 0 + } else { + // SAFETY: a plain query. + let size = unsafe { library.library.GetSerializedSize() }; + let _call = call("serialise", "the whole library"); + if let Err(e) = serialise(&library.library, &tmp, size) { tracing::warn!(error = %e, "host pipeline library not serialised"); + let _ = std::fs::remove_file(&tmp); return; } + library.added.store(0, Ordering::Relaxed); + SAVED.store(size as u64, Ordering::Relaxed); + size } }; let used: Vec = USED.lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().cloned().collect(); - let written = std::fs::create_dir_all(dir) - .and_then(|()| write_atomically(&dir.join(LIBRARY_FILE), &blob)) + let library_written = if bytes > 0 { replace_library(dir, &tmp) } else { Ok(()) }; + if bytes > 0 && library_written.is_ok() { + // In place unless the system refused and the new one waits beside it. + let in_place = !dir.join(NEXT_FILE).exists(); + if in_place && VIEW[0].load(Ordering::Relaxed) != 0 { + REPLACED[1].store(crate::host::now_ms(), Ordering::Relaxed); + REPLACED[0].fetch_add(1, Ordering::Relaxed); + } + crate::host::trail(|| { + format!( + "pipeline library: saved {bytes} bytes, {}", + if in_place { "renamed over the library's file" } else { "left beside the library's file for the next start" } + ) + }); + } + let written = library_written .and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes())); match written { Ok(()) => tracing::info!( - bytes = blob.len(), + bytes, early = used.len(), made = MADE.load(Ordering::Relaxed), loaded = LOADED.load(Ordering::Relaxed), @@ -185,6 +638,35 @@ pub(crate) fn save(now: bool) { } } +/// Writes the library's `size` serialised bytes to the file `tmp`: through +/// a mapping of that file, so that the bytes are the file's pages and not +/// 1.3 GB more of the process's own memory for the seconds a save takes; +/// through a buffer where the file cannot be mapped (and with +/// `VICTORY_LIBRARY_MAP=0`). +fn serialise(library: &ID3D12PipelineLibrary1, tmp: &std::path::Path, size: usize) -> std::io::Result<()> { + let failed = |e: windows::core::Error| std::io::Error::other(e.to_string()); + if mapped() + && let Some(mut file) = Mapped::create(tmp, size) + { + // SAFETY: a buffer of the size the library asks for. + return unsafe { library.Serialize(file.bytes_mut()) }.map_err(failed); + } + let mut bytes = vec![0u8; size]; + // SAFETY: a buffer of the size the library asks for. + unsafe { library.Serialize(&mut bytes) }.map_err(failed)?; + std::fs::write(tmp, &bytes) +} + +/// Renames the written library `tmp` over the library's file in `dir`. This +/// run may have that file mapped: Windows 11 replaces a mapped file, and +/// the mapping goes on reading the old one for as long as a handle on it +/// is open ([`holds`]; with none, only the pages in memory at that moment +/// stay: the rest read as zeros). Where a system refuses, the new library +/// is left beside it as [`NEXT_FILE`] for the next start. +fn replace_library(dir: &std::path::Path, tmp: &std::path::Path) -> std::io::Result<()> { + std::fs::rename(tmp, dir.join(LIBRARY_FILE)).or_else(|_| std::fs::rename(tmp, dir.join(NEXT_FILE))) +} + /// Writes `bytes` to a temporary file beside `path`, then renames it over /// `path`: a reader never sees a part. fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { @@ -246,9 +728,111 @@ mod tests { let Some(device) = crate::host::host().and_then(|h| h.device.cast::().ok()) else { return; // no host GPU here }; - let library = open(&device, b"not a pipeline library".repeat(16)).expect("an empty library"); + let library = open(&device, Blob::Held(b"not a pipeline library".repeat(16))).expect("an empty library"); // SAFETY: a plain query on a live library. assert!(unsafe { library.library.GetSerializedSize() } > 0); - assert!(library._blob.is_empty()); + assert!(matches!(library._blob, Blob::None)); + } + + /// A mapped file reads as the file's bytes, a file written through a + /// mapping holds what was written, and the library's file can be + /// replaced while it is mapped (or the new one waits as the next). + #[test] + fn the_library_file_is_mapped_and_replaced() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(LIBRARY_FILE); + assert!(matches!(Blob::of(dir.path()), Blob::None), "no file yet"); + std::fs::write(&path, b"").unwrap(); + assert!(matches!(Blob::of(dir.path()), Blob::None), "an empty file"); + let old: Vec = (0..200_000u32).map(|i| i as u8).collect(); + std::fs::write(&path, &old).unwrap(); + let blob = Blob::of(dir.path()); + assert!(matches!(blob, Blob::Mapped(_)) || !mapped()); + assert_eq!(blob.bytes(), &old[..]); + // A save while the old file is mapped. + let tmp = path.with_extension("tmp"); + let new: Vec = (0..300_000u32).map(|i| (i * 7) as u8).collect(); + { + let mut file = Mapped::create(&tmp, new.len()).expect("a new file, mapped"); + file.bytes_mut().copy_from_slice(&new); + } + assert_eq!(std::fs::read(&tmp).unwrap(), new); + replace_library(dir.path(), &tmp).unwrap(); + assert!(!tmp.exists()); + // The mapping still reads the old library. + assert_eq!(blob.bytes(), &old[..]); + drop(blob); + // The next start reads the new one, wherever the save left it. + assert_eq!(Blob::of(dir.path()).bytes(), &new[..]); + assert!(!dir.path().join(NEXT_FILE).exists()); + } + + /// The bytes at `at` of the pattern the test below writes. + fn pattern(at: usize, out: &mut [u8]) { + for (i, word) in out.chunks_exact_mut(4).enumerate() { + let v = ((at / 4 + i) as u32).wrapping_mul(2_654_435_761).wrapping_add(1); + word.copy_from_slice(&v.to_le_bytes()); + } + } + + /// A file of `len` bytes (whole MiB) of [`pattern`], written past the + /// system's cache: none of its pages is in memory afterwards. False + /// where the folder's file system does not take such writes. + fn write_uncached(path: &std::path::Path, len: usize) -> bool { + use std::io::Write; + use std::os::windows::fs::OpenOptionsExt; + // FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH + const UNCACHED: u32 = 0x2000_0000 | 0x8000_0000; + const CHUNK: usize = 1 << 20; + let Ok(mut file) = std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .custom_flags(UNCACHED) + .open(path) + else { + return false; + }; + // Such writes want a buffer on a sector boundary. + let mut store = vec![0u8; CHUNK + 4096]; + let start = store.as_ptr().align_offset(4096); + for at in (0..len).step_by(CHUNK) { + let chunk = &mut store[start..start + CHUNK]; + pattern(at, chunk); + if file.write_all(chunk).is_err() { + return false; + } + } + true + } + + /// The device loss of runs 72, 73 and 82: the library's file is + /// replaced while it is mapped, and pages of the mapping that were not + /// in memory then are read afterwards (in the runs: pages the trim let + /// go and Windows gave to something else). With the file's handle kept + /// open they still read as the old file. (With it closed, as before, + /// all but the first few read as zeros on the PC this was found on.) + #[test] + fn a_replaced_library_file_still_reads_from_the_disk() { + const LEN: usize = 8 << 20; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(LIBRARY_FILE); + if !write_uncached(&path, LEN) { + return; // no uncached writes here: nothing to show + } + let mapped = Mapped::open_holding(&path, true).expect("the file, mapped"); + // A save: the new library, renamed over the mapped one. + let tmp = path.with_extension("tmp"); + { + let mut file = Mapped::create(&tmp, LEN).expect("a new file, mapped"); + file.bytes_mut().fill(0xEE); + } + replace_library(dir.path(), &tmp).unwrap(); + // Every page of the old mapping, read for the first time now. + let mut expected = vec![0u8; 4096]; + for (page, bytes) in mapped.bytes().chunks(4096).enumerate() { + pattern(page * 4096, &mut expected); + assert!(bytes == &expected[..], "page {page} of the replaced library no longer reads as the old file"); + } } } diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 6ffc032..de0b366 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -16,7 +16,8 @@ //! guess; a pass the title runs only once and whose pipeline takes longer //! is lost. -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, OnceLock}; use std::time::{Duration, Instant}; @@ -27,7 +28,7 @@ use super::host::{GraphicsState, HostPipeline}; pub(crate) struct Pending { shaders: Vec>, pub(crate) graphics: Option>, - queued: AtomicBool, + queue_state: AtomicU8, made: OnceLock>, /// What identifies it across runs (shader containers and state), and /// whether a draw has used it yet. @@ -52,7 +53,7 @@ impl Pending { Pending { shaders, graphics, - queued: AtomicBool::new(false), + queue_state: AtomicU8::new(NOT_QUEUED), made: OnceLock::new(), key: key.finalize().to_hex()[..32].to_owned(), used: AtomicBool::new(false), @@ -109,22 +110,25 @@ pub(crate) fn waiting() -> u64 { /// queues it on first use. pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { if p.made.get().is_none() { - start(p); + start(p, REQUESTED); wait(p, crate::frame::current()); } let made = p.made.get()?.as_ref(); - if made.is_some() && !p.used.swap(true, Ordering::Relaxed) { + // Also one that could not be made (a shader that does not translate): + // the next run then finds that out while loading, like the others, + // instead of in the world's frames, where each first use of such a + // pipeline waits on the frame's budget for nothing. + if !p.used.swap(true, Ordering::Relaxed) { super::library::note_used(&p.key); } made } -/// Queues `p` for the workers, once. -fn start(p: &Arc) { - if !p.queued.swap(true, Ordering::Relaxed) { - PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed); - queue(p.clone()); - } +/// Makes `p` on this thread if it is not made yet (waiting for a worker +/// that is making it); whether it has a host pipeline. +pub(crate) fn now(p: &Arc) -> bool { + p.make(); + p.made.get().is_some_and(|made| made.is_some()) } /// At the title's creation of a pipeline: starts it at once if an earlier @@ -132,18 +136,43 @@ fn start(p: &Arc) { pub(crate) fn early(p: &Arc) { if !p.shaders.is_empty() && super::library::wanted_early(&p.key) { super::library::EARLY.fetch_add(1, Ordering::Relaxed); - start(p); + start(p, EARLY); } } +/// Whether the frame's budget is one for all threads together: a thread +/// that waits takes what is left of it and gives back what it did not +/// use. Counted only when a wait had ended, the budget was one per thread: +/// each of the title's five recording threads began its first wait of a +/// frame with nothing counted yet and waited the whole half second, 2.5 s +/// of waiting in every frame in which pipelines were being made (runs +/// 34-49: "2504 ms waiting for pipelines" in each such frame). +/// On by default; `VICTORY_PIPELINE_WAIT_SHARED=0` counts as before. +fn shared_budget() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_WAIT_SHARED").is_none_or(|v| v != "0")) +} + /// Waits for `p` while frame `frame` has budget left. fn wait(p: &Pending, frame: u64) { - static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); - static WAITED_US: AtomicU64 = AtomicU64::new(0); - if FRAME.swap(frame, Ordering::Relaxed) != frame { - WAITED_US.store(0, Ordering::Relaxed); + // 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)); + let shared = shared_budget(); + let left = { + let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner()); + if spent.0 != frame { + *spent = (frame, Duration::ZERO); + } + let left = BUDGET.saturating_sub(spent.1); + if shared { + spent.1 += left; + } + left + }; + if left.is_zero() { + return; } - let left = BUDGET.saturating_sub(Duration::from_micros(WAITED_US.load(Ordering::Relaxed))); let started = Instant::now(); let (lock, done) = &DONE; let mut held = lock.lock().unwrap_or_else(|e| e.into_inner()); @@ -154,22 +183,115 @@ fn wait(p: &Pending, frame: u64) { } held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0; } - WAITED_US.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + drop(held); + let waited = started.elapsed().min(left); + { + let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner()); + // A frame that began meanwhile has its own budget. + if spent.0 == frame { + if shared { + spent.1 = spent.1.saturating_sub(left - waited); + } else { + spent.1 += waited; + } + } + } + #[cfg(feature = "diagnostics")] + crate::copystat::add( + crate::copystat::C::PipelineWaitUs, + started.elapsed().as_micros() as u64, + ); } -/// Hands `p` to the workers (half the logical processors, 2 to 8), started -/// on first use. -fn queue(p: Arc) { - static SENDER: OnceLock>> = OnceLock::new(); - let sender = SENDER.get_or_init(|| { - let (sender, receiver) = std::sync::mpsc::channel::>(); - let receiver = Arc::new(Mutex::new(receiver)); +const NOT_QUEUED: u8 = 0; +const EARLY: u8 = 1; +const REQUESTED: u8 = 2; +const MAKING: u8 = 3; + +struct Queue { + early: VecDeque>, + requested: VecDeque>, +} + +impl Queue { + const fn new() -> Self { + Self { + early: VecDeque::new(), + requested: VecDeque::new(), + } + } + + /// Queues an unrequested pipeline or promotes one queued at creation. + /// Returns whether it is new to the queue, or `None` if nothing changed. + fn push(&mut self, p: &Arc, priority: u8) -> Option { + let prev = p.queue_state.load(Ordering::Relaxed); + if prev >= priority { + return None; + } + p.queue_state.store(priority, Ordering::Relaxed); + if priority == REQUESTED { + self.requested.push_back(p.clone()); + } else { + self.early.push_back(p.clone()); + } + 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) + })?; + p.queue_state.store(MAKING, Ordering::Relaxed); + Some(p) + } +} + +static QUEUE: Mutex = Mutex::new(Queue::new()); +static AVAILABLE: Condvar = Condvar::new(); + +/// Start or promote work for a draw without waiting behind the entire early +/// list. Queue changes and worker claims happen under the same lock. +fn start(p: &Arc, priority: u8) { + if p.queue_state.load(Ordering::Relaxed) >= priority { + return; + } + if !workers() { + if p.queue_state.swap(MAKING, Ordering::Relaxed) == NOT_QUEUED { + p.make(); + } + return; + } + let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(new) = queue.push(p, priority) { + if new { + PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed); + } + AVAILABLE.notify_one(); + } +} + +fn next() -> Arc { + let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(p) = queue.pop() { + return p; + } + queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner()); + } +} + +/// Starts the workers (half the logical processors, 2 to 8) on first use. +fn workers() -> bool { + static RUNNING: OnceLock = OnceLock::new(); + *RUNNING.get_or_init(|| { + let mut running = false; let workers = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8)); for i in 0..workers { - let receiver = receiver.clone(); let spawned = std::thread::Builder::new() .name(format!("victory-pipelines-{i}")) - .spawn(move || { + .spawn(|| { // Below the title's own threads (loading, recording). // SAFETY: a plain call on our own thread. unsafe { @@ -177,9 +299,7 @@ fn queue(p: Arc) { let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); } loop { - let next = receiver.lock().unwrap_or_else(|e| e.into_inner()).recv(); - let Ok(p) = next else { return }; - p.make(); + next().make(); if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 { drained(); } else { @@ -189,15 +309,12 @@ fn queue(p: Arc) { }); if let Err(e) = spawned { tracing::warn!(error = %e, "no pipeline worker"); + } else { + running = true; } } - sender - }); - if let Err(e) = sender.send(p) { - // No worker: made here instead. - e.0.make(); - WAITING.fetch_sub(1, Ordering::Relaxed); - } + running + }) } /// The most pipelines waiting at once since the workers last ran out. @@ -228,11 +345,31 @@ mod tests { fn first_use_is_made_by_a_worker() { let p = Arc::new(Pending::new(Vec::new(), None)); assert!(ready(&p).is_none()); - assert!(p.queued.load(Ordering::Relaxed)); + assert_ne!(p.queue_state.load(Ordering::Relaxed), NOT_QUEUED); let started = Instant::now(); while p.made.get().is_none() && started.elapsed() < Duration::from_secs(10) { std::thread::yield_now(); } assert!(matches!(p.made.get(), Some(None))); } + + #[test] + fn draws_promote_early_pipelines_without_claiming_them_twice() { + let earlier = Arc::new(Pending::new(Vec::new(), None)); + let promoted = Arc::new(Pending::new(Vec::new(), None)); + let requested = Arc::new(Pending::new(Vec::new(), None)); + let mut queue = Queue::new(); + + assert_eq!(queue.push(&earlier, EARLY), Some(true)); + assert_eq!(queue.push(&promoted, EARLY), Some(true)); + assert_eq!(queue.push(&requested, REQUESTED), Some(true)); + 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_eq!(queue.push(&promoted, REQUESTED), None); + assert!(Arc::ptr_eq(&queue.pop().unwrap(), &earlier)); + assert!(queue.pop().is_none()); + } } diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index d925048..91a23ee 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -11,6 +11,12 @@ //! [`components`] does not know keep the first vertex's value, and so do //! components past the end of the vertex (an element that reaches into the //! next one, which the layout allows). +//! +//! A pipeline the title makes for rectangles completes them on the GPU +//! instead, in a geometry stage (`victory_shader::emit::rect_list_gs`): +//! from the vertex shader's outputs, whichever vertex the corner is, for +//! direct, indexed and indirect draws alike. This expansion is what is +//! left for a pipeline that could not get that stage. /// Expands `rects` rectangles of `stride`-byte vertices from `src` into six /// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 5992fad..1335401 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -34,9 +34,403 @@ struct Queue { object: Object, kind: u32, desc: QueueDesc, + /// What the queue was given after a wait for a fence that had not been + /// reached, in order; it runs when the fence gets there. + #[cfg(windows)] + held: std::sync::Mutex>, } const _: () = assert!(std::mem::offset_of!(Queue, kind) == 0x10); +/// One thing a waiting queue holds back. +#[cfg(windows)] +enum Held { + /// The queue waits for the fence (its address) to reach the value. + Wait(usize, u64), + /// A list of the next submission waits for a memory value. + Value(crate::list::ValueWait), + /// A submission: the lists' host sides, taken from the title's lists + /// (which it may reset meanwhile), and the order they run in. + Run(Vec, Vec), + /// A signal of the queue's, due after what it holds before it. + Signal(usize, u64), +} + +/// The queues that hold something (their addresses). +#[cfg(windows)] +static WAITING: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +#[cfg(windows)] +fn lock(mutex: &std::sync::Mutex) -> std::sync::MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Whether queues wait for fences. `VICTORY_QUEUE_WAIT=0`: they do not, +/// and every submission runs when it is made (as before). +#[cfg(windows)] +fn waits() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_QUEUE_WAIT").is_none_or(|v| v != "0")) +} + +/// Whether a submission is held list by list: the lists before the first +/// one whose wait for a memory value is not met run at once, and each list +/// that waits is held with the lists after it, behind its own waits. +/// Holding a submission whole made the title's queues wait for each other: +/// a graphics submission was held for a value a compute list writes, and +/// that compute list for a value an earlier list of the same graphics +/// submission writes. Nothing moved until the present forced it, and the +/// title reached its present only after waiting about 2.5 s, every frame +/// (runs 27-30: 2.4-2.9 s from the last submission to the present call, +/// 13-32 ms before waits were honoured; the frame's main graphics +/// submissions, 88 lists, ran forced, the compute lists before them). +/// On by default; `VICTORY_SPLIT_WAITS=0` holds whole submissions, as +/// before. +#[cfg(windows)] +fn split() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SPLIT_WAITS").is_none_or(|v| v != "0")) +} + +/// Whether a list is cut into host lists at its waits for memory values +/// (`crate::list::cut`), and a queue runs a submission part by part: it +/// stands at each wait until the value is in memory, with everything +/// recorded before the wait run and its bottom-of-pipe writes done, as on +/// the console. Held list by list ([`split`]) a wait still held its whole +/// list: the title's lists are chains of jobs, each behind a wait for a +/// value another queue's list writes in the middle of its own chain +/// (frame 858 of run 33: a compute list of 433 commands with 13 waits; +/// graphics lists of the form "341 dispatches, wait, draws"), so two lists +/// each waited for a write behind the other's wait and only the present +/// moved them, in the wrong order. +/// On by default where waits are honoured list by list; +/// `VICTORY_CUT_WAITS=0` holds whole lists, as before. +#[cfg(windows)] +pub(crate) fn cuts() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + waits() && split() && *ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WAITS").is_none_or(|v| v != "0")) +} + +/// Whether a present runs what queues still hold (on by default: a wait +/// is not kept across frames). `VICTORY_WAIT_FORCE=0` keeps it held: for +/// finding out whether the title's waits reach across its presents; a +/// wait nothing ever meets then stops the title for good. +#[cfg(windows)] +fn forces() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WAIT_FORCE").is_none_or(|v| v != "0")) +} + +/// A submission to a queue whose lists are cut at their waits ([`cuts`]). +/// The lists before the first one that waits run at once if the queue +/// holds nothing; the rest goes behind what the queue holds, part by part +/// (`crate::list::detach_parts`): the waits of a part, then its host +/// lists. [`release_held`] runs the queue's line as far as the values are +/// there, now and whenever a submission has run. +#[cfg(windows)] +fn submit_cut(this: This, lists: &[This]) { + let Some(host) = crate::host::host() else { + return; + }; + let first = if lock(&queue(this).held).is_empty() { + lists + .iter() + .position(|&l| crate::list::cut_list(l)) + .unwrap_or(lists.len()) + } else { + 0 + }; + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || { + let named: Vec = lists + .iter() + .map(|&l| match crate::list::host_list(l) { + Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize), + None => format!("title {l:?}"), + }) + .collect(); + format!( + "SUBMIT queue kind {:?} held {} lists {named:?} (the first {first} run at once, the rest part by part)", + Some(queue(this).kind), + first < lists.len() + ) + }); + if first > 0 && crate::host::late() { + // Sent to the card and not waited for: their host sides are taken + // from the title's lists (which it may reset before they have run) + // and come back, with their tables' slots, when they are settled. + let (taken, order) = crate::list::detach(&lists[..first]); + host.execute_late(taken, order); + } else if first > 0 { + let now: Vec<_> = lists[..first] + .iter() + .filter_map(|&l| crate::list::host_list(l)) + .collect(); + host.execute(&now); + // They have run: their descriptor tables' slots are free again, as + // on the path without cuts ([`execute`]). This path replaced that + // one without the call, so the lists that run at once kept their + // slots until the title's reset and the ring ran out as before + // (run 45: 3,143 of 15,942 tables refused in one frame). + crate::list::tables_done(&lists[..first]); + } + if first < lists.len() { + let parts = crate::list::detach_parts(&lists[first..]); + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!( + kind = queue(this).kind, + lists = lists.len(), + run_at_once = first, + parts = parts.len(), + waits = parts.iter().map(|p| p.0.len()).sum::(), + "a submission is given to its queue part by part (its lists wait for memory values)" + ); + } + { + let mut held = lock(&queue(this).held); + for (waits, taken, order) in parts { + held.extend(waits.into_iter().map(Held::Value)); + held.push(Held::Run(taken, order)); + } + } + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + // What ran may be what another queue waits for, and what was just + // given to the queue may be free to run already. + release_held(false); +} + +/// A submission to a queue that honours waits, list by list ([`split`]). +/// shortcut: a wait still holds its whole list, not only the commands +/// after it; and lists named twice among those held stay in one piece. +#[cfg(windows)] +fn submit_split(this: This, lists: &[This]) { + let Some(host) = crate::host::host() else { + return; + }; + let by = crate::list::waits_by_list(lists); + // Behind what the queue already holds, nothing runs now. + let cut = if lock(&queue(this).held).is_empty() { + (0..lists.len()) + .find(|&i| by[i].iter().any(|w| !w.met())) + .unwrap_or(lists.len()) + } else { + 0 + }; + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || { + let named: Vec = lists + .iter() + .map(|&l| match crate::list::host_list(l) { + Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize), + None => format!("title {l:?}"), + }) + .collect(); + format!( + "SUBMIT queue kind {:?} held {} lists {named:?} (the first {cut} run at once)", + Some(queue(this).kind), + cut < lists.len() + ) + }); + if cut > 0 { + let now: Vec<_> = lists[..cut] + .iter() + .filter_map(|&l| crate::list::host_list(l)) + .collect(); + host.execute(&now); + } + if cut < lists.len() { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!( + kind = queue(this).kind, + lists = lists.len(), + run_at_once = cut, + waits = ?by[cut], + "lists of a submission are held for a memory value" + ); + } + let rest = &lists[cut..]; + // A list's host side can be taken once. + let twice = rest.iter().enumerate().any(|(i, l)| rest[..i].contains(l)); + let mut pieces: Vec = Vec::new(); + let mut from = cut; + while from < lists.len() { + // Up to the next list that waits for anything (met or not: it + // is looked at again when its turn comes). + let to = if twice { + lists.len() + } else { + (from + 1..lists.len()) + .find(|&i| !by[i].is_empty()) + .unwrap_or(lists.len()) + }; + let waits: Vec = by[from..to].concat(); + pieces.extend(waits.into_iter().map(Held::Value)); + let (taken, order) = crate::list::detach(&lists[from..to]); + pieces.push(Held::Run(taken, order)); + from = to; + } + lock(&queue(this).held).extend(pieces); + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + // What ran may be what another queue waits for, and what was just held + // may be free to run already. + release_held(false); +} + +/// Adds `what()` to what the queue holds, if it holds anything (it waits +/// for a fence): whether it was added. +#[cfg(windows)] +fn hold(this: This, what: impl FnOnce() -> Held) -> bool { + if this.is_null() { + return false; + } + let mut held = lock(&queue(this).held); + if held.is_empty() { + return false; + } + held.push(what()); + true +} + +/// Runs what waiting queues hold as far as their fences have been reached +/// (`all`: all of it), each queue's in the order it was given. Called +/// where a fence may have moved: after a signal and after a submission (a +/// list's bottom-of-pipe write may be into a fence), never from inside +/// one. +#[cfg(windows)] +pub(crate) fn release_held(all: bool) { + // One caller at a time, so a queue's submissions keep their order. + static RELEASING: std::sync::Mutex<()> = std::sync::Mutex::new(()); + if lock(&WAITING).is_empty() { + return; + } + let _one = lock(&RELEASING); + loop { + let queues = lock(&WAITING).clone(); + let mut moved = false; + for q in queues { + // SAFETY: a live queue: one released is taken off the list. + let held = unsafe { &(*(q as *const Queue)).held }; + let mut held = lock(held); + loop { + match held.first() { + None => break, + Some(&Held::Wait(fence, value)) + if !all && crate::fence::completed(fence as This) < value => + { + break; + } + Some(Held::Value(wait)) if !all && !value_met(wait) => break, + Some(_) => {} + } + match held.remove(0) { + Held::Wait(..) => {} + Held::Value(wait) => { + // Passed at a present without being met: what the + // queue stood at. + if all && !value_met(&wait) { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 16 { + tracing::warn!( + queue = format_args!("{q:#x}"), + ?wait, + "a wait for a memory value was not met at a present: the queue runs on" + ); + } + } + } + Held::Run(lists, order) => { + #[cfg(feature = "diagnostics")] + crate::capture::op(q, || { + format!( + "RUN held submission of {} lists (forced {all})", + order.len() + ) + }); + // Diagnostics: the part behind this one stands at + // waits that are met already, so the two could have + // been one host submission (one wait for the card, + // each range shaders write compared once). + #[cfg(feature = "diagnostics")] + { + let waits = held.iter().take_while(|h| matches!(h, Held::Value(_))).count(); + if waits > 0 + && matches!(held.get(waits), Some(Held::Run(..))) + && held[..waits].iter().all(|h| matches!(h, Held::Value(w) if w.met())) + { + crate::copystat::add(crate::copystat::C::PartsTogether, 1); + } + } + if crate::host::late() + && let Some(host) = crate::host::host() + { + // Not waited for: the host keeps the lists + // until they are settled. + host.execute_late(lists, order); + } else { + let ran = { + let runs: Vec<&crate::host::HostList> = + order.iter().map(|&i| lists[i].host()).collect(); + match crate::host::host() { + Some(host) => { + host.execute(&runs); + true + } + None => false, + } + }; + // They have run: their host lists are used again. + if ran { + crate::list::recycle(lists, &order); + } + } + if all { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Forced, 1); + static ONCE: AtomicBool = AtomicBool::new(false); + if !ONCE.swap(true, Ordering::Relaxed) { + tracing::warn!( + "a queue still held a submission at a present: its fence was not reached" + ); + } + } + } + // Behind what was sent to the card and not waited + // for, if anything was. + Held::Signal(fence, value) => { + if !crate::host::late_signal(fence, value) { + crate::fence::set(fence as This, value); + } + } + } + moved = true; + } + if held.is_empty() { + lock(&WAITING).retain(|&w| w != q); + } + } + if !moved { + break; + } + } +} + +/// Whether a queue may pass `wait`: memory holds the value, or, with +/// submissions sent to the card without a wait (`crate::host::late`), it +/// will once those in the air have run. +#[cfg(windows)] +fn value_met(wait: &crate::list::ValueWait) -> bool { + wait.met() || (crate::host::late() && crate::host::late_met(wait)) +} + fn queue<'a>(this: This) -> &'a Queue { // SAFETY: called from queue methods only. unsafe { &*this.cast::() } @@ -61,6 +455,8 @@ pub(crate) extern "system" fn create( }, kind: desc.kind, desc, + #[cfg(windows)] + held: Default::default(), }); object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out) } @@ -107,11 +503,17 @@ extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT ) } extern "system" fn release(this: This) -> u32 { - object::release_boxed::(this) + let left = object::release_boxed::(this); + #[cfg(windows)] + if left == 0 { + lock(&WAITING).retain(|&q| q != this as usize); + } + left } -/// Runs the lists' host lists and waits for them (decision 0007). -extern "system" fn execute(_: This, count: u32, lists: *const This) { +/// Runs the lists' host lists and waits for them (decision 0007). A queue +/// that waits for a fence keeps them until the fence is reached. +extern "system" fn execute(this: This, count: u32, lists: *const This) { if lists.is_null() { return; } @@ -119,13 +521,64 @@ extern "system" fn execute(_: This, count: u32, lists: *const This) { if let Some(host) = crate::host::host() { // SAFETY: the title passes `count` lists. let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) }; + if cuts() && !this.is_null() { + submit_cut(this, lists); + return; + } + if waits() && split() && !this.is_null() { + submit_split(this, lists); + return; + } + // A list that waits for a memory value not there yet: the queue + // holds the submission, as it does behind a fence. + if waits() && !this.is_null() { + let unmet = crate::list::unmet_waits(lists); + if !unmet.is_empty() { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!(kind = queue(this).kind, ?unmet, "a submission is held for a memory value"); + } + lock(&queue(this).held).extend(unmet.into_iter().map(Held::Value)); + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + } + let kept = hold(this, || { + let (taken, order) = crate::list::detach(lists); + Held::Run(taken, order) + }); + // Diagnostics: the order submissions are made in, next to the + // commands of the frame's `ops` file (which are in recording order). + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || { + let kind = (!this.is_null()).then(|| queue(this).kind); + // The lists as the frame's other lines name them (their host sides). + let named: Vec = lists + .iter() + .map(|&l| match crate::list::host_list(l) { + Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize), + None => format!("title {l:?}"), + }) + .collect(); + format!("SUBMIT queue kind {kind:?} held {kept} lists {named:?}") + }); + if kept { + return; + } let host_lists: Vec<_> = lists .iter() .filter_map(|&l| crate::list::host_list(l)) .collect(); host.execute(&host_lists); + crate::list::tables_done(lists); + // What the lists wrote at the bottom of the pipe may be a fence + // another queue waits for. + release_held(false); return; } + let _ = this; static ONCE: AtomicBool = AtomicBool::new(false); if !ONCE.swap(true, Ordering::Relaxed) { tracing::warn!(count, "command lists submitted; no host GPU runs them"); @@ -157,15 +610,80 @@ extern "system" fn signal2_x( } /// Markers and events only matter to profilers. extern "system" fn marker(_: This) {} -extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT { +extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT { if fence.is_null() { return E_INVALIDARG; } + // A queue that waits signals after what it holds. + #[cfg(windows)] + if hold(this, || Held::Signal(fence as usize, value)) { + return S_OK; + } + // Behind the submissions sent to the card and not waited for: the + // fence is set when they are settled. + #[cfg(windows)] + if crate::host::late_signal(fence as usize, value) { + return S_OK; + } + let _ = this; crate::fence::signal(fence, value) } -/// Nothing runs on the queue, so waiting for a fence never blocks it. -extern "system" fn wait(_: This, fence: This, _value: u64) -> HRESULT { - if fence.is_null() { E_INVALIDARG } else { S_OK } +/// From here on the queue runs nothing it is given until `fence` reaches +/// `value`: how the console orders work between queues (the title's +/// compute queue waits for the depth the graphics queue draws). Our +/// submissions run when they are made, so a wait for a value already +/// reached is nothing; otherwise what the queue is given next is held +/// ([`Held`]) until a signal or a list's bottom-of-pipe write gets the +/// fence there. +extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { + if fence.is_null() { + return E_INVALIDARG; + } + #[cfg(windows)] + if !this.is_null() { + let now = crate::fence::completed(fence); + // Whether the title uses this at all (the first calls). + { + static CALLS: AtomicU64 = AtomicU64::new(0); + if CALLS.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!(kind = queue(this).kind, now, value, "a queue is told to wait for a fence"); + } + } + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || format!("WAIT queue kind {} for fence {fence:?} value {value} (now {now})", queue(this).kind)); + let behind = { + let mut held = lock(&queue(this).held); + let behind = !held.is_empty() || now < value; + if behind && waits() { + held.push(Held::Wait(fence as usize, value)); + } + behind + }; + if behind { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!( + kind = queue(this).kind, + now, + value, + held = waits(), + "a queue waits for a fence not reached yet" + ); + } + } + if behind && waits() { + { + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + // The fence may have got there meanwhile. + release_held(false); + } + } + let _ = (this, value); + S_OK } /// Ticks per second of GPU timestamps (see [`Written::GpuTimestamp`]). extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT { @@ -242,6 +760,24 @@ extern "system" fn present( plane_parameters: *const Plane, _parameters: *const u8, ) -> HRESULT { + #[cfg(all(windows, feature = "diagnostics"))] + crate::copystat::present_begins(); + // Submissions sent to the card and not waited for are settled first, + // and what that frees runs in its own order, before anything is forced. + #[cfg(windows)] + if crate::host::late() && !crate::host::late_free_present() { + crate::host::settle_for_present(); + release_held(false); + crate::host::settle_for_present(); + } else if crate::host::late() { + // The present is sent ahead too: what waits for a value a flight + // will write runs behind that flight, and nothing is settled here. + release_held(false); + } + // shortcut: what a queue still holds at a present runs now, whatever + // its fence: a wait is not kept across frames. + #[cfg(windows)] + release_held(forces()); let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; if frame.is_power_of_two() { let (draws, dispatches) = crate::list::take_counts(); @@ -272,8 +808,11 @@ extern "system" fn present( } } #[cfg(all(windows, feature = "diagnostics"))] - if crate::capture::listed(frame) { - crate::capture::dump_targets(frame); + { + crate::capture::frame_drew(frame, crate::draw::drawn()); + if crate::capture::listed(frame) { + crate::capture::dump_targets(frame); + } } #[cfg(windows)] if planes > 0 diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 46c5c71..3782a0d 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -237,6 +237,339 @@ pub(crate) fn pc_format(format: u32) -> u32 { } } +/// The format of a texture the host GPU renders to or writes as unordered +/// access, for the title's `format`. The console's GPU does both with the +/// 16-bit colour formats B5G5R5A1 (86) and B4G4R4A4 (115), and Grand Theft +/// Auto VI has full-screen targets in both; a host that refuses either use +/// (NVIDIA) refused the whole texture, so every pass that wrote it drew +/// nothing. There 8-bit RGBA stands in: the same channels in the same +/// order, every 4-bit level exact and every 5-bit level within 1/510. +/// The title's pipelines and views of such targets name the stand-in too +/// ([`view_format`], the host view checks). +/// shortcut: copies between such a target and a texture the title fills +/// itself in the 16-bit format are skipped ([`stands_in`]); convert them +/// if a pass turns out to need one. +pub(crate) fn target_format(format: u32) -> u32 { + const STAND_INS: [(u32, u32); 2] = [(86, 28), (115, 28)]; + let Some(i) = STAND_INS.iter().position(|&(f, _)| f == format) else { + return format; + }; + #[cfg(windows)] + { + use windows::Win32::Graphics::Direct3D12::*; + static REFUSED: std::sync::OnceLock<[bool; 2]> = std::sync::OnceLock::new(); + let refused = REFUSED.get_or_init(|| { + STAND_INS.map(|(f, _)| { + let Some(host) = crate::host::host() else { + return false; + }; + let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(f as i32), + ..Default::default() + }; + // SAFETY: a plain query into our own structure. + let asked = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_FORMAT_SUPPORT, + (&raw mut support).cast(), + size_of_val(&support) as u32, + ) + }; + let both = D3D12_FORMAT_SUPPORT1_RENDER_TARGET.0 + | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0; + let refused = asked.is_err() || support.Support1.0 & both != both; + if refused { + tracing::info!(format = f, "the host does not render to this format: 8-bit RGBA stands in"); + } + refused + }) + }); + if refused[i] { + return STAND_INS[i].1; + } + } + format +} + +/// Whether the host copy of the title texture `this` is in a stand-in +/// format ([`target_format`]): its texels are not laid out as the title's. +#[cfg(windows)] +pub(crate) fn stands_in(this: This) -> bool { + if this.is_null() { + return false; + } + let own = pc_format(resource(this).desc.format); + target_format(own) != own + && host_resource(this) + // SAFETY: a live resource. + .is_some_and(|host| unsafe { host.GetDesc() }.Format.0 as u32 == target_format(own)) +} + +/// Depth textures the title also asks unordered access for (the console +/// allows both; the host copy loses the unordered access): how many were +/// made, and how often such a texture was bound as the depth target, +/// cleared as depth, and asked for an unordered access view the host could +/// not give. Measured to decide what such textures need (a colour twin, or +/// to be colour textures altogether). +pub(crate) static DEPTH_UNORDERED: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Whether the title asked for both depth and unordered access for `this`. +#[cfg(windows)] +pub(crate) fn depth_and_unordered(this: This) -> bool { + !this.is_null() && resource(this).desc.flags & 6 == 6 +} + +/// The colour twin of a depth texture the title also writes as unordered +/// access. The console allows both on one texture; the host gives a depth +/// texture no unordered access, so shaders write a colour texture of the +/// same size and format family instead, and one is copied into the other +/// when a side is used after the other was written +/// (`HostList::twin_use`). +/// shortcut: whole textures are copied, not the mips and slices written. +/// A depth texture with a stencil plane gets a twin for each plane (Grand +/// Theft Auto VI's tiled lighting writes each pixel's material class into +/// the depth plane and masks into the stencil plane, then draws each class +/// with the depth test "equal"): the stencil plane's is copied through a +/// buffer, the depth plane's is drawn into the plane by a pass of ours +/// (`HostList::pass_plane`). Unordered access views of a multisampled +/// texture stay null. +#[cfg(windows)] +pub(crate) struct Twin { + /// The colour texture and the state it is in, as a host copy's. + pub(crate) colour: std::sync::Arc, + /// Which side lacks what the other was written last, after the lists + /// submitted so far: bit 0 the depth texture, bit 1 the twin. + pub(crate) behind: std::sync::atomic::AtomicU32, + /// For a depth texture with a stencil plane, `colour` is the twin of + /// that plane (8 bits a texel) and this the buffer the two are copied + /// through: no colour format shares a family with a depth-stencil + /// format, but the host copies between a buffer and one plane. + pub(crate) through: Option, + /// For a depth texture with a stencil plane: the twin of its depth + /// plane, 16 bits a texel for the console's 16-bit depth-stencil + /// formats and a 32-bit float otherwise. No host colour format holds + /// the bits of a 24-bit depth plane, so the two are not copied: a pass + /// draws the twin into the plane. + pub(crate) plane: Option>, +} + +#[cfg(windows)] +impl Drop for Twin { + fn drop(&mut self) { + TWINS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Colour twins alive, depth textures with unordered access left without +/// one, and the copies recorded into depth textures and into twins since +/// the last frame-rate line. +#[cfg(windows)] +pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Depth planes drawn from their twins by the pass since the last +/// frame-rate line; and since the start, how often a depth plane's twin +/// lacked what was written to the plane (not given to it), and how often a +/// depth plane was used in the list that had written its twin, before the +/// pass (which runs when the list closes). +#[cfg(windows)] +pub(crate) static PLANES: [std::sync::atomic::AtomicU64; 3] = + [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// The colour twin of title texture `this`, if it has one. +#[cfg(windows)] +pub(crate) fn twin(this: This) -> Option> { + if this.is_null() { + return None; + } + hosted(this, true).and_then(|made| made.1) +} + +/// The twin's texture, for the unordered access views of `this`. +#[cfg(windows)] +pub(crate) fn twin_resource<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + let (_, twin) = hosted(this, true)?; + // SAFETY: as in `host_resource`: the twin lives as long as the host + // copy, which a depth texture keeps until the title releases it. + twin.map(|t| unsafe { &*std::ptr::from_ref(&t.colour.texture) }) +} + +/// The texture of the twin of the depth plane of `this`, a depth texture +/// with a stencil plane, for the unordered access views of that plane. +#[cfg(windows)] +pub(crate) fn twin_plane_resource<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + let (_, twin) = hosted(this, true)?; + let twin = twin?; + // SAFETY: as in `twin_resource`. + twin.plane + .as_ref() + .map(|p| unsafe { &*std::ptr::from_ref(&p.texture) }) +} + +/// The colour twin for a texture described by `desc` whose host copy is +/// `depth`, if the title asks for depth and unordered access both and the +/// host can copy between the two: the same size, mips and slices in the +/// depth format's typeless family (R16 for 16-bit depth, R32 for 32-bit), +/// or R8 for the stencil plane of a format that has one, with unordered +/// access only. A format with a stencil plane gets a twin for its depth +/// plane too, R16 for the console's 16-bit depth-stencil formats and R32 +/// otherwise. `VICTORY_DEPTH_TWINS=0` makes none (such views stay null), +/// `VICTORY_DEPTH_TWINS=stencil` only those of formats with a stencil +/// plane, `VICTORY_DEPTH_TWINS=nodepth` none for the depth planes of such +/// formats. +#[cfg(windows)] +fn twin_texture( + desc: &ResourceDesc, + depth: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, +) -> Option> { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D12::*; + const DEPTH_AND_UNORDERED: u32 = 6; + const UNORDERED: u32 = 4; + const UNORDERED_ACCESS: u32 = 0x8; + // R32 and R16 typeless: the families of the depth formats of one plane. + const ONE_PLANE: [u32; 2] = [39, 53]; + if desc.dimension == BUFFER || desc.flags & DEPTH_AND_UNORDERED != DEPTH_AND_UNORDERED { + return None; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_none_or(|v| v != "0")) { + return None; + } + // R32G8X24 and R24G8 typeless: depth with a stencil plane, whose twin + // is R8 typeless. + const WITH_STENCIL: [u32; 2] = [19, 44]; + const R8_TYPELESS: u32 = 60; + let typeless = family(pc_format(desc.format)); + let stencil = WITH_STENCIL.contains(&typeless); + static STENCIL_ONLY: std::sync::OnceLock = std::sync::OnceLock::new(); + let stencil_only = *STENCIL_ONLY + .get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_some_and(|v| v == "stencil")); + if !stencil && stencil_only { + return None; + } + if !(stencil || ONE_PLANE.contains(&typeless)) || desc.sample_count > 1 { + TWINS[1].fetch_add(1, Relaxed); + return None; + } + let host = crate::host::host()?; + let mut d = *desc; + d.layout = 0; + d.alignment = 0; + d.flags = UNORDERED; + d.format = if stencil { R8_TYPELESS } else { typeless }; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let mut texture: Option = None; + // SAFETY: the description has the host layout, as in `host_texture`; + // the out pointer is ours. + let made = unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32), + None, + &mut texture, + ) + }; + if let Err(e) = made { + tracing::warn!(error = %e, desc = ?d, "no colour twin for a depth texture"); + } + let Some(texture) = texture else { + TWINS[1].fetch_add(1, Relaxed); + return None; + }; + crate::host::name(&texture, || { + format!("depth twin {}x{} f{}", d.width, d.height, d.format) + }); + // The buffer a stencil plane and its twin are copied through: as big + // as the plane's mips and slices laid out for a copy (they follow the + // depth plane's in the texture's subresources). + let through = if stencil { + // SAFETY: a live texture. + let of = unsafe { depth.GetDesc() }; + let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize); + let mut bytes = 0; + // SAFETY: a plain query; the out pointer is ours. + unsafe { + host.device.GetCopyableFootprints( + &of, + planes, + planes, + 0, + None, + None, + None, + Some(&mut bytes), + ); + } + let Some(buffer) = host.uav_buffer(bytes) else { + TWINS[1].fetch_add(1, Relaxed); + return None; + }; + Some(buffer) + } else { + None + }; + // The twin of the depth plane of a format with a stencil plane: R16 + // typeless (53) for the console's 16-bit depth-stencil formats (118 to + // 120), whose shaders write 16-bit steps, R32 typeless (39) otherwise. + static NO_PLANE: std::sync::OnceLock = std::sync::OnceLock::new(); + let no_plane = *NO_PLANE + .get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_some_and(|v| v == "nodepth")); + let plane = if stencil && !no_plane { + d.format = if (118..=120).contains(&desc.format) { + 53 + } else { + 39 + }; + let mut texture: Option = None; + // SAFETY: as for the first twin. + let made = unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32), + None, + &mut texture, + ) + }; + if let Err(e) = made { + tracing::warn!(error = %e, desc = ?d, "no twin for a depth plane"); + } + texture.map(|texture| { + crate::host::name(&texture, || { + format!("depth plane twin {}x{} f{}", d.width, d.height, d.format) + }); + std::sync::Arc::new(HostTexture::new(texture, UNORDERED_ACCESS)) + }) + } else { + None + }; + TWINS[0].fetch_add(1, Relaxed); + Some(std::sync::Arc::new(Twin { + colour: std::sync::Arc::new(HostTexture::new(texture, UNORDERED_ACCESS)), + behind: std::sync::atomic::AtomicU32::new(0), + through, + plane, + })) +} + /// The typeless format of a format's family (itself if it has none). pub(crate) fn family(format: u32) -> u32 { const FAMILIES: [(u32, u32); 22] = [ @@ -280,11 +613,13 @@ pub(crate) const SRGB: [(u32, u32); 3] = [(29, 28), (91, 87), (93, 88)]; /// typeless (see [`DEPTH_FORMATS`], [`SRGB`]): the title's own; `None` if /// the host copy is typed. pub(crate) fn view_format(this: This) -> Option { - let own = pc_format(resource(this).desc.format); + // First: a view of no resource (a typed null view) has none. let host = host_resource(this)?; + let own = pc_format(resource(this).desc.format); // SAFETY: a live resource. let format = unsafe { host.GetDesc() }.Format.0 as u32; - (format != own).then_some(own) + // A stand-in target is typed. + (format != own && format != target_format(own)).then_some(own) } /// Depth formats with their typeless family: depth textures that shaders @@ -331,6 +666,23 @@ impl PlacedFootprint { let last = u64::from(self.width).div_ceil(block) * element; Some(u64::from(self.row_pitch) * lines.saturating_sub(1) + last) } + + /// For a read back through a host buffer: this footprint at offset 0 + /// with its rows pitched as the host wants them (multiples of 256 + /// bytes), then the bytes that buffer needs, the bytes of a row, the + /// rows, and the title's own pitch. + pub(crate) fn host_rows(&self) -> Option<(PlacedFootprint, [u64; 4])> { + let (element, block) = element(self.format)?; + let lines = (u64::from(self.height).div_ceil(block) * u64::from(self.depth)).max(1); + let row = u64::from(self.width).div_ceil(block) * element; + let pitch = row.max(1).next_multiple_of(256); + let host = PlacedFootprint { + offset: 0, + row_pitch: u32::try_from(pitch).ok()?, + ..*self + }; + Some((host, [pitch * lines, row, lines, u64::from(self.row_pitch)])) + } } const _: () = assert!(size_of::() == 32); @@ -645,6 +997,12 @@ impl Memory { .ok_or(E_INVALIDARG)?; // SAFETY: the size is non-zero. let ptr = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(E_OUTOFMEMORY)?; + // The big ones are named in the log: the memory line counts our own + // allocations by size, and these are the title's memory given out + // of ours (a heap it made through the device, a descriptor heap). + if info.size >= 32 << 20 { + tracing::info!(mb = info.size >> 20, at = ?ptr, "memory for the title from our allocator (a heap or a descriptor heap)"); + } Ok(Memory { ptr, layout, @@ -746,9 +1104,10 @@ struct Resource { heap_flags: u32, backing: Backing, /// Textures also live on the host GPU (decision 0007); buffers do not - /// yet. + /// yet. With, for a depth texture the title also writes as unordered + /// access, the colour texture shaders write instead ([`Twin`]). #[cfg(windows)] - host: Option>, + host: Hosted, } /// A title texture's host copy and the state it is in. The title's barriers @@ -761,6 +1120,458 @@ struct Resource { pub(crate) struct HostTexture { pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, pub(crate) state: std::sync::atomic::AtomicU32, + /// The bytes the host gives it. + bytes: u64, + /// Whether its contents come from title memory ([`fills`]): counted in + /// [`KINDS`] while it lives. + filled: bool, +} + +/// What a title texture has on the host: its host copy and, for a depth +/// texture shaders also write, the colour twin. +#[cfg(windows)] +type Made = (std::sync::Arc, Option>); + +/// A title texture's host side. The host copy is made when something first +/// uses the texture, not when the title creates it: Grand Theft Auto VI +/// had created 3,871 textures (9.2 GB on the host) before its world's first +/// frame, of which a frame's lists name some hundreds (run 23), on a card +/// with 12 GB. A title texture is memory the title has either way; its host +/// copy is the card's. +#[cfg(windows)] +struct Hosted { + /// The host copy (and twin) once made. Taken out again only by + /// [`let_go_idle`] and when the title releases the resource. + made: std::sync::Mutex>, + /// The state and clear value the title created the texture with. + state: u32, + clear: Option<[u32; 5]>, + /// When the host copy was last asked for (`crate::host::moment`), + /// written under `made`'s lock. + used: std::sync::atomic::AtomicU64, + /// The host refused to make it: not tried again. + refused: std::sync::atomic::AtomicBool, + /// Its host copy was let go as idle once. + gone: std::sync::atomic::AtomicBool, + /// A texture of [`PLACED_TEXTURES`]. + placed: std::sync::atomic::AtomicBool, +} + +/// Counts for the memory line: host copies of textures the title fills +/// alive and their bytes; such copies let go as idle since the start and +/// their bytes; made again after that and their bytes; and host copies made +/// since the start. +#[cfg(windows)] +pub(crate) static KINDS: [std::sync::atomic::AtomicU64; 7] = + [const { std::sync::atomic::AtomicU64::new(0) }; 7]; + +/// Every title texture alive (not buffers), by address: for the sweep and +/// the memory line. A texture leaves the table before it is freed. +#[cfg(windows)] +static TEXTURES: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); + +#[cfg(windows)] +fn textures() -> std::sync::MutexGuard<'static, std::collections::BTreeSet> { + TEXTURES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The title textures the host renders to or writes (targets, depth, +/// unordered access), by the address of their memory: what a view the +/// title places in that memory in another format shows ([`alias_of`]). A +/// texture leaves the table before it is freed. +#[cfg(windows)] +static TARGETS_AT: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// For `this`, a texture made for a view the title placed in memory +/// ([`texture_at`]): the title texture the host writes that lies in the +/// same memory, if there is one of the same size, levels and layers with +/// texels of the same width. The console reads such a texture through the +/// view as it is +/// (Grand Theft Auto VI packs light as R9G9B9E5 into R32_UINT textures +/// with compute shaders, which cannot write R9G9B9E5, and samples them +/// through R9G9B9E5 views placed at the textures' addresses: the sky, the +/// sky and light probes, the bounced light the lighting pass adds). On the +/// host the two are two textures and what the shaders wrote exists in one +/// of them only: the other was filled from title memory, which nothing +/// writes, so everything read through such a view was black. +/// Textures of several levels or layers count too (the screen probes' +/// light atlas has four levels, the camera's sky light cache six layers, +/// the cloud and sky tables are volumes): only textures of one level and +/// one layer were found at first, and the programs behind the others read +/// the title's unwritten memory - the sky light cache's second stage wrote +/// all zeros from a first stage that held light (run 88). +/// `VICTORY_ALIAS_COPY=0`: none is found, as before; `=1`: only textures +/// of one level and one layer, as at first. +#[cfg(windows)] +pub(crate) fn alias_of(this: This) -> Option { + use std::sync::atomic::Ordering::Relaxed; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if this.is_null() + || !*ON.get_or_init(|| std::env::var_os("VICTORY_ALIAS_COPY").is_none_or(|v| v != "0")) + { + return None; + } + static WHOLE: std::sync::OnceLock = std::sync::OnceLock::new(); + let whole = + *WHOLE.get_or_init(|| std::env::var_os("VICTORY_ALIAS_COPY").is_none_or(|v| v != "1")); + let r = resource(this); + // A level count of 0 asks for a full chain: not counted here. + let one = |d: &ResourceDesc| { + d.dimension != BUFFER + && d.mip_levels >= 1 + && d.depth_or_array_size >= 1 + && (whole || (d.mip_levels == 1 && d.depth_or_array_size == 1)) + && d.sample_count <= 1 + }; + if !r.host.placed.load(Relaxed) || !fills(&r.desc) || !one(&r.desc) { + return None; + } + // Under the table's lock: a texture leaves it before it is freed. + let targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner()); + let other = *targets.get(&(r.data() as u64))? as This; + let o = resource(other); + const DEPTH: u32 = 0x2; + let same = one(&o.desc) + && o.desc.dimension == r.desc.dimension + && o.desc.width == r.desc.width + && o.desc.height == r.desc.height + && o.desc.mip_levels == r.desc.mip_levels + && o.desc.depth_or_array_size == r.desc.depth_or_array_size + && o.desc.flags & DEPTH == 0 + && target_format(o.desc.format) == o.desc.format + && element(o.desc.format).is_some_and(|e| e.1 == 1 && Some(e) == element(r.desc.format)); + same.then_some(other) +} + +/// Whether host copies are made on first use. On by default; +/// `VICTORY_LAZY_TEXTURES=0` makes each when the title creates its texture, +/// as before. +#[cfg(windows)] +fn lazy() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_TEXTURES").is_none_or(|v| v != "0")) +} + +/// Whether a texture described by `desc` takes its contents from title +/// memory: one the host neither renders to nor writes (no target, depth or +/// unordered access flag). Its host copy can be made again from that +/// memory; any other texture's contents exist on the host alone. +#[cfg(windows)] +fn fills(desc: &ResourceDesc) -> bool { + const TARGET_DEPTH_UNORDERED: u32 = 0x7; + desc.dimension != BUFFER && desc.flags & TARGET_DEPTH_UNORDERED == 0 +} + +/// Whether the title fills texture `this` itself ([`fills`]). +#[cfg(windows)] +pub(crate) fn title_fills(this: This) -> bool { + !this.is_null() && fills(&resource(this).desc) +} + +/// Whether `this` is a texture whose host copy is not made yet (and may +/// still be): a descriptor slot written with a view of it waits +/// (`crate::descriptor::make_waiting`). +#[cfg(windows)] +pub(crate) fn host_waits(this: This) -> bool { + if this.is_null() || !lazy() { + return false; + } + let r = resource(this); + r.desc.dimension != BUFFER + && !r.host.refused.load(std::sync::atomic::Ordering::Relaxed) + && r.host.made.lock().unwrap_or_else(|e| e.into_inner()).is_none() +} + +/// The host side of title texture `this`: made now if it is not there and +/// `make` says so. `None` for buffers and for textures the host refuses. +#[cfg(windows)] +fn hosted(this: This, make: bool) -> Option { + use std::sync::atomic::Ordering::Relaxed; + let r = resource(this); + if r.desc.dimension == BUFFER { + return None; + } + let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + if made.is_none() { + if !make || r.host.refused.load(Relaxed) { + return None; + } + let clear = r + .host + .clear + .as_ref() + .map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast::()); + let Some(texture) = host_texture(&r.desc, r.host.state, clear) else { + r.host.refused.store(true, Relaxed); + return None; + }; + let twin = twin_texture(&r.desc, &texture); + // One line per depth texture with unordered access: its address is + // the one target dumps and the captured frame's list of commands + // name. + if r.desc.flags & 6 == 6 { + tracing::info!( + resource = ?this, + desc = ?r.desc, + twin = twin.is_some(), + "depth texture with unordered access" + ); + } + let state = crate::host::legal_state(&texture, crate::host::texture_state(r.host.state)); + let mut host = HostTexture::new(texture, state); + host.filled = fills(&r.desc); + if host.filled { + KINDS[0].fetch_add(1, Relaxed); + KINDS[1].fetch_add(host.bytes, Relaxed); + } + if r.host.gone.load(Relaxed) { + KINDS[4].fetch_add(1, Relaxed); + KINDS[5].fetch_add(host.bytes, Relaxed); + } + KINDS[6].fetch_add(1, Relaxed); + *made = Some((std::sync::Arc::new(host), twin)); + // Slots the title wrote with views of it while it had no host copy + // are made before the next submission runs. + crate::descriptor::texture_made(this as usize); + } + r.host.used.store(crate::host::moment(), Relaxed); + made.clone() +} + +/// The host copy of title texture `this` if it is made, without making it +/// (for diagnostics, which must not count as a use). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn host_made<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + let (host, _) = hosted(this, false)?; + // SAFETY: as in `host_resource`. + Some(unsafe { &*std::ptr::from_ref(&host.texture) }) +} + +/// Whether more host copies of textures the title fills may be made for +/// shaders that pick textures by index (`draw.rs` `heap_textures`): always +/// up to `FLOOR` bytes of them, beyond that while the card's memory in use +/// by this process is under nine tenths of the budget the system gives it +/// (`VICTORY_TEXTURE_BUDGET_MB` sets a limit on those copies' bytes +/// instead). Past the budget the system moves the card's memory into the +/// PC's, which ended runs 20 and 24. +#[cfg(windows)] +pub(crate) fn room() -> bool { + use std::sync::atomic::Ordering::Relaxed; + const FLOOR: u64 = 2 << 30; + const WITHOUT_BUDGET: u64 = 4 << 30; + static LIMIT: std::sync::OnceLock> = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + let mb = std::env::var("VICTORY_TEXTURE_BUDGET_MB").ok()?; + mb.trim().parse::().ok().map(|mb| mb << 20) + }); + let filled = KINDS[1].load(Relaxed); + if let Some(limit) = limit { + return filled < limit; + } + if filled < FLOOR { + return true; + } + match crate::host::host().and_then(|h| h.video_memory()) { + Some([budget, used, ..]) => used < budget / 10 * 9, + None => filled < WITHOUT_BUDGET, + } +} + +/// Lets go of the host copies of textures the title fills that nothing +/// names any more: placed textures were never released (one host texture +/// per address and description ever viewed: 18,639 of them, 2.5 GB, after +/// nine minutes of run 24), nor those of texture objects before the title +/// released them. A host copy goes when +/// - the title fills the texture ([`fills`]) and the host never copied +/// into it: its contents are in title memory; +/// - only the resource holds it: no list not yet reset names it (a list +/// holds the copies of the textures it uses, `HostList::transition`); +/// - only the host copy holds the host texture: no descriptor slot views +/// it (a slot keeps what it views, `HostHeap::kept`), so no shader can +/// read it through a slot made earlier, by a table or by an index; +/// - nothing asked for it for `IDLE_MS` and `IDLE_FRAMES` frames. +/// +/// The next use makes the host copy anew and uploads the title's memory +/// again (its staging state goes with it). The title resource stays: its +/// address is what views and lists name. +/// shortcut: [`host_resource`] hands out the host texture without holding +/// it; a thread that asked for it and has not yet recorded its use (which +/// makes the list or the slot hold it) is protected by that idle time alone. +/// Every caller uses it at once, within the title's call. +/// Called before a submission starts, by the thread that submits. +/// `VICTORY_TEXTURE_SWEEP=0` lets nothing go. +#[cfg(windows)] +pub(crate) fn let_go_idle() { + use std::sync::atomic::Ordering::Relaxed; + const IDLE_MS: u64 = 5_000; + const IDLE_FRAMES: u64 = 4; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_none_or(|v| v != "0")) { + return; + } + // For the trail (`crate::host::trail`): how many went, their bytes, + // and the first one. + let (mut went, mut bytes, mut first) = (0u64, 0u64, None); + let all = textures(); + for &at in all.iter() { + // SAFETY: a texture leaves the table before it is freed, under the + // lock held here (`Drop for Resource`). + let r = unsafe { &*(at as *const Resource) }; + if !fills(&r.desc) || crate::texture::host_wrote(at) { + continue; + } + let gone = { + let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + let idle = made.as_ref().is_some_and(|(host, _)| { + crate::host::long_ago(r.host.used.load(Relaxed), IDLE_MS, IDLE_FRAMES) + && std::sync::Arc::strong_count(host) == 1 + && crate::host::references(&host.texture) == 1 + }); + if idle { + // Under the lock: the next use must not find the staging + // state of the texture let go (it says "uploaded"). + crate::texture::unstage(at as This); + made.take() + } else { + None + } + }; + if let Some((host, _)) = gone { + r.host.gone.store(true, Relaxed); + KINDS[2].fetch_add(1, Relaxed); + KINDS[3].fetch_add(host.bytes, Relaxed); + went += 1; + bytes += host.bytes; + if first.is_none() { + first = Some(at); + } + crate::host::retire(host); + } + } + if went > 0 { + crate::host::trail(|| { + format!( + "sweep: {went} host copies of textures the title fills let go ({} KiB), each held by its title texture alone (no list, no slot); the first: title texture {:#x}", + bytes >> 10, + first.unwrap_or(0) + ) + }); + } +} + +/// For the memory line: title textures with a host copy the host renders +/// to or writes and those copies' bytes (twins included); title textures +/// without a host copy and the bytes of title memory they are; host copies +/// of textures the title fills and their bytes; of all title textures, +/// the placed ones with a host copy; the bytes of the twins alone (the +/// layer's own: the console has no second texture for a depth texture +/// shaders write); and, of the host copies of placed textures the title +/// fills, the bytes of those whose title memory is not mapped any more and +/// of those a descriptor slot still shows (the card holds a texture the +/// title has given up for as long as a slot shows it). The last two are +/// estimates from every 16th such texture: asking Windows about the memory +/// of all 16,000 takes too long. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn census() -> [u64; 10] { + const EVERY: u64 = 16; + let mut count = [0u64; 10]; + let mut placed_filled = 0u64; + let all = textures(); + for &at in all.iter() { + // SAFETY: as in `let_go_idle`. + let r = unsafe { &*(at as *const Resource) }; + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + match made.as_ref() { + Some((host, twin)) => { + let kind = if host.filled { 4 } else { 0 }; + count[kind] += 1; + count[kind + 1] += host.bytes + twin.as_ref().map_or(0, |t| t.colour.bytes); + count[7] += twin.as_ref().map_or(0, |t| t.colour.bytes); + let placed = r.host.placed.load(std::sync::atomic::Ordering::Relaxed); + if placed { + count[6] += 1; + } + if placed && host.filled { + placed_filled += 1; + // Its first page: a texture's smallest mips lie there, + // and are mapped first and unmapped last. + if placed_filled.is_multiple_of(EVERY) && !crate::texture::committed(r.data().cast_const(), 1) { + count[8] += host.bytes * EVERY; + if crate::host::references(&host.texture) > 1 { + count[9] += host.bytes * EVERY; + } + } + } + } + None => { + count[2] += 1; + count[3] += footprint(&r.desc).map_or(0, |f| f.size); + } + } + } + count +} + +/// Host textures alive (the title's and the twins) and the bytes the host +/// gives them, for the memory line. +#[cfg(windows)] +pub(crate) static HOST_TEXTURES: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The bytes the host allocates for `texture`. +#[cfg(windows)] +fn host_bytes(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource) -> u64 { + let Some(host) = crate::host::host() else { + return 0; + }; + // SAFETY: plain queries on a live resource and device. + unsafe { + let desc = texture.GetDesc(); + host.device.GetResourceAllocationInfo(0, &[desc]).SizeInBytes + } +} + +#[cfg(windows)] +impl HostTexture { + fn new(texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32) -> HostTexture { + use std::sync::atomic::Ordering::Relaxed; + let bytes = host_bytes(&texture); + HOST_TEXTURES[0].fetch_add(1, Relaxed); + HOST_TEXTURES[1].fetch_add(bytes, Relaxed); + HostTexture { + texture, + state: std::sync::atomic::AtomicU32::new(state), + bytes, + filled: false, + } + } +} + +#[cfg(windows)] +impl Drop for HostTexture { + fn drop(&mut self) { + use std::sync::atomic::Ordering::Relaxed; + HOST_TEXTURES[0].fetch_sub(1, Relaxed); + HOST_TEXTURES[1].fetch_sub(self.bytes, Relaxed); + if self.filled { + KINDS[0].fetch_sub(1, Relaxed); + KINDS[1].fetch_sub(self.bytes, Relaxed); + } + } +} + +/// How many textures placed in title memory have a resource of ours +/// (never released), for the memory line. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn placed_textures() -> u64 { + PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()).len() as u64 } /// Moves the host texture to `wanted` (a host texture state); the host @@ -768,14 +1579,16 @@ pub(crate) struct HostTexture { #[cfg(windows)] pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u32)> { use windows::core::Interface; - let host = resource(this).host.as_ref()?; + let (host, _) = hosted(this, true)?; let before = host .state .swap(wanted, std::sync::atomic::Ordering::Relaxed); (before != wanted).then(|| (host.texture.as_raw(), before)) } -/// The host GPU's copy of a title resource, if it has one. +/// The host GPU's copy of a title resource, if it has one: made now if +/// this is the texture's first use ([`Hosted`]). Asking is a use; what must +/// not count as one asks `host_made`. #[cfg(windows)] pub(crate) fn host_resource<'a>( this: This, @@ -783,7 +1596,13 @@ pub(crate) fn host_resource<'a>( if this.is_null() { return None; } - resource(this).host.as_deref().map(|h| &h.texture) + let (host, _) = hosted(this, true)?; + // SAFETY: the resource holds the host copy until the title releases it + // (lists and slots that name the texture hold it past that), or until + // `let_go_idle` takes it: only from a texture the title fills, that no + // list and no slot holds and that nothing asked for in seconds (the + // asking just made is noted under the same lock). + Some(unsafe { &*std::ptr::from_ref(&host.texture) }) } /// A title texture's host copy, shared, for a list to hold. @@ -792,7 +1611,7 @@ pub(crate) fn host_copy(this: This) -> Option> { if this.is_null() { return None; } - resource(this).host.clone() + hosted(this, true).map(|made| made.0) } /// A host texture like the title's: same description, in GPU memory, @@ -815,14 +1634,21 @@ fn host_texture( d.flags &= PC_FLAGS; // PC refuses depth targets that are also unordered-access (the console // allows both; Grand Theft Auto VI's shadow maps ask for it). - // shortcut: the host copy loses UAV use; give it a second view-only - // copy if draws write it as a UAV. + // The host copy loses the unordered access: shaders write a colour + // twin instead ([`Twin`]). const DEPTH: u32 = 2; const UNORDERED: u32 = 4; if d.flags & DEPTH != 0 { + if d.flags & UNORDERED != 0 { + DEPTH_UNORDERED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } d.flags &= !UNORDERED; } d.format = pc_format(d.format); + const TARGET: u32 = 1; + if d.flags & (TARGET | UNORDERED) != 0 { + d.format = target_format(d.format); + } const DENY_SHADER_RESOURCE: u32 = 8; if d.flags & DENY_SHADER_RESOURCE == 0 && let Some(&(_, typeless)) = DEPTH_FORMATS.iter().find(|&&(f, _)| f == d.format) @@ -840,6 +1666,9 @@ fn host_texture( // SAFETY: the title passes a whole clear value. let mut value = unsafe { clear.cast::<[u32; 5]>().read_unaligned() }; value[0] = pc_format(value[0]); + if d.flags & (TARGET | UNORDERED) != 0 { + value[0] = target_format(value[0]); + } value }); let heap = D3D12_HEAP_PROPERTIES { @@ -927,8 +1756,6 @@ fn hand_out_resource( ) -> HRESULT { #[cfg(not(windows))] let _ = (state, clear); - #[cfg(windows)] - let host = host_texture(&desc, state, clear); let resource = Box::new(Resource { object: Object::new(&RESOURCE_FUNCTIONS), desc, @@ -936,14 +1763,33 @@ fn hand_out_resource( heap_flags, backing, #[cfg(windows)] - host: host.map(|texture| { - let state = crate::host::legal_state(&texture, crate::host::texture_state(state)); - std::sync::Arc::new(HostTexture { - texture, - state: state.into(), - }) - }), + host: Hosted { + made: std::sync::Mutex::new(None), + state, + // SAFETY: the title passes a whole clear value (the format, + // then color or depth and stencil: 5 words) or null. + clear: (!clear.is_null()).then(|| unsafe { clear.cast::<[u32; 5]>().read_unaligned() }), + used: std::sync::atomic::AtomicU64::new(0), + refused: std::sync::atomic::AtomicBool::new(false), + gone: std::sync::atomic::AtomicBool::new(false), + placed: std::sync::atomic::AtomicBool::new(false), + }, }); + // The host copy waits for the texture's first use ([`Hosted`]). + #[cfg(windows)] + if desc.dimension != BUFFER { + let at = std::ptr::from_ref::(&resource) as usize; + textures().insert(at); + if !fills(&desc) { + TARGETS_AT + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(resource.data() as u64, at); + } + if !lazy() { + let _ = hosted(at as This, true); + } + } #[cfg(windows)] if desc.dimension == BUFFER { let at = std::ptr::from_ref::(&resource) as usize; @@ -955,11 +1801,28 @@ fn hand_out_resource( #[cfg(windows)] impl Drop for Resource { fn drop(&mut self) { - #[cfg(feature = "diagnostics")] - if self + // Out of the table of textures first: the sweep looks at the ones + // in it, under its lock. + if self.desc.dimension != BUFFER { + textures().remove(&(std::ptr::from_ref::(self) as usize)); + if !fills(&self.desc) { + let mut targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner()); + let at = self.data() as u64; + if targets.get(&at) == Some(&(std::ptr::from_ref::(self) as usize)) { + targets.remove(&at); + } + } + } + let made = self .host + .made + .get_mut() + .unwrap_or_else(|e| e.into_inner()) + .take(); + #[cfg(feature = "diagnostics")] + if made .as_ref() - .is_some_and(|h| std::sync::Arc::strong_count(h) > 1) + .is_some_and(|(h, _)| std::sync::Arc::strong_count(h) > 1) { // Before lists held their textures, this freed a texture that // lists not yet run still named (a GPU page fault). @@ -973,6 +1836,14 @@ impl Drop for Resource { ); } } + // A running submission may still read the host copy (and a depth + // texture's colour twin). + if let Some((host, twin)) = made { + crate::host::retire(host); + if let Some(twin) = twin { + crate::host::retire(twin); + } + } crate::texture::forget(std::ptr::from_ref::(self) as usize); crate::descriptor::forget(std::ptr::from_ref::(self) as usize); if self.desc.dimension == BUFFER { @@ -1140,13 +2011,26 @@ pub(crate) extern "system" fn create_at_address( /// resource object (device 0x230, Grand Theft Auto VI's streamed and /// interface textures), by address and description: a resource at that /// address, made the first time a draw reads one. -/// shortcut: never released (one host texture per distinct address and -/// description viewed); release them when the title unmaps or reuses the -/// memory once streaming grows VRAM use. +/// The resource is kept for the run (views and lists name its address); +/// its host texture is let go when nothing names it any more +/// ([`let_go_idle`]) and made again on the next use. #[cfg(windows)] static PLACED_TEXTURES: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); +/// The bytes of title memory a texture with the resource description +/// `desc` (as words) takes where the title placed it; `None` for a buffer +/// and for a description without a size. +#[cfg(windows)] +pub(crate) fn placed_bytes(desc: &[u32; 14]) -> Option { + // SAFETY: 56 bytes in the description's layout. + let d = unsafe { desc.as_ptr().cast::().read_unaligned() }; + if d.dimension == BUFFER { + return None; + } + footprint(&d).map(|f| f.size) +} + /// The resource for a texture placed at `address` with the resource /// description `desc` (as words), made on first use. #[cfg(windows)] @@ -1174,7 +2058,11 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { return None; } map.insert((address, *desc), out as usize); - resource(out).host.is_some().then_some(out) + resource(out) + .host + .placed + .store(true, std::sync::atomic::Ordering::Relaxed); + Some(out) } pub(crate) extern "system" fn create_placed( @@ -1783,6 +2671,684 @@ mod tests { } } + /// A 16-bit depth texture the title also asks unordered access for gets + /// a colour twin, and the host copies one into the other, both ways: a + /// pattern put into the twin is copied to the depth texture, the twin + /// is overwritten with zeros, and the pattern comes back from the depth + /// texture. A copy the host does not allow ends the test (with the + /// debug layer's message under `VICTORY_D3D12_DEBUG=1` in a diagnostics + /// build). + #[cfg(windows)] + #[test] + fn a_depth_texture_and_its_twin_copy_into_each_other() { + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + const DEPTH_WRITE: u32 = 0x10; + let desc = ResourceDesc { + flags: 6, + ..texture(4, 4, 55, 1) + }; + let mut depth = null; + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &desc, + DEPTH_WRITE, + null.cast(), + &RESOURCE_IIDS[0], + &mut depth + ), + S_OK + ); + let host_depth = host_resource(depth).unwrap(); + let Some(twin) = twin_resource(depth) else { + return; // twins are turned off + }; + // SAFETY: live resources. + let (d, t) = unsafe { (host_depth.GetDesc(), twin.GetDesc()) }; + // Both R16 typeless: one a depth texture, one with unordered access. + assert_eq!((d.Format.0, d.Flags.0), (53, 2)); + assert_eq!((t.Format.0, t.Flags.0), (53, 4)); + + // Four rows of four 16-bit texels, 256 bytes apart as copies place + // them: the pattern, then as many zeros. + let mut pattern = vec![0u8; 1024]; + for row in 0..4 { + for b in 0..8 { + pattern[row * 256 + b] = (1 + row * 8 + b) as u8; + } + } + let (upload, data) = host.upload_buffer(2048).unwrap(); + // SAFETY: the buffer's mapping, 2048 bytes. + unsafe { + std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024); + std::ptr::write_bytes(data.add(1024), 0, 1024); + } + let readback_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let readback_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option = None; + // SAFETY: plain creation of a readback buffer. + unsafe { + host.device + .CreateCommittedResource( + &readback_heap, + D3D12_HEAP_FLAG_NONE, + &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .unwrap(); + } + let readback = readback.unwrap(); + + // A texture's one subresource; the four rows of a buffer at `offset`. + let whole = |texture: &ID3D12Resource| 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: 0, + }, + }; + let rows = |buffer: &ID3D12Resource, offset: u64| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(53), + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let (written, tested, source, dest) = ( + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let moved = crate::host::transition; + let list = host.new_list().unwrap(); + // SAFETY: an open list and live resources; the two textures are one + // size in one format family. + unsafe { + let l = &list.list; + // The pattern into the twin, the twin into the depth texture. + l.ResourceBarrier(&[moved(twin, written, dest), moved(host_depth, tested, dest)]); + l.CopyTextureRegion(&whole(twin), 0, 0, 0, &rows(&upload, 0), None); + l.ResourceBarrier(&[moved(twin, dest, source)]); + l.CopyResource(host_depth, twin); + // Zeros over the twin, then the depth texture back into it. + l.ResourceBarrier(&[moved(twin, source, dest)]); + l.CopyTextureRegion(&whole(twin), 0, 0, 0, &rows(&upload, 1024), None); + l.ResourceBarrier(&[moved(host_depth, dest, source)]); + l.CopyResource(twin, host_depth); + // The twin read back; both textures to the states they had. + l.ResourceBarrier(&[moved(twin, dest, source)]); + l.CopyTextureRegion(&rows(&readback, 0), 0, 0, 0, &whole(twin), None); + l.ResourceBarrier(&[ + moved(twin, source, written), + moved(host_depth, source, tested), + ]); + } + list.close(); + host.execute(&[&list]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the copies finished (execute waits); the buffer is 1024 bytes. + let read = unsafe { + readback + .Map( + 0, + Some(&D3D12_RANGE { + Begin: 0, + End: 1024, + }), + Some(&mut mapped), + ) + .unwrap(); + std::slice::from_raw_parts(mapped.cast::(), 1024) + }; + for row in 0..4 { + let at = row * 256; + assert_eq!(read[at..at + 8], pattern[at..at + 8], "row {row}"); + } + } + + /// A depth texture with a stencil plane that the title also asks + /// unordered access for gets a twin of the stencil plane, and what + /// shaders write there is in the stencil plane once the list is closed: + /// a pattern put into the twin is read back from the plane. + #[cfg(windows)] + #[test] + fn a_stencil_planes_twin_reaches_the_plane() { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + const DEPTH_WRITE: u32 = 0x10; + let desc = ResourceDesc { + flags: 6, + ..texture(4, 4, 45, 1) + }; + let mut depth = null; + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &desc, + DEPTH_WRITE, + null.cast(), + &RESOURCE_IIDS[0], + &mut depth + ), + S_OK + ); + let host_depth = host_resource(depth).unwrap(); + let Some(twin) = twin_resource(depth) else { + return; // twins are turned off + }; + // SAFETY: live resources. + let (d, t) = unsafe { (host_depth.GetDesc(), twin.GetDesc()) }; + // R24G8 typeless with depth, R8 typeless with unordered access. + assert_eq!((d.Format.0, d.Flags.0), (44, 2)); + assert_eq!((t.Format.0, t.Flags.0), (60, 4)); + + // Four rows of four texels, 256 bytes apart as copies place them. + let mut pattern = vec![0u8; 1024]; + for row in 0..4 { + for b in 0..4 { + pattern[row * 256 + b] = (1 + row * 4 + b) as u8; + } + } + let (upload, data) = host.upload_buffer(1024).unwrap(); + // SAFETY: the buffer's mapping, 1024 bytes. + unsafe { std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024) }; + let readback_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let readback_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + // Room for the rows as the host places them (512 bytes apart + // for the stencil plane on NVIDIA, not 256). + Width: 4096, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option = None; + // SAFETY: plain creation of a readback buffer. + unsafe { + host.device + .CreateCommittedResource( + &readback_heap, + D3D12_HEAP_FLAG_NONE, + &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .unwrap(); + } + let readback = readback.unwrap(); + // How the host lays the stencil plane (subresource 1) out in a buffer. + let mut plane = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + // SAFETY: a plain query writing one footprint. + unsafe { + host.device + .GetCopyableFootprints(&d, 1, 1, 0, Some(&mut plane), None, None, None); + } + let pattern_rows = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(60), + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }; + + // A subresource of a texture; rows of a buffer. + let whole = |texture: &ID3D12Resource, index: u32| 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: index, + }, + }; + let rows = |buffer: &ID3D12Resource, placed: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: placed, + }, + } + }; + let (written, source, dest) = ( + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let moved = crate::host::transition; + + // The pattern into the twin, where a shader would write it. + let fill = host.new_list().unwrap(); + // SAFETY: an open list and live resources. + unsafe { + let l = &fill.list; + l.ResourceBarrier(&[moved(twin, written, dest)]); + l.CopyTextureRegion(&whole(twin, 0), 0, 0, 0, &rows(&upload, pattern_rows), None); + l.ResourceBarrier(&[moved(twin, dest, written)]); + } + fill.close(); + host.execute(&[&fill]); + + // A list in which a shader writes the twin: closing it copies the + // twin into the stencil plane. + let list = host.new_list().unwrap(); + assert!(list.twin_use(depth, true, true)); + list.twins_written(); + list.close(); + host.execute(&[&list]); + + // The stencil plane read back from the state the list left it in. + let state = host_copy(depth).unwrap().state.load(Relaxed); + let state = D3D12_RESOURCE_STATES(state as i32); + let back = host.new_list().unwrap(); + // SAFETY: an open list and live resources; a whole subresource. + unsafe { + let l = &back.list; + l.ResourceBarrier(&[moved(host_depth, state, source)]); + let (to, from) = (rows(&readback, plane), whole(host_depth, 1)); + l.CopyTextureRegion(&to, 0, 0, 0, &from, None); + l.ResourceBarrier(&[moved(host_depth, source, state)]); + } + back.close(); + host.execute(&[&back]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the copies finished (execute waits); the buffer is 4096 bytes. + let read = unsafe { + readback + .Map( + 0, + Some(&D3D12_RANGE { + Begin: 0, + End: 4096, + }), + Some(&mut mapped), + ) + .unwrap(); + std::slice::from_raw_parts(mapped.cast::(), 4096) + }; + let pitch = plane.Footprint.RowPitch as usize; + for row in 0..4 { + let (at, from) = (row * pitch, row * 256); + assert_eq!(read[at..at + 4], pattern[from..from + 4], "row {row}"); + } + } + + /// The depth plane of a depth-stencil texture is drawn from the plane's + /// twin when the list that wrote the twin closes: class numbers are put + /// into the twin of a texture in the console's 16-bit depth-stencil + /// format, and draws with the depth test "equal" at the depth the + /// title's lighting computes for a class (the number times the float + /// nearest 1/65535) then cover the texels of that class and no other. + #[cfg(windows)] + #[test] + fn a_depth_planes_twin_is_drawn_into_the_plane() { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Foundation::RECT; + use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + use windows::core::s; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + const DEPTH_WRITE: u32 = 0x10; + let desc = ResourceDesc { + flags: 6, + ..texture(4, 4, 118, 1) + }; + let mut depth = null; + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &desc, + DEPTH_WRITE, + null.cast(), + &RESOURCE_IIDS[0], + &mut depth + ), + S_OK + ); + let host_depth = host_resource(depth).unwrap(); + let Some(plane) = twin_plane_resource(depth) else { + return; // these twins are turned off + }; + // SAFETY: live resources. + let (d, t) = unsafe { (host_depth.GetDesc(), plane.GetDesc()) }; + // R24G8 typeless with depth, R16 typeless with unordered access. + assert_eq!((d.Format.0, d.Flags.0), (44, 2)); + assert_eq!((t.Format.0, t.Flags.0), (53, 4)); + + // Four rows of four class numbers (16 bits each), 256 bytes apart + // as copies place them. 128 and 129 are the classes whose 24-bit + // depth lies nearest a half step. + const CLASSES: [u16; 16] = [ + 8, 65, 128, 129, 65, 8, 129, 128, 0, 255, 65, 64, 129, 130, 8, 65, + ]; + let mut pattern = vec![0u8; 1024]; + for (i, class) in CLASSES.into_iter().enumerate() { + let at = i / 4 * 256 + i % 4 * 2; + pattern[at..at + 2].copy_from_slice(&class.to_le_bytes()); + } + let (upload, data) = host.upload_buffer(1024).unwrap(); + // SAFETY: the buffer's mapping, 1024 bytes. + unsafe { std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024) }; + let buffer = |kind: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut made: Option = None; + // SAFETY: plain creation of a buffer. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + state, + None, + &mut made, + ) + .unwrap(); + } + made.unwrap() + }; + let readback = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + // The colour target the draws cover: 4x4, 8 bits a texel. + let target = { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 4, + Height: 4, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT(61), + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let mut made: Option = None; + // SAFETY: plain creation of a texture. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut made, + ) + .unwrap(); + } + made.unwrap() + }; + let rows_of = |format: i32| D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(format), + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }; + // A texture's one subresource; rows of a buffer. + let whole = |texture: &ID3D12Resource| 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: 0, + }, + }; + let rows = |buffer: &ID3D12Resource, placed: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: placed, + }, + } + }; + let (written, source, dest, tested, drawn) = ( + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_RENDER_TARGET, + ); + let moved = crate::host::transition; + + // The class numbers into the twin, where a shader would write them. + let fill = host.new_list().unwrap(); + // SAFETY: an open list and live resources. + unsafe { + let l = &fill.list; + l.ResourceBarrier(&[moved(plane, written, dest)]); + l.CopyTextureRegion(&whole(plane), 0, 0, 0, &rows(&upload, rows_of(53)), None); + l.ResourceBarrier(&[moved(plane, dest, written)]); + } + fill.close(); + host.execute(&[&fill]); + + // A list in which a shader writes the twins: closing it draws the + // depth plane's twin into the plane. + let list = host.new_list().unwrap(); + assert!(list.twin_use(depth, true, true)); + list.twins_written(); + list.close(); + host.execute(&[&list]); + + // The draws: a triangle over the target at the depth of a class, + // as the title's lighting places its rectangles. + const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants = 1, b0)" +cbuffer Drawn : register(b0) { uint number; }; +[RootSignature(RS)] +float4 corner(uint i : SV_VertexID) : SV_Position { + float z = float(number) * asfloat(0x37800080); + return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, z, 1.0); +} +float4 lit() : SV_Target { return 1.0; } +"#; + let vs = crate::host::compile(SOURCE, s!("corner"), s!("vs_5_1")).unwrap(); + let ps = crate::host::compile(SOURCE, s!("lit"), s!("ps_5_1")).unwrap(); + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = 0xf; + let mut formats = [DXGI_FORMAT(0); 8]; + formats[0] = DXGI_FORMAT(61); + // SAFETY: plain creation; the description points at live data. + let (signature, pipeline) = unsafe { + let signature: ID3D12RootSignature = + host.device.CreateRootSignature(0, &vs[..]).unwrap(); + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&signature), + VS: code(&vs[..]), + PS: code(&ps[..]), + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // As the title's lighting: test "equal", nothing written. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_EQUAL, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: formats, + DSVFormat: DXGI_FORMAT(45), + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + let pipeline: ID3D12PipelineState = + host.device.CreateGraphicsPipelineState(&desc).unwrap(); + (signature, pipeline) + }; + let state = host_copy(depth).unwrap().state.load(Relaxed); + let state = D3D12_RESOURCE_STATES(state as i32); + let colour = host.rtv(Some(&target), None); + let depth_view = host.dsv( + host_depth, + Some(&D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT(45), + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + ..Default::default() + }), + ); + let back = host.new_list().unwrap(); + // SAFETY: an open list and live resources and views. + unsafe { + let l = &back.list; + if state != tested { + l.ResourceBarrier(&[moved(host_depth, state, tested)]); + } + l.ClearRenderTargetView(colour, &[0.0; 4], None); + l.SetGraphicsRootSignature(&signature); + l.SetPipelineState(&pipeline); + l.OMSetRenderTargets(1, Some(&colour), false, Some(&depth_view)); + l.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: 4.0, + Height: 4.0, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + l.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: 4, + bottom: 4, + }]); + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4)); + // Classes 65 and 129 are drawn; the others are not. + for class in [65u32, 129] { + l.SetGraphicsRoot32BitConstant(0, class, 0); + l.DrawInstanced(3, 1, 0, 0); + } + l.ResourceBarrier(&[moved(&target, drawn, source)]); + let (to, from) = (rows(&readback, rows_of(61)), whole(&target)); + l.CopyTextureRegion(&to, 0, 0, 0, &from, None); + } + back.close(); + host.execute(&[&back]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the copy finished (execute waits); the buffer is 1024 bytes. + let read = unsafe { + readback + .Map( + 0, + Some(&D3D12_RANGE { + Begin: 0, + End: 1024, + }), + Some(&mut mapped), + ) + .unwrap(); + std::slice::from_raw_parts(mapped.cast::(), 1024) + }; + for (i, class) in CLASSES.into_iter().enumerate() { + let covered = read[i / 4 * 256 + i % 4] != 0; + let drawn = matches!(class, 65 | 129); + assert_eq!(covered, drawn, "texel {i}, class {class}"); + } + } + #[test] fn committed_and_placed_resources_map_at_their_gpu_address() { let null = std::ptr::null(); diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 998ec71..082f42e 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -15,6 +15,7 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use victory_pipeline::{Cache, Converter}; use victory_shader::emit::{HostShader, StaticSampler, UserData}; +use victory_shader::resource::RootIndexedView; use victory_shader::{HwStage, RootType}; static CACHE: OnceLock = OnceLock::new(); @@ -53,6 +54,8 @@ fn build() -> &'static [u8; 32] { match exe { Ok(mut bytes) => { bytes.extend_from_slice(&limit.to_le_bytes()); + // Which group barriers wait is part of the translation too. + bytes.push(victory_shader::emit::group_sync()); *blake3::hash(&bytes).as_bytes() } Err(e) => { @@ -206,10 +209,22 @@ fn encode(s: &HostShader) -> Vec { word(&mut out, v); } } - for slots in [&s.root_cbvs, &s.root_srvs] { + for slots in [&s.root_cbvs, &s.root_srvs, &s.root_uavs] { word(&mut out, slots.len() as u32); out.extend(slots); } + word(&mut out, s.root_indexed_views.len() as u32); + for view in &s.root_indexed_views { + for value in [ + u32::from(view.table_slot), + u32::from(view.constant_slot), + view.constant_dword, + view.byte_offset, + u32::from(view.shift), + ] { + word(&mut out, value); + } + } out } @@ -266,6 +281,18 @@ fn decode(bytes: &[u8]) -> Option { } let root_cbvs = r.list()?; let root_srvs = r.list()?; + let root_uavs = r.list()?; + let n = r.word()? as usize; + let mut root_indexed_views = Vec::with_capacity(n.min(256)); + for _ in 0..n { + root_indexed_views.push(RootIndexedView { + table_slot: u8::try_from(r.word()?).ok()?, + constant_slot: u8::try_from(r.word()?).ok()?, + constant_dword: r.word()?, + byte_offset: r.word()?, + shift: u8::try_from(r.word()?).ok().filter(|&s| s < 32)?, + }); + } r.0.is_empty().then_some(HostShader { stage, dxil, @@ -274,6 +301,8 @@ fn decode(bytes: &[u8]) -> Option { static_samplers, root_cbvs, root_srvs, + root_uavs, + root_indexed_views, }) } @@ -300,6 +329,14 @@ mod tests { ])], root_cbvs: vec![2], root_srvs: vec![0, 3], + root_uavs: vec![1], + root_indexed_views: vec![RootIndexedView { + table_slot: 1, + constant_slot: 2, + constant_dword: 3, + byte_offset: 32, + shift: 5, + }], } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index c7b390b..9474869 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -16,7 +16,7 @@ //! indexed heaps keep what their first use copied. use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use windows::Win32::Graphics::Direct3D12::ID3D12Resource; @@ -40,21 +40,786 @@ pub(crate) struct Shadow { /// Ranges shaders of a submission not yet copied back may be writing: /// title memory there is older than the copy. pending: Mutex>, - /// The copy's bytes before the submission ran, from an offset on, - /// covering the ranges its shaders write: what the GPU wrote differs. - before: Mutex)>>, + /// With [`relay`]: how many submissions not yet copied back declared + /// each range of `pending` ([`Flights`]). Locked inside `pending`'s + /// lock. + flights: Mutex, + /// The copy's bytes before the submission ran, for the ranges its + /// shaders write (`pending`), each at its offset in the copy: what the + /// GPU wrote differs. Room for the whole copy; only those ranges' bytes + /// are set (and read). + before: Mutex>>, + /// With snapshots kept ([`keeps`]): which 64 KiB pieces of the snapshot + /// hold the copy's bytes as they are now, and whether the snapshot is + /// counted in [`KEPT_BYTES`]. + kept: Mutex<(Vec, bool)>, + /// When the copy was last asked for (`crate::host::moment`): a window + /// outside buffers nothing asked for in a while, and nothing holds, is + /// let go ([`let_go_idle`]). + used: AtomicU64, + /// The lowest and highest title address asked for in the copy (a + /// window is 4 MiB whatever was asked: measured for the memory line). + asked: [AtomicU64; 2], + /// Asks for the copy that gave no length (root views: they read from + /// their address to the copy's end, whatever lies there). + unsized_asks: AtomicU64, + /// A number no other copy has had. Its address is no name for a copy: + /// one let go and another made may share it. + id: u64, + /// With [`cards`], for a big title buffer: `buffer` is in the card's + /// own memory, and this is the rest of the copy. + card: Option, + /// A window of title memory outside buffers, not a title buffer's copy. + window: bool, + /// With `crate::inplace`: not a copy at all. `buffer` is placed in a + /// heap opened on the title memory itself, so shaders read and write + /// the title's own bytes and nothing is copied either way. The heap, + /// and the bytes from the buffer's first byte to `start` (the heap + /// begins on a 64 KiB line; a title buffer need not). + place: Option<(windows::Win32::Graphics::Direct3D12::ID3D12Heap, u64)>, +} + +/// What a copy in the card's memory ([`cards`]) has beside the buffer +/// shaders see. +struct Card { + /// The CPU's side, in the PC's memory: what `data` maps. Title memory + /// is copied into it as into any copy, and what changed in it goes to + /// the card's side before the next submission. + staging: ID3D12Resource, + /// The card side's bytes as they were when the submission's shaders + /// started, in the card's memory too: made when shader writes are + /// first declared for the copy, and compared with the card's side, on + /// the card, after each submission that declares some. + before: Mutex>, + /// Offsets of the copy whose bytes changed on the CPU's side and have + /// not gone to the card's side yet. + dirty: Mutex>, + /// With [`relay`]: the offsets that went from `dirty` to the card's + /// side, each with the number of the send that took it + /// ([`card_dirty`]), kept until a fetch sent after it has been merged. + /// Locked inside `dirty`'s lock. + sent: Mutex>, + /// The buffers' bytes (the title buffer's, rounded up to 64 KiB). + size: u64, +} + +/// Whether the host copies of big title buffers are in the card's own +/// memory (on by default since run 75 showed it holds: the BVH skinning +/// list went from 50.5 to 4.5 ms on the card; `VICTORY_CARD_BUFFERS=0` +/// keeps every copy in the PC's memory, as before. Read when a copy is +/// made, so it takes a fresh start). +/// +/// Every host copy was a buffer in the PC's memory that the card reads +/// and writes over the bus, so that our code can fill it and compare it. +/// The title's shaders read almost all their buffer data from a few big +/// title buffers (in the gameplay frame of run 69, 190-330 MB of distinct +/// ranges of the 174 MB heap per list against 0-13 MB elsewhere), and a +/// skinning dispatch of ONE group of 32 threads took 1.8 ms on the card +/// (run 70): the time of some 170 loads one after the other, not of the +/// arithmetic. +/// +/// With the switch, a title buffer of [`card_limits`]' size or more has two +/// sides. Shaders see `Shadow::buffer`, in the card's memory. The CPU's +/// side (`Card::staging`, what `Shadow::data` maps) takes title memory as +/// before, and the ranges that changed in it are copied to the card's side +/// before each submission (`Host::card_before`). What shaders wrote is +/// found on the card: after the submission's lists a compute pass of ours +/// compares each declared range, by 64 KiB piece, with the card side's +/// bytes from before (`Card::before`), and only the pieces that differ are +/// fetched and merged into title memory, byte by byte as +/// [`Shadow::copy_back`] does (`Host::card_back`, [`Shadow::card_merge`]). +/// No snapshot is taken and nothing is compared on the CPU for such a copy. +/// +/// What it assumes is what [`keeps`] assumes: shaders write a copy only in +/// ranges declared as written. A write outside them is seen by later +/// shaders, as before, and goes back to the title the next time a declared +/// range holds its piece (before: never). +pub(crate) fn cards() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_BUFFERS").is_none_or(|v| v != "0")) +} + +/// The smallest title buffer whose copy goes to the card's memory, and the +/// most bytes of such copies (their "before" twins not counted: a copy +/// shaders write takes its size twice), both in bytes: +/// `VICTORY_CARD_BUFFERS_MIN_MB` (16) and `VICTORY_CARD_BUFFERS_MB` (512). +/// Run 69's gameplay has ten title buffers of 16 MiB or more, 494 MB, and +/// 1,650 MB of the card's budget free. +fn card_limits() -> (u64, u64) { + static LIMITS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); + *LIMITS.get_or_init(|| { + let mb = |name: &str, default: u64| { + std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(default) << 20 + }; + (mb("VICTORY_CARD_BUFFERS_MIN_MB", 16).max(1 << 20), mb("VICTORY_CARD_BUFFERS_MB", 512)) + }) +} + +/// Bytes alive of copies' card sides, and of their "before" twins. +static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// The copies in the card's memory. +static CARDED: Mutex>> = Mutex::new(Vec::new()); + +/// Since the last frame line: bytes copied to card sides and the ranges +/// they were; pieces compared on the card, pieces fetched and their +/// bytes; the waits for the card the fetches added and their microseconds. +pub(crate) static CARD_STATS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; + +/// [`CARD_STATS`], taken; then the copies in the card's memory, their +/// bytes and their "before" twins' bytes. +pub(crate) fn card_stats() -> [u64; 10] { + let mut out = [0u64; 10]; + for (i, stat) in CARD_STATS.iter().enumerate() { + out[i] = stat.swap(0, Ordering::Relaxed); + } + out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.strong_count() > 0).count() as u64; + out[8] = CARD_BYTES[0].load(Ordering::Relaxed) + WINDOW_CARD_BYTES.load(Ordering::Relaxed); + out[9] = CARD_BYTES[1].load(Ordering::Relaxed); + out +} + +/// The bytes of the hashes kept on the card for a copy of `size` bytes: 16 +/// for each 64 KiB piece (a copy that does not start on a piece boundary +/// has one piece more). +pub(crate) fn card_hash_bytes(size: u64) -> u64 { + (size / PIECE as u64 + 2) * 16 +} + +/// A buffer of `size` bytes in the card's memory for a title buffer's +/// copy, if the copy is to be there: [`cards`] is on, the size is within +/// [`card_limits`] and below 1 GiB (the compare counts in 32 bits), and the +/// host has what it takes (`Host::card_ready`). +fn card_for(size: u64) -> Option { + if !cards() { + return None; + } + let (least, most) = card_limits(); + if size < least || size >= 1 << 30 { + return None; + } + let host = host()?; + if !host.card_ready() { + return None; + } + // Only while the card has room: with this copy on it, a fifth of the + // budget the system gives us must still be free. Copies are made when + // the world loads, before the textures fill the card; the texture + // queue's own rule (`resource::room`: nine tenths of the budget) counts + // them, so the card's use stays where it was and the textures' share + // shrinks by the copies' bytes, at most `card_limits`' second number. + if let Some([budget, used, ..]) = host.video_memory() + && used + size > budget / 10 * 8 + { + return None; + } + if CARD_BYTES[0].fetch_add(size, Ordering::Relaxed) + size > most { + CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed); + return None; + } + let buffer = host.uav_buffer(size); + if buffer.is_none() { + CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed); + } + buffer +} + +/// The most bytes of windows outside buffers whose copies go to the card's +/// memory (`VICTORY_CARD_WINDOWS_MB`; 0, the default, none). +/// +/// Windows are two thirds of the PC memory the card shares (run 104: 861 +/// windows, 3,552 MB of 5,400), and every draw that takes vertices, indices +/// or constants from the title's own allocator reads them over the bus. +/// Shaders write none of them (run 91: "0.0 MB compared in 0 ranges of +/// windows"), so a window on the card needs only what a card copy has +/// already: the CPU's side takes title memory as before, and what changed +/// in it goes up before each submission. No hashes, no compare, no fetch, +/// unless a shader does declare a write to it one day. +/// +/// A window goes to the card while there is room under this number and +/// while a fifth of the card's budget is free, as title buffers do +/// (`card_for`): textures keep their room, and once they have filled the +/// card later windows stay where they are. The CPU's side stays in the PC's +/// memory, so the memory shared with the card does not shrink by this +/// alone; what moves is what shaders read. +fn window_card_most() -> u64 { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_CARD_WINDOWS_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0) << 20 + }) +} + +/// Bytes alive of windows' card sides ([`window_card_most`]). +static WINDOW_CARD_BYTES: AtomicU64 = AtomicU64::new(0); + +/// A buffer in the card's memory for a window of `size` bytes, if it is to +/// be there ([`window_card_most`]). +fn window_card_for(size: u64) -> Option { + let most = window_card_most(); + if most == 0 || !cards() { + return None; + } + let host = host()?; + if !host.card_ready() { + return None; + } + if let Some([budget, used, ..]) = host.video_memory() + && used + size > budget / 10 * 8 + { + return None; + } + if WINDOW_CARD_BYTES.fetch_add(size, Ordering::Relaxed) + size > most { + WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); + return None; + } + let buffer = host.uav_buffer(size); + if buffer.is_none() { + WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); + } + buffer +} + +/// The copies in the card's memory whose CPU side changed since they were +/// last asked: each with the changed offsets, in order and joined where +/// they touch. The ranges are taken: the caller copies them to the card's +/// side (`Host::card_before`). +/// +/// With [`relay`], `sent_as` is the number of the send that takes them +/// (`crate::host`'s order of the queue): each range is noted with it, in +/// the same lock that took it, so that a merge of pieces fetched before +/// that send knows the card did not hold these bytes yet +/// ([`Shadow::card_merge_relay`]). Notes of sends that every fetch still to +/// be merged came after are dropped. +pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc, Vec<(usize, usize)>)> { + let mut out = Vec::new(); + let mut carded = CARDED.lock().unwrap_or_else(|e| e.into_inner()); + let fetched = RELAY_FETCHED.load(Ordering::Acquire); + carded.retain(|weak| { + let Some(shadow) = weak.upgrade() else { + return false; + }; + let ranges = shadow + .card + .as_ref() + .map(|c| { + let mut dirty = c.dirty.lock().unwrap_or_else(|e| e.into_inner()); + let ranges = std::mem::take(&mut *dirty); + if relay() { + let mut sent = c.sent.lock().unwrap_or_else(|e| e.into_inner()); + sent.retain(|s| s.2 > fetched); + sent.extend(ranges.iter().map(|&(a, b)| (a, b, sent_as))); + } + ranges + }) + .unwrap_or_default(); + if !ranges.is_empty() { + out.push((shadow, joined(ranges))); + } + true + }); + out +} + +/// Ranges in order, those that overlap or touch as one. +fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> { + ranges.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); + for (from, to) in ranges { + match out.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => out.push((from, to)), + } + } + out +} + +/// Runs of pieces to hash again (`Host::card_before`), those that overlap +/// or touch as one, in order: every piece of `runs` is in the result once +/// and no other piece is. Ranges sent up lie close together (514 a frame +/// for 87 MB in run 102), and each had a pass of its own over its pieces, +/// 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()); + for run in runs { + match out.last_mut() { + Some(last) if run.first <= last.first + last.pieces => { + last.pieces = last.pieces.max(run.first + run.pieces - last.first); + last.to = last.to.max(run.to); + } + _ => out.push(run), + } + } + out +} + +/// A declared range of a copy in the card's memory, as the compare on the +/// card takes it: its offsets in the copy, its first 64 KiB piece (pieces +/// are cut at multiples of 64 KiB of title memory; piece 0 holds offset +/// 0), how many pieces hold it, and where the copy starts in piece 0. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct CardSpan { + pub(crate) from: u32, + pub(crate) to: u32, + pub(crate) first: u32, + pub(crate) pieces: u32, + pub(crate) skew: u32, +} + +/// [`CardSpan`] for offsets `[from, to)` (`from < to`) of a copy of title +/// memory from `start` on. +fn card_span_of(start: usize, from: usize, to: usize) -> CardSpan { + let pieces = pieces_of(start, from, to); + CardSpan { + from: from as u32, + to: to as u32, + first: pieces.start as u32, + pieces: pieces.len() as u32, + skew: (start % PIECE) as u32, + } +} + +/// The offsets of piece `i` of `span` that lie in the span, for a copy of +/// `len` bytes of title memory from `start` on: what is fetched and merged +/// of a piece the compare found differing. +fn card_piece_of(start: usize, len: usize, span: &CardSpan, i: u32) -> (usize, usize) { + let (lo, hi) = piece_at(start, len, (span.first + i) as usize); + (lo.max(span.from as usize), hi.min(span.to as usize)) +} + +#[cfg(test)] +mod card_tests { + use super::{CardSpan, PIECE, card_piece_of, card_span_of, joined, joined_piece_runs}; + + /// Joined runs hold every piece of the runs given, once, and no other. + #[test] + fn piece_runs_join_without_losing_or_adding_pieces() { + let run = |first: u32, pieces: u32| CardSpan { + from: first * 65536, + to: (first + pieces) * 65536, + first, + pieces, + skew: 7, + }; + let runs = vec![run(40, 1), run(3, 2), run(4, 1), run(5, 3), run(40, 1), run(9, 1), run(41, 2), run(100, 1)]; + let mut wanted: Vec = runs.iter().flat_map(|r| r.first..r.first + r.pieces).collect(); + wanted.sort_unstable(); + wanted.dedup(); + let joined = joined_piece_runs(runs); + let got: Vec = joined.iter().flat_map(|r| r.first..r.first + r.pieces).collect(); + assert_eq!(got, wanted); + assert_eq!(joined.iter().map(|r| (r.first, r.pieces)).collect::>(), [(3, 5), (9, 1), (40, 3), (100, 1)]); + assert!(joined.iter().all(|r| r.skew == 7)); + assert!(joined_piece_runs(Vec::new()).is_empty()); + } + + /// The offsets the compare's shader takes for a piece (`CARD_COMPARE` + /// in host.rs), before it widens them to 16 bytes. + fn shader_piece(span: &CardSpan, i: u32) -> (u32, u32) { + let piece = span.first + i; + let lo = piece * 65536; + let lo = if lo > span.skew { lo - span.skew } else { 0 }; + let hi = (piece + 1) * 65536 - span.skew; + (lo.max(span.from), hi.min(span.to)) + } + + /// The pieces of a span cover it without gaps, and the shader's + /// arithmetic names the same bytes as ours. + #[test] + fn the_shader_and_the_merge_cut_the_same_pieces() { + for start in [0usize, 4096, PIECE - 16, PIECE, 3 * PIECE + 0x1f00, 0xd_b790_df00] { + let len = 5 * PIECE + 4096; + for (from, to) in [(0, len), (0, 1), (16, PIECE), (PIECE - 4, PIECE + 4), (2 * PIECE, len), (12345, 4 * PIECE + 7)] { + let span = card_span_of(start, from, to); + let mut at = from; + for i in 0..span.pieces { + let (lo, hi) = card_piece_of(start, len, &span, i); + assert_eq!(lo, at, "{start:#x} {from} {to} piece {i}"); + assert!(hi > lo && hi - lo <= PIECE); + assert_eq!(shader_piece(&span, i), (lo as u32, hi as u32), "{start:#x} {from} {to} piece {i}"); + at = hi; + } + assert_eq!(at, to, "{start:#x} {from} {to}"); + } + } + } + + /// Changed ranges are joined where they overlap or touch, and only there. + #[test] + fn ranges_join_where_they_touch() { + assert_eq!(joined(vec![(8, 12), (0, 4), (4, 6), (10, 20), (30, 31)]), [(0, 6), (8, 20), (30, 31)]); + assert!(joined(Vec::new()).is_empty()); + } +} + +/// Whether the copy-back of what shaders wrote runs on a thread of its own, +/// beside the submitting thread and outside the submission lock +/// (`VICTORY_RELAY=1` or `2`; off by default; not with kept snapshots, +/// [`keeps`]). `crate::host::relay` says what it does; here it changes +/// what a copy keeps: +/// +/// - the ranges shaders may be writing are counted per submission +/// ([`Flights`]): a range two flights declared stays closed to refreshes +/// until both have been copied back; +/// - the merge of what the card wrote never stores into memory the card +/// may be writing ([`merge_piece`]): what it learns goes into title +/// memory and into the copy's reference (the snapshot, or the CPU's side +/// of a copy in the card's memory), under that reference's lock; +/// - what goes up to a copy in the card's memory is numbered +/// ([`card_dirty`]), so that a merge can tell the title's bytes the card +/// had not received from bytes the card wrote. +pub(crate) fn relay() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_RELAY").is_ok_and(|v| v == "1" || v == "2") && !keeps()) +} + +/// The submission being prepared (its number among those started): what +/// [`Shadow::writing`] counts a declared range for ([`Flights`]). +static PREPARED: AtomicU64 = AtomicU64::new(0); + +/// A submission's preparing begins (`crate::host`, under the submission +/// lock). +pub(crate) fn preparing(number: u64) { + PREPARED.store(number, Ordering::Relaxed); +} + +/// With [`relay`]: the number of the last send of changed ranges to the +/// card (`crate::host`'s order of the queue) that every fetch still to be +/// merged came after. Notes of sends up to it are of no use any more. +static RELAY_FETCHED: AtomicU64 = AtomicU64::new(0); + +/// A fetch sent after send `number` is the oldest one that may still be +/// merged ([`RELAY_FETCHED`]). +pub(crate) fn relay_fetched(number: u64) { + RELAY_FETCHED.fetch_max(number, Ordering::AcqRel); +} + +/// With [`relay`]: how many submissions that are not copied back yet +/// declared each range shaders may be writing (range, count, the last +/// submission that declared it). +/// +/// Without it a range declared by two flights was one entry, and the end +/// of the first flight's copy-back removed it while the second was still +/// writing: the next refresh would have put title bytes over what the +/// second flight's shaders were writing. +#[derive(Default)] +struct Flights(Vec<((usize, usize), u32, u64)>); + +impl Flights { + /// Submission `number` declares `range`: counted once for it, however + /// often it declares it. + fn declare(&mut self, range: (usize, usize), number: u64) { + match self.0.iter_mut().find(|f| f.0 == range) { + Some(f) => { + if f.2 != number { + f.1 += 1; + f.2 = number; + } + } + None => self.0.push((range, 1, number)), + } + } + + /// One submission that declared `ranges` (each once) is copied back: + /// the ranges no other submission still holds. + fn done(&mut self, ranges: &[(usize, usize)]) -> Vec<(usize, usize)> { + let mut free = Vec::new(); + for range in ranges { + match self.0.iter().position(|f| f.0 == *range) { + Some(at) => { + self.0[at].1 = self.0[at].1.saturating_sub(1); + if self.0[at].1 == 0 { + self.0.swap_remove(at); + free.push(*range); + } + } + // Not counted (declared before anything counted): free. + None => free.push(*range), + } + } + free + } +} + +/// The relay's merge of a stretch of a copy ([`relay`]). `now` is what the +/// card's memory holds, read once; `held` is the copy's reference for the +/// stretch (its snapshot, or the CPU's side of a copy in the card's +/// memory): what the card's memory held when it was last looked at; +/// `title` is title memory as just read. Every byte the card changed +/// (`now` differs from `held`) goes into `title` and into `held`; every +/// other byte of both stays as it is, so a byte the title wrote and the +/// card did not keeps the title's value. Whether `title` changed. +/// +/// Nothing is stored into `now`'s source: the card may be writing it for a +/// later flight at this moment, and a store there, even of the value just +/// read, could undo that write. (The merge of a waited-for submission +/// stores every byte of a differing stretch back into the copy.) +fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { + let mut differs = 0u8; + for ((n, h), t) in now.iter().zip(held.iter_mut()).zip(title.iter_mut()) { + let wrote = if *n != *h { 0xffu8 } else { 0 }; + let merged = (*t & !wrote) | (*n & wrote); + differs |= merged ^ *t; + *t = merged; + *h = (*h & !wrote) | (*n & wrote); + } + differs != 0 +} + +/// `[from, to)` without the ranges of `skip`, in order. +fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, usize)> { + skip.sort_unstable(); + let mut out = Vec::new(); + let mut at = from; + for (a, b) in skip { + if b <= at { + continue; + } + if a >= to { + break; + } + if a > at { + out.push((at, a)); + } + at = at.max(b); + } + if at < to { + out.push((at, to)); + } + out +} + +#[cfg(test)] +mod relay_tests { + use super::{Flights, changed_runs, merge_piece, outside}; + + /// A range two flights declared is free only when both are done, in + /// either order; a submission that declares it many times counts once. + #[test] + fn a_range_stays_closed_until_every_flight_that_declared_it_is_done() { + let (a, b) = ((0x1000, 0x2000), (0x1800, 0x3000)); + let mut flights = Flights::default(); + for _ in 0..3 { + flights.declare(a, 7); + } + flights.declare(b, 7); + flights.declare(a, 8); + // Flight 7 lands: `a` is still flight 8's, `b` was only flight 7's. + assert_eq!(flights.done(&[a, b]), vec![b]); + // Declared again meanwhile by a third. + flights.declare(a, 9); + assert_eq!(flights.done(&[a]), vec![]); + assert_eq!(flights.done(&[a]), vec![a]); + assert!(flights.0.is_empty()); + // The later flight first: the same. + flights.declare(a, 1); + flights.declare(a, 2); + assert_eq!(flights.done(&[a]), vec![]); + assert_eq!(flights.done(&[a]), vec![a]); + // A range never counted is free at once. + assert_eq!(flights.done(&[b]), vec![b]); + } + + /// The merge moves exactly the bytes the card changed, into title + /// memory and into the reference, and stores nothing else. + #[test] + fn the_merge_stores_only_what_the_card_changed() { + let held0: Vec = (0..200u32).map(|i| (i * 5 + 1) as u8).collect(); + let mut now = held0.clone(); + for at in [0usize, 3, 4, 5, 64, 199] { + now[at] ^= 0x33; + } + // The title wrote other bytes meanwhile, and one the card wrote too. + let mut title = held0.clone(); + for at in [1usize, 5, 100] { + title[at] = 0xee; + } + let title0 = title.clone(); + let mut held = held0.clone(); + assert!(merge_piece(&now, &mut held, &mut title)); + for at in 0..200 { + if now[at] != held0[at] { + assert_eq!((title[at], held[at]), (now[at], now[at]), "the card's byte at {at}"); + } else { + assert_eq!((title[at], held[at]), (title0[at], held0[at]), "untouched at {at}"); + } + } + // Again with nothing new: nothing changes and nothing is reported. + let (title1, held1) = (title.clone(), held.clone()); + assert!(!merge_piece(&now, &mut held, &mut title)); + assert_eq!((title, held), (title1, held1)); + } + + #[test] + fn ranges_are_cut_out() { + assert_eq!(outside(10, 50, vec![]), vec![(10, 50)]); + assert_eq!(outside(10, 50, vec![(0, 10), (50, 60)]), vec![(10, 50)]); + assert_eq!(outside(10, 50, vec![(30, 35), (0, 12), (34, 40), (48, 99)]), vec![(12, 30), (40, 48)]); + assert_eq!(outside(10, 50, vec![(0, 99)]), vec![]); + } + + /// A model of a copy in the PC's memory under the relay: the card + /// writes `copy` directly; `snap` is the snapshot; `title` is title + /// memory. Flight A and flight B declare overlapping ranges and both + /// are in the air; the title's CPU writes in between and its bytes are + /// put in beside the flights' (`merge_under_writes`: into the copy and + /// the snapshot); A lands while B is still writing; then B lands. + #[test] + fn two_flights_overlapping_ranges_and_a_cpu_write_in_between() { + const N: usize = 64; + let base: Vec = (0..N as u32).map(|i| i as u8).collect(); + let (mut copy, mut title) = (base.clone(), base.clone()); + // A declares [0, 40), B declares [24, 64): each byte's snapshot is + // taken when the first range that holds it is declared. + let (a, b) = ((0usize, 40usize), (24usize, 64usize)); + let mut snap = base.clone(); + // The card runs A: writes 4..12 and 30..34. + for at in (4..12).chain(30..34) { + copy[at] = 0xa0; + } + // The title's CPU writes 8..10 (over A's bytes), 20 and 50, after + // A's refresh: the next submission's preparing finds them against + // the snapshot and puts them in, into the copy and the snapshot. + for at in [8usize, 9, 20, 50] { + title[at] = 0x77; + } + for (at, n) in changed_runs(&title, &snap) { + copy[at..at + n].copy_from_slice(&title[at..at + n]); + snap[at..at + n].copy_from_slice(&title[at..at + n]); + } + // The card starts B: it has written 32..36 so far, over A's 32..34. + for at in 32..36 { + copy[at] = 0xb0; + } + // A lands (B still on the card): its range is merged. The copy is + // read once and not written. + let seen = copy.clone(); + { + let mut t = title[a.0..a.1].to_vec(); + assert!(merge_piece(&seen[a.0..a.1], &mut snap[a.0..a.1], &mut t)); + title[a.0..a.1].copy_from_slice(&t); + } + assert_eq!(copy, seen, "the merge stores nothing into the copy"); + // A's bytes are in title memory, except where the title wrote + // after A's shaders did (8, 9: the title's); B's first bytes came + // along; nothing of B's range beyond A's was touched. + for at in (4..8).chain(10..12).chain(30..32) { + assert_eq!(title[at], 0xa0, "A's byte at {at}"); + } + assert_eq!((title[8], title[9], title[20], title[50]), (0x77, 0x77, 0x77, 0x77)); + for at in 32..36 { + assert_eq!(title[at], 0xb0, "B's byte so far at {at}"); + } + // The card finishes B: 36..44. + for at in 36..44 { + copy[at] = 0xb1; + } + // The title's CPU writes 40 after B's shader did: found against + // the snapshot at the next preparing, which is before B lands. + title[40] = 0x55; + for (at, n) in changed_runs(&title[b.0..b.1], &snap[b.0..b.1]) { + let at = at + b.0; + copy[at..at + n].copy_from_slice(&title[at..at + n]); + snap[at..at + n].copy_from_slice(&title[at..at + n]); + } + // B lands. + let seen = copy.clone(); + { + let mut t = title[b.0..b.1].to_vec(); + assert!(merge_piece(&seen[b.0..b.1], &mut snap[b.0..b.1], &mut t)); + title[b.0..b.1].copy_from_slice(&t); + } + // B's results are there, never replaced by A's older ones. + for at in 32..36 { + assert_eq!(title[at], 0xb0); + } + for at in (36..40).chain(41..44) { + assert_eq!(title[at], 0xb1, "B's byte at {at}"); + } + assert_eq!(title[40], 0x55, "the title wrote it last"); + // In the declared ranges the copy, the snapshot and title memory + // now agree byte for byte: nothing is left to hand back, and + // nothing was lost. + assert_eq!(copy[a.0..b.1], title[a.0..b.1]); + assert_eq!(snap[a.0..b.1], title[a.0..b.1]); + // A third merge finds nothing. + let mut t = title.clone(); + assert!(!merge_piece(©, &mut snap, &mut t)); + } + + /// A model of a copy in the card's memory under the relay: `card` is + /// the card's side, `cpu` the CPU's side, `title` title memory. The + /// title's changed bytes go into the CPU's side at once and up to the + /// card with a later send; pieces fetched before that send must not + /// take the card's older bytes there for something the card wrote. + #[test] + fn title_bytes_not_yet_on_the_card_are_not_taken_for_shader_writes() { + const N: usize = 48; + let base: Vec = (0..N as u32).map(|i| (i + 100) as u8).collect(); + let (mut card, mut cpu, mut title) = (base.clone(), base.clone(), base.clone()); + // Flight A's shaders write 10..14 on the card. + for at in 10..14 { + card[at] = 0xa0; + } + // The title's CPU writes 12 (over A's) and 30; the preparing of + // the next submission puts both into the CPU's side and notes them + // to go up (send 5). They are not on the card yet. + title[12] = 0x77; + title[30] = 0x78; + let mut noted = Vec::new(); + for (at, n) in changed_runs(&title, &cpu) { + cpu[at..at + n].copy_from_slice(&title[at..at + n]); + noted.push((at, at + n, 5u64)); + } + // A's pieces are fetched after send 4, before send 5: the fetch + // holds A's bytes and the card's old bytes at 12 and 30. + let fetched = card.clone(); + let fetched_after = 4u64; + // Send 5 goes up behind it. + for &(a, b, _) in ¬ed { + card[a..b].copy_from_slice(&cpu[a..b]); + } + // The merge leaves out what went up after the fetch. + let skip: Vec<(usize, usize)> = noted.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1)).collect(); + let mut changed = false; + for (a, b) in outside(0, N, skip) { + let mut t = title[a..b].to_vec(); + changed |= merge_piece(&fetched[a..b], &mut cpu[a..b], &mut t); + title[a..b].copy_from_slice(&t); + } + assert!(changed); + // A's bytes arrived; the title's two writes stand, in title memory + // and on both sides of the copy. + for at in [10usize, 11, 13] { + assert_eq!((title[at], cpu[at]), (0xa0, 0xa0)); + } + assert_eq!((title[12], cpu[12], card[12]), (0x77, 0x77, 0x77)); + assert_eq!((title[30], cpu[30], card[30]), (0x78, 0x78, 0x78)); + assert_eq!(card, cpu); + assert_eq!(card, title); + // Without the leaving out, the card's old byte at 30 would have + // been taken for a shader write and put over the title's. + let mut wrong_title = title.clone(); + let mut wrong_cpu = cpu.clone(); + merge_piece(&fetched, &mut wrong_cpu, &mut wrong_title); + assert_eq!(wrong_title[30], base[30]); + } } /// Snapshot memory kept for reuse (already touched, so no page faults). static POOL: Mutex>> = Mutex::new(Vec::new()); -/// An empty buffer with room for `n` bytes, from the pool if it has one. +/// An empty buffer with room for `n` bytes, from the pool if it has one +/// of about that size: a small copy's snapshot took the 174 MB buffer kept +/// for the big heap's, which then got another, until eight of them were +/// reserved (1.4 GB in run 24). fn pooled(n: usize) -> Vec { let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let most = n.saturating_mul(4).max(1 << 20); let fit = pool .iter() .enumerate() - .filter(|(_, v)| v.capacity() >= n) + .filter(|(_, v)| v.capacity() >= n && v.capacity() <= most) .min_by_key(|(_, v)| v.capacity()) .map(|(i, _)| i); let mut v = match fit { @@ -65,18 +830,803 @@ fn pooled(n: usize) -> Vec { v } -/// Returns a snapshot buffer to the pool (at most 8 kept, the largest). +/// Returns a snapshot buffer to the pool: at most 8 kept, the largest, and +/// of those the largest one and the next ones up to `KEPT` bytes in all. fn give_back(v: Vec) { + const KEPT: usize = 512 << 20; let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); pool.push(v); - if pool.len() > 8 { - pool.sort_by_key(|v| std::cmp::Reverse(v.capacity())); - pool.truncate(8); - } + pool.sort_by_key(|v| std::cmp::Reverse(v.capacity())); + pool.truncate(8); + let (mut seen, mut total) = (0, 0usize); + pool.retain(|v| { + seen += 1; + total = total.saturating_add(v.capacity()); + seen == 1 || total <= KEPT + }); } const NOT_WATCHED: u8 = 2; +/// Where `a` and `b` (of one length) first differ, compared eight bytes at +/// a time. +fn first_difference(a: &[u8], b: &[u8]) -> Option { + let whole = a.len().min(b.len()) / 8 * 8; + let from = a[..whole] + .chunks_exact(8) + .zip(b[..whole].chunks_exact(8)) + .position(|(x, y)| x != y) + .map_or(whole, |word| word * 8); + a[from..].iter().zip(&b[from..]).position(|(x, y)| x != y).map(|i| from + i) +} + +/// Where `a` and `b` (of one length) last differ. +fn last_difference(a: &[u8], b: &[u8]) -> Option { + let whole = a.len().min(b.len()) / 8 * 8; + if let Some(i) = a[whole..].iter().zip(&b[whole..]).rposition(|(x, y)| x != y) { + return Some(whole + i); + } + let word = a[..whole] + .chunks_exact(8) + .zip(b[..whole].chunks_exact(8)) + .rposition(|(x, y)| x != y)? + * 8; + a[word..word + 8] + .iter() + .zip(&b[word..word + 8]) + .rposition(|(x, y)| x != y) + .map(|i| word + i) +} + +#[cfg(test)] +mod difference_tests { + use super::{first_difference, last_difference}; + + /// The word-wise searches agree with the byte-wise ones they replace. + #[test] + fn differences_are_found_as_byte_by_byte() { + let base: Vec = (0..61u32).map(|i| (i * 7 + 3) as u8).collect(); + let same = base.clone(); + assert_eq!(first_difference(&base, &same), None); + assert_eq!(last_difference(&base, &same), None); + for len in [0usize, 1, 7, 8, 9, 16, 23, 61] { + for at in 0..len { + for other in at..len { + let (a, mut b) = (&base[..len], base[..len].to_vec()); + b[at] ^= 0x80; + b[other] ^= 0x01; + let first = a.iter().zip(&b).position(|(x, y)| x != y); + let last = a.iter().zip(&b).rposition(|(x, y)| x != y); + assert_eq!(first_difference(a, &b), first, "{len} {at} {other}"); + assert_eq!(last_difference(a, &b), last, "{len} {at} {other}"); + } + } + } + } +} + +/// The unit shader writes are looked for and put back in. +const PIECE: usize = 64 << 10; + +/// Copies `len` bytes, on several threads if they are many: a snapshot of +/// the world's big heap is 100-170 MB per submission, 2-4 GB a frame, and +/// one thread copies some 8 GB/s. +/// +/// # Safety +/// Both ranges are valid for `len` bytes and do not overlap. +unsafe fn copy_wide(src: *const u8, dst: *mut u8, len: usize) { + const PER_THREAD: usize = 16 << 20; + let threads = (len / PER_THREAD).clamp(1, 6); + if threads == 1 { + // SAFETY: the caller's. + unsafe { std::ptr::copy_nonoverlapping(src, dst, len) }; + return; + } + let (src, dst, each) = (src as usize, dst as usize, len.div_ceil(threads)); + std::thread::scope(|s| { + for i in 0..threads { + let at = (i * each).min(len); + let n = each.min(len - at); + s.spawn(move || { + // SAFETY: a part of the caller's ranges. + unsafe { std::ptr::copy_nonoverlapping((src + at) as *const u8, (dst + at) as *mut u8, n) }; + }); + } + }); +} + +/// Whether the snapshots of a submission's shader-written ranges, and the +/// compare that finds what the shaders wrote, run on several threads +/// across ranges (`VICTORY_WIDE_BACK=1`; off by default). +/// +/// Both ran range by range on the submitting thread, a range on several +/// threads only if it was 16 MiB or more. The ranges left on the CPU's side +/// since the big buffers went to the card are small and many: in run 86, +/// 7,024 declared ranges a frame, 375 MB of them compared after the card +/// ran in 563 pieces of work, none of 16 MiB: 51 ms a frame of snapshots +/// and 35 ms of comparing, one thread, bound by one core's memory speed. +/// +/// With the switch a submission's snapshots are noted as it is prepared +/// and taken together when its refreshes are done, just before it goes to +/// the card ([`take_snapshots`]), and the compares of everything declared +/// run together after the card ([`find_all`]), both cut into pieces of +/// work of about 1 MiB for a few threads that are kept ([`wide`]). The +/// bytes taken and the bytes compared are the same ones: a range's bytes +/// cannot change between the moment it is declared and the end of the +/// preparing (a declared range is left alone by every refresh, the title's +/// own copies write title memory and not the copy, and the card runs the +/// lists only afterwards). +pub(crate) fn wide_back() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_BACK").is_some_and(|v| v == "1")) +} + +type Job = Box; + +/// Threads kept for [`wide`]: what they are to do, and the word that there +/// is something. +struct Workers { + jobs: Mutex>, + more: std::sync::Condvar, +} + +fn workers() -> &'static Workers { + static WORKERS: std::sync::OnceLock = std::sync::OnceLock::new(); + static STARTED: std::sync::Once = std::sync::Once::new(); + let workers = WORKERS.get_or_init(|| Workers { + jobs: Mutex::new(std::collections::VecDeque::new()), + more: std::sync::Condvar::new(), + }); + STARTED.call_once(|| { + let n = std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6); + for i in 0..n { + let _ = std::thread::Builder::new().name(format!("victory-wide-{i}")).spawn(move || { + let workers = WORKERS.get().expect("made above"); + loop { + let job = { + let mut jobs = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(job) = jobs.pop_front() { + break job; + } + jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner()); + } + }; + job(); + } + }); + } + }); + workers +} + +/// Runs `jobs` on the kept threads and on this one, and returns when all +/// of them are done. The jobs copy and compare memory; they do not panic. +fn wide(jobs: Vec) { + if jobs.len() < 2 { + for job in jobs { + job(); + } + return; + } + let workers = workers(); + let left = Arc::new((Mutex::new(jobs.len()), std::sync::Condvar::new())); + { + let mut queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); + for job in jobs { + let left = left.clone(); + queue.push_back(Box::new(move || { + job(); + let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner()); + *n -= 1; + if *n == 0 { + left.1.notify_all(); + } + })); + } + } + workers.more.notify_all(); + loop { + let job = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()).pop_front(); + match job { + Some(job) => job(), + None => break, + } + } + 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()); + } +} + +/// [`wide`], for the host's own work on host copies (a submission's +/// refreshes, the merge of what shaders wrote to card copies). +pub(crate) fn wide_run(jobs: Vec>) { + wide(jobs); +} + +/// About this many bytes to a piece of work for [`wide`]. +const WIDE_JOB: usize = 1 << 20; + +/// With [`wide_back`]: the snapshots noted while a submission is prepared +/// (from, to, bytes), taken by [`take_snapshots`]. +static SNAPS: Mutex> = Mutex::new(Vec::new()); + +/// With [`wide_back`], when a submission's refreshes are done and before +/// its lists go to the card: takes the snapshots [`Shadow::writing`] noted. +/// Nothing to do without the switch. +pub(crate) fn take_snapshots() { + let snaps = std::mem::take(&mut *SNAPS.lock().unwrap_or_else(|e| e.into_inner())); + if snaps.is_empty() { + return; + } + wide(copy_jobs(snaps)); +} + +/// `copies` (from, to, bytes) as pieces of work of about [`WIDE_JOB`] +/// bytes each: long ones cut, short ones together. +fn copy_jobs(copies: Vec<(usize, usize, usize)>) -> Vec { + let mut jobs: Vec = Vec::new(); + let mut group: Vec<(usize, usize, usize)> = Vec::new(); + let mut bytes = 0; + let flush = |group: &mut Vec<(usize, usize, usize)>, jobs: &mut Vec| { + let group = std::mem::take(group); + if !group.is_empty() { + jobs.push(Box::new(move || { + for (src, dst, len) in group { + // SAFETY: the caller's ranges: a host copy's mapping and + // its snapshot, which do not overlap. + unsafe { std::ptr::copy_nonoverlapping(src as *const u8, dst as *mut u8, len) }; + } + })); + } + }; + for (src, dst, len) in copies { + let mut at = 0; + while at < len { + let n = (WIDE_JOB - bytes).min(len - at); + group.push((src + at, dst + at, n)); + at += n; + bytes += n; + if bytes >= WIDE_JOB { + flush(&mut group, &mut jobs); + bytes = 0; + } + } + } + flush(&mut group, &mut jobs); + jobs +} + +/// With [`wide_back`]: for each of `work` (a copy not in the card's memory +/// and a range `[address, end)` its shaders may have written, declared and +/// not yet done), the 64 KiB pieces that differ from the snapshot, as +/// [`Shadow::copy_back_with`] takes them; found on several threads. +pub(crate) fn find_all(work: &[(Arc, usize, usize)]) -> Vec> { + let scans = work + .iter() + .map(|(shadow, address, end)| { + let (from, to) = shadow.inside(*address, end.saturating_sub(*address)); + // The snapshot's memory stays until the range is done with + // (`copy_back_done`), which comes after this. + match shadow.before.lock().unwrap_or_else(|e| e.into_inner()).as_ref() { + Some(before) => (shadow.data as usize, before.as_ptr() as usize, shadow.start as usize, from, to), + None => (0, 0, 0, 0, 0), + } + }) + .collect(); + find_pieces(scans) +} + +/// For each of `scans` (where a copy's bytes are, where its snapshot's +/// are, the title address the copy starts at, offsets from and to): the +/// 64 KiB pieces (cut at multiples of 64 KiB of title memory, as +/// [`Shadow::differing`] cuts them) of `[from, to)` whose bytes differ, as +/// (offset, bytes) in order. On several threads ([`wide`]), in pieces of +/// work of about [`WIDE_JOB`] bytes that hold whole pieces. +fn find_pieces(scans: Vec<(usize, usize, usize, usize, usize)>) -> Vec> { + // What a job finds: (which scan, its place among that scan's jobs, the + // pieces). + type Found = Vec<(usize, usize, Vec<(usize, usize)>)>; + // A job's part of a scan: the scan, then which and place. + type Part = (usize, usize, usize, usize, usize, usize, usize); + let found: Arc> = Arc::default(); + let mut jobs: Vec = Vec::new(); + let mut group: Vec = Vec::new(); + let mut bytes = 0; + let flush = |group: &mut Vec, jobs: &mut Vec| { + let group = std::mem::take(group); + if group.is_empty() { + return; + } + let found = found.clone(); + jobs.push(Box::new(move || { + let mut mine: Found = Vec::with_capacity(group.len()); + for (data, before, start, from, to, which, place) in group { + let mut pieces = Vec::new(); + let mut at = from; + while at < to { + let n = (PIECE - (start + at) % PIECE).min(to - at); + // SAFETY: inside the copy's mapping and its snapshot + // (which holds the copy's bytes at the copy's offsets); + // nothing writes either while a submission's results + // are compared. + let (now, old) = unsafe { + ( + std::slice::from_raw_parts((data + at) as *const u8, n), + std::slice::from_raw_parts((before + at) as *const u8, n), + ) + }; + if now != old { + pieces.push((at, n)); + } + at += n; + } + mine.push((which, place, pieces)); + } + found.lock().unwrap_or_else(|e| e.into_inner()).extend(mine); + })); + }; + let count = scans.len(); + for (which, (data, before, start, from, to)) in scans.into_iter().enumerate() { + let (mut at, mut place) = (from, 0); + while at < to { + // Cut where pieces end, so that every job sees whole pieces. + let room = (WIDE_JOB - bytes).max(PIECE); + let mut next = (at + room).min(to); + if next < to { + next -= (start + next) % PIECE; + if next <= at { + next = (at + PIECE - (start + at) % PIECE).min(to); + } + } + group.push((data, before, start, at, next, which, place)); + bytes += next - at; + place += 1; + at = next; + if bytes >= WIDE_JOB { + flush(&mut group, &mut jobs); + bytes = 0; + } + } + } + flush(&mut group, &mut jobs); + wide(jobs); + let mut found = std::mem::take(&mut *found.lock().unwrap_or_else(|e| e.into_inner())); + found.sort_unstable_by_key(|f| (f.0, f.1)); + let mut out = vec![Vec::new(); count]; + for (which, _, pieces) in found { + out[which].extend(pieces); + } + out +} + +/// Since the last frame-rate line, of the shader-written ranges looked for +/// on the CPU (copies not in the card's memory): bytes snapshotted in +/// windows outside buffers and in title buffers' copies; bytes compared in +/// windows, in buffers' copies, and of those in copies of 1 MiB or more; +/// ranges compared in windows and in buffers' copies. +static BACK_CLASS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; + +/// For the frame-rate line: where the CPU's search for shader writes goes +/// (per frame). A copy of a title buffer can go to the card's memory, +/// where the card does the search (`VICTORY_CARD_BUFFERS_MIN_MB`); a +/// window outside buffers cannot as the code stands. +pub(crate) fn back_line(frames: f64) { + let c: Vec = BACK_CLASS.iter().map(|c| c.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if c.iter().all(|&v| v == 0.0) { + return; + } + let mb = |v: f64| v / (1 << 20) as f64; + tracing::info!( + "shader writes looked for on the CPU per frame: {:.1} MB compared in {:.0} ranges of windows outside buffers ({:.1} MB \ + snapshotted), {:.1} MB in {:.0} ranges of title buffers' copies ({:.1} MB snapshotted), of them {:.1} MB in copies \ + of 1 MiB or more (VICTORY_CARD_BUFFERS_MIN_MB=1 would have the card look there)", + mb(c[2]), + c[5], + mb(c[0]), + mb(c[3]), + c[6], + mb(c[1]), + mb(c[4]), + ); +} + +#[cfg(test)] +mod wide_tests { + use super::{Job, PIECE, WIDE_JOB, copy_jobs, find_pieces, wide}; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Every job runs once, however many there are, and `wide` returns + /// only when all have. + #[test] + fn all_jobs_run_before_wide_returns() { + for n in [0usize, 1, 2, 7, 300] { + let ran = Arc::new(AtomicUsize::new(0)); + let jobs: Vec = (0..n) + .map(|i| { + let ran = ran.clone(); + Box::new(move || { + ran.fetch_add(i + 1, Ordering::Relaxed); + }) as Job + }) + .collect(); + wide(jobs); + assert_eq!(ran.load(Ordering::Relaxed), n * (n + 1) / 2, "{n} jobs"); + } + } + + /// Copies cut into jobs copy every byte once: long ones, short ones + /// and empty ones. + #[test] + fn copies_cut_into_jobs_copy_the_same_bytes() { + let len = 3 * WIDE_JOB + 12345; + let src: Vec = (0..len).map(|i| (i * 31 + i / 977) as u8).collect(); + let mut dst = vec![0u8; len]; + let (s, d) = (src.as_ptr() as usize, dst.as_mut_ptr() as usize); + // Ranges of the buffer, each to the same offsets of the other. + let cuts = [0, 1, 1, 4096, 70_000, WIDE_JOB + 3, 2 * WIDE_JOB + 3, 2 * WIDE_JOB + 9, len]; + let copies: Vec<(usize, usize, usize)> = cuts.windows(2).map(|w| (s + w[0], d + w[0], w[1] - w[0])).collect(); + let jobs = copy_jobs(copies); + assert!(jobs.len() >= 3); + wide(jobs); + assert!(src == dst); + } + + /// The pieces found on several threads are the ones a walk piece by + /// piece finds, for copies that start anywhere in a 64 KiB piece of + /// title memory and ranges that start and end anywhere. + #[test] + fn pieces_found_wide_are_those_found_one_by_one() { + let len = 5 * WIDE_JOB / 2 + 777; + let old: Vec = (0..len).map(|i| (i * 7 + i / 513) as u8).collect(); + let mut now = old.clone(); + // Changes: single bytes at piece edges, a run across two pieces, + // the last byte, and nothing in between. + for at in [0usize, 1, PIECE - 1, PIECE, 3 * PIECE + 5, WIDE_JOB - 1, WIDE_JOB, WIDE_JOB + PIECE / 2, 2 * WIDE_JOB + 9, len - 1] { + now[at] ^= 0x5a; + } + for byte in &mut now[9 * PIECE - 40..9 * PIECE + 40] { + *byte ^= 0x01; + } + let (data, before) = (now.as_ptr() as usize, old.as_ptr() as usize); + let mut scans = Vec::new(); + let mut wanted = Vec::new(); + for start in [0usize, 4096, PIECE - 16, 0xd_b790_df00] { + for (from, to) in [(0, len), (0, 1), (1, 2), (PIECE - 1, PIECE + 1), (3 * PIECE, 3 * PIECE), (12345, len - 1), (WIDE_JOB - 3, 2 * WIDE_JOB + 10)] { + scans.push((data, before, start, from, to)); + let mut pieces = Vec::new(); + let mut at = from; + while at < to { + let n = (PIECE - (start + at) % PIECE).min(to - at); + if now[at..at + n] != old[at..at + n] { + pieces.push((at, n)); + } + at += n; + } + wanted.push(pieces); + } + } + // A scan of nothing (a range whose snapshot is gone). + scans.push((0, 0, 0, 0, 0)); + wanted.push(Vec::new()); + assert_eq!(find_pieces(scans), wanted); + } +} + +/// Since the last frame-rate line, of [`Shadow::merge_under_writes`]: pages +/// compared, changed runs put in, and their bytes. +static MERGED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +/// [`MERGED`], taken. +pub(crate) fn merged_stats() -> [u64; 3] { + [0, 1, 2].map(|i| MERGED[i].swap(0, Ordering::Relaxed)) +} + +/// The runs of bytes where `now` differs from `was` (of one length), as +/// (offset, bytes) in order: every differing byte is in a run and no equal +/// byte is. +fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { + let n = now.len().min(was.len()); + let mut runs = Vec::new(); + let mut i = 0; + while i < n { + // Equal bytes, eight at a time while they last. + while i + 8 <= n && now[i..i + 8] == was[i..i + 8] { + i += 8; + } + while i < n && now[i] == was[i] { + i += 1; + } + if i >= n { + break; + } + let first = i; + while i < n && now[i] != was[i] { + i += 1; + } + runs.push((first, i - first)); + } + runs +} + +#[cfg(test)] +mod merge_tests { + use super::changed_runs; + + /// The runs hold exactly the bytes that differ: putting them into the + /// old bytes gives the new ones, and no run holds an equal byte. + #[test] + fn changed_runs_are_exactly_the_bytes_that_differ() { + let was: Vec = (0..300u32).map(|i| (i * 13 + 5) as u8).collect(); + for changes in [vec![], vec![0], vec![299], vec![7, 8, 9], vec![7, 9], vec![15, 16, 17, 23, 24, 64, 65, 66, 67, 68, 69, 70, 71, 72, 298, 299]] { + let mut now = was.clone(); + for &at in &changes { + now[at] ^= 0x41; + } + let runs = changed_runs(&now, &was); + let mut put = was.clone(); + let mut held = Vec::new(); + for &(at, n) in &runs { + assert!(n > 0); + put[at..at + n].copy_from_slice(&now[at..at + n]); + held.extend(at..at + n); + } + assert_eq!(put, now, "{changes:?}"); + assert_eq!(held, changes, "{changes:?}"); + // Runs do not touch: two that did would be one. + assert!(runs.windows(2).all(|w| w[0].0 + w[0].1 < w[1].0), "{changes:?}"); + } + assert!(changed_runs(&[], &[]).is_empty()); + } +} + +/// Host copies alive (also those only a list, a descriptor pass or a +/// snapshot still holds) and the bytes of title memory they copy. +static LIVE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +impl Drop for Shadow { + fn drop(&mut self) { + if self.place.is_some() { + // Never counted with the copies (`Shadow::placed`). + crate::inplace::gone(self.window, self.len); + return; + } + LIVE[0].fetch_sub(1, Ordering::Relaxed); + LIVE[1].fetch_sub(self.len, Ordering::Relaxed); + if self.kept.get_mut().unwrap_or_else(|e| e.into_inner()).1 { + KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed); + } + let window = self.window; + if let Some(card) = &mut self.card { + if window { + WINDOW_CARD_BYTES.fetch_sub(card.size, Ordering::Relaxed); + } else { + CARD_BYTES[0].fetch_sub(card.size, Ordering::Relaxed); + } + if card.before.get_mut().unwrap_or_else(|e| e.into_inner()).is_some() { + CARD_BYTES[1].fetch_sub(card_hash_bytes(card.size), Ordering::Relaxed); + } + } + } +} + +/// Whether a copy's snapshot is kept from one submission to the next and +/// only the pieces that changed in between are taken again +/// (`VICTORY_KEEP_SNAPSHOTS=1`; off by default). +/// +/// A snapshot is the copy's bytes before a submission, to find what its +/// shaders wrote. Taken anew for every submission it is 1,050 MB of copying +/// a frame (72-86 ms in gameplay, runs 61 and 62) for buffers of which +/// 100 MB changed. Kept, a piece of it is taken again only after something +/// changed the copy there: a refresh from title memory ([`Shadow::copy`]), +/// shader writes found after a submission, or the bytes put back then +/// ([`Shadow::copy_back`]). +/// +/// What it assumes, and why it is not on by default: that nothing else +/// writes a copy. A shader that writes a buffer through a view we did not +/// declare as written (we declare the unordered-access views of shaders +/// that can store) changes the copy unseen; with a fresh snapshot that +/// write is simply never put back, with a kept one it would be taken for a +/// write of a later submission and put back then, over whatever the title +/// wrote there since. +fn keeps() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_SNAPSHOTS").is_some_and(|v| v == "1")) +} + +/// Bytes of the snapshots kept, and the most that may be. +static KEPT_BYTES: AtomicU64 = AtomicU64::new(0); +/// `VICTORY_KEEP_SNAPSHOTS_MB`, 256 unless set (it was 768: run 80, with +/// kept snapshots beside copies in the card's memory, ran the PC out of +/// memory in 27 s; kept snapshots are the PC's memory, all of it resident). +fn kept_most() -> u64 { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_KEEP_SNAPSHOTS_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(256) << 20 + }) +} + +/// The 64 KiB pieces, cut at multiples of 64 KiB of title memory, that +/// hold offsets `[from, to)` of a copy of memory from `start` on +/// (`from < to`); piece 0 holds offset 0. +fn pieces_of(start: usize, from: usize, to: usize) -> std::ops::Range { + let first = start / PIECE; + (start + from) / PIECE - first..(start + to - 1) / PIECE - first + 1 +} + +/// The offsets that piece `piece` holds of a copy of `len` bytes of memory +/// from `start` on. +fn piece_at(start: usize, len: usize, piece: usize) -> (usize, usize) { + let first = start / PIECE; + let lo = ((first + piece) * PIECE).saturating_sub(start); + let hi = ((first + piece + 1) * PIECE - start).min(len); + (lo, hi) +} + +#[cfg(test)] +mod piece_tests { + use super::{PIECE, piece_at, pieces_of}; + + /// The pieces cover a copy without gaps, each cut where the compare + /// cuts (at multiples of 64 KiB of title memory). + #[test] + fn pieces_cover_the_copy_as_the_compare_cuts_it() { + for start in [0usize, 1, 4096, PIECE - 1, PIECE, PIECE + 77, 5 * PIECE + 12345] { + for len in [1usize, 100, PIECE - 1, PIECE, PIECE + 1, 3 * PIECE + 500] { + let count = pieces_of(start, 0, len).end; + let mut at = 0; + for piece in 0..count { + let (lo, hi) = piece_at(start, len, piece); + assert_eq!(lo, at, "{start} {len} {piece}"); + // As `Shadow::differing` cuts: to the next multiple. + let n = (PIECE - (start + at) % PIECE).min(len - at); + assert_eq!(hi, at + n, "{start} {len} {piece}"); + assert_eq!(pieces_of(start, lo, hi), piece..piece + 1); + assert_eq!(pieces_of(start, hi - 1, hi), piece..piece + 1); + at = hi; + } + assert_eq!(at, len, "{start} {len}"); + assert_eq!(pieces_of(start, 0, len), 0..count); + } + } + } +} + +/// Copies of windows outside buffers let go since the start, and their +/// bytes. +static LET_GO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// For the memory line: the windows let go since the start and their +/// bytes, and of the bytes of the windows alive, how many lie between the +/// lowest and the highest address ever asked for in each. +#[cfg(feature = "diagnostics")] +pub(crate) fn windows() -> [u64; 3] { + let asked: u64 = { + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + loose + .values() + .map(|s| { + let low = s.asked[0].load(Ordering::Relaxed); + let high = s.asked[1].load(Ordering::Relaxed); + high.saturating_sub(low) + }) + .sum() + }; + [LET_GO[0].load(Ordering::Relaxed), LET_GO[1].load(Ordering::Relaxed), asked] +} + +/// For the memory line, of the windows alive: the bytes of their pages +/// ever copied from title memory (the rest of each window is memory the +/// host zeroed and nothing read: what a window made no bigger than what is +/// read would not hold); the windows a descriptor slot shows and their +/// bytes (they stay until the title writes the slot again); the windows a +/// list or a pass over the heap holds and their bytes; the windows asked +/// for without a length (root views, which keep the 4 MiB grid) and their +/// bytes; and the window grid in bytes ([`window`]). +#[cfg(feature = "diagnostics")] +pub(crate) fn window_use() -> [u64; 8] { + let mut out = [0u64; 8]; + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + for s in loose.values() { + let copied = s.copied.lock().unwrap_or_else(|e| e.into_inner()); + let pages = copied.iter().filter(|&&at| at != 0).count() as u64; + out[0] += (pages * PAGE as u64).min(s.len); + if crate::host::references(&s.buffer) > 1 { + out[1] += 1; + out[2] += s.len; + } + if Arc::strong_count(s) > 1 { + out[3] += 1; + out[4] += s.len; + } + if s.unsized_asks.load(Ordering::Relaxed) > 0 { + out[5] += 1; + out[6] += s.len; + } + } + out[7] = window(); + out +} + +/// Lets go of the copies of windows outside buffers that nothing names any +/// more. They were never freed, and the world's streaming keeps asking for +/// new ones: 648 windows (2.8 GB) when the cutscene began, 974 (4.3 GB) +/// eight minutes later (run 24). A window goes when +/// - only the table of windows holds its copy: no list not yet reset reads +/// or writes it, no pass over the heap keeps its range, no submission is +/// comparing it; +/// - only the copy holds its host buffer: no descriptor slot views it (a +/// slot keeps the buffer it views, `HostHeap::kept`), so no draw can read +/// it through a slot made earlier; +/// - nothing asked for it for `IDLE_MS` and `IDLE_FRAMES` frames. +/// +/// The next read of that memory makes a new copy and copies the window +/// again. Called before a submission starts, by the thread that submits. +pub(crate) fn let_go_idle() { + const IDLE_MS: u64 = 10_000; + const IDLE_FRAMES: u64 = 4; + let gone: Vec> = { + // Held from the look to the removal: `loose` hands a copy out + // under the same lock, so none is handed out in between. + let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let idle: Vec<(u64, u64)> = map + .iter() + .filter(|(_, s)| { + Arc::strong_count(s) == 1 + && crate::host::long_ago(s.used.load(Ordering::Relaxed), IDLE_MS, IDLE_FRAMES) + && crate::host::references(&s.buffer) == 1 + }) + .map(|(key, _)| *key) + .collect(); + idle.into_iter().filter_map(|key| map.remove(&key)).collect() + }; + if !gone.is_empty() { + let (went, bytes) = (gone.len(), gone.iter().map(|s| s.len).sum::()); + crate::host::trail(|| { + format!("sweep: {went} host copies of windows of title memory let go ({} KiB), held by no list and no slot", bytes >> 10) + }); + } + for shadow in gone { + LET_GO[0].fetch_add(1, Ordering::Relaxed); + LET_GO[1].fetch_add(shadow.len, Ordering::Relaxed); + // Nothing runs now and nothing names it: freed at once unless a + // submission is running after all. + crate::host::retire(shadow); + } +} + +/// For the memory line: host copies alive and their bytes, of them the +/// windows of memory outside buffers and their bytes, and the snapshot +/// buffers kept for reuse and the bytes they reserve. +#[cfg(feature = "diagnostics")] +pub(crate) fn memory() -> [u64; 6] { + let (windows, window_bytes) = { + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + // Each copy once: a window may stand under several keys. + let mut seen = std::collections::HashSet::new(); + let bytes: u64 = loose + .values() + .filter(|s| seen.insert(Arc::as_ptr(s) as usize)) + .map(|s| s.len) + .sum(); + (seen.len() as u64, bytes) + }; + let (kept, kept_bytes) = { + let pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + (pool.len() as u64, pool.iter().map(|v| v.capacity() as u64).sum::()) + }; + [ + LIVE[0].load(Ordering::Relaxed), + LIVE[1].load(Ordering::Relaxed), + windows, + window_bytes, + kept, + kept_bytes, + ] +} + // SAFETY: D3D12 resources are free-threaded; `data` is a persistent mapping // written only on the submitting thread. unsafe impl Send for Shadow {} @@ -89,14 +1639,52 @@ impl Shadow { self.gpu + (address - self.start) } + /// The title memory the copy is of: its start and length. + pub(crate) fn span(&self) -> (u64, u64) { + (self.start, self.len) + } + + /// The offset of a title address in the copy, if it lies in it. + pub(crate) fn offset_in(&self, address: u64) -> Option { + address.checked_sub(self.start).filter(|&at| at < self.len) + } + /// Bytes from a title address to the buffer's end. pub(crate) fn left(&self, address: u64) -> u64 { (self.start + self.len).saturating_sub(address) } + /// Whether the memory behind the copy turned out not to be write-watched: + /// every refresh then copies its whole range. + pub(crate) fn unwatched(&self) -> bool { + self.watched.load(Ordering::Relaxed) == NOT_WATCHED + } + + /// The copy's own number (see the field). + pub(crate) fn id(&self) -> u64 { + self.id + } + /// Offset of a title address from the buffer's start. pub(crate) fn offset(&self, address: u64) -> u64 { - address - self.start + address - self.start + self.place.as_ref().map_or(0, |place| place.1) + } + + /// Title memory `[start, start + len)` in place: `placed` is a buffer + /// over it in a heap opened on it. Shaped as a copy so that everything + /// that binds, views or keeps a copy works on it unchanged; what + /// copies does nothing ([`Shadow::update`], [`Shadow::gpu_writes`]). + fn placed(placed: crate::inplace::Placed, start: u64, len: u64, window: bool) -> Shadow { + crate::host::name(&placed.buffer, || format!("title memory {start:#x}+{len:#x} in place")); + let mut shadow = Shadow::new(placed.buffer, start as *mut u8, placed.gpu, start, len); + // Not a copy: not counted with them, and nothing asks what the + // title wrote there. + LIVE[0].fetch_sub(1, Ordering::Relaxed); + LIVE[1].fetch_sub(len, Ordering::Relaxed); + *shadow.watched.get_mut() = NOT_WATCHED; + shadow.window = window; + shadow.place = Some((placed.heap, placed.bias)); + shadow } /// Brings `len` bytes at `address` up to date when `list` is submitted, @@ -108,6 +1696,8 @@ impl Shadow { fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Shadow { let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64; + LIVE[0].fetch_add(1, Ordering::Relaxed); + LIVE[1].fetch_add(len, Ordering::Relaxed); Shadow { buffer, data, @@ -117,7 +1707,19 @@ impl Shadow { copied: Mutex::new(vec![0; pages as usize]), watched: AtomicU8::new(0), pending: Mutex::default(), + flights: Mutex::default(), before: Mutex::default(), + kept: Mutex::default(), + used: AtomicU64::new(crate::host::moment()), + asked: [AtomicU64::new(u64::MAX), AtomicU64::new(0)], + unsized_asks: AtomicU64::new(0), + id: { + static NEXT: AtomicU64 = AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) + }, + card: None, + window: false, + place: None, } } @@ -138,46 +1740,126 @@ impl Shadow { /// before the submission (a copy per declared range and submission); /// a GPU-side dirty mask would save that if big ranges make it slow. pub(crate) fn gpu_writes(self: &Arc, list: &HostList, address: u64, len: u64) { + // In place the shaders write title memory itself: no snapshot, no + // compare, nothing to copy back, and no wait on its account. + // shortcut: another host copy of the same bytes (a title buffer + // inside this one with a copy of its own, a texture in it) is not + // told: the card's writes are not seen by write watching. + if self.place.is_some() { + return; + } let len = len.min(self.left(address)); list.defer_gpu_write(self, address as usize, len as usize); } /// At submission, after the range's refresh: a submitted list's shaders /// write this range. Its bytes are kept to tell later what the GPU wrote: - /// one snapshot per copy and submission, grown to cover every range the - /// submission declares (the world declares overlapping views of its - /// 174 MB heap dozens of times), in reused memory (fresh snapshots cost - /// ~2.3 million page faults per world frame). + /// one snapshot per copy and submission, each byte taken once, when the + /// first range holding it is declared (the world declares overlapping + /// views of its 174 MB heap dozens of times, from different offsets: a + /// snapshot grown to cover each was copied whole every time), in reused + /// memory (fresh snapshots cost ~2.3 million page faults per world + /// frame). pub(crate) fn writing(&self, address: usize, len: usize) { - self.pending - .lock() - .unwrap_or_else(|e| e.into_inner()) - .push((address, address + len)); - let (from, to) = self.inside(address, len); - // SAFETY: inside the mapping. - let host = |a: usize, b: usize| unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) }; - let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); - let (start, end) = match &*before { - Some((at, bytes)) => ((*at).min(from), (at + bytes.len()).max(to)), - None => (from, to), - }; - if let Some((at, bytes)) = &*before - && (*at, at + bytes.len()) == (start, end) - { + if self.place.is_some() { return; } - // Parts newly covered from the copy, the rest as it was taken. - let mut grown = pooled(end - start); - match before.take() { - Some((at, bytes)) => { - grown.extend_from_slice(host(start, at)); - grown.extend_from_slice(&bytes); - grown.extend_from_slice(host(at + bytes.len(), end)); - give_back(bytes); - } - None => grown.extend_from_slice(host(start, end)), + let range = (address, address + len); + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + // With the copy-back on its own thread: counted for this submission + // (once), whether or not an earlier one still holds the range. + if relay() { + self.flights.lock().unwrap_or_else(|e| e.into_inner()).declare(range, PREPARED.load(Ordering::Relaxed)); + } + // Dispatches declare the same ranges thousands of times. + if pending.contains(&range) { + return; + } + // In the card's memory: no snapshot. What shaders wrote is found on + // the card (`Host::card_before` reads the declared ranges from the + // lists). + if self.card.is_some() { + pending.push(range); + return; + } + // The parts no declared range holds yet: their bytes are taken now, + // just after the range's refresh (a part declared earlier has not + // been refreshed since, and keeps the bytes taken then). + let mut parts = vec![self.inside(address, len)]; + for &(a, e) in pending.iter() { + let (a, e) = self.inside(a, e - a); + let mut rest = Vec::with_capacity(parts.len() + 1); + for (from, to) in parts { + if e <= from || a >= to { + rest.push((from, to)); + continue; + } + if from < a { + rest.push((from, a)); + } + if e < to { + rest.push((e, to)); + } + } + parts = rest; + } + pending.push(range); + let taken: usize = parts.iter().map(|&(from, to)| to.saturating_sub(from)).sum(); + BACK_CLASS[usize::from(!self.window)].fetch_add(taken as u64, Ordering::Relaxed); + let total = self.len as usize; + let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); + let snapshot = before.get_or_insert_with(|| pooled(total)); + if keeps() { + // Piece by piece, and only the pieces not known current. A + // piece the part holds whole is current from now on; of a + // piece it holds partly only the part's bytes are taken, as + // without the switch, and it is taken again next time (the + // rest of it may belong to a range declared earlier, whose + // bytes stay as they were taken). + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if kept.0.is_empty() { + kept.0 = vec![false; self.pieces(0, total.max(1)).end]; + } + for (from, to) in parts { + if from >= to { + continue; + } + for piece in self.pieces(from, to) { + if kept.0[piece] { + continue; + } + let (lo, hi) = self.piece(piece); + let whole = from <= lo && hi <= to; + let (lo, hi) = (lo.max(from), hi.min(to)); + // SAFETY: as below; `hi <= total`. + unsafe { + std::ptr::copy_nonoverlapping(self.data.add(lo), snapshot.as_mut_ptr().add(lo), hi - lo); + } + kept.0[piece] = whole; + } + } + return; + } + if wide_back() { + // Noted, and taken with the submission's other snapshots when + // its refreshes are done (`take_snapshots`): the range is + // declared from here on, so nothing changes its bytes before + // then. The snapshot's memory stays where it is until the + // range is done with (`copy_back_done`). + let mut snaps = SNAPS.lock().unwrap_or_else(|e| e.into_inner()); + let (data, snapshot) = (self.data as usize, snapshot.as_mut_ptr() as usize); + snaps.extend(parts.into_iter().filter(|&(from, to)| from < to).map(|(from, to)| (data + from, snapshot + from, to - from))); + return; + } + for (from, to) in parts { + if from < to { + // SAFETY: the copy's mapping and the snapshot's allocation + // (`pooled`) both hold `total` bytes, and `to <= total`. + unsafe { + copy_wide(self.data.add(from), snapshot.as_mut_ptr().add(from), to - from); + } + } } - *before = Some((start, grown)); } /// After the submission ran: copies the bytes its shaders wrote back @@ -186,83 +1868,488 @@ impl Shadow { /// command memory shares the big GPU heap with what shaders write), and /// putting back the copy's older bytes there broke the title's own /// records (a fence list read as -1, title+0x4e9b54a). Returns the bytes - /// written. + /// written. The range must lie in ranges declared with + /// [`Shadow::writing`] and not yet done: `Host::execute` passes the + /// union of a submission's ranges, each byte once, then calls + /// [`Shadow::copy_back_done`]. pub(crate) fn copy_back(&self, address: usize, len: usize) -> usize { - let mut snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner()); + self.copy_back_with(address, len, None) + } + + /// [`Shadow::copy_back`]; `found`, if given, is the pieces of the range + /// that differ from the snapshot, found beforehand ([`find_all`]). + pub(crate) fn copy_back_with(&self, address: usize, len: usize, found: Option>) -> usize { + if self.place.is_some() { + return 0; + } + let snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner()); let mut written = 0; let (from, to) = self.inside(address, len); let start = self.start as usize; - if let Some((taken, before)) = &*snapshot - && *taken <= from - && to <= taken + before.len() + self.compared(from, to); + if let Some(before) = &*snapshot && from < to { - let before = &before[from - taken..to - taken]; + // SAFETY: `writing` set the snapshot's bytes of every declared + // range, at the copy's offsets. + let before = unsafe { std::slice::from_raw_parts(before.as_ptr().add(from), to - from) }; // By 64 KiB piece: the copy compared with its bytes before the - // submission, title memory read only where the GPU wrote. - const PIECE: usize = 64 << 10; + // submission (on several threads: gigabytes a frame, bound by + // memory speed), title memory read only where the GPU wrote. + #[cfg(feature = "diagnostics")] + let scanning = std::time::Instant::now(); + let differing = match found { + Some(found) => found, + None => self.differing(from, to, before), + }; + #[cfg(feature = "diagnostics")] + let syncing = { + use crate::copystat::{C, add}; + add(C::BackScanUs, scanning.elapsed().as_micros() as u64); + add(C::BackDiffer, differing.len() as u64); + std::time::Instant::now() + }; + // Where the copy changes (the GPU wrote, and below the title's + // bytes come in), a kept snapshot is no longer current. + for &(at, n) in &differing { + self.changed(at, at + n); + } let mut title = vec![0u8; PIECE]; - let mut synced = Vec::new(); - let mut at = from; - while at < to { - let n = (PIECE - (start + at) % PIECE).min(to - at); + for (at, n) in differing { // SAFETY: inside the mapping; only the submitting thread // writes it. let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; let old = &before[at - from..at - from + n]; + // From the first byte that differs to the last: title + // memory is read and written there only (a shader that sets + // a few words of a piece cost a read, a walk and a write of + // all 64 KiB of it). + let Some(first) = first_difference(host, old) else { + continue; + }; + let last = last_difference(host, old).unwrap_or(first); + let (at, n) = (at + first, last + 1 - first); + let (host, old) = (&mut host[first..=last], &old[first..=last]); let title = &mut title[..n]; - if host != old && crate::host::read_into((start + at) as *const u8, title) { - // Title memory with the GPU's bytes put in; the copy - // takes the title's bytes in turn. - let mut changed = false; - for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) { - if *h != *o && *t != *h { - *t = *h; - changed = true; - } - *h = *t; - } - if changed { - crate::watch::writing(start + at, n); - crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); - written += n; - } - synced.push((start + at) / PAGE); + if !crate::host::read_into((start + at) as *const u8, title) { + continue; + } + // Title memory with the GPU's bytes put in; the copy takes + // the title's bytes in turn. + // Without a branch, so the loop runs many bytes at a time: + // the GPU's byte where the copy's byte is not what it was + // before the submission, else the title's. (With the two + // searches above this was 44 ms a frame for 970 pieces.) + let mut differs = 0u8; + for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) { + let gpu = if *h != *o { 0xffu8 } else { 0 }; + let merged = (*t & !gpu) | (*h & gpu); + differs |= merged ^ *t; + *t = merged; + *h = merged; + } + if differs != 0 { + crate::watch::writing(start + at, n); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + written += n; + } + } + // Our write shows as a title write at the copy's next refresh, + // which copies those pages once more (some dozens of MB a + // frame). Asking about the whole range here, to note them + // current, cost more: 19-31 askings a frame over 110-174 MB of + // view memory, each a walk of its guards. + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackSyncUs, syncing.elapsed().as_micros() as u64); + } + written + } + + /// Offsets `[from, to)` of the copy are compared with the snapshot: for + /// the frame line's counts. + fn compared(&self, from: usize, to: usize) { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackCompared, (to - from) as u64); + let (bytes, ranges) = if self.window { (2, 5) } else { (3, 6) }; + BACK_CLASS[bytes].fetch_add((to - from) as u64, Ordering::Relaxed); + BACK_CLASS[ranges].fetch_add(1, Ordering::Relaxed); + if !self.window && self.len >= 1 << 20 { + BACK_CLASS[4].fetch_add((to - from) as u64, Ordering::Relaxed); + } + } + + /// [`relay`]: the declared range `[address, address + len)` of a copy + /// in the PC's memory is about to be looked through + /// (`crate::shadow::find_all`) by the thread that settles: counted as + /// [`Shadow::copy_back_with`] counts it. + pub(crate) fn relay_compared(&self, address: usize, len: usize) { + let (from, to) = self.inside(address, len); + self.compared(from, to); + } + + /// [`relay`], for a copy in the PC's memory: offsets `[at, at + n)` + /// are a 64 KiB piece of a declared range that differed from the + /// snapshot when it was looked through. What the card wrote there + /// since the snapshot was last brought up goes into title memory, from + /// the first to the last such byte, and into the snapshot, so that the + /// next flight's merge finds only what the card writes from now on. + /// The copy is read once and never written: a later flight's shaders + /// may be writing it at this moment. Under the snapshot's lock, which + /// [`Shadow::merge_under_writes`] holds while it reads title memory + /// and puts the title's bytes into the copy and the snapshot: the two + /// never see each other half done. `now` and `title` are scratch + /// memory. Returns the bytes written to title memory. + pub(crate) fn relay_merge(&self, at: usize, n: usize, now: &mut Vec, title: &mut Vec) -> usize { + let start = self.start as usize; + if self.card.is_some() || n == 0 || at + n > self.len as usize { + return 0; + } + let mut snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner()); + let Some(before) = snapshot.as_mut() else { + return 0; + }; + now.clear(); + now.reserve(n); + // SAFETY: inside the copy's mapping (checked above), read into + // room just reserved; the card may write the mapping meanwhile, and + // each byte read is one it held at some moment. + unsafe { + std::ptr::copy_nonoverlapping(self.data.add(at), now.as_mut_ptr(), n); + now.set_len(n); + } + // SAFETY: the snapshot's allocation holds the copy's length + // (`writing`), and these offsets are in a range declared and not + // done with, whose bytes it holds; nothing else touches them + // without the lock held here. + let held = unsafe { std::slice::from_raw_parts_mut(before.as_mut_ptr().add(at), n) }; + let Some(first) = first_difference(now, held) else { + return 0; + }; + let last = last_difference(now, held).unwrap_or(first); + let (at, n) = (at + first, last + 1 - first); + let (now, held) = (&now[first..=last], &mut held[first..=last]); + title.clear(); + title.resize(n, 0); + // Title memory not there: looked at again when the next flight + // that declared the range lands (the snapshot stays as it is). + if !crate::host::read_into((start + at) as *const u8, title) { + return 0; + } + if !merge_piece(now, held, title) { + return 0; + } + crate::watch::writing(start + at, n); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + n + } + + /// The 64 KiB pieces (cut at multiples of 64 KiB of title memory) of + /// `[from, to)` of the copy that differ from `before` (the bytes from + /// `from` on), as (offset, bytes) in order; compared on several threads + /// when the range is big. + fn differing(&self, from: usize, to: usize, before: &[u8]) -> Vec<(usize, usize)> { + let (start, data) = (self.start as usize, self.data as usize); + let scan = |a: usize, b: usize| -> Vec<(usize, usize)> { + let mut found = Vec::new(); + let mut at = a; + while at < b { + let n = (PIECE - (start + at) % PIECE).min(b - at); + // SAFETY: inside the mapping, which nothing writes while a + // submission's results are compared. + let host = unsafe { std::slice::from_raw_parts((data + at) as *const u8, n) }; + if host != &before[at - from..at - from + n] { + found.push((at, n)); } at += n; } - // Pages made equal to title memory are current in the copy, so - // our own write is not taken for the title's; others keep what - // they had (a title write there shows at the next refresh). - let (first, last) = ((start + from).div_ceil(PAGE), (start + to) / PAGE); - if first < last - && !synced.is_empty() - && self.watched.load(Ordering::Relaxed) != NOT_WATCHED - && let Some((now, _)) = crate::watch::writes(first * PAGE, last * PAGE, true) - { - let base = start / PAGE; - let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - for page in synced.into_iter().filter(|p| (first..last).contains(p)) { - copied[page - base] = now; + found + }; + const PER_THREAD: usize = 16 << 20; + let threads = ((to - from) / PER_THREAD).clamp(1, 8); + if threads == 1 { + return scan(from, to); + } + // Cut on piece boundaries, so that every thread sees whole pieces. + let cut = |i: usize| { + if i == threads { + return to; + } + let at = from + (to - from) / threads * i; + (at - (start + at) % PIECE).max(from) + }; + let scan = &scan; + std::thread::scope(|s| { + let parts: Vec<_> = (0..threads) + .map(|i| { + let (a, b) = (cut(i), cut(i + 1)); + s.spawn(move || scan(a, b)) + }) + .collect(); + parts + .into_iter() + .flat_map(|part| match part.join() { + Ok(found) => found, + Err(panic) => std::panic::resume_unwind(panic), + }) + .collect() + }) + } + + /// After [`Shadow::copy_back`] of a submission's ranges: every submitted + /// step that declared one of `ranges` (`(address, end)`, as declared) is + /// done with it (one submission runs at a time), and the snapshot with + /// the last range. + /// + /// With [`relay`] several submissions may hold a range: `ranges` are + /// those of one of them (each once), and a range is done with when the + /// last submission that declared it is ([`Flights`]). + pub(crate) fn copy_back_done(&self, ranges: &[(usize, usize)]) { + if self.place.is_some() { + return; + } + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + if relay() { + let free = self.flights.lock().unwrap_or_else(|e| e.into_inner()).done(ranges); + pending.retain(|r| !free.contains(r)); + } else { + pending.retain(|r| !ranges.contains(r)); + } + if !pending.is_empty() || self.card.is_some() { + return; + } + if keeps() { + // Kept for the next submission, if it is worth it (a megabyte + // or more) and there is room. + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if !kept.1 && self.len >= 1 << 20 { + if KEPT_BYTES.fetch_add(self.len, Ordering::Relaxed) + self.len <= kept_most() { + kept.1 = true; + } else { + KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed); + } + } + if kept.1 { + return; + } + // Given back: nothing of it is current next time. (The lock + // on the pieces ends here: `copy_back` takes it while it holds + // the snapshot's.) + kept.0.clear(); + } + if let Some(bytes) = self.before.lock().unwrap_or_else(|e| e.into_inner()).take() { + give_back(bytes); + } + } + + /// The 64 KiB pieces (cut at multiples of 64 KiB of title memory, as + /// [`Shadow::differing`] cuts them) that hold offsets `[from, to)` of + /// the copy; `from < to`. + fn pieces(&self, from: usize, to: usize) -> std::ops::Range { + pieces_of(self.start as usize, from, to) + } + + /// The offsets in the copy that piece `piece` holds. + fn piece(&self, piece: usize) -> (usize, usize) { + piece_at(self.start as usize, self.len as usize, piece) + } + + /// The copy's bytes at offsets `[from, to)` change: a kept snapshot is + /// not current there any more. + fn changed(&self, from: usize, to: usize) { + if !keeps() || from >= to { + return; + } + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if kept.0.is_empty() { + return; + } + for piece in self.pieces(from, to) { + kept.0[piece] = false; + } + } + + /// Whether shaders of a submission not yet copied back may be writing + /// the copy. + pub(crate) fn writes_pending(&self) -> bool { + !self.pending.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + } + + /// Whether [`Shadow::update`] of `[address, address + len)` would leave + /// title bytes behind: a range shaders may be writing holds a page the + /// title wrote since the copy last took it. The answer comes from the + /// write-watch journal alone, as the submission's one asking left it + /// (`crate::watch::asked`); where the journal cannot say (memory not + /// write-watched, a range not asked about) it is yes. A page the copy + /// never took whole counts as written if the title ever wrote it. + /// + /// For submissions sent to the card without a wait + /// (`crate::host::late`): the ranges are those of flights in the air, + /// which are then settled before this refresh. + pub(crate) fn stale_under_writes(&self, address: usize, len: usize) -> bool { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), (address + len).min(end)); + if from >= to { + return false; + } + let busy: Vec<(usize, usize)> = self + .pending + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .filter(|&&(a, e)| a < to && e > from) + .map(|&(a, e)| (a.max(from), e.min(to))) + .collect(); + if busy.is_empty() { + return false; + } + if self.watched.load(Ordering::Relaxed) == NOT_WATCHED { + return true; + } + let base = start / PAGE; + let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + busy.into_iter().any(|(a, e)| match crate::watch::asked(a, e) { + Some((_, written)) => written.into_iter().any(|(page, write)| { + page >= base && copied.get(page - base).is_none_or(|&at| at == 0 || write > at) + }), + None => true, + }) + } + + /// Where [`Shadow::stale_under_writes`] says yes: puts the bytes the + /// title changed into the copy, in the ranges shaders may be writing, + /// and only those bytes, so that what the shaders write beside them + /// stays (`crate::host::late_exact`). For each page of such a range + /// that the title wrote since the copy last took it, title memory as + /// it is now is compared with what the copy held when the range was + /// given to the shaders: the copy's CPU side for a copy in the card's + /// memory (the changed runs go up before the next submission, each a + /// copy of its own bytes, `runs_left` of them at most), the snapshot + /// for the others (the changed bytes go into the copy and into the + /// snapshot, so the compare after the card ran takes them for the + /// title's and not the shaders'). + /// + /// Whether the caller must still settle the flights: the journal + /// cannot say what was written, a snapshot is missing, or `runs_left` + /// ran out. Pages done before that stay done. + pub(crate) fn merge_under_writes(&self, address: usize, len: usize, runs_left: &mut usize) -> bool { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), (address + len).min(end)); + if from >= to { + return false; + } + let busy: Vec<(usize, usize)> = self + .pending + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .filter(|&&(a, e)| a < to && e > from) + .map(|&(a, e)| (a.max(from), e.min(to))) + .collect(); + if busy.is_empty() { + return false; + } + if self.watched.load(Ordering::Relaxed) == NOT_WATCHED { + return true; + } + 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, + // else the guards. The journal alone said nothing for copies + // of view memory, which is guarded and not write-watched, and + // those were all of run 99's cases: the flights were settled + // 4-5 times a frame for "0 pages looked at". + let Some((now, written)) = crate::watch::writes(a, e, true) else { + return true; + }; + let stale: Vec = { + let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + written + .into_iter() + .filter(|&(page, write)| page >= base && copied.get(page - base).is_none_or(|&at| at == 0 || write > at)) + .map(|(page, _)| page) + .collect() + }; + for page in stale { + let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(e)); + if lo >= hi { + 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 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) }; + let runs = changed_runs(title, held); + if runs.len() > *runs_left { + return true; + } + *runs_left -= runs.len(); + for (r, m) in runs { + held[r..r + m].copy_from_slice(&title[r..r + m]); + self.card_changed(at + r, at + r + m); + MERGED[1].fetch_add(1, Ordering::Relaxed); + MERGED[2].fetch_add(m as u64, Ordering::Relaxed); + } + } else { + let Some(snapshot) = before.as_mut() else { + 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); + // 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 let Some(at) = copied.get_mut(page - base) { + *at = now; + } } } } - // Every submitted step that declared the range is done with it (one - // submission runs at a time), and the snapshot with the last range. - let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); - pending.retain(|&r| r != (address, address + len)); - if pending.is_empty() - && let Some((_, bytes)) = snapshot.take() - { - give_back(bytes); - } - written + false } /// 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. pub(crate) fn update(&self, address: usize, len: usize) -> usize { + // In place: the card reads title memory itself. + if self.place.is_some() { + return 0; + } let (start, end) = (self.start as usize, (self.start + self.len) as usize); let (from, to) = (address.max(start), (address + len).min(end)); if from >= to { @@ -313,7 +2400,13 @@ impl Shadow { } self.watched.store(NOT_WATCHED, Ordering::Relaxed); } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::WholeBytes, (to - from) as u64); + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); self.copy(from, to); + #[cfg(feature = "diagnostics")] + crate::copystat::whole(from, to - from, started.elapsed().as_micros() as u64); to - from } @@ -361,8 +2454,197 @@ impl Shadow { // SAFETY: inside the mapping (`from` and `to` are within the buffer). let at = unsafe { self.data.add(from - start) }; crate::host::copy_mapped(at, from as *const u8, to - from, false); + // After the bytes are in: a snapshot taken meanwhile is not current. + self.changed(from - start, to - start); + self.card_changed(from - start, to - start); to - from } + + /// Whether shaders read and write this copy in the card's own memory + /// ([`cards`]). + pub(crate) fn carded(&self) -> bool { + self.card.is_some() + } + + /// The CPU side's bytes at offsets `[from, to)` changed: they go to the + /// card's side before the next submission. + fn card_changed(&self, from: usize, to: usize) { + let Some(card) = &self.card else { + return; + }; + if from >= to { + return; + } + let mut dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); + match dirty.last_mut() { + Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)), + _ => dirty.push((from, to)), + } + } + + /// Of a copy in the card's memory: the CPU's side (PC memory), the + /// card side's bytes from before if made yet, and their size. + pub(crate) fn card_sides(&self) -> Option<(&ID3D12Resource, Option, u64)> { + let card = self.card.as_ref()?; + let before = card.before.lock().unwrap_or_else(|e| e.into_inner()).clone(); + Some((&card.staging, before, card.size)) + } + + /// Shader writes are declared for a copy in the card's memory: makes + /// its "before" twin with `make` (bytes to buffer) if it has none. + /// Whether one was made now: the caller fills it, whole, from the + /// card's side before the submission's lists run. Without one (no + /// memory) every piece of a declared range is fetched. + pub(crate) fn card_make_before(&self, make: impl FnOnce(u64) -> Option) -> bool { + let Some(card) = &self.card else { + return false; + }; + let mut before = card.before.lock().unwrap_or_else(|e| e.into_inner()); + if before.is_some() { + return false; + } + *before = make(card.size); + if before.is_some() { + CARD_BYTES[1].fetch_add(card_hash_bytes(card.size), Ordering::Relaxed); + } + before.is_some() + } + + /// The declared range `[address, end)` as the compare on the card + /// takes it; `None` if none of it lies in the copy. + pub(crate) fn card_span(&self, address: usize, end: usize) -> Option { + let (from, to) = self.inside(address, end.saturating_sub(address)); + (from < to).then(|| card_span_of(self.start as usize, from, to)) + } + + /// The pieces that hold offsets `[from, to)` of the copy (cut to it), + /// as the card's hashing takes them. + pub(crate) fn card_run(&self, from: usize, to: usize) -> CardSpan { + let to = to.min(self.len as usize); + card_span_of(self.start as usize, from.min(to.saturating_sub(1)), to) + } + + /// The offsets of piece `i` of `span` that lie in the span. + pub(crate) fn card_piece(&self, span: &CardSpan, i: u32) -> (usize, usize) { + card_piece_of(self.start as usize, self.len as usize, span, i) + } + + /// After a submission, for a copy in the card's memory: `gpu` is what + /// the card's side holds at offset `at` on, in a piece the compare + /// found differing. The bytes shaders wrote (those that differ from the + /// CPU's side, which is what the card's side held when they started) + /// go into title memory, from the first to the last of them, as + /// [`Shadow::copy_back`] puts them; the CPU's side takes the result and + /// sends it up before the next submission. `title` is scratch memory. + /// Returns the bytes written to title memory. + pub(crate) fn card_merge(&self, at: usize, gpu: &[u8], title: &mut Vec) -> usize { + let start = self.start as usize; + if self.card.is_none() || at + gpu.len() > self.len as usize { + return 0; + } + // SAFETY: inside the mapping (checked above); only the submitting + // thread writes it. + let old = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) }; + let Some(first) = first_difference(gpu, old) else { + return 0; + }; + let last = last_difference(gpu, old).unwrap_or(first); + let (at, n) = (at + first, last + 1 - first); + let (gpu, old) = (&gpu[first..=last], &mut old[first..=last]); + title.clear(); + title.resize(n, 0); + let mut written = 0; + if crate::host::read_into((start + at) as *const u8, title) { + // As in `copy_back`: the card's byte where it is not what it + // was before the submission, else the title's. + let mut differs = 0u8; + for ((t, g), o) in title.iter_mut().zip(gpu).zip(old.iter_mut()) { + let wrote = if *g != *o { 0xffu8 } else { 0 }; + let merged = (*t & !wrote) | (*g & wrote); + differs |= merged ^ *t; + *t = merged; + *o = merged; + } + if differs != 0 { + crate::watch::writing(start + at, n); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + written = n; + } + } else { + // Title memory is not mapped there: the copy keeps what the + // card wrote, as before. + old.copy_from_slice(gpu); + } + // The card's side and its "before" take the result. + self.card_changed(at, at + n); + written + } + + /// [`relay`], for a copy in the card's memory: `gpu` is what the + /// card's side held at offset `at` on when a fetch sent after send + /// `fetched_after` (`crate::host`'s order of the queue) ran, in a piece + /// the compare found differing. The bytes that differ from the CPU's + /// side are what shaders wrote; they go into title memory, from the + /// first to the last of them, and into the CPU's side. Nothing is sent + /// up afterwards (the card holds these bytes or newer ones: sending + /// them up could undo a later flight's write), and the title's other + /// bytes are left to the refresh. + /// + /// Left out: bytes of the CPU's side that hold title bytes the card + /// had not received when the fetch ran, those still to go up and those + /// that went up with a later send. There the card's side is the older + /// one, and taking it for a shader's write would put it over what the + /// title wrote. Under the CPU side's lock (the snapshot's, which such + /// a copy has no other use for), as [`Shadow::merge_under_writes`]. + /// `title` is scratch memory. Returns the bytes written to title + /// memory. + pub(crate) fn card_merge_relay(&self, at: usize, gpu: &[u8], fetched_after: u64, title: &mut Vec) -> usize { + let start = self.start as usize; + let Some(card) = &self.card else { + return 0; + }; + if at + gpu.len() > self.len as usize { + return 0; + } + let _side = self.before.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: inside the mapping (checked above). The offsets are in a + // range declared and not done with, which no refresh writes; what + // does write it (the title's bytes put in under shader writes) + // holds the lock held here. + let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) }; + let Some(first) = first_difference(gpu, held) else { + return 0; + }; + let last = last_difference(gpu, held).unwrap_or(first); + let (at, n) = (at + first, last + 1 - first); + let (gpu, held) = (&gpu[first..=last], &mut held[first..=last]); + let skip: Vec<(usize, usize)> = { + let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); + let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner()); + dirty + .iter() + .copied() + .chain(sent.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1))) + .filter(|&(a, b)| a < at + n && b > at) + .collect() + }; + title.clear(); + title.resize(n, 0); + let mapped = crate::host::read_into((start + at) as *const u8, title); + let mut changed = false; + for (a, b) in outside(at, at + n, skip) { + let (a, b) = (a - at, b - at); + // Title memory that is not mapped: the CPU's side keeps what + // the card wrote, as before; `title` is scratch then. + changed |= merge_piece(&gpu[a..b], &mut held[a..b], &mut title[a..b]); + } + if !mapped || !changed { + return 0; + } + crate::watch::writing(start + at, n); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + n + } } struct Entry { @@ -393,9 +2675,93 @@ pub(crate) fn unregister(resource: usize, start: u64) { buffers().remove(&(start, resource)); } +/// The title buffer holding `address`, as (start, length), without making +/// its copy (diagnostics: which buffer a dropped program's root view names). +#[cfg(feature = "diagnostics")] +pub(crate) fn extent(address: u64) -> Option<(u64, u64)> { + buffers() + .range(..=(address, usize::MAX)) + .rev() + .take(64) + .find(|(_, e)| e.end > address) + .map(|(k, e)| (k.0, e.end - k.0)) +} + +/// Title memory `[at, at + len)` is about to show something else or be +/// given up: what is in place there (`crate::inplace`) is taken out of the +/// tables, so that the next ask makes a copy or opens the memory anew, and +/// goes when no list and no slot holds it any more. Returns how many. +pub(crate) fn in_place_let_go(at: u64, len: u64) -> u64 { + let end = at.saturating_add(len); + let mut gone: Vec> = Vec::new(); + { + let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let keys: Vec<(u64, u64)> = map + .range((at.saturating_sub(WINDOW), 0)..(end, 0)) + .filter(|(key, shadow)| shadow.place.is_some() && key.0 + key.1 > at) + .map(|(key, _)| *key) + .collect(); + gone.extend(keys.into_iter().filter_map(|key| map.remove(&key))); + } + { + // As `lookup` finds a buffer: among the 256 that start below. + let mut map = buffers(); + for (_, entry) in map.range_mut(..(end, 0)).rev().take(256) { + if entry.end > at && entry.shadow.as_ref().is_some_and(|s| s.place.is_some()) { + gone.extend(entry.shadow.take()); + } + } + } + let n = gone.len() as u64; + for shadow in gone { + crate::host::retire(shadow); + } + n +} + +/// For the in-place census (`crate::inplace`): the title buffers (start, +/// bytes, false) and the windows outside buffers that have a copy (start, +/// bytes, true). +pub(crate) fn spans() -> Vec<(u64, u64, bool)> { + let mut spans: Vec<(u64, u64, bool)> = buffers().iter().map(|(key, entry)| (key.0, entry.end - key.0, false)).collect(); + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + spans.extend(loose.keys().map(|&(start, len)| (start, len, true))); + spans +} + /// The copy of the innermost title buffer holding `[address, address + -/// len)`, made on first use. +/// len)`, made on first use. A `len` of 0 or 1 is an ask without a length +/// (a root view: the caller reads on to the copy's end). pub(crate) fn find(address: u64, len: u64) -> Option> { + lookup(address, len, false) +} + +/// As [`find`], for an ask that is done with the copy when its list has +/// run (a draw's vertex and index buffers, indirect arguments): outside +/// buffer objects it takes a window that is there already and holds the +/// range ([`holder`]), and makes one of its own only if none does. +/// +/// [`find`] names a window by the ask alone, which a descriptor slot needs +/// (the slot shows the window its view found when it was made, and the +/// pass that brings it up to date must find the same one). A draw needs no +/// such thing: it binds the copy it found and brings that copy up to date. +/// Named by the ask alone, every draw's range was a window of its own +/// wherever the windows are cut finer than 4 MiB: draws that bind +/// different ranges of the same memory then each copied their range, and +/// windows nothing asked for again for ten seconds were let go and made +/// (and copied) anew. Run 71, on a 256 KiB grid: 350 MB copied per frame +/// against 120 MB, 7,087 write-watch askings against 2,600, and 5,263 +/// windows (4.5 GB) let go in two minutes against 393 in a whole run. +pub(crate) fn find_any(address: u64, len: u64) -> Option> { + // With whole windows (the default) there is one window to a cell and + // nothing to choose: exactly `find`. + if !fine() { + return find(address, len); + } + lookup(address, len, true) +} + +fn lookup(address: u64, len: u64, any: bool) -> Option> { let end = address.checked_add(len.max(1))?; let mut map = buffers(); let key = map @@ -406,15 +2772,46 @@ pub(crate) fn find(address: u64, len: u64) -> Option> { .map(|(k, _)| *k); let Some(key) = key else { drop(map); - return loose(address, end); + return loose(address, end, len <= 1, any); }; let entry = map.get_mut(&key)?; if entry.shadow.is_none() { let len = entry.end - key.0; // Rounded up so that views ending in the buffer's last 256 bytes fit. // Shaders write some buffers (unordered access), so not upload memory. - let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(1 << 16))?; + let size = len.next_multiple_of(1 << 16); + // In place, if asked for and the memory can be opened + // (`crate::inplace::place_for`): the buffer is the title's own + // memory. Not the big ones `cards` puts in the card's memory: those + // are read too often to stay in the PC's. + let big = cards() && size >= card_limits().0; + if !big && let Some(placed) = crate::inplace::place_for(key.0, len, false) { + entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false))); + return entry.shadow.clone(); + } + let (buffer, data) = host()?.shared_buffer(size)?; crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", key.0)); + // A big one, with `cards`: shaders get a buffer in the card's own + // memory, and the one just made is the CPU's side. + let (buffer, card) = match card_for(size) { + Some(on_card) => { + crate::host::name(&on_card, || format!("title buffer {:#x}+{len:#x} on the card", key.0)); + tracing::info!( + start = format_args!("{:#x}", key.0), + len, + "a buffer's host copy is in the card's memory" + ); + let card = Card { + staging: buffer, + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + size, + }; + (on_card, Some(card)) + } + None => (buffer, None), + }; // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; if len >= 16 << 20 { @@ -430,7 +2827,13 @@ pub(crate) fn find(address: u64, len: u64) -> Option> { "buffer copied to the host" ); } - entry.shadow = Some(Arc::new(Shadow::new(buffer, data, gpu, key.0, len))); + let mut shadow = Shadow::new(buffer, data, gpu, key.0, len); + shadow.card = card; + let shadow = Arc::new(shadow); + if shadow.card.is_some() { + CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow)); + } + entry.shadow = Some(shadow); } entry.shadow.clone() } @@ -438,22 +2841,193 @@ pub(crate) fn find(address: u64, len: u64) -> Option> { /// Titles also use memory outside any buffer object as GPU memory (Grand /// Theft Auto VI's interface vertices, from its own allocator). Such memory /// gets copies of the aligned windows it touches. -/// shortcut: copies of windows are never freed; key them to the title's -/// allocations if memory use grows. +/// A window nothing names any more is let go ([`let_go_idle`]). +/// shortcut: a window is 4 MiB however little of it is read (the memory +/// line says how much was ever asked for, and how much was ever copied); +/// [`window`] cuts the windows of asks that give a length on a finer grid. const WINDOW: u64 = 4 << 20; +/// The grid the windows of asks with a length are cut on, in bytes: 4 MiB +/// unless `VICTORY_WINDOW_KB` names a smaller power of two (64 at least). +/// A window is the PC's memory, all of it, however little of it is read: +/// 803 windows held 3.3 GB in run 60's gameplay, and all that was ever +/// asked for in them lay within 1.6 GB. On a grid of 1 MiB or 256 KiB a +/// window ends nearer to what is read. An ask without a length keeps the +/// 4 MiB grid whatever is set: a root view reads from its address to its +/// window's end, and mesh streams bound that way reach megabytes. +/// shortcut: the default stays 4 MiB until a run with the memory line's +/// window counts has shown what the finer grids give; the same memory +/// asked for with different ranges then lies in more than one window. +fn window() -> u64 { + static GRID: std::sync::OnceLock = std::sync::OnceLock::new(); + *GRID.get_or_init(|| { + let kb = std::env::var("VICTORY_WINDOW_KB").ok().and_then(|v| v.trim().parse::().ok()); + grid(kb) + }) +} + +/// The window grid in bytes for a setting in KiB: a power of two from +/// 64 KiB to 4 MiB, 4 MiB for anything else. +fn grid(kb: Option) -> u64 { + match kb { + Some(kb) if kb.is_power_of_two() && (64..=4096).contains(&kb) => kb << 10, + _ => WINDOW, + } +} + +/// The window (start, bytes) of title memory for an ask of `[address, +/// end)` on a grid of `grid` bytes. +fn window_of(address: u64, end: u64, grid: u64) -> (u64, u64) { + let start = address & !(grid - 1); + (start, end.next_multiple_of(grid) - start) +} + +/// Whether the window of an ask without a length begins at the ask instead +/// of at the 4 MiB line below it. Such an ask (a root view) reads from its +/// address to the end of its 4 MiB cell; what lies below the lowest +/// address ever asked for in the cell is memory the host zeroed and nothing +/// reads (513 of run 65's 782 windows were asked for that way, 2,052 MB; +/// of all windows' 3,236 MB, 1,988 MB were ever copied). With this on, the +/// window is the cell's tail from the ask's step on ([`TAIL_STEP`]); an ask +/// lower in the cell later makes a longer tail, which every ask from then +/// on takes, and the shorter one goes when nothing holds it any more. +/// shortcut: off unless `VICTORY_WINDOW_TAILS=1`. A longer tail is another +/// host buffer than the shorter one: what was bound to the shorter stays +/// right only because every list brings up to date the copy it bound +/// (`draw.rs` keeps a root view's copy with its slot). It pays only +/// together with `VICTORY_WINDOW_KB` below 4096: on the 4 MiB grid an ask +/// with a length in the same cell makes the whole cell's window, and the +/// tail is that. +fn tails() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WINDOW_TAILS").is_some_and(|v| v == "1")) +} + +/// Tails begin on multiples of this. A longer tail is a new host buffer, +/// filled from title memory from its first byte to its last: begun on the +/// 64 KiB page of each ask, a cell whose asks came from the top down made +/// up to 63 of them, one after the other (part of run 71's copies). On +/// this step it is 15 at most, and a tail holds up to 192 KiB it did not +/// need. +const TAIL_STEP: u64 = 256 << 10; + +/// The window (start, bytes) a tail ask at `address` makes: from the ask's +/// step ([`TAIL_STEP`]) to the end of its 4 MiB cell. +fn tail_of(address: u64, end: u64) -> (u64, u64) { + let (cell, len) = window_of(address, end, WINDOW); + let start = address & !(TAIL_STEP - 1); + (start, cell + len - start) +} + +/// Of `windows` (start, bytes), the one an ask of `[address, end)` that +/// may take any window takes ([`find_any`]): the longest that holds the +/// whole range. +fn holder(windows: impl Iterator, address: u64, end: u64) -> Option<(u64, u64)> { + windows + .filter(|&(start, bytes)| start <= address && start + bytes >= end) + .max_by_key(|&(start, bytes)| (bytes, std::cmp::Reverse(start))) +} + +/// Whether windows may be smaller than their 4 MiB cell (a finer grid, or +/// tails): only then is there more than one window to choose from. +fn fine() -> bool { + tails() || window() < WINDOW +} + +/// For the memory line: the bytes of title memory the windows alive lie +/// over (each byte once), beside the windows' own bytes in +/// [`memory`]: the difference is memory that is in more than one window, +/// which is copied once for each. +#[cfg(feature = "diagnostics")] +pub(crate) fn window_cover() -> u64 { + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + cover(loose.keys().copied()) +} + +/// The bytes `windows` (start, bytes; in order of start) lie over, each +/// byte once. +#[cfg_attr(not(any(test, feature = "diagnostics")), allow(dead_code))] +fn cover(windows: impl Iterator) -> u64 { + let (mut covered, mut reached) = (0, 0); + for (start, bytes) in windows { + let end = start + bytes; + if end > reached { + covered += end - start.max(reached); + reached = end; + } + } + covered +} + +/// Of `windows` (start, bytes; in order), the longest tail a tail ask at +/// `address` can take: the first that begins in the ask's cell at or below +/// the ask's page and ends where the cell ends. +fn longest_tail(windows: impl Iterator, address: u64, end: u64) -> Option<(u64, u64)> { + let (cell, len) = window_of(address, end, WINDOW); + let step = address & !(TAIL_STEP - 1); + windows + .filter(|&(start, bytes)| start >= cell && start <= step && start + bytes == cell + len) + .min() +} + /// Copies of title memory outside buffers, by (start, length). static LOOSE: Mutex>> = Mutex::new(BTreeMap::new()); -fn loose(address: u64, end: u64) -> Option> { - let start = address & !(WINDOW - 1); - let len = end.next_multiple_of(WINDOW) - start; +fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option> { let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let (cell, _) = window_of(address, end, WINDOW); + let named = window_of(address, end, if unsized_ask { WINDOW } else { window() }); + let (start, len) = if unsized_ask && tails() { + let there = map.range((cell, 0)..=(address, u64::MAX)).map(|(key, _)| *key); + longest_tail(there, address, end).unwrap_or_else(|| tail_of(address, end)) + } else if any && fine() && !unsized_ask { + // The windows that begin in the ask's cell at or below the ask (one + // that begins in a cell below and reaches this far is passed over: + // the ask then makes its own). + let there = map.range((cell, 0)..=(address, u64::MAX)).map(|(key, _)| *key); + holder(there, address, end).unwrap_or(named) + } else { + named + }; + // Under the lock, with the handing out: see `let_go_idle`. + let note = |shadow: &Shadow| { + shadow.used.store(crate::host::moment(), Ordering::Relaxed); + shadow.asked[0].fetch_min(address, Ordering::Relaxed); + shadow.asked[1].fetch_max(end, Ordering::Relaxed); + if unsized_ask { + shadow.unsized_asks.fetch_add(1, Ordering::Relaxed); + } + }; if let Some(shadow) = map.get(&(start, len)) { + note(shadow); return Some(shadow.clone()); } + // In place, if asked for and the window's memory can be opened: the + // window is the title's own memory, with nothing to copy. + if let Some(placed) = crate::inplace::place_for(start, len, true) { + let shadow = Arc::new(Shadow::placed(placed, start, len, true)); + note(&shadow); + map.insert((start, len), shadow.clone()); + return Some(shadow); + } let (buffer, data) = host()?.shared_buffer(len)?; crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x}")); + // With room for windows on the card (`window_card_most`): shaders get a + // buffer there, and the one just made is the CPU's side. + let (buffer, card) = match window_card_for(len) { + Some(on_card) => { + crate::host::name(&on_card, || format!("title memory {start:#x}+{len:#x} on the card")); + let card = Card { + staging: buffer, + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + size: len, + }; + (on_card, Some(card)) + } + None => (buffer, None), + }; // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; tracing::debug!( @@ -461,11 +3035,124 @@ fn loose(address: u64, end: u64) -> Option> { len, "loose memory copied to the host" ); - let shadow = Arc::new(Shadow::new(buffer, data, gpu, start, len)); + let mut shadow = Shadow::new(buffer, data, gpu, start, len); + shadow.window = true; + shadow.card = card; + let shadow = Arc::new(shadow); + if shadow.card.is_some() { + CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow)); + } + note(&shadow); map.insert((start, len), shadow.clone()); Some(shadow) } +#[cfg(test)] +mod window_tests { + use super::{WINDOW, cover, grid, holder, longest_tail, tail_of, window_of}; + + /// An ask that may take any window takes the longest that holds all of + /// it, and none that holds only a part. + #[test] + fn an_ask_takes_the_longest_window_that_holds_it() { + let cell = 0xd_1200_0000u64; + let (ask, end) = (cell + 0x9_0000, cell + 0xb_0000); + assert_eq!(holder([].into_iter(), ask, end), None); + let there = [ + (cell, 0x4_0000), // ends below the ask + (cell + 0x8_0000, 0x2_0000), // holds its first half only + (cell + 0x8_0000, 0x4_0000), // holds it + (cell + 0x4_0000, 0x10_0000), // holds it, longer + (cell + 0xa_0000, 0x40_0000), // begins above it + ]; + assert_eq!(holder(there.into_iter(), ask, end), Some((cell + 0x4_0000, 0x10_0000))); + // Of two as long, the one that begins lower. + let two = [(cell + 0x8_0000, 0x8_0000), (cell + 0x4_0000, 0x8_0000)]; + assert_eq!(holder(two.into_iter(), ask, end), Some((cell + 0x4_0000, 0x8_0000))); + } + + /// What windows lie over counts each byte once. + #[test] + fn overlapping_windows_cover_their_memory_once() { + assert_eq!(cover([].into_iter()), 0); + let apart = [(0x10_0000u64, 0x4_0000u64), (0x20_0000, 0x4_0000)]; + assert_eq!(cover(apart.into_iter()), 0x8_0000); + // One inside another, one overlapping its end, one touching. + let over = [ + (0x10_0000u64, 0x10_0000u64), + (0x14_0000, 0x4_0000), + (0x1c_0000, 0x8_0000), + (0x24_0000, 0x4_0000), + ]; + assert_eq!(cover(over.into_iter()), 0x18_0000); + } + + /// A tail runs from the ask's page to the end of its 4 MiB cell, and an + /// ask takes the longest tail there is that holds it. + #[test] + fn tails_run_to_the_cells_end_and_the_longest_is_taken() { + let cell = 0xd_1200_0000u64; + let ask = cell + 0x12_3456; + assert_eq!(tail_of(ask, ask + 1), (cell + 0x10_0000, WINDOW - 0x10_0000)); + // The cell's first page: the whole cell, the window there always was. + assert_eq!(tail_of(cell + 0xffff, cell + 0x1_0000), (cell, WINDOW)); + let end = cell + WINDOW; + let tail = |from: u64| (cell + from, WINDOW - from); + // Nothing there, or only tails that begin above the ask. + assert_eq!(longest_tail([].into_iter(), ask, ask + 1), None); + assert_eq!(longest_tail([tail(0x20_0000)].into_iter(), ask, ask + 1), None); + // The longest of those that hold the ask; windows that do not reach + // the cell's end (cut on a finer grid for asks with a length) and + // windows of other cells are not tails. + let there = [ + (cell - WINDOW, WINDOW), + (cell, 0x4_0000), + tail(0x8_0000), + tail(0x10_0000), + (cell + 0x10_0000, 0x4_0000), + tail(0x20_0000), + ]; + assert_eq!(longest_tail(there.into_iter(), ask, ask + 1), Some(tail(0x8_0000))); + let (start, bytes) = tail(0x8_0000); + assert!(start <= ask && start + bytes == end); + // The whole cell's window is the longest tail of all. + let with_whole = [(cell, WINDOW), tail(0x8_0000)]; + assert_eq!(longest_tail(with_whole.into_iter(), ask, ask + 1), Some((cell, WINDOW))); + } + + /// The setting takes powers of two from 64 KiB to 4 MiB; anything else + /// leaves the grid as it was. + #[test] + fn the_grid_is_a_power_of_two_or_the_default() { + assert_eq!(grid(None), WINDOW); + assert_eq!(grid(Some(4096)), WINDOW); + assert_eq!(grid(Some(1024)), 1 << 20); + assert_eq!(grid(Some(256)), 256 << 10); + assert_eq!(grid(Some(64)), 64 << 10); + for bad in [0, 32, 100, 1000, 8192] { + assert_eq!(grid(Some(bad)), WINDOW, "{bad}"); + } + } + + /// A window holds its ask and is cut on the grid; on the default grid + /// it is the window there always was. + #[test] + fn windows_hold_their_ask_on_the_grid() { + let (address, end) = (0xd_1234_5678u64, 0xd_1234_5678u64 + 0x9000); + assert_eq!(window_of(address, end, WINDOW), (0xd_1200_0000, 4 << 20)); + assert_eq!(window_of(address, end, 1 << 20), (0xd_1230_0000, 1 << 20)); + assert_eq!(window_of(address, end, 256 << 10), (0xd_1234_0000, 256 << 10)); + // An ask across a grid line takes both cells. + let end = address + 0x4_0000; + assert_eq!(window_of(address, end, 256 << 10), (0xd_1234_0000, 512 << 10)); + for g in [64u64 << 10, 256 << 10, 1 << 20, WINDOW] { + let (start, len) = window_of(address, end, g); + assert!(start <= address && start + len >= end); + assert!(start % g == 0 && len % g == 0); + } + } +} + /// For device-removed reports: the copy of title memory whose host range /// starts closest below host GPU address `va`, and where `va` is in it. pub(crate) fn near(va: u64) -> String { diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 60eab0c..47d413d 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -43,18 +43,29 @@ pub(crate) struct Staging { layout: victory_formats::texture::Layout, /// Mips per array slice. mips: u32, + /// The staging buffer's bytes (counted in `STAGED` while it lives). + bytes: u64, memory: *const u8, last: Mutex, + /// Whether the staging buffer was detiled since a submitted list last + /// uploaded it, and whether one has uploaded it at all: a list records + /// the upload only then. (Every list that sampled a title texture + /// uploaded all of it again, changed or not: 5,411 subresource copies + /// of 1,120 textures in one frame of run 18.) + dirty: std::sync::atomic::AtomicBool, + uploaded: std::sync::atomic::AtomicBool, + /// When a list last recorded a use of it (`crate::host::moment`). + used: std::sync::atomic::AtomicU64, } /// What a texture's staging buffer holds: the hash of the memory detiled -/// (memory not watched), or the write-watch asking it was detiled after, -/// with room to read the memory into. +/// (memory not watched), or the write-watch asking it was detiled after. #[derive(Default)] struct Last { hash: Option, asked: u64, - read: Vec, + /// The frame a partly mapped texture was last read in. + partial: Option, } // SAFETY: the staging mapping is written only at submission, under @@ -65,6 +76,378 @@ unsafe impl Sync for Staging {} static STAGING: Mutex>>> = Mutex::new(None); +/// The buffer a texture the host writes is copied through into the texture +/// of a view the title placed in its memory in another format +/// ([`alias`]): every level of every layer as each of the two formats lays +/// it out for a copy (the same bytes: the texels are as wide), the written +/// texture's layout first. +struct Through { + buffer: ID3D12Resource, + parts: Vec<( + D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + )>, +} + +/// The most levels times layers [`alias`] copies (a cube of nine levels). +const ALIAS_PARTS: u32 = 54; + +// SAFETY: a device-local buffer only lists record copies with. +unsafe impl Send for Through {} +// SAFETY: as above. +unsafe impl Sync for Through {} + +/// The copy buffers of [`alias`], by the placed view's texture. +static THROUGH: Mutex>>> = Mutex::new(None); + +/// Brings `placed`, the texture of a view the title placed in the memory +/// of `source` in another format (`crate::resource::alias_of`), up to date +/// with what the host wrote to `source`: the texels of every level and +/// layer are copied as they are, through a buffer (the host copies between +/// two formats of one texel width in no other way). Recorded the first time +/// the list reads the view +/// and again whenever the list used `source` in another way since (wrote +/// it, or read it itself). Leaves `placed` in the copy destination state, +/// as [`upload`] does. False if the copy cannot be made: the caller fills +/// the texture from title memory, as before. +pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool { + const TARGET_OR_UNORDERED: u32 = 0x4 | 0x8; + const COPY_DEST: u32 = 0x400; + const COPY_SOURCE: u32 = 0x800; + let (Some(to), Some(from)) = ( + crate::resource::host_resource(placed), + crate::resource::host_resource(source), + ) else { + return false; + }; + let Some(host) = host() else { return false }; + let through = { + let mut map = THROUGH.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_with(HashMap::new); + match map.get(&(placed as usize)) { + Some(through) => through.clone(), + None => { + // SAFETY: live textures. + let (of_from, of_to) = unsafe { (from.GetDesc(), to.GetDesc()) }; + // Levels times layers (a volume's slices are one part). + let count = |d: &D3D12_RESOURCE_DESC| { + let layers = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + 1 + } else { + u32::from(d.DepthOrArraySize) + }; + u32::from(d.MipLevels) * layers + }; + let parts = count(&of_from); + if parts == 0 || parts > ALIAS_PARTS || parts != count(&of_to) { + return false; + } + let mut rows = [(); 2] + .map(|()| vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); parts as usize]); + let mut bytes = [0u64; 2]; + // SAFETY: plain queries; the out pointers are ours and + // hold `parts` layouts each. + unsafe { + host.device.GetCopyableFootprints( + &of_from, + 0, + parts, + 0, + Some(rows[0].as_mut_ptr()), + None, + None, + Some(&mut bytes[0]), + ); + host.device.GetCopyableFootprints( + &of_to, + 0, + parts, + 0, + Some(rows[1].as_mut_ptr()), + None, + None, + Some(&mut bytes[1]), + ); + } + let alike = rows[0].iter().zip(&rows[1]).all(|(a, b)| { + let (fa, fb) = (a.Footprint, b.Footprint); + a.Offset == b.Offset + && (fa.Width, fa.Height, fa.Depth, fa.RowPitch) + == (fb.Width, fb.Height, fb.Depth, fb.RowPitch) + }); + if bytes[0] == 0 || bytes[0] != bytes[1] || !alike { + return false; + } + let Some(buffer) = host.uav_buffer(bytes[0]) else { + return false; + }; + crate::host::name(&buffer, || { + format!( + "alias copy {}x{} f{} to f{}", + of_from.Width, of_from.Height, of_from.Format.0, of_to.Format.0 + ) + }); + tracing::info!( + view = ?placed, + texture = ?source, + width = of_from.Width, + height = of_from.Height, + parts, + written_as = of_from.Format.0, + read_as = of_to.Format.0, + "a view placed in the memory of a texture the host writes, in another format: read from that texture by a copy on the host" + ); + let [of_written, of_read] = rows; + let through = Arc::new(Through { + buffer, + parts: of_written.into_iter().zip(of_read).collect(), + }); + map.insert(placed as usize, through.clone()); + through + } + } + }; + let first = list.first_use(placed as usize); + // The source's first use in the list records nothing (its prelude + // brings it to the state); a use in another way since the last copy + // shows as a change of state. + let before = list.transition(source, COPY_SOURCE).map(|(texture, before)| { + let state = crate::host::legal_state(texture, COPY_SOURCE); + let barrier = crate::host::transition( + texture, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(state as i32), + ); + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + before + }); + if !first && before.is_none() { + return true; + } + crate::list::ensure_state(list, placed, COPY_DEST); + let part = |texture: &ID3D12Resource, index: usize| 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: index as u32, + }, + }; + let rows = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(&through.buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: *row, + }, + }; + let (common, read, written) = ( + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + #[cfg(feature = "diagnostics")] + list.note_op(|| format!("alias copy of {source:?} into {placed:?}")); + // SAFETY: an open list and live resources; the buffer is as big as + // the footprints and rests in the common state between copies. + unsafe { + list.list + .ResourceBarrier(&[crate::host::transition(&through.buffer, common, written)]); + for (index, (of_written, _)) in through.parts.iter().enumerate() { + list.list + .CopyTextureRegion(&rows(of_written), 0, 0, 0, &part(from, index), None); + } + list.list + .ResourceBarrier(&[crate::host::transition(&through.buffer, written, read)]); + for (index, (_, of_read)) in through.parts.iter().enumerate() { + list.list + .CopyTextureRegion(&part(to, index), 0, 0, 0, &rows(of_read), None); + } + list.list + .ResourceBarrier(&[crate::host::transition(&through.buffer, read, common)]); + } + list.keep(&through.buffer); + // A draw that also writes the source (a view of it handled before + // this one) needs it in that state again; the next read of the alias + // then copies once more, as it must after a write. + if let Some(before) = before + && before & TARGET_OR_UNORDERED != 0 + { + crate::list::ensure_state(list, source, before); + } + true +} + +/// Whether a texture refresh that finds the runtime remapping title memory +/// goes on without waiting for it (`VICTORY_TEXTURE_NO_WAIT=1`; off by +/// default). +/// +/// A texture whose memory is all mapped is read in place, under a lock +/// the runtime takes alone while it changes a mapping +/// (`crate::watch::title_memory_reading`), so that no page goes away under +/// the read. While the world streams in the runtime remaps all the time, +/// and each of the frame's 150-360 refreshes waited for it: runs 99-101 +/// have 4, 15 and 16 frame lines with over 300 ms of "textures", up to +/// 3,708 ms, and on every one of them the wait for this lock is the whole +/// of it (1,345 of 1,381 ms; 3,630 of 3,708; the write-watch askings 3-12 +/// ms, the texture's own lock 0). +/// +/// With the switch the refresh asks for the lock without waiting. If the +/// runtime has it, the texture is read through the kernel instead, which +/// needs no lock: it fails if a page is not there, and then the texture is +/// left as it is and read at its next refresh, a frame later. A read +/// through the kernel costs about 0.6 ms a megabyte against 0.3 in place. +/// +/// What changes for the picture: a texture that arrives while the runtime +/// is remapping may show a frame later. It never shows partly read. +fn no_wait() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_NO_WAIT").is_some_and(|v| v == "1")) +} + +/// Since the last frame-rate line, with [`no_wait`]: refreshes that read +/// through the kernel because title memory was being remapped, and those +/// left for the next refresh because a page was not there. +pub(crate) static UNLOCKED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Since the last frame-rate line, of texture refreshes on every thread, in +/// microseconds: waiting for the texture's own lock (another thread is +/// refreshing the same texture), asking the write watch and the guards, +/// waiting for title memory to hold still (the lock the runtime takes +/// alone while it remaps, `crate::watch::title_memory_reading`), and the +/// refreshes in all. +/// +/// While the world streams in, the frame line's "textures" is seconds a +/// frame in some runs and tenths in others for the same megabytes (2,566 +/// ms for 110 MB in run 93, 314 ms for 132 MB in run 91; before these +/// counters, runs 81, 83, 85 and 94 each had lines of 1.5-2.9 s), and the +/// submitting thread is not running while it lasts (run 93: 240-310 ms of +/// its own time a frame beside 1,100-1,800 ms of "textures"): it waits. +/// These say for what. +pub(crate) static REFRESH_WAITS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// `f`'s result, its time added to [`REFRESH_WAITS`]' place `slot`. +fn waited(slot: usize, f: impl FnOnce() -> T) -> T { + let started = std::time::Instant::now(); + let out = f(); + REFRESH_WAITS[slot].fetch_add(started.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + out +} + +thread_local! { + /// Room to read a texture's memory into: one buffer per submitting + /// thread. Each texture kept its own, a second copy in memory of every + /// write-watched or partly mapped texture ever sampled, for the run. + static READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Calls `f` with `size` bytes of this thread's read buffer (their +/// contents are whatever the last texture left). +fn with_read(size: usize, f: impl FnOnce(&mut [u8]) -> R) -> R { + READ.with(|read| { + let mut read = read.borrow_mut(); + if read.len() < size { + read.resize(size, 0); + } + f(&mut read[..size]) + }) +} + +/// Whether a texture all of whose memory is mapped is read through the +/// kernel's copy instead of in place (`VICTORY_TEXTURE_COPY=1`; off by +/// default). Round 3 of the memory work read every such texture that way +/// to be safe from pages taken away under the read; it cost 0.6 ms per MB +/// against 0.3 in place (90-105 ms a frame while the world streams in, runs +/// 72 and 73, against 20-40), and both runs with it lost the graphics +/// device, for a reason not found. The read in place is safe now for +/// another reason (`crate::watch::title_memory_reading`); this switch is +/// left to tell whether the copy was what lost the device. +fn through_copy() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_COPY").is_some_and(|v| v == "1")) +} + +/// Calls `f` with the `size` bytes of title memory at `memory`, read +/// through the kernel into this thread's read buffer; pages that are not +/// there read as zeros. The bytes are those a read in place would see. +fn with_title(memory: *const u8, size: usize, f: impl FnOnce(&[u8]) -> R) -> R { + with_read(size, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), memory, size, false); + f(read) + }) +} + +/// Staging buffers alive (also those only a list still holds) and their +/// bytes. +static STAGED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +impl Drop for Staging { + fn drop(&mut self) { + use std::sync::atomic::Ordering::Relaxed; + STAGED[0].fetch_sub(1, Relaxed); + STAGED[1].fetch_sub(self.bytes, Relaxed); + } +} + +/// For the memory line: staging buffers alive, their bytes, and how many +/// of them their texture still has (the others wait for a list's reset). +#[cfg(feature = "diagnostics")] +pub(crate) fn memory() -> [u64; 3] { + use std::sync::atomic::Ordering::Relaxed; + let kept = STAGING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .map_or(0, |map| map.len() as u64); + [STAGED[0].load(Relaxed), STAGED[1].load(Relaxed), kept] +} + +/// Staging buffers let go as idle since the start, and their bytes. +static LET_GO: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// For the memory line: staging buffers let go as idle, and their bytes. +#[cfg(feature = "diagnostics")] +pub(crate) fn let_go() -> [u64; 2] { + use std::sync::atomic::Ordering::Relaxed; + [LET_GO[0].load(Relaxed), LET_GO[1].load(Relaxed)] +} + +/// Lets go of the staging buffers no list recorded a use of for `IDLE_MS` +/// and `IDLE_FRAMES` frames and no list holds: a staging buffer is system memory the size of its +/// texture, kept so that an unchanged texture is not uploaded again, and +/// those of textures no longer sampled were kept for the run (2,246 of +/// them, 2.1 GB, at the end of run 24). The next list that samples such a +/// texture makes a staging buffer anew, detiles and uploads once more. +/// Called before a submission starts, by the thread that submits. +pub(crate) fn let_go_idle() { + use std::sync::atomic::Ordering::Relaxed; + const IDLE_MS: u64 = 10_000; + const IDLE_FRAMES: u64 = 4; + let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let Some(map) = map.as_mut() else { + return; + }; + // A list that recorded an upload or a check holds the staging until it + // is reset: one only the table holds is named by no list, recorded or + // running. + let (mut went, mut bytes) = (0u64, 0u64); + map.retain(|_, s| { + let keep = Arc::strong_count(s) > 1 + || !crate::host::long_ago(s.used.load(Relaxed), IDLE_MS, IDLE_FRAMES); + if !keep { + LET_GO[0].fetch_add(1, Relaxed); + LET_GO[1].fetch_add(s.bytes, Relaxed); + went += 1; + bytes += s.bytes; + } + keep + }); + if went > 0 { + crate::host::trail(|| format!("sweep: {went} staging buffers of textures let go ({} KiB), held by no list", bytes >> 10)); + } +} + /// Textures the host GPU wrote by a copy or resolve: their contents are on /// the host, not in title memory, which stays as it was. static HOST_WRITTEN: Mutex>> = Mutex::new(None); @@ -76,6 +459,17 @@ pub(crate) fn host_written(resource: This) { .insert(resource as usize); } +/// Whether the host GPU wrote `resource` by a copy or resolve +/// ([`host_written`]): its host copy cannot be made again from title +/// memory. +pub(crate) fn host_wrote(resource: usize) -> bool { + HOST_WRITTEN + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .is_some_and(|set| set.contains(&resource)) +} + /// The title released a resource. pub(crate) fn forget(resource: usize) { let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); @@ -86,6 +480,10 @@ pub(crate) fn forget(resource: usize) { if let Some(set) = set.as_mut() { set.remove(&resource); } + let mut through = THROUGH.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(through) = through.as_mut() { + through.remove(&resource); + } } /// Whether `resource`'s host copy takes its contents from title memory: @@ -114,6 +512,20 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) let Some(staging) = staging(resource, texture) else { return; }; + use std::sync::atomic::Ordering::Relaxed; + staging.used.store(crate::host::moment(), Relaxed); + // The host texture has the staging buffer's contents: only the check + // at submission is left, and what it finds changed the next list that + // samples the texture uploads (a frame late where every list of the + // frame was recorded before that check). + if staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexSkipped, 1); + list.defer_texture(staging); + return; + } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexUploads, 1); const COPY_DEST: u32 = 0x400; crate::list::ensure_state(list, resource, COPY_DEST); // The staging buffer lives as long as `staging`, which the deferred @@ -165,11 +577,26 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) // SAFETY: an open list; both locations name live resources. unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; } + // When the list is submitted, its copy takes what the staging buffer + // holds by then: noted before the check below, which sets `dirty` + // again if it detiles (the next list then uploads once more). + { + let staging = staging.clone(); + list.defer_host(move || { + staging.uploaded.store(true, Relaxed); + staging.dirty.store(false, Relaxed); + }); + } // Once per submission however many of its lists sample the texture. list.defer_texture(staging); } impl Staging { + /// The title memory the texture is read from: address and bytes. + pub(crate) fn memory(&self) -> (usize, usize) { + (self.memory as usize, self.layout.size as usize) + } + /// Detiles the texture memory into the staging buffer if it changed /// since the last time (and is mapped at all). pub(crate) fn refresh(&self) { @@ -183,35 +610,123 @@ impl Staging { /// Returns the bytes of title memory read. fn refresh_now(&self) -> usize { + let whole = std::time::Instant::now(); + let read = self.refresh_timed(); + REFRESH_WAITS[3].fetch_add(whole.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + read + } + + fn refresh_timed(&self) -> usize { let size = self.layout.size as usize; let start = self.memory as usize; - let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); + let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); let last = &mut *last; - if let Some((now, written)) = crate::watch::writes(start, start + size, false) { + if let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) { if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { return 0; } last.asked = now; // Read through the copy, which stands unmapped pages: memory of // big pools is too slow to ask page by page. - last.read.resize(size, 0); - crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false); - self.detile(&last.read); + with_read(size, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); + self.detile(read); + }); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexWatched, size as u64); return size; } - if !committed(self.memory, size) { - #[cfg(feature = "diagnostics")] - tracing::debug!( - memory = ?self.memory, - size, - desc = ?self.layout.desc, - "a sampled texture's memory is not committed" - ); - return 0; + // View memory has no write-watch, and a texture there was hashed + // whole at every check: 229 MB and 51 ms a frame in a gameplay view + // where two textures change (run 58). It is guarded now, as buffers + // in view memory are: a write of the title's to it faults once and + // is noted, a mapping is announced by the runtime. While neither + // happened the texture is as it was. What the guard cannot see (a + // write to the same pages through another view) is still found by + // the hash, which is taken every eighth frame only, by the + // texture's address, so the textures take turns. + // `VICTORY_TEXTURE_GUARD=0` hashes at every check, as before. + static GUARD: std::sync::OnceLock = std::sync::OnceLock::new(); + if *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) + && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true)) + { + const HASH_EVERY: u64 = 8; + let unwritten = last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked); + last.asked = now; + let turn = crate::frame::current().wrapping_add((start >> 16) as u64) % HASH_EVERY == 0; + if unwritten && !turn { + return 0; + } } - // SAFETY: committed memory of the texture's layout size. + // From here on the texture's memory may be read in place. Held until + // that read is done: the runtime changes what title memory shows + // only with this taken alone, so what `committed` finds mapped + // stays mapped (see `crate::watch::title_memory_reading`; without + // it a page went between the asking and the read in runs 71 and + // 74). + let _mapped = if no_wait() { + // Not waited for: while the runtime remaps title memory the + // texture is read through the kernel instead, whole or not at + // all (`no_wait`). + let Some(mapped) = crate::watch::title_memory_reading_now() else { + return self.refresh_unlocked(last, size); + }; + mapped + } else { + waited(2, crate::watch::title_memory_reading) + }; + if !committed(self.memory, size) { + // Partly mapped: a streamed texture with only some mips' pages + // there, the usual state while it streams in. Read through the + // copy, which stands unmapped pages (zeros), and upload what + // is there; nothing at all mapped changes nothing. + // shortcut: read again at most every 30 frames (reading around + // unmapped pages is slow, and nothing tells us when pages + // arrive): a mip that streams in shows up to 30 frames late. + let frame = crate::frame::current(); + if last.partial.is_some_and(|at| frame < at + 30) { + return 0; + } + last.partial = Some(frame); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexHashed, size as u64); + let changed = with_read(size, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); + let hash = blake3::hash(read); + if last.hash == Some(hash) { + return false; + } + last.hash = Some(hash); + if read.iter().all(|&b| b == 0) { + return false; + } + self.detile(read); + true + }); + #[cfg(feature = "diagnostics")] + if changed { + crate::copystat::add(crate::copystat::C::TexChanged, size as u64); + } + let _ = changed; + return size; + } + if through_copy() { + return with_title(self.memory, size, |tiled| { + let hash = blake3::hash(tiled); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexHashed, size as u64); + if last.hash == Some(hash) { + return size; + } + last.hash = Some(hash); + self.detile(tiled); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexChanged, size as u64); + size + }); + } + // SAFETY: committed memory of the texture's layout size, and it + // stays committed while `_mapped` is held. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; let hash = blake3::hash(tiled); #[cfg(feature = "diagnostics")] @@ -226,8 +741,38 @@ impl Staging { size } + /// A refresh while the runtime is remapping title memory ([`no_wait`]): + /// the texture is read through the kernel, which fails if a page of it + /// is not there at this moment. Then nothing is taken and the texture + /// is looked at again at its next refresh (what was learnt about writes + /// to it is forgotten, so that it is not passed over as unwritten). + /// Returns the bytes read. + fn refresh_unlocked(&self, last: &mut Last, size: usize) -> usize { + use std::sync::atomic::Ordering::Relaxed; + let read = with_read(size, |read| { + if !crate::host::read_into(self.memory, read) { + return false; + } + let hash = blake3::hash(read); + if last.hash != Some(hash) { + last.hash = Some(hash); + self.detile(read); + } + true + }); + if read { + UNLOCKED[0].fetch_add(1, Relaxed); + size + } else { + UNLOCKED[1].fetch_add(1, Relaxed); + last.asked = 0; + 0 + } + } + /// Detiles `tiled` (the texture's memory) into the staging buffer. fn detile(&self, tiled: &[u8]) { + self.dirty.store(true, std::sync::atomic::Ordering::Relaxed); #[cfg(feature = "diagnostics")] if tiled.iter().all(|&b| b == 0) { tracing::debug!( @@ -256,9 +801,109 @@ impl Staging { } } +/// Lets go of a title texture's staging buffer (lists that recorded an +/// upload from it hold it until they have run); the next upload makes one +/// anew. +pub(crate) fn unstage(resource: This) { + let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = map.as_mut() { + map.remove(&(resource as usize)); + } +} + +/// Whether a title texture has a staging buffer: a list recorded its +/// upload, and the lists that sample it check it at submission. +pub(crate) fn is_staged(resource: This) -> bool { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + map.as_ref().is_some_and(|map| map.contains_key(&(resource as usize))) +} + +/// The bytes of a title texture's memory, and whether all of it is mapped, +/// if the texture has been staged for upload. +pub(crate) fn staged(resource: This) -> Option<(u64, bool)> { + let s = { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + map.as_ref()?.get(&(resource as usize))?.clone() + }; + let size = s.layout.size as usize; + Some((size as u64, committed(s.memory, size))) +} + /// Whether `[at, at + len)` is committed memory (streamed textures may be /// unmapped until their pages arrive). pub(crate) fn committed(at: *const u8, len: usize) -> bool { + if by_query() { + return committed_by_query(at, len); + } + if len == 0 { + return true; + } + let (there, of) = readable(at as usize, len, true); + there == of +} + +/// Whether the two questions above and below are put to `VirtualQuery`, as +/// they were (`VICTORY_COMMITTED_QUERY=1`). `VirtualQuery` answers with the +/// length of the run of pages in the same state, which it finds by walking +/// the page tables to the run's end: 8.8 ms for one question in the title's +/// 1.1 GB block (round 6). The pass over the heap's views asks three or +/// more of them for every texture slot that is due, 3,000 slots a frame +/// when the card has no room (run 75): that pass then ran 208-264 ms, and +/// while it ran the submitting thread's write-watch askings waited behind +/// the walks (run 76: 8-22 askings a frame of 6-21 ms each, 46-172 ms). +fn by_query() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_COMMITTED_QUERY").is_some_and(|v| v == "1")) +} + +/// Of the kernel's pages that hold `[at, at + len)` (`len > 0`): how many +/// can be read, and how many there are; with `all`, it stops at the first +/// that cannot. One question to the kernel for up to 256 pages at once +/// (`QueryWorkingSetEx`: the state of each page asked about, no walk); a +/// page not in the working set may still be there (never touched, or +/// trimmed), and a one-byte read through the kernel says. +/// A page that is committed and may not be read counts as not there, which +/// is what the callers ask for: they read or write the memory next. +fn readable(at: usize, len: usize, all: bool) -> (usize, usize) { + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + const KERNEL_PAGE: usize = 4096; + let (first, last) = (at / KERNEL_PAGE, at.saturating_add(len - 1) / KERNEL_PAGE); + let of = last - first + 1; + let mut there = 0; + // SAFETY: plain data. + let mut info: [PSAPI_WORKING_SET_EX_INFORMATION; 256] = unsafe { std::mem::zeroed() }; + let mut page = first; + while page <= last { + let n = (last - page + 1).min(info.len()); + for (i, entry) in info[..n].iter_mut().enumerate() { + entry.VirtualAddress = ((page + i) * KERNEL_PAGE) as *mut _; + } + // SAFETY: `n` entries of the size given; our own process. + let asked = unsafe { + K32QueryWorkingSetEx( + GetCurrentProcess(), + info.as_mut_ptr().cast(), + (n * size_of::()) as u32, + ) + } != 0; + for (i, entry) in info[..n].iter().enumerate() { + // Bit 0 of the answer: the page is in the working set. + // SAFETY: plain data the query filled in. + let valid = asked && unsafe { entry.VirtualAttributes.Flags } & 1 != 0; + let mut byte = [0u8]; + if valid || crate::host::read_into(((page + i) * KERNEL_PAGE) as *const u8, &mut byte) { + there += 1; + } else if all { + return (there, of); + } + } + page += n; + } + (there, of) +} + +fn committed_by_query(at: *const u8, len: usize) -> bool { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; let mut p = at as usize; let end = p + len; @@ -275,6 +920,67 @@ pub(crate) fn committed(at: *const u8, len: usize) -> bool { true } +/// How many bytes of `[at, at + len)` are committed memory: all of a +/// texture that is there, some of one streaming in (its smaller mips lie +/// at the start of its memory, and their pages are mapped first), none of +/// one not there. With neither the first nor the last page committed the +/// answer is none without a look at the pages between (two queries for the +/// slots whose texture is away, which are asked again and again). +pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; + if len == 0 { + return 0; + } + let start = at as usize; + let end = start.saturating_add(len); + if !committed(at, 1) && !committed((end - 1) as *const u8, 1) { + return 0; + } + if !by_query() { + static BY_PAGE: std::sync::OnceLock = std::sync::OnceLock::new(); + if *BY_PAGE.get_or_init(|| std::env::var_os("VICTORY_MAPPED_BY_PAGE").is_some_and(|v| v == "1")) { + // By page, without the walk: whole pages, cut to the range. + let (there, _) = readable(start, len, false); + return (there as u64 * 4096).min(len as u64); + } + // By 64 KiB block, one page asked of each: the title's memory is + // mapped in blocks of that size (the console's page), and the + // answer is a measure of how much of a texture has arrived, not a + // promise that every byte can be read (the upload reads through the + // kernel). By page, a texture half there cost a failed kernel read + // for each of its missing pages, every frame it stayed due: 1,663 + // textures "uploaded in part" kept the pass over the heap's views at + // 90-160 ms a frame (run 81). `VICTORY_MAPPED_BY_PAGE=1`: by page. + const BLOCK: usize = 64 << 10; + let mut there = 0u64; + let mut block = start & !(BLOCK - 1); + while block < end { + let (lo, hi) = (block.max(start), block.saturating_add(BLOCK).min(end)); + if readable(lo, 1, true).0 == 1 { + there += (hi - lo) as u64; + } + block = block.saturating_add(BLOCK); + } + return there; + } + let (mut p, mut there) = (start, 0u64); + while p < end { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; + let next = (info.BaseAddress as usize).saturating_add(info.RegionSize).min(end); + if n == 0 || next <= p { + break; + } + if info.State == MEM_COMMIT { + there += (next - p) as u64; + } + p = next; + } + there +} + /// The staging state of a title texture, made on first use. fn staging(resource: This, texture: &ID3D12Resource) -> Option> { let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); @@ -327,6 +1033,8 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { ) }); tracing::debug!(?desc, total, "texture contents uploaded from title memory"); + STAGED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + STAGED[1].fetch_add(total, std::sync::atomic::Ordering::Relaxed); let s = Arc::new(Staging { buffer, #[cfg(feature = "diagnostics")] @@ -336,9 +1044,124 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { rows, layout, mips: u32::from(d.MipLevels), + bytes: total, memory, last: Mutex::default(), + dirty: std::sync::atomic::AtomicBool::new(true), + uploaded: std::sync::atomic::AtomicBool::new(false), + used: std::sync::atomic::AtomicU64::new(crate::host::moment()), }); map.insert(resource as usize, s.clone()); Some(s) } + +#[cfg(test)] +mod title_memory_tests { + use super::with_title; + + /// Title memory whose tail is reserved and not committed reads through + /// the copy as its bytes and then zeros, without a fault; so does + /// memory a page of which is taken away between two reads, and the + /// zeros are zeros whatever the read buffer held before. + #[test] + fn an_uncommitted_tail_reads_as_zeros() { + use windows_sys::Win32::System::Memory::*; + const HEAD: usize = 0xb_0000; + const SIZE: usize = 0x20_0000; + // SAFETY: a private reservation of our own; only committed pages + // are written in place, and nothing else reads them in place. + unsafe { + // The read buffer holds something else first. + let other = vec![0x77u8; SIZE]; + with_title(other.as_ptr(), SIZE, |bytes| assert!(bytes.iter().all(|&b| b == 0x77))); + let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::(); + assert!(!base.is_null()); + assert_eq!(VirtualAlloc(base.cast(), HEAD, MEM_COMMIT, PAGE_READWRITE), base.cast()); + base.write_bytes(0x5a, HEAD); + with_title(base, SIZE, |bytes| { + assert!(bytes[..HEAD].iter().all(|&b| b == 0x5a), "what is mapped"); + assert!(bytes[HEAD..].iter().all(|&b| b == 0), "what is not: zeros"); + }); + // The title takes a page in the middle away: zeros from then + // on, the rest as before. + assert_ne!(VirtualFree(base.add(0x4_0000).cast(), 0x1_0000, MEM_DECOMMIT), 0); + with_title(base, SIZE, |bytes| { + assert!(bytes[..0x4_0000].iter().all(|&b| b == 0x5a)); + assert!(bytes[0x4_0000..0x5_0000].iter().all(|&b| b == 0)); + assert!(bytes[0x5_0000..HEAD].iter().all(|&b| b == 0x5a)); + assert!(bytes[HEAD..].iter().all(|&b| b == 0)); + }); + assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0); + } + } + + /// The texture both device-loss runs named last (16 texels wide, 4 or 8 + /// high, format 10, layout 0x100, console flags 0x300000; its memory + /// began 0x300 into a page in run 73 and 0x700 in run 72, and here also + /// 0xf00, so that a page line runs through it): what the detiling is + /// given and what it writes are the same read in place and read through + /// the copy, and the rows it writes end where the staging buffer the + /// host sizes for it ends (896 bytes for 4 rows of 128 bytes 256 apart, + /// 1,920 for 8). + #[test] + fn the_small_texture_of_runs_72_and_73_detiles_the_same_both_ways() { + use windows_sys::Win32::System::Memory::*; + for (height, within) in [(4u32, 0x300usize), (8, 0x700), (4, 0xf00), (8, 0xf00)] { + // The description as the log printed it, word for word. + let words: [u32; 14] = [3, 0, 0, 0, 16, 0, height, 65537, 10, 1, 0, 256, 3_145_728, 0]; + // SAFETY: fourteen words are a resource description (56 bytes, + // plain numbers). + let desc: crate::resource::ResourceDesc = unsafe { std::mem::transmute(words) }; + let layout = crate::resource::texture_layout(&desc) + .expect("a console layout") + .planes[0] + .layout + .clone(); + let size = layout.size as usize; + let (row, pitch) = (16 * 8, 256usize); + assert!(size >= row * height as usize, "the layout holds every texel"); + // Committed pages and a reserved one after them; the texture + // begins `within` bytes into the first, as the title placed it. + // SAFETY: our own reservation; the committed part is written + // and read in place, by this thread alone. + unsafe { + let pages = size.div_ceil(4096) + 1; + let base = VirtualAlloc(std::ptr::null(), (pages + 1) * 4096, MEM_RESERVE, PAGE_NOACCESS).cast::(); + assert!(!base.is_null()); + assert_eq!(VirtualAlloc(base.cast(), pages * 4096, MEM_COMMIT, PAGE_READWRITE), base.cast()); + for i in 0..pages * 4096 { + base.add(i).write((i * 7 + i / 251) as u8); + } + let memory = base.add(within); + let in_place = std::slice::from_raw_parts(memory, size); + // The bytes: the same in place and through the copy. + with_title(memory, size, |copied| assert_eq!(copied, in_place)); + // What the detiling writes: the same, and inside the bytes + // the host's staging buffer for this texture has. + let staged = (height as usize - 1) * pitch + row; + assert_eq!(staged, if height == 4 { 896 } else { 1920 }); + let detile = |tiled: &[u8]| { + // The slice `Staging::detile` hands over: whole rows. + let mut linear = vec![0xeeu8; pitch * height as usize]; + layout + .detile(tiled, 0, 0, &mut linear, pitch, pitch * height as usize) + .expect("detiled"); + linear + }; + let direct = detile(in_place); + let through = with_title(memory, size, |copied| detile(copied)); + assert_eq!(direct, through); + for y in 0..height as usize { + assert!(direct[y * pitch..][..row].iter().any(|&b| b != 0xee), "row {y} written"); + assert!(direct[y * pitch + row..(y + 1) * pitch].iter().all(|&b| b == 0xee), "nothing past row {y}"); + } + // A buffer of exactly the staged bytes is enough. + let mut exact = vec![0u8; staged]; + layout + .detile(in_place, 0, 0, &mut exact, pitch, pitch * height as usize) + .expect("the staging buffer's bytes are enough"); + assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0); + } + } + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 7694609..60089a7 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -10,7 +10,9 @@ //! copy leaves each 64 KiB block it took read-only, and our vectored handler //! takes the first write to it: it notes the block as written and gives the //! write access back. The runtime tells us when it maps or unmaps views -//! ([`title_memory_remapped`]), which resets their protection. +//! ([`title_memory_remapped`]), which resets their protection. Blocks found +//! wholly uncommitted are skipped while they remain so; one query can +//! confirm a whole region, including ordinary reservations between views. //! //! shortcut: writes into physical pages through another view (xmem's //! `write_physical`, DirectStorage's page destinations) are not seen at @@ -35,14 +37,264 @@ struct Journal { written: BTreeMap, /// Room for the kernel's answer. found: Vec, + /// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`]) + /// and the asking that did: `writes` answers for a range inside one + /// from the journal, without another kernel call. + ahead: Vec<(usize, usize)>, + ahead_asked: u64, + /// The ahead asking stands for a whole submission ([`ask_once`]): no + /// other ahead asking is made, and `ahead` stays, until + /// [`ask_once_end`]. + kept: bool, } static JOURNAL: Mutex = Mutex::new(Journal { asked: 0, written: BTreeMap::new(), found: Vec::new(), + ahead: Vec::new(), + ahead_asked: 0, + kept: false, }); +/// Ranges of one submission closer than this are asked about together: +/// walking the pages between them costs less than another kernel call (a +/// call that resets written pages costs 30-70 microseconds whatever the +/// range). +const AHEAD_GAP: usize = (8 << 20) / PAGE; +/// The most one asking covers (its answer needs 8 bytes per 4 KiB page). +const AHEAD_MAX: usize = (1 << 30) / PAGE; + +/// Asks the kernel about many ranges `(start, end)` at once, before the +/// [`writes`] of each: ranges close together are one asking, and `writes` +/// then answers from the journal until [`ask_ahead_done`]. The world's +/// submissions refresh thousands of host copies (6,664 askings a frame, +/// 456 ms, in run 14). Ranges that are not write-watched, or lie alone, are +/// left to `writes`. +pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { + let mut pieces: Vec<(usize, usize)> = ranges + .iter() + .filter(|r| r.0 < r.1) + .map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE))) + .collect(); + if pieces.len() < 2 { + return; + } + pieces.sort_unstable(); + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let j = &mut *j; + // The submission's one asking stands ([`ask_once`]): what it does not + // hold is left to `writes`. + if j.kept { + return; + } + j.asked += 1; + j.ahead_asked = j.asked; + j.ahead.clear(); + let mut i = 0; + while i < pieces.len() { + let first = pieces[i].0; + let mut last = pieces[i].1; + let mut k = i + 1; + while k < pieces.len() + && pieces[k].0 <= last + AHEAD_GAP + && last.max(pieces[k].1) - first <= AHEAD_MAX + { + last = last.max(pieces[k].1); + k += 1; + } + ask_run(j, &pieces[i..k]); + i = k; + } +} + +/// Since the last frame line: the kernel askings that took a millisecond +/// or more, their microseconds, and the longest asking's. An asking walks +/// page tables, some ten microseconds for most ranges; in run 75 the 2,644 +/// askings of a frame took 219 ms in the lines where the pass over the +/// heap's views ran long, 25-50 ms in the others. These numbers say +/// whether a few askings wait for something or all of them are slow. +#[cfg(feature = "diagnostics")] +static SLOW: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +#[cfg(feature = "diagnostics")] +fn slow(us: u64) { + use std::sync::atomic::Ordering::Relaxed; + if us >= 1000 { + SLOW[0].fetch_add(1, Relaxed); + SLOW[1].fetch_add(us, Relaxed); + } + SLOW[2].fetch_max(us, Relaxed); +} + +/// [`SLOW`], taken. +#[cfg(feature = "diagnostics")] +pub(crate) fn slow_asks() -> [u64; 3] { + [0, 1, 2].map(|i| SLOW[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// The submission's refreshes are done: `writes` asks the kernel again. +pub(crate) fn ask_ahead_done() { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + if !j.kept { + j.ahead.clear(); + } +} + +/// Whether a submission asks the kernel once, before its first refresh, +/// about every range its lists refresh (`VICTORY_ASK_ONCE=1`; off by +/// default). +/// +/// A submission's refreshes are done in groups, between the title's own +/// buffer copies (each copy flushes the refreshes recorded before it), and +/// every group asked the kernel again: 2,644 askings a frame, 70 a +/// submission. With the switch the journal answers all of them from one +/// asking made when the submission starts. +/// +/// What changes: memory the title's other threads write while the +/// submission is being prepared is seen by the next submission's asking, +/// not by this one's later groups. What this submission's lists read was +/// written before they were submitted, so before the asking. Our own +/// writes into title memory while preparing are told to the journal +/// ([`wrote`]) or end the asking ([`ask_once_end`]). +pub(crate) fn once() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + // On by default since run 81 (with card buffers: 375-450 ms a frame + // against 573-647, the picture unchanged over four minutes); + // `VICTORY_ASK_ONCE=0` asks per range, as before. + *ON.get_or_init(|| std::env::var_os("VICTORY_ASK_ONCE").is_none_or(|v| v != "0")) +} + +/// With [`once`]: asks about `ranges` (everything a submission's lists +/// refresh) as [`ask_ahead`] does, and lets that asking stand until +/// [`ask_once_end`]. +pub(crate) fn ask_once(ranges: &[(usize, usize)]) { + if !once() { + return; + } + ask_once_end(); + ask_ahead(ranges); + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let j = &mut *j; + if j.ahead.is_empty() { + // `ask_ahead` asked nothing (fewer than two ranges). + j.asked += 1; + j.ahead_asked = j.asked; + } + // `ask_ahead` leaves a range that lies alone to `writes`, which asks + // once per flush: with one asking for the submission that was every + // such range asked again at each of its 70 flushes (run 76: 2,300 + // askings a frame with the switch on, as without it). They are asked + // here, once; what is not write-watched stays with `writes`. + for &(start, end) in ranges { + if start >= end { + continue; + } + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + if !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) && ask_kernel(j, first, last) { + j.ahead.push((first, last)); + } + } + j.kept = !j.ahead.is_empty(); +} + +/// The submission's one asking stands no longer: its refreshes are done, +/// or title memory was written in a way the journal was not told. +pub(crate) fn ask_once_end() { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + if j.kept { + j.kept = false; + j.ahead.clear(); + } +} + +/// We wrote title memory `[at, at + len)` while a submission's one asking +/// stands (the title's buffer copies, done at submission): its pages count +/// as written after that asking, so the refreshes that follow copy them. +pub(crate) fn wrote(at: usize, len: usize) { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + if !j.kept || len == 0 { + return; + } + j.asked += 1; + let now = j.asked; + for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) { + j.written.insert(page, now); + } +} + +/// One kernel asking for `pieces` (page ranges in order); by halves if it +/// fails, as a run across two reservations or into memory that is not +/// write-watched does. A piece alone is left to [`writes`]. +fn ask_run(j: &mut Journal, pieces: &[(usize, usize)]) { + if pieces.len() < 2 { + return; + } + let first = pieces[0].0; + let last = pieces.iter().map(|p| p.1).max().unwrap_or(first); + if ask_kernel(j, first, last) { + j.ahead.push((first, last)); + return; + } + let (a, b) = pieces.split_at(pieces.len() / 2); + ask_run(j, a); + ask_run(j, b); +} + +/// Asks the kernel for the written pages of pages `[first, last)` and notes +/// them in the journal under the ahead asking; false (and nothing changed) +/// if the range is not write-watched memory of one reservation. +fn ask_kernel(j: &mut Journal, first: usize, last: usize) -> bool { + use windows_sys::Win32::System::Memory::GetWriteWatch; + const WRITE_WATCH_FLAG_RESET: u32 = 1; + let mut count = (last - first) * PAGE / KERNEL_PAGE; + j.found.resize(count.max(j.found.len()), 0); + let mut granularity = 0; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + // SAFETY: the answer buffer holds `count` entries. + let failed = unsafe { + GetWriteWatch( + WRITE_WATCH_FLAG_RESET, + (first * PAGE) as *const _, + (last - first) * PAGE, + j.found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + } != 0; + if failed { + return false; + } + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::Watches, 1); + add(C::WatchUs, started.elapsed().as_micros() as u64); + slow(started.elapsed().as_micros() as u64); + } + let now = j.ahead_asked; + for k in 0..count { + let page = j.found[k] / PAGE; + j.written.insert(page, now); + } + true +} + +/// What [`writes`] would say of `[start, end)` from the journal alone, if +/// the range lies in one asked ahead ([`ask_ahead`], [`ask_once`]): the +/// pages written since tracking began and the asking that last found each +/// written, with the number of the asking that stands (as [`writes`] gives +/// it). `None` if the kernel would have to be asked. +pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)> { + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + let j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + j.ahead + .iter() + .any(|&(a, b)| a <= first && last <= b) + .then(|| (j.ahead_asked, j.written.range(first..last).map(|(&p, &w)| (p, w)).collect())) +} + /// The pages of `[start, end)` (whole pages) as last written, for pages /// written since tracking began: `(page number, asking)` in page order, and /// this asking's number, which is higher than any in the list but those the @@ -54,6 +306,16 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve let (first, last) = (start / PAGE, end.div_ceil(PAGE)); let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); let j = &mut *j; + // Asked ahead with the submission's other ranges: the journal has it. + if j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { + return Some(( + j.ahead_asked, + j.written + .range(first..last) + .map(|(&p, &w)| (p, w)) + .collect(), + )); + } let mut count = (last - first) * PAGE / KERNEL_PAGE; j.found.resize(count.max(j.found.len()), 0); let mut granularity = 0; @@ -75,7 +337,12 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve if !guarded { return None; } - guard(first * PAGE, last * PAGE)? + #[cfg(feature = "diagnostics")] + let guarding = std::time::Instant::now(); + let written = guard(first * PAGE, last * PAGE); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::GuardUs, guarding.elapsed().as_micros() as u64); + written? } else { Vec::new() }; @@ -84,6 +351,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve use crate::copystat::{C, add}; add(C::Watches, 1); add(C::WatchUs, started.elapsed().as_micros() as u64); + slow(started.elapsed().as_micros() as u64); } j.asked += 1; let now = j.asked; @@ -108,11 +376,15 @@ struct Guards { protected: BTreeSet, /// Of those, the ones not written since a copy took them. clean: BTreeSet, + /// 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, } static GUARDS: Mutex = Mutex::new(Guards { protected: BTreeSet::new(), clean: BTreeSet::new(), + absent: BTreeSet::new(), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { @@ -123,12 +395,20 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> { /// they were last guarded (all of a block's pages), guarding them again /// before the caller copies them. `None` if the memory is not a view. fn guard(start: usize, end: usize) -> Option> { - use windows_sys::Win32::System::Memory::{MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery}; - // SAFETY: plain data filled in by the query. - let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - // SAFETY: a valid out pointer of the right size. - let n = unsafe { VirtualQuery(start as *const _, &mut info, size_of_val(&info)) }; - if n == 0 || info.Type != MEM_MAPPED { + // A range whose first block the guards hold already (read-only by our + // hand, or noted absent) is a view: no question to Windows. The + // question walks the page tables to the end of the pages that share the + // first one's state, and a guarded view is one long run of read-only + // pages: 0.6 ms for the title's 174 MB heap, 16 times a frame, and most + // of the 68 ms a frame of "guards" (run 58). + // `VICTORY_GUARD_ASK=1` asks every time, as before. + static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); + let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && { + let g = guards(); + let first = start / BLOCK; + g.protected.contains(&first) || g.absent.contains(&first) + }; + if !known && !is_view(start, end) { return None; } install(); @@ -136,8 +416,35 @@ fn guard(start: usize, end: usize) -> Option> { let mut written = Vec::new(); let mut run: Option = None; let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); + // The range's clean blocks, in order: read off the set 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 set meanwhile is the block it stands at or ones before it. + let clean: Vec = g.clean.range(first..last).copied().collect(); + if clean.len() == last - first { + // Nothing written, mapped or new since the range was last taken. + return Some(written); + } + let mut next_clean = 0; + let mut uncommitted_until = first; for block in first..=last { - let open = block < last && !g.clean.contains(&block); + while next_clean < clean.len() && clean[next_clean] < block { + next_clean += 1; + } + let is_clean = next_clean < clean.len() && clean[next_clean] == block; + let mut open = block < last && !is_clean; + if open && g.absent.contains(&block) { + // Ordinary commits need no runtime mapping notification. Reuse + // this asking's query for the following blocks in the same region. + if block >= uncommitted_until { + uncommitted_until = uncommitted_end(block); + } + open = block >= uncommitted_until; + if open { + g.absent.remove(&block); + } + } if open { written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE); if g.protected.contains(&block) { @@ -155,8 +462,53 @@ fn guard(start: usize, end: usize) -> Option> { Some(written) } +/// Whether `[start, end)` is view memory. The title's views lie in +/// placeholders, mapped and unmapped block by block as it streams, so a +/// range can begin in a block that is not mapped right now: the first +/// pages of the range that are there decide. A range with nothing there +/// counts as a view (its blocks are noted absent, and looked at again when +/// the runtime maps them). +/// +/// Looking at the first address only took such a range for "not a view": +/// its copy was marked not watched for good and copied whole at every +/// refresh, around its unmapped pages (run 54: 300 such ranges, 570 MB +/// copied a frame for them, 255 copies a frame reading around holes). +/// `VICTORY_GUARD_HOLES=0` looks at the first address only, as before. +fn is_view(start: usize, end: usize) -> bool { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery, + }; + static HOLES: std::sync::OnceLock = std::sync::OnceLock::new(); + let holes = *HOLES.get_or_init(|| std::env::var_os("VICTORY_GUARD_HOLES").is_none_or(|v| v != "0")); + let mut at = start; + loop { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; + if n == 0 { + return false; + } + if info.Type == MEM_MAPPED { + return true; + } + // Committed memory that is no view (the title's heaps, ours), or + // the answer as it was before. + if info.State == MEM_COMMIT || !holes { + return false; + } + // A hole (a placeholder, or free): on to what follows it. + let next = (info.BaseAddress as usize).saturating_add(info.RegionSize); + if next <= at || next >= end { + return true; + } + at = next; + } +} + /// Makes blocks `[from, to)` read-only and notes them guarded and clean; -/// block by block if they span views, leaving out any that fail (unmapped). +/// block by block if they span views, leaving out any that fail, and +/// noting those not committed (unmapped) absent. fn protect(g: &mut Guards, from: usize, to: usize) { use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; let set = |from: usize, to: usize| { @@ -182,10 +534,28 @@ fn protect(g: &mut Guards, from: usize, to: usize) { for block in from..to { if set(block, block + 1) { note(g, block, block + 1); + } else if block < uncommitted_end(block) { + g.absent.insert(block); } } } +/// The end (exclusive) of the whole uncommitted blocks starting at `block`. +fn uncommitted_end(block: usize) -> usize { + use windows_sys::Win32::System::Memory::{ + MEM_FREE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, VirtualQuery, + }; + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery((block * BLOCK) as *const _, &mut info, size_of_val(&info)) }; + if n != 0 && matches!(info.State, MEM_RESERVE | MEM_FREE) { + (info.BaseAddress as usize).saturating_add(info.RegionSize) / BLOCK + } else { + block + } +} + /// Gives write access back to the guarded blocks of `[start, end)` and /// notes them written; true if any was guarded. fn open(g: &mut Guards, start: usize, end: usize) -> bool { @@ -212,17 +582,77 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { pub fn writing(at: usize, len: usize) { // The length is the title's (`fread`'s size times count, saturated). open(&mut guards(), at, at.saturating_add(len)); + // A placed texture there changes with no descriptor written. + crate::descriptor::host::remapped(at, len); +} + +/// Held shared by a read of title memory in place, and alone by the runtime +/// while it changes what title memory shows. +/// +/// The runtime does not change a mapping in one step. To unmap one page of +/// a view it unmaps the whole view and maps what stays again +/// (`xmem.rs` `unmap`), and a view it maps is a reservation until the next +/// call commits it (`map`, then `commit`). For that moment pages the title +/// never gave up are "reserved, never committed", and a thread reading +/// them in place takes an access violation: run 71 in `Layout::detile`, +/// run 74 in the hash before it, both under `Staging::refresh_now`, which +/// had asked whether the texture was all mapped and been told yes. Asking +/// cannot help; not changing the mapping while such a read is under way +/// does. +static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(()); + +/// What the runtime holds while it changes what title memory shows +/// ([`title_memory_remapping`]). +pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>); + +/// The runtime is about to map, unmap or move physical pages of title +/// memory: until what it returns is dropped, no read of title memory in +/// place is under way and none begins ([`title_memory_reading`]). Taken +/// around the whole change, the unmapping and the mapping again. +pub fn title_memory_remapping() -> Remapping { + Remapping(MAPPING.write().unwrap_or_else(|e| e.into_inner())) +} + +/// What a read of title memory in place holds ([`title_memory_reading`]). +pub struct Reading(#[allow(dead_code)] std::sync::RwLockReadGuard<'static, ()>); + +/// For reading title memory in place: until what it returns is dropped, +/// the runtime changes no mapping, so memory found mapped stays mapped. +/// Not to be taken twice by one thread, nor held across anything that +/// maps title memory. +pub fn title_memory_reading() -> Reading { + Reading(MAPPING.read().unwrap_or_else(|e| e.into_inner())) +} + +/// [`title_memory_reading`] if it can be had at once: `None` while the +/// runtime changes a mapping (or waits to), for a caller that has another +/// way to read and would rather not wait. +pub fn title_memory_reading_now() -> Option { + match MAPPING.try_read() { + Ok(guard) => Some(Reading(guard)), + Err(std::sync::TryLockError::Poisoned(e)) => Some(Reading(e.into_inner())), + Err(std::sync::TryLockError::WouldBlock) => None, + } } /// The runtime mapped or unmapped title memory `[at, at + len)`: what it -/// shows is new and read-write, so it is no longer guarded. +/// shows is new and read-write, so it is no longer guarded (nor known +/// unmapped). pub fn title_memory_remapped(at: usize, len: usize) { + // A placed texture there arrives, goes or changes with no descriptor + // written. + crate::descriptor::host::remapped(at, len); + // The views the runtime told us of there are no longer what it shows. + crate::inplace::views_gone(at, len); + // And nothing stays in place over it. + crate::inplace::title_memory_freeing(at, len); let mut g = guards(); - let blocks: Vec = g - .protected - .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) - .copied() - .collect(); + let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK); + let absent: Vec = g.absent.range(range.clone()).copied().collect(); + for block in absent { + g.absent.remove(&block); + } + let blocks: Vec = g.protected.range(range).copied().collect(); for block in blocks { g.protected.remove(&block); g.clean.remove(&block); @@ -358,17 +788,264 @@ mod tests { let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) }; file.read(into).is_ok_and(|n| n == 13) }; - assert!(!read(&mut file), "the kernel does not fault into our handler"); + assert!( + !read(&mut file), + "the kernel does not fault into our handler" + ); writing(view + 100, 13); assert!(read(&mut file)); // SAFETY: the bytes just read. - assert_eq!(unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }, b"from the disk"); - assert_eq!(guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect())); + let landed = unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }; + assert_eq!(landed, b"from the disk"); + assert_eq!( + guard(view, view + 2 * BLOCK), + Some((view / PAGE..view / PAGE + 1).collect()) + ); // SAFETY: our view. - unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) }; + unsafe { + UnmapViewOfFile( + windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { + Value: view as *mut _, + }, + ) + }; title_memory_remapped(view, 2 * BLOCK); } + #[test] + fn writes_in_partly_committed_view_blocks_are_reported() { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, + SEC_RESERVE, UnmapViewOfFile, + }; + + const SIZE: usize = 3 * BLOCK; + struct View(MEMORY_MAPPED_VIEW_ADDRESS); + impl Drop for View { + fn drop(&mut self) { + title_memory_remapped(self.0.Value as usize, SIZE); + // SAFETY: our view is still mapped. + unsafe { UnmapViewOfFile(self.0) }; + } + } + // SAFETY: a new reserved pagefile section. The view holds its own + // reference after we close the handle, including on assertion failure. + let view = unsafe { + let section = CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE | SEC_RESERVE, + 0, + SIZE as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, SIZE); + CloseHandle(section); + assert!(!view.Value.is_null()); + View(view) + }; + let start = view.0.Value as usize; + let commit = |at: usize, len| { + // SAFETY: these pages belong to our reserved view. + let committed = unsafe { VirtualAlloc(at as _, len, MEM_COMMIT, PAGE_READWRITE) }; + assert_eq!(committed as usize, at); + }; + let early = start + BLOCK + 3 * KERNEL_PAGE; + let late = start + 2 * BLOCK + 3 * KERNEL_PAGE; + commit(start, BLOCK); + commit(early, KERNEL_PAGE); + let refresh = || guard(start, start + SIZE).unwrap(); + assert_eq!(refresh(), [start / PAGE, early / PAGE, late / PAGE]); + // The last block is still entirely reserved. + assert!(!refresh().contains(&(late / PAGE))); + + commit(late, KERNEL_PAGE); // Ordinary commit, without a runtime mapping notification. + for at in [early, late] { + assert!(writable(at)); + // SAFETY: each address is inside its committed read-write page. + unsafe { (at as *mut u8).write_volatile(1) }; + } + assert_eq!(refresh(), [early / PAGE, late / PAGE]); + } + + /// A range of view memory whose first block is not mapped is a view + /// all the same: its blocks are reported once, then the ones written + /// or mapped since. + #[test] + fn a_range_that_begins_in_an_unmapped_block_is_guarded() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, + MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2, + VirtualAlloc2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a fresh placeholder of three blocks and a pagefile + // section of three; the middle block is mapped first. + let (p, section) = unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + 3 * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (3 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + (p, section) + }; + let map = |block: usize| { + // SAFETY: splits the placeholder at the block and maps the + // section's block there. + let view = unsafe { + VirtualFree( + (p + block * BLOCK) as *mut _, + BLOCK, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ); + MapViewOfFile3( + section, + GetCurrentProcess(), + (p + block * BLOCK) as *const _, + (block * BLOCK) as u64, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, p + block * BLOCK); + view + }; + let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE; + let all: Vec = (0..3).flat_map(pages).collect(); + // Nothing mapped at all: a view with every block absent. + assert!(is_view(p, p + 3 * BLOCK)); + let middle = map(1); + title_memory_remapped(p + BLOCK, BLOCK); + // The range begins in the placeholder, its middle block is a view. + assert!(is_view(p, p + 3 * BLOCK)); + assert_eq!(guard(p, p + 3 * BLOCK), Some(all)); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()), "nothing written since"); + // SAFETY: inside the mapped middle block. + unsafe { ((p + BLOCK + 8) as *mut u8).write_volatile(1) }; + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); + let first = map(0); + title_memory_remapped(p, BLOCK); + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(0).collect())); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + // Memory of ours that is no view stays none. + let mut local = [0u8; 16]; + let at = local.as_mut_ptr() as usize; + assert!(!is_view(at, at + local.len())); + // SAFETY: our views and placeholder. + unsafe { + UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); + UnmapViewOfFile2(GetCurrentProcess(), middle, MEM_PRESERVE_PLACEHOLDER); + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + windows_sys::Win32::Foundation::CloseHandle(section); + } + title_memory_remapped(p, 3 * BLOCK); + } + + /// Blocks of a placeholder between views are reported once, then not + /// again (they cannot be guarded) until the runtime maps them. + #[test] + fn unmapped_blocks_are_reported_once_until_mapped() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, + MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2, + VirtualAlloc2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a fresh placeholder of three blocks and a pagefile + // section of two; block 0 shows the section's first block, as the + // runtime maps physical pages. + let (p, section) = unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + 3 * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + (p, section) + }; + let map = |block: usize| { + // SAFETY: splits the placeholder at the block and maps the + // section's block there. + let view = unsafe { + VirtualFree( + (p + block * BLOCK) as *mut _, + BLOCK, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ); + MapViewOfFile3( + section, + GetCurrentProcess(), + (p + block * BLOCK) as *const _, + (block * BLOCK) as u64, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, p + block * BLOCK); + view + }; + let first = map(0); + let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE; + let all: Vec = (0..3).flat_map(pages).collect(); + assert_eq!(guard(p, p + 3 * BLOCK), Some(all)); + assert_eq!( + guard(p, p + 3 * BLOCK), + Some(Vec::new()), + "nothing written since" + ); + let second = map(1); + title_memory_remapped(p + BLOCK, BLOCK); + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + // SAFETY: our views and placeholder. + unsafe { + UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); + UnmapViewOfFile2(GetCurrentProcess(), second, MEM_PRESERVE_PLACEHOLDER); + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + windows_sys::Win32::Foundation::CloseHandle(section); + } + title_memory_remapped(p, 3 * BLOCK); + } + /// A write or mapping that runs past the end of the address space (a /// title's `fread` with a huge count) covers up to the end; the sum used /// to overflow. Up there no test has guarded blocks. @@ -379,3 +1056,53 @@ mod tests { title_memory_remapped(top, usize::MAX); } } + +#[cfg(test)] +mod mapping_tests { + use super::{title_memory_reading, title_memory_remapping}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, mpsc}; + use std::time::Duration; + + /// A change of mapping waits for a read in place that is under way, and + /// a read in place waits for a change of mapping. + #[test] + fn reads_in_place_and_remappings_wait_for_each_other() { + // A reader holds; the change does not begin until it lets go. + let changed = Arc::new(AtomicBool::new(false)); + let reading = title_memory_reading(); + let (began, wait) = mpsc::channel(); + let change = { + let changed = changed.clone(); + std::thread::spawn(move || { + began.send(()).unwrap(); + let _changing = title_memory_remapping(); + changed.store(true, Ordering::SeqCst); + }) + }; + wait.recv().unwrap(); + std::thread::sleep(Duration::from_millis(100)); + assert!(!changed.load(Ordering::SeqCst), "the mapping changed under a read in place"); + drop(reading); + change.join().unwrap(); + assert!(changed.load(Ordering::SeqCst)); + // A change holds; the read does not begin until it is done. + let read = Arc::new(AtomicBool::new(false)); + let changing = title_memory_remapping(); + let (began, wait) = mpsc::channel(); + let reader = { + let read = read.clone(); + std::thread::spawn(move || { + began.send(()).unwrap(); + let _reading = title_memory_reading(); + read.store(true, Ordering::SeqCst); + }) + }; + wait.recv().unwrap(); + std::thread::sleep(Duration::from_millis(100)); + assert!(!read.load(Ordering::SeqCst), "a read in place began during a change of mapping"); + drop(changing); + reader.join().unwrap(); + assert!(read.load(Ordering::SeqCst)); + } +} diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index 4bd223a..ac34d4c 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -114,6 +114,11 @@ fn heap_alloc(size: usize, align: usize) -> Option<(*mut u8, u32)> { heap.blocks .insert(ptr as usize, Block { size, apu, layout }); heap.by_apu.insert(apu, ptr as usize); + // The big ones are named in the log: they are the title's audio memory + // given out of our allocator, which the memory line counts as ours. + if size >= 32 << 20 { + tracing::info!(mb = size >> 20, at = ?ptr, "audio memory for the title from our allocator"); + } Some((ptr, apu)) } diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index c94146f..324db9e 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -976,6 +976,16 @@ fn into_destination( if super::xmem::write_physical(pages, offset, &data[..n]) { Ok(()) } else { + // Said aloud: Grand Theft Auto VI never reads a request's result + // (it only polls for completion), so a destination left unwritten + // is a model or texture that silently holds whatever its pages + // held before. + tracing::warn!( + offset, + len, + pages = pages.len(), + "dstorage: a destination's physical pages could not be written (unknown page or a host failure); its request fails" + ); Err(E_INVALIDARG) } } diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index a411bd0..a45081e 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1144,7 +1144,21 @@ mod host { return None; } self.empty_until[slot] = None; - Some(convert(&state.Gamepad)) + #[allow(unused_mut)] + let mut pad = convert(&state.Gamepad); + // The scripted keys (`VICTORY_KEYS`) also press the first + // pad's buttons, by the stand-in pad's table: with a real pad + // connected the stand-in is not there, and a title that listens + // to the pad (Grand Theft Auto VI's start screen) saw nothing. + #[cfg(feature = "diagnostics")] + if slot == 0 { + for vk in scripted() { + if let Some(&(_, button)) = super::FALLBACK_BUTTONS.iter().find(|(key, _)| *key == vk) { + pad.buttons |= button; + } + } + } + Some(pad) } fn keys(&mut self) -> Vec { diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index a441c91..7500ea5 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -428,6 +428,9 @@ pub extern "system" fn XMemAllocatePhysicalPages( flags = format_args!("{flags:#x}"), "XMemAllocatePhysicalPages" ); + // For the GPU side's in-place census: only a committed section can be + // opened as a host heap. + victory_gpu::title_memory_section(handle as usize, size as u64, on_wine()); let section = Arc::new(Section(handle)); let mut physical = physical(); let first = physical.next_page; @@ -596,6 +599,11 @@ pub extern "system" fn XMemMapPhysicalPages( ) -> *mut c_void { let base = address as usize; let mut physical = physical(); + // Until the pages are mapped again: `unmap` takes whole views away and + // maps what stays of them again, and a mapped view is a reservation + // until it is committed. A read of title memory in place must not fall + // into that gap (`victory_gpu::title_memory_remapping`). + let _changing = victory_gpu::title_memory_remapping(); unmap(&mut physical, base, n * PAGE); if pages.is_null() { return address; @@ -663,6 +671,8 @@ 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 mut physical = physical(); + // As in `XMemMapPhysicalPages`: no read in place meets the gap. + let _changing = victory_gpu::title_memory_remapping(); unmap(&mut physical, to, len); for k in (0..len).step_by(PAGE) { if from == 0 { @@ -728,6 +738,8 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { } // New contents, read-write: the GPU side's copies no longer guard it. victory_gpu::title_memory_remapped(base, len); + // What the range shows now, for the GPU side's in-place census. + victory_gpu::title_memory_view(base, len, slice.section.0 as usize, (slice.index * PAGE) as u64); physical.views.insert(base, (len, slice)); true } @@ -868,6 +880,25 @@ pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut Workin gpu_optimal_limit: gpu_optimal, ..Default::default() }; + // What the title is told, logged at the first asking and at every + // 1,024th: "used" is all the process has committed, the layer's own + // memory and the card's included (27 GB in run 60's gameplay against a + // limit of 13.5 GB). A title that budgets its streaming from these two + // figures believes it is far over its limit. + // shortcut: the figure is not yet the title's own memory alone (its + // heaps and the pages it mapped); count those if this line shows the + // title asking. + static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let asked = ASKED.fetch_add(1, Ordering::Relaxed); + if asked % 1024 == 0 { + tracing::info!( + asked = asked + 1, + which = _which, + limit_mb = stats.title_limit >> 20, + used_mb = stats.title_used >> 20, + "the title asks how much memory it uses" + ); + } // SAFETY: checked non-null; the title passes room for the structure. unsafe { out.write(stats) }; 1 @@ -1112,6 +1143,57 @@ mod tests { assert_eq!(XMemIsToolsMemAvailable(), 0); } + /// A thread that reads a mapped page in place, as the GPU side reads a + /// texture, never meets the moment in which the runtime has taken the + /// page's view away to map it again: mapping the same pages at the same + /// address unmaps the view and maps a new one, and without the lock the + /// reader faults on a page "reserved, never committed" (the crashes of + /// runs 71 and 74). + #[test] + fn a_read_in_place_never_meets_the_gap_of_a_remapping() { + use std::sync::atomic::{AtomicBool, Ordering}; + let mut pages = [0usize; 3]; + let mut n = 3; + assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1); + let a = XMemVirtualAlloc( + std::ptr::null_mut(), + 3 * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ); + assert!(!a.is_null()); + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + // SAFETY: mapped read-write. + unsafe { a.cast::().write(1) }; + let first = a as usize; + let stop = std::sync::Arc::new(AtomicBool::new(false)); + let reader = { + let stop = stop.clone(); + std::thread::spawn(move || { + let mut reads = 0u64; + while !stop.load(Ordering::Relaxed) { + let _reading = victory_gpu::title_memory_reading(); + // SAFETY: the page is mapped whenever no change of + // mapping is under way, and none is while `_reading` + // is held. + assert_eq!(unsafe { (first as *const u8).read_volatile() }, 1); + reads += 1; + } + reads + }) + }; + for _ in 0..2000 { + // The same pages at the same address: the view goes and comes + // back, with the same bytes. + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + } + stop.store(true, Ordering::Relaxed); + assert!(reader.join().expect("the reader never faulted") > 0); + assert_eq!(XMemMapPhysicalPages(a, 3, std::ptr::null()), a); + assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); + } + #[test] fn mapping_no_pages_changes_nothing() { let pages = allocate(2); diff --git a/crates/victory-loader/Cargo.toml b/crates/victory-loader/Cargo.toml index 637253a..0f3497b 100644 --- a/crates/victory-loader/Cargo.toml +++ b/crates/victory-loader/Cargo.toml @@ -24,6 +24,7 @@ windows-sys = { workspace = true, features = [ "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", + "Win32_System_Performance", "Win32_System_Threading", ] } diff --git a/crates/victory-loader/src/console_insn.rs b/crates/victory-loader/src/console_insn.rs new file mode 100644 index 0000000..3791b18 --- /dev/null +++ b/crates/victory-loader/src/console_insn.rs @@ -0,0 +1,249 @@ +//! Instructions the console's CPU (Zen 2) has and an Intel PC's lacks, emulated: the title's +//! code raises STATUS_ILLEGAL_INSTRUCTION on them (GTA VI zeroes memory with a `clzero` loop at +//! its first frames), and the vectored handler steps over them here. +//! +//! Ported from XCL (github.com/ivall/xcl, GPL-2.0-only): `insn.rs` (decoder, as +//! `console_insn_decode.rs`, unchanged) and `eh.rs` `emulate_console_only`. + +#[path = "console_insn_decode.rs"] +mod decode; + +use decode::ConsoleOnly; +use std::cell::Cell; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT; + +const CONTINUE_EXECUTION: i32 = -1; + +/// Whether what Windows said about memory is remembered per thread (the regions it found +/// writable, the code bytes it found readable) and not asked again at every emulated +/// instruction. A query walks the pages of the region it answers for: asked from outside, it +/// took 2-9 ms in the title's heaps of 0.6-2.2 GB and 89 ms in its 6.2 GB page pool (run 30), +/// and the title zeroes blocks of them with `clzero` loops all through a frame: six of its +/// threads spent 25-78 % of their time inside that query (runs 29 and 30), about 27 s of +/// processor time in Windows per 9 s frame. On by default; `VICTORY_CLZERO_ASK=1` asks every +/// time, as before. +fn remembers() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CLZERO_ASK").is_none_or(|v| v != "1")) +} + +/// Answers a remembered region gives before Windows is asked about it again: one freed or +/// protected meanwhile is forgotten then. +const ANSWERS: u32 = 4096; + +thread_local! { + /// The regions Windows last said are committed and writable (start, end), newest first, + /// and the answers they gave since they were emptied. + static WRITABLE: Cell<([(usize, usize); 4], u32)> = const { Cell::new(([(0, 0); 4], 0)) }; + /// Faulting addresses and the code bytes found readable there, newest first. + static CODE: Cell<[(usize, usize); 8]> = const { Cell::new([(0, 0); 8]) }; +} + +/// Instructions emulated, the times Windows was asked about memory for them, and the bytes +/// `clzero` loops zeroed, since the start. +static EMULATED: AtomicU64 = AtomicU64::new(0); +static ASKED: AtomicU64 = AtomicU64::new(0); +static ZEROED: AtomicU64 = AtomicU64::new(0); + +fn readable(va: usize, bytes: usize) -> bool { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQuery}; + // SAFETY: plain data filled in by the query. + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0; + ASKED.fetch_add(1, Relaxed); + found && m.State == MEM_COMMIT && m.Protect & (PAGE_NOACCESS | PAGE_GUARD) == 0 && m.BaseAddress as usize + m.RegionSize >= va + bytes +} + +fn writable(va: usize, bytes: usize) -> bool { + writable_to(va, va + bytes) == Some(va + bytes) +} + +/// Where the committed, writable memory that `va` lies in ends, at most `end`; None if `va` +/// is not in such memory. A region found is remembered ([`remembers`]). +/// shortcut: a remembered region that was freed or protected since is written all the same +/// for up to [`ANSWERS`] answers: the write then faults inside the handler, which the guard +/// on view memory opens as it does any write, and which is a crash otherwise (as the +/// unchecked single-line emulation behind this one already is). +fn writable_to(va: usize, end: usize) -> Option { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, VirtualQuery}; + let remember = remembers(); + if remember { + let (regions, answers) = WRITABLE.with(Cell::get); + if let Some(&(_, to)) = regions.iter().find(|&&(from, to)| from <= va && va < to) { + let next = if answers >= ANSWERS { ([(0, 0); 4], 0) } else { (regions, answers + 1) }; + WRITABLE.with(|w| w.set(next)); + return Some(to.min(end)); + } + } + // SAFETY: plain data filled in by the query. + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0; + ASKED.fetch_add(1, Relaxed); + if !found || m.State != MEM_COMMIT || m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 { + return None; + } + let (from, to) = (m.BaseAddress as usize, m.BaseAddress as usize + m.RegionSize); + if remember { + WRITABLE.with(|w| { + let (mut regions, answers) = w.get(); + regions.rotate_right(1); + regions[0] = (from, to); + w.set((regions, answers)); + }); + } + Some(to.min(end)) +} + +/// An illegal instruction at `ctx.Rip`: a console-only one is emulated and stepped over +/// (`CONTINUE_EXECUTION`); anything else returns 0 (the crash report and the title's handlers +/// see it). +/// +/// # Safety +/// `ctx` is the faulting thread's context, from the exception being dispatched. +pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { + let rip = ctx.Rip as usize; + // The same few instructions fault again and again: their bytes are asked about once. + let known = if remembers() { CODE.with(Cell::get) } else { [(0, 0); 8] }; + let n = match known.iter().find(|&&(at, n)| at == rip && n > 0) { + Some(&(_, n)) => n, + None => { + if !readable(rip, 1) { + return 0; + } + let n = (1..=16).rev().find(|&n| readable(rip, n)).unwrap_or(0); + if remembers() { + let mut known = known; + known.rotate_right(1); + known[0] = (rip, n); + CODE.with(|c| c.set(known)); + } + n + } + }; + // SAFETY: `n` bytes at `rip` are readable. + let code = unsafe { std::slice::from_raw_parts(rip as *const u8, n) }; + let Some((what, len)) = decode::decode(code) else { return 0 }; + static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); + if let Ok(mut seen) = SEEN.lock() + && !seen.contains(&std::mem::discriminant(&what)) + { + seen.push(std::mem::discriminant(&what)); + if what != ConsoleOnly::Ud2 { + tracing::warn!(instruction = ?what, at = format_args!("{rip:#x}"), "a console CPU instruction this CPU lacks: emulated (logged once)"); + } + } + match what { + ConsoleOnly::Ud2 => return 0, + ConsoleOnly::Clwb => { + // nothing to write back on the PC: patched to NOPs, no exception next time + use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect}; + let mut old = 0u32; + // SAFETY: the instruction's own bytes, made writable for the patch and restored. + unsafe { + if VirtualProtect(rip as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) != 0 { + std::slice::from_raw_parts_mut(rip as *mut u8, len).fill(0x90); + VirtualProtect(rip as *const _, len, old, &mut old); + } + } + } + ConsoleOnly::Monitorx => {} + ConsoleOnly::Mwaitx => std::hint::spin_loop(), + ConsoleOnly::Clzero => { + // with an address-size prefix (0x67) the line is at EAX, zero-extended + let a32 = code[..len - 3].contains(&0x67); + let line = (if a32 { ctx.Rax & 0xFFFF_FFFF } else { ctx.Rax } as usize) & !63; + if !writable(line, 64) { + return 0; // the real instruction faults there too + } + // SAFETY: the 64-byte line is committed and writable. + unsafe { std::ptr::write_bytes(line as *mut u8, 0, 64) }; + } + ConsoleOnly::ClzeroLoop { end_reg } => { + // the whole `clzero; add rax,40h; cmp rax,end; jb` loop at once + let regs: [u64; 16] = [ + ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.Rbx, ctx.Rsp, ctx.Rbp, ctx.Rsi, ctx.Rdi, ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15, + ]; + let end = regs[end_reg as usize & 15] as usize; + let start = ctx.Rax as usize; + if end > start && end - start < 2 << 30 { + // Region by region: a block may lie across several (the title's pages are + // mapped one view each), and one answer for all of it was a refusal, after + // which every 64-byte line took an exception of its own. + let mut at = start; + while at < end { + let Some(to) = writable_to(at, end) else { break }; + // SAFETY: committed and writable from `at` to `to`. + unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) }; + at = to; + } + if at == start { + return 0; + } + ZEROED.fetch_add((at - start) as u64, Relaxed); + if at < end { + // What follows is not writable: the loop goes on there (the same + // instruction again), where the real one faults too. + ctx.Rax = at as u64; + return CONTINUE_EXECUTION; + } + } + ctx.Rax = end as u64; + } + ConsoleOnly::Rdpru => { + let mut v = 0i64; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut v) }; + let v = if ctx.Rcx as u32 <= 1 { v as u64 } else { 0 }; + ctx.Rax = v & 0xFFFF_FFFF; + ctx.Rdx = v >> 32; + } + ConsoleOnly::Rdpid(r) => { + // SAFETY: no preconditions. + let cpu = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessorNumber() } as u64; + let regs: [&mut u64; 16] = [ + &mut ctx.Rax, &mut ctx.Rcx, &mut ctx.Rdx, &mut ctx.Rbx, &mut ctx.Rsp, &mut ctx.Rbp, &mut ctx.Rsi, &mut ctx.Rdi, &mut ctx.R8, &mut ctx.R9, &mut ctx.R10, &mut ctx.R11, &mut ctx.R12, &mut ctx.R13, + &mut ctx.R14, &mut ctx.R15, + ]; + *regs[r as usize & 15] = cpu; + } + // the low quadword changes; the high one is zeroed, as a Zen 5 does + ConsoleOnly::Extrq { dst, src, len, idx } => { + // SAFETY: the context's XMM registers (CONTEXT_FLOATING_POINT is captured for exceptions). + let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters }; + let (len, idx) = match src { + Some(s) => { + let c = x[s as usize & 15].Low; + (c as u8, (c >> 8) as u8) + } + None => (len, idx), + }; + let d = &mut x[dst as usize & 15]; + d.Low = decode::extrq(d.Low, len, idx); + d.High = 0; + } + ConsoleOnly::Insertq { dst, src, reg, len, idx } => { + // SAFETY: as above. + let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters }; + let s = x[src as usize & 15]; + let (len, idx) = if reg { (s.High as u8, (s.High >> 8) as u8) } else { (len, idx) }; + let d = &mut x[dst as usize & 15]; + d.Low = decode::insertq(d.Low, s.Low, len, idx); + d.High = 0; + } + } + ctx.Rip += len as u64; + // How often this runs at all (each one is an exception: a trip into Windows and back). + let emulated = EMULATED.fetch_add(1, Relaxed) + 1; + if emulated >= 1 << 16 && emulated.is_power_of_two() { + tracing::info!( + emulated, + asked = ASKED.load(Relaxed), + zeroed_mb = ZEROED.load(Relaxed) >> 20, + "console CPU instructions emulated so far, the times Windows was asked about memory for them, and what clzero loops zeroed" + ); + } + CONTINUE_EXECUTION +} diff --git a/crates/victory-loader/src/console_insn_decode.rs b/crates/victory-loader/src/console_insn_decode.rs new file mode 100644 index 0000000..5b8488e --- /dev/null +++ b/crates/victory-loader/src/console_insn_decode.rs @@ -0,0 +1,237 @@ +//! Instructions the console's CPU (Zen 2) has and a PC's may lack – a title raises +//! STATUS_ILLEGAL_INSTRUCTION on them on an Intel CPU before Ice Lake / Alder Lake (CLWB, +//! SHA) or on any Intel CPU (CLZERO, RDPRU, MONITORX / MWAITX and SSE4a's EXTRQ / INSERTQ, +//! which are AMD's). The exception handler (`eh`) emulates the ones decoded here and steps over +//! them. + +/// A console-only instruction at the faulting address. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConsoleOnly { + /// `clwb m8`: write a cache line back – nothing to do, the PC's memory is coherent + Clwb, + /// `clzero`: zero the 64-byte cache line at rAX + Clzero, + /// `clzero` loop: `clzero; add rax, 0x40; cmp rax, ; jb -12` – zero `[rax..reg)` + ClzeroLoop { end_reg: u8 }, + /// `rdpru`: ecx = 0 MPERF / 1 APERF → edx:eax (a counter) + Rdpru, + /// `monitorx` / `mwaitx`: a wait the emulation skips + Monitorx, + Mwaitx, + /// `rdpid r64`: TSC_AUX (the processor number) into the register (CONTEXT order: rax, rcx, + /// rdx, rbx, rsp, rbp, rsi, rdi, r8..r15) + Rdpid(u8), + /// SSE4a `extrq xmm, imm8 (length), imm8 (index)` / `extrq xmm1, xmm2` (`src` Some: the + /// length and index in xmm2's bits 5:0 and 13:8): a bit field of the low quadword, moved + /// down and zero-extended (the high quadword zeroed). Registers are XMM numbers 0..15. + Extrq { dst: u8, src: Option, len: u8, idx: u8 }, + /// SSE4a `insertq xmm1, xmm2, imm8 (length), imm8 (index)` / `insertq xmm1, xmm2` (`reg`: + /// the length and index in xmm2's bits 69:64 and 77:72): the low bits of xmm2 put into a + /// bit field of xmm1's low quadword. + Insertq { dst: u8, src: u8, reg: bool, len: u8, idx: u8 }, + /// `ud2`: the title's own trap (not emulated) + Ud2, +} + +/// A field length of SSE4a's six bits: 0 is 64. +fn field_len(len: u8) -> u32 { + match len & 63 { + 0 => 64, + n => n as u32, + } +} + +/// EXTRQ on a low quadword: `len` bits from bit `idx`, zero-extended (a field past bit 63 is +/// undefined on the console; here it is what a shift gives). +pub fn extrq(v: u64, len: u8, idx: u8) -> u64 { + let (len, idx) = (field_len(len), (idx & 63) as u32); + let field = v.checked_shr(idx).unwrap_or(0); + if len >= 64 { + field + } else { + field & ((1u64 << len) - 1) + } +} + +/// INSERTQ on a low quadword: the low `len` bits of `src` put at bit `idx` of `dst`. +pub fn insertq(dst: u64, src: u64, len: u8, idx: u8) -> u64 { + let (len, idx) = (field_len(len), (idx & 63) as u32); + let ones = if len >= 64 { u64::MAX } else { (1u64 << len) - 1 }; + let mask = ones.checked_shl(idx).unwrap_or(0); + (dst & !mask) | ((src & ones).checked_shl(idx).unwrap_or(0) & mask) +} + +/// The length of a ModRM-encoded operand (ModRM, SIB and displacement) at `b[0]`, None when the +/// bytes run out. +fn modrm_len(b: &[u8]) -> Option { + let modrm = *b.first()?; + let (md, rm) = (modrm >> 6, modrm & 7); + if md == 3 { + return Some(1); + } + let mut len = 1; + let mut base = rm; + if rm == 4 { + base = *b.get(1)? & 7; + len += 1; + } + len += match md { + 0 if base == 5 => 4, // disp32 (rip-relative, or a SIB without a base) + 0 => 0, + 1 => 1, + _ => 4, + }; + (b.len() >= len).then_some(len) +} + +/// The console-only instruction at the start of `code` and its length. +pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> { + let mut i = 0; + // `rep`: the last of F2 / F3, which decides between them (and over 66) for SSE4a + let (mut p66, mut pf3, mut rep, mut rex) = (false, false, 0u8, 0u8); + while let Some(&b) = code.get(i) { + match b { + 0x66 => p66 = true, + 0xF2 => rep = 0xF2, + 0xF3 => { + pf3 = true; + rep = 0xF3; + } + 0x2E | 0x3E | 0x26 | 0x36 | 0x64 | 0x65 | 0x67 => {} + // REX counts only right before the opcode: one before a legacy prefix is ignored + 0x40..=0x4F => { + rex = b; + i += 1; + continue; + } + _ => break, + } + rex = 0; + i += 1; + } + if *code.get(i)? != 0x0F { + return None; + } + match (*code.get(i + 1)?, code.get(i + 2).copied()) { + (0x01, Some(0xFC)) => { + // clzero (0F 01 FC); add rax, 0x40 (48 83 C0 40); cmp rax, ([48|4C] 39 modrm); jb -12 (72 F4) + // (not after an 0x67: that CLZERO is at EAX, and the jb goes back to the 0F, past the + // prefix – it is stepped alone, the loop is taken from the next one) + if code.len() >= i + 12 + && !code[..i].contains(&0x67) + && code[i + 3..i + 7] == [0x48, 0x83, 0xC0, 0x40] + && (code[i + 7] == 0x48 || code[i + 7] == 0x4C) + && code[i + 8] == 0x39 + && code[i + 10..i + 12] == [0x72, 0xF4] + { + let rex_r = code[i + 7] == 0x4C; + let modrm = code[i + 9]; + let reg_idx = ((modrm >> 3) & 7) | if rex_r { 8 } else { 0 }; + Some((ConsoleOnly::ClzeroLoop { end_reg: reg_idx }, i + 12)) + } else { + Some((ConsoleOnly::Clzero, i + 3)) + } + } + (0x01, Some(0xFD)) => Some((ConsoleOnly::Rdpru, i + 3)), + (0x01, Some(0xFA)) => Some((ConsoleOnly::Monitorx, i + 3)), + (0x01, Some(0xFB)) => Some((ConsoleOnly::Mwaitx, i + 3)), + (0x0B, _) => Some((ConsoleOnly::Ud2, i + 2)), + // SSE4a: register operands only (ModRM mod 3); REX.R extends reg, REX.B rm + // (the last of F2 / F3 decides: F2 INSERTQ, F3 #UD; neither with 66: EXTRQ) + (0x78 | 0x79, Some(m)) if (rep == 0xF2 || (rep == 0 && p66)) && m >> 6 == 3 => { + let reg = ((m >> 3) & 7) | (rex & 4) << 1; + let rm = (m & 7) | (rex & 1) << 3; + let imm = |k: usize| code.get(i + 3 + k).copied(); + match (code[i + 1], rep == 0xF2) { + // extrq xmm(rm), imm8, imm8 – the ModRM reg field is /0 + (0x78, false) if (m >> 3) & 7 == 0 => Some((ConsoleOnly::Extrq { dst: rm, src: None, len: imm(0)?, idx: imm(1)? }, i + 5)), + (0x79, false) => Some((ConsoleOnly::Extrq { dst: reg, src: Some(rm), len: 0, idx: 0 }, i + 3)), + (0x78, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: false, len: imm(0)?, idx: imm(1)? }, i + 5)), + (0x79, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: true, len: 0, idx: 0 }, i + 3)), + _ => None, + } + } + // 66 0F AE /6 with a memory operand (without 66 it is xsaveopt) + (0xAE, Some(m)) if p66 && (m >> 3) & 7 == 6 && m >> 6 != 3 => Some((ConsoleOnly::Clwb, i + 2 + modrm_len(&code[i + 2..])?)), + // F3 0F C7 /7 with a register operand + (0xC7, Some(m)) if pf3 && (m >> 3) & 7 == 7 && m >> 6 == 3 => Some((ConsoleOnly::Rdpid((m & 7) | (rex & 1) << 3), i + 3)), + _ => None, + } +} + +/// `code` as hex, for a log line. +pub fn hex(code: &[u8]) -> String { + code.iter().map(|b| format!("{b:02x}")).collect::>().join(" ") +} + +#[cfg(test)] +mod tests { + use super::*; + + /// EXTRQ / INSERTQ as AMD's manual gives them: a length of 0 is 64. + #[test] + fn sse4a_bit_fields() { + assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 8, 16), 0xBC); + assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 0, 0), 0x1234_5678_9ABC_DEF0); + assert_eq!(extrq(0x8000_0000_0000_0000, 1, 63), 1); + assert_eq!(insertq(0xFFFF_FFFF_FFFF_FFFF, 0xAB, 8, 8), 0xFFFF_FFFF_FFFF_ABFF); + assert_eq!(insertq(0, 0x1FF, 4, 60), 0xF000_0000_0000_0000); + assert_eq!(insertq(0x1111, 0xDEAD_BEEF_0000_0000, 0, 0), 0xDEAD_BEEF_0000_0000); + for (v, len, idx) in [(0x0123_4567_89AB_CDEFu64, 12u8, 20u8), (u64::MAX, 63, 1), (0x55, 3, 0)] { + assert_eq!(extrq(insertq(0, v, len, idx), len, idx), extrq(v, len, 0)); + } + } + + #[test] + fn decodes_the_console_only_instructions() { + assert_eq!(decode(&[0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 3))); + // clzero loop against r10 (4C 39 D0 = cmp rax, r10) + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xD0, 0x72, 0xF4]), + Some((ConsoleOnly::ClzeroLoop { end_reg: 10 }, 12)) + ); + // clzero loop against rdx (48 39 D0 = cmp rax, rdx) + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]), + Some((ConsoleOnly::ClzeroLoop { end_reg: 2 }, 12)) + ); + // the same loop after an address-size prefix: that one CLZERO alone + assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 4))); + assert_eq!(decode(&[0x0F, 0x01, 0xFD]), Some((ConsoleOnly::Rdpru, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFA]), Some((ConsoleOnly::Monitorx, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFB]), Some((ConsoleOnly::Mwaitx, 3))); + assert_eq!(decode(&[0x0F, 0x0B]), Some((ConsoleOnly::Ud2, 2))); + // clwb [rax]; clwb [rcx+0x40]; clwb [rsp+8]; clwb [rip+disp32]; clwb [r8] + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 4))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x71, 0x40]), Some((ConsoleOnly::Clwb, 5))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24, 0x08]), Some((ConsoleOnly::Clwb, 6))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x35, 1, 2, 3, 4]), Some((ConsoleOnly::Clwb, 8))); + assert_eq!(decode(&[0x66, 0x41, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 5))); + // rdpid rax; rdpid r9 + assert_eq!(decode(&[0xF3, 0x0F, 0xC7, 0xF8]), Some((ConsoleOnly::Rdpid(0), 4))); + assert_eq!(decode(&[0xF3, 0x41, 0x0F, 0xC7, 0xF9]), Some((ConsoleOnly::Rdpid(9), 5))); + // not console-only: clflushopt (/7), xsaveopt (no 66), a plain mov, truncated bytes + // SSE4a, as a retail game has it (#216: insertq xmm0, xmm1 with length / index bytes) + assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08, 0x10]), Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 8, idx: 16 }, 6))); + assert_eq!(decode(&[0xF2, 0x45, 0x0F, 0x79, 0xC1]), Some((ConsoleOnly::Insertq { dst: 8, src: 9, reg: true, len: 0, idx: 0 }, 5))); + assert_eq!(decode(&[0x66, 0x0F, 0x78, 0xC2, 0x04, 0x08]), Some((ConsoleOnly::Extrq { dst: 2, src: None, len: 4, idx: 8 }, 6))); + assert_eq!(decode(&[0x66, 0x0F, 0x79, 0xCA]), Some((ConsoleOnly::Extrq { dst: 1, src: Some(2), len: 0, idx: 0 }, 4))); + assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08]), None, "an immediate missing"); + assert_eq!(decode(&[0x0F, 0x78, 0xC1, 0x08, 0x10]), None, "VMREAD without a prefix is not SSE4a"); + // prefixes as a Zen 5 runs them (Kalmarv on #209): the last of F2 / F3 decides, 66 next + // to them does not; 0x67 and a REX before a legacy prefix are ignored + let insertq = Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 16, idx: 16 }, 7)); + for code in [[0x66, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF2, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x67, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x41, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10]] { + assert_eq!(decode(&code), insertq, "{code:02x?}"); + } + for code in [[0xF2, 0xF3, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x66, 0xF3, 0x0F, 0x78, 0xC0, 0x10, 0x10]] { + assert_eq!(decode(&code), None, "#UD on the CPU: {code:02x?}"); + } + assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 4))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x38]), None); + assert_eq!(decode(&[0x0F, 0xAE, 0x30]), None); + assert_eq!(decode(&[0x48, 0x8B, 0x01]), None); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24]), None); + assert_eq!(decode(&[0x0F]), None); + } +} diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index 7d13646..3f77a88 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -357,6 +357,15 @@ unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option { } unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + // an instruction of the console's CPU this one lacks: emulated, the title goes on + // SAFETY: the system passes valid exception pointers. + if unsafe { (*(*info).ExceptionRecord).ExceptionCode } == EXCEPTION_ILLEGAL_INSTRUCTION { + // SAFETY: the faulting thread's context, for the exception being dispatched. + let r = unsafe { crate::console_insn::emulate(&mut *(*info).ContextRecord) }; + if r != 0 { + return r; + } + } // SAFETY: the system passes valid exception pointers. if unsafe { emulate_amd_only(info) } { return -1; // EXCEPTION_CONTINUE_EXECUTION diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 233ca47..28cabd6 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -22,6 +22,7 @@ //! on, pass every thread start and end on to the attached images. #[cfg(windows)] +mod console_insn; mod crash; pub mod prepare; pub mod resolve; diff --git a/crates/victory-shader/src/bvh.rs b/crates/victory-shader/src/bvh.rs new file mode 100644 index 0000000..43fb195 --- /dev/null +++ b/crates/victory-shader/src/bvh.rs @@ -0,0 +1,696 @@ +//! The console GPU's ray-tracing node test, `image_bvh_intersect_ray` and +//! `image_bvh64_intersect_ray`, on the CPU: the node formats, and what the +//! instruction returns for one ray and one node. The emitter lowers the +//! instruction to the same arithmetic in the same order +//! (`emit/intersect.rs`), so its code can be compared against this dword +//! for dword. +//! +//! The instruction tests one ray against one 64-byte node of a bounding +//! volume hierarchy and returns four dwords. Traversal (the stack, instance +//! transforms, culling, the hit distance `numerator / denominator`) is the +//! program's own code. +//! +//! # Node pointers +//! +//! A node pointer's low three bits are the node's kind, the rest its byte +//! offset in 8-byte units: the node is at `(pointer >> 3) << 6` past the +//! base address of the descriptor (40 bits in dword 0 and the low byte of +//! dword 1, in 256-byte units). The 32-bit form takes a 32-bit pointer; +//! the 64-bit form a 64-bit one, with which a program uses one descriptor +//! with base 0 for every structure and adds `address >> 3` itself. +//! +//! | kind | node | +//! |---|---| +//! | 0-3 | triangle 0-3 of a triangle node | +//! | 4 | box node, 16-bit floats (64 bytes) | +//! | 5 | box node, 32-bit floats (128 bytes) | +//! | 6 | instance: not read by the instruction | +//! | 7 | procedural primitive: not read by the instruction | +//! +//! # Box nodes +//! +//! Four child pointers at bytes 0-15 (`0xffff_ffff`: none), then four +//! boxes, each minimum x y z, maximum x y z: 16-bit floats from byte 16 +//! (12 bytes a box), or 32-bit floats from byte 16 (24 bytes a box; bytes +//! 112-127 are not read). The result is the pointers of the children whose +//! box the ray enters before its extent, nearest entry first when the +//! descriptor enables box sorting (bit 63), and `0xffff_ffff` for the rest. +//! +//! # Triangle nodes +//! +//! Five vertices of three 32-bit floats at bytes 0-59 and a dword at byte +//! 60 with one byte per triangle: bits 1:0 name the triangle's vertex that +//! barycentric I weighs, bits 3:2 the one J weighs (the builder stores an +//! input triangle's second vertex at the former, its third at the latter +//! and its first at the remaining one, so I and J are the weights of the +//! input triangle's second and third vertices). Triangle `k` of the node +//! uses the node's vertices [`TRIANGLE_VERTICES`]`[k]`. A program that +//! keeps fewer triangles in a node uses the bytes of the unused vertices +//! for its own data. +//! +//! With the descriptor's triangle return mode set (bit 120) the result is +//! the hit distance's numerator, its denominator, and the numerators of I +//! and J over the same denominator, as floats. The denominator is positive +//! for a triangle whose vertices run clockwise seen from the ray's origin +//! in a left-handed coordinate system. A miss returns +infinity, 1.0, 0, 0. +//! The ray's extent is not tested for triangles. +//! +//! # Where this comes from +//! +//! The node formats, the descriptor bits and the tests are those of the +//! public software emulation of this instruction in the open-source Vulkan +//! driver for this GPU family (box test and sorting network as there; the +//! triangle test is the watertight one it uses, Woop, Benthin and Wald, +//! JCGT 2013), and agree with what Grand Theft Auto VI's own structure +//! builder writes and its trace programs read. Not known from either: how +//! the console rounds, which of two boxes entered at the same distance it +//! returns first, and what it returns for a ray exactly through an edge +//! (here: a hit in both triangles of the edge) or for kinds 6 and 7 (here: +//! a triangle miss; the title's programs do not read it). + +/// The result dword for a box the ray misses, or a child that is not there. +pub const NONE: u32 = 0xffff_ffff; + +/// The node's vertices that make triangle 0-3, by the triangle's own +/// vertex numbers 0-2. +pub const TRIANGLE_VERTICES: [[u32; 3]; 4] = [[0, 1, 2], [1, 3, 2], [2, 3, 4], [2, 4, 0]]; + +/// Descriptor dword 1: boxes are returned nearest first. +pub const BOX_SORT: u32 = 1 << 31; +/// Descriptor dword 3: triangles return the numerators of I and J (clear: +/// a triangle id and a hit status, which nothing here produces). +pub const RETURN_BARYCENTRICS: u32 = 1 << 24; +/// Descriptor dword 3, bits 31:28: the descriptor's type, a ray-tracing +/// structure. +pub const DESCRIPTOR_TYPE: u32 = 8; + +/// The ray as the instruction takes it. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Ray { + pub extent: f32, + pub origin: [f32; 3], + pub direction: [f32; 3], + /// What the program computed as `1 / direction`. + pub inverse: [f32; 3], +} + +impl Ray { + /// A ray with the inverse direction a program computes by division. + pub fn new(origin: [f32; 3], direction: [f32; 3], extent: f32) -> Self { + Self { + extent, + origin, + direction, + inverse: direction.map(|d| 1.0 / d), + } + } +} + +/// The kind of the node a pointer names. +pub fn kind(pointer: u64) -> u32 { + (pointer & 7) as u32 +} + +/// The byte address of the node `pointer` names, for a descriptor whose +/// first two dwords are `word0` and `word1`. +pub fn node_address(word0: u32, word1: u32, pointer: u64) -> u64 { + let base = (u64::from(word1 & 0xff) << 32 | u64::from(word0)) << 8; + base.wrapping_add((pointer >> 3) << 6) +} + +/// What the instruction returns for the node at `words` (its first 28 +/// dwords; a 64-byte node's dwords 16-27 are not read) named by a pointer +/// of this `kind`, with box sorting as `sort` says and the triangle return +/// mode set. +pub fn intersect(words: &[u32; 28], kind: u32, ray: &Ray, sort: bool) -> [u32; 4] { + match kind & 7 { + 4 => boxes(&children(words), &boxes16(words), ray, sort), + 5 => boxes(&children(words), &boxes32(words), ray, sort), + k @ 0..=3 => triangle(&triangle_vertices(words, k), ray).map(f32::to_bits), + _ => MISS.map(f32::to_bits), + } +} + +/// A box node's four child pointers. +pub fn children(words: &[u32; 28]) -> [u32; 4] { + [words[0], words[1], words[2], words[3]] +} + +/// The four boxes of a 16-bit box node: minimum x y z, maximum x y z. +pub fn boxes16(words: &[u32; 28]) -> [[f32; 6]; 4] { + std::array::from_fn(|b| { + std::array::from_fn(|k| { + let half = 6 * b + k; + half_to_f32((words[4 + half / 2] >> (16 * (half % 2))) as u16) + }) + }) +} + +/// The four boxes of a 32-bit box node. +pub fn boxes32(words: &[u32; 28]) -> [[f32; 6]; 4] { + std::array::from_fn(|b| std::array::from_fn(|k| f32::from_bits(words[4 + 6 * b + k]))) +} + +/// [`TRIANGLE_VERTICES`] of triangle `k` in four bits each, vertex 0 lowest +/// (as the public descriptions of the format give it: 0x210, 0x231, 0x432, +/// 0x042). +pub fn vertex_map(k: u32) -> u32 { + let v = TRIANGLE_VERTICES[(k & 3) as usize]; + v[0] | v[1] << 4 | v[2] << 8 +} + +/// The vertices of triangle `k` (0-3) of a triangle node, the first being +/// the one neither barycentric weighs, then I's, then J's. +pub fn triangle_vertices(words: &[u32; 28], k: u32) -> [[f32; 3]; 3] { + let id = words[15] >> (8 * k); + let (i, j) = (id & 3, id >> 2 & 3); + // An id naming one vertex twice, or a vertex 3, is malformed; it reads + // what this arithmetic lands on (a vertex of the node), as the emitted + // code does. + let first = 3u32.wrapping_sub(i).wrapping_sub(j) & 3; + [first, i, j].map(|n| { + let vertex = (vertex_map(k) >> (4 * n) & 0xf) as usize; + std::array::from_fn(|c| f32::from_bits(words[3 * vertex + c])) + }) +} + +/// The box test: child pointers of the boxes the ray enters, `NONE` for +/// the others; sorted by entry distance when `sort`, in child order +/// otherwise. +pub fn boxes(children: &[u32; 4], boxes: &[[f32; 6]; 4], ray: &Ray, sort: bool) -> [u32; 4] { + // An infinite inverse (a direction component of 0) would turn an + // origin exactly on a box's face into a NaN. (Maximum then minimum, as + // the emitted code: a NaN becomes the lower bound, where `clamp` would + // keep it.) + #[allow(clippy::manual_clamp)] + let inverse = ray.inverse.map(|x| x.max(-f32::MAX).min(f32::MAX)); + let mut ids = [NONE; 4]; + let mut distances = [f32::INFINITY; 4]; + for (n, b) in boxes.iter().enumerate() { + let (mut near, mut far) = ([0f32; 3], [0f32; 3]); + for a in 0..3 { + let low = (b[a] - ray.origin[a]) * inverse[a]; + let high = (b[3 + a] - ray.origin[a]) * inverse[a]; + near[a] = low.min(high); + far[a] = low.max(high); + } + let enter = near[0].max(near[1]).max(near[2]); + let leave = far[0].min(far[1]).min(far[2]); + // A box whose minimum x is NaN is switched off. + if !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent { + ids[n] = children[n]; + distances[n] = enter; + } + } + if sort { + for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] { + if distances[b] < distances[a] { + distances.swap(a, b); + ids.swap(a, b); + } + } + } + ids +} + +/// What a triangle the ray misses returns. +pub const MISS: [f32; 4] = [f32::INFINITY, 1.0, 0.0, 0.0]; + +/// The triangle test: the hit distance's numerator, the denominator, and +/// the numerators of the weights of vertices 1 and 2; [`MISS`] otherwise. +/// Watertight: the vertices are sheared so the ray runs along its largest +/// axis, and the signs of the three edge functions decide, so a ray +/// between two triangles that share an edge cannot miss both. Any NaN +/// misses, and so does a triangle seen edge-on. +pub fn triangle(p: &[[f32; 3]; 3], ray: &Ray) -> [f32; 4] { + let d = ray.direction; + let size = d.map(f32::abs); + // The largest axis, and the other two in an order that keeps the + // triangle's winding. + let kz = if size[0] >= size[1] { + if size[0] >= size[2] { 0 } else { 2 } + } else if size[1] >= size[2] { + 1 + } else { + 2 + }; + let (mut kx, mut ky) = ((kz + 1) % 3, (kz + 2) % 3); + if d[kz] < 0.0 { + std::mem::swap(&mut kx, &mut ky); + } + let sz = ray.inverse[kz]; + let (sx, sy) = (d[kx] * sz, d[ky] * sz); + let sheared = |v: &[f32; 3]| { + let r = [ + v[0] - ray.origin[0], + v[1] - ray.origin[1], + v[2] - ray.origin[2], + ]; + (r[kx] - sx * r[kz], r[ky] - sy * r[kz], sz * r[kz]) + }; + let (ax, ay, az) = sheared(&p[0]); + let (bx, by, bz) = sheared(&p[1]); + let (cx, cy, cz) = sheared(&p[2]); + let u = cx * by - cy * bx; + let v = ax * cy - ay * cx; + let w = bx * ay - by * ax; + let behind = u < 0.0 || v < 0.0 || w < 0.0; + let before = u > 0.0 || v > 0.0 || w > 0.0; + let det = u + (v + w); + let t = (u * az + v * bz) + w * cz; + let ahead = det > 0.0 && t >= 0.0 || det < 0.0 && t <= 0.0; + if !(behind && before) && ahead { + [t, det, v, w] + } else { + MISS + } +} + +/// A 16-bit float as a 32-bit one (exact). +pub fn half_to_f32(h: u16) -> f32 { + let sign = u32::from(h >> 15) << 31; + let (exponent, mantissa) = (u32::from(h >> 10 & 0x1f), u32::from(h & 0x3ff)); + let bits = match exponent { + 0 if mantissa == 0 => sign, + 0 => { + // Subnormal: normalise. + let shift = mantissa.leading_zeros() - 21; + sign | (113 - shift) << 23 | (mantissa << shift & 0x3ff) << 13 + } + 0x1f => sign | 0xff << 23 | mantissa << 13, + e => sign | (e + 112) << 23 | mantissa << 13, + }; + f32::from_bits(bits) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// The smallest 16-bit float not below `x` (`up`) or not above it. + pub(crate) fn f32_to_half(x: f32, up: bool) -> u16 { + let mut best: Option = None; + for h in 0..=0xffffu16 { + let f = half_to_f32(h); + if f.is_nan() || if up { f < x } else { f > x } { + continue; + } + best = match best { + Some(b) if (half_to_f32(b) - x).abs() <= (f - x).abs() => Some(b), + _ => Some(h), + }; + } + best.expect("a half") + } + + /// A 32-bit box node. + pub(crate) fn box32(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] { + let mut w = [0u32; 28]; + w[..4].copy_from_slice(&children); + for (b, bx) in boxes.iter().enumerate() { + for (k, x) in bx.iter().enumerate() { + w[4 + 6 * b + k] = x.to_bits(); + } + } + w + } + + /// A 16-bit box node holding `boxes` rounded outward. + pub(crate) fn box16(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] { + let mut w = [0u32; 28]; + w[..4].copy_from_slice(&children); + for (b, bx) in boxes.iter().enumerate() { + for (k, x) in bx.iter().enumerate() { + let half = 6 * b + k; + let h = if x.is_nan() { + 0x7e00 + } else { + f32_to_half(*x, k >= 3) + }; + w[4 + half / 2] |= u32::from(h) << (16 * (half % 2)); + } + } + w + } + + /// A triangle node: up to five vertices, and the dword at byte 60. + pub(crate) fn triangles(vertices: &[[f32; 3]], id: u32) -> [u32; 28] { + let mut w = [0u32; 28]; + for (n, v) in vertices.iter().enumerate() { + for (c, x) in v.iter().enumerate() { + w[3 * n + c] = x.to_bits(); + } + } + w[15] = id; + w + } + + const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0]; + + fn moved(b: [f32; 6], by: [f32; 3]) -> [f32; 6] { + std::array::from_fn(|k| b[k] + by[k % 3]) + } + + const OFF: [f32; 6] = [f32::NAN; 6]; + + #[test] + fn node_pointers_name_64_byte_nodes_past_the_descriptors_base() { + // The 64-bit form as the title uses it: base 0, the structure's + // address folded into the pointer. + let structure = 0x12_3456_7800u64; + let pointer = (structure >> 8 << 5) + (0x40 >> 3 | 5); + assert_eq!(kind(pointer), 5); + assert_eq!(node_address(0, BOX_SORT, pointer), structure + 0x40); + // The 32-bit form: the base in the descriptor. + let word0 = (structure >> 8) as u32; + let word1 = (structure >> 40) as u32 | BOX_SORT; + assert_eq!( + node_address(word0, word1, 0x1000 >> 3 | 4), + structure + 0x1000 + ); + // A base past 4 GiB of 256-byte units. + assert_eq!(node_address(0, 0x8000_0001, 8), (1 << 40) + 64); + } + + #[test] + fn halves_convert_exactly() { + assert_eq!(half_to_f32(0x3c00), 1.0); + assert_eq!(half_to_f32(0xc000), -2.0); + assert_eq!(half_to_f32(0x7c00), f32::INFINITY); + assert_eq!(half_to_f32(0x0001), 2f32.powi(-24)); + assert_eq!(half_to_f32(0x03ff), 1023.0 * 2f32.powi(-24)); + assert_eq!(half_to_f32(0x7bff), 65504.0); + assert!(half_to_f32(0x7e00).is_nan()); + assert_eq!(half_to_f32(0x8000).to_bits(), 0x8000_0000); + // Outward rounding of the test helper. + assert!(half_to_f32(f32_to_half(0.1, true)) >= 0.1); + assert!(half_to_f32(f32_to_half(0.1, false)) <= 0.1); + } + + #[test] + fn boxes_are_returned_nearest_first_and_misses_last() { + let children = [0x105, 0x20c, 0x304, 0x400]; + // Along +x from the origin: boxes at x = 30, 10, (off axis), 20. + let node = box32( + children, + [ + moved(UNIT, [30.0, 0.0, 0.0]), + moved(UNIT, [10.0, 0.0, 0.0]), + moved(UNIT, [10.0, 5.0, 0.0]), + moved(UNIT, [20.0, 0.0, 0.0]), + ], + ); + let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0); + assert_eq!(intersect(&node, 5, &ray, true), [0x20c, 0x400, 0x105, NONE]); + // Without sorting: child order, the miss in its place. + assert_eq!( + intersect(&node, 5, &ray, false), + [0x105, 0x20c, NONE, 0x400] + ); + // The extent cuts the far ones off (entered at 9, 19, 29). + let short = Ray { + extent: 19.5, + ..ray + }; + assert_eq!( + intersect(&node, 5, &short, true), + [0x20c, 0x400, NONE, NONE] + ); + // An entry exactly at the extent is no hit. + let exact = Ray { + extent: 19.0, + ..ray + }; + assert_eq!(intersect(&node, 5, &exact, true), [0x20c, NONE, NONE, NONE]); + // Backwards: nothing. + let back = Ray::new([0.0; 3], [-1.0, 0.0, 0.0], 1000.0); + assert_eq!(intersect(&node, 5, &back, true), [NONE; 4]); + } + + #[test] + fn a_ray_starting_inside_a_box_enters_it_at_its_origin() { + let node = box32( + [8, 16, NONE, NONE], + [UNIT, moved(UNIT, [3.0, 0.0, 0.0]), OFF, OFF], + ); + let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 100.0); + // Box 0 is entered at -1 (behind the origin), box 1 at 2. + assert_eq!(intersect(&node, 5, &ray, true), [8, 16, NONE, NONE]); + // Even with a tiny extent the box around the origin is a hit. + let tiny = Ray { + extent: 1e-6, + ..ray + }; + assert_eq!(intersect(&node, 5, &tiny, true), [8, NONE, NONE, NONE]); + } + + #[test] + fn axis_aligned_rays_and_origins_on_a_face_make_no_nan() { + let node = box32([8, 16, 24, 32], [UNIT, OFF, OFF, OFF]); + // Direction components of 0: the inverse is infinite. + let ray = Ray::new([-5.0, -1.0, 0.0], [1.0, 0.0, 0.0], 100.0); + assert!(ray.inverse[1].is_infinite()); + // The origin lies in the plane of the box's -y face: (-1 - -1) x inf + // would be a NaN; with the inverse held finite it is 0, and the ray + // running along the face is inside. + assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]); + // Along the +y face it is outside: the face's plane is left at 0 + // and the box is entered at 4 (as the public emulation has it). + let top = Ray::new([-5.0, 1.0, 0.0], [1.0, 0.0, 0.0], 100.0); + assert_eq!(intersect(&node, 5, &top, true), [NONE; 4]); + let outside = Ray::new([-5.0, 1.5, 0.0], [1.0, 0.0, 0.0], 100.0); + assert_eq!(intersect(&node, 5, &outside, true), [NONE; 4]); + // -0 gives -infinity. + let minus = Ray::new([-5.0, 0.5, 0.0], [1.0, -0.0, 0.0], 100.0); + assert_eq!(minus.inverse[1], f32::NEG_INFINITY); + assert_eq!(intersect(&node, 5, &minus, true), [8, NONE, NONE, NONE]); + } + + #[test] + fn a_box_switched_off_and_a_missing_child_return_none() { + let node = box32( + [8, NONE, 24, 32], + [UNIT, UNIT, [f32::NAN, -1.0, -1.0, 1.0, 1.0, 1.0], OFF], + ); + let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0); + // Child 1 is hit but is not there: its pointer is what "none" is. + assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]); + } + + #[test] + fn equal_distances_keep_child_order() { + let node = box32([8, 16, 24, 32], [UNIT; 4]); + let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0); + assert_eq!(intersect(&node, 5, &ray, true), [8, 16, 24, 32]); + } + + #[test] + fn half_float_boxes_test_like_their_widened_values() { + let boxes = [ + moved(UNIT, [30.0, 0.1, 0.0]), + moved(UNIT, [10.0, 0.0, 0.3]), + moved(UNIT, [10.0, 5.0, 0.0]), + moved(UNIT, [20.7, 0.0, 0.0]), + ]; + let children = [0x105, 0x20c, 0x304, 0x400]; + let node = box16(children, boxes); + let wide = boxes16(&node); + for (w, b) in wide.iter().zip(&boxes) { + for k in 0..3 { + assert!(w[k] <= b[k] && w[3 + k] >= b[3 + k], "rounded outward"); + } + } + let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0); + assert_eq!(intersect(&node, 4, &ray, true), [0x20c, 0x400, 0x105, NONE]); + assert_eq!( + intersect(&node, 4, &ray, true), + intersect(&box32(children, wide), 5, &ray, true) + ); + } + + /// The hit a result describes: distance, I, J, front face. + fn hit(r: [u32; 4]) -> Option<(f32, f32, f32, bool)> { + let [t, det, i, j] = r.map(f32::from_bits); + (t != f32::INFINITY).then(|| (t / det, i / det, j / det, det > 0.0)) + } + + /// Clockwise seen from the origin looking down +z in a left-handed + /// system (x right, y up): the front face. + const TRIANGLE: [[f32; 3]; 3] = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]]; + + #[test] + fn a_triangle_returns_distance_and_weights_over_one_denominator() { + let node = triangles(&TRIANGLE, 9); + let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0); + let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit"); + assert_eq!(t, 5.0); + // (0, 0) = 0.5 v0 + 0.25 v1 + 0.25 v2. + assert_eq!((i, j), (0.25, 0.25)); + assert!(front); + // Near vertex 1: I near 1. + let ray = Ray::new([1.75, -1.75, 0.0], [0.0, 0.0, 1.0], 100.0); + let (_, i, j, _) = hit(intersect(&node, 0, &ray, true)).expect("a hit"); + assert!(i > 0.85 && j < 0.1, "{i} {j}"); + // From behind: the same weights, the back face. + let ray = Ray::new([0.0, 0.0, 10.0], [0.0, 0.0, -1.0], 100.0); + let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit"); + assert_eq!((t, i, j, front), (5.0, 0.25, 0.25, false)); + // An unnormalised direction: the distance is in its units. + let ray = Ray::new([0.0; 3], [0.0, 0.0, 4.0], 100.0); + assert_eq!(hit(intersect(&node, 0, &ray, true)).unwrap().0, 1.25); + } + + #[test] + fn a_triangle_is_missed_beside_behind_and_edge_on() { + let node = triangles(&TRIANGLE, 9); + let miss = MISS.map(f32::to_bits); + // Beside it. + let ray = Ray::new([3.0, 0.0, 0.0], [0.0, 0.0, 1.0], 100.0); + assert_eq!(intersect(&node, 0, &ray, true), miss); + // It lies behind the origin. + let ray = Ray::new([0.0, 0.0, 6.0], [0.0, 0.0, 1.0], 100.0); + assert_eq!(intersect(&node, 0, &ray, true), miss); + // In its plane. + let ray = Ray::new([-5.0, 0.0, 5.0], [1.0, 0.0, 0.0], 100.0); + assert_eq!(intersect(&node, 0, &ray, true), miss); + // A triangle with no area. + let flat = triangles(&[[0.0, 0.0, 5.0], [1.0, 1.0, 5.0], [2.0, 2.0, 5.0]], 9); + let ray = Ray::new([1.0, 1.0, 0.0], [0.0, 0.0, 1.0], 100.0); + assert_eq!(intersect(&flat, 0, &ray, true), miss); + // A vertex that is not a number, a direction of zero. + let nan = triangles(&[[f32::NAN, 2.0, 5.0], TRIANGLE[1], TRIANGLE[2]], 9); + let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0); + assert_eq!(intersect(&nan, 0, &ray, true), miss); + let still = Ray::new([0.0; 3], [0.0; 3], 100.0); + assert_eq!(intersect(&node, 0, &still, true), miss); + // The extent is the program's to test: a far triangle is a hit. + let short = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 1.0); + assert!(hit(intersect(&node, 0, &short, true)).is_some()); + } + + #[test] + fn a_ray_through_a_shared_edge_misses_neither_triangle() { + // Two triangles of a quad sharing the diagonal, wound alike. + let quad = [ + [-1.0, -1.0, 4.0], + [-1.0, 1.0, 4.0], + [1.0, 1.0, 4.0], + [1.0, -1.0, 4.0], + ]; + let first = triangles(&[quad[0], quad[1], quad[2]], 9); + let second = triangles(&[quad[0], quad[2], quad[3]], 9); + // A fan of rays crossing the diagonal, some exactly on it. + for n in -40..=40 { + let x = n as f32 / 64.0; + for (ox, oy) in [(x, x), (x, x + 1.0 / 1024.0), (x + 1.0 / 1024.0, x)] { + for d in [[0.0, 0.0, 1.0], [0.125, -0.0625, 1.0], [0.25, 0.5, 2.0]] { + // Aim at (ox, oy, 4). + let s = 4.0 / d[2]; + let ray = Ray::new([ox - d[0] * s, oy - d[1] * s, 0.0], d, 100.0); + let a = hit(intersect(&first, 0, &ray, true)); + let b = hit(intersect(&second, 0, &ray, true)); + assert!( + a.is_some() || b.is_some(), + "a hole at {ox} {oy} along {d:?}" + ); + for h in [a, b].into_iter().flatten() { + assert!((h.0 - s).abs() < 1e-5 && h.3, "{h:?}"); + } + } + } + } + } + + #[test] + fn the_id_dword_says_which_vertices_the_weights_belong_to() { + // What the title's builder does with an input triangle (a, b, c) + // and an id byte: a at the vertex neither field names, b at I's, + // c at J's. + let [a, b, c] = TRIANGLE; + let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0); + let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true); + for (i, j) in [(1u32, 2u32), (2, 0), (0, 1), (2, 1), (0, 2), (1, 0)] { + let mut stored = [[0f32; 3]; 3]; + stored[(3 - i - j) as usize] = a; + stored[i as usize] = b; + stored[j as usize] = c; + let node = triangles(&stored, i | j << 2); + assert_eq!(intersect(&node, 0, &ray, true), plain, "I {i} J {j}"); + } + // The higher bits of the byte (opaque and the like) change nothing. + let node = triangles(&[a, b, c], 9 | 0x80); + assert_eq!(intersect(&node, 0, &ray, true), plain); + } + + #[test] + fn triangles_one_to_three_take_their_vertices_and_their_id_byte() { + let [a, b, c] = TRIANGLE; + let far = [50.0, 50.0, 50.0]; + let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0); + let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true); + for k in 1..4u32 { + // Triangle k's vertices 0, 1, 2 are the node's `TRIANGLE_VERTICES[k]`. + let mut vertices = [far; 5]; + let at = TRIANGLE_VERTICES[k as usize]; + vertices[at[0] as usize] = a; + vertices[at[1] as usize] = b; + vertices[at[2] as usize] = c; + // Triangle 0's byte would be malformed here; only byte k counts. + let node = triangles(&vertices, 9 << (8 * k)); + assert_eq!(intersect(&node, k, &ray, true), plain, "triangle {k}"); + } + // A pair as the title's builder stores it: the second triangle's + // own vertex at node vertex 3, named by I. + let d = [2.0, 2.0, 5.0]; + // Input triangles (a, b, c) and (a, d, b): they share a and b. + let node = triangles(&[a, b, c, d], 9 | (1 | 2 << 2) << 8); + // Triangle 1 = node vertices (1, 3, 2) = (b, d, c) as vertices 0, 1, 2. + let got = triangle_vertices(&node, 1); + assert_eq!(got, [b, d, c]); + } + + #[test] + fn instances_and_procedural_nodes_return_a_triangle_miss() { + let node = triangles(&TRIANGLE, 9); + let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0); + for k in [6, 7] { + assert_eq!(intersect(&node, k, &ray, true), MISS.map(f32::to_bits)); + } + } + + #[test] + fn the_largest_axis_and_its_sign_do_not_change_the_answer() { + // The same triangle and ray turned so the ray's largest axis is each + // of the three, forwards and backwards. Both turns are rotations, + // so the facing stays. + let turn = |v: [f32; 3], axis: usize, flip: bool| { + let mut r = v; + for _ in 0..axis { + r = [r[2], r[0], r[1]]; + } + if flip { + // Half a turn about the axis after the largest one's next. + let largest = (2 + axis) % 3; + r[largest] = -r[largest]; + r[(largest + 1) % 3] = -r[(largest + 1) % 3]; + } + r + }; + let ray = Ray::new([0.25, -0.5, 0.0], [0.0625, 0.125, 1.0], 100.0); + let base = hit(triangle(&TRIANGLE, &ray).map(f32::to_bits)).expect("a hit"); + for axis in 0..3 { + for flip in [false, true] { + let p = TRIANGLE.map(|v| turn(v, axis, flip)); + let r = Ray::new( + turn(ray.origin, axis, flip), + turn(ray.direction, axis, flip), + 100.0, + ); + let h = hit(triangle(&p, &r).map(f32::to_bits)).expect("a hit"); + assert!((h.0 - base.0).abs() < 1e-5, "{axis} {flip}: {h:?} {base:?}"); + assert!((h.1 - base.1).abs() < 1e-5 && (h.2 - base.2).abs() < 1e-5); + assert_eq!(h.3, base.3, "facing, axis {axis} flip {flip}"); + } + } + } +} diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index 8b05b12..3c346d9 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -44,6 +44,7 @@ impl SigElement { 18 => 68, 19 => 67, 20 => 69, + 28 => 23, // barycentrics 30 => 25, // cull primitive _ => 0, } @@ -114,10 +115,27 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { out } +/// The most a mesh shader's outputs may take, in bytes (D3D12). +pub(crate) const MESH_OUTPUT_LIMIT: u64 = 32 * 1024; + +/// A mesh shader's output size as the DXIL validator measures it against +/// [`MESH_OUTPUT_LIMIT`]: 4 bytes per component of every vertex element +/// and primitive element, times the maxima rounded up to multiples of 32. +pub(crate) fn mesh_output_bytes( + vertex: &[SigElement], + primitive: &[SigElement], + max_vertices: u32, + max_primitives: u32, +) -> u64 { + let scalars = |els: &[SigElement]| els.iter().map(|e| u64::from(e.cols)).sum::(); + let align = |n: u32| u64::from(n).next_multiple_of(32); + 4 * (scalars(vertex) * align(max_vertices) + scalars(primitive) * align(max_primitives)) +} + /// A resource bound by register, as `PSV0` lists it. #[derive(Debug, Clone, Copy)] pub(crate) struct Binding { - /// PSV resource type: 1 sampler, 2 CBV. + /// PSV resource type: 1 sampler, 2 CBV, 4 raw SRV, 7 raw UAV. pub kind: u32, pub space: u32, pub register: u32, @@ -126,7 +144,7 @@ pub(crate) struct Binding { } pub(crate) struct Psv<'a> { - /// PSV shader kind: 0 pixel, 1 vertex, 5 compute. + /// PSV shader kind: 0 pixel, 1 vertex, 2 geometry, 5 compute. pub stage: u8, /// Vertex: writes `SV_Position`. Pixel: writes depth. pub flag: bool, @@ -136,6 +154,9 @@ pub(crate) struct Psv<'a> { pub prims: &'a [SigElement], /// Mesh: its state and the group-shared bytes it declares. pub mesh: Option<(super::shader::Mesh, u32)>, + /// Geometry (triangles in, triangle strips out on stream 0): its + /// maximum vertex count. `flag`: writes `SV_Position`. + pub geometry: Option, pub bindings: &'a [Binding], /// Compute: thread-group size and required wave size. pub threads: [u32; 3], @@ -189,6 +210,15 @@ pub(crate) fn psv(p: &Psv) -> Vec { info[27] = mesh.topology; info[30] = p.prims.len() as u8; } + if let Some(max_vertices) = p.geometry { + // Input primitive (3: triangles), output topology (5: triangle + // strips), stream mask, position written; the vertex maximum. + info[0..4].copy_from_slice(&3u32.to_le_bytes()); + info[4..8].copy_from_slice(&5u32.to_le_bytes()); + info[8..12].copy_from_slice(&1u32.to_le_bytes()); + info[12] = u8::from(p.flag); + info[26..28].copy_from_slice(&(max_vertices as u16).to_le_bytes()); + } out.extend(info); u32s(&mut out, &[p.bindings.len() as u32]); if !p.bindings.is_empty() { diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index dabd4a4..e54767f 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -68,6 +68,16 @@ impl Host { let warp = warp || std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1"); // SAFETY: plain D3D12/DXGI calls with valid out pointers. unsafe { + // `VICTORY_D3D12_DEBUG`: the debug layer, whose messages a + // refused pipeline's error then carries. + if std::env::var_os("VICTORY_D3D12_DEBUG").is_some() { + let mut debug: Option = None; + if D3D12GetDebugInterface(&mut debug).is_ok() + && let Some(debug) = debug + { + debug.EnableDebugLayer(); + } + } let mut device: Option = None; if warp { let factory: IDXGIFactory4 = @@ -132,21 +142,23 @@ impl Host { ShaderVisibility: vis, }) .collect(); - let mut views: Vec<(u8, bool)> = stages + // By slot, then kind: 0 CBV, 1 SRV, 2 UAV. + let mut views: Vec<(u8, u8)> = stages .iter() .flat_map(|(s, _)| { - let cbvs = s.root_cbvs.iter().map(|&r| (r, false)); - cbvs.chain(s.root_srvs.iter().map(|&r| (r, true))) + let cbvs = s.root_cbvs.iter().map(|&r| (r, 0)); + let srvs = s.root_srvs.iter().map(|&r| (r, 1)); + cbvs.chain(srvs).chain(s.root_uavs.iter().map(|&r| (r, 2))) }) .collect(); views.sort_unstable(); views.dedup(); - for (slot, srv) in views { + for (slot, kind) in views { params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: if srv { - D3D12_ROOT_PARAMETER_TYPE_SRV - } else { - D3D12_ROOT_PARAMETER_TYPE_CBV + ParameterType: match kind { + 1 => D3D12_ROOT_PARAMETER_TYPE_SRV, + 2 => D3D12_ROOT_PARAMETER_TYPE_UAV, + _ => D3D12_ROOT_PARAMETER_TYPE_CBV, }, Anonymous: D3D12_ROOT_PARAMETER1_0 { Descriptor: D3D12_ROOT_DESCRIPTOR1 { @@ -233,7 +245,34 @@ impl Host { ..Default::default() }; // SAFETY: the description points at live data. - unsafe { self.device.CreateComputePipelineState(&desc) }.map_err(err) + unsafe { self.device.CreateComputePipelineState(&desc) }.map_err(|e| self.explained(e)) + } + + /// The error with the debug layer's messages since the last call, if + /// the layer is on (`VICTORY_D3D12_DEBUG`). + fn explained(&self, e: windows::core::Error) -> String { + let mut text = err(e); + let Ok(queue) = self.device.cast::() else { + return text; + }; + // SAFETY: each message is read into a buffer of the size the queue + // asks for, aligned for the message header. + unsafe { + for i in 0..queue.GetNumStoredMessages() { + let mut len = 0usize; + let _ = queue.GetMessage(i, None, &mut len); + let mut buffer = vec![0u64; len.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::(); + if queue.GetMessage(i, Some(message), &mut len).is_ok() { + let m = &*message; + let bytes = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength.saturating_sub(1)); + text.push_str(" | "); + text.push_str(&String::from_utf8_lossy(bytes)); + } + } + queue.ClearStoredMessages(); + } + text } /// A graphics pipeline from a vertex and a pixel shader, with float or @@ -255,6 +294,18 @@ impl Host { root: &ID3D12RootSignature, vs: &[u8], ps: &[u8], + ) -> Result { + self.pipeline_with_gs(root, vs, None, ps) + } + + /// As [`Host::pipeline_with`], with a geometry shader between the two + /// (the rectangle stage, `rect_list_gs`). + pub fn pipeline_with_gs( + &self, + root: &ID3D12RootSignature, + vs: &[u8], + gs: Option<&[u8]>, + ps: &[u8], ) -> Result { let inputs = sig(vs, FourCC::ISG1)?; let names: Vec = inputs @@ -287,6 +338,10 @@ impl Host { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len(), }, + GS: gs.map_or(D3D12_SHADER_BYTECODE::default(), |gs| D3D12_SHADER_BYTECODE { + pShaderBytecode: gs.as_ptr().cast(), + BytecodeLength: gs.len(), + }), SampleMask: u32::MAX, RasterizerState: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, @@ -528,6 +583,8 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), } } diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs new file mode 100644 index 0000000..78a1d99 --- /dev/null +++ b/crates/victory-shader/src/emit/intersect.rs @@ -0,0 +1,557 @@ +//! The console's ray-tracing node test, `image_bvh_intersect_ray` and +//! `image_bvh64_intersect_ray`, as inline DXIL: the host has no instruction +//! that tests one ray against one node of the title's own structures. +//! +//! [`crate::bvh`] says what the instruction computes and is the reference: +//! the code made here does the same float operations in the same order +//! (DXIL float operations carry no fast-math flags, so the host may not +//! reorder or fuse them), and the tests in `intersect_tests.rs` run it on +//! the card against the reference. +//! +//! The title's nodes are in title memory, named by address: they are read +//! through the host's copies of title memory ([`Lower::memory`]), one look +//! in its directory per node (two for a 128-byte box node). +//! +//! Shape of the code, under the instruction's lane guard: +//! +//! ```text +//! kind = pointer & 7 +//! box (4, 5): 4 child pointers; 24 box floats (kind 5) or 24 halves widened (kind 4); +//! four slab tests; the sorting network +//! triangle (0-3): the id dword, three vertices at the bytes it names; the watertight test +//! other (6, 7): a triangle miss +//! ``` +//! +//! Each lane reads only the dwords its node's kind needs: 28 for a 32-bit +//! box node, 16 for a 16-bit one, 10 for a triangle. + +use super::{Attr, Bin, Fields, Inst, Lower, Operand, Reg, Term, V, Why, flags, pred}; +use crate::bvh; +use crate::resource::BvhNodes; + +#[cfg(test)] +thread_local! { + /// The tests' stand-in for title memory ([`Lower::bvh_memory`]): a + /// heap slot holding a raw buffer, and the title address of its first + /// byte. (The card tests have no host to keep copies of title memory + /// and their directory.) + pub(in crate::emit) static TEST_MEMORY: std::cell::Cell> = + const { std::cell::Cell::new(None) }; +} + +/// Where the instruction's node is. +#[derive(Clone, Copy)] +enum NodeAt { + /// At this byte of a raw buffer of the host. + Buffer { handle: V, byte: V }, + /// In title memory: the raw view of the host copy holding the node's + /// first 64 bytes and the node's byte in it ([`Lower::bvh_memory`]), + /// and the node's address, for the second half of a 128-byte node. + Memory { handle: V, byte: V, low: V, high: V }, +} + +/// The ray operands, as floats. +struct Ray { + extent: V, + origin: [V; 3], + direction: [V; 3], + inverse: [V; 3], +} + +impl<'a> Lower<'a> { + /// `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`. + pub(super) fn bvh(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Image { + data, + addr, + rsrc, + dmask, + a16, + d16, + tfe, + lwe, + .. + } = &inst.fields + else { + unreachable!() + }; + if *a16 || *d16 || *tfe || *lwe || *dmask != 0xf { + return Err("a ray-tracing node test with 16-bit operands or a partial result"); + } + let wide = inst.name() == "image_bvh64_intersect_ray"; + // Operand VGPRs in order: the node pointer (two dwords in the + // 64-bit form), the ray's extent, origin, direction and inverse + // direction. + let mut regs = Vec::new(); + for a in addr { + if let Operand::Vector { reg, dwords } = *a { + regs.extend((0..dwords).map(|k| reg + k)); + } + } + if regs.len() != if wide { 12 } else { 11 } { + return Err("a ray-tracing node test's operands"); + } + let Operand::Vector { reg: dst, .. } = *data else { + return Err("a ray-tracing node test's result"); + }; + let site = (b, i); + let nodes = self + .x + .res + .bvh + .iter() + .find(|n| n.0 == site) + .map(|n| n.1) + .ok_or("an untracked ray-tracing structure")?; + let (sort, barycentrics) = match nodes { + BvhNodes::Resource => (true, true), + BvhNodes::Memory { word1, word3 } => ( + word1 & bvh::BOX_SORT != 0, + word3 & bvh::RETURN_BARYCENTRICS != 0, + ), + }; + if !barycentrics { + // Mode 0 returns a triangle id and a hit status in the last two + // dwords; no program of the title asks for it. + return Err("a ray-tracing structure that returns triangle ids"); + } + let guard = self.guard(b, i)?; + let mut x = Vec::with_capacity(regs.len()); + for &r in ®s { + let v = inst.read(Reg::V(r)).ok_or("an unread operand")?; + x.push(self.i32_of(v)?); + } + let pointer = x[0]; + let pointer_high = wide.then(|| x[1]); + let f: Vec = x[1 + usize::from(wide)..] + .iter() + .map(|&v| self.as_float(v)) + .collect(); + let ray = Ray { + extent: f[0], + origin: [f[1], f[2], f[3]], + direction: [f[4], f[5], f[6]], + inverse: [f[7], f[8], f[9]], + }; + let c = self.cur; + let at = match nodes { + BvhNodes::Resource => { + let src = self + .descriptors + .get(&(site, false)) + .copied() + .ok_or("an untracked ray-tracing structure")?; + let handle = self.handle(site, src, false, (11, 0))?; + // (pointer >> 3) << 6 from the buffer's start. + let (kind_bits, k3) = (self.s.m.i32(!7), self.s.m.i32(3)); + let byte = self.s.m.bin(c, Bin::And, pointer, kind_bits); + let byte = self.s.m.bin(c, Bin::Shl, byte, k3); + NodeAt::Buffer { handle, byte } + } + BvhNodes::Memory { .. } => { + let Operand::Scalar { code, .. } = *rsrc else { + return Err("a ray-tracing structure descriptor not in SGPRs"); + }; + let mut words = [pointer; 2]; + for (k, w) in words.iter_mut().enumerate() { + let v = inst + .read(Reg::S(code + k as u8)) + .ok_or("an unread operand")?; + *w = self.i32_of(v)?; + } + let (low, high) = self.bvh_address(words[0], words[1], pointer, pointer_high); + // One look for the node's copy, before the branches: a + // node is 64 bytes on 64, so its first half lies in one + // 64 KiB page whatever its kind. + let (handle, byte) = self.bvh_memory(low, high, guard); + NodeAt::Memory { + handle, + byte, + low, + high, + } + } + }; + let zero = self.s.m.i32(0); + let gate = self.begin_guarded(guard); + let head = self.cur; + let (k4, k6, k7) = (self.s.m.i32(4), self.s.m.i32(6), self.s.m.i32(7)); + let kind = self.s.m.bin(head, Bin::And, pointer, k7); + let pair = self.s.m.bin(head, Bin::And, pointer, k6); + let is_box = self.s.m.cmp(head, pred::EQ, pair, k4); + let is_triangle = self.s.m.cmp(head, pred::IULT, kind, k4); + let (box_block, leaf_block) = (self.s.m.new_block(), self.s.m.new_block()); + let (triangle_block, join) = (self.s.m.new_block(), self.s.m.new_block()); + self.s + .m + .terminate(head, Term::CondBr(is_box, box_block, leaf_block)); + self.s + .m + .terminate(leaf_block, Term::CondBr(is_triangle, triangle_block, join)); + self.cur = box_block; + let boxes = self.bvh_boxes(at, kind, &ray, sort); + let box_end = self.cur; + self.s.m.terminate(box_end, Term::Br(join)); + self.cur = triangle_block; + let triangle = self.bvh_triangle(at, kind, &ray); + let triangle_end = self.cur; + self.s.m.terminate(triangle_end, Term::Br(join)); + self.cur = join; + // Kinds 6 and 7 (an instance, a procedural primitive): not known + // what the console returns; the title's programs do not read it. + let other = bvh::MISS.map(|f| self.s.m.i32(f.to_bits())); + let i32t = self.s.t.i32; + let mut results = Vec::with_capacity(4); + for k in 0..4 { + let phi = self.s.m.phi(join, i32t); + self.s.m.set_phi( + phi, + vec![ + (boxes[k], box_end), + (triangle[k], triangle_end), + (other[k], leaf_block), + ], + ); + results.push((phi, zero)); + } + let results = self.end_guarded(gate, &results); + for (k, &r) in results.iter().enumerate() { + self.write(inst, Reg::V(dst + k as u8), r, guard); + } + Ok(()) + } + + /// Title memory at `low`/`high` for a node's bytes: the raw view of the + /// host copy holding the address and the byte in that view + /// ([`Lower::memory`]: a page the host has no copy of reads zeros and + /// is left for the host to fetch, for lanes that run). + fn bvh_memory(&mut self, low: V, high: V, guard: Option) -> (V, V) { + #[cfg(test)] + if let Some((slot, base)) = TEST_MEMORY.get() { + // The buffer at heap slot `slot` holds the bytes from title + // address `base` on; any other address reads past its end, + // which is zeros. + let c = self.cur; + let slot = self.s.m.i32(slot); + let handle = self.s.heap_handle(c, slot, false, false, (11, 0)); + let (base_low, base_high) = + (self.s.m.i32(base as u32), self.s.m.i32((base >> 32) as u32)); + let at = self.s.m.bin(c, Bin::Sub, low, base_low); + let in_low = self.s.m.cmp(c, pred::IUGE, low, base_low); + let in_high = self.s.m.cmp(c, pred::EQ, high, base_high); + let inside = self.s.m.bin(c, Bin::And, in_low, in_high); + let outside = self.s.m.i32(0xffff_ff00); + let at = self.s.m.select(c, inside, at, outside); + return (handle, at); + } + self.memory(low, high, guard) + } + + /// `count` dwords of the node from its byte `base` + `offset` (`base` + /// computed, `offset` fixed; none of the node's bytes past 127), read + /// four at a time. + fn bvh_node_words(&mut self, at: NodeAt, base: Option, offset: u32, count: u32) -> Vec { + let c = self.cur; + let (undef, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + // The second half of a 128-byte node may lie in the next 64 KiB + // page, which may be in another copy: its own look, made once. + let mut second = None; + let mut out = Vec::with_capacity(count as usize); + for start in (0..count).step_by(4) { + let n = (count - start).min(4); + let node_byte = offset + 4 * start; + let (handle, mut byte) = match at { + NodeAt::Buffer { handle, byte } => (handle, byte), + NodeAt::Memory { handle, byte, .. } if node_byte < 64 => (handle, byte), + NodeAt::Memory { low, high, .. } => *second.get_or_insert_with(|| { + let (low, high) = self.address_plus(low, high, 64); + // Every lane in this block runs the instruction. + let (handle, byte) = self.bvh_memory(low, high, None); + let k64 = self.s.m.i32(64); + (handle, self.s.m.bin(c, Bin::Sub, byte, k64)) + }), + }; + if let Some(b) = base { + byte = self.s.m.bin(c, Bin::Add, byte, b); + } + let k = self.s.m.i32(node_byte); + let byte = self.s.m.bin(c, Bin::Add, byte, k); + let mask = self.s.m.i8((1u8 << n) - 1); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[handle, byte, undef, mask, align], + ); + for k in 0..n { + let f = self.s.m.extract(c, r, k); + out.push(self.as_int(f)); + } + } + out + } + + /// The node's title address, [`bvh::node_address`]: the descriptor's + /// base (dword 0 and the low byte of dword 1, in 256-byte units) plus + /// `(pointer >> 3) << 6`. + fn bvh_address(&mut self, word0: V, word1: V, pointer: V, pointer_high: Option) -> (V, V) { + let c = self.cur; + let i64t = self.s.m.int(64); + let (zero, byte) = (self.s.m.i32(0), self.s.m.i32(0xff)); + let base_high = self.s.m.bin(c, Bin::And, word1, byte); + let base = self.join64(word0, base_high); + let k8 = self.s.m.int_const(i64t, 8); + let base = self.s.m.bin(c, Bin::Shl, base, k8); + let p = self.join64(pointer, pointer_high.unwrap_or(zero)); + let (k3, k6) = (self.s.m.int_const(i64t, 3), self.s.m.int_const(i64t, 6)); + let p = self.s.m.bin(c, Bin::LShr, p, k3); + let p = self.s.m.bin(c, Bin::Shl, p, k6); + let a = self.s.m.bin(c, Bin::Add, base, p); + self.s.flags |= flags::INT64; + self.split64(a) + } + + /// The box test ([`bvh::boxes`]): four result dwords. Starts in the + /// current block and leaves `self.cur` at the block it ends in. + fn bvh_boxes(&mut self, at: NodeAt, kind: V, ray: &Ray, sort: bool) -> [V; 4] { + let head = self.cur; + let children = self.bvh_node_words(at, None, 0, 4); + let k5 = self.s.m.i32(5); + let wide = self.s.m.cmp(head, pred::EQ, kind, k5); + let (wide_block, half_block) = (self.s.m.new_block(), self.s.m.new_block()); + let join = self.s.m.new_block(); + self.s + .m + .terminate(head, Term::CondBr(wide, wide_block, half_block)); + // 32-bit floats: 24 dwords from byte 16. + self.cur = wide_block; + let k16 = self.s.m.i32(16); + let words = self.bvh_node_words(at, None, 16, 24); + let floats: Vec = words.iter().map(|&w| self.as_float(w)).collect(); + self.s.m.terminate(wide_block, Term::Br(join)); + // 16-bit floats: 24 halves in 12 dwords from byte 16, the low half + // of a dword first. + self.cur = half_block; + let words = self.bvh_node_words(at, None, 16, 12); + let f32t = self.s.t.f32; + let mut halves = Vec::with_capacity(24); + for n in 0..24 { + let mut h = words[n / 2]; + if n % 2 == 1 { + h = self.s.m.bin(half_block, Bin::LShr, h, k16); + } + // The conversion reads the low 16 bits. + halves.push(self.s.op( + half_block, + "legacyF16ToF32", + Attr::ReadNone, + f32t, + 131, + &[h], + )); + } + self.s.m.terminate(half_block, Term::Br(join)); + self.cur = join; + let mut coords = Vec::with_capacity(24); + for n in 0..24 { + let phi = self.s.m.phi(join, f32t); + self.s + .m + .set_phi(phi, vec![(floats[n], wide_block), (halves[n], half_block)]); + coords.push(phi); + } + // The inverse direction held finite ([`bvh::boxes`]). + let (most, least) = ( + self.s.m.f32(f32::MAX.to_bits()), + self.s.m.f32((-f32::MAX).to_bits()), + ); + let inverse = ray.inverse.map(|x| { + let x = self.binary(35, x, least); + self.binary(36, x, most) + }); + let c = join; + let (none, infinity, fzero) = ( + self.s.m.i32(bvh::NONE), + self.s.m.f32(f32::INFINITY.to_bits()), + self.s.m.f32(0), + ); + let mut ids = [none; 4]; + let mut distances = [infinity; 4]; + for n in 0..4 { + let bx = &coords[6 * n..6 * n + 6]; + let (mut near, mut far) = ([fzero; 3], [fzero; 3]); + for a in 0..3 { + let low = self.s.m.bin(c, Bin::Sub, bx[a], ray.origin[a]); + let low = self.s.m.bin(c, Bin::Mul, low, inverse[a]); + let high = self.s.m.bin(c, Bin::Sub, bx[3 + a], ray.origin[a]); + let high = self.s.m.bin(c, Bin::Mul, high, inverse[a]); + near[a] = self.binary(36, low, high); + far[a] = self.binary(35, low, high); + } + let enter = self.binary(35, near[0], near[1]); + let enter = self.binary(35, enter, near[2]); + let leave = self.binary(36, far[0], far[1]); + let leave = self.binary(36, leave, far[2]); + let from = self.binary(35, enter, fzero); + // Ordered compares: a NaN anywhere is a miss. + let through = self.s.m.cmp(c, pred::OGE, leave, from); + let before = self.s.m.cmp(c, pred::OLT, enter, ray.extent); + let off = self.is_nan_f32(bx[0]); + let on = self.s.m.bool(true); + let on = self.s.m.bin(c, Bin::Xor, off, on); + let hit = self.s.m.bin(c, Bin::And, through, before); + let hit = self.s.m.bin(c, Bin::And, hit, on); + ids[n] = self.s.m.select(c, hit, children[n], none); + distances[n] = self.s.m.select(c, hit, enter, infinity); + } + if sort { + for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] { + let swap = self.s.m.cmp(c, pred::OLT, distances[b], distances[a]); + let (da, db) = (distances[a], distances[b]); + distances[a] = self.s.m.select(c, swap, db, da); + distances[b] = self.s.m.select(c, swap, da, db); + let (ia, ib) = (ids[a], ids[b]); + ids[a] = self.s.m.select(c, swap, ib, ia); + ids[b] = self.s.m.select(c, swap, ia, ib); + } + } + ids + } + + /// The triangle test ([`bvh::triangle`] of [`bvh::triangle_vertices`]): + /// four result dwords, made in the current block. + fn bvh_triangle(&mut self, at: NodeAt, kind: V, ray: &Ray) -> [V; 4] { + let c = self.cur; + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + // The triangle's byte of the dword at byte 60: which of its + // vertices barycentric I and J weigh. + let id = self.bvh_node_words(at, None, 60, 1)[0]; + let (k2, k3, k12, k15) = (k(self, 2), k(self, 3), k(self, 12), k(self, 15)); + let shift = self.s.m.bin(c, Bin::Shl, kind, k3); + let id = self.s.m.bin(c, Bin::LShr, id, shift); + let i = self.s.m.bin(c, Bin::And, id, k3); + let j = self.s.m.bin(c, Bin::LShr, id, k2); + let j = self.s.m.bin(c, Bin::And, j, k3); + let first = self.s.m.bin(c, Bin::Sub, k3, i); + let first = self.s.m.bin(c, Bin::Sub, first, j); + let first = self.s.m.bin(c, Bin::And, first, k3); + // The node's vertices the triangle is made of, four bits each. + let (k0, k1) = (k(self, 0), k(self, 1)); + let maps: [V; 4] = std::array::from_fn(|n| k(self, bvh::vertex_map(n as u32))); + let (is0, is1, is2) = ( + self.s.m.cmp(c, pred::EQ, kind, k0), + self.s.m.cmp(c, pred::EQ, kind, k1), + self.s.m.cmp(c, pred::EQ, kind, k2), + ); + let map = self.s.m.select(c, is2, maps[2], maps[3]); + let map = self.s.m.select(c, is1, maps[1], map); + let map = self.s.m.select(c, is0, maps[0], map); + let mut p = Vec::with_capacity(3); + for n in [first, i, j] { + let nibble = self.s.m.bin(c, Bin::Shl, n, k2); + let vertex = self.s.m.bin(c, Bin::LShr, map, nibble); + let vertex = self.s.m.bin(c, Bin::And, vertex, k15); + let byte = self.s.m.bin(c, Bin::Mul, vertex, k12); + let words = self.bvh_node_words(at, Some(byte), 0, 3); + // Relative to the ray's origin. + let r: Vec = (0..3) + .map(|a| { + let f = self.as_float(words[a]); + self.s.m.bin(c, Bin::Sub, f, ray.origin[a]) + }) + .collect(); + p.push([r[0], r[1], r[2]]); + } + // The ray's largest axis z, and x and y after it in an order that + // keeps the winding. + let fzero = self.s.m.f32(0); + let size = ray.direction.map(|d| self.unary(6, d)); + let xy = self.s.m.cmp(c, pred::OGE, size[0], size[1]); + let xz = self.s.m.cmp(c, pred::OGE, size[0], size[2]); + let yz = self.s.m.cmp(c, pred::OGE, size[1], size[2]); + let z0 = self.s.m.bin(c, Bin::And, xy, xz); + let on = self.s.m.bool(true); + let not_xy = self.s.m.bin(c, Bin::Xor, xy, on); + let z1 = self.s.m.bin(c, Bin::And, not_xy, yz); + // Component (kz + n) % 3 of `q`. + let pick = |l: &mut Self, q: [V; 3], n: usize| { + let rest = l.s.m.select(c, z1, q[(1 + n) % 3], q[(2 + n) % 3]); + l.s.m.select(c, z0, q[n % 3], rest) + }; + let dz = pick(self, ray.direction, 0); + let backwards = self.s.m.cmp(c, pred::OLT, dz, fzero); + // (x, y, z) of `q`: the two after the largest axis, swapped for a + // ray that runs backwards along it. + let axes = |l: &mut Self, q: [V; 3]| { + let (x, y) = (pick(l, q, 1), pick(l, q, 2)); + [ + l.s.m.select(c, backwards, y, x), + l.s.m.select(c, backwards, x, y), + pick(l, q, 0), + ] + }; + let d = axes(self, ray.direction); + let sz = pick(self, ray.inverse, 0); + let sx = self.s.m.bin(c, Bin::Mul, d[0], sz); + let sy = self.s.m.bin(c, Bin::Mul, d[1], sz); + let mut sheared = Vec::with_capacity(3); + for r in p { + let r = axes(self, r); + let x = self.s.m.bin(c, Bin::Mul, sx, r[2]); + let x = self.s.m.bin(c, Bin::Sub, r[0], x); + let y = self.s.m.bin(c, Bin::Mul, sy, r[2]); + let y = self.s.m.bin(c, Bin::Sub, r[1], y); + let z = self.s.m.bin(c, Bin::Mul, sz, r[2]); + sheared.push((x, y, z)); + } + let [(ax, ay, az), (bx, by, bz), (cx, cy, cz)] = sheared[..] else { + unreachable!() + }; + // p * q - r * s. + let cross = |l: &mut Self, p: V, q: V, r: V, s: V| { + let a = l.s.m.bin(c, Bin::Mul, p, q); + let b = l.s.m.bin(c, Bin::Mul, r, s); + l.s.m.bin(c, Bin::Sub, a, b) + }; + let u = cross(self, cx, by, cy, bx); + let v = cross(self, ax, cy, ay, cx); + let w = cross(self, bx, ay, by, ax); + let any = |l: &mut Self, p: u8| { + let a = l.s.m.cmp(c, p, u, fzero); + let b = l.s.m.cmp(c, p, v, fzero); + let d = l.s.m.cmp(c, p, w, fzero); + let a = l.s.m.bin(c, Bin::Or, a, b); + l.s.m.bin(c, Bin::Or, a, d) + }; + let behind = any(self, pred::OLT); + let before = any(self, pred::OGT); + let outside = self.s.m.bin(c, Bin::And, behind, before); + let inside = self.s.m.bin(c, Bin::Xor, outside, on); + let det = self.s.m.bin(c, Bin::Add, v, w); + let det = self.s.m.bin(c, Bin::Add, u, det); + let t = self.s.m.bin(c, Bin::Mul, u, az); + let t2 = self.s.m.bin(c, Bin::Mul, v, bz); + let t = self.s.m.bin(c, Bin::Add, t, t2); + let t2 = self.s.m.bin(c, Bin::Mul, w, cz); + let t = self.s.m.bin(c, Bin::Add, t, t2); + // The distance is not negative: the numerator has the + // denominator's sign (or is 0). Ordered compares: a denominator + // of 0 or a NaN is a miss. + let front = self.s.m.cmp(c, pred::OGT, det, fzero); + let front_ahead = self.s.m.cmp(c, pred::OGE, t, fzero); + let front = self.s.m.bin(c, Bin::And, front, front_ahead); + let back = self.s.m.cmp(c, pred::OLT, det, fzero); + let back_ahead = self.s.m.cmp(c, pred::OLE, t, fzero); + let back = self.s.m.bin(c, Bin::And, back, back_ahead); + let ahead = self.s.m.bin(c, Bin::Or, front, back); + let hit = self.s.m.bin(c, Bin::And, inside, ahead); + let miss = bvh::MISS.map(|f| self.s.m.f32(f.to_bits())); + let out = [t, det, v, w]; + std::array::from_fn(|n| { + let f = self.s.m.select(c, hit, out[n], miss[n]); + self.as_int(f) + }) + } +} diff --git a/crates/victory-shader/src/emit/intersect_tests.rs b/crates/victory-shader/src/emit/intersect_tests.rs new file mode 100644 index 0000000..0266579 --- /dev/null +++ b/crates/victory-shader/src/emit/intersect_tests.rs @@ -0,0 +1,690 @@ +//! The ray-tracing node test end to end: a synthetic compute program that +//! runs `image_bvh64_intersect_ray` (or the 32-bit form) once per thread, +//! lowered to DXIL, validated by `dxil.dll` when present, run on the host +//! GPU and WARP, and compared dword for dword with the CPU reference +//! ([`crate::bvh`]). +//! +//! The nodes are in a raw buffer. Two ways to name it are run: the +//! buffer's descriptor from the program's table (a resource of the host, +//! [`crate::resource::BvhNodes::Resource`]), and the title's way, a +//! descriptor of numbers over title memory with the structure's address in +//! the node pointer or in the descriptor. These tests have no host that +//! keeps copies of title memory and their directory, so for the second +//! they put a stand-in under the node reader +//! (`lower::intersect::TEST_MEMORY`); without it the same program reads +//! through the directory, which is only checked to lower and validate. + +use super::host::{Dispatch, Host, Root, Stride, View}; +use super::lower::intersect::TEST_MEMORY; +use super::{HostShader, lower, validator}; +use crate::bvh::{self, Ray, tests as nodes}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::resource::BvhNodes; +use crate::{ShaderError, io, ir, resource, structure}; + +/// Threads of one group, each with its own record. +const THREADS: u32 = 32; +/// Bytes of a thread's record: the node pointer (two dwords), the ray's +/// extent, origin, direction and inverse direction, and whether the +/// thread runs the instruction. +const RECORD: u32 = 64; +/// Where the nodes start in the buffer. +const NODES: u32 = THREADS * RECORD; +/// What the result registers hold before the instruction. +const BEFORE: [u32; 4] = [1, 2, 3, 4]; + +/// How the program names the nodes' memory. +#[derive(Clone, Copy, PartialEq)] +enum Descriptor { + /// The buffer's descriptor from the table. + Table, + /// Numbers, as the title builds it: dwords 0 and 1 (the base address + /// in 256-byte units and the box sorting bit); the size and the rest of + /// the flags as the title sets them. + Numbers(u32, u32), +} + +/// The descriptor the title builds for the 64-bit form: the whole address +/// space, sorted boxes, barycentrics returned. +const WHOLE: Descriptor = Descriptor::Numbers(0, bvh::BOX_SORT); + +/// The program: per thread, the record's twelve operand dwords in v1-v12, +/// the instruction's result in v13-v16 (under a lane mask of the threads +/// whose record says so), stored to the UAV at 16 bytes a thread. +fn program(wide: bool, descriptor: Descriptor) -> Vec { + let mut w = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 + 0xF408_0302, + 0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20 + 0x3428_0086, // v_lshlrev_b32 v20, 6, v0 + 0xE038_1000, + 0x8002_0114, // buffer_load_dwordx4 v[1:4], v20, s[8:11], 0 offen + 0xE038_1010, + 0x8002_0514, // buffer_load_dwordx4 v[5:8], v20, s[8:11], 0 offen offset:16 + 0xE038_1020, + 0x8002_0914, // buffer_load_dwordx4 v[9:12], v20, s[8:11], 0 offen offset:32 + 0xE030_1030, + 0x8002_1114, // buffer_load_dword v17, v20, s[8:11], 0 offen offset:48 + ]; + for k in 0..4u32 { + // v_mov_b32 v13+k, 1+k + w.push(0x7E00_0200 | (13 + k) << 17 | (0x81 + k)); + } + let rsrc = match descriptor { + Descriptor::Table => 8, + Descriptor::Numbers(word0, word1) => { + // s_mov_b32 s24, word0 + w.extend([0xBE98_03FF, word0]); + if word1 == bvh::BOX_SORT { + // As the title makes it. + w.push(0xBE99_0B81); // s_brev_b32 s25, 1 + } else { + w.extend([0xBE99_03FF, word1]); // s_mov_b32 s25, word1 + } + w.extend([ + 0xBE9A_03C1, // s_mov_b32 s26, -1 + 0xBE9B_03FF, + 0x8900_03FF, // s_mov_b32 s27, 0x890003ff + ]); + 24 + } + }; + w.extend([ + 0xBE94_037E, // s_mov_b32 s20, exec_lo + 0x7DAA_2280, // v_cmpx_ne_u32 exec_lo, 0, v17 + ]); + let first = 0x0000_0D01 | (rsrc >> 2) << 16; + if wide { + // image_bvh64_intersect_ray v[13:16], [v1 .. v12], s[rsrc:rsrc+3] + w.extend([0xF19C_9F07, first, 0x0504_0302, 0x0908_0706, 0x000C_0B0A]); + } else { + // image_bvh_intersect_ray v[13:16], [v1, v3 .. v12], s[rsrc:rsrc+3] + w.extend([0xF198_9F07, first, 0x0605_0403, 0x0A09_0807, 0x0000_0C0B]); + } + w.extend([ + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0x342A_0084, // v_lshlrev_b32 v21, 4, v0 + 0xE078_1000, + 0x8003_0D15, // buffer_store_dwordx4 v[13:16], v21, s[12:15], 0 offen + 0xBF81_0000, // s_endpgm + ]); + w +} + +fn native(words: &[u32]) -> NativeProgram { + let table = |kind, at| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: at, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }; + NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 22, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![table(ResourceType::Srv, 0), table(ResourceType::Uav, 8)], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [THREADS, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } +} + +/// Lowers the program; the DXIL is validated when the validator is there. +fn build( + wide: bool, + descriptor: Descriptor, +) -> Result<(HostShader, resource::Resources), ShaderError> { + let native = native(&program(wide, descriptor)); + 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 lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + })?; + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views.clone(), + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + Ok((shader, res)) +} + +/// One thread's test: a node (by its index in the node list), the kind its +/// pointer carries, and the ray; `None` leaves the thread masked out. +type Case = Option<(usize, u32, Ray)>; + +/// The scene: node dwords (a 32-bit box node takes 32, the others 16) and +/// where each node starts, in dwords from the first node. +struct Scene { + words: Vec, + starts: Vec, +} + +impl Scene { + fn new() -> Self { + Self { + words: Vec::new(), + starts: Vec::new(), + } + } + + /// Adds a node of `dwords` (16 or 32) and returns its index. + fn add(&mut self, node: [u32; 28], dwords: usize) -> usize { + self.starts.push(self.words.len()); + let mut padded = [0u32; 32]; + padded[..28].copy_from_slice(&node); + // Bytes the instruction must not read as part of the node: what + // follows a 64-byte node, and a box node's last 16 bytes. + for w in padded.iter_mut().skip(if dwords == 16 { 16 } else { 28 }) { + *w = 0x7fc0_dead; + } + self.words.extend(&padded[..dwords]); + self.starts.len() - 1 + } + + /// The pointer of node `n` with `kind`, counted from the first node. + fn pointer(&self, n: usize, kind: u32) -> u32 { + (4 * self.starts[n] as u32) >> 3 | kind + } + + /// What the instruction reads of node `n`. + fn node(&self, n: usize) -> [u32; 28] { + std::array::from_fn(|k| self.words.get(self.starts[n] + k).copied().unwrap_or(0)) + } +} + +/// A small generator of repeatable numbers. +struct Numbers(u64); + +impl Numbers { + fn next(&mut self) -> u32 { + self.0 = self + .0 + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (self.0 >> 33) as u32 + } + + /// A float in -1..1 in steps of 1/4096 (exactly representable). + fn unit(&mut self) -> f32 { + (self.next() % 8193) as f32 / 4096.0 - 1.0 + } + + fn vector(&mut self, scale: f32) -> [f32; 3] { + [ + self.unit() * scale, + self.unit() * scale, + self.unit() * scale, + ] + } +} + +/// The scene and batches of cases over it. +fn scene() -> (Scene, Vec>) { + let mut s = Scene::new(); + let mut g = Numbers(0x5eed); + const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0]; + let moved = + |b: [f32; 6], by: [f32; 3]| -> [f32; 6] { std::array::from_fn(|k| b[k] + by[k % 3]) }; + let off = [f32::NAN; 6]; + let mut box_nodes = Vec::new(); + // The boxes of the reference's own tests, in both widths. + let lined = [ + moved(UNIT, [30.0, 0.0, 0.0]), + moved(UNIT, [10.0, 0.0, 0.0]), + moved(UNIT, [10.0, 5.0, 0.0]), + moved(UNIT, [20.0, 0.0, 0.0]), + ]; + let ids = [0x105, 0x20c, 0x304, 0x400]; + box_nodes.push((s.add(nodes::box32(ids, lined), 32), 5)); + box_nodes.push((s.add(nodes::box16(ids, lined), 16), 4)); + // Boxes around the origin, one switched off, one child missing. + let around = [ + UNIT, + moved(UNIT, [0.5, 0.5, 0.5]), + off, + [-4.0, -0.25, -0.25, 4.0, 0.25, 0.25], + ]; + let ids2 = [8, bvh::NONE, 24, 0x1fff_fffc]; + box_nodes.push((s.add(nodes::box32(ids2, around), 32), 5)); + box_nodes.push((s.add(nodes::box16(ids2, around), 16), 4)); + // Random boxes. + for n in 0..6 { + let boxes: [[f32; 6]; 4] = std::array::from_fn(|_| { + let (c, h) = (g.vector(8.0), g.vector(2.0).map(f32::abs)); + std::array::from_fn(|k| c[k % 3] + if k < 3 { -h[k] } else { h[k - 3] }) + }); + let ids: [u32; 4] = std::array::from_fn(|k| 0x1000 * (n + 1) + 8 * k as u32 + 5); + if n % 2 == 0 { + box_nodes.push((s.add(nodes::box32(ids, boxes), 32), 5)); + } else { + box_nodes.push((s.add(nodes::box16(ids, boxes), 16), 4)); + } + } + // Triangles: one of the reference's tests, a pair as the title's + // builder stores it, all four triangles of a full node with turned + // ids, random ones. + let mut triangle_nodes = Vec::new(); + let front = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]]; + triangle_nodes.push((s.add(nodes::triangles(&front, 9), 16), 0)); + let pair = s.add( + nodes::triangles( + &[front[0], front[1], front[2], [2.0, 2.0, 5.0]], + 9 | 0x80 | 6 << 8, + ), + 16, + ); + triangle_nodes.extend([(pair, 0), (pair, 1)]); + let five = [ + [-3.0, -1.0, 6.0], + [-1.0, 2.0, 6.5], + [1.0, -1.0, 6.0], + [3.0, 2.0, 6.5], + [5.0, -1.0, 7.0], + ]; + // I and J per triangle: (1, 2), (2, 0), (0, 1), (1, 2). + let full = s.add(nodes::triangles(&five, 9 | 2 << 8 | 4 << 16 | 9 << 24), 16); + triangle_nodes.extend((0..4).map(|k| (full, k))); + for _ in 0..5 { + let c = g.vector(6.0); + let v: [[f32; 3]; 3] = std::array::from_fn(|_| { + let d = g.vector(3.0); + [c[0] + d[0], c[1] + d[1], c[2] + d[2]] + }); + triangle_nodes.push((s.add(nodes::triangles(&v, 9), 16), 0)); + } + let mut cases: Vec = Vec::new(); + // Rays of the reference's tests against the lined-up boxes. + for &(n, kind) in &box_nodes[..2] { + for (origin, direction, extent) in [ + ([0.0; 3], [1.0, 0.0, 0.0], 1000.0), + ([0.0; 3], [1.0, 0.0, 0.0], 19.5), + ([0.0; 3], [1.0, 0.0, 0.0], 19.0), + ([0.0; 3], [-1.0, 0.0, 0.0], 1000.0), + ([40.0, 0.0, 0.0], [-2.0, 0.0, 0.0], 1000.0), + ([0.0, -1.0, 0.0], [1.0, 0.0, 0.0], 1000.0), + ([0.0, 1.0, 0.0], [1.0, 0.0, 0.0], 1000.0), + ([0.0, 0.5, 0.25], [1.0, -0.0, 0.0], 1000.0), + ([0.0; 3], [0.0; 3], 1000.0), + ] { + cases.push(Some((n, kind, Ray::new(origin, direction, extent)))); + } + } + // Random rays at every box node, half of them aimed at a box. + for &(n, kind) in &box_nodes { + let words = s.node(n); + let boxes = if kind == 5 { + bvh::boxes32(&words) + } else { + bvh::boxes16(&words) + }; + for k in 0..12 { + let origin = g.vector(12.0); + let direction = if k % 2 == 0 { + let b = boxes[(k / 2) % 4]; + if b[0].is_nan() { + g.vector(1.0) + } else { + std::array::from_fn(|a| (b[a] + b[3 + a]) / 2.0 - origin[a] + g.unit() / 2.0) + } + } else { + g.vector(1.0) + }; + let extent = if k % 3 == 0 { 6.0 } else { 100.0 }; + cases.push(Some((n, kind, Ray::new(origin, direction, extent)))); + } + } + // Rays at every triangle: aimed inside, at an edge, at a vertex, past + // it, from both sides, along each axis. + for &(n, kind) in &triangle_nodes { + let p = bvh::triangle_vertices(&s.node(n), kind); + let at = |w: [f32; 3]| -> [f32; 3] { + std::array::from_fn(|a| w[0] * p[0][a] + w[1] * p[1][a] + w[2] * p[2][a]) + }; + for (k, w) in [ + [0.5, 0.25, 0.25], + [0.125, 0.75, 0.125], + [0.5, 0.5, 0.0], + [0.0, 0.5, 0.5], + [1.0, 0.0, 0.0], + [0.75, 0.75, -0.5], + [-0.25, 0.5, 0.75], + [0.25, 0.25, 0.5], + ] + .into_iter() + .enumerate() + { + let target = at(w); + let origin = if k % 2 == 0 { [0.0; 3] } else { g.vector(16.0) }; + let mut direction: [f32; 3] = std::array::from_fn(|a| target[a] - origin[a]); + if k == 7 { + // The triangle lies behind. + direction = direction.map(|d| -d); + } + cases.push(Some((n, kind, Ray::new(origin, direction, 100.0)))); + } + for axis in 0..3 { + for sign in [1.0f32, -1.0] { + let target = at([0.25, 0.5, 0.25]); + let mut origin = target; + origin[axis] -= 8.0 * sign; + let mut direction = [0.0; 3]; + direction[axis] = sign; + cases.push(Some((n, kind, Ray::new(origin, direction, 100.0)))); + } + } + } + // Kinds the instruction does not read, and threads masked out. + let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0); + cases.extend([ + Some((triangle_nodes[0].0, 6, ray)), + Some((triangle_nodes[0].0, 7, ray)), + None, + Some(( + box_nodes[0].0, + 5, + Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0), + )), + None, + ]); + let batches = cases + .chunks(THREADS as usize) + .map(<[Case]>::to_vec) + .collect(); + (s, batches) +} + +/// The buffer for one batch: the threads' records, then the nodes. Node +/// pointers count from `base` before the first node, in bytes. +fn buffer(scene: &Scene, batch: &[Case], base: u64) -> Vec { + let mut data = vec![0u32; (NODES / 4) as usize]; + for (t, case) in batch.iter().enumerate() { + let Some((n, kind, ray)) = case else { continue }; + let r = &mut data[t * (RECORD / 4) as usize..][..13]; + let pointer = (base >> 3) + u64::from(scene.pointer(*n, *kind)); + (r[0], r[1]) = (pointer as u32, (pointer >> 32) as u32); + r[2] = ray.extent.to_bits(); + for a in 0..3 { + r[3 + a] = ray.origin[a].to_bits(); + r[6 + a] = ray.direction[a].to_bits(); + r[9 + a] = ray.inverse[a].to_bits(); + } + r[12] = 1; + } + data.extend(&scene.words); + data +} + +fn expected(scene: &Scene, case: &Case, sort: bool) -> [u32; 4] { + match case { + Some((n, kind, ray)) => bvh::intersect(&scene.node(*n), *kind, ray, sort), + None => BEFORE, + } +} + +/// Sets the tests' title memory for this thread until dropped. +struct Memory; + +impl Memory { + fn at(base: u64) -> Self { + // Heap slot 0: the buffer of records and nodes. + TEST_MEMORY.set(Some((0, base))); + Self + } +} + +impl Drop for Memory { + fn drop(&mut self) { + TEST_MEMORY.set(None); + } +} + +/// Runs every batch on the hardware adapter and WARP and compares with +/// the reference. `pointers` is what node pointers count from, in bytes +/// before the first node. +fn run(wide: bool, descriptor: Descriptor, pointers: u64, sort: bool) { + let (shader, res) = build(wide, descriptor).expect("the program lowers"); + assert_eq!(res.bvh.len(), 1); + let (scene, batches) = scene(); + // The reference must see a bit of everything, or the comparison + // proves little. + let all: Vec<&Case> = batches.iter().flatten().collect(); + let results: Vec<[u32; 4]> = all.iter().map(|c| expected(&scene, c, sort)).collect(); + let boxes = |hits: usize| { + all.iter() + .zip(&results) + .filter(|(c, r)| { + matches!(c, Some((_, 4 | 5, _))) + && r.iter().filter(|&&x| x != bvh::NONE).count() == hits + }) + .count() + }; + let triangles = |hit: bool| { + all.iter() + .zip(&results) + .filter(|(c, r)| { + matches!(c, Some((_, 0..=3, _))) && (r[0] != f32::INFINITY.to_bits()) == hit + }) + .count() + }; + assert!( + boxes(0) > 5 && boxes(1) > 5 && boxes(2) > 5 && boxes(3) > 0, + "box cases" + ); + assert!( + triangles(true) > 30 && triangles(false) > 30, + "triangle cases" + ); + // Sorting must matter to some case, or the unsorted run proves nothing. + assert!( + all.iter() + .any(|c| expected(&scene, c, true) != expected(&scene, c, false)), + "no case tells sorted from unsorted" + ); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + for (b, batch) in batches.iter().enumerate() { + let data = buffer(&scene, batch, pointers); + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(vec![0; 5]))], + views: &[ + View::Buffer { + data: &data, + stride: Stride::Raw, + }, + View::RawUav(4 * THREADS), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + for t in 0..THREADS as usize { + let case = batch.get(t).copied().flatten(); + let want = match batch.get(t) { + Some(c) => expected(&scene, c, sort), + // A thread past the batch: its record is zeros, so it + // is masked out. + None => BEFORE, + }; + let got = &out[0][4 * t..4 * t + 4]; + assert_eq!( + got, + want, + "{label}, batch {b} thread {t}: {case:x?}\n got {:x?} = {:?}\nwant {:x?} = {:?}", + got, + got.iter().map(|&x| f32::from_bits(x)).collect::>(), + want, + want.map(f32::from_bits), + ); + } + } + ran += 1; + } + assert!(ran > 0, "no SM 6.6 device available"); +} + +#[test] +fn the_64_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() { + // Pointers count from the buffer's start. + run(true, Descriptor::Table, u64::from(NODES), true); + assert_eq!( + build(true, Descriptor::Table).unwrap().1.bvh[0].1, + BvhNodes::Resource + ); +} + +#[test] +fn the_32_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() { + run(false, Descriptor::Table, u64::from(NODES), true); +} + +/// Where the tests' title memory puts the buffer: past 4 GiB, on 256 bytes. +const BASE: u64 = 0x12_3456_7800; + +#[test] +fn the_64_bit_node_test_over_title_memory_matches_the_reference_on_the_card() { + // The title's way: one descriptor for all of memory, the structure's + // address folded into a 64-bit pointer. + let _memory = Memory::at(BASE); + run(true, WHOLE, BASE + u64::from(NODES), true); +} + +#[test] +fn the_32_bit_node_test_over_title_memory_matches_the_reference_on_the_card() { + // The title's other way: the structure's address in the descriptor + // (in 256-byte units, 40 bits), a 32-bit pointer from there. Here with + // an address past 2^40 bytes, and without box sorting. + let base = 0x312_3456_7800u64; + let structure = base + u64::from(NODES); + let _memory = Memory::at(base); + let descriptor = Descriptor::Numbers((structure >> 8) as u32, (structure >> 40) as u32); + run(false, descriptor, 0, false); + // And sorted. + let descriptor = Descriptor::Numbers( + (structure >> 8) as u32, + (structure >> 40) as u32 | bvh::BOX_SORT, + ); + run(false, descriptor, 0, true); +} + +#[test] +fn a_descriptor_of_numbers_is_title_memory_read_through_the_directory() { + for wide in [true, false] { + let native = native(&program(wide, WHOLE)); + 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)).expect("tracked"); + // The flags the title sets: sorted boxes, barycentrics, a + // ray-tracing structure. No resource is taken for it: the buffer + // loads' and the store's descriptors are all there is. + assert_eq!(res.bvh.len(), 1); + assert_eq!( + res.bvh[0].1, + BvhNodes::Memory { + word1: 0x8000_0000, + word3: 0x8900_03ff + } + ); + assert_eq!(res.descriptors.len(), 5); + // Without the tests' stand-in the nodes are read as the title's + // programs will read them: through the host's directory of title + // memory. The program lowers and validates, and asks the host for + // the directory and for the list of pages it found no copy of. + let (shader, _) = build(wide, WHOLE).expect("lowers through the directory"); + assert!(shader.root_srvs.contains(&super::SLOT_MEMORY)); + assert!(shader.root_uavs.contains(&super::SLOT_FAULTS)); + } +} + +#[test] +fn a_structure_that_returns_triangle_ids_is_refused_by_name() { + // Triangle return mode 0 (bit 24 of dword 3 clear): the last two + // result dwords would be a triangle id and a hit status. + let mut words = program(true, WHOLE); + let flags = words.iter().position(|&w| w == 0x8900_03FF).unwrap(); + words[flags] = 0x8800_03FF; + let native = native(&words); + 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)).expect("tracked"); + let io = io::raise(&p, &native).expect("io::raise"); + let r = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + match r { + Err(ShaderError::Unsupported { what, .. }) => { + assert_eq!(what, "a ray-tracing structure that returns triangle ids"); + } + other => panic!("{:?}", other.map(|_| ())), + } +} diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..0643fa9 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -9,7 +9,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use super::UserData; -use super::bitcode::{Attr, Bin, Cast, Term, V, pred}; +use super::bitcode::{Attr, Bin, Cast, Rmw, Term, V, pred}; use super::container::SigElement; use super::shader::{Shader, flags}; use crate::ShaderError; @@ -17,11 +17,30 @@ use crate::gfx10::{Dpp, Fields, NULL, Operand}; use crate::io::{Barycentric, Export, Input, Interp, Io, Target}; use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource}; -use crate::resource::{Address, CODE, Resources, Role, Site, Source}; +use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source}; use crate::structure::{Atom, Bool, LaneExit, Structured}; +/// The ray-tracing node test (`image_bvh_intersect_ray`), a child module so +/// it shares the emitter's state. +#[path = "intersect.rs"] +pub(super) mod intersect; + type Why = &'static str; +/// How an interpolation evaluates an input channel. +#[derive(Debug, Clone, Copy)] +enum Eval { + /// Loaded with this DXIL interpolation mode (1: constant, P0). + Mode(u8), + /// From the vertex values of a constant element: P0 when `p0`, plus + /// i (P1 - P0), plus j (P2 - P0), weights as floats. + Weights { + p0: bool, + i: Option, + j: Option, + }, +} + #[derive(Debug, Clone, Copy)] enum Val { I32(V), @@ -35,8 +54,11 @@ pub(crate) struct Lowered { pub cmp_samplers: u64, pub root_cbvs: Vec, pub root_srvs: Vec, + pub root_uavs: Vec, pub user_data: Vec, pub samplers: Vec<[u32; 4]>, + /// The wave size the shader requires of the host, if any. + pub wave_size: Option, /// Heap handles made with a non-uniform index. #[cfg(test)] pub nonuniform_handles: u32, @@ -86,6 +108,14 @@ const TWO_PI: f32 = std::f32::consts::TAU; /// `s_sendmsg` id of a mesh or NGG stage's output allocation request. const GS_ALLOC_REQ: u16 = 9; +/// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0, +/// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)). +fn inline_f16(c: u8) -> u32 { + [ + 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, + ][usize::from(c - 240)] +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Numeric { Unorm, @@ -161,6 +191,9 @@ struct Lower<'a> { lane_bits: HashMap, /// IR phi location by value. phi_at: HashMap, + /// Descriptor dwords with no host value (addresses, formats, all of a constant + /// buffer's): no program reads them as numbers ([`Self::dead`]). + stale: HashSet, mask_phis: HashMap, pending_masks: Vec<(V, usize, usize)>, data_phis: Vec<(V, usize, usize)>, @@ -173,7 +206,10 @@ struct Lower<'a> { scalar: HashMap, exports: HashMap, interps: HashMap, - handles: HashMap<(usize, Site, u8, bool, u32), V>, + handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>, + /// Element strides read from the host's table by heap slot + /// ([`super::shader::SLOT_STRIDES`]), by block and descriptor load. + strides: HashMap<(usize, Site, u8), V>, /// Blocks splitting the edge from one IR block to another. edges: HashMap<(usize, usize), usize>, /// Per IR block: a `done` export is behind every lane entering it. @@ -193,6 +229,40 @@ struct Lower<'a> { flat: Option, /// Mesh: IR blocks whose `s_barrier` is left out. no_barrier: HashSet, + /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane + /// branch lies between the entry and the block, or the program has a + /// loop a lane can be cut out of): the barrier there keeps its fences + /// and does not wait for the group ([`super::group_sync`]). + fence_only: HashSet, + /// A group barrier before every LDS access (a console wave run as two host waves). + split_lds: bool, + /// With `split_lds`, LDS accesses in lane branches: per IR block whether every lane runs + /// it, and whether the host waves meet at its start and before its exit ([`lds_meetings`]). + lds_meet: Option<(Vec, Vec<(bool, bool)>)>, + /// A console wave64 program run as two host waves of 32 that exchange through LDS: the first + /// of two exchange dwords, whether the group has no upper half (32 threads or fewer), and per + /// IR block whether every lane runs it (exchanges need both halves there). + exchange: Option<(u32, bool, Vec)>, + /// With `exchange`: nothing is exchanged, each host wave acts as a wave + /// of its own ([`with_local_waves`]). + local: bool, + /// The instruction being lowered may read a lane mask as a number under + /// `local` (a bit count, a first set bit, `v_mbcnt`). + local_ok: bool, + /// With `local`: every mask read and lane read is taken per host wave + /// ([`with_local_waves_any`]). + local_any: bool, + /// With `exchange`: VGPR values every lane holds alike ([`lane_uniform`]); a first-lane + /// read of one needs nothing from the other host wave. + uniform: HashSet, + /// The console lane (0..63) of this thread, made in the entry block. + clane: Option, + /// The first exchange dword of this thread's console wave ([`Self::exchange_pair`]). + pair: Option, + /// A console wave64 program in host waves of 32: the LDS dword counting the console threads + /// handed to host waves (`wave_base`), and the base made in the entry block. + halves: Option, + wave_base: Option, /// Vertex and mesh outputs holding 16-bit values: row, whether two per /// dword, and the row packed after it. half_outputs: HashMap)>, @@ -259,6 +329,612 @@ const LANE_MASK: Why = "a lane mask read as data"; /// Instructions that read a lane mask (not EXEC implicitly, not a lane's /// bit) as a number. +/// Per IR block: every lane of the wave that started the program runs it – no per-lane branch +/// separates it from the entry (it lies in no lane branch's region: the blocks reachable from +/// the branch that do not post-dominate it). None with an indirect exit (not followed). +fn all_lane_blocks(st: &Structured) -> Option> { + let n = st.exits.len(); + let mut succ: Vec> = vec![Vec::new(); n]; + for (b, e) in st.exits.iter().enumerate() { + match *e { + LaneExit::Jump(t) => succ[b].push(t), + LaneExit::Branch { taken, not_taken, .. } => { + succ[b].push(taken); + succ[b].push(not_taken); + } + LaneExit::End => {} + LaneExit::Indirect => return None, + } + } + // post-dominators (bitsets; a virtual exit after every End) + let words = n.div_ceil(64); + let full = vec![u64::MAX; words]; + let mut pdom: Vec> = (0..n).map(|b| if succ[b].is_empty() { let mut v = vec![0; words]; v[b / 64] |= 1 << (b % 64); v } else { full.clone() }).collect(); + let mut changed = true; + while changed { + changed = false; + for b in (0..n).rev() { + if succ[b].is_empty() { + continue; + } + let mut v = full.clone(); + for &t in &succ[b] { + for w in 0..words { + v[w] &= pdom[t][w]; + } + } + v[b / 64] |= 1 << (b % 64); + if v != pdom[b] { + pdom[b] = v; + changed = true; + } + } + } + let mut all = vec![true; n]; + for (d, e) in st.exits.iter().enumerate() { + let LaneExit::Branch { when, .. } = *e else { continue }; + if st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) { + continue; // a uniform branch: all lanes go the same way + } + // blocks reachable from the lane branch that do not post-dominate it + let mut seen = vec![false; n]; + let mut stack: Vec = succ[d].clone(); + while let Some(b) = stack.pop() { + if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 { + continue; + } + seen[b] = true; + all[b] = false; + stack.extend(succ[b].iter().copied()); + } + } + Some(all) +} + +/// VGPR values that are the same in every lane holding them (`all` is [`all_lane_blocks`]): +/// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars, +/// constants and such values; or loaded from an address made of them. The compiler keeps +/// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`. +/// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes +/// run (no lane branch can have split the arriving lanes); loop-carried values never do. +fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + let mut same: HashSet = HashSet::new(); + for b in crate::ir::reverse_postorder(&p.blocks) { + let block = &p.blocks[b]; + let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false)); + for phi in &block.phis { + if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) { + same.insert(phi.value); + } + } + for (i, inst) in block.insts.iter().enumerate() { + let name = inst.name(); + let ops: Vec = match &inst.fields { + Fields::Valu(v) + if v.dpp.is_none() + && v.sdwa.is_none() + && !name.starts_with("v_mbcnt") + && !name.starts_with("v_cmpx") + && !name.contains("lane") => + { + v.src.clone() + } + _ => continue, + }; + if st.guards[b][i].is_some() { + continue; // lanes outside EXEC keep another value + } + let alike = ops.iter().all(|op| match *op { + Operand::Vector { reg, .. } => { + // every dword of the operand the instruction reads from that register on + let read: Vec = + inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect(); + !read.is_empty() && read.iter().all(|x| same.contains(x)) + } + // a scalar is one value; a lane mask is not, unless a compare of such values made it + Operand::Scalar { code, .. } if code != NULL => { + inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x)) + } + _ => true, + }); + if alike { + same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); + } + } + } + same +} + +/// What a register value holds, for [`wave_local`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Wave { + /// Nothing that depends on how the threads are divided into waves. + Plain, + /// The number of the wave's first lane in a mask (`s_ff1`). + First, + /// A reduction over the wave's lanes: a count, a sum, a minimum... + Total(super::wave::Op), + /// A count or sum over the lanes below this one. + Prefix, + /// Derived from what a first-lane atomic returned: the slots the wave reserved. + Base, + /// A mix the idiom does not make. + Mixed, +} + +/// Whether a console wave64 program may run with each host wave as a wave of its own +/// ([`with_local_waves`]): its wave-wide values are used only as the allocation idiom uses +/// them, which does not care how the threads are divided into waves. A first-lane number only +/// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter; +/// a prefix only goes onto the base that atomic returned; the first lane does nothing else. +/// Anything else done with them takes one wave to be the whole thread group (a tile's result, +/// say) and is refused, with the offset and what was found. +/// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections +/// are stopped by the lowering itself. +// shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this +// host wave's first lane), and a guarded write of a plain value over a wave-dependent one is +// the only mix of old and new lanes that is looked at. +pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> { + use super::wave::{Op, Shape}; + const FIRST: Why = "a wave's first-lane number used as data"; + const TOTAL: Why = "a count or sum over the wave used as data"; + const PREFIX: Why = "a count or sum over the lanes below used without a reserved base"; + const MIXED: Why = "a value that depends on the wave on some paths only"; + const EFFECT: Why = "a write by the wave's first lane other than its reservation"; + fn of(kind: &HashMap, v: Option) -> Wave { + v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain) + } + fn put(kind: &mut HashMap, v: Value, k: Wave) { + if k == Wave::Plain { + kind.remove(&v); + } else { + kind.insert(v, k); + } + } + let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base); + let why = |k: Wave| match k { + Wave::First => FIRST, + Wave::Total(_) => TOTAL, + Wave::Prefix => PREFIX, + _ => MIXED, + }; + // a mask (by its low dword) under which only a wave's first lane runs + let first_mask = |firsts: &HashSet, m: Option| { + m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| { + st.bools + .support(b) + .iter() + .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v))) + }) + }; + // One instruction outside a section: the kind of what it writes, and whether it is a + // first lane's reservation. + let step = |inst: &Inst, kind: &HashMap, firsts: &mut HashSet| -> Result<(Wave, bool), Why> { + let name = inst.name(); + let val = |op: &Operand| match *op { + Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), + Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)), + _ => None, + }; + let ops: Vec = match &inst.fields { + Fields::Valu(v) => v.src.clone(), + Fields::Sop { dst, src, .. } => { + let mut o = src.clone(); + if matches!(name, "s_addk_i32" | "s_mulk_i32") { + o.extend(dst.iter().copied()); + } + o + } + Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => { + data.iter().copied().collect() + } + _ => Vec::new(), + }; + let kinds: Vec = ops.iter().map(|o| of(kind, val(o))).collect(); + // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide + // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it + // writes, which only the lanes outside EXEC keep. + let named: Vec = ops.iter().filter_map(|o| val(o)).collect(); + for &(r, v) in &inst.reads { + let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r); + if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) { + continue; + } + let k = of(kind, Some(v)); + if wild(k) { + return Err(why(k)); + } + } + let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed); + let sum = |k: Wave| k == Wave::Total(Op::AddU); + let is_mask = |o: &Operand| { + val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v)) + }; + let mut reserved = false; + let out = match (name, &kinds[..]) { + ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First, + ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => { + Wave::Total(Op::AddU) + } + // bits of a mask below the lane; with -1 for the mask, the lane's number + ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => { + match (matches!(ops[0], Operand::Scalar { .. }), *b) { + (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix, + (false, Wave::Plain | Wave::Base) => Wave::Plain, + (_, k) => return Err(why(k)), + } + } + // nothing wave-dependent goes in; what derives from a reserved base stays marked + _ if !kinds.iter().any(|&k| wild(k)) => { + let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. }); + if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain } + } + ("v_mov_b32" | "s_mov_b32", [k]) => *k, + ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => { + // the lane whose own number is the first lane's + let lane = match (*a, *b) { + (Wave::First, k) if !wild(k) => &ops[1], + (k, Wave::First) if !wild(k) => &ops[0], + _ => return Err(why(w)), + }; + if !matches!(lane, Operand::Vector { .. }) { + return Err(FIRST); + } + let mask = match &inst.fields { + _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)), + Fields::Valu(v) => match v.dst { + Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)), + _ => None, + }, + _ => None, + }; + firsts.extend(mask); + Wave::Plain + } + ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) { + (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base, + (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix, + (x, y) if sum(x) && sum(y) => x, + _ => return Err(why(w)), + }, + ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) { + (Wave::Base, Wave::Prefix) => Wave::Base, + (Wave::Prefix, Wave::Plain) => Wave::Prefix, + (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y, + _ => return Err(why(w)), + }, + ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) { + (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x, + _ => return Err(why(w)), + }, + ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x]) + if sum(*x) || *x == Wave::Prefix => + { + *x + } + ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => { + if *c == Wave::Base { Wave::Base } else { Wave::Prefix } + } + // the reservation: the first lane adds its wave's total to a shared counter + (_, [Wave::Total(op)]) if name.contains("_atomic_") => { + let want = match op { + Op::AddU => "buffer_atomic_add", + Op::MinU => "buffer_atomic_umin", + Op::MaxU => "buffer_atomic_umax", + Op::MinI => "buffer_atomic_smin", + Op::MaxI => "buffer_atomic_smax", + Op::Or => "buffer_atomic_or", + Op::And => "buffer_atomic_and", + Op::Xor => "buffer_atomic_xor", + _ => "", + }; + if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) { + return Err(TOTAL); + } + reserved = true; + Wave::Base + } + _ => return Err(why(w)), + }; + Ok((out, reserved)) + }; + let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect(); + let order = crate::ir::reverse_postorder(&p.blocks); + let pass = |kind: &mut HashMap, firsts: &mut HashSet, check: bool| -> Result<(), (usize, Why)> { + for &b in &order { + let block = &p.blocks[b]; + for phi in &block.phis { + let mut k = Wave::Plain; + for (n, &a) in phi.args.iter().enumerate() { + let x = of(kind, Some(a)); + k = match (k, x) { + _ if n == 0 => x, + (k, x) if k == x => k, + (Wave::Plain, m @ (Wave::Base | Wave::Prefix)) + | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m, + _ => Wave::Mixed, + }; + } + put(kind, phi.value, k); + } + for (i, inst) in block.insts.iter().enumerate() { + // inside a whole-wave section: what the simulation found each value to be + if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) { + for &(_, w) in &inst.writes { + let k = match sec.shapes.get(&w) { + None => Wave::Mixed, + Some(&Shape::K(_)) => Wave::Plain, + Some(&Shape::Value(v)) => of(kind, Some(v)), + Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)), + Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) { + Wave::Plain | Wave::Base => Wave::Total(op), + // the first lane's own sum of a total is that total + Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op), + _ => Wave::Mixed, + }, + Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) { + Wave::Plain | Wave::Base => Wave::Prefix, + Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix, + _ => Wave::Mixed, + }, + Some(_) => Wave::Mixed, + }; + put(kind, w, k); + } + continue; + } + let name = inst.name(); + if name.starts_with("s_cbranch") { + continue; // with the block's exit, below + } + let (k, reserved) = match step(inst, kind, firsts) { + Ok(r) => r, + Err(why) if check => return Err((inst.machine.offset, why)), + Err(_) => (Wave::Mixed, false), + }; + // the same test as `Lower::inst`'s `effect` + let effect = matches!(inst.fields, Fields::Exp { .. }) + || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") + || name.contains("store") + || name.contains("atomic") + || matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_read") + || name.starts_with("ds_swizzle") + || name.contains("permute")); + if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) { + return Err((inst.machine.offset, EFFECT)); + } + let guarded = st.guards[b][i].is_some(); + for &(r, w) in &inst.writes { + let mut kw = match r { + // "some lane is counted" keeps the count's kind; any other SCC is one bit of data + Reg::Scc if !name.starts_with("s_bcnt1") => { + if wild(k) { Wave::Mixed } else { Wave::Plain } + } + _ => k, + }; + // a guarded write leaves the old value in the lanes outside EXEC + if guarded + && matches!(r, Reg::V(_)) + && kw == Wave::Plain + && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix) + { + kw = Wave::Mixed; + } + put(kind, w, kw); + } + } + // a branch on "some lane is counted": fine where the structure made it the lane's + // own bit (the mask is EXEC under a scalar condition) + if check + && let Some(last) = block.insts.last() + && last.name().starts_with("s_cbranch_scc") + && let Some(scc) = last.read(Reg::Scc) + && wild(of(kind, Some(scc))) + { + let own = matches!(st.exits[b], LaneExit::Branch { when, .. } + if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc))); + if !own { + return Err((last.machine.offset, TOTAL)); + } + } + } + Ok(()) + }; + let mut kind: HashMap = HashMap::new(); + let mut firsts: HashSet = HashSet::new(); + // to a fixpoint (values carried around loops), then once more to say what is wrong + let mut settled = false; + for _ in 0..16 { + let before = (kind.clone(), firsts.len()); + pass(&mut kind, &mut firsts, false)?; + if (&before.0, before.1) == (&kind, firsts.len()) { + settled = true; + break; + } + } + if !settled { + return Err((0, MIXED)); + } + pass(&mut kind, &mut firsts, true) +} + +/// The mode of a group barrier the translation adds (host waves meeting): +/// a wait for the group with a shared-memory fence; the fence alone with +/// `VICTORY_GROUP_SYNC=0` ([`super::group_sync`]). +fn meeting_mode() -> u32 { + if super::group_sync() == 0 { 8 } else { 1 | 8 } +} + +/// LDS accesses of a console wave run as two host waves, where some sit in blocks that only +/// some lanes run (`all` is [`all_lane_blocks`]): per IR block, whether the host waves meet (a +/// group barrier) at its start and before its exit. `None` if barriers cannot keep the +/// console's order. +/// +/// The console runs the wave's lanes in step, so an LDS write is seen by every later read. Two +/// host waves keep that order if they meet between any two accesses of which one writes. A +/// barrier must be run by every thread, so it cannot stand in a lane branch's region; but +/// every way into and out of such a region passes a block all lanes run, and the waves meet +/// there: before the exit of an all-lane block into a region with LDS accesses, and at the +/// start of an all-lane block entered from one. Accesses in all-lane blocks get their own +/// barrier as before. What that cannot order is a write and a read inside one region (blocks +/// joined without an all-lane block between them): refused. +/// shortcut: two writes in one region are taken not to hit the same dword from both halves. +fn lds_meetings(p: &crate::ir::Program, st: &Structured, all: &[bool]) -> Option> { + let n = st.exits.len(); + let succ = |b: usize| -> Vec { + match st.exits[b] { + LaneExit::Jump(t) => vec![t], + LaneExit::Branch { taken, not_taken, .. } => vec![taken, not_taken], + LaneExit::End | LaneExit::Indirect => Vec::new(), + } + }; + // regions: blocks not every lane runs, joined by the edges between them + let mut region: Vec = (0..n).collect(); + fn find(region: &mut [usize], mut b: usize) -> usize { + while region[b] != b { + region[b] = region[region[b]]; + b = region[b]; + } + b + } + for b in 0..n { + for t in succ(b) { + if !all[b] && !all[t] { + let (x, y) = (find(&mut region, b), find(&mut region, t)); + region[x] = y; + } + } + } + // per region: LDS reads, LDS writes + let mut reads = vec![false; n]; + let mut writes = vec![false; n]; + for (b, block) in p.blocks.iter().enumerate().take(n) { + if all[b] { + continue; + } + let r = find(&mut region, b); + for i in &block.insts { + let name = i.name(); + if !matches!(i.fields, Fields::Ds { .. }) || name.starts_with("ds_swizzle") || name.contains("permute") { + continue; + } + if name.starts_with("ds_read") { + reads[r] = true; + } else { + writes[r] = true; + } + } + } + if (0..n).any(|r| reads[r] && writes[r]) { + return None; + } + let mut meet = vec![(false, false); n]; + for b in 0..n { + for t in succ(b) { + if all[b] && !all[t] { + let r = find(&mut region, t); + meet[b].1 |= reads[r] || writes[r]; + } else if !all[b] && all[t] { + let r = find(&mut region, b); + meet[t].0 |= reads[r] || writes[r]; + } + } + } + Some(meet) +} + +/// Masks held as numbers or constant lane sets in guards or lane branches: the lane tests its +/// own bit by its console lane. +fn lane_constant_masks(st: &Structured) -> bool { + let whens = st.exits.iter().filter_map(|e| match *e { + LaneExit::Branch { when, .. } => Some(when), + _ => None, + }); + let mut work: Vec = st.guards.iter().flatten().flatten().copied().chain(whens).collect(); + // Through lane-mask joins too: an edge that brings a number or a constant lane set needs + // the lane's own bit of it. + // shortcut: masks only selects read (`v_cndmask_b32`, carries in) are not followed; such + // a program still stops with "a constant lane mask" or "an opaque lane mask". + let (mut seen, mut joins) = (HashSet::new(), HashSet::new()); + while let Some(g) = work.pop() { + if !seen.insert(g) { + continue; + } + for a in st.bools.support(g) { + match a { + Atom::Opaque(_) | Atom::Constant(_) => return true, + Atom::Phi(id) if joins.insert(id) => { + if let Some(edges) = st.phi_masks.get(&id) { + work.extend(edges.iter().copied()); + } + } + _ => {} + } + } + } + false +} + +/// The widest wave the host GPU runs (0: not known – no host-specific forms); see +/// [`set_host_max_wave`]. +static HOST_MAX_WAVE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// The host GPU's `WaveLaneCountMax`: 32 lets console wave64 compute programs whose cross-lane +/// code stays inside 32-lane halves run in waves of 32 instead of being refused. +pub fn set_host_max_wave(lanes: u32) { + HOST_MAX_WAVE.store(lanes, std::sync::atomic::Ordering::Relaxed); +} + +thread_local! { + /// See [`with_local_waves`]. + static LOCAL_WAVES: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// See [`with_local_waves_any`]. + static LOCAL_ANY: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// As [`with_local_waves`], with every other use of a lane mask as a number +/// and every lane read and write taken per host wave too: the program runs +/// as it would on a console of 32-lane waves, lanes numbered 0..31 or +/// 32..63 by half. Right for code that only relies on what HLSL's wave +/// operations promise; a program that takes one wave to be its whole +/// thread group gets per-half results. The last resort for programs that +/// do not translate otherwise. +pub(super) fn with_local_waves_any(f: impl FnOnce() -> R) -> R { + let was = LOCAL_ANY.replace(true); + let r = with_local_waves(f); + LOCAL_ANY.set(was); + r +} + +/// Runs `f` with console wave64 programs on 32-lane hosts lowered with each +/// host wave as a wave of its own ("local"): no exchange between the two +/// halves of a console wave, so no barriers and no need for every lane to +/// reach the code. What HLSL's wave operations promise holds for any +/// division of the threads into waves, and the idiom the title's compute +/// programs use them for does not care which wave a thread is in: count or +/// sum over the wave, the first lane reserves that many slots with an atomic +/// add, every lane takes the base (`WaveReadLaneFirst`) plus its prefix. +/// Each lane still gets a slot of its own; only the order differs. +/// Only that idiom's operations are lowered this way: a lane mask read as +/// a number by anything but a bit count, a first-set-bit or `v_mbcnt`, and +/// lane reads and writes outside whole-wave sections, stop the translation. +/// shortcut: where a count or sum goes is not checked. A program that uses +/// a wave-wide result as data for the whole console wave (a tile's maximum, +/// say, with one wave per thread group) gets its half's result. It is used +/// only for programs that do not translate otherwise. +pub(super) fn with_local_waves(f: impl FnOnce() -> R) -> R { + let was = LOCAL_WAVES.replace(true); + let r = f(); + LOCAL_WAVES.set(was); + r +} + +pub(super) fn host_max_wave() -> u32 { + HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed) +} + fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); let ops: Vec<&Operand> = match &i.fields { @@ -284,26 +960,105 @@ fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { }) } -/// Where half `h` (dword h / 2, the high half when odd) of a parameter -/// packing 16-bit rows `a` and `b` two per dword comes from: a row and -/// channel of `elements`, none for padding. Channel c of `a` is half c; -/// `b` starts at the dword after `a`'s last channel. -fn packed_half(elements: &[SigElement], a: u8, b: Option, h: u8) -> Option<(u8, u8)> { - let extent = |r: u8| { - elements +/// The parameters packing 16-bit rows two per dword and where each lays +/// its elements out: (first row, [(dword, register, column, columns)]). +/// +/// The console gives every 16-bit element whole dwords. A parameter leads +/// with the first element of its first row, then the first element of its +/// second row. An element that shares a register behind another one (the +/// signature packs a short element into the free columns of an earlier +/// register) is NOT in that row's halves: it follows in the first +/// parameter, in row order, that has whole dwords left. Grand Theft Auto +/// VI's packed pedestrian shaders show both cases: TEXCOORD7 (register 1, +/// columns 2-3, behind the two columns of TEXCOORD0) is exported in dword 3 +/// of parameter 0, after TEXCOORD1's two dwords; TEXCOORD6 (register 4, +/// column 3, behind the three columns of TEXCOORD4) in dword 3 of +/// parameter 3, after TEXCOORD5 and TEXCOORD7, while the high half of +/// TEXCOORD4's second dword stays zero. +type PackedLayout = Vec<(u8, Vec<(u8, u8, u8, u8)>)>; + +fn packed_layout(elements: &[SigElement], packs: &[(u8, Option)]) -> PackedLayout { + let of_row = |r: u8| { + let mut of: Vec<&SigElement> = elements .iter() .filter(|e| e.row == Some(u32::from(r))) - .map(|e| e.col + e.cols) - .max() + .collect(); + of.sort_by_key(|e| e.col); + of }; - let na = extent(a)?; - let a_halves = na.div_ceil(2) * 2; - if h < a_halves { - return (h < na).then_some((a, h)); + let mut packs = packs.to_vec(); + packs.sort_unstable(); + packs.dedup_by_key(|p| p.0); + // Per parameter: its first row, the dwords used, the elements. + let mut layout: Vec<(u8, u8, Vec<(u8, u8, u8, u8)>)> = Vec::new(); + let mut behind = Vec::new(); + for &(a, b) in &packs { + let mut placed = Vec::new(); + let mut at = 0u8; + if !of_row(a).is_empty() { + for r in [Some(a), b].into_iter().flatten() { + let of = of_row(r); + let Some((lead, more)) = of.split_first() else { + continue; + }; + placed.push((at, r, lead.col, lead.cols)); + at += lead.cols.div_ceil(2); + behind.extend(more.iter().map(|e| (r, e.col, e.cols))); + } + } + layout.push((a, at, placed)); } - let b = b?; - let c = h - a_halves; - (c < extent(b)?).then_some((b, c)) + behind.sort_unstable(); + for (r, col, cols) in behind { + let need = cols.div_ceil(2); + if let Some(p) = layout.iter_mut().find(|p| p.1 + need <= 4) { + p.2.push((p.1, r, col, cols)); + p.1 += need; + } + } + layout.into_iter().map(|(a, _, of)| (a, of)).collect() +} + +/// Where half `h` (dword h / 2, the high half when odd) of the parameter +/// whose first 16-bit row is `a` comes from: a register and column of +/// `elements`, none for padding ([`packed_layout`]; `packs` lists every +/// parameter packing two 16-bit rows per dword). +fn packed_half( + elements: &[SigElement], + packs: &[(u8, Option)], + a: u8, + h: u8, +) -> Option<(u8, u8)> { + let layout = packed_layout(elements, packs); + let (_, of) = layout.iter().find(|p| p.0 == a)?; + of.iter().find_map(|&(dword, row, col, cols)| { + let k = h.checked_sub(2 * dword)?; + (k < cols).then_some((row, col + k)) + }) +} + +/// The pixel inputs packing two 16-bit rows per dword, as (first row, +/// second row) ([`packed_layout`]). +fn input_packs(io: &StageIo, inputs: &[SigElement]) -> Vec<(u8, Option)> { + let StageIo::Ps { + inputs: entries, .. + } = io + else { + return Vec::new(); + }; + let partners = half_input_partners(io, inputs); + entries + .iter() + .filter(|i| i.fp16 && i.pack2) + .map(|i| { + let b = if i.row2 != i.row { + Some(i.row2) + } else { + partners.get(&i.row).copied() + }; + (i.row, b) + }) + .collect() } /// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]): @@ -338,6 +1093,39 @@ fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap HashMap { + let StageIo::Ps { + inputs: entries, .. + } = io + else { + return HashMap::new(); + }; + let packed = || entries.iter().filter(|i| i.fp16 && i.pack2); + let mut free: Vec = inputs + .iter() + .filter(|e| e.half && e.kind == 0) + .filter_map(|e| u8::try_from(e.row?).ok()) + .filter(|&r| !entries.iter().any(|i| i.row == r)) + .filter(|&r| !packed().any(|i| i.row2 != i.row && i.row2 == r)) + .collect(); + free.sort_unstable(); + free.dedup(); + let mut missing: Vec<_> = packed().filter(|i| i.row2 == i.row).collect(); + missing.sort_by_key(|i| i.row); + let mut partners = HashMap::new(); + for i in missing { + if let Some(k) = free.iter().position(|&r| r > i.row) { + partners.insert(i.row, free.remove(k)); + } + } + partners +} + fn unsupported(offset: usize, what: Why) -> Stop { Stop::Fail(ShaderError::Unsupported { offset, what }) } @@ -360,6 +1148,15 @@ impl<'a> Lower<'a> { && (i.name().contains("store") || i.name().contains("atomic")) }); let mut console_lanes = false; + // LDS accesses get a group barrier each (a console wave split in two host waves) + let mut split_lds = false; + // with `split_lds`, LDS accesses in lane branches: the blocks every lane runs, and + // where the host waves meet around those branches (`lds_meetings`) + let mut lds_meet: Option<(Vec, Vec<(bool, bool)>)> = None; + // a console wave64 program in two host waves of 32 (`exchange`) + let mut exchange: Option<(u32, bool, Vec)> = None; + // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter + let mut halves: Option = None; if let StageIo::Cs(cs) = x.native.io { s.threads = Some(cs.threads); s.lds_dwords = cs.lds_bytes() / 4; @@ -374,36 +1171,145 @@ impl<'a> Lower<'a> { || matches!(n, "v_readlane_b32" | "v_writelane_b32") || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some()) || reads_mask_as_data(x.st, i) - }) || { - // Masks held as numbers or constant lane sets: the lane - // tests its own bit by its console lane. - let whens = x.st.exits.iter().filter_map(|e| match *e { - LaneExit::Branch { when, .. } => Some(when), - _ => None, - }); - let mut all: Vec = - x.st.guards - .iter() - .flatten() - .flatten() - .copied() - .chain(whens) - .collect(); - all.sort_unstable(); - all.dedup(); - all.into_iter().any(|g| { - x.st.bools - .support(g) - .iter() - .any(|a| matches!(a, Atom::Opaque(_) | Atom::Constant(_))) - }) - }; - let wave = if x.native.wave64 { 64 } else { 32 }; - let one_wave = cs.threads.iter().product::() <= wave; + }) || lane_constant_masks(x.st); + let mut wave = if x.native.wave64 { 64 } else { 32 }; + let group = cs.threads.iter().product::(); + let one_wave = group <= wave; + // A host whose waves are at most 32 lanes (NVIDIA) refuses `WaveSize(64)`. A console + // wave64 program whose cross-lane code stays inside 32-lane halves – DPP rows, + // `ds_swizzle`, `v_permlane16` / `v_permlanex16`, which the ISA confines there – runs + // exactly in waves of 32: the thread relabelling makes each host wave one half of a + // console wave (lanes 32k..32k+31). Not when it crosses halves (`v_mbcnt`, + // `v_readlane`, `v_writelane`, `ds_(b)permute`, masks as numbers or lane-constant + // masks), nor when LDS may be shared within the console wave without barriers (a + // group over 32 threads with LDS): those still need 64-lane waves. + if wave == 64 && host_max_wave() == 32 && (console_lanes || one_wave && s.lds_dwords > 0) { + let crosses = insts().any(|i| { + let n = i.name(); + n.starts_with("v_mbcnt") + || matches!(n, "v_readlane_b32" | "v_writelane_b32") + || n.starts_with("ds_permute") + || n.starts_with("ds_bpermute") + || reads_mask_as_data(x.st, i) + }) || lane_constant_masks(x.st); + if !crosses && (s.lds_dwords == 0 || group <= 32) { + wave = 32; + } else { + // (Groups of several console waves too: each console wave is two host + // waves, which exchange through their own pair of dwords.) + // LDS the console shares within its one wave without barriers: split into + // two waves of 32, a group barrier before every LDS access keeps their order + // – where every thread of the group gets there (no lane branch around it, + // no guard), else a barrier would hang the group + let lds = |i: &Inst| { + matches!(i.fields, Fields::Ds { .. }) + && !(i.name().starts_with("ds_swizzle") || i.name().contains("permute")) + }; + if let Some(all) = all_lane_blocks(x.st) { + let ok = p.blocks.iter().enumerate().all(|(b, blk)| { + blk.insts.iter().all(|inst| { + !lds(inst) || all.get(b).copied().unwrap_or(false) + }) + }); + let mut lds_ok = !(s.lds_dwords > 0 && group > 32) || ok; + if !lds_ok && let Some(meet) = lds_meetings(p, x.st, &all) { + lds_meet = Some((all.clone(), meet)); + lds_ok = true; + } + if lds_ok { + wave = 32; + split_lds = s.lds_dwords > 0 && group > 32; + if crosses { + // lanes 32..63 are the other host wave: masks, lane reads and lane + // numbers go through two exchange dwords past the program's LDS + exchange = Some((s.lds_dwords, group <= 32, all)); + s.lds_dwords += 2 * group.div_ceil(64); + } + } + } + } + // `VICTORY_WAVE_WHY=1`: why a program keeps 64-lane waves (one line per reason) + if wave == 64 && std::env::var_os("VICTORY_WAVE_WHY").is_some() { + let mut why: Vec<&str> = Vec::new(); + for i in insts() { + let n = i.name(); + let r = if n.starts_with("v_mbcnt") { + "v_mbcnt" + } else if n == "v_readlane_b32" { + "v_readlane" + } else if n == "v_writelane_b32" { + "v_writelane" + } else if n.starts_with("ds_permute") || n.starts_with("ds_bpermute") { + "ds_(b)permute" + } else if reads_mask_as_data(x.st, i) { + "mask as data" + } else { + continue; + }; + if !why.contains(&r) { + why.push(r); + } + } + if lane_constant_masks(x.st) { + why.push("lane-constant mask"); + } + if s.lds_dwords > 0 && group > 32 { + why.push("LDS in a group over 32"); + match all_lane_blocks(x.st) { + None => why.push("an indirect exit"), + Some(all) if lds_meetings(p, x.st, &all).is_none() => { + why.push("an LDS read and write in one lane-branch region") + } + Some(_) => {} + } + } + why.sort_unstable(); + eprintln!("WAVE64-WHY group={group} lds={} [{}]", s.lds_dwords > 0, why.join(", ")); + } + } + if wave == 32 && x.native.wave64 { + // console threads go to host waves in the order the waves take them (`wave_base`) + halves = Some(s.lds_dwords); + s.lds_dwords += 1; + } if console_lanes || one_wave && s.lds_dwords > 0 { s.wave_size = Some(wave); } } + // The title's barriers a thread of the group may never reach, which + // leaves the others waiting on the host: those in blocks some lanes + // do not run, and all of them in a program with a loop closed by a + // plain jump (a lane still in it at the iteration limit leaves the + // program there, `abort_block`). + let fence_only: HashSet = if insts().any(|i| i.name() == "s_barrier") { + let order = crate::ir::reverse_postorder(&p.blocks); + let mut place = vec![usize::MAX; p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + place[b] = n; + } + let back = |from: usize, to: usize| { + let at = |b: usize| place.get(b).copied().unwrap_or(usize::MAX); + at(from) != usize::MAX && at(to) <= at(from) + }; + let cut_short = x + .st + .exits + .iter() + .enumerate() + .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t))); + let all = all_lane_blocks(x.st); + (0..p.blocks.len()) + .filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier")) + .filter(|&b| { + cut_short + || all + .as_ref() + .is_none_or(|all| !all.get(b).copied().unwrap_or(false)) + }) + .collect() + } else { + HashSet::new() + }; let mut no_barrier = HashSet::new(); if let StageIo::Ms(ms) = &x.native.io { s.prims = x.prims.clone(); @@ -465,6 +1371,7 @@ impl<'a> Lower<'a> { pending_masks: Vec::new(), data_phis: Vec::new(), read_phis: HashSet::new(), + stale: HashSet::new(), params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(), user_data: None, user_reads: BTreeMap::new(), @@ -479,6 +1386,7 @@ impl<'a> Lower<'a> { exports: x.io.exports.iter().map(|e| (e.site, e)).collect(), interps: x.io.interps.iter().map(|(s, i)| (*s, i)).collect(), handles: HashMap::new(), + strides: HashMap::new(), edges: HashMap::new(), exported: vec![false; p.blocks.len()], rpo: vec![usize::MAX; p.blocks.len()], @@ -486,8 +1394,23 @@ impl<'a> Lower<'a> { writes_uavs, src0: None, console_lanes, + split_lds, + lds_meet, + local: exchange.is_some() && LOCAL_WAVES.get(), + local_ok: false, + local_any: LOCAL_ANY.get(), + uniform: match &exchange { + Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all), + _ => HashSet::new(), + }, + exchange, + clane: None, + pair: None, + halves, + wave_base: None, flat: None, no_barrier, + fence_only, half_outputs: half_outputs(&x.native.io, &x.outputs), mask_data: match x.native.stage { HwStage::Cs => MaskData::Console, @@ -584,6 +1507,9 @@ impl<'a> Lower<'a> { unreachable!() }; let name = inst.name(); + if self.scalar.get(&(b, i)).is_some_and(|a| a.param == MEMORY) { + return self.memory_flat(inst, b, i); + } let rest = name .strip_prefix("global_load_") .ok_or("a global memory write")?; @@ -620,6 +1546,9 @@ impl<'a> Lower<'a> { bits: 0, words: [0, 0], }; + if let Some(bias) = self.root_bias(a.param) { + off = self.s.m.bin(c, Bin::Add, off, bias); + } Some(self.handle((b, i), &src, false, (11, 0))?) }; let dword = |l: &mut Self, byte: V| -> Result { @@ -751,7 +1680,18 @@ impl<'a> Lower<'a> { (op, src, mask, ident, Some(inclusive)) } }; - if self.mask_data == MaskData::None { + // Mesh: no host wave size can be declared, so a reduction is over this host wave + // only. A minimum or maximum is taken that way: the compiler's "next distinct + // value" loop (the wave's minimum, then the lanes that hold it) serves every + // lane however the lanes are divided into waves. A sum, a bit reduction or a + // prefix would be of part of a console wave: still refused. + if self.mask_data == MaskData::None + && (prefix.is_some() + || !matches!( + op, + Op::MinU | Op::MaxU | Op::MinI | Op::MaxI | Op::MinF | Op::MaxF + )) + { return Err("a wave reduction in a mesh shader"); } let c = self.cur; @@ -818,6 +1758,62 @@ impl<'a> Lower<'a> { ) } }; + // two host waves of 32 hold the console's 64 lanes: their results combine + let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) { + // this host wave's own result (and prefix): each wave on its own, or a group of + // 32 threads or fewer, which one host wave holds whole (combining with the 0 a + // missing half "gives" broke AND, MIN and signed MAX) + r + } else if self.exchange.is_some() { + if !self.all_lanes(self.cur_ir) { + return Err("a wave reduction where not every lane runs"); + } + let bits = |l: &mut Self, v: V| if float { l.as_int(v) } else { v }; + let back = |l: &mut Self, v: V| if float { l.as_float(v) } else { v }; + match prefix { + Some(_) => { + // the upper half adds the lower half's total to its prefix + let (k0, ku) = (self.s.m.i8(0), self.s.m.i8(u8::from(!float))); + let total = self.s.op(c, &format!("waveActiveOp.{sfx}"), Attr::NoUnwind, ty, 119, &[arg, k0, ku]); + let tb = bits(self, total); + let c = self.cur; + let (lo, _) = self.exchange_halves(c, tb); + let lo = back(self, lo); + let cl = self.console_lane(); + let k32 = self.s.m.i32(32); + let upper = self.s.m.cmp(c, pred::IUGE, cl, k32); + let zero = if float { self.s.m.f32(0) } else { self.s.m.i32(0) }; + let add = self.s.m.select(c, upper, lo, zero); + self.s.m.bin(c, Bin::Add, r, add) + } + None => { + let rb = bits(self, r); + let c = self.cur; + let (lo, hi) = self.exchange_halves(c, rb); + let (lo, hi) = (back(self, lo), back(self, hi)); + match op { + Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi), + Op::Or => self.s.m.bin(c, Bin::Or, lo, hi), + Op::And => self.s.m.bin(c, Bin::And, lo, hi), + Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi), + _ => { + // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40 + let code = match op { + Op::MaxF => 35, + Op::MinF => 36, + Op::MinU => 40, + Op::MaxU => 39, + Op::MinI => 38, + _ => 37, + }; + self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi]) + } + } + } + } + } else { + r + }; Ok(if float { self.as_int(r) } else { r }) } @@ -880,6 +1876,9 @@ impl<'a> Lower<'a> { }; self.vals.insert(phi.value, val); } + if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].0) { + self.lds_meeting(); + } let mut i = 0; while i < p.blocks[b].insts.len() { self.inst(b, i)?; @@ -893,6 +1892,9 @@ impl<'a> Lower<'a> { i += 1; } self.mask_ok = self.mask_data == MaskData::Console; + if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].1) { + self.lds_meeting(); + } self.tail[b] = Some(self.cur); self.exit(b)?; } @@ -901,11 +1903,15 @@ impl<'a> Lower<'a> { self.s.samplers = self.samplers.len() as u32; let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect(); let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect(); + let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect(); let cmp_samplers = self.s.cmp_samplers; + let wave_size = self.s.wave_size; Ok(Lowered { + wave_size, cmp_samplers, root_cbvs, root_srvs, + root_uavs, #[cfg(test)] nonuniform_handles: self.s.nonuniform_handles, #[cfg(test)] @@ -931,6 +1937,11 @@ impl<'a> Lower<'a> { for &(reg, v) in &self.x.p.inputs { let val = match reg { Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use + // Most programs only interpolate with them: loaded on first + // use as a value (`get`). + Reg::V(_) if matches!(io_inputs.get(&v), Some(Input::Barycentric { .. })) => { + continue; + } Reg::S(n) => match io_inputs.get(&v) { Some(&input) => self.input(input), // Above the SGPRs the hardware initializes, a register @@ -941,6 +1952,10 @@ impl<'a> Lower<'a> { None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => { Val::I32(self.s.m.i32(0)) } + // A scalar parked in a VGPR lane (`ir::unspill`), read where the + // paths only seem to allow it before any save: the lane of a VGPR + // nobody wrote, and VGPRs nobody set read as zero. + None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)), None => Val::Missing("a hardware SGPR input"), }, Reg::Scc => Val::Missing("SCC on entry"), @@ -967,7 +1982,7 @@ impl<'a> Lower<'a> { None => Val::Missing("a vertex input the signature lacks"), }; } - Input::Barycentric { .. } => return Val::Missing("barycentrics read directly"), + Input::Barycentric { kind, index } => return self.barycentric(kind, index), Input::PrimitiveId => return Val::Missing("the primitive id"), // The console code tests it against 0 (`v_cmp_ne_u32`), as the // host's value can be. @@ -1129,9 +2144,87 @@ impl<'a> Lower<'a> { self.vals.insert(v, val); return Ok(val); } + if let Some(loaded) = self.lazy_barycentric(v) { + loaded?; + return Ok(self.vals[&v]); + } Err("a value defined after its use") } + /// Loads `v` if it is a barycentric input VGPR not loaded yet (see + /// `inputs`): `None` if it is not one. + fn lazy_barycentric(&mut self, v: Value) -> Option> { + let (kind, index) = self.x.io.inputs.iter().find_map(|&(w, i)| match i { + Input::Barycentric { kind, index } if w == v => Some((kind, index)), + _ => None, + })?; + let val = self.barycentric(kind, index); + self.vals.insert(v, val); + Some(match val { + Val::Missing(w) => Err(w), + _ => Ok(()), + }) + } + + /// Barycentric `index` (0 i, 1 j) of `kind` as a value: a channel of + /// `SV_Barycentrics` declared with the same interpolation mode. + /// + /// GFX10 interpolates P0 + i (P1 - P0) + j (P2 - P0), so i and j are + /// the weights of vertices 1 and 2. The host's weights (x, y, z) are + /// those of vertices 0, 1 and 2, vertex 0 being the provoking vertex, + /// which is the console's P0 (`v_interp_mov` P0 is lowered to a flat + /// input): i is y and j is z. + /// shortcut: triangles only; on lines and points the console's i and j + /// are not checked against the host's weights. + fn barycentric(&mut self, kind: Barycentric, index: u8) -> Val { + let Some(mode) = interp_mode(kind) else { + return Val::Missing("pull-model barycentrics"); + }; + if index > 1 { + return Val::Missing("pull-model barycentrics"); + } + // One element per interpolation mode (the console's own, if its + // signature declares one): DXIL allows two. + let bary = |e: &SigElement| e.kind == 28; + let id = match self + .s + .inputs + .iter() + .position(|e| bary(e) && (e.interp == mode || e.usage == 0)) + { + Some(id) => id, + None => { + let index = self.s.inputs.iter().filter(|e| bary(e)).count() as u32; + if index >= 2 { + return Val::Missing("barycentrics of a third interpolation mode"); + } + // A system value the validator wants unpacked (packing + // location -1), like other non-packed system values. + self.s.inputs.push(SigElement { + name: "SV_Barycentrics".into(), + index, + kind: 28, + comp: 9, + interp: mode, + row: None, + col: 0, + cols: 3, + usage: 0, + half: false, + }); + self.s.inputs.len() - 1 + } + }; + let e = &mut self.s.inputs[id]; + if e.col != 0 || e.cols < 3 { + return Val::Missing("a console barycentrics element without i and j"); + } + e.row = None; + e.interp = mode; + self.s.flags |= flags::BARYCENTRICS; + self.load_any_input(id, index + 1) + } + fn i32_of(&mut self, v: Value) -> Result { match self.get(v)? { Val::I32(x) => Ok(x), @@ -1148,7 +2241,7 @@ impl<'a> Lower<'a> { RootType::Constants | RootType::Table => {} _ => return Val::Missing("a root descriptor"), } - let index = u32::from(rp.user_data) + dword; + let index = u32::from(rp.user_data) + dword - self.user_first(); self.user_reads.insert( index, UserData { @@ -1158,6 +2251,63 @@ impl<'a> Lower<'a> { dword, }, ); + Val::I32(self.user_at(index)) + } + + /// The user-data index that is dword 0 of the host's user data: 0, or + /// 16 for a program with a spilled user-data table, whose parameters + /// all sit at 16 and above. (The host's root signature has 64 dwords: + /// a builder stage with constants up to index 45, eight root views, + /// their biases and the memory directory would not fit with 16 dwords + /// nothing reads in front.) + fn user_first(&self) -> u32 { + if crate::spill::is_spilled(self.x.native) { + 16 + } else { + 0 + } + } + + /// A user-data dword no register of the console's holds: one the host + /// computes when it binds (`root` says what, an `Other` code of + /// `shader.rs`), placed after the layout's own dwords. + fn host_word(&mut self, root: RootType, slot: u8, dword: u32) -> V { + let known = self + .user_reads + .values() + .find(|u| u.root == root && u.slot == slot && u.dword == dword) + .map(|u| u.index); + let index = match known { + Some(index) => index, + None => { + let first = self.user_first(); + let layout = &self.x.native.layout; + let mut index = layout + .iter() + .map(|e| u32::from(e.user_data) + e.sgprs) + .max() + .unwrap_or(0) + .saturating_sub(first); + while self.user_reads.contains_key(&index) { + index += 1; + } + self.user_reads.insert( + index, + UserData { + index, + slot, + root, + dword, + }, + ); + index + } + }; + self.user_at(index) + } + + /// User-data dword `index`, loaded in the entry block. + fn user_at(&mut self, index: u32) -> V { self.s.user_data = self.s.user_data.max(index + 1); let h = match self.user_data { Some(h) => h, @@ -1177,7 +2327,409 @@ impl<'a> Lower<'a> { 59, &[h, row], ); - Val::I32(self.s.m.extract(entry, r, index % 4)) + self.s.m.extract(entry, r, index % 4) + } + + /// Whether some instruction computes with `v` (scalar or vector + /// arithmetic), rather than only naming it in a descriptor operand, + /// moving it (at most `depth` moves are followed) or comparing it: a + /// waterfall loop keeps a descriptor's dwords per lane, reads the first + /// lane's back and compares the lanes' with them. + fn computed_with(&self, v: Value, depth: u32) -> bool { + self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| { + if !i.reads.iter().any(|r| r.1 == v) { + return false; + } + let name = i.name(); + let moves = matches!( + name, + "s_mov_b32" + | "s_mov_b64" + | "v_mov_b32" + | "v_readfirstlane_b32" + | "v_readlane_b32" + | "v_writelane_b32" + | "v_cndmask_b32" + ); + match &i.fields { + Fields::Sop { .. } | Fields::Valu(_) if moves => { + depth > 0 && i.writes.iter().any(|w| self.computed_with(w.1, depth - 1)) + } + Fields::Sop { .. } | Fields::Valu(_) => { + !(name.starts_with("v_cmp") || name.starts_with("s_cmp")) + } + _ => false, + } + }) + } + + /// The title address (low dword, bits from 32 up) of the buffer view + /// whose descriptor the scalar load at `site` reads from the start of + /// a table entry, as the host tells it when it binds (`shader.rs` + /// `USER_VIEW_ADDRESS`); none for anything else. (The console's + /// descriptor holds more in the second dword, the stride from bit 16 + /// up; code that takes the address masks those away.) + fn view_address(&mut self, site: Site) -> Option<(V, V)> { + use super::shader::USER_VIEW_ADDRESS; + let a = self.scalar.get(&site).copied()?; + let rp = *self.x.native.layout.get(a.param)?; + if rp.root != RootType::Table || a.dynamic.is_some() || a.offset % 32 != 0 { + return None; + } + let dword = a.offset / 4; + let used = self + .x + .native + .used + .iter() + .filter(|u| { + u.root == RootType::Table + && u.user_data == rp.user_data + && u.table_offset_dwords <= dword + }) + .max_by_key(|u| u.table_offset_dwords)?; + if used.dwords != 4 || !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) { + return None; + } + let lo = self.host_word(RootType::Other(USER_VIEW_ADDRESS), rp.slot, dword); + let hi = self.host_word(RootType::Other(USER_VIEW_ADDRESS + 1), rp.slot, dword); + Some((lo, hi)) + } + + /// `lo`, `hi` plus the instruction's byte offset `off`, with the carry. + fn address_plus(&mut self, lo: V, hi: V, off: i32) -> (V, V) { + if off == 0 { + return (lo, hi); + } + let c = self.cur; + let i32t = self.s.t.i32; + let k = self.s.m.i32(off as u32); + let sum = self.s.m.bin(c, Bin::Add, lo, k); + // Up: a carry when the sum wrapped below `lo`. Down: a borrow when + // it wrapped above. + let wrapped = self + .s + .m + .cmp(c, if off > 0 { pred::IULT } else { pred::IUGT }, sum, lo); + let one = self.s.m.cast(c, Cast::ZExt, wrapped, i32t); + let hi = self.s.m.bin(c, if off > 0 { Bin::Add } else { Bin::Sub }, hi, one); + (sum, hi) + } + + /// Title memory at the 40-bit address `lo`, `hi` (`shader.rs` + /// `SLOT_MEMORY`): the handle of the raw view of the host copy holding + /// it and the byte in that view. A page without a copy reads zeros + /// (and drops writes) through the null view at the first slot, and its + /// number is left for the host, for lanes that run (`guard`). + fn memory(&mut self, lo: V, hi: V, guard: Option) -> (V, V) { + use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE}; + let c = self.cur; + let (i32t, res) = (self.s.t.i32, self.s.t.res_ret); + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (k16, k8) = (k(self, 16), k(self, 0xFF)); + let low = self.s.m.bin(c, Bin::LShr, lo, k16); + let high = self.s.m.bin(c, Bin::And, hi, k8); + let high = self.s.m.bin(c, Bin::Shl, high, k16); + let page = self.s.m.bin(c, Bin::Or, low, high); + // Inside the directory whatever the address (lanes that do not run + // compute one too); its last entry is never filled. + let last = k(self, MEMORY_PAGES - 1); + let page = self + .s + .op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[page, last]); + let k3 = k(self, 3); + let at = self.s.m.bin(c, Bin::Shl, page, k3); + let directory = self.s.root_srv_handle(SLOT_MEMORY); + let (iu, both, align) = (self.s.m.undef(i32t), self.s.m.i8(3), k(self, 4)); + let entry = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[directory, at, iu, both, align], + ); + let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1)); + let (copy, start) = (self.as_int(copy), self.as_int(start)); + // A page without a copy: its number, at a place by the number, or + // at the sink for lanes that do not run and pages that have one. + let zero = k(self, 0); + let mut missing = self.s.m.cmp(c, pred::EQ, copy, zero); + if let Some(g) = guard { + missing = self.s.m.bin(c, Bin::And, missing, g); + } + let places = k(self, MEMORY_FAULTS - 1); + let place = self.s.m.bin(c, Bin::URem, page, places); + let one = k(self, 1); + let place = self.s.m.bin(c, Bin::Add, place, one); + let k2 = k(self, 2); + let place = self.s.m.bin(c, Bin::Shl, place, k2); + let place = self.s.m.select(c, missing, place, zero); + let faults = self.s.root_uav_handle(SLOT_FAULTS); + let void = self.s.t.void; + let mask = self.s.m.i8(1); + self.s.op( + c, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &[faults, place, iu, page, iu, iu, iu, mask, align], + ); + let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0); + let slot = self.s.m.bin(c, Bin::Add, base, copy); + let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0)); + let k64k = k(self, 0xFFFF); + let within = self.s.m.bin(c, Bin::And, lo, k64k); + let byte = self.s.m.bin(c, Bin::Add, start, within); + (h, byte) + } + + /// `global_load_*`, `global_store_*` and `global_atomic_*` on title + /// memory by address (`resource::MEMORY`): the address is the VGPR + /// pair, each lane its own. + fn memory_flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Flat { + dst, + addr, + data, + saddr, + offset, + lds, + cache, + } = &inst.fields + else { + unreachable!() + }; + if *lds || !matches!(saddr, None | Some(Operand::Scalar { code: NULL, .. })) { + return Err("a global address with a scalar base"); + } + let Some(Operand::Vector { reg: areg, .. }) = *addr else { + return Err("a global address not in VGPRs"); + }; + let word = |l: &mut Self, k: u8| -> Result { + let v = inst.read(Reg::V(areg + k)).ok_or("a global address")?; + l.i32_of(v) + }; + let (lo, hi) = (word(self, 0)?, word(self, 1)?); + let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset)); + let guard = self.guard(b, i)?; + let c = self.cur; + let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void); + let iu = self.s.m.undef(i32t); + let align = self.s.m.i32(4); + let name = inst.name(); + let count = |rest: &str| match rest { + "dword" => Ok(1u8), + "dwordx2" => Ok(2), + "dwordx3" => Ok(3), + "dwordx4" => Ok(4), + _ => Err(name), + }; + if let Some(rest) = name.strip_prefix("global_load_") { + let n = count(rest)?; + let Some(Operand::Vector { reg, .. }) = *dst else { + return Err("a global load result"); + }; + let (h, byte) = self.memory(lo, hi, guard); + let mask = self.s.m.i8((1u8 << n) - 1); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[h, byte, iu, mask, align], + ); + for k in 0..n { + let x = self.s.m.extract(c, r, u32::from(k)); + let x = self.as_int(x); + self.write(inst, Reg::V(reg + k), x, guard); + } + return Ok(()); + } + if let Some(rest) = name.strip_prefix("global_store_") { + let n = count(rest)?; + let d = data.as_ref().ok_or("global store data")?; + let vals = self.vgprs(inst, d, n)?; + let (h, byte) = self.memory(lo, hi, guard); + let mut args = vec![h, byte, iu]; + args.extend(&vals); + args.resize(3 + 4, iu); + args.push(self.s.m.i8((1u8 << n) - 1)); + args.push(align); + let at = self.begin_guarded(guard); + self.s + .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args); + self.end_guarded(at, &[]); + return Ok(()); + } + let Some(op) = name.strip_prefix("global_atomic_") else { + return Err(name); + }; + let d = data.as_ref().ok_or("global atomic data")?; + let v = self.vgprs(inst, d, 1)?[0]; + // With `glc` the value from before comes back, in the result + // register the instruction names. + let back = match (*dst, cache.glc) { + (Some(Operand::Vector { reg, .. }), true) => Some(reg), + _ => None, + }; + let old = match back.and_then(|reg| inst.read(Reg::V(reg))) { + Some(x) => self.i32_of(x)?, + None => self.s.m.i32(0), + }; + let (h, byte) = self.memory(lo, hi, guard); + // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed + // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8. + let simple = match op { + "add" => Some((0, v)), + "sub" => { + let zero = self.s.m.i32(0); + Some((0, self.s.m.bin(c, Bin::Sub, zero, v))) + } + "and" => Some((1, v)), + "or" => Some((2, v)), + "xor" => Some((3, v)), + "smin" => Some((4, v)), + "smax" => Some((5, v)), + "umin" => Some((6, v)), + "umax" => Some((7, v)), + "swap" => Some((8, v)), + "fmin" | "fmax" => None, + _ => return Err(name), + }; + let at = self.begin_guarded(guard); + let was = match simple { + Some((code, x)) => { + let code = self.s.m.i32(code); + self.s.op( + self.cur, + "atomicBinOp.i32", + Attr::NoUnwind, + i32t, + 78, + &[h, code, byte, iu, iu, x], + ) + } + None => { + // A float minimum or maximum has no atomic operation on + // the host: the dword is exchanged for the smaller (larger) + // of itself and the value until no other thread got in + // between. Each failed pass means another one's succeeded; + // the limit only keeps a broken card from hanging. + let head = self.cur; + let mask = self.s.m.i8(1); + let first = self.s.op( + head, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[h, byte, iu, mask, align], + ); + let first = self.s.m.extract(head, first, 0); + let first = self.as_int(first); + let (pass, done) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(head, Term::Br(pass)); + self.cur = pass; + let seen = self.s.m.phi(pass, i32t); + let n = self.s.m.phi(pass, i32t); + let (f32t, fv) = (self.s.t.f32, self.as_float(v)); + let fseen = self.as_float(seen); + // `dx.op.binary`: FMax 35, FMin 36. + let pick = if op == "fmin" { 36 } else { 35 }; + let wanted = self + .s + .op(pass, "binary.f32", Attr::ReadNone, f32t, pick, &[fseen, fv]); + let wanted = self.as_int(wanted); + let found = self.s.op( + pass, + "atomicCompareExchange.i32", + Attr::NoUnwind, + i32t, + 79, + &[h, byte, iu, iu, seen, wanted], + ); + let one = self.s.m.i32(1); + let n1 = self.s.m.bin(pass, Bin::Add, n, one); + let lost = self.s.m.cmp(pass, pred::NE, found, seen); + let limit = self.s.m.i32(1 << 16); + let more = self.s.m.cmp(pass, pred::IULT, n1, limit); + let again = self.s.m.bin(pass, Bin::And, lost, more); + self.s.m.terminate(pass, Term::CondBr(again, pass, done)); + let zero = self.s.m.i32(0); + self.s.m.set_phi(seen, vec![(first, head), (found, pass)]); + self.s.m.set_phi(n, vec![(zero, head), (n1, pass)]); + self.cur = done; + found + } + }; + let was = self.end_guarded(at, &[(was, old)])[0]; + if let Some(reg) = back { + self.write(inst, Reg::V(reg), was, None); + } + Ok(()) + } + + /// `s_load_dword*` from title memory by address (`resource::MEMORY`): + /// the SGPR pair plus the instruction's offsets. + fn memory_smem(&mut self, inst: &Inst) -> Result<(), Why> { + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + base: Operand::Scalar { code: base, .. }, + offset, + soffset, + .. + } = inst.fields + else { + return Err("a scalar load from memory"); + }; + let count = match inst.name().strip_prefix("s_load_dword") { + Some("") => 1u8, + Some("x2") => 2, + Some("x4") => 4, + Some("x8") => 8, + Some("x16") => 16, + _ => return Err("a scalar memory access by address"), + }; + let word = |l: &mut Self, k: u8| -> Result { + let v = inst.read(Reg::S(base + k)).ok_or("an address not in SGPRs")?; + l.i32_of(v) + }; + let (mut lo, mut hi) = (word(self, 0)?, word(self, 1)?); + let c = self.cur; + let (i32t, res) = (self.s.t.i32, self.s.t.res_ret); + if !matches!(soffset, Operand::Scalar { code: NULL, .. }) { + // An offset register counts up from the address. + let so = self.operand(inst, &soffset)?; + let sum = self.s.m.bin(c, Bin::Add, lo, so); + let carry = self.s.m.cmp(c, pred::IULT, sum, lo); + let carry = self.s.m.cast(c, Cast::ZExt, carry, i32t); + hi = self.s.m.bin(c, Bin::Add, hi, carry); + lo = sum; + } + let (iu, align) = (self.s.m.undef(i32t), self.s.m.i32(4)); + for first in (0..count).step_by(4) { + let n = (count - first).min(4); + let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first)); + let (h, byte) = self.memory(lo, hi, None); + let mask = self.s.m.i8((1u8 << n) - 1); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[h, byte, iu, mask, align], + ); + for k in 0..n { + let x = self.s.m.extract(c, r, u32::from(k)); + let x = self.as_int(x); + self.write(inst, Reg::S(code + first + k), x, None); + } + } + Ok(()) } /// A dword of a lane mask as a number: the ballot of the lanes' bits, @@ -1212,7 +2764,20 @@ impl<'a> Lower<'a> { .s .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]); self.s.flags |= flags::WAVE_OPS; - let xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1)); + let mut xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1)); + if self.exchange.is_some() { + // a host wave's ballot is its half's 32 bits: the halves exchange them + let b = self.def_block.get(&lo).copied(); + if self.local { + if !self.local_ok && !self.local_any { + return Err("a lane mask read as data in a half-wave"); + } + } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) { + // (a group of 32 or fewer has no other half to exchange with) + return Err("a lane mask exchanged where not every lane runs"); + } + xy = self.exchange_halves(at, xy.0); + } self.ballots.insert(lo, xy); xy } @@ -1241,15 +2806,13 @@ impl<'a> Lower<'a> { } } - /// GFX10 puts an inline f16 constant in the low half of the operand. + /// An operand read as f16 data: GFX10 puts an inline f16 constant in + /// the low half of the operand (upstream PR #637, checked there against + /// the instruction encodings; the half-and-half reading taken from PR + /// #458 gave the high half the constant too). fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result { match *op { - Operand::Const(c @ 240..=248) => { - let h = [ - 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, - ][usize::from(c - 240)]; - Ok(self.s.m.i32(h)) - } + Operand::Const(c @ 240..=248) => Ok(self.s.m.i32(inline_f16(c))), _ => self.operand(inst, op), } } @@ -1466,6 +3029,17 @@ impl<'a> Lower<'a> { self.s.m.select(c, keep, r, t) } + /// Whether an f32 value is NaN, tested in integer arithmetic so host + /// drivers (such as NVIDIA) do not fold `fcmp uno` away under fast-math. + fn is_nan_f32(&mut self, f: V) -> V { + let c = self.cur; + let bits = self.as_int(f); + let mask = self.s.m.i32(0x7FFF_FFFF); + let abs = self.s.m.bin(c, Bin::And, bits, mask); + let inf = self.s.m.i32(0x7F80_0000); + self.s.m.cmp(c, pred::IUGT, abs, inf) + } + /// The median of three. With a NaN among them the hardware gives the /// minimum of the three instead (the host's minimum skips NaNs, so that /// is the smallest number among them). @@ -1476,9 +3050,11 @@ impl<'a> Lower<'a> { let t = self.binary(36, hi, third); let median = self.binary(35, lo, t); let least = self.binary(36, lo, third); - let ab = self.s.m.cmp(c, pred::UNO, a, b); - let nan3 = self.s.m.cmp(c, pred::UNO, third, third); - let nan = self.s.m.bin(c, Bin::Or, ab, nan3); + let nan_a = self.is_nan_f32(a); + let nan_b = self.is_nan_f32(b); + let nan_3 = self.is_nan_f32(third); + let nan_ab = self.s.m.bin(c, Bin::Or, nan_a, nan_b); + let nan = self.s.m.bin(c, Bin::Or, nan_ab, nan_3); self.s.m.select(c, nan, least, median) } @@ -1644,16 +3220,149 @@ impl<'a> Lower<'a> { } } + /// A console wave64 program in host waves of 32: the first console thread of this host wave + /// (0, 32, 64, ...). A GPU need not give a host wave consecutive thread indices (NVIDIA's + /// 8 x 8 groups), so each wave takes the next 32 from an LDS counter instead: every thread + /// zeroes it, the group meets, each wave's first lane adds 32 and the wave takes what it + /// found. Branch-free, in the entry block, which every thread runs. + fn wave_base(&mut self) -> Option { + let slot = self.halves?; + if let Some(v) = self.wave_base { + return Some(v); + } + let (e, i32t) = (self.s.entry, self.s.t.i32); + let lds = self.s.lds(); + let k = self.s.m.i32(slot); + let ptr = self.s.m.element(e, lds, k); + let zero = self.s.m.i32(0); + self.s.m.store(e, ptr, zero); + self.group_sync(e); + let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let first = self.s.m.cmp(e, pred::EQ, lane, zero); + let k32 = self.s.m.i32(32); + let add = self.s.m.select(e, first, k32, zero); + let ptr = self.s.m.element(e, lds, k); + let old = self.s.m.atomic(e, Rmw::Add, ptr, add); + let base = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[old]); + self.s.flags |= flags::WAVE_OPS; + self.wave_base = Some(base); + Some(base) + } + + /// The console thread index of this thread in the group: `wave_base` plus the host lane + /// (host waves of 32), else the wave's first thread index rounded down plus the lane. + fn console_thread(&mut self) -> V { + let (e, i32t) = (self.s.entry, self.s.t.i32); + let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + if let Some(base) = self.wave_base() { + return self.s.m.bin(e, Bin::Add, base, lane); + } + let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]); + let first = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[flat]); + let wave = self.s.wave_size.unwrap_or(32); + let mask = self.s.m.i32(!(wave - 1)); + let base = self.s.m.bin(e, Bin::And, first, mask); + self.s.m.bin(e, Bin::Add, base, lane) + } + + /// This thread's console lane (0..63): its relabelled thread index (`thread_id`), whose host + /// wave holds a 32-aligned run of console lanes. Without `exchange`: the host lane. + fn console_lane(&mut self) -> V { + if self.exchange.is_none() { + return self.lane_index(); + } + if let Some(v) = self.clane { + return v; + } + let (e, i32t) = (self.s.entry, self.s.t.i32); + let f = self.console_thread(); + let _ = i32t; + let k63 = self.s.m.i32(63); + let cl = self.s.m.bin(e, Bin::And, f, k63); + self.s.flags |= flags::WAVE_OPS; + self.clane = Some(cl); + cl + } + + /// A group barrier with an LDS fence in `block`. + fn group_sync(&mut self, block: usize) { + let mode = self.s.m.i32(meeting_mode()); + let void = self.s.t.void; + self.s.op(block, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } + + /// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get + /// (lower half's, upper half's). A group with no upper half gets 0 for it. + fn exchange_halves(&mut self, at: usize, mine: V) -> (V, V) { + let Some((slot, small, _)) = self.exchange.as_ref().map(|(a, b, _)| (*a, *b, ())) else { + let z = self.s.m.i32(0); + return (mine, z); + }; + if small { + let z = self.s.m.i32(0); + return (mine, z); + } + if self.local { + // each host wave on its own: its half holds `mine`, the other nothing + let cl = self.console_lane(); + let (k32, z) = (self.s.m.i32(32), self.s.m.i32(0)); + let upper = self.s.m.cmp(at, pred::IUGE, cl, k32); + let lo = self.s.m.select(at, upper, z, mine); + let hi = self.s.m.select(at, upper, mine, z); + return (lo, hi); + } + // the pair of dwords of this thread's console wave: its half's, then both + let pair = self.exchange_pair(slot); + let cl = self.console_lane(); + let five = self.s.m.i32(5); + let half = self.s.m.bin(at, Bin::LShr, cl, five); + let index = self.s.m.bin(at, Bin::Add, pair, half); + let lds = self.s.lds(); + let ptr = self.s.m.element(at, lds, index); + self.s.m.store(at, ptr, mine); + self.group_sync(at); + let one = self.s.m.i32(1); + let k1 = self.s.m.bin(at, Bin::Add, pair, one); + let p0 = self.s.m.element(at, lds, pair); + let p1 = self.s.m.element(at, lds, k1); + let lo = self.s.m.load(at, p0); + let hi = self.s.m.load(at, p1); + // the slots are written again only after every thread read them + self.group_sync(at); + (lo, hi) + } + + /// The first of the two exchange dwords of this thread's console wave (made in the entry + /// block): a group of several console waves has a pair for each. + fn exchange_pair(&mut self, slot: u32) -> V { + if let Some(v) = self.pair { + return v; + } + let e = self.s.entry; + let thread = self.console_thread(); + let six = self.s.m.i32(6); + let wave = self.s.m.bin(e, Bin::LShr, thread, six); + let one = self.s.m.i32(1); + let twice = self.s.m.bin(e, Bin::Shl, wave, one); + let base = self.s.m.i32(slot); + let v = self.s.m.bin(e, Bin::Add, base, twice); + self.pair = Some(v); + v + } + + /// Whether every lane runs IR block `b` (always true without `exchange`). + fn all_lanes(&self, b: usize) -> bool { + self.exchange.as_ref().is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false)) + } + /// This lane's bit of the mask `lo`, `hi` (wave64). fn lane_bit(&mut self, at: usize, lo: V, hi: Option) -> V { - let lane = self.s.op( - at, - "waveGetLaneIndex", - Attr::ReadOnly, - self.s.t.i32, - 111, - &[], - ); + self.s.flags |= flags::WAVE_OPS; + let lane = if self.exchange.is_some() { + self.console_lane() + } else { + self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[]) + }; let (k31, k32, one, z) = ( self.s.m.i32(31), self.s.m.i32(32), @@ -1889,6 +3598,19 @@ impl<'a> Lower<'a> { let [x, y, _] = self.s.threads.expect("compute"); let e = self.s.entry; let i32t = self.s.t.i32; + if self.halves.is_some() { + let f = self.console_thread(); + self.s.flags |= flags::WAVE_OPS; + let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y)); + return Val::I32(match c { + 0 => self.s.m.bin(e, Bin::URem, f, xk), + 1 => { + let t = self.s.m.bin(e, Bin::UDiv, f, xk); + self.s.m.bin(e, Bin::URem, t, yk) + } + _ => self.s.m.bin(e, Bin::UDiv, f, xy), + }); + } let flat = self.s.op( e, "flattenedThreadIdInGroup.i32", @@ -1930,7 +3652,7 @@ impl<'a> Lower<'a> { // program's count are culled and vertices past it unused; this costs // the host the unused vertex and primitive slots. Pass the program's own // counts if that shows in frame time. - fn mesh_prologue(&mut self, mesh: super::shader::Mesh) -> Result<(), Why> { + fn mesh_prologue(&mut self, mut mesh: super::shader::Mesh) -> Result<(), Why> { let threads = self.s.threads.expect("mesh")[0]; if mesh.topology != 2 { return Err("a mesh shader not drawing triangles"); @@ -1938,6 +3660,27 @@ impl<'a> Lower<'a> { if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 { return Err("a mesh shader beyond the host's limits"); } + // D3D12 caps the outputs of the declared maxima at 32 KiB. Lane n + // writes only vertex n and primitive n, so maxima past the lanes are + // never reached: they come down to the lane count when the outputs + // do not fit. + use super::container::{MESH_OUTPUT_LIMIT, mesh_output_bytes}; + let (outputs, prims) = (&self.s.outputs, &self.s.prims); + let fits = |m: super::shader::Mesh| { + mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT + }; + if !fits(mesh) { + mesh.max_vertices = mesh.max_vertices.min(threads); + mesh.max_primitives = mesh.max_primitives.min(threads); + // shortcut: outputs past the cap even at the lane count are + // still emitted with the lower maxima (drivers take them); + // refuse them here if one hangs. + // Experiment (`VICTORY_MESH_OUTPUT_STRICT=1`): they are refused. + if !fits(mesh) && std::env::var_os("VICTORY_MESH_OUTPUT_STRICT").is_some() { + return Err("a mesh shader whose outputs pass the host's 32 KiB"); + } + self.s.mesh = Some(mesh); + } let e = self.s.entry; let void = self.s.t.void; let (v, p) = ( @@ -1947,18 +3690,33 @@ impl<'a> Lower<'a> { self.s .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]); let flat = self.mesh_thread(); - let guard = (threads > mesh.max_primitives).then(|| self.s.m.cmp(e, pred::IULT, flat, p)); - let at = self.begin_guarded(guard); let z = self.s.m.i32(0); - self.s.op( - self.cur, - "emitIndices", - Attr::NoUnwind, - void, - 169, - &[flat, z, z, z], - ); - self.end_guarded(at, &[]); + // Every primitive of the declared count starts culled, also those + // past the lanes (a count of 256 with 128 lanes): lane n culls + // primitives n, n + lanes, ... The host draws all it was promised, + // and one never written has whatever indices its memory held: long + // triangles over the whole target, each pixel of them shaded. + let passes = mesh.max_primitives.div_ceil(threads.max(1)); + for pass in 0..passes { + let index = if pass == 0 { + flat + } else { + let past = self.s.m.i32(pass * threads); + self.s.m.bin(self.cur, Bin::Add, flat, past) + }; + let guard = ((pass + 1) * threads > mesh.max_primitives) + .then(|| self.s.m.cmp(self.cur, pred::IULT, index, p)); + let at = self.begin_guarded(guard); + self.s.op( + self.cur, + "emitIndices", + Attr::NoUnwind, + void, + 169, + &[index, z, z, z], + ); + self.end_guarded(at, &[]); + } Ok(()) } @@ -2028,6 +3786,36 @@ impl<'a> Lower<'a> { r } + /// `x` in the first lane of this host wave where `guard` holds, and whether it has such a + /// lane: the console reads the first lane of EXEC, and a lane that got here with EXEC clear + /// (a guard, not a branch) is not one. With none, `x` of the wave's first lane here. + fn first_lane(&mut self, x: V, guard: Option) -> (V, V) { + let c = self.cur; + let i32t = self.s.t.i32; + self.s.flags |= flags::WAVE_OPS; + let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[x]); + let Some(g) = guard else { + return (first, self.s.m.bool(true)); + }; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]); + let (lo, hi) = (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1)); + let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32)); + // FirstbitLo (dx.op 32): the lowest set bit + let flo = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]); + let fhi = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]); + let fhi = self.s.m.bin(c, Bin::Add, fhi, k32); + let in_lo = self.s.m.cmp(c, pred::NE, lo, z); + let in_hi = self.s.m.cmp(c, pred::NE, hi, z); + let any = self.s.m.bin(c, Bin::Or, in_lo, in_hi); + let lane = self.s.m.select(c, in_lo, flo, fhi); + // no lane in EXEC: read this lane (one that is here); the read is not used + let me = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let lane = self.s.m.select(c, any, lane, me); + let at = self.read_lane(x, lane); + (self.s.m.select(c, any, at, first), any) + } + fn read_lane(&mut self, x: V, lane: V) -> V { self.s.op( self.cur, @@ -2127,6 +3915,42 @@ impl<'a> Lower<'a> { self.write(inst, Reg::V(reg), r, guard); return Ok(()); } + if name == "ds_bpermute_b32" { + // Backward permute: no LDS is touched. Each lane takes the data + // register of the lane its address names, (address + offset) / 4 + // within the wave; a source lane outside EXEC gives 0. (Grand + // Theft Auto VI's checkerboard shadow-mask generators read their + // neighbours' samples with it; without them every shadowed light + // was multiplied by an empty mask.) + // shortcut: a source lane that is not at this instruction on the + // host (it left through a branch, not a guard) is read as the + // host gives it; the console reads 0. + self.cross_lane(false)?; + if self.exchange.as_ref().is_some_and(|e| !e.1) { + // a console wave of 64 run as two host waves: the lane named + // may be in the other one + return Err("a lane permute across two host waves"); + } + let at = self.vgprs(inst, addr.as_ref().ok_or("a permute address")?, 1)?[0]; + let x = self.vgprs(inst, data.first().ok_or("a permute source")?, 1)?[0]; + let o = self.s.m.i32(offset); + let at = self.s.m.bin(c, Bin::Add, at, o); + let two = self.s.m.i32(2); + let src = self.s.m.bin(c, Bin::LShr, at, two); + let last = self.s.m.i32(self.wave() - 1); + let src = self.s.m.bin(c, Bin::And, src, last); + let x = match guard { + Some(g) => { + let z = self.s.m.i32(0); + self.s.m.select(c, g, x, z) + } + None => x, + }; + let r = self.read_lane(x, src); + let reg = dst_reg.ok_or("a permute result")?; + self.write(inst, Reg::V(reg), r, guard); + return Ok(()); + } if self.s.lds_dwords == 0 { return Err("LDS the program does not allocate"); } @@ -2158,6 +3982,81 @@ impl<'a> Lower<'a> { (u32::from(*offset1) * scale, w), ] }; + // Bytes and halves: the dword holding them, and their bit position + // in it (naturally aligned, so they never straddle dwords). + // `_d16` reads fill a register's low half (`_d16_hi` its high half) + // and keep the other; `_d16_hi` writes take the data's high half. + let base = name.trim_end_matches("_hi").trim_end_matches("_d16"); + let sub = match base { + "ds_read_u8" | "ds_read_i8" | "ds_write_b8" => Some(8u32), + "ds_read_u16" | "ds_read_i16" | "ds_write_b16" => Some(16), + _ => None, + }; + let sub = sub.filter(|_| { + base == name + || name.ends_with("_d16") && base.starts_with("ds_read") + || name.ends_with("_d16_hi") + }); + if let Some(bits) = sub { + let p = dword(self, offset); + let o = self.s.m.i32(offset); + let at = self.s.m.bin(c, Bin::Add, a, o); + let three = self.s.m.i32(3); + let byte = self.s.m.bin(c, Bin::And, at, three); + let sh = self.s.m.bin(c, Bin::Shl, byte, three); + let mask = self.s.m.i32((1u32 << bits) - 1); + if name.starts_with("ds_read") { + let reg = dst_reg.ok_or("an LDS read result")?; + let w = self.s.m.load(c, p); + let x = self.s.m.bin(c, Bin::LShr, w, sh); + let x = if base.contains("_i") { + let k = self.s.m.i32(32 - bits); + let x = self.s.m.bin(c, Bin::Shl, x, k); + self.s.m.bin(c, Bin::AShr, x, k) + } else { + self.s.m.bin(c, Bin::And, x, mask) + }; + let x = if base == name { + x + } else { + let old = match inst.read(Reg::V(reg)) { + Some(v) => self.i32_of(v)?, + None => self.s.m.i32(0), + }; + let half = self.s.m.i32(0xFFFF); + let x = self.s.m.bin(c, Bin::And, x, half); + let (x, keep) = if name.ends_with("_hi") { + let k16 = self.s.m.i32(16); + (self.s.m.bin(c, Bin::Shl, x, k16), half) + } else { + (x, self.s.m.i32(0xFFFF_0000)) + }; + let old = self.s.m.bin(c, Bin::And, old, keep); + self.s.m.bin(c, Bin::Or, old, x) + }; + self.write(inst, Reg::V(reg), x, guard); + } else { + // Clear, then set: two atomics, so lanes writing other + // bytes of the dword keep theirs. + let mut x = self.vgprs(inst, data.first().ok_or("an LDS write")?, 1)?[0]; + if name != base { + // The data's high half. + let k16 = self.s.m.i32(16); + x = self.s.m.bin(c, Bin::LShr, x, k16); + } + let x = self.s.m.bin(c, Bin::And, x, mask); + let x = self.s.m.bin(c, Bin::Shl, x, sh); + let m = self.s.m.bin(c, Bin::Shl, mask, sh); + let ones = self.s.m.i32(u32::MAX); + let keep = self.s.m.bin(c, Bin::Xor, m, ones); + use super::bitcode::Rmw; + let at = self.begin_guarded(guard); + self.s.m.atomic(self.cur, Rmw::And, p, keep); + self.s.m.atomic(self.cur, Rmw::Or, p, x); + self.end_guarded(at, &[]); + } + return Ok(()); + } if let Some(rest) = name.strip_prefix("ds_read") { let elements = if rest.starts_with('2') { pair(name) @@ -2218,7 +4117,7 @@ impl<'a> Lower<'a> { "min_u32" => Some(Rmw::UMin), "max_u32" => Some(Rmw::UMax), "wrxchg_b32" => Some(Rmw::Xchg), - "cmpst_b32" => None, + "cmpst_b32" | "max_f32" | "min_f32" => None, _ => return Err("an LDS operation"), }; let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0]; @@ -2232,6 +4131,19 @@ impl<'a> Lower<'a> { None => self.s.m.i32(0), }; let p = dword(self, offset); + if let Some(max) = match op.as_str() { + "max_f32" => Some(true), + "min_f32" => Some(false), + _ => None, + } { + let at = self.begin_guarded(guard); + let r = self.lds_float_min_max(p, v0, max); + let r = self.end_guarded(at, &[(r, outside)])[0]; + if let Some(reg) = dst_reg { + self.write(inst, Reg::V(reg), r, None); + } + return Ok(()); + } let at = self.begin_guarded(guard); let r = match rmw { Some(op) => self.s.m.atomic(self.cur, op, p, v0), @@ -2248,12 +4160,98 @@ impl<'a> Lower<'a> { Ok(()) } + /// `ds_max_f32` (`max`) or `ds_min_f32` on the LDS dword at `p` with + /// the float bits `data`; the old bits return. + /// + /// DXIL has no float atomics on group-shared memory, so this is a + /// compare-exchange loop around [`Lower::lds_float_pick`], which gives + /// what RDNA2 writes (measured on gfx1036, reported on the pull + /// request): an sNaN, data first, then memory, is written quieted; + /// otherwise a NaN loses to a number (two quiet NaNs give the data); + /// numbers compare as floats with -0 below +0. + // shortcut: f32 denormals compare as kept; with the console's MODE + // flushing them they would order as ±0 first (MODE is not modelled). + fn lds_float_min_max(&mut self, p: V, data: V, max: bool) -> V { + let pre = self.cur; + let init = self.s.m.load(pre, p); + let (lp, exit) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(pre, Term::Br(lp)); + let i32t = self.s.t.i32; + let old = self.s.m.phi(lp, i32t); + self.cur = lp; + let new = self.lds_float_pick(old, data, max); + let prev = self.s.m.cmpxchg(lp, p, old, new); + let done = self.s.m.cmp(lp, pred::EQ, prev, old); + self.s.m.set_phi(old, vec![(init, pre), (prev, lp)]); + self.s.m.terminate(lp, Term::CondBr(done, exit, lp)); + self.cur = exit; + old + } + + /// What `ds_max_f32` (`max`) or `ds_min_f32` writes over the dword + /// `mem` with `data` (float bits; see [`Lower::lds_float_min_max`]). + fn lds_float_pick(&mut self, mem: V, data: V, max: bool) -> V { + let c = self.cur; + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (abs_mask, inf, quiet, zero) = ( + k(self, 0x7FFF_FFFF), + k(self, 0x7F80_0000), + k(self, 0x40_0000), + k(self, 0), + ); + let nan = |l: &mut Self, x: V| { + let m = l.s.m.bin(c, Bin::And, x, abs_mask); + l.s.m.cmp(c, pred::IUGT, m, inf) + }; + let snan = |l: &mut Self, x: V| { + let n = nan(l, x); + let q = l.s.m.bin(c, Bin::And, x, quiet); + let sig = l.s.m.cmp(c, pred::EQ, q, zero); + l.s.m.bin(c, Bin::And, n, sig) + }; + // A total order of the numbers as signed integers, -0 below +0: + // negative floats' magnitude bits reversed. + let key = |l: &mut Self, x: V| { + let k31 = l.s.m.i32(31); + let sign = l.s.m.bin(c, Bin::AShr, x, k31); + let flip = l.s.m.bin(c, Bin::And, sign, abs_mask); + l.s.m.bin(c, Bin::Xor, x, flip) + }; + let (dk, mk) = (key(self, data), key(self, mem)); + let take = self + .s + .m + .cmp(c, if max { pred::SGT } else { pred::SLT }, dk, mk); + let r = self.s.m.select(c, take, data, mem); + let (dn, mn) = (nan(self, data), nan(self, mem)); + // One NaN: the number; two quiet NaNs: the data. + let r = self.s.m.select(c, mn, data, r); + let both = self.s.m.bin(c, Bin::And, dn, mn); + let only_data = { + let t = self.s.m.bool(true); + let not_both = self.s.m.bin(c, Bin::Xor, both, t); + self.s.m.bin(c, Bin::And, dn, not_both) + }; + let r = self.s.m.select(c, only_data, mem, r); + // Signalling NaNs win, quieted: the data's first. + let qm = self.s.m.bin(c, Bin::Or, mem, quiet); + let sm = snan(self, mem); + let r = self.s.m.select(c, sm, qm, r); + let qd = self.s.m.bin(c, Bin::Or, data, quiet); + let sd = snan(self, data); + self.s.m.select(c, sd, qd, r) + } + + // ---- instructions ---- // ---- instructions ---- fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> { let inst: &'a Inst = &self.x.p.blocks[b].insts[i]; let offset = inst.machine.offset; let name = inst.name(); + self.local_ok = name.starts_with("s_bcnt1_i32_") + || name.starts_with("s_ff1_i32_") + || name.starts_with("v_mbcnt_"); self.mask_ok = match self.mask_data { MaskData::Console => true, MaskData::Host => { @@ -2265,7 +4263,9 @@ impl<'a> Lower<'a> { "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64" ) } - MaskData::None => false, + // Mesh: only "do all lanes hold the first lane's value?" (`uniform_test`), which + // each host wave answers for itself. + MaskData::None => self.uniform_test(inst), }; let effect = matches!(inst.fields, Fields::Exp { .. }) || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") @@ -2276,6 +4276,17 @@ impl<'a> Lower<'a> { && !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || name.contains("permute")); + if self.split_lds + && matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_swizzle") || name.contains("permute")) + && self.lds_meet.as_ref().is_none_or(|(all, _)| all[b]) + { + // the two host waves of a console wave meet before each LDS access: what the other + // half wrote is visible, and what it still reads is not overwritten + let mode = self.s.m.i32(meeting_mode()); + let void = self.s.t.void; + self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } let r = match &inst.fields { Fields::Sop { .. } => self.sop(inst), Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()), @@ -2283,7 +4294,17 @@ impl<'a> Lower<'a> { // Thread-group sync with a shared-memory fence, and a UAV // fence when the program writes UAVs (the waits before an // s_barrier make those writes visible on the console). - let mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 }; + let mut mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 }; + // Without the wait for the group (bit 0) where not every + // lane arrives, or where the switch says so. + let waits = match super::group_sync() { + 0 => false, + 1 => !self.fence_only.contains(&b), + _ => true, + }; + if !waits { + mode &= !1; + } let mode = self.s.m.i32(mode); let void = self.s.t.void; self.s @@ -2295,6 +4316,15 @@ impl<'a> Lower<'a> { Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)), Fields::Valu(_) => self.valu(inst, b, i), Fields::Vintrp { .. } => self.interp(inst, (b, i)), + // The ray and node test. A failure is a refusal at once: an + // instruction without a side effect otherwise only stops the + // program where its results are needed, and two trace programs + // came out without their test that way. + Fields::Image { .. } if name.starts_with("image_bvh") => { + return self + .bvh(inst, b, i) + .map_err(|why| unsupported(offset, why)); + } Fields::Image { .. } => self.image(inst, b, i), Fields::Buffer { .. } => self.buffer(inst, b, i), Fields::Exp { .. } => self.export(b, i), @@ -2314,6 +4344,103 @@ impl<'a> Lower<'a> { } } + /// 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) { + let mode = self.s.m.i32(meeting_mode()); + let void = self.s.t.void; + self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } + + /// Whether `v` is a register no program reads as a number: a descriptor dword without + /// a host value ([`Self::stale`]), a lane mask's dword (outside compute, where a ballot + /// gives the mask as data), or a join of only such values. Compiled code joins numbers + /// with numbers: where one of these meets numbers at a join, the register is dead on + /// that path (a variable set in one arm of a branch, its use behind a flag kept in a + /// VGPR). + fn dead(&self, v: Value, seen: &mut Vec) -> bool { + if self.stale.contains(&v) { + return true; + } + let st = self.x.st; + if self.mask_data != MaskData::Console + && (st.masks.contains_key(&v) || st.highs.contains_key(&v)) + { + return true; + } + let Some(&(b, i)) = self.phi_at.get(&v) else { + return false; + }; + if seen.contains(&v) { + return true; + } + seen.push(v); + self.x.p.blocks[b].phis[i] + .args + .iter() + .all(|&a| self.dead(a, seen)) + } + + /// `s_bcnt1_i32_b*` of the lanes that differ from the first lane's value: + /// `v_readfirstlane_b32 s, v`, `v_cmp_eq_u32 m, s, v`, `s_xor_b* d, m, exec`. The + /// compiler tests a value for being the same in the whole wave this way, to take a + /// scalar path; both paths give each lane the same result, so the lanes of a host + /// wave may ask it of their own first lane, whatever the wave's size. + fn uniform_test(&self, inst: &Inst) -> bool { + let p = self.x.p; + let writer = |v: Value| -> Option<&'a Inst> { + let b = *self.def_block.get(&v)?; + p.blocks[b] + .insts + .iter() + .find(|i| i.writes.iter().any(|w| w.1 == v)) + }; + let scalar = |i: &Inst, op: &Operand| match *op { + Operand::Scalar { code, .. } if code != NULL && code != EXEC => i.read(Reg::S(code)), + _ => None, + }; + if !inst.name().starts_with("s_bcnt1_i32_") { + return false; + } + let Fields::Sop { src, .. } = &inst.fields else { + return false; + }; + let Some(xor) = src.first().and_then(|o| scalar(inst, o)).and_then(writer) else { + return false; + }; + let Fields::Sop { src, .. } = &xor.fields else { + return false; + }; + if !matches!(xor.name(), "s_xor_b64" | "s_xor_b32") + || !src + .iter() + .any(|o| matches!(o, Operand::Scalar { code: EXEC, .. })) + { + return false; + } + let Some(cmp) = src.iter().find_map(|o| scalar(xor, o)).and_then(writer) else { + return false; + }; + let Fields::Valu(f) = &cmp.fields else { + return false; + }; + if !matches!(cmp.name(), "v_cmp_eq_u32" | "v_cmp_eq_i32") || f.sdwa.is_some() || f.dpp.is_some() { + return false; + } + let lanes = f.src.iter().find_map(|o| match *o { + Operand::Vector { reg, .. } => cmp.read(Reg::V(reg)), + _ => None, + }); + let first = f.src.iter().find_map(|o| scalar(cmp, o)).and_then(writer); + lanes.is_some() + && first.is_some_and(|fl| { + fl.name() == "v_readfirstlane_b32" + && matches!(&fl.fields, Fields::Valu(g) + if matches!(g.src.first(), Some(&Operand::Vector { reg, .. }) + if fl.read(Reg::V(reg)) == lanes)) + }) + } + fn is_mask(&self, v: Option) -> bool { v.is_some_and(|v| self.x.st.masks.contains_key(&v)) } @@ -2341,6 +4468,19 @@ impl<'a> Lower<'a> { // vertex fetch call, whose results arrive as inputs. return Err("a register the emitter does not model"); } + if name == "s_getpc_b64" { + // The address of the next instruction is no number the host has: tables in + // the code are read by their tracked address. As a number the counter is + // that instruction's offset in the code, so an address paths join before + // one load is the byte in the code, whichever table each path took + // (resource tracking gives such a join as the computed term, with no base). + let z = self.s.m.i32(0); + let at = self.s.m.i32(inst.machine.offset as u32 + 4); + let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1))); + self.set(lo, Val::I32(at)); + self.set(hi, Val::I32(z)); + return Ok(()); + } let c = self.cur; let src32 = |l: &mut Self, k: usize| -> Result { // SOPK arithmetic reads its destination as the first source. @@ -2547,9 +4687,15 @@ impl<'a> Lower<'a> { Ok(()) } "s_mov_b64" => { - let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); - self.set(lo, Val::I32(a)); - self.set(hi, Val::I32(b)); + // Each half by itself: two numbers that travel as a pair (two scalars + // parked in neighbouring VGPR lanes, say) need not both have a value. + for (h, v) in [(0, lo), (1, hi)] { + let val = match half(self, 0, h) { + Ok(a) => Val::I32(a), + Err(why) => Val::Missing(why), + }; + self.set(v, val); + } Ok(()) } "s_cselect_b64" => { @@ -2809,6 +4955,9 @@ impl<'a> Lower<'a> { if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) { return self.code_smem(inst, a); } + if self.scalar.get(&site).is_some_and(|a| a.param == MEMORY) { + return self.memory_smem(inst); + } let Some(rest) = name.strip_prefix("s_buffer_load_dword") else { return self.descriptor_data(inst, site); }; @@ -2850,6 +4999,65 @@ impl<'a> Lower<'a> { } return Ok(()); } + // A buffer the program picks from the view heap by an index it + // computes (`ResourceHeap`) has no used-resource entry, and the + // heap holds a buffer view there, not a constant buffer: read as + // raw bytes, as a table's SRV is below. Read as a constant buffer + // (the host's validation: "Descriptor Type in Heap: SRV, Register + // Type: CBV", heap index 17) the loads gave nothing: Grand Theft + // Auto VI's meshlet culling (BatchCullMeshlets, + // BatchCullPreSkinnedMeshlets, BatchCullBatchCSMeshlets) reads its + // batch records, mesh headers and instance transforms this way, so + // it passed no meshlet and every indirect mesh draw ran empty. + // The host's table of strides by heap slot tells a buffer view + // (not 0) from anything else, which is still read as a constant + // buffer; only the load that fits the slot runs. + let picked = match kind { + None => self.slot_stride(src)?, + Some(_) => None, + }; + if let Some(stride) = picked { + let zero = self.s.m.i32(0); + let is_buffer = self.s.m.cmp(self.cur, pred::NE, stride, zero); + let at = self.begin_guarded(Some(is_buffer)); + let h = self.handle(site, src, false, (11, 0))?; + let mut raw = Vec::new(); + for k in 0..count { + let b = self.cur; + let off = self.s.m.i32(4 * k); + let a = self.s.m.bin(b, Bin::Add, addr, off); + let mask = self.s.m.i8(1); + let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + let r = self.s.op( + b, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, a, u, mask, al], + ); + let x = self.s.m.extract(b, r, 0); + let x = self.as_int(x); + raw.push((x, zero)); + } + let raw = self.end_guarded(at, &raw); + let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero); + let at = self.begin_guarded(Some(other)); + let h = self.handle(site, src, false, (13, 0x1_0000))?; + let mut both = Vec::new(); + for (k, &r) in raw.iter().enumerate() { + let b = self.cur; + let off = self.s.m.i32(4 * k as u32); + let a = self.s.m.bin(b, Bin::Add, addr, off); + let x = self.cbuffer_dword(h, a); + both.push((x, r)); + } + let both = self.end_guarded(at, &both); + for (k, x) in both.into_iter().enumerate() { + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { let h = self.handle(site, src, false, (11, 0))?; for k in 0..count { @@ -2943,20 +5151,91 @@ impl<'a> Lower<'a> { Some("x16") => 16, _ => return Err("a scalar memory read as data"), }; - // How the program uses the descriptor tells the view's kind. - let use_at = self - .x - .res - .descriptors - .iter() - .filter(|d| d.role == Role::Resource) - .find_map(|d| { - d.source.leaves().into_iter().find_map(|l| match *l { - Source::Loaded { load, first } if load == site => Some((d.site, first)), - _ => None, + // How the program uses the descriptor tells the view's kind: an image or buffer + // instruction before a scalar buffer load, which reads any buffer. + let x = self.x; + let uses = |of: Site| { + x.res + .descriptors + .iter() + .filter(|d| d.role == Role::Resource) + .filter_map(move |d| { + d.source.leaves().into_iter().find_map(|l| match *l { + Source::Loaded { load, first } if load == of => Some((d.site, first)), + _ => None, + }) }) - }); + }; + let by_scalar_load = |u: &(Site, u8)| { + matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. }) + }; + let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next()); + // The console compiler loads a descriptor again wherever it needs it, and for a + // size it reads the dwords of a load that nothing uses as a descriptor (a texture + // picked from the heap by an index held per lane: one load for its width, one for + // its base level, one for each read of the image). Another load of as many dwords + // from the same address reads the same descriptor, so what uses that one tells + // this one's kind. The handle is still made from this load's own operands, which + // hold here. + let address = self.scalar.get(&site).copied(); + let twin = || { + let a = address?; + let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name(); + x.res + .scalar + .iter() + .filter(|(s, b)| *s != site && *b == a && same(*s)) + .find_map(|(s, _)| use_of(*s)) + }; + let use_at = use_of(site).or_else(twin); let Some((at, first)) = use_at else { + // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only + // copies its dwords and compares them, lane against first lane, and every load + // that reaches those lanes reads one address. Each dword stands in as its place + // in the table, so the lanes compare equal as they do on the console. + if self.x.res.lane_copied.contains(&site) + && let Some(a) = self.scalar.get(&site).copied() + { + for k in 0..count { + let x = self.s.m.i32(a.offset / 4 + k); + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } + // A sampler's descriptor: no program reads its dwords as numbers, so where one + // meets numbers at a join the register is dead on that path (`dead`), as a + // descriptor's address or format is. + let sampler = x.res.descriptors.iter().any(|d| { + d.role == Role::Sampler + && d.source.leaves().into_iter().any( + |l| matches!(*l, Source::Loaded { load, .. } if load == site), + ) + }); + if sampler { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a sampler's descriptor read as data"); + } + // A buffer view the code only takes the address of, to walk + // the memory behind it (a ray-tracing structure): the address + // from the host, the other dwords have no value. + if count <= 4 + && let Some((lo, hi)) = self.view_address(site) + { + for k in 0..count { + let reg = Reg::S(code + k as u8); + match k { + 0 => self.write(inst, reg, lo, None), + 1 => self.write(inst, reg, hi, None), + _ => { + if let Some(v) = inst.write(reg) { + self.vals.insert(v, Val::Missing(OTHER)); + self.stale.insert(v); + } + } + } + } + return Ok(()); + } return Err("a descriptor read only as data"); }; let src = Source::Loaded { load: site, first }; @@ -2968,6 +5247,8 @@ impl<'a> Lower<'a> { || used.is_some_and(|u| u.kind == ResourceType::Uav); let u = if uav { 0x1000 } else { 0 }; let (props, image) = match &ui.fields { + // A ray-tracing structure in a buffer of the host: read raw. + Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None), Fields::Image { dim, .. } => { let kind = match dim { 0 => 1, @@ -2991,10 +5272,20 @@ impl<'a> Lower<'a> { (11 | u, 0) }; if used.is_some_and(|u| u.kind == ResourceType::Cbv) { + self.stale.extend(inst.writes.iter().map(|w| w.1)); return Err("a constant buffer's descriptor read as data"); } (props, None) } + // Read by scalar buffer loads alone: the raw view `smem` reads it through. + Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => { + ((11, 0), None) + } + // A constant buffer: nothing of its descriptor is a number. + Fields::Smem { .. } => { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a constant buffer's descriptor read as data"); + } _ => return Err("a scalar memory read as data"), }; let h = self.handle(site, &src, false, props)?; @@ -3047,7 +5338,31 @@ impl<'a> Lower<'a> { let d3 = self.s.m.bin(c, Bin::Or, base, last); vec![(1, d1), (2, d2), (3, d3), (4, depth)] } - None => vec![(2, field(self, 0))], + None => { + // A raw view counts bytes; the descriptor's record count is in elements. + let n = field(self, 0); + let stride = used.map_or(0, |u| u.stride); + let n = if props.0 & 0xFF == 11 && stride > 1 { + let k = self.s.m.i32(stride); + self.s.m.bin(c, Bin::UDiv, n, k) + } else { + n + }; + let mut words = vec![(2, n)]; + // Its address too, where the code computes with it and the + // host can tell it. + let computed = (0..2u8).any(|k| { + inst.write(Reg::S(code + first + k)) + .is_some_and(|v| self.computed_with(v, 6)) + }); + if first == 0 + && computed + && let Some((lo, hi)) = self.view_address(site) + { + words.extend([(0, lo), (1, hi)]); + } + words + } }; for k in 0..count { let rel = k.wrapping_sub(u32::from(first)); @@ -3056,6 +5371,7 @@ impl<'a> Lower<'a> { None => { if let Some(v) = inst.write(Reg::S(code + k as u8)) { self.vals.insert(v, Val::Missing(OTHER)); + self.stale.insert(v); } } } @@ -3082,8 +5398,19 @@ impl<'a> Lower<'a> { }; let c = self.cur; let mut addr = self.s.m.i32(a.offset); - if let Some(d) = a.dynamic { - let d = self.i32_of(d)?; + if let Some(value) = a.dynamic { + let mut d = self.i32_of(value)?; + // A term held per lane reached the address through + // `v_readfirstlane_b32`: the first lane's. + let per_lane = self.def_block.get(&value).is_some_and(|&b| { + let writes = |i: &Inst| i.writes.iter().any(|w| w.1 == value && matches!(w.0, Reg::V(_))); + self.x.p.blocks[b].insts.iter().any(writes) + }); + if per_lane { + self.s.flags |= flags::WAVE_OPS; + let i32t = self.s.t.i32; + d = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]); + } addr = self.s.m.bin(c, Bin::Add, addr, d); } for k in 0..count { @@ -3248,16 +5575,48 @@ impl<'a> Lower<'a> { fn built_offset(&mut self, src: &Source) -> Result<(u32, Option), Why> { match src { Source::Built { address, .. } => { - let x = match address.dynamic { + let mut x = match address.dynamic { Some(v) => Some(self.i32_of(v)?), None => None, }; + if let Some(bias) = self.root_bias(address.param) { + x = Some(match x { + Some(d) => self.s.m.bin(self.cur, Bin::Add, d, bias), + None => bias, + }); + } Ok((address.offset, x)) } _ => Ok((0, None)), } } + /// For a root view the host binds as a raw view that may begin before + /// the title's address (`shader.rs` `USER_VIEW_BIAS`): the bytes to add + /// to offsets through it. Every root UAV, and the root SRVs of programs + /// with a spilled user-data table (the others keep the views they + /// have). + fn root_bias(&mut self, param: usize) -> Option { + use super::shader::USER_VIEW_BIAS; + let rp = *self.x.native.layout.get(param)?; + if rp.root != RootType::Descriptor { + return None; + } + let kind = self + .x + .native + .used + .iter() + .find(|u| u.user_data == rp.user_data) + .map(|u| u.kind); + let biased = match kind { + Some(ResourceType::Uav) => true, + Some(ResourceType::Srv) => crate::spill::is_spilled(self.x.native), + _ => false, + }; + biased.then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0)) + } + /// The used-resource entry a descriptor loaded from a table falls in. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> { if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } = @@ -3308,7 +5667,7 @@ impl<'a> Lower<'a> { ) -> Result { match src { Source::Loaded { load, first } => { - let key = (self.cur, *load, *first, sampler, props.0); + let key = (self.cur, *load, *first, sampler, props); if let Some(&h) = self.handles.get(&key) { return Ok(h); } @@ -3363,30 +5722,22 @@ impl<'a> Lower<'a> { (RootType::Descriptor, Some(ResourceType::Srv), 11) => { Ok(self.s.root_srv_handle(rp.slot)) } - _ => Err("a root UAV or typed root view"), + // A root UAV: a raw buffer whether the access reads + // (11) or writes (11 with the UAV bit). Indexed + // accesses reach here as raw ones at index times the + // entry's stride (`buffer`). + (RootType::Descriptor, Some(ResourceType::Uav), 11 | 0x100b) => { + Ok(self.s.root_uav_handle(rp.slot)) + } + (RootType::Descriptor, Some(ResourceType::Srv), 0x100b) => { + Err("a write through a root SRV") + } + _ => Err("a typed root view"), } } Source::Phi { block, args } => { - // Each predecessor computes its heap index at its end; the - // join picks one with a phi. let _ = site; - let mut incoming = Vec::new(); - for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { - if self.block[q].is_none() { - continue; - } - let (Some(tail), Source::Loaded { load, first }) = (self.tail[q], arg) else { - return Err("a descriptor chosen by control flow"); - }; - let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); - let here = std::mem::replace(&mut self.cur, at); - let index = self.heap_index(*load, *first, sampler); - self.cur = here; - incoming.push((index?, at)); - } - let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; - let phi = self.s.m.phi(join, self.s.t.i32); - self.s.m.set_phi(phi, incoming); + let phi = self.descriptor_phi(*block, args, sampler, 8)?; Ok(self.s.heap_handle(self.cur, phi, sampler, false, props)) } Source::Select { scc, args } => { @@ -3417,6 +5768,94 @@ impl<'a> Lower<'a> { } } + /// The heap index a descriptor phi picks. Each predecessor computes its + /// heap index at its end and the join picks one with a phi; a + /// predecessor whose descriptor is itself chosen by control flow (a + /// phi of an earlier join, which dominates it) gives that join's phi, + /// at most `depth` joins deep. + fn descriptor_phi( + &mut self, + block: usize, + args: &[Source], + sampler: bool, + depth: u32, + ) -> Result { + const WHY: Why = "a descriptor chosen by control flow"; + let p = self.x.p; + let mut incoming = Vec::new(); + for (&q, arg) in p.blocks[block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let tail = self.tail[q].ok_or(WHY)?; + let at = self.edges.get(&(q, block)).copied().unwrap_or(tail); + let index = match arg { + Source::Loaded { load, first } => { + let here = std::mem::replace(&mut self.cur, at); + let index = self.heap_index(*load, *first, sampler); + self.cur = here; + index? + } + Source::Phi { block: inner, args: inner_args } if depth > 0 => { + self.descriptor_phi(*inner, inner_args, sampler, depth - 1)? + } + _ => return Err(WHY), + }; + incoming.push((index, at)); + } + let join = self.block[block].ok_or(WHY)?; + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) + } + + /// The bytes per element of the buffer view `src` names, if the program + /// picks it from the view heap at an index it computes (root type + /// `ResourceHeap`): read from the host's table by heap slot in the + /// current block. + fn slot_stride(&mut self, src: &Source) -> Result, Why> { + let Source::Loaded { load, first } = src else { + return Ok(None); + }; + let heap = self + .scalar + .get(load) + .and_then(|a| self.x.native.layout.get(a.param)) + .is_some_and(|p| p.root == RootType::ResourceHeap); + if !heap { + return Ok(None); + } + let key = (self.cur, *load, *first); + if let Some(&v) = self.strides.get(&key) { + return Ok(Some(v)); + } + let c = self.cur; + let slot = self.heap_index(*load, *first, false)?; + // Inside the table whatever the index (lanes that do not run + // compute one too): a root view has no bounds of its own. + let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1); + let i32t = self.s.t.i32; + let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]); + let two = self.s.m.i32(2); + let byte = self.s.m.bin(c, Bin::Shl, slot, two); + let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES); + let iu = self.s.m.undef(self.s.t.i32); + let mask = self.s.m.i8(1); + let align = self.s.m.i32(4); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, byte, iu, mask, align], + ); + let f = self.s.m.extract(c, r, 0); + let v = self.as_int(f); + self.strides.insert(key, v); + Ok(Some(v)) + } + /// The heap index of a descriptor that may differ between lanes, /// computed in the current block (or, chosen by control flow, at the /// join). @@ -3744,6 +6183,36 @@ impl<'a> Lower<'a> { return self.packed16(inst, op, guard); } match name { + "v_mad_u64_u32" => { + // a * b + c, c and the result 64 bits wide; the carry out + // of the sum is this lane's bit of the mask it names. + let (a, b) = (s(self, 0)?, s(self, 1)?); + let x = self.src64(inst, 2)?; + let i64t = self.s.m.int(64); + self.s.flags |= flags::INT64; + let a = self.s.m.cast(c, Cast::ZExt, a, i64t); + let b = self.s.m.cast(c, Cast::ZExt, b, i64t); + let product = self.s.m.bin(c, Bin::Mul, a, b); + let r = self.s.m.bin(c, Bin::Add, product, x); + let carry = self.s.m.cmp(c, pred::IULT, r, x); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 64-bit result"); + }; + let (lo, hi) = self.split64(r); + self.write(inst, Reg::V(reg), lo, guard); + self.write(inst, Reg::V(reg + 1), hi, guard); + if let Some(Operand::Scalar { code, .. }) = v.carry + && let Some(w) = inst.write(Reg::S(code)) + { + self.lane_bits.insert(w, carry); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + Ok(()) + } "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => { let n = s(self, 0)?; let x = self.src64(inst, 1)?; @@ -3922,6 +6391,152 @@ impl<'a> Lower<'a> { let r = self.fmad(a, bb, cc); float(self, r) } + "v_div_scale_f32" => { + // RDNA2 ISA: src0 = value to scale, src1 = denominator, src2 = numerator. + let (a, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let (ai, ni, di) = (self.as_int(a), self.as_int(num), self.as_int(den)); + let (k23, k255, kabs) = ( + self.s.m.i32(23), + self.s.m.i32(0xFF), + self.s.m.i32(0x7FFF_FFFF), + ); + let (zero, k23_exp, k232_exp, k96) = ( + self.s.m.i32(0), + self.s.m.i32(23), + self.s.m.i32(232), + self.s.m.i32(96), + ); + let exp_of = |l: &mut Self, x: V| { + let s = l.s.m.bin(c, Bin::LShr, x, k23); + l.s.m.bin(c, Bin::And, s, k255) + }; + let (e1, e2) = (exp_of(self, ni), exp_of(self, di)); + let n_abs = self.s.m.bin(c, Bin::And, ni, kabs); + let d_abs = self.s.m.bin(c, Bin::And, di, kabs); + let z1 = self.s.m.cmp(c, pred::EQ, n_abs, zero); + let z2 = self.s.m.cmp(c, pred::EQ, d_abs, zero); + let any_zero = self.s.m.bin(c, Bin::Or, z1, z2); + let special = { + let s1 = self.s.m.cmp(c, pred::EQ, e1, k255); + let s2 = self.s.m.cmp(c, pred::EQ, e2, k255); + let a12 = self.s.m.bin(c, Bin::Or, s1, s2); + self.s.m.bin(c, Bin::Or, a12, any_zero) + }; + let is_den = self.s.m.cmp(c, pred::EQ, ai, di); + let diff = self.s.m.bin(c, Bin::Sub, e2, e1); + let den_tiny = self.s.m.cmp(c, pred::IULE, e2, k23_exp); + let den_huge = self.s.m.cmp(c, pred::IUGE, e2, k232_exp); + let num_tiny_exp = self.s.m.cmp(c, pred::IULE, e1, k23_exp); + let num_huge = self.s.m.cmp(c, pred::IUGE, e1, k232_exp); + let num_gap = self.s.m.cmp(c, pred::SGE, diff, k96); + let not_den_huge = { + let t = self.s.m.bool(true); + self.s.m.bin(c, Bin::Xor, den_huge, t) + }; + let num_gap = self.s.m.bin(c, Bin::And, num_gap, not_den_huge); + let num_tiny = self.s.m.bin(c, Bin::Or, num_tiny_exp, num_gap); + let up_raw = self.s.m.select(c, is_den, den_tiny, num_tiny); + let dn_raw = self.s.m.select(c, is_den, den_huge, num_huge); + let not_special = { + let t = self.s.m.bool(true); + self.s.m.bin(c, Bin::Xor, special, t) + }; + let up = self.s.m.bin(c, Bin::And, up_raw, not_special); + let dn = self.s.m.bin(c, Bin::And, dn_raw, not_special); + let uncancelled = { + let x_tiny = self.s.m.bin(c, Bin::Xor, den_tiny, num_tiny); + let x_huge = self.s.m.bin(c, Bin::Xor, den_huge, num_huge); + self.s.m.bin(c, Bin::Or, x_tiny, x_huge) + }; + let flag_raw = self.s.m.select(c, is_den, uncancelled, up_raw); + let flag = self.s.m.bin(c, Bin::And, flag_raw, not_special); + let k_up = self.s.m.f32(0x5F80_0000); + let k_dn = self.s.m.f32(0x1F80_0000); + let a_up = self.s.m.bin(c, Bin::Mul, a, k_up); + let a_dn = self.s.m.bin(c, Bin::Mul, a, k_dn); + let r = self.s.m.select(c, dn, a_dn, a); + let r = self.s.m.select(c, up, a_up, r); + let qnan = self.s.m.f32(0x7FC0_0000); + let r = self.s.m.select(c, any_zero, qnan, r); + float(self, r)?; + if let Some(Operand::Scalar { code, .. }) = v.carry + && let Some(w) = inst.write(Reg::S(code)) + { + self.lane_bits.insert(w, flag); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + Ok(()) + } + "v_div_fmas_f32" => { + let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let m = inst + .read(Reg::S(crate::ir::VCC)) + .and_then(|v| self.x.st.masks.get(&v).copied()) + .ok_or("v_div_fmas_f32 without VCC")?; + let vcc = self.boolean(m, c)?; + let tmp = self.fmad(a, bb, cc); + let ci = self.as_int(cc); + let (k23, k255, k128) = (self.s.m.i32(23), self.s.m.i32(0xFF), self.s.m.i32(128)); + let sh = self.s.m.bin(c, Bin::LShr, ci, k23); + let exp = self.s.m.bin(c, Bin::And, sh, k255); + let exp_ge = self.s.m.cmp(c, pred::IUGE, exp, k128); + let (k_up, k_dn) = (self.s.m.f32(0x5F80_0000), self.s.m.f32(0x1F80_0000)); + let scale = self.s.m.select(c, exp_ge, k_up, k_dn); + let scaled = self.s.m.bin(c, Bin::Mul, tmp, scale); + let r = self.s.m.select(c, vcc, scaled, tmp); + float(self, r) + } + "v_div_fixup_f32" => { + let (q, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let (qi, di, ni) = (self.as_int(q), self.as_int(den), self.as_int(num)); + let (ksign, kabs, kinf) = ( + self.s.m.i32(0x8000_0000), + self.s.m.i32(0x7FFF_FFFF), + self.s.m.i32(0x7F80_0000), + ); + let (kqnan_bit, kneg_qnan, zero) = ( + self.s.m.i32(0x0040_0000), + self.s.m.i32(0xFFC0_0000), + self.s.m.i32(0), + ); + let sign = { + let x = self.s.m.bin(c, Bin::Xor, ni, di); + self.s.m.bin(c, Bin::And, x, ksign) + }; + let q_abs = self.s.m.bin(c, Bin::And, qi, kabs); + let d_abs = self.s.m.bin(c, Bin::And, di, kabs); + let n_abs = self.s.m.bin(c, Bin::And, ni, kabs); + let q_nan = self.s.m.cmp(c, pred::IUGT, q_abs, kinf); + let d_nan = self.s.m.cmp(c, pred::IUGT, d_abs, kinf); + let n_nan = self.s.m.cmp(c, pred::IUGT, n_abs, kinf); + let d_inf = self.s.m.cmp(c, pred::EQ, d_abs, kinf); + let n_inf = self.s.m.cmp(c, pred::EQ, n_abs, kinf); + let d_zero = self.s.m.cmp(c, pred::EQ, d_abs, zero); + let n_zero = self.s.m.cmp(c, pred::EQ, n_abs, zero); + let both_inf = self.s.m.bin(c, Bin::And, n_inf, d_inf); + let both_zero = self.s.m.bin(c, Bin::And, n_zero, d_zero); + let invalid = self.s.m.bin(c, Bin::Or, both_inf, both_zero); + let make_inf = { + let t = self.s.m.bin(c, Bin::Or, n_inf, d_zero); + self.s.m.bin(c, Bin::Or, t, q_nan) + }; + let make_zero = self.s.m.bin(c, Bin::Or, d_inf, n_zero); + let signed_q = self.s.m.bin(c, Bin::Or, sign, q_abs); + let signed_inf = self.s.m.bin(c, Bin::Or, sign, kinf); + let n_qnan = self.s.m.bin(c, Bin::Or, ni, kqnan_bit); + let d_qnan = self.s.m.bin(c, Bin::Or, di, kqnan_bit); + let r = self.s.m.select(c, make_zero, sign, signed_q); + let r = self.s.m.select(c, make_inf, signed_inf, r); + let r = self.s.m.select(c, invalid, kneg_qnan, r); + let r = self.s.m.select(c, d_nan, d_qnan, r); + let r = self.s.m.select(c, n_nan, n_qnan, r); + let rf = self.as_float(r); + float(self, rf) + } "v_fmac_f32" | "v_mac_f32" | "v_mac_legacy_f32" => { let (a, bb) = (f(self, 0)?, f(self, 1)?); let Some(Operand::Vector { reg, .. }) = v.dst else { @@ -4046,8 +6661,8 @@ impl<'a> Lower<'a> { let mut xs = Vec::new(); for i in 0..3 { let op = v.src.get(i).ok_or("a missing operand")?; - let x = self.operand(inst, op)?; let mut x = if v.opsel_hi >> i & 1 != 0 { + let x = self.f16_operand(inst, op)?; let h = if v.opsel >> i & 1 != 0 { let k16 = self.s.m.i32(16); self.s.m.bin(c, Bin::LShr, x, k16) @@ -4057,6 +6672,7 @@ impl<'a> Lower<'a> { self.s .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]) } else { + let x = self.operand(inst, op)?; self.as_float(x) }; if v.neg_hi >> i & 1 != 0 { @@ -4125,7 +6741,7 @@ impl<'a> Lower<'a> { let mut halves = Vec::new(); for k in 0..2 { let op = v.src.get(k).ok_or("a missing operand")?; - let mut x = self.operand(inst, op)?; + let mut x = self.f16_operand(inst, op)?; if v.opsel >> k & 1 != 0 { let k16 = self.s.m.i32(16); x = self.s.m.bin(c, Bin::LShr, x, k16); @@ -4156,10 +6772,37 @@ impl<'a> Lower<'a> { Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), _ => None, }; - let m = mask - .and_then(|m| self.x.st.masks.get(&m).copied()) - .ok_or("a select on an untracked mask")?; - let cond = self.boolean(m, c)?; + const UNTRACKED: Why = "a select on an untracked mask"; + let cond = match mask.and_then(|m| self.x.st.masks.get(&m).copied()) { + Some(m) => self.boolean(m, c)?, + // A mask the code holds as a number (a constant bit + // pattern: every other lane, every other pair...): + // this lane's bit of it. Exact where host lanes are + // the console's. + None if self.mask_data == MaskData::Console => { + // Each host wave taken as a wave of its own has no + // console lane numbers to pick the bits by. + if self.local { + return Err("a constant lane mask in a half-wave"); + } + let m = mask.ok_or(UNTRACKED)?; + let lo = self.i32_of(m).map_err(|_| UNTRACKED)?; + // wave64: the register after it holds lanes 32-63. + let high = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) if self.x.native.wave64 => { + Some(inst.read(Reg::S(code + 1)).ok_or(UNTRACKED)?) + } + _ => None, + }; + let hi = match high { + Some(h) => Some(self.i32_of(h).map_err(|_| UNTRACKED)?), + None => None, + }; + self.cross_lane(false)?; + self.lane_bit(c, lo, hi) + } + None => return Err(UNTRACKED), + }; if v.abs != 0 || v.neg != 0 { let (a, bb) = (f(self, 0)?, f(self, 1)?); let r = self.s.m.select(c, cond, bb, a); @@ -4211,6 +6854,41 @@ impl<'a> Lower<'a> { } else { self.cross_lane(false)?; } + if let Some(slot) = self.exchange.as_ref().map(|e| e.0) { + if self.local && self.local_any { + // this host wave's lane of that number (lanes 32..63 are 0..31 here) + let k31 = self.s.m.i32(31); + let here = self.s.m.bin(self.cur, Bin::And, lane, k31); + let r = self.read_lane(a, here); + return int(self, r); + } + if self.local { + return Err("a lane read in a half-wave"); + } + if self.exchange.as_ref().is_some_and(|e| e.1) { + // a group of 32 or fewer: the lane is in this host wave + let r = self.read_lane(a, lane); + return int(self, r); + } + // the lane that holds it may be in the other host wave: it gives it through LDS + if !self.all_lanes(self.cur_ir) { + return Err("a lane read where not every lane runs"); + } + let cl = self.console_lane(); + let is = self.s.m.cmp(self.cur, pred::EQ, cl, lane); + let k = self.exchange_pair(slot); + let at = self.begin_guarded(Some(is)); + let lds = self.s.lds(); + let ptr = self.s.m.element(self.cur, lds, k); + self.s.m.store(self.cur, ptr, a); + self.end_guarded(at, &[]); + let c2 = self.cur; + self.group_sync(c2); + let ptr = self.s.m.element(c2, lds, k); + let r = self.s.m.load(c2, ptr); + self.group_sync(c2); + return int(self, r); + } let r = self.read_lane(a, lane); int(self, r) } @@ -4225,7 +6903,10 @@ impl<'a> Lower<'a> { None => self.s.m.i32(0), }; self.cross_lane(false)?; - let me = self.lane_index(); + if self.local && !self.local_any { + return Err("a lane write in a half-wave"); + } + let me = self.console_lane(); let is = self.s.m.cmp(c, pred::EQ, me, lane); let r = self.s.m.select(c, is, a, old); int(self, r) @@ -4242,15 +6923,34 @@ impl<'a> Lower<'a> { } "v_readfirstlane_b32" => { let a = s(self, 0)?; - self.s.flags |= flags::WAVE_OPS; - let r = self.s.op( - c, - "waveReadLaneFirst.i32", - Attr::NoUnwind, - self.s.t.i32, - 118, - &[a], - ); + let (mine, any) = self.first_lane(a, guard); + // two host waves that exchange: the console's first lane may be in the other + // one, unless every lane holds the same value + let alike = match v.src.first() { + Some(&Operand::Vector { reg, .. }) => { + inst.read(Reg::V(reg)).is_some_and(|x| self.uniform.contains(&x)) + } + _ => true, + }; + let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local; + let r = if halves && !alike { + if !self.all_lanes(self.cur_ir) { + return Err("a first-lane read where not every lane runs"); + } + let c = self.cur; + let i32t = self.s.t.i32; + let has = self.s.m.cast(c, Cast::ZExt, any, i32t); + let (lo_has, hi_has) = self.exchange_halves(c, has); + let (lo, hi) = self.exchange_halves(c, mine); + let z = self.s.m.i32(0); + let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z); + let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z); + // neither half has a lane in EXEC: the console reads lane 0 + let hi = self.s.m.select(c, in_hi, hi, lo); + self.s.m.select(c, in_lo, lo, hi) + } else { + mine + }; int(self, r) } _ => { @@ -4275,11 +6975,7 @@ impl<'a> Lower<'a> { let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result { let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?; let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?; - let lo = l.s.m.cast(c, Cast::ZExt, lo, i64t); - let hi = l.s.m.cast(c, Cast::ZExt, hi, i64t); - let k32 = l.s.m.int_const(i64t, 32); - let hi = l.s.m.bin(c, Bin::Shl, hi, k32); - Ok(l.s.m.bin(c, Bin::Or, lo, hi)) + Ok(l.join64(lo, hi)) }; match op { Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1)), @@ -4298,6 +6994,16 @@ impl<'a> Lower<'a> { } } + fn join64(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let ty = self.s.m.int(64); + let lo = self.s.m.cast(c, Cast::ZExt, lo, ty); + let hi = self.s.m.cast(c, Cast::ZExt, hi, ty); + let shift = self.s.m.int_const(ty, 32); + let hi = self.s.m.bin(c, Bin::Shl, hi, shift); + self.s.m.bin(c, Bin::Or, lo, hi) + } + /// The low and high dwords of an i64. fn split64(&mut self, x: V) -> (V, V) { let c = self.cur; @@ -4488,8 +7194,13 @@ impl<'a> Lower<'a> { return self.write_f(inst, f, guard); } let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> { - if v.omod != 0 { - return Err("an output modifier on a 16-bit operation"); + match v.omod { + 0 => {} + k => { + let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)]; + let k = l.s.m.f32(factor.to_bits()); + f = l.s.m.bin(l.cur, Bin::Mul, f, k); + } } if v.clamp { f = l.unary(7, f); @@ -4595,6 +7306,30 @@ impl<'a> Lower<'a> { }; return float_result(self, r); } + if matches!(name, "v_cvt_u16_f16" | "v_cvt_i16_f16") { + if v.clamp || v.omod != 0 { + return Err("modifiers on a 16-bit integer operation"); + } + // Toward zero, saturating at the 16-bit range (infinities + // included); NaN gives 0. Clamped in f32 first, where every + // f16 is exact, so the conversion never leaves i32's range + // (upstream PR #384's arithmetic; the source's abs and neg + // modifiers are applied by `half_fsrc`, as before). + let a = self.half_fsrc(inst, 0)?; + let (lo, hi) = if name == "v_cvt_u16_f16" { + (0.0f32, 65535.0f32) + } else { + (-32768.0, 32767.0) + }; + let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits())); + let t = self.binary(35, a, lo); + let t = self.binary(36, t, hi); + let r = self.s.m.cast(c, Cast::FpToSi, t, i32t); + let nan = self.s.m.cmp(c, pred::UNO, a, a); + let z = self.s.m.i32(0); + let r = self.s.m.select(c, nan, z, r); + return self.write_half(inst, r, guard); + } if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") { if v.clamp || v.omod != 0 { return Err("modifiers on a 16-bit integer operation"); @@ -4606,67 +7341,47 @@ impl<'a> Lower<'a> { if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 { return Err("modifiers on a 16-bit integer operation"); } - let r = match name { - "v_cvt_u16_f16" | "v_cvt_i16_f16" => { - // Toward zero, saturating at the 16-bit range (infinities - // included); NaN gives 0. Clamped in f32 first, where every - // f16 is exact, so the conversion never leaves i32's range. - let a = self.half_fsrc(inst, 0)?; - let (lo, hi) = if name == "v_cvt_u16_f16" { - (0.0f32, 65535.0f32) - } else { - (-32768.0, 32767.0) - }; - let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits())); - let t = self.binary(35, a, lo); - let t = self.binary(36, t, hi); - let r = self.s.m.cast(c, Cast::FpToSi, t, i32t); - let nan = self.s.m.cmp(c, pred::UNO, a, a); - let z = self.s.m.i32(0); - self.s.m.select(c, nan, z, r) + let r = { + let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); + let k16 = self.s.m.i32(16); + let sext = |l: &mut Self, x: V| { + let t = l.s.m.bin(c, Bin::Shl, x, k16); + l.s.m.bin(c, Bin::AShr, t, k16) + }; + if name.ends_with("_i16") { + a = sext(self, a); + b = sext(self, b); } - _ => { - let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); - let k16 = self.s.m.i32(16); - let sext = |l: &mut Self, x: V| { - let t = l.s.m.bin(c, Bin::Shl, x, k16); - l.s.m.bin(c, Bin::AShr, t, k16) - }; - if name.ends_with("_i16") { - a = sext(self, a); - b = sext(self, b); + let k15 = self.s.m.i32(15); + match name { + "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b), + "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b), + "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a), + "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b), + "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => { + // src0 is the shift (4 bits), src1 the value. + let sh = self.s.m.bin(c, Bin::And, a, k15); + let x = if name == "v_ashrrev_i16" { + sext(self, b) + } else { + b + }; + let op = match name { + "v_lshlrev_b16" => Bin::Shl, + "v_lshrrev_b16" => Bin::LShr, + _ => Bin::AShr, + }; + self.s.m.bin(c, op, x, sh) } - let k15 = self.s.m.i32(15); - match name { - "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b), - "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b), - "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a), - "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b), - "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => { - // src0 is the shift (4 bits), src1 the value. - let sh = self.s.m.bin(c, Bin::And, a, k15); - let x = if name == "v_ashrrev_i16" { - sext(self, b) - } else { - b - }; - let op = match name { - "v_lshlrev_b16" => Bin::Shl, - "v_lshrrev_b16" => Bin::LShr, - _ => Bin::AShr, - }; - self.s.m.bin(c, op, x, sh) - } - _ => { - let p = match name { - "v_max_u16" => pred::IUGT, - "v_min_u16" => pred::IULT, - "v_max_i16" => pred::SGT, - _ => pred::SLT, - }; - let t = self.s.m.cmp(c, p, a, b); - self.s.m.select(c, t, a, b) - } + _ => { + let p = match name { + "v_max_u16" => pred::IUGT, + "v_min_u16" => pred::IULT, + "v_max_i16" => pred::SGT, + _ => pred::SLT, + }; + let t = self.s.m.cmp(c, p, a, b); + self.s.m.select(c, t, a, b) } } }; @@ -5231,7 +7946,7 @@ impl<'a> Lower<'a> { } else if self.s.mesh.is_none() { self.cross_lane(false)?; } - let lane = self.lane_index(); + let lane = self.console_lane(); let below = if name == "v_mbcnt_lo_u32_b32" { lane } else { @@ -5454,99 +8169,175 @@ impl<'a> Lower<'a> { let Some(&interp) = self.interps.get(&site) else { return Err("the first half of an interpolation"); }; - let (attribute, mode) = match interp { - Interp::Interpolated { - attribute, - barycentric, - .. - } => ( - attribute, - match barycentric { - Barycentric::PerspectiveCenter => 2, - Barycentric::PerspectiveCentroid => 3, - Barycentric::PerspectiveSample => 6, - Barycentric::LinearCenter => 4, - Barycentric::LinearCentroid => 5, - Barycentric::LinearSample => 7, - Barycentric::PerspectivePullModel => return Err("pull-model interpolation"), - }, - ), - // P0, the provoking vertex: a flat (nointerpolation) input. - Interp::Vertex { - attribute, - vertex: 2, - } => (attribute, 1), - Interp::Vertex { .. } => return Err("a non-provoking vertex value"), - }; - let dst = match &inst.fields { - Fields::Vintrp { dst, .. } => *dst, - Fields::Valu(v) => v.dst.ok_or("an interpolation")?, + let name = inst.name(); + let (dst, src) = match &inst.fields { + Fields::Vintrp { dst, src, .. } => (*dst, Some(*src)), + Fields::Valu(v) => { + if v.abs != 0 || v.neg != 0 { + return Err("interpolation operand modifiers"); + } + (v.dst.ok_or("an interpolation")?, v.src.get(1).copied()) + } _ => unreachable!(), }; let Operand::Vector { reg, .. } = dst else { return Err("an interpolation"); }; - // A channel of an input element, interpolated as `mode` says. - let channel = |l: &mut Self, row: u8, ch: u8| -> Result { - let (id, col) = l - .find_input(row, ch) - .ok_or("an input the signature lacks")?; - let e = &mut l.s.inputs[id]; - if e.interp != mode && e.usage != 0 { - return Err("one input interpolated two ways"); + // A float operand of the instruction. + let float = |l: &mut Self, op: Option| -> Result { + let x = l.operand(inst, &op.ok_or("an interpolation operand")?)?; + Ok(l.as_float(x)) + }; + // What the result adds to the evaluated channel (a second half's + // first half, when the halves evaluate on their own). + let mut add = None; + let (attribute, eval) = match *interp { + Interp::Interpolated { + attribute, + barycentric, + .. + } => { + let mode = interp_mode(barycentric).ok_or("pull-model interpolation")?; + let eval = if self.per_vertex(attribute.row) { + // The element is read per vertex elsewhere, so it is + // constant: weigh its vertices with SV_Barycentrics. + let mut ij = [None; 2]; + for (index, w) in ij.iter_mut().enumerate() { + let x = match self.barycentric(barycentric, index as u8) { + Val::I32(x) => x, + Val::Missing(w) => return Err(w), + Val::Bit(_) => unreachable!(), + }; + *w = Some(self.as_float(x)); + } + Eval::Weights { + p0: true, + i: ij[0], + j: ij[1], + } + } else { + Eval::Mode(mode) + }; + (attribute, eval) } - e.interp = mode; - match l.load_any_input(id, col) { - Val::I32(x) => Ok(x), - _ => Err("an input"), + // P0, the provoking vertex: a flat (nointerpolation) input. + Interp::Vertex { + attribute, + vertex: 2, + } => (attribute, Eval::Mode(1)), + // P10 and P20: what the first and second halves weigh, P1 - P0 + // and P2 - P0, which is what the hardware holds for an + // attribute the program also interpolates. + Interp::Vertex { attribute, vertex } if self.interpolated(attribute.row) => { + let one = Some(self.s.m.f32(1f32.to_bits())); + let (i, j) = if vertex == 0 { + (one, None) + } else { + (None, one) + }; + (attribute, Eval::Weights { p0: false, i, j }) + } + Interp::Vertex { .. } => return Err("a non-provoking vertex value"), + // A half of an interpolation with computed i or j: P0 + i P10, + // or the old dst (f16: the third operand) + j P20. + Interp::Weighted { attribute } if name.starts_with("v_interp_p1") => { + let i = Some(float(self, src)?); + ( + attribute, + Eval::Weights { + p0: true, + i, + j: None, + }, + ) + } + Interp::Weighted { attribute } => { + let old = match &inst.fields { + Fields::Valu(v) => v.src.get(2).copied(), + _ => Some(dst), + }; + add = Some(float(self, old)?); + let j = Some(float(self, src)?); + ( + attribute, + Eval::Weights { + p0: false, + i: None, + j, + }, + ) } }; let packing = match &self.x.native.io { StageIo::Ps { inputs, .. } => inputs .iter() .find(|i| i.row == attribute.row && i.fp16) - .map(|i| (i.pack2, (i.row2 != i.row).then_some(i.row2))), + .map(|i| { + let packs = if i.pack2 { + input_packs(&self.x.native.io, &self.s.inputs) + } else { + Vec::new() + }; + (i.pack2, packs) + }), _ => None, }; - let f16 = inst.name().ends_with("_f16"); + let f16 = name.ends_with("_f16"); + // The evaluated channel plus `add`, as a float. + let total = |l: &mut Self, row: u8, ch: u8| -> Result { + let x = l.eval_channel(row, ch, eval)?; + let x = l.as_float(x); + Ok(match add { + Some(a) => l.s.m.bin(l.cur, Bin::Add, a, x), + None => x, + }) + }; let x = match packing { None if f16 || attribute.high => return Err("a 16-bit read of a 32-bit input"), - None => channel(self, attribute.row, attribute.channel)?, - Some((pack2, b)) => { + None => { + let x = total(self, attribute.row, attribute.channel)?; + self.as_int(x) + } + Some((pack2, packs)) => { // 16-bit values: one in the low half of each dword, or two // per dword (`packed_half`); the host's are 32-bit floats. let half = |l: &mut Self, h: u8| -> Result, Why> { let src = if pack2 { - packed_half(&l.s.inputs, attribute.row, b, h) + packed_half(&l.s.inputs, &packs, attribute.row, h) } else { h.is_multiple_of(2).then_some((attribute.row, h / 2)) }; - let Some((row, ch)) = src else { - return Ok(None); - }; - let x = channel(l, row, ch)?; - let f = l.as_float(x); - let i32t = l.s.t.i32; - Ok(Some(l.s.op( - l.cur, - "legacyF32ToF16", - Attr::ReadNone, - i32t, - 130, - &[f], - ))) + match src { + Some((row, ch)) => total(l, row, ch).map(Some), + None => Ok(None), + } }; - let h = 2 * attribute.channel; + let to_f16 = |l: &mut Self, f: V| { + let i32t = l.s.t.i32; + l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) + }; + let h = 2 * attribute.channel + u8::from(attribute.high); let c = self.cur; - if f16 { - let lo = half(self, h + u8::from(attribute.high))? - .ok_or("a packed input half no element holds")?; + if name == "v_interp_p1ll_f16" { + // An f32 result from 16-bit vertex values. + let f = half(self, h)?.ok_or("a packed input half no element holds")?; + self.as_int(f) + } else if f16 { + let f = half(self, h)?.ok_or("a packed input half no element holds")?; + let lo = to_f16(self, f); self.low_half(inst, reg, lo) - } else if mode == 1 { + } else if matches!(eval, Eval::Mode(1)) { // The whole dword of a flat input: both halves. + let h = 2 * attribute.channel; let z = self.s.m.i32(0); - let lo = half(self, h)?.unwrap_or(z); - let hi = half(self, h + 1)?.unwrap_or(z); + let lo = match half(self, h)? { + Some(f) => to_f16(self, f), + None => z, + }; + let hi = match half(self, h + 1)? { + Some(f) => to_f16(self, f), + None => z, + }; let k16 = self.s.m.i32(16); let hi = self.s.m.bin(c, Bin::Shl, hi, k16); self.s.m.bin(c, Bin::Or, lo, hi) @@ -5560,6 +8351,100 @@ impl<'a> Lower<'a> { Ok(()) } + /// Whether the program reads attribute row `row` per vertex (an + /// interpolation with computed barycentrics, or P10 or P20): then its + /// element is declared constant and read with `attributeAtVertex`. + fn per_vertex(&self, row: u8) -> bool { + self.x.io.interps.iter().any(|(_, i)| match *i { + Interp::Weighted { attribute } => attribute.row == row, + Interp::Vertex { attribute, vertex } => { + attribute.row == row && vertex != 2 && self.interpolated(row) + } + Interp::Interpolated { .. } => false, + }) + } + + /// Whether the program interpolates attribute row `row` (so the + /// hardware holds P1 - P0 and P2 - P0 for it). + fn interpolated(&self, row: u8) -> bool { + self.x.io.interps.iter().any(|(_, i)| match *i { + Interp::Interpolated { attribute, .. } | Interp::Weighted { attribute } => { + attribute.row == row + } + Interp::Vertex { .. } => false, + }) + } + + /// Channel `ch` of input row `row` evaluated as `eval` says, as raw bits. + fn eval_channel(&mut self, row: u8, ch: u8, eval: Eval) -> Result { + let (id, col) = self + .find_input(row, ch) + .ok_or("an input the signature lacks")?; + let mode = match eval { + Eval::Mode(mode) => mode, + Eval::Weights { .. } => 1, + }; + let e = &mut self.s.inputs[id]; + if e.interp != mode && e.usage != 0 { + return Err("one input interpolated two ways"); + } + e.interp = mode; + let Eval::Weights { p0, i, j } = eval else { + return match self.load_any_input(id, col) { + Val::I32(x) => Ok(x), + _ => Err("an input"), + }; + }; + let v0 = self.vertex_input(id, col, 0); + let c = self.cur; + let mut acc = p0.then_some(v0); + for (k, w) in [(1, i), (2, j)] { + let Some(w) = w else { continue }; + let vk = self.vertex_input(id, col, k); + let d = self.s.m.bin(c, Bin::Sub, vk, v0); + acc = Some(match acc { + Some(a) => self.fmad(w, d, a), + None => self.s.m.bin(c, Bin::Mul, w, d), + }); + } + let acc = acc.ok_or("an interpolation")?; + Ok(self.as_int(acc)) + } + + /// Vertex `k` (0 the provoking vertex, as `barycentric` orders them) + /// of a constant input element's channel, as a float. + fn vertex_input(&mut self, id: usize, col: u8, k: u8) -> V { + let e = &mut self.s.inputs[id]; + e.usage |= 1 << col; + let int = e.comp != 9; + let (ty, suffix) = if int { + (self.s.t.i32, ".i32") + } else { + (self.s.t.f32, ".f32") + }; + self.s.flags |= flags::BARYCENTRICS; + let entry = self.s.entry; + let args = [ + self.s.m.i32(id as u32), + self.s.m.i32(0), + self.s.m.i8(col), + self.s.m.i8(k), + ]; + let v = self.s.op( + entry, + &format!("attributeAtVertex{suffix}"), + Attr::ReadNone, + ty, + 137, + &args, + ); + if int { + self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.f32) + } else { + v + } + } + /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit /// results keep the register's high half (GFX10). fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V { @@ -5594,9 +8479,6 @@ impl<'a> Lower<'a> { return Err("an image access with tfe or lwe"); } let name = inst.name(); - if *a16 && name.starts_with("image_sample_b") { - return Err("a biased image sample with 16-bit coordinates"); - } // A load or sample with no channel enabled returns the first. let dmask = if *dmask == 0 { &1 } else { dmask }; let site = (b, i); @@ -5625,13 +8507,15 @@ impl<'a> Lower<'a> { regs.extend((0..dwords).map(|k| reg + k)); } } - // With a16, two 16-bit components per VGPR, low half first. - let addr_val = |l: &mut Self, k: usize| -> Result { - let r = *regs - .get(if *a16 { k / 2 } else { k }) - .ok_or("an image address")?; + // Full 32-bit address VGPR at `reg_idx` (offset, bias, z-compare). + let addr_u32 = |l: &mut Self, reg_idx: usize| -> Result { + let r = *regs.get(reg_idx).ok_or("an image address")?; let v = inst.read(Reg::V(r)).ok_or("an image address")?; - let x = l.i32_of(v)?; + l.i32_of(v) + }; + // With a16, two 16-bit components per VGPR starting at `base_reg`, low half first. + let addr_packed = |l: &mut Self, base_reg: usize, k: usize| -> Result { + let x = addr_u32(l, base_reg + if *a16 { k / 2 } else { k })?; if !*a16 { return Ok(x); } @@ -5640,6 +8524,7 @@ impl<'a> Lower<'a> { let x = l.s.m.bin(c, Bin::LShr, x, sh); Ok(l.s.m.bin(c, Bin::And, x, mask)) }; + let addr_val = |l: &mut Self, k: usize| -> Result { addr_packed(l, 0, k) }; let src = self .descriptors .get(&(site, false)) @@ -5652,8 +8537,8 @@ impl<'a> Lower<'a> { .is_some_and(|u| u.kind == ResourceType::Uav); let props = (kind | if uav { 0x1000 } else { 0 }, 0x409); if let Some(op) = name.strip_prefix("image_atomic_") { - // DXIL's atomic operations on a 32-bit integer texture UAV; the - // old value returns with glc. Sub is the add of the negation. + // GLC returns the old value. DXIL implements subtraction by adding + // the two's complement of the operand at the same width. let code = match op { "add" | "sub" => 0, "and" => 1, @@ -5673,12 +8558,13 @@ impl<'a> Lower<'a> { if *d16 || *a16 { return Err("a 16-bit image atomic"); } - // dmask: the data dwords (cmpswap: twice the value's). - // shortcut: 64-bit image atomics (two dwords, an R32G32 view) - // need the host's 64-bit typed atomics; they stop the program. - if *dmask != if code == u32::MAX { 3 } else { 1 } { - return Err("a 64-bit image atomic"); - } + // Compare-exchange consumes a replacement followed by a comparand. + let compare = code == u32::MAX; + let wide = match (compare, *dmask) { + (false, 1) | (true, 3) => false, + (false, 3) | (true, 15) => true, + _ => return Err("an image atomic data mask"), + }; let iu = self.s.m.undef(self.s.t.i32); let mut cs = vec![iu; 3]; for (k, slot) in cs.iter_mut().enumerate().take(coords) { @@ -5687,42 +8573,69 @@ impl<'a> Lower<'a> { let Operand::Vector { reg, .. } = *data else { return Err("image atomic data"); }; - let vals = self.vgprs(inst, data, if code == u32::MAX { 2 } else { 1 })?; - let mut value = vals[0]; - if op == "sub" { - let z = self.s.m.i32(0); - value = self.s.m.bin(c, Bin::Sub, z, value); - } - let old = match inst.read(Reg::V(reg)) { - Some(v) if cache.glc => self.i32_of(v)?, - _ => self.s.m.i32(0), + let width = if wide { 2 } else { 1 }; + let vals = self.vgprs(inst, data, if compare { 2 * width } else { width })?; + let (ty, component) = if wide { + self.s.flags |= flags::INT64 | flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64; + (self.s.m.int(64), 0x107) // one uint64_t in an R32G32_UINT view + } else { + (self.s.t.i32, 0x105) }; - let h = self.handle(site, src, false, (kind | 0x1000, 0x105))?; - let at = self.begin_guarded(guard); - let i32t = self.s.t.i32; + let original = if wide { + self.join64(vals[0], vals[1]) + } else { + vals[0] + }; + let value = if op == "sub" { + let zero = self.s.m.int_const(ty, 0); + self.s.m.bin(c, Bin::Sub, zero, original) + } else { + original + }; + let h = self.handle(site, src, false, (kind | 0x1000, component))?; let mut args = vec![h]; - let r = if code == u32::MAX { - // cmpswap: data is (new, compare). + let (intrinsic, opcode) = if compare { + let comparand = if wide { + self.join64(vals[2], vals[3]) + } else { + vals[1] + }; args.extend(cs); - args.extend([vals[1], vals[0]]); - self.s.op( - self.cur, - "atomicCompareExchange.i32", - Attr::NoUnwind, - i32t, - 79, - &args, - ) + args.extend([comparand, value]); + let intrinsic = if wide { + "atomicCompareExchange.i64" + } else { + "atomicCompareExchange.i32" + }; + (intrinsic, 79) } else { args.push(self.s.m.i32(code)); args.extend(cs); args.push(value); - self.s - .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args) + ( + if wide { + "atomicBinOp.i64" + } else { + "atomicBinOp.i32" + }, + 78, + ) }; - let r = self.end_guarded(at, &[(r, old)])[0]; + let at = self.begin_guarded(guard); + let r = self + .s + .op(self.cur, intrinsic, Attr::NoUnwind, ty, opcode, &args); if cache.glc { - self.write(inst, Reg::V(reg), r, None); + let old = self.end_guarded(at, &[(r, original)])[0]; + if wide { + let (lo, hi) = self.split64(old); + self.write(inst, Reg::V(reg), lo, None); + self.write(inst, Reg::V(reg + 1), hi, None); + } else { + self.write(inst, Reg::V(reg), old, None); + } + } else { + self.end_guarded(at, &[]); } return Ok(()); } @@ -5779,16 +8692,18 @@ impl<'a> Lower<'a> { self.end_guarded(at, &[]); return Ok(()); } + let has_cl = name.ends_with("_cl"); let (op, sample) = match name { - "image_sample" | "image_sample_o" => (60, true), - "image_sample_lz" | "image_sample_l" => (62, true), - "image_sample_b" => (61, true), + "image_sample" | "image_sample_o" | "image_sample_cl" => (60, true), + "image_sample_lz" | "image_sample_l" | "image_sample_lz_o" => (62, true), + "image_sample_b" | "image_sample_b_cl" => (61, true), "image_sample_c_lz" => (65, true), - "image_sample_d" => (63, true), + "image_sample_d" | "image_sample_d_cl" => (63, true), "image_get_lod" if self.s.pixel => (81, true), // Implicit derivatives: pixel shaders only. "image_sample_c" if self.s.pixel => (64, true), - "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" => (73, true), + "image_sample_c_cl" if self.s.pixel => (64, true), + "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" | "image_gather4_l_o" => (73, true), "image_load" | "image_load_mip" => (66, false), "image_get_resinfo" => (72, false), _ => return Err(name), @@ -5833,6 +8748,8 @@ impl<'a> Lower<'a> { let h = self.handle(site, src, false, props)?; let fu = self.s.m.undef(self.s.t.f32); let iu = self.s.m.undef(self.s.t.i32); + // A gather at a named level, done as four texel reads (below). + let mut gathered: Option<[V; 4]> = None; let r = if sample { let ss = self .descriptors @@ -5849,14 +8766,26 @@ impl<'a> Lower<'a> { // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13, // signed (programmable offsets: gathers only). let offset_word = name.ends_with("_o"); - let first = - usize::from(offset_word) + usize::from(name == "image_sample_b") + usize::from(cmp); + let first = usize::from(offset_word) + + usize::from(name.starts_with("image_sample_b")) + + usize::from(cmp); // Coordinates the size divides (not the array slice); explicit // gradients (x then y) come before the coordinates. let spatial = coords - usize::from(kind == 6 || kind == 7); - let grads = if op == 63 { 2 * spatial } else { 0 }; + // A cube's gradients are the two of its face coordinates. + let grads = if kind == 5 { 2 } else { spatial }; + let deriv_regs = if op == 63 { + if *a16 { + grads.div_ceil(2) + } else { + grads + } + } else { + 0 + }; + let coord_base = first + 2 * deriv_regs; let mut cs = vec![fu; 4]; - // With a16, sampling coordinates and LOD are f16. + // With a16, sampling coordinates, gradients, LOD and clamp are f16. let to_float = |l: &mut Self, x: V| { if *a16 { let f = l.s.t.f32; @@ -5865,14 +8794,14 @@ impl<'a> Lower<'a> { l.as_float(x) } }; + if kind == 5 && (*unorm || op == 81) { + return Err("a cube sample with texel coordinates or a level query"); + } for (k, slot) in cs.iter_mut().enumerate().take(coords) { - let x = addr_val(self, first + grads + k)?; + let x = addr_packed(self, coord_base, k)?; *slot = to_float(self, x); } if kind == 5 { - if *unorm || op == 63 || op == 81 { - return Err("a cube sample with texel coordinates, gradients or a level query"); - } let dir = self.cube_direction(cs[0], cs[1], cs[2]); cs[..3].copy_from_slice(&dir); } @@ -5921,59 +8850,164 @@ impl<'a> Lower<'a> { for o in os.iter_mut().take(offsets) { *o = zero; } + if offset_word && offsets > 0 { + let w = addr_val(self, 0)?; + for (k, at) in [(0, 26), (1, 18)].into_iter().take(offsets.min(2)) { + // Bits at..at+5 sign-extended: shift up, then down. + let left = self.s.m.i32(at); + let t = self.s.m.bin(c, Bin::Shl, w, left); + let k26 = self.s.m.i32(26); + os[k] = self.s.m.bin(c, Bin::AShr, t, k26); + } + } let mut args = vec![h, sh]; args.extend(&cs); + let clamp = if has_cl { + let x = addr_packed(self, coord_base, coords)?; + to_float(self, x) + } else { + fu + }; match op { + // Outside a pixel shader there are no screen derivatives: + // the validator refuses `sample` there ("features + // incompatible with the shader stage": 730 compute programs, + // among them the G-buffer resolves and the sky), and what a + // driver does with it is its own affair. + // shortcut: such a sample reads level 0 (a bias: that + // level). The console takes derivatives from neighbouring + // lanes there; compute them from the lanes if a resolve + // shows the wrong mip. + 60 if !self.s.pixel => { + args.extend(&os); + args.push(self.s.m.f32(0)); + self.s.op( + c, + "sampleLevel.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 62, + &args, + ) + } 60 => { if offset_word { - // DXIL takes immediate offsets in -8..=7; the - // console's are 6-bit and may be computed. + // DXIL wants immediate offsets in -8..=7 here; the + // console's are 6-bit and may be computed. A + // constant word in range becomes immediates + // (upstream PR #634); anything else keeps the + // offsets computed above (upstream refuses those). let w = addr_val(self, 0)?; - let w = self - .s - .m - .int_value(w) - .ok_or("a sample offset that is not constant")? - as u32; - for (k, o) in os.iter_mut().enumerate().take(offsets) { - let x = (w >> (8 * k) & 0x3F) as i32; - let x = if x >= 32 { x - 64 } else { x }; - if !(-8..=7).contains(&x) { - return Err("a sample offset past -8..7"); + if let Some(w) = self.s.m.int_value(w) { + let w = w as u32; + let field = |k: usize| { + let x = (w >> (8 * k) & 0x3F) as i32; + if x >= 32 { x - 64 } else { x } + }; + let n = offsets.min(2); + if (0..n).all(|k| (-8..=7).contains(&field(k))) { + for (k, o) in os.iter_mut().enumerate().take(n) { + *o = self.s.m.i32(field(k) as u32); + } } - *o = self.s.m.i32(x as u32); } } args.extend(&os); - args.push(fu); + args.push(clamp); self.s .op(c, "sample.f32", Attr::ReadOnly, self.s.t.res_ret, 60, &args) } 61 => { - let bias = addr_val(self, 0)?; - let bias = self.as_float(bias); + // With a16 the bias is an f16 in the low half of its + // word (the word is whole, the value is not). + let bias = addr_u32(self, usize::from(offset_word))?; + let bias = if *a16 { + let low = self.s.m.i32(0xFFFF); + let bias = self.s.m.bin(c, Bin::And, bias, low); + to_float(self, bias) + } else { + self.as_float(bias) + }; args.extend(&os); - args.extend([bias, fu]); + if self.s.pixel { + args.extend([bias, clamp]); + self.s.op( + c, + "sampleBias.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 61, + &args, + ) + } else { + // As above: the bias is the level. + args.push(bias); + self.s.op( + c, + "sampleLevel.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 62, + &args, + ) + } + } + 63 if kind == 5 => { + // A cube with explicit gradients: the host wants them + // as changes of the direction, the console gives the + // changes of the face coordinates (the face is one + // unit wide). The level they select is taken from the + // longer of the two, in texels, and sampled directly. + // shortcut: no anisotropic filtering for these samples + // (the longer axis alone decides the level). + let mut len = [fu; 2]; + for (axis, slot) in len.iter_mut().enumerate() { + let mut sum = self.s.m.f32(0); + for k in 0..2 { + let x = addr_packed(self, first + axis * deriv_regs, k)?; + let x = to_float(self, x); + let sq = self.s.m.bin(c, Bin::Mul, x, x); + sum = self.s.m.bin(c, Bin::Add, sum, sq); + } + *slot = self.unary(24, sum); // square root + } + let longer = self.binary(35, len[0], len[1]); // maximum + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let z = self.s.m.i32(0); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]); + 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 + // 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); + args.extend(&os); + args.push(lod); self.s.op( c, - "sampleBias.f32", + "sampleLevel.f32", Attr::ReadOnly, self.s.t.res_ret, - 61, + 62, &args, ) } 63 => { let mut g = vec![fu; 6]; for k in 0..spatial { - let x = addr_val(self, first + k)?; + let x = addr_packed(self, first, k)?; g[k] = to_float(self, x); - let y = addr_val(self, first + spatial + k)?; + let y = addr_packed(self, first + deriv_regs, k)?; g[3 + k] = to_float(self, y); } args.extend(&os); args.extend(g); - args.push(fu); + args.push(clamp); self.s.op( c, "sampleGrad.f32", @@ -5984,12 +9018,12 @@ impl<'a> Lower<'a> { ) } 64 | 65 => { - let reference = addr_val(self, first - 1)?; + let reference = addr_u32(self, first - 1)?; let reference = self.as_float(reference); args.extend(&os); args.push(reference); let name = if op == 64 { - args.push(fu); + args.push(clamp); "sampleCmp.f32" } else { "sampleCmpLevelZero.f32" @@ -5999,7 +9033,7 @@ impl<'a> Lower<'a> { } 62 => { let lod = if name == "image_sample_l" { - let x = addr_val(self, coords)?; + let x = addr_packed(self, coord_base, coords)?; to_float(self, x) } else { self.s.m.f32(0) @@ -6022,26 +9056,88 @@ impl<'a> Lower<'a> { if dmask.count_ones() != 1 { return Err("a gather of several channels"); } - if offset_word { - let w = addr_val(self, 0)?; - for (k, at) in [(0, 26), (1, 18)] { - // Bits at..at+5 sign-extended: shift up, then down. - let left = self.s.m.i32(at); - let t = self.s.m.bin(c, Bin::Shl, w, left); - let k26 = self.s.m.i32(26); - os[k] = self.s.m.bin(c, Bin::AShr, t, k26); + if matches!(name, "image_gather4_l" | "image_gather4_l_o") + && coords == 2 + && spatial == 2 + { + // The host's gather has no level: it read level 0 + // where the title names one (the depth pyramid its + // occlusion tests read: most of the world was + // culled against the wrong depths). The four texels + // are read at the level instead, in the gather's + // order: (u0,v1) (u1,v1) (u1,v0) (u0,v0). + // With an offset too (`image_gather4_l_o`): the + // offset is in texels of that level. Grand Theft + // Auto VI's meshlet culling takes a 4x4 block of + // the pyramid as one gather and three offset ones + // ((2,0), (0,2), (2,2)); the three read level 0, + // two texels beside the first one's place, so a + // meshlet three or four texels wide was tested + // against a quarter of what it covers. + // shortcut: the level is rounded to a whole one and + // coordinates past the edge are clamped, whatever + // the sampler says. + let lod = addr_packed(self, coord_base, coords)?; + let lod = to_float(self, lod); + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); + let zero = self.s.m.f32(0); + let lod = self.binary(35, lod, zero); // maximum + let lod = self.unary(26, lod); // round to nearest + let mip = self.s.m.cast(c, Cast::FpToUi, lod, i32t); + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); + let half = self.s.m.f32(0.5f32.to_bits()); + let one = self.s.m.f32(1.0f32.to_bits()); + let (mut lo, mut hi) = ([iu; 2], [iu; 2]); + for k in 0..2 { + let n = self.s.m.extract(c, d, k as u32); + let n = self.s.m.cast(c, Cast::UiToFp, n, f32t); + let last = self.s.m.bin(c, Bin::Sub, n, one); + let t = self.s.m.bin(c, Bin::Mul, cs[k], n); + let t = self.s.m.bin(c, Bin::Sub, t, half); + let first = self.unary(27, t); // round down + // The offset word's field (0 without one). + let by = self.s.m.cast(c, Cast::SiToFp, os[k], f32t); + let first = self.s.m.bin(c, Bin::Add, first, by); + let next = self.s.m.bin(c, Bin::Add, first, one); + for (slot, x) in [(&mut lo[k], first), (&mut hi[k], next)] { + let x = self.binary(35, x, zero); // maximum + let x = self.binary(36, x, last); // minimum + *slot = self.s.m.cast(c, Cast::FpToSi, x, i32t); + } } + let ch = dmask.trailing_zeros(); + let mut g = [fu; 4]; + let mut read = None; + let texels = [(lo[0], hi[1]), (hi[0], hi[1]), (hi[0], lo[1]), (lo[0], lo[1])]; + for (slot, (x, y)) in g.iter_mut().zip(texels) { + let r = self.s.op( + c, + "textureLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 66, + &[h, mip, x, y, iu, iu, iu, iu], + ); + *slot = self.s.m.extract(c, r, ch); + read = Some(r); + } + gathered = Some(g); + read.expect("four reads") + } else { + args.extend(&os[..2]); + args.push(self.s.m.i32(dmask.trailing_zeros())); + self.s.op( + c, + "textureGather.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 73, + &args, + ) } - args.extend(&os[..2]); - args.push(self.s.m.i32(dmask.trailing_zeros())); - self.s.op( - c, - "textureGather.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 73, - &args, - ) } } } else { @@ -6080,7 +9176,10 @@ impl<'a> Lower<'a> { }; let mut xs = Vec::new(); for ch in channels { - let x = self.s.m.extract(c, r, ch); + let x = match gathered { + Some(g) => g[ch as usize], + None => self.s.m.extract(c, r, ch), + }; xs.push(if *d16 { // shortcut: d16 results are taken as floats (rounded to // nearest even); integer formats would keep 16 bits. @@ -6166,6 +9265,10 @@ impl<'a> Lower<'a> { unreachable!() }; let name = inst.name(); + if name == "buffer_gl0_inv" || name == "buffer_gl1_inv" { + // The host has no console buffer cache to invalidate. + return Ok(()); + } if *lds || *tfe { return Err("a buffer access to LDS or with tfe"); } @@ -6192,6 +9295,14 @@ impl<'a> Lower<'a> { Some("cmpswap") => Some(u32::MAX), Some(_) => return Err(name), }; + // Byte and 16-bit accesses: bits, and whether a load sign-extends. + let narrow = match name { + "buffer_load_ubyte" | "buffer_store_byte" => Some((8, false)), + "buffer_load_sbyte" => Some((8, true)), + "buffer_load_ushort" | "buffer_store_short" => Some((16, false)), + "buffer_load_sshort" => Some((16, true)), + _ => None, + }; // d16: two 16-bit channels per VGPR, low half first. let d16 = name.starts_with("buffer_") && name.contains("_format_d16_"); let plain = name.replace("_format_d16_", "_format_"); @@ -6200,7 +9311,7 @@ impl<'a> Lower<'a> { .or(plain.strip_prefix("buffer_store_")) .or(plain.strip_prefix("tbuffer_load_")) { - _ if atomic.is_some() => (false, 1), + _ if atomic.is_some() || narrow.is_some() => (false, 1), Some("dword") => (false, 1), Some("dwordx2") => (false, 2), Some("dwordx3") => (false, 3), @@ -6245,6 +9356,36 @@ impl<'a> Lower<'a> { if let Some(x) = extra { off = self.s.m.bin(c, Bin::Add, off, x); } + // A buffer the program picks from the view heap by an index it + // computes: no used-resource entry gives its stride, the host's + // table by heap slot does; the access becomes a raw one at the + // element's byte. (Also tells the host this shader reads such + // buffers.) + let mut index = index; + if let Some(stride) = self.slot_stride(src)? + && let Some(element) = index + && !typed + && used.is_none() + { + let at = self.s.m.bin(c, Bin::Mul, element, stride); + off = self.s.m.bin(c, Bin::Add, at, off); + index = None; + } + // A structured buffer by its used-resource entry's stride: raw + // bytes too. The host makes its buffer views raw (a raw read + // through a structured view gives zeros on NVIDIA), and one kind + // of view can then serve every shader that reads the buffer. + if let (Some(element), Some(u)) = (index, used) + && !typed + && u.kind != ResourceType::Cbv + && u.stride >= 4 + && u.stride.is_multiple_of(4) + { + let k = self.s.m.i32(u.stride); + let at = self.s.m.bin(c, Bin::Mul, element, k); + off = self.s.m.bin(c, Bin::Add, at, off); + index = None; + } if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed { // A constant buffer read per lane (a dynamically indexed array). // shortcut: the console's CBV descriptor is taken to have a 16-byte @@ -6272,10 +9413,104 @@ impl<'a> Lower<'a> { let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav); let u = if uav { 0x1000 } else { 0 }; let iu = self.s.m.undef(self.s.t.i32); + if let Some((bits, signed)) = narrow { + // Below a dword: raw buffers are read and written in dwords on + // 4 bytes, so the dword that holds the value is read and + // shifted, or changed with two atomic operations that touch + // only the value's own bits (other lanes may write the rest of + // the dword at the same time). A 16-bit value at a dword's + // last byte continues in the next dword. + let byte = match index { + None => off, + Some(index) if used.is_some_and(|u| u.stride == 1) => { + self.s.m.bin(c, Bin::Add, index, off) + } + Some(_) => return Err("a byte or 16-bit buffer access by index"), + }; + let h = self.handle(site, src, false, (11 | u, 0))?; + let k3 = self.s.m.i32(3); + let within = self.s.m.bin(c, Bin::And, byte, k3); + let aligned = self.s.m.bin(c, Bin::Sub, byte, within); + let shift = self.s.m.bin(c, Bin::Shl, within, k3); + let four = self.s.m.i32(4); + let next = self.s.m.bin(c, Bin::Add, aligned, four); + let ones = self.s.m.i32(if bits == 8 { 0xff } else { 0xffff }); + let zero = self.s.m.i32(0); + let k8 = self.s.m.i32(8); + let straddles = self.s.m.cmp(c, pred::EQ, within, k3); + if !store { + let mask = self.s.m.i8(1); + let align = self.s.m.i32(4); + let dword = |l: &mut Self, at: V| { + let r = l.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + l.s.t.res_ret, + 139, + &[h, at, iu, mask, align], + ); + let f = l.s.m.extract(c, r, 0); + l.as_int(f) + }; + let low = dword(self, aligned); + let mut x = self.s.m.bin(c, Bin::LShr, low, shift); + if bits == 16 { + let high = dword(self, next); + let high = self.s.m.bin(c, Bin::Shl, high, k8); + let high = self.s.m.select(c, straddles, high, zero); + x = self.s.m.bin(c, Bin::Or, x, high); + } + x = self.s.m.bin(c, Bin::And, x, ones); + if signed { + let up = self.s.m.i32(32 - bits); + x = self.s.m.bin(c, Bin::Shl, x, up); + x = self.s.m.bin(c, Bin::AShr, x, up); + } + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + self.write(inst, Reg::V(reg), x, guard); + return Ok(()); + } + let d = data.as_ref().ok_or("buffer store data")?; + let v = self.vgprs(inst, d, 1)?[0]; + let v = self.s.m.bin(c, Bin::And, v, ones); + let all = self.s.m.i32(u32::MAX); + let clear = self.s.m.bin(c, Bin::Shl, ones, shift); + let keep = self.s.m.bin(c, Bin::Xor, clear, all); + let set = self.s.m.bin(c, Bin::Shl, v, shift); + let keep_next = self.s.m.i32(0xffff_ff00); + let set_next = self.s.m.bin(c, Bin::LShr, v, k8); + let (and, or) = (self.s.m.i32(1), self.s.m.i32(2)); + let i32t = self.s.t.i32; + let at = self.begin_guarded(guard); + for (op, x) in [(and, keep), (or, set)] { + let args = [h, op, aligned, iu, iu, x]; + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args); + } + if bits == 16 { + let second = self.begin_guarded(Some(straddles)); + for (op, x) in [(and, keep_next), (or, set_next)] { + let args = [h, op, next, iu, iu, x]; + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args); + } + self.end_guarded(second, &[]); + } + self.end_guarded(at, &[]); + return Ok(()); + } if let Some(op) = atomic { let d = data.as_ref().ok_or("buffer atomic data")?; let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?; let (h, coords) = match index { + // A raw buffer (stride 1) read by index: the index is the byte. + Some(index) if used.is_some_and(|u| u.stride == 1) => { + let byte = self.s.m.bin(c, Bin::Add, index, off); + (self.handle(site, src, false, (11 | u, 0))?, [byte, iu, iu]) + } Some(index) => { let stride = used.map_or(0, |u| u.stride); if stride < 4 || !stride.is_multiple_of(4) { @@ -6359,6 +9594,12 @@ impl<'a> Lower<'a> { (69, "bufferStore.f32") } else { match index { + // A raw buffer (stride 1) written by index: the index is the byte. + Some(index) if used.is_some_and(|u| u.stride == 1) => { + let byte = self.s.m.bin(c, Bin::Add, index, off); + args.push(self.handle(site, src, false, (11 | u, 0))?); + args.extend([byte, iu]); + } Some(index) => { let stride = used.map_or(0, |u| u.stride); if stride < 4 || !stride.is_multiple_of(4) { @@ -6420,6 +9661,19 @@ impl<'a> Lower<'a> { let mask = self.s.m.i8((1u8 << count) - 1); let align = self.s.m.i32(4); match index { + // A raw buffer (stride 1) read by index: the index is the byte. + Some(index) if used.is_some_and(|u| u.stride == 1) => { + let byte = self.s.m.bin(c, Bin::Add, index, off); + let h = self.handle(site, src, false, (11 | u, 0))?; + self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, byte, iu, mask, align], + ) + } Some(index) => { let stride = used.map_or(0, |u| u.stride); if stride < 4 || !stride.is_multiple_of(4) { @@ -6531,7 +9785,13 @@ impl<'a> Lower<'a> { } _ => None, }; - if let Some((row, (pack2, b))) = halves { + if let Some((row, (pack2, _))) = halves { + let packs: Vec<(u8, Option)> = self + .half_outputs + .iter() + .filter(|(_, h)| h.0) + .map(|(&r, h)| (r, h.1)) + .collect(); for ch in 0..4u8 { let Some(value) = e.values[usize::from(ch)] else { continue; @@ -6539,7 +9799,7 @@ impl<'a> Lower<'a> { for high in [false, true] { let h = 2 * ch + u8::from(high); let src = if pack2 { - packed_half(outputs, row, b, h) + packed_half(outputs, &packs, row, h) } else { (!high).then_some((row, ch)) }; @@ -6631,7 +9891,28 @@ impl<'a> Lower<'a> { } // A mesh lane writes its own vertex or primitive, where it exports. let at = if mesh { - self.begin_guarded(guard) + let flat = self.mesh_thread(); + let limit = if let Some(m) = self.s.mesh { + if primitive { + m.max_primitives + } else { + m.max_vertices + } + } else { + 0 + }; + let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX); + let mesh_guard = if limit > 0 && threads > limit { + let lim = self.s.m.i32(limit); + let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, lim); + match guard { + Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)), + None => Some(in_bounds), + } + } else { + guard + }; + self.begin_guarded(mesh_guard) } else { None }; @@ -6696,15 +9977,47 @@ impl<'a> Lower<'a> { fn emit_indices(&mut self, e: &Export, guard: Option) -> Result<(), Why> { let v = e.values[0].ok_or("a primitive export without its indices")?; let x = self.i32_of(v)?; + let flat = self.mesh_thread(); + let guard = if let Some(mesh) = self.s.mesh { + let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX); + if threads > mesh.max_primitives { + let p = self.s.m.i32(mesh.max_primitives); + let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, p); + match guard { + Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)), + None => Some(in_bounds), + } + } else { + guard + } + } else { + guard + }; let at = self.begin_guarded(guard); let c = self.cur; let z = self.s.m.i32(0); - let culled = self.s.m.cmp(c, pred::SLT, x, z); - let mut args = vec![self.mesh_thread()]; - for k in 0..3 { - let (shift, mask) = (self.s.m.i32(10 * k), self.s.m.i32(0x3FF)); + let mut culled = self.s.m.cmp(c, pred::SLT, x, z); + // A primitive that names a vertex past the declared count, or one + // no lane writes (lane n writes vertex n alone), is culled too: the + // host would read a vertex nothing set, at any position. + let written = self.s.mesh.map(|m| { + m.max_vertices + .min(self.s.threads.map_or(u32::MAX, |t| t[0])) + }); + let mut indices = [z; 3]; + for (k, slot) in indices.iter_mut().enumerate() { + let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x3FF)); let i = self.s.m.bin(c, Bin::LShr, x, shift); let i = self.s.m.bin(c, Bin::And, i, mask); + if let Some(n) = written { + let n = self.s.m.i32(n); + let past = self.s.m.cmp(c, pred::IUGE, i, n); + culled = self.s.m.bin(c, Bin::Or, culled, past); + } + *slot = i; + } + let mut args = vec![flat]; + for i in indices { args.push(self.s.m.select(c, culled, z, i)); } let void = self.s.t.void; @@ -6837,7 +10150,24 @@ impl<'a> Lower<'a> { let (phi, _) = self.counters[&to]; let one = self.s.m.i32(1); let next = self.s.m.bin(c, Bin::Add, phi, one); - let limit = self.s.m.i32(super::loop_limit()); + // Per stage unless the switch names one: a loop that never meets its + // exit (a count read from a buffer the host has not got yet, say) + // runs to the limit in every lane. A million iterations a pixel + // hung the GPU for seconds a draw until Windows reset it + // (PS_Textured_Eight, 2026-11-24, run 12). + // shortcut: a pixel loop past 128 iterations, a vertex or mesh loop + // past 256 or a compute loop past 4,096 is cut short. (They were + // 1,024, 4,096 and 65,536: the opening cutscene then lost the card + // 14-25 frames in, in a minimap or shadow mesh draw; with every + // loop cut at 64 it ran 90 frames. Raise them again once shaders + // stop reading data that is not there yet.) + let limit = match super::loop_limit() { + LOOP_LIMIT if self.s.pixel => 1 << 7, + LOOP_LIMIT if self.s.mesh.is_some() || self.s.threads.is_none() => 1 << 8, + LOOP_LIMIT => 1 << 12, + named => named, + }; + let limit = self.s.m.i32(limit); self.counters .get_mut(&to) .expect("header") @@ -6882,30 +10212,89 @@ impl<'a> Lower<'a> { fn fill_phis(&mut self) -> Result<(), Stop> { let p = self.x.p; - // A phi that only another read phi consumes is live too. Without this, a value with no DXIL form that - // reaches a read through two joins is taken for dead at the first join and replaced by zero below, and the - // lowering accepts what it refuses when the same value is read directly. - let mut work: Vec = self.read_phis.iter().copied().collect(); + // Lane-mask joins first (what an edge brings may ask for more joins, + // of masks and of numbers): each edge's mask as the structure + // tracked it, a constant or a scalar-built one included. + let st = self.x.st; + while let Some((v, b, i)) = self.pending_masks.pop() { + let phi = &p.blocks[b].phis[i]; + let offset = p.blocks[b].offset; + let args = st + .phi_masks + .get(&phi.value) + .ok_or_else(|| unsupported(offset, "a lane-mask join of an untracked mask"))?; + let mut incoming = Vec::new(); + for (n, &q) in p.blocks[b].preds.iter().enumerate() { + let Some(qb) = self.tail[q] else { continue }; + let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); + let x = self.boolean(args[n], qb).map_err(|w| unsupported(offset, w))?; + incoming.push((x, qb)); + } + self.s.m.set_phi(v, incoming); + } + // A join that only another join reads is read wherever that one is. Left + // unmarked, a value without a DXIL form coming into it became zero without a + // word (the looked-up tint of the material resolve programs, whose size + // computation had no value, was zero in every lane that way). + // shortcut: only with `VICTORY_STRICT_JOINS` set (the offline pack + // listing sets it to count them): 40 programs that translate today + // stop by name with it (vehicle paint pixel shaders at "the first + // half of an interpolation", foliage mesh shaders); until those are + // lowered they keep drawing with that zero. + static STRICT: std::sync::OnceLock = std::sync::OnceLock::new(); + let strict = *STRICT.get_or_init(|| std::env::var_os("VICTORY_STRICT_JOINS").is_some()); + let mut work: Vec = if strict { + self.read_phis.iter().copied().collect() + } else { + Vec::new() + }; while let Some(v) = work.pop() { let Some(&(b, i)) = self.phi_at.get(&v) else { continue; }; - for &arg in &p.blocks[b].phis[i].args { - if self.phi_at.contains_key(&arg) && self.read_phis.insert(arg) { - work.push(arg); + for &a in &p.blocks[b].phis[i].args { + if self.phi_at.contains_key(&a) && self.read_phis.insert(a) { + work.push(a); } } } for (v, b, i) in std::mem::take(&mut self.data_phis) { let phi = &p.blocks[b].phis[i]; let bit = phi.reg == Reg::Scc; + // A join of numbers with dead registers (`dead`): the paths that bring those + // never read the result, so they bring zero. Not for a join that is itself a + // lane mask (a ballot gives that one as data). + let st = self.x.st; + let numbers = !bit + && !st.masks.contains_key(&phi.value) + && !st.highs.contains_key(&phi.value) + && phi + .args + .iter() + .any(|a| matches!(self.vals.get(a), Some(Val::I32(_)))); let mut incoming = Vec::new(); for (n, &q) in p.blocks[b].preds.iter().enumerate() { let Some(qb) = self.tail[q] else { continue }; let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); let arg = phi.args[n]; + if self.read_phis.contains(&phi.value) && !self.vals.contains_key(&arg) { + let _ = self.lazy_barycentric(arg); + // A root parameter nothing read before the join (user + // data is loaded on first use, in the entry block). + if !self.vals.contains_key(&arg) + && let Some(&(param, dword)) = self.params.get(&arg) + { + let val = self.user(param, dword); + self.vals.insert(arg, val); + } + } let x = match (self.vals.get(&arg).copied(), bit) { (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x, + (Some(Val::Missing(_)) | None, false) + if numbers && self.dead(arg, &mut Vec::new()) => + { + self.s.m.i32(0) + } (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => { return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); } @@ -6925,26 +10314,24 @@ impl<'a> Lower<'a> { for (phi, incoming) in std::mem::take(&mut self.counters).into_values() { self.s.m.set_phi(phi, incoming); } - while let Some((v, b, i)) = self.pending_masks.pop() { - let phi = &p.blocks[b].phis[i]; - let offset = p.blocks[b].offset; - let mut incoming = Vec::new(); - for (n, &q) in p.blocks[b].preds.iter().enumerate() { - let Some(qb) = self.tail[q] else { continue }; - let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); - let m = - *self.x.st.masks.get(&phi.args[n]).ok_or_else(|| { - unsupported(offset, "a lane-mask join of an untracked mask") - })?; - let x = self.boolean(m, qb).map_err(|w| unsupported(offset, w))?; - incoming.push((x, qb)); - } - self.s.m.set_phi(v, incoming); - } Ok(()) } } +/// The DXIL interpolation mode of a kind of barycentrics (none for the +/// pull model). +fn interp_mode(kind: Barycentric) -> Option { + Some(match kind { + Barycentric::PerspectiveCenter => 2, + Barycentric::PerspectiveCentroid => 3, + Barycentric::PerspectiveSample => 6, + Barycentric::LinearCenter => 4, + Barycentric::LinearCentroid => 5, + Barycentric::LinearSample => 7, + Barycentric::PerspectivePullModel => return None, + }) +} + #[cfg(test)] mod tests { use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; @@ -6955,6 +10342,128 @@ mod tests { const S_ENDPGM: u32 = 0xBF81_0000; + #[test] + fn packed_pixel_inputs_find_their_second_row() { + use super::super::container::SigElement; + use super::half_input_partners; + use crate::native::{PsInput, Usage}; + let entry = |row, row2, pack2| PsInput { + usage: Usage::Generic, + row, + mask: 0xF, + attr: row, + flat: false, + fp16: true, + pack2, + row2, + }; + let element = |row| SigElement { + name: "TEXCOORD".into(), + index: row, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col: 0, + cols: 4, + usage: 0, + half: true, + }; + // Rows 0 and 3 pack and leave their second row out; 5 names its + // own (6). Unnamed 16-bit rows: 1, 4, 6, 7. + let io = StageIo::Ps { + inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }; + let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into(); + let p = half_input_partners(&io, &sig); + assert_eq!(p.get(&0), Some(&1)); + assert_eq!(p.get(&3), Some(&4)); + assert_eq!(p.get(&5), None); + } + + /// The packed pedestrian layouts of Grand Theft Auto VI: an element + /// behind another one in its register follows in the first parameter + /// with a dword left, and is not a half of its register's row. + #[test] + fn packed_elements_behind_another_take_the_first_free_dword() { + use super::super::container::SigElement; + use super::packed_half; + let element = |index, row, col, cols| SigElement { + name: "TEXCOORD".into(), + index, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col, + cols, + usage: 0, + half: true, + }; + // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel + // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4 + // column 3; parameter 3 (rows 6 and 7) carries it in dword 3. + let sig = vec![ + element(1, 2, 0, 4), + element(2, 3, 0, 4), + element(4, 4, 0, 3), + element(6, 4, 3, 1), + element(3, 5, 0, 4), + element(5, 6, 0, 4), + element(7, 7, 0, 2), + element(9, 9, 0, 3), + element(11, 10, 0, 3), + element(15, 12, 0, 4), + ]; + let packs = [ + (2, Some(3)), + (4, Some(5)), + (6, Some(7)), + (9, Some(10)), + (12, None), + ]; + let at = |a, h| packed_half(&sig, &packs, a, h); + // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3. + assert_eq!(at(4, 2), Some((4, 2))); + assert_eq!(at(4, 3), None); + assert_eq!(at(4, 4), Some((5, 0))); + assert_eq!(at(4, 7), Some((5, 3))); + // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone. + assert_eq!(at(6, 3), Some((6, 3))); + assert_eq!(at(6, 5), Some((7, 1))); + assert_eq!(at(6, 6), Some((4, 3))); + assert_eq!(at(6, 7), None); + // Parameters without such an element are as before. + assert_eq!(at(9, 3), None); + assert_eq!(at(9, 4), Some((10, 0))); + assert_eq!(at(12, 3), Some((12, 3))); + assert_eq!(at(12, 4), None); + // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at + // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1, + // TEXCOORD7. + let sig = vec![ + element(0, 1, 0, 2), + element(7, 1, 2, 2), + element(1, 2, 0, 4), + element(2, 3, 0, 4), + element(4, 4, 0, 3), + ]; + let packs = [(3, Some(4)), (1, Some(2))]; + let at = |a, h| packed_half(&sig, &packs, a, h); + assert_eq!(at(1, 1), Some((1, 1))); + assert_eq!(at(1, 2), Some((2, 0))); + assert_eq!(at(1, 5), Some((2, 3))); + assert_eq!(at(1, 6), Some((1, 2))); + assert_eq!(at(1, 7), Some((1, 3))); + assert_eq!(at(3, 6), Some((4, 2))); + assert_eq!(at(3, 7), None); + // A row no element holds gives nothing, as before. + assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None); + } + /// Whether a synthetic compute program translates with these input registers. fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); @@ -7049,6 +10558,14 @@ mod tests { } } + #[test] + fn buffer_cache_invalidations_lower_as_no_ops() { + // MUBUF opcode 0x071/0x072 with no data operand: the title asks the + // host to invalidate its cached view of a buffer. + assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv"); + assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv"); + } + #[test] fn a_scalar_carry_chain_reaches_the_select() { // The high dword of a 64-bit add or subtract, then a select on the @@ -7298,6 +10815,7 @@ mod tests { } #[test] + #[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"] fn a_missing_value_stays_missing_through_two_live_joins() { let mut words = [ 0xF490_0180, diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 89652da..d9003c1 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -50,10 +50,9 @@ //! descriptors (1,024 world compute programs, ray-tracing material //! resolves) read raw views this way. //! -//! * **Texture atomics** (added 2026-11-23): a texture UAV the shader uses -//! atomically is declared a 32-bit unsigned single-channel view; the -//! host's view at that index must be an R32 integer view (64-bit atomics -//! stop the translation). Global loads from a root SRV read it raw. +//! * **Texture atomics** use a scalar integer UAV. The host binds R32_UINT +//! for 32-bit operations and R32G32_UINT for 64-bit operations. The latter +//! require SM 6.6 atomic support on typed and descriptor-heap resources. //! //! Entry points: [`translate`] (container bytes as the title passes them //! at pipeline creation → [`HostShader`]), [`emit`] (the same with the @@ -74,16 +73,26 @@ //! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are //! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the //! console never exports them). +//! * **Rectangle lists** ([`rect_list_gs`], `gs_6_6`): the console draws a +//! rectangle from three vertices; the host has no such topology. A +//! pipeline the title makes for rectangles (topology type 19) gets a +//! geometry shader of ours between the translated vertex and pixel +//! shaders and draws triangle lists with the title's own vertex counts. +//! It binds nothing. mod bitcode; mod container; #[cfg(all(test, windows))] mod diff_tests; +#[cfg(all(test, windows))] +mod intersect_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; mod lower; +mod rect; mod sampler; mod shader; +mod threading; #[cfg(windows)] pub mod validator; #[cfg(all(test, windows))] @@ -97,7 +106,13 @@ use crate::native::{HwStage, NativeProgram, RootType}; use crate::{ShaderError, io, ir, resource, structure}; pub use sampler::StaticSampler; -pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; +pub use lower::set_host_max_wave; +pub use rect::rect_list_gs; +pub use shader::{ + MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, + SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, + set_view_heap_limit, +}; /// The loop limit without an override: 2^20. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; @@ -122,6 +137,33 @@ pub fn loop_limit() -> u32 { }) } +/// Which of a translated program's group barriers wait for the whole +/// group (`GroupMemoryBarrierWithGroupSync`); the others keep their memory +/// fence and lose the wait. A wait that some thread of the group never +/// reaches is undefined on the host, and NVIDIA's wait is for every +/// thread: the group stands until Windows resets the card. (The console's +/// barrier is the wave's, whatever lanes are live, and a wave that ended +/// is not waited for.) `VICTORY_GROUP_SYNC`: +/// - unset or `2`: every barrier waits, as before. +/// - `1`: the title's `s_barrier` waits only in a block every lane runs, +/// in a program no lane can be cut out of at the iteration limit. +/// - `0`: no barrier waits, neither the title's nor the ones the +/// translation adds (wave64 programs in two host waves exchange through +/// them, so such programs compute wrong values). For one run that tells +/// whether a barrier is what stops the card: with it no run can stand in +/// a barrier. +/// +/// Part of the translation: the shader cache keys on it (`victory-gpu`'s +/// does). +pub fn group_sync() -> u8 { + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_GROUP_SYNC").ok().as_deref().map(str::trim) { + Some("0") => 0, + Some("1") => 1, + _ => 2, + }) +} + /// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset, /// unreadable or 0. Pure, for testing. fn parse_loop_limit(value: Option<&str>) -> u32 { @@ -156,6 +198,11 @@ pub struct HostShader { /// Root SRVs (raw buffers) the shader reads: `t` in /// [`ROOT_CBV_SPACE`]. pub root_srvs: Vec, + /// Root UAVs (raw buffers) the shader reads or writes: `u` in + /// [`ROOT_CBV_SPACE`]. + pub root_uavs: Vec, + /// Heap descriptors that can be selected from root state at bind time. + pub root_indexed_views: Vec, } impl HostShader { @@ -204,7 +251,7 @@ pub fn translate(container: &[u8]) -> Result { offset: 0, what: "a container without a vertex, pixel, compute or mesh program", })?; - let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let p = crate::spill::build(&native)?; // Structurisation first: tracing per-lane descriptors needs it (its // failure is reported after the earlier stages'). let st = structure::structure(&p); @@ -223,6 +270,139 @@ pub fn emit( io: &io::Io, res: &resource::Resources, ) -> Result { + let original = emit_program(c, native, p, st, io, res); + // A console wave64 compute program on a host of 32-lane waves that + // still needs 64 lanes, or whose cross-lane code sits where not every + // lane runs: once more with its early-outs left out + // ([`ir::without_early_outs`]), which is what usually keeps the whole + // body from being a block every lane runs. + let stuck = match &original { + Ok((_, wave)) => *wave == Some(64), + Err(ShaderError::Unsupported { what, .. }) => what.ends_with("where not every lane runs"), + Err(_) => false, + }; + if stuck && native.stage == HwStage::Cs && native.wave64 && lower::host_max_wave() == 32 { + let why = std::env::var_os("VICTORY_WAVE_WHY").is_some(); + let report = |what: &str, r: &Result<(HostShader, Option), ShaderError>| { + if why { + match r { + Ok((_, wave)) => eprintln!("WAVE64-RETRY {what}: wave {wave:?}"), + Err(e) => eprintln!("WAVE64-RETRY {what}: {e}"), + } + } + }; + let done = |r: &Result<(HostShader, Option), ShaderError>| matches!(r, Ok((_, wave)) if *wave != Some(64)); + // Each host wave as a wave of its own (`lower::with_local_waves`), + // for programs still stopped where not every lane runs. + let local_on = std::env::var_os("VICTORY_WAVE_LOCAL").is_none_or(|v| v != "0"); + // Where the wave operations are the allocation idiom + // ([`lower::wave_local`]) that is exact. Other programs are taken + // the same way last of all, each half-wave giving its own results + // (approximate: a tile-wide result becomes two half-tile ones); + // `VICTORY_WAVE_LOCAL=idiom` refuses those instead. + let strict = std::env::var_os("VICTORY_WAVE_LOCAL").is_some_and(|v| v == "idiom"); + let idiom = |p: &ir::Program, st: &structure::Structured| match lower::wave_local(p, st) { + Ok(()) => true, + Err((offset, what)) => { + if why { + eprintln!("WAVE64-RETRY local waves: not the allocation idiom at {offset:#x}: {what}"); + } + false + } + }; + // The program in two other forms: without its early-outs, and + // without any branch that only skips code no lane is left for. + let form = |p: Option| { + p.and_then(|p| { + let st = structure::structure(&p).ok()?; + let io = io::raise(&p, native).ok()?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?; + Some((p, st, io, res)) + }) + }; + let forms = [ + ("without early-outs", form(ir::without_early_outs(p))), + ("without skips", form(ir::without_skips(p))), + ]; + for (name, f) in &forms { + if let Some((p, st, io, res)) = f { + let again = emit_program(c, native, p, st, io, res); + report(name, &again); + if done(&again) { + return again.map(|(shader, _)| shader); + } + } + } + if local_on { + // exact first (every form), then approximate + for exact in [true, false] { + if !exact && strict { + break; + } + for (name, f) in &forms { + if let Some((p, st, io, res)) = f + && idiom(p, st) == exact + { + let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); + report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + if idiom(p, st) == exact { + let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); + report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + // Last: every mask and lane read per host wave. + if !strict { + for (name, f) in &forms { + if let Some((p, st, io, res)) = f { + let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); + report(&format!("local waves (APPROXIMATE, any mask), {name}"), &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); + report("local waves (APPROXIMATE, any mask)", &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + } + let original = original.map(|(shader, _)| shader); + // Retry unsupported programs only. Threading can separate an unknown + // register value from its apparent use on a mutually exclusive path. + if !matches!(original, Err(ShaderError::Unsupported { .. })) { + return original; + } + let edges = threading::constant_edges(p, st); + if edges.is_empty() { + return original; + } + let p = ir::thread_edges(p, &edges)?; + let st = structure::structure(&p)?; + let io = io::raise(&p, native)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader) +} + +/// The translated program, and the wave size it requires of the host. +fn emit_program( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + st: &structure::Structured, + io: &io::Io, + res: &resource::Resources, +) -> Result<(HostShader, Option), ShaderError> { let sig = |fourcc| -> Result, ShaderError> { match c.part(fourcc) { Some(part) => signature(part.data), @@ -241,6 +421,8 @@ pub fn emit( // Constant, as DXC declares it (the AMD compiler crashed on a // front face without a mode). (13, _) => 1, + // Until a read says which mode (`lower`). + (28, _) => 2, (0 | 6 | 7, 9) => 2, (0, _) => 1, _ => 0, @@ -289,7 +471,8 @@ pub fn emit( prims, mesh_stride, })?; - Ok(HostShader { + let wave_size = l.wave_size; + let shader = HostShader { stage: native.stage, dxil: l.dxil, user_data: l.user_data, @@ -308,7 +491,10 @@ pub fn emit( samplers: l.samplers, root_cbvs: l.root_cbvs, root_srvs: l.root_srvs, - }) + root_uavs: l.root_uavs, + root_indexed_views: res.root_indexed_views.clone(), + }; + Ok((shader, wave_size)) } /// The rows of an `ISG1`/`OSG1` part. @@ -358,6 +544,7 @@ fn signature(part: &[u8]) -> Result, ShaderError> { 68 => 18, 69 => 20, 70 => 15, + 23 => 28, // barycentrics 25 => 30, // cull primitive _ => { return Err(ShaderError::Unsupported { @@ -486,11 +673,12 @@ mod tests { } /// A wave64 compute program that writes only EXEC's high dword - /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask is + /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was /// opaque and keyed by the unchanged low dword, so building its lane bit /// needed the mask's own value: lowering recursed until the stack /// overflowed, which takes the whole process down (found by - /// random-input testing). Now the instruction fails like any other that + /// random-input testing). Now that low dword, seen with two high + /// dwords, has no mask, and the instruction fails like any other that /// cannot be expressed: its result is missing, and only a side effect /// that uses it would stop the translation. #[test] @@ -520,6 +708,108 @@ mod tests { } } + /// A wave64 compute program: `body`, then a store of v1 to a UAV. + fn stores_v1(body: &[u32]) -> Result<(), ShaderError> { + use crate::native::RootParam; + use crate::{ResourceType, RootType, UsedResource}; + // s_mov_b32 s1, 0; s_load_dwordx4 s[8:11], s[0:1], 0 + let mut words = vec![0xBE81_0380, 0xF408_0200, 0xFA00_0000]; + words.extend_from_slice(body); + // v_lshlrev_b32 v3, 2, v0; buffer_store_dword v1, v3, s[8:11], 0 offen; + // s_endpgm + words.extend_from_slice(&[0x3406_0082, 0xE070_1000, 0x8002_0103, 0xBF81_0000]); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 4, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 2, + threads: [64, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + let container = crate::dxbc::build(&[]); + let c = Container::parse(&container).unwrap(); + emit(&c, &native, &p, &st, &io, &res).map(|_| ()) + } + + /// The high dword of a wave64 mask rewritten alone (`s_mov_b32 vcc_hi` + /// or `exec_hi`): lanes 32-63 took the mask the low dword was first + /// written with (the compare's, EXEC's on entry). Now the store refuses; + /// without the write it translates. + #[test] + fn a_mask_whose_high_dword_is_rewritten_is_refused() { + // v_cmp_eq_u32 vcc, 0, v0; v_mov_b32 v2, 11; v_cndmask_b32 v1, 0, v2, vcc + let select = [0x7D84_0080, 0x7E04_028B, 0x0202_0480]; + // The same with v_add_co_ci_u32 v1, vcc, 0, v2, vcc. + let carry = [0x7D84_0080, 0x7E04_028B, 0x5002_0480]; + // v_mov_b32 v1, 7 + let mov = [0x7E02_0287]; + for body in [&select[..], &carry, &mov] { + stores_v1(body).unwrap(); + } + // s_mov_b32 vcc_hi, 0 after the compare. + let select_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x0202_0480]; + let carry_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x5002_0480]; + // s_mov_b32 exec_hi, 0; v_mov_b32 v1, 7, then the same after + // s_mov_b64 s[2:3], exec. + let exec_hi = [0xBEFF_0380, 0x7E02_0287]; + let exec_hi_saved = [0xBE82_047E, 0xBEFF_0380, 0x7E02_0287]; + for body in [&select_hi[..], &carry_hi, &exec_hi, &exec_hi_saved] { + assert!(stores_v1(body).is_err(), "{body:x?}"); + } + } + + /// `ds_bpermute_b32` stores nothing: each lane reads the lane its address + /// names. It stopped as "LDS the program does not allocate" (sticky lips) + /// or "an LDS operation" (the checkerboard shadow masks). + #[test] + fn a_backward_permute_reads_the_lane_its_address_names() { + // v_mov_b32 v2, 11; ds_bpermute_b32 v1, v0, v2 + stores_v1(&[0x7E04_028B, 0xDACC_0000, 0x0100_0200]).unwrap(); + } + + /// A carry-in reading a join of compares after a divergent branch. A + /// lane that skipped the inner compare has VCC clear there (VOPC clears + /// inactive lanes), not the first compare's bit, so the join is no + /// per-lane phi: lowering refuses it. + #[test] + fn a_carry_in_from_a_divergent_join_is_refused() { + let body = [ + 0x7E04_028B, // v_mov_b32 v2, 11 + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBE82_376A, // s_andn1_saveexec_b64 s[2:3], vcc + 0xBF88_0001, // s_cbranch_execz 1 + 0x7D84_0081, // v_cmp_eq_u32 vcc, 1, v0 + 0x88FE_027E, // s_or_b64 exec, exec, s[2:3] + 0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc + ]; + let e = stores_v1(&body).unwrap_err().to_string(); + assert!(e.contains("a carry-in from an untracked mask"), "{e}"); + } + /// A pixel shader writing a constant colour. #[cfg(windows)] fn constant_color() -> Vec { @@ -565,6 +855,8 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), }; let file = |var: &str, stage| { std::env::var(var).ok().map(|p| super::HostShader { @@ -575,6 +867,8 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), }) }; let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps); @@ -746,4 +1040,528 @@ mod tests { // Translated or refused with a reason; it must not panic. let _ = super::emit(&c, &native, &p, &st, &io, &res); } + + #[test] + fn valu_div_f32_sequence_executes_on_gpu() { + let words: &[u32] = &[ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 + 0xF408_0302, + 0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20 + 0x340E_0083, // v_lshlrev_b32 v7, 3, v0 + 0xE034_1000, + 0x8002_0107, // buffer_load_dwordx2 v[1:2], v7, s[8:11], 0 offen + 0xD56D_6A03, + 0x0406_0502, // v_div_scale_f32 v3, vcc_lo, v2, v2, v1 + 0xD56D_1008, + 0x0406_0501, // v_div_scale_f32 v8, s16, v1, v2, v1 + 0x7E08_5503, // v_rcp_f32 v4, v3 + 0xD54B_0005, + 0x23CA_0903, // v_fma_f32 v5, -v3, v4, 1.0 + 0xD54B_0004, + 0x0412_0905, // v_fma_f32 v4, v5, v4, v4 + 0x100A_0908, // v_mul_f32 v5, v8, v4 + 0xD54B_0006, + 0x2422_0B03, // v_fma_f32 v6, -v3, v5, v8 + 0xD56F_0004, + 0x0416_0906, // v_div_fmas_f32 v4, v6, v4, v5 + 0xD55F_0001, + 0x0406_0504, // v_div_fixup_f32 v1, v4, v2, v1 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 + 0xE070_1000, + 0x8003_0107, // buffer_store_dword v1, v7, s[12:15], 0 offen + 0xBF81_0000, // s_endpgm + ]; + let native = super::NativeProgram { + stage: super::HwStage::Cs, + wave64: false, + vgprs: 9, + layout: vec![ + crate::RootParam { + root: crate::RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + crate::RootParam { + root: crate::RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![ + crate::UsedResource { + kind: crate::ResourceType::Srv, + root: crate::RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }, + crate::UsedResource { + kind: crate::ResourceType::Uav, + root: crate::RootType::Table, + table_offset_dwords: 8, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }, + ], + io: crate::native::StageIo::Cs(crate::native::ComputeIo { + rsrc2: 5 << 1, + threads: [7, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + let l = super::lower::lower(&super::lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .unwrap(); + let mut dxil = l.dxil; + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut dxil).unwrap(); + } + #[cfg(windows)] + if let Ok(host) = super::host::Host::new(false) { + let cs = super::HostShader { + stage: super::HwStage::Cs, + dxil, + user_data: l.user_data, + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: l.root_cbvs, + root_srvs: l.root_srvs, + root_uavs: l.root_uavs, + root_indexed_views: Vec::new(), + }; + let (root, pso) = host.compute_pipeline(&cs).unwrap(); + let inputs: Vec = [ + 7.0f32, 3.0, -1.0, 1e-40, 1.0, 1e35, 1e-35, 1e-36, 0.0, 0.0, -1.0, 0.0, -1e35, 1e35, + ] + .into_iter() + .map(f32::to_bits) + .collect(); + let out = host + .dispatch( + &root, + &pso, + &super::host::Dispatch { + roots: vec![(0, super::host::Root::Constants(vec![0, 0, 0, 0, 0]))], + views: &[ + super::host::View::Buffer { + data: &inputs, + stride: super::host::Stride::Raw, + }, + super::host::View::RawUav(64), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap(); + let got: Vec = out[0][..7].iter().copied().map(f32::from_bits).collect(); + assert!((got[0] - (7.0f32 / 3.0)).abs() < 1e-6, "got {:?}", got); + assert_eq!(out[0][1], (-1.0f32 / 1e-40).to_bits()); + assert!( + (got[2] - 1e-35).abs() <= 1e-40, + "lane 2 got {:?} ({:#x})", + got[2], + out[0][2] + ); + assert!( + (got[3] - 10.0).abs() < 1e-5, + "lane 3 got {:?} ({:#x})", + got[3], + out[0][3] + ); + assert_eq!(out[0][4], 0xFFC0_0000); + assert_eq!(out[0][5], (-1.0f32 / 0.0).to_bits()); + assert!( + (got[6] - (-1.0)).abs() < 1e-6, + "lane 6 got {:?} ({:#x})", + got[6], + out[0][6] + ); + } + } +} + +#[cfg(test)] +mod atomic_tests { + use super::*; + use crate::native::{ComputeIo, RootParam, StageIo}; + + #[test] + fn heap_texture_atomic_widths() { + // A synthetic compute shader loads a 2D UAV from a root table, + // compares or adds at (0, 0), then uses the returned register(s). + for (opcode, mask, wide) in [ + (16u32, 3, false), + (16, 15, true), + (17, 1, false), + (17, 3, true), + ] { + let words = [ + 0xBE81_0380, // s_mov_b32 s1, 0 (table address high) + 0xF40C_0200, + 0xFA00_0000, // s_load_dwordx8 s[8:15], s[0:1], 0 + 0x7E00_0280, + 0x7E02_0280, // v0, v1 = coordinates + 0x7E04_0281, + 0x7E06_0282, + 0x7E08_0283, + 0x7E0A_0284, // v2..v5 = 1..4 + 0xF000_2008 | opcode << 18 | mask << 8, + 0x0002_0200, + // Use the old value in a second atomic at the same location. + 0xF044_0008 | (if wide { 3 } else { 1 }) << 8, + 0x0002_0200, + 0xBF81_0000, + ]; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 6, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 2, + threads: [32, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, false, native.vgprs).unwrap(); + let bytes = crate::dxbc::build(&[]); + let shader = emit( + &Container::parse(&bytes).unwrap(), + &native, + &p, + &structure::structure(&p).unwrap(), + &io::raise(&p, &native).unwrap(), + &resource::track(&p, &native.layout, native.stage, None).unwrap(), + ) + .unwrap(); + let container = Container::parse(&shader.dxil).unwrap(); + let features = u64::from_le_bytes( + container + .part(FourCC::SFI0) + .unwrap() + .data + .try_into() + .unwrap(), + ); + let required = 0x1040_8000; // heap atomics, typed atomics, Int64Ops + assert_eq!(features & required, if wide { required } else { 0 }); + #[cfg(windows)] + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut shader.dxil.clone()).unwrap(); + } + } + } +} + +#[cfg(test)] +mod barycentric_tests { + use super::container::SigElement; + use super::*; + use crate::native::{PsInput, StageIo, Usage}; + + /// `SPI_PS_INPUT_ADDR` bits: PERSP_CENTER, LINEAR_CENTER. + const PERSP_CENTER: u32 = 1 << 1; + const LINEAR_CENTER: u32 = 1 << 5; + + /// `exp mrt0, v, v, v, v done vm`. + fn exp_mrt0(r: u32) -> [u32; 2] { + [0xF800_180F, r * 0x0101_0101] + } + + /// VOP2 `v_add_f32 v, v, v`. + fn v_add_f32(dst: u32, a: u32, b: u32) -> u32 { + 3 << 25 | dst << 17 | b << 9 | (256 + a) + } + + fn element(name: &str, kind: u8, row: u32) -> SigElement { + SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp: 0, + row: Some(row), + col: 0, + cols: 4, + usage: 0, + half: false, + } + } + + /// Translates a pixel program with the input VGPRs `input_addr` + /// enables and one float4 TEXCOORD0 attribute (attr 0, row 0). + fn pixel(words: &[u32], input_addr: u32) -> Result { + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 8, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![PsInput { + usage: Usage::Generic, + row: 0, + mask: 0b1111, + attr: 0, + flat: false, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let mut target = element("SV_Target", 16, 0); + target.usage = 15; + let isg1 = container::signature(&[element("TEXCOORD", 0, 0)], true); + let osg1 = container::signature(&[target], false); + let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let res = resource::track(&p, &native.layout, native.stage, None)?; + let io = io::raise(&p, &native)?; + let st = structure::structure(&p)?; + emit(&c, &native, &p, &st, &io, &res) + } + + /// The translation's `SFI0` features and `ISG1` rows. + fn parts(shader: &HostShader) -> (u64, Vec) { + let c = Container::parse(&shader.dxil).unwrap(); + let sfi0 = c.part(FourCC::SFI0).unwrap().data.try_into().unwrap(); + ( + u64::from_le_bytes(sfi0), + signature(c.part(FourCC::ISG1).unwrap().data).unwrap(), + ) + } + + fn validate(shader: &HostShader) { + #[cfg(windows)] + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut shader.dxil.clone()).unwrap(); + } + let _ = shader; + } + + /// Custom interpolation reads I and J (v0, v1 with PERSP_CENTER) as + /// plain floats: they are channels y and z of `SV_Barycentrics`, the + /// weights of vertices 1 and 2. + #[test] + fn barycentrics_read_as_values_are_sv_barycentrics() { + let [e0, e1] = exp_mrt0(2); + let words = [v_add_f32(2, 0, 1), e0, e1, 0xBF81_0000]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature"); + let bary: Vec<_> = inputs.iter().filter(|e| e.kind == 28).collect(); + assert_eq!(bary.len(), 1, "{inputs:?}"); + assert_eq!((bary[0].index, bary[0].col, bary[0].cols), (0, 0, 3)); + // Not packed: the validator wants packing location -1. + assert_eq!(bary[0].row, None); + // Only y and z (I and J) are read. + let isg1 = Container::parse(&shader.dxil).unwrap(); + let isg1 = isg1.part(FourCC::ISG1).unwrap().data; + let rw: Vec = (0..2).map(|k| isg1[8 + 32 * k + 25]).collect(); + assert!(rw.contains(&0b110), "{rw:?}"); + validate(&shader); + } + + /// Two kinds of barycentrics read directly: one element per mode. + #[test] + fn two_barycentric_modes_get_two_elements() { + // v0-v1 perspective i, j; v2-v3 linear i, j. + let [e0, e1] = exp_mrt0(4); + let words = [v_add_f32(4, 0, 3), e0, e1, 0xBF81_0000]; + let shader = pixel(&words, PERSP_CENTER | LINEAR_CENTER).unwrap(); + let (_, inputs) = parts(&shader); + let mut indices: Vec = inputs + .iter() + .filter(|e| e.kind == 28) + .map(|e| e.index) + .collect(); + indices.sort(); + assert_eq!(indices, [0, 1], "{inputs:?}"); + validate(&shader); + } + + /// I and J only fed to `v_interp_*` stay host interpolation: no + /// barycentrics are declared. + #[test] + fn interpolation_alone_declares_no_barycentrics() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + e0, + e1, + 0xBF81_0000, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_eq!(features & 0x2_0000, 0); + assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}"); + validate(&shader); + } + + /// Both: the attribute is interpolated and J is used as a value. + #[test] + fn interpolation_and_a_barycentric_value_together() { + let [e0, e1] = exp_mrt0(3); + let words = [ + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + v_add_f32(3, 2, 1), // v3 = attribute + j + e0, + e1, + 0xBF81_0000, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0); + assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1); + validate(&shader); + } + /// The `PSV0` interpolation mode of TEXCOORD0 (row 0, x-w, float). + fn texcoord_mode(shader: &HostShader) -> u8 { + let c = Container::parse(&shader.dxil).unwrap(); + let psv = c.part(FourCC::PSV0).unwrap().data; + let row = [1, 0, 0x44, 0, 3]; + let at = psv.windows(5).position(|w| w == row).unwrap(); + psv[at + 5] + } + + const S_ENDPGM: u32 = 0xBF81_0000; + + /// An interpolation whose i is computed (`v_mul_f32 v3, 0.5, v0`) reads + /// the attribute's vertices: TEXCOORD0 becomes constant, read with + /// `attributeAtVertex`; i and j are `SV_Barycentrics` values. + #[test] + fn computed_barycentrics_read_the_vertices() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0x1006_00F0, // v_mul_f32 v3, 0.5, v0 + 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature"); + assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + } + + /// Weights from constants alone: the vertices, no `SV_Barycentrics`. + #[test] + fn constant_weights_need_no_barycentrics() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0x7E06_02F0, // v_mov_b32 v3, 0.5 + 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x + 0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature"); + assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}"); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + } + + /// The same attribute interpolated with the loaded i and j and with a + /// computed j: both from its vertices, the first weighed with + /// `SV_Barycentrics`. + #[test] + fn computed_and_loaded_barycentrics_on_one_attribute() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0xC810_0100, // v_interp_p1_f32 v4, v0, attr0.y + 0xC811_0101, // v_interp_p2_f32 v4, v1, attr0.y + 0x1006_02F0, // v_mul_f32 v3, 0.5, v1 + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x + v_add_f32(2, 2, 4), + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (_, inputs) = parts(&shader); + assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + } + + /// P10 of an attribute the program interpolates is P1 - P0. + #[test] + fn p10_of_an_interpolated_attribute() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + 0xC812_0000, // v_interp_mov_f32 v4, p10, attr0.x + v_add_f32(2, 2, 4), + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + // Alone, what the hardware holds is not known. + let [e0, e1] = exp_mrt0(4); + let words = [0xC812_0000, e0, e1, S_ENDPGM]; + assert!(pixel(&words, PERSP_CENTER).is_err()); + } } diff --git a/crates/victory-shader/src/emit/rect.rs b/crates/victory-shader/src/emit/rect.rs new file mode 100644 index 0000000..c05f28b --- /dev/null +++ b/crates/victory-shader/src/emit/rect.rs @@ -0,0 +1,484 @@ +//! The geometry shader that completes the console's rectangle lists (list +//! topology 17, pipeline topology type 19). A rectangle comes as three +//! vertices, three corners of a screen-aligned rectangle; the hardware +//! draws the whole rectangle and continues every vertex shader output +//! linearly into the fourth corner. The host has no such topology: the +//! draw goes out as a triangle list with this shader behind the translated +//! vertex shader, so vertex counts, vertex numbers, indices and indirect +//! arguments stay the title's, and each rectangle arrives here as one +//! triangle. +//! +//! Which vertex is the corner between the other two varies: Grand Theft +//! Auto VI's full-screen rectangles come as top left, bottom left, bottom +//! right (the second), its tiled lighting as top left, bottom left, top +//! right (the first). The corner is the vertex that shares x with one of +//! the others and y with the other; the fourth vertex lies opposite it, +//! `a + b - corner` for the position and every float output. That holds +//! for three vertices with one positive w (then it is the same in clip +//! space and on the screen, whatever the interpolation mode); three that +//! differ in w, or are not such corners, stay the triangle they make. +//! +//! Flat values are the first vertex's: both triangles start with it (the +//! halves on either side of the diagonal through it, turning as the three +//! vertices do), which is the vertex the host takes a flat input from, and +//! the fourth vertex's integer outputs are the first vertex's. +//! +//! shortcut: that the console takes a rectangle's flat values from its +//! first vertex follows from the hardware's provoking-vertex setting for +//! triangles; it is not measured on a rectangle. + +use super::bitcode::{Attr, Bin, Term, V, pred}; +use super::container::SigElement; +use super::shader::{Geometry, Shader}; +use crate::ShaderError; +use crate::dxbc::{Container, FourCC}; + +/// Vertices emitted per rectangle: two triangles. +const VERTICES: u32 = 6; + +/// The scalars a geometry shader may emit per invocation (vertices times +/// output components). +const MAX_SCALARS: u32 = 1024; + +/// The geometry shader (a DXIL container) for rectangle lists drawn with +/// the translated vertex shader `vs` and, if the pipeline has one, the +/// translated pixel shader `ps` (both as [`super::HostShader::dxil`]). Its +/// inputs and outputs are the vertex shader's outputs, register for +/// register, so it links with both. A pixel shader that declares a +/// primitive id gets the rectangle's number, which the host leaves to the +/// geometry stage when there is one. +pub fn rect_list_gs(vs: &[u8], ps: Option<&[u8]>) -> Result, ShaderError> { + let sig = |dxil: &[u8], fourcc| -> Result, ShaderError> { + let c = Container::parse(dxil)?; + match c.part(fourcc) { + Some(part) => super::signature(part.data), + None => Ok(Vec::new()), + } + }; + let outputs = sig(vs, FourCC::OSG1)?; + let wanted = match ps { + Some(ps) => sig(ps, FourCC::ISG1)?, + None => Vec::new(), + }; + build(outputs, &wanted) +} + +/// [`rect_list_gs`] from the vertex shader's outputs and the pixel +/// shader's inputs. +fn build(mut outputs: Vec, ps_inputs: &[SigElement]) -> Result, ShaderError> { + let unsupported = |what| ShaderError::Unsupported { offset: 0, what }; + if outputs.iter().any(|e| e.row.is_none()) { + return Err(unsupported("a rectangle list output without a register")); + } + let Some(position) = outputs + .iter() + .position(|e| e.kind == 3 && e.comp == 9 && e.cols == 4) + else { + return Err(unsupported("a rectangle list without a four-component position")); + }; + for e in &mut outputs { + // Interpolation as `emit_program` declares a vertex shader's + // outputs; a geometry shader's inputs carry the same modes. + e.interp = match (e.kind, e.comp) { + (3, _) => 4, + (0 | 6 | 7, 9) => 2, + (0, _) => 1, + _ => 0, + }; + e.usage = (1 << e.cols) - 1; + } + let mut s = Shader::new(false); + s.geometry = Some(Geometry { + max_vertices: VERTICES, + }); + s.inputs = outputs.clone(); + // The primitive id the pixel shader declares, as one more output. + let wanted = ps_inputs + .iter() + .find(|e| e.kind == 10 && e.row.is_some()) + .filter(|_| !outputs.iter().any(|o| o.kind == 10)); + let primitive = match wanted { + Some(e) => { + // Alone in its columns, and in a row of constant elements. + let clash = outputs.iter().any(|o| { + let overlap = o.col < e.col + e.cols && e.col < o.col + o.cols; + o.row == e.row && (o.interp != 1 || overlap) + }); + if clash { + return Err(unsupported( + "a rectangle list whose primitive id shares a register with a vertex output", + )); + } + outputs.push(SigElement { + interp: 1, + usage: (1 << e.cols) - 1, + ..e.clone() + }); + Some(outputs.len() - 1) + } + None => None, + }; + let scalars: u32 = outputs.iter().map(|e| u32::from(e.cols)).sum(); + if scalars * VERTICES > MAX_SCALARS { + return Err(unsupported( + "a rectangle list with more output components than a geometry shader emits", + )); + } + s.outputs = outputs; + let b = s.entry; + + // Every input of the three vertices: [element][column][vertex]. + let mut corners: Vec> = Vec::new(); + for id in 0..s.inputs.len() { + let mut columns = Vec::new(); + for col in 0..s.inputs[id].cols { + columns.push([0, 1, 2].map(|vertex| load(&mut s, id, col, vertex))); + } + corners.push(columns); + } + + // One positive w, and no two vertices in one place. + let (x, y, w) = ( + corners[position][0], + corners[position][1], + corners[position][3], + ); + let zero = s.m.f32(0); + let mut plain = s.m.cmp(b, pred::OGT, w[0], zero); + for &other in &w[1..] { + let one_w = same(&mut s, other, w[0]); + plain = both(&mut s, plain, one_w); + } + for (i, j) in [(0, 1), (0, 2), (1, 2)] { + let (same_x, same_y) = (same(&mut s, x[i], x[j]), same(&mut s, y[i], y[j])); + let together = both(&mut s, same_x, same_y); + let apart = not(&mut s, together); + plain = both(&mut s, plain, apart); + } + // corner[i]: vertex i is the corner between the other two (the first + // that shares x with one of them and y with the other). + let mut corner: Vec = Vec::new(); + for i in 0..3 { + let (a, c) = ((i + 1) % 3, (i + 2) % 3); + let (xa, yc) = (same(&mut s, x[i], x[a]), same(&mut s, y[i], y[c])); + let (xc, ya) = (same(&mut s, x[i], x[c]), same(&mut s, y[i], y[a])); + let (one, other) = (both(&mut s, xa, yc), both(&mut s, xc, ya)); + let shares = either(&mut s, one, other); + let mut here = both(&mut s, shares, plain); + for &found in &corner { + let earlier = not(&mut s, found); + here = both(&mut s, here, earlier); + } + corner.push(here); + } + + // What the six emitted vertices carry: [element][column][vertex]. + let mut emitted: Vec> = Vec::new(); + for (id, columns) in corners.iter().enumerate() { + let float = s.inputs[id].comp == 9; + let mut out = Vec::new(); + for &[p0, p1, p2] in columns { + // The fourth vertex: `a + b - corner`. Integers (flat), and + // three vertices without a corner, keep the first vertex's + // value; the second triangle of the latter is then empty. + let mut fourth = p0; + if float { + for (k, (a, c, at)) in [(p1, p2, p0), (p2, p0, p1), (p0, p1, p2)] + .into_iter() + .enumerate() + { + let sum = s.m.bin(b, Bin::Add, a, c); + let opposite = s.m.bin(b, Bin::Sub, sum, at); + fourth = s.m.select(b, corner[k], opposite, fourth); + } + } + // Corner first: (v0, v1, v3), (v0, v3, v2). Second: (v0, v1, + // v2), (v0, v2, v3). Third: (v0, v1, v2), (v0, v3, v1). + let third = s.m.select(b, corner[0], fourth, p2); + let fifth = s.m.select(b, corner[1], p2, fourth); + let sixth = s.m.select(b, corner[0], p2, p1); + let sixth = s.m.select(b, corner[1], fourth, sixth); + out.push([p0, p1, third, p0, fifth, sixth]); + } + emitted.push(out); + } + + // The rectangle's number: the triangle's, three vertices a rectangle. + let mut number = None; + if let Some(id) = primitive { + let n = s.op(b, "primitiveID.i32", Attr::ReadNone, s.t.i32, 108, &[]); + number = Some((id, n)); + } + let stream = s.m.i8(0); + for vertex in 0..VERTICES as usize { + for (id, columns) in emitted.iter().enumerate() { + let name = if s.outputs[id].comp == 9 { + "storeOutput.f32" + } else { + "storeOutput.i32" + }; + for (col, values) in columns.iter().enumerate() { + let args = [ + s.m.i32(id as u32), + s.m.i32(0), + s.m.i8(col as u8), + values[vertex], + ]; + s.op(b, name, Attr::NoUnwind, s.t.void, 5, &args); + } + } + if let Some((id, n)) = number { + let args = [s.m.i32(id as u32), s.m.i32(0), s.m.i8(0), n]; + s.op(b, "storeOutput.i32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.op(b, "emitStream", Attr::NoUnwind, s.t.void, 97, &[stream]); + // The strip ends after the first triangle. + if vertex == 2 { + s.op(b, "cutStream", Attr::NoUnwind, s.t.void, 98, &[stream]); + } + } + s.m.terminate(b, Term::Ret); + Ok(s.finish()) +} + +/// Column `col` of input `id` at vertex `vertex` of the triangle. +fn load(s: &mut Shader, id: usize, col: u8, vertex: u32) -> V { + let (name, ty) = if s.inputs[id].comp == 9 { + ("loadInput.f32", s.t.f32) + } else { + ("loadInput.i32", s.t.i32) + }; + let args = [ + s.m.i32(id as u32), + s.m.i32(0), + s.m.i8(col), + s.m.i32(vertex), + ]; + let entry = s.entry; + s.op(entry, name, Attr::ReadNone, ty, 4, &args) +} + +/// Two floats are equal. +fn same(s: &mut Shader, a: V, b: V) -> V { + let entry = s.entry; + s.m.cmp(entry, pred::OEQ, a, b) +} + +fn both(s: &mut Shader, a: V, b: V) -> V { + let entry = s.entry; + s.m.bin(entry, Bin::And, a, b) +} + +fn either(s: &mut Shader, a: V, b: V) -> V { + let entry = s.entry; + s.m.bin(entry, Bin::Or, a, b) +} + +fn not(s: &mut Shader, a: V) -> V { + let (entry, on) = (s.entry, s.m.bool(true)); + s.m.bin(entry, Bin::Xor, a, on) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn element(name: &str, index: u32, kind: u8, comp: u8, row: u32, cols: u8) -> SigElement { + SigElement { + name: name.into(), + index, + kind, + comp, + interp: 0, + row: Some(row), + col: 0, + cols, + usage: 0, + half: false, + } + } + + /// A position, a float interpolant and an integer one. + fn outputs() -> Vec { + vec![ + element("SV_Position", 0, 3, 9, 0, 4), + element("TEXCOORD", 0, 0, 9, 1, 4), + element("TEXCOORD", 1, 0, 5, 2, 2), + ] + } + + /// The stage is a geometry shader of triangles in and six strip + /// vertices out, with the vertex shader's outputs on both sides and + /// the primitive id the pixel shader declares; the validator, where + /// there is one, accepts it. + #[test] + fn the_rectangle_stage_is_a_geometry_shader() { + let wanted = [element("SV_PrimitiveID", 0, 10, 5, 3, 1)]; + let gs = build(outputs(), &wanted).unwrap(); + let c = Container::parse(&gs).unwrap(); + // Program version: geometry (2), shader model 6.6. + assert_eq!(c.part(FourCC::DXIL).unwrap().data[..4], [0x66, 0, 2, 0]); + let psv = c.part(FourCC::PSV0).unwrap().data; + // Triangles in, triangle strips out, stream 0, a position. + assert_eq!(psv[4..17], [3, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 1]); + // Geometry stage, six vertices, three inputs, four outputs. + assert_eq!(psv[28..34], [2, 0, 6, 0, 3, 4]); + let sig = |fourcc| super::super::signature(c.part(fourcc).unwrap().data).unwrap(); + let (ins, outs) = (sig(FourCC::ISG1), sig(FourCC::OSG1)); + assert_eq!(ins.len(), 3); + assert_eq!(outs.len(), 4); + for (i, o) in ins.iter().zip(&outs) { + assert_eq!((&i.name, i.index, i.row), (&o.name, o.index, o.row)); + assert_eq!((i.col, i.cols, i.comp), (o.col, o.cols, o.comp)); + } + assert_eq!((outs[3].kind, outs[3].row), (10, Some(3))); + #[cfg(windows)] + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut gs.clone()).unwrap(); + let plain = build(outputs(), &[]).unwrap(); + v.validate(&mut plain.clone()).unwrap(); + } + } + + /// Refused with a reason: no position, a primitive id in a register a + /// vertex output has, more components than six vertices may carry. + #[test] + fn rectangle_stages_that_cannot_be_made_are_refused() { + assert!(build(outputs()[1..].to_vec(), &[]).is_err()); + let taken = [element("SV_PrimitiveID", 0, 10, 5, 1, 1)]; + assert!(build(outputs(), &taken).is_err()); + let mut many = vec![element("SV_Position", 0, 3, 9, 0, 4)]; + many.extend((1..=43).map(|row| element("TEXCOORD", row - 1, 0, 9, row, 4))); + assert!(build(many, &[]).is_err()); + } + + /// A vertex shader that passes a position and a float4 through, and a + /// pixel shader that writes the float4. + #[cfg(windows)] + fn pass_through() -> (super::super::HostShader, super::super::HostShader) { + let position = SigElement { + interp: 4, + usage: 15, + ..element("SV_Position", 0, 3, 9, 0, 4) + }; + let coord = SigElement { + interp: 2, + usage: 15, + ..element("TEXCOORD", 0, 0, 9, 1, 4) + }; + let mut vs = Shader::new(false); + vs.inputs = vec![ + SigElement { + usage: 15, + ..element("POSITION", 0, 0, 9, 0, 4) + }, + SigElement { + interp: 0, + ..coord.clone() + }, + ]; + vs.outputs = vec![position.clone(), coord.clone()]; + let mut ps = Shader::new(true); + ps.inputs = vec![ + SigElement { + usage: 0, + ..position + }, + coord, + ]; + ps.outputs = vec![SigElement { + usage: 15, + ..element("SV_Target", 0, 16, 9, 0, 4) + }]; + // Vertex: output id from input id. Pixel: target 0 from input 1. + for (s, copies) in [(&mut vs, &[(0, 0), (1, 1)][..]), (&mut ps, &[(1, 0)][..])] { + let b = s.entry; + for &(from, to) in copies { + for col in 0..4 { + let args = [s.m.i32(from), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)]; + let v = s.op(b, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args); + let args = [s.m.i32(to), s.m.i32(0), s.m.i8(col), v]; + s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + } + s.m.terminate(b, Term::Ret); + } + let host = |stage, s: Shader| super::super::HostShader { + stage, + dxil: s.finish(), + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + }; + ( + host(crate::native::HwStage::Vs, vs), + host(crate::native::HwStage::Ps, ps), + ) + } + + /// Three corners of the whole target, the corner between the other two + /// first (as the tiled lighting sends its tiles), second (as + /// full-screen rectangles come) or third: with the stage every texel + /// is drawn and the interpolant continues into the fourth corner's + /// half; without it part of the target is not drawn. + #[test] + #[cfg(windows)] + fn rectangles_are_drawn_whole() { + use super::super::host::{Draw, Host}; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let (vs, ps) = pass_through(); + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut vs.dxil.clone()).unwrap(); + v.validate(&mut ps.dxil.clone()).unwrap(); + } + let gs = rect_list_gs(&vs.dxil, Some(&ps.dxil[..])).unwrap(); + let root = host.root_signature(&vs, &ps).unwrap(); + // Position (z 0.5, w 1) and an interpolant that is the position. + let vertex = |(x, y): (f32, f32)| [x, y, 0.5, 1.0, x, y, 0.0, 1.0]; + for (name, corners) in [ + ("corner first", [(-1.0, 1.0), (-1.0, -1.0), (1.0, 1.0)]), + ("corner second", [(-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)]), + ("corner third", [(-1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]), + ] { + let vertices = corners.map(vertex).concat(); + let draw = |gs: Option<&[u8]>| { + let pso = host + .pipeline_with_gs(&root, &vs.dxil, gs, &ps.dxil) + .unwrap(); + let d = Draw { + roots: Vec::new(), + textures: &[], + samplers: &[], + vertices: &vertices, + stride: 32, + size: (8, 8), + mesh_groups: 0, + }; + host.draw(&root, &pso, &d).unwrap() + }; + let whole = draw(Some(&gs[..])); + for (i, texel) in whole.iter().enumerate() { + let (x, y) = ((i % 8) as f32, (i / 8) as f32); + let want = [(x + 0.5) / 4.0 - 1.0, 1.0 - (y + 0.5) / 4.0, 0.0, 1.0]; + assert!( + texel.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4), + "{name}: texel {i} is {texel:?}, not {want:?}" + ); + } + let half = draw(None); + let missing = half.iter().zip(&whole).filter(|(a, b)| a != b).count(); + assert!(missing >= 24, "{name}: only {missing} texels need the stage"); + } + } +} diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index dd2eb75..fe257db 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -13,13 +13,73 @@ pub const SAMPLER_SPACE: u32 = 0; /// `t` in this space. pub const ROOT_CBV_SPACE: u32 = 1; +/// The root SRV `t` in [`ROOT_CBV_SPACE`] of a shader that +/// reads buffers through descriptors it picks from the view heap at an +/// index it computes (SM 6.6 dynamic resources): a raw buffer of +/// [`SLOT_STRIDES_COUNT`] dwords the host keeps, dword `i` the bytes per +/// element of the buffer view at heap slot `i` (0: none or not a buffer). +/// The console's descriptor holds that stride and its hardware multiplies +/// the element index by it; the program's code does not say it, and the +/// used-resource list only names what tables hold. A shader that has this +/// 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; +/// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it. +pub const SLOT_STRIDES_COUNT: u32 = 1 << 21; + +/// Title memory by address (`resource::MEMORY`): console code reads and +/// writes through raw 40-bit addresses it takes from root constants, +/// descriptors and other memory (the ray-tracing structure builder and the +/// programs that walk its structures). The host keeps copies of the title +/// memory shaders use; a shader with such an access finds the copy by the +/// address: +/// +/// - the root SRV `t` in [`ROOT_CBV_SPACE`] is a directory of +/// [`MEMORY_PAGES`] entries of two dwords, one per 64 KiB of title +/// address space: the number of the host copy holding that page (0: none +/// yet) and the page's byte offset in that copy; +/// - copy `n` is the raw buffer view at view-heap slot `base + n`, `base` +/// the user-data dword of kind [`USER_MEMORY_BASE`]; slot `base` itself +/// reads zeros and drops writes; +/// - the root UAV `u` takes the page numbers of accesses that +/// found no copy ([`MEMORY_FAULTS`] dwords, dword 0 a sink), which the +/// host reads afterwards to make those copies for the frames to come. +pub const SLOT_MEMORY: u8 = 254; +/// See [`SLOT_MEMORY`]. +pub const SLOT_FAULTS: u8 = 253; +/// Entries of the [`SLOT_MEMORY`] directory: title addresses below 128 GiB. +pub const MEMORY_PAGES: u32 = 1 << 21; +/// Dwords of the [`SLOT_FAULTS`] buffer. +pub const MEMORY_FAULTS: u32 = 4096; +/// `RootType::Other` code of a user-data dword the host computes: the view +/// heap slot of the memory copies' views ([`SLOT_MEMORY`]). +pub const USER_MEMORY_BASE: u32 = 0x100; +/// `RootType::Other` code of a user-data dword the host computes: the low +/// 32 bits of the title address of the buffer view at dword `dword` of the +/// descriptor table of root parameter `slot`; [`USER_VIEW_ADDRESS`] + 1: +/// its bits from 32 up. (Console code reads the address out of a buffer +/// descriptor and uses it as a pointer.) +pub const USER_VIEW_ADDRESS: u32 = 0x101; +/// `RootType::Other` code of a user-data dword the host computes: the +/// bytes (0 to 15) by which the raw view the host binds for the root view +/// of root parameter `slot` begins before the title's address. A raw view +/// begins on 16 bytes of its host buffer; the console's root views begin +/// anywhere (the structure builder's counters sit at addresses ending in +/// 4 and c). The shader adds the dword to every byte offset through that +/// view. Asked for every root UAV, and for the root SRVs of programs with +/// a spilled user-data table. +pub const USER_VIEW_BIAS: u32 = 0x103; + /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { pub const RAW_BUFFERS: u64 = 1 << 4; pub const STENCIL_REF: u64 = 1 << 11; pub const TYPED_UAV_LOADS: u64 = 1 << 13; pub const WAVE_OPS: u64 = 1 << 19; + pub const BARYCENTRICS: u64 = 1 << 22; pub const INT64: u64 = 1 << 20; + pub const ATOMIC_TYPED64: u64 = 1 << 27; + pub const ATOMIC_HEAP64: u64 = 1 << 32; pub const RESOURCE_HEAP: u64 = 1 << 30; pub const SAMPLER_HEAP: u64 = 1 << 31; } @@ -45,6 +105,25 @@ pub(crate) struct Mesh { pub topology: u8, } +/// What a geometry shader declares: triangles in, triangle strips out on +/// stream 0, one instance. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Geometry { + pub max_vertices: u32, +} + +/// The null slot a host view heap keeps at its end when the title's heap did not fit in it +/// (0: no limit). Shaders translated while it is set read that slot for any view index at or +/// past it: a host that caps its heap (NVIDIA at 1 000 000 views; a retail game's heap is +/// larger) hung its GPU on reads past the end (GPU-based validation: "descriptor heap index +/// out of bounds"), which AMD's driver forgives. +static VIEW_LIMIT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// See [`VIEW_LIMIT`]: `null_slot` is the last slot of the host's view heap, kept null. +pub fn set_view_heap_limit(null_slot: u32) { + VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed); +} + pub(crate) struct Shader { pub m: Module, pub t: Types, @@ -55,6 +134,8 @@ pub(crate) struct Shader { pub prims: Vec, /// A mesh shader (`threads` is its thread-group size). pub mesh: Option, + /// A geometry shader (the rectangle stage, `rect.rs`); `pixel` is false. + pub geometry: Option, /// Dwords of user data the shader reads (0: no user-data buffer). pub user_data: u32, /// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`]. @@ -65,6 +146,8 @@ pub(crate) struct Shader { pub root_cbvs: Vec<(u8, V)>, /// Root SRVs (raw buffers) read, likewise. pub root_srvs: Vec<(u8, V)>, + /// Root UAVs (raw buffers) read or written, likewise. + pub root_uavs: Vec<(u8, V)>, pub flags: u64, /// Heap handles made with a non-uniform index. pub nonuniform_handles: u32, @@ -115,11 +198,13 @@ impl Shader { outputs: Vec::new(), prims: Vec::new(), mesh: None, + geometry: None, user_data: 0, samplers: 0, cmp_samplers: 0, root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), flags: 0, nonuniform_handles: 0, threads: None, @@ -236,6 +321,31 @@ impl Shader { h } + /// The handle of the root UAV (a raw buffer) of root parameter `slot`: + /// `u` in [`ROOT_CBV_SPACE`]. + pub fn root_uav_handle(&mut self, slot: u8) -> V { + if let Some(&(_, h)) = self.root_uavs.iter().find(|r| r.0 == slot) { + return h; + } + let r = self.m.i32(u32::from(slot)); + let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(1)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, r, f], + ); + let h = self.annotate(block, h, 11 | 0x1000, 0); + self.flags |= flags::RAW_BUFFERS; + self.root_uavs.push((slot, h)); + h + } + /// The handle of immediate sampler `n` (a comparison sampler when its /// bit in `cmp_samplers` is set). pub fn sampler_handle(&mut self, block: usize, n: u32) -> V { @@ -286,6 +396,25 @@ impl Shader { nonuniform: bool, props: (u32, u32), ) -> V { + // a view index past the host heap (`set_view_heap_limit`) reads its null slot instead + let limit = VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed); + // (as `dx.op.binary` UMin: a compare and select emitted here made the bitcode invalid) + let index = if !sampler && limit != 0 { + let null = self.m.i32(limit); + let i32t = self.t.i32; + self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null]) + } else if sampler { + // A sampler heap has at most 2,048 samplers on any host: an + // index past that (a number read from memory the host has not + // got yet) stays inside the largest heap there is. + // shortcut: not the bound heap's own count, which a title + // heap smaller than 2,048 would need. + let last = self.m.i32(2047); + let i32t = self.t.i32; + self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]) + } else { + index + }; self.flags |= if sampler { flags::SAMPLER_HEAP } else { @@ -318,6 +447,7 @@ impl Shader { || self.samplers > 0 || !self.root_cbvs.is_empty() || !self.root_srvs.is_empty() + || !self.root_uavs.is_empty() { let empty = self.m.md_str(""); let mut cbvs = None; @@ -401,6 +531,43 @@ impl Shader { } srvs = Some(self.m.md_node(list)); } + let mut uavs = None; + if !self.root_uavs.is_empty() { + let ty = self + .m + .named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + let no = self.m.bool(false); + let no = self.m.md_value(no); + let mut list = Vec::new(); + for (n, (slot, _)) in self.root_uavs.clone().into_iter().enumerate() { + // Id, variable, name, space, lower bound, range size, + // shape (11: raw buffer), globally coherent, counter, + // rasterizer ordered, no extra properties. + let ops = vec![ + Some(i32c(&mut self, n as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, ROOT_CBV_SPACE)), + Some(i32c(&mut self, u32::from(slot))), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 11)), + Some(no), + Some(no), + Some(no), + None, + ]; + list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 7, + space: ROOT_CBV_SPACE, + register: u32::from(slot), + dxil_kind: 11, + }); + } + uavs = Some(self.m.md_node(list)); + } let mut samplers = None; if self.samplers > 0 { let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]); @@ -430,11 +597,12 @@ impl Shader { } samplers = Some(self.m.md_node(list)); } - resources = Some(self.m.md_node(vec![srvs, None, cbvs, samplers])); - // PSV0 lists them as the module does: CBVs, samplers, SRVs. + resources = Some(self.m.md_node(vec![srvs, uavs, cbvs, samplers])); + // PSV0 lists them as the module does: CBVs, samplers, SRVs, UAVs. bindings.sort_by_key(|b| match b.kind { 2 => 0, 1 => 1, + 7 => 3, _ => 2, }); } @@ -468,6 +636,11 @@ impl Shader { }); } } + // A geometry shader lists four streams: the other three have + // no outputs. + if self.geometry.is_some() { + view.extend([0, 0, 0]); + } let arr = self.m.array(view.len() as u32, self.t.i32); let elems: Vec = view.iter().map(|&v| self.m.i32(v)).collect(); let arr = self.m.aggregate(arr, &elems); @@ -488,8 +661,8 @@ impl Shader { if self.pixel && self.outputs.iter().any(|o| o.kind == 20) { self.flags |= flags::STENCIL_REF; } - // Entry properties: shader flags (tag 0), thread-group size (4), - // wave size (11). + // Entry properties: shader flags (tag 0), geometry state (1), + // thread-group size (4), wave size (11). let mut props = Vec::new(); if self.flags != 0 { props.push(i32c(&mut self, 0)); @@ -497,6 +670,13 @@ impl Shader { let f = self.m.int_const(i64t, self.flags as i64); props.push(self.m.md_value(f)); } + if let Some(g) = self.geometry { + // Input primitive (3: triangles), maximum vertices, stream + // mask, output topology (5: triangle strips), instances. + props.push(i32c(&mut self, 1)); + let state = [3, g.max_vertices, 1, 5, 1].map(|n| Some(i32c(&mut self, n))); + props.push(self.m.md_node(state.to_vec())); + } if let Some(threads) = self.threads { let t = threads.map(|n| Some(i32c(&mut self, n))); let t = self.m.md_node(t.to_vec()); @@ -543,9 +723,10 @@ impl Shader { let version = self.m.md_node(vec![Some(one), Some(six)]); self.m.named_md("dx.version", vec![version]); self.m.named_md("dx.valver", vec![version]); - // Program kinds: 0 pixel, 1 vertex, 5 compute, 13 mesh. + // Program kinds: 0 pixel, 1 vertex, 2 geometry, 5 compute, 13 mesh. let (name, kind) = match (self.threads, self.pixel) { _ if self.mesh.is_some() => ("ms", 13u32), + _ if self.geometry.is_some() => ("gs", 2), (Some(_), _) => ("cs", 5u32), (None, true) => ("ps", 0), (None, false) => ("vs", 1), @@ -578,12 +759,21 @@ impl Shader { if self.flags & flags::INT64 != 0 { features |= 0x8000; } + if self.flags & flags::BARYCENTRICS != 0 { + features |= 0x2_0000; + } if self.flags & flags::RESOURCE_HEAP != 0 { features |= 0x200_0000; } if self.flags & flags::SAMPLER_HEAP != 0 { features |= 0x400_0000; } + if self.flags & flags::ATOMIC_TYPED64 != 0 { + features |= 0x40_0000; + } + if self.flags & flags::ATOMIC_HEAP64 != 0 { + features |= 0x1000_0000; + } let sfi0 = features.to_le_bytes(); let isg1 = container::signature(&self.inputs, true); let osg1 = container::signature(&self.outputs, false); @@ -599,6 +789,7 @@ impl Shader { outputs: &self.outputs, prims: &self.prims, mesh: self.mesh.map(|m| (m, self.lds_dwords * 4)), + geometry: self.geometry.map(|g| g.max_vertices), bindings: &bindings, threads: self.threads.unwrap_or_default(), wave_size: self.wave_size, diff --git a/crates/victory-shader/src/emit/threading.rs b/crates/victory-shader/src/emit/threading.rs new file mode 100644 index 0000000..01bd4fe --- /dev/null +++ b/crates/victory-shader/src/emit/threading.rs @@ -0,0 +1,218 @@ +//! Jump threading for uniform diamonds. One arm can set a flag that fixes +//! the join's next branch. Registers recycled on that arm then never reach +//! the other successor, even if an ordinary SSA phi joins their values. +use crate::gfx10::{Fields, Operand, Valu}; +use crate::ir::{Exit, Program, Reg, Value}; +use crate::structure::{Atom, Bool, LaneExit, Structured}; +use std::collections::HashMap; + +fn plain(v: &Valu) -> bool { + v.abs == 0 + && v.neg == 0 + && v.opsel == 0 + && !v.clamp + && v.omod == 0 + && v.sdwa.is_none() + && v.dpp.is_none() +} + +fn immediate(op: Operand) -> Option { + match op { + Operand::Const(c) => crate::resource::inline(c), + Operand::Literal(n) => Some(n), + _ => None, + } +} + +pub(super) fn constant_edges(p: &Program, st: &Structured) -> Vec<(usize, usize, usize)> { + let mut constants = HashMap::new(); + for (b, block) in p.blocks.iter().enumerate() { + for (i, inst) in block.insts.iter().enumerate() { + if inst.name() == "v_mov_b32" + && st.guards[b][i].is_none() + && let Fields::Valu(v) = &inst.fields + && plain(v) + && let [src] = v.src.as_slice() + && let Some(word) = immediate(*src) + && let [(_, dst)] = inst.writes.as_slice() + { + constants.insert(*dst, word); + } + } + } + let mut edges = Vec::new(); + for (join, block) in p.blocks.iter().enumerate() { + let LaneExit::Branch { + when, + taken, + not_taken, + } = st.exits[join] + else { + continue; + }; + if when == Bool::TRUE || when == Bool::FALSE { + continue; + } + // Keep memory accesses and wave operations at their original + // reconvergence point. Only duplicate scalar ALU and comparisons. + if !block.insts.iter().all(|i| match &i.fields { + Fields::Sop { .. } => true, + Fields::Sopp { .. } => i.name().starts_with("s_cbranch_"), + Fields::Valu(_) => i.name().starts_with("v_cmp_"), + _ => false, + }) { + continue; + } + let [a, b] = block.preds.as_slice() else { + continue; + }; + // A triangle has a direct edge from the fork to the join. A full + // diamond has an unconditional jump at the end of each arm. + let arm_from = |arm: usize| match p.blocks[arm].preds.as_slice() { + &[fork] if p.blocks[arm].exit == Exit::Jump(join) => Some(fork), + _ => None, + }; + let fork = match (arm_from(*a), arm_from(*b)) { + (Some(f), Some(g)) if f == g => f, + (_, Some(f)) if f == *a => f, + (Some(f), _) if f == *b => f, + _ => continue, + }; + if fork == join || a == b { + continue; + } + let LaneExit::Branch { when: entry, .. } = st.exits[fork] else { + continue; + }; + if !st + .bools + .support(entry) + .iter() + .all(|a| matches!(a, Atom::Uniform(_))) + { + continue; + } + for (edge, &pred) in block.preds.iter().enumerate() { + let value = |v: Value| { + let input = block + .phis + .iter() + .find(|p| p.value == v) + .map_or(v, |p| p.args[edge]); + constants.get(&input).copied() + }; + // Restrict the branch's decision diagram to known comparisons. + // Unknown tests stop the proof. Keep the original join for the + // other arm, which may still go either way. + let mut cond = when; + while let Some((Atom::Lane(id), lo, hi)) = st.bools.node(cond) { + let Some(inst) = block + .insts + .iter() + .find(|i| i.writes.iter().any(|&(_, v)| v == id)) + else { + break; + }; + let Fields::Valu(v) = &inst.fields else { break }; + let [left, right] = v.src.as_slice() else { + break; + }; + let operand = |op| match op { + Operand::Vector { reg, dwords: 1 } => value(inst.read(Reg::V(reg))?), + _ => immediate(op), + }; + let (Some(x), Some(y)) = (operand(*left), operand(*right)) else { + break; + }; + if !plain(v) { + break; + } + let yes = match inst.name() { + "v_cmp_eq_u32" | "v_cmp_eq_i32" => x == y, + "v_cmp_ne_u32" | "v_cmp_ne_i32" => x != y, + _ => break, + }; + cond = if yes { hi } else { lo }; + } + if cond == Bool::TRUE || cond == Bool::FALSE { + edges.push(( + pred, + join, + if cond == Bool::TRUE { taken } else { not_taken }, + )); + break; + } + } + } + edges +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ir; + use crate::structure; + + // s8 initially holds a descriptor address. One arm overwrites it with + // a buffer load and sets v1. Only that arm can use s8 as the stored value. + const WORDS: [u32; 19] = [ + 0xbe810380, // s1 = 0 (table address high) + 0xf4080200, 0xfa000000, // load SRV into s[8:11] + 0xf4080300, 0xfa000020, // load UAV into s[12:15] + 0x7e020280, // v1 = 0 + 0xbf068002, 0xbf850003, // if s2 == 0, jump to join + 0xf4200204, 0xfa00000c, // s8 = buffer.Load(12) + 0x7e020281, // v1 = 1 + 0x7d840280, 0xbf870002, // join: if v1 == 0, jump to constant + 0x7e060208, 0xbf820001, // v3 = s8, jump to store + 0x7e060293, // constant: v3 = 19 + 0xe0700000, 0x80030300, // store v3 at byte 0 + 0xbf810000, // end + ]; + + fn program(words: &[u32]) -> Program { + ir::build( + &words + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect::>(), + false, + 4, + ) + .unwrap() + } + + #[test] + fn only_the_buffer_load_reaches_the_numeric_read() { + let p = program(&WORDS); + let st = structure::structure(&p).unwrap(); + let edges = constant_edges(&p, &st); + assert_eq!(edges, [(0, 2, 4)]); + let p = ir::thread_edges(&p, &edges).unwrap(); + let load = &p.blocks[1].insts[0]; + assert_eq!(p.blocks[3].insts[0].read(Reg::S(8)), load.write(Reg::S(8))); + assert_eq!( + p.blocks[0].exit, + Exit::Branch { + taken: 6, + not_taken: 1 + } + ); + assert_eq!(p.blocks[6].exit, Exit::Jump(4)); + assert_eq!(p.blocks[6].insts.len(), p.blocks[2].insts.len()); + } + + #[test] + fn leaves_unknown_flags_and_divergent_forks_alone() { + let mut words = WORDS; + words[5] = 0x7e020202; // v1 = s2 + words[10] = 0x7e020203; // v1 = s3 + let p = program(&words); + assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty()); + let mut words = WORDS; + words[6] = 0x7d840080; // compare 0 with lane-dependent v0 + words[7] = 0xbf870003; // branch on VCC + let p = program(&words); + assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty()); + } +} diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index b4ee77d..fe98439 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -3,7 +3,8 @@ //! //! Covers RDNA2 hardware semantics that differ from naive DXIL lowering: //! `v_med3_f32`/`v_med3_f16` with NaN operands, `v_fract_f32`/`v_fract_f16` -//! near `1.0`, and turn-range reduction for `v_sin_*`/`v_cos_*`. +//! near `1.0`, turn-range reduction for `v_sin_*`/`v_cos_*`, and the LDS +//! float atomics `ds_min_f32`/`ds_max_f32`. use super::host::{Dispatch, Host, Root, View}; use super::{HostShader, lower, validator}; @@ -43,9 +44,33 @@ const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 { /// VOP3 `op vdst, src0, src1, src2` (no modifiers). const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] { + vop3_mod(op, vdst, src0, src1, src2, 0, 0, 0, false) +} + +/// VOP3 `op vdst, src0, src1, src2` with explicit `abs`, `neg`, `omod`, `clamp`. +#[allow(clippy::too_many_arguments)] +const fn vop3_mod( + op: u16, + vdst: u8, + src0: u16, + src1: u16, + src2: u16, + abs: u8, + neg: u8, + omod: u8, + clamp: bool, +) -> [u32; 2] { [ - 0x35 << 26 | (op as u32 & 0x3FF) << 16 | vdst as u32, - (src0 as u32 & 0x1FF) | (src1 as u32 & 0x1FF) << 9 | (src2 as u32 & 0x1FF) << 18, + 0x35 << 26 + | (op as u32 & 0x3FF) << 16 + | (clamp as u32) << 15 + | (abs as u32 & 7) << 8 + | vdst as u32, + (neg as u32 & 7) << 29 + | (omod as u32 & 3) << 27 + | (src0 as u32 & 0x1FF) + | (src1 as u32 & 0x1FF) << 9 + | (src2 as u32 & 0x1FF) << 18, ] } @@ -69,6 +94,12 @@ const fn vgpr(n: u8) -> u16 { /// 4 dwords of root constants in `s0..s3`, runs `body` (leaving its result in /// `v0`), and stores `v0` to dword 0 of the raw UAV at heap index 0. fn build_valu_cs(body: &[u32]) -> HostShader { + build_cs(body, 1, 0) +} + +/// [`build_valu_cs`] with `threads` threads in x (thread index in `v0` +/// on entry, before `body`) and `lds_bytes` of LDS (a multiple of 512). +fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader { let mut words = Vec::new(); // s[4:5] = descriptor table address (heap index 0 -> byte offset 0). words.push(s_mov_b32(5, 0x80)); // inline constant 0 @@ -116,8 +147,8 @@ fn build_valu_cs(body: &[u32]) -> HostShader { slot: 1, }], io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 - threads: [1, 1, 1], + rsrc2: (5 << 1) | ((lds_bytes / 512) << 15), // 5 user SGPRs: s0..s4 + threads: [threads, 1, 1], }), code, }; @@ -148,6 +179,8 @@ fn build_valu_cs(body: &[u32]) -> HostShader { static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -172,11 +205,20 @@ pub(super) static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(() fn run_cases( shader: &HostShader, cases: &[[u32; 4]], + check: impl FnMut(&str, usize, [u32; 4], u32), +) { + run_cases_on(shader, cases, &[("hardware", false), ("warp", true)], check); +} + +fn run_cases_on( + shader: &HostShader, + cases: &[[u32; 4]], + devices: &[(&str, bool)], mut check: impl FnMut(&str, usize, [u32; 4], u32), ) { let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let mut ran = 0; - for (label, warp) in [("hardware", false), ("warp", true)] { + for &(label, warp) in devices { let Ok(host) = Host::new(warp) else { eprintln!("no SM 6.6 {label} device; skipped"); continue; @@ -209,7 +251,7 @@ fn run_cases( } ran += 1; } - assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); + assert!(ran > 0, "no SM 6.6 device available ({devices:?})"); } fn is_f16_nan(bits: u16) -> bool { @@ -868,6 +910,286 @@ fn bfe_signed_and_unsigned_match_rdna2() { }); } +#[test] +fn f16_omod_applies_before_clamp() { + // VOP3 v_add_f16 (0x132 = 0x100 + VOP2 0x32): v0 = (v1 + v2) * omod [clamp] + let mul2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 1, false)); + let mul4 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 2, false)); + let div2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, false)); + let div2_clamp = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, true)); + + // f16 constants: 0.25=0x3400, 0.5=0x3800, 0.75=0x3A00, 1.0=0x3C00, 1.5=0x3E00, 2.0=0x4000, -0.5=0xB800 + run_cases( + &mul2, + &[[0x3400, 0x3800, 0, 0]], // (0.25 + 0.5) * 2 = 1.5 (0x3E00) + |backend, _, _, got| { + assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 mul:2"); + }, + ); + run_cases( + &mul4, + &[[0x3400, 0x3400, 0, 0]], // (0.25 + 0.25) * 4 = 2.0 (0x4000) + |backend, _, _, got| { + assert_eq!(got as u16, 0x4000, "{backend}: v_add_f16 mul:4"); + }, + ); + run_cases( + &div2, + &[[0x3E00, 0x3E00, 0, 0]], // (1.5 + 1.5) / 2 = 1.5 (0x3E00) + |backend, _, _, got| { + assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 div:2"); + }, + ); + // Ordering check: (0.75 + 0.75) = 1.5; div:2 before clamp gives 0.75 (0x3A00), + // whereas clamp before div:2 would give 0.5 (0x3800). + let clamp_cases: &[(u16, u16, u16)] = &[ + (0x3A00, 0x3A00, 0x3A00), // (0.75 + 0.75) / 2 = 0.75 -> 0.75 + (0x3E00, 0x3E00, 0x3C00), // (1.5 + 1.5) / 2 = 1.5 -> clamped to 1.0 + (0xB800, 0xB800, 0x0000), // (-0.5 + -0.5) / 2 = -0.5 -> clamped to 0.0 + ]; + let inputs: Vec<[u32; 4]> = clamp_cases + .iter() + .map(|&(a, b, _)| [u32::from(a), u32::from(b), 0, 0]) + .collect(); + run_cases(&div2_clamp, &inputs, |backend, i, _, got| { + let want = clamp_cases[i].2; + assert_eq!( + got as u16, want, + "{backend}: v_add_f16 div:2 clamp case {i}: got {:#06x}, want {want:#06x}", + got as u16, + ); + }); +} + +#[test] +fn cvt_16bit_int_from_f16_saturates_and_honors_modifiers() { + // VOP3 v_cvt_u16_f16 = 0x1D2 (0x180 + VOP1 0x52) + // VOP3 v_cvt_i16_f16 = 0x1D3 (0x180 + VOP1 0x53) + let cvt_u16 = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 0, 0, 0, false)); + let cvt_u16_abs = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 1, 0, 0, false)); + let cvt_i16 = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 0, 0, false)); + let cvt_i16_neg = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 1, 0, false)); + + let u16_cases: &[(u16, u16)] = &[ + (0xBC00, 0), // -1.0 -> 0 + (0xFC00, 0), // -inf -> 0 + (0x7E00, 0), // NaN -> 0 + (0x57BC, 123), // 123.75 -> 123 + (0x7BFF, 65504), // 65504.0 (max finite f16) -> 65504 + (0x7C00, 0xFFFF), // +inf -> 65535 (saturated) + ]; + let u16_in: Vec<[u32; 4]> = u16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect(); + run_cases(&cvt_u16, &u16_in, |backend, i, inp, got| { + let want = u16_cases[i].1; + assert_eq!( + got as u16, want, + "{backend}: v_cvt_u16_f16({:#06x}) = {:#06x}, want {want:#06x}", + inp[0], got as u16, + ); + }); + run_cases( + &cvt_u16_abs, + &[[0xD7BC, 0, 0, 0]], // |-123.75| -> 123 + |backend, _, _, got| { + assert_eq!(got as u16, 123, "{backend}: v_cvt_u16_f16 |src0|"); + }, + ); + + let i16_cases: &[(u16, u16)] = &[ + (0xFC00, 0x8000), // -inf -> -32768 + (0xF8E2, 0x8000), // -40000.0 -> -32768 (saturated, not wrapped) + (0xD7BC, (-123i16) as u16), // -123.75 -> -123 + (0x7E00, 0), // NaN -> 0 + (0x57BC, 123), // 123.75 -> 123 + (0x78E2, 0x7FFF), // +40000.0 -> 32767 (saturated, not wrapped) + (0x7C00, 0x7FFF), // +inf -> 32767 + ]; + let i16_in: Vec<[u32; 4]> = i16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect(); + run_cases(&cvt_i16, &i16_in, |backend, i, inp, got| { + let want = i16_cases[i].1; + assert_eq!( + got as u16, want, + "{backend}: v_cvt_i16_f16({:#06x}) = {:#06x}, want {want:#06x}", + inp[0], got as u16, + ); + }); + run_cases( + &cvt_i16_neg, + &[[0x57BC, 0, 0, 0], [0x78E2, 0, 0, 0]], // -(123.75) -> -123; -(40000.0) -> -32768 + |backend, i, _, got| { + let want = [(-123i16) as u16, 0x8000][i]; + assert_eq!(got as u16, want, "{backend}: v_cvt_i16_f16 -src0 case {i}"); + }, + ); +} + +const S_BARRIER: u32 = 0xBF8A_0000; + +/// VOP2 `op vdst, src0, vsrc1`. +const fn vop2(op: u8, vdst: u8, src0: u16, vsrc1: u8) -> u32 { + (op as u32 & 0x3F) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) +} + +/// DS `op vdst, addr, data0` at offset 0. +const fn ds(op: u8, vdst: u8, addr: u8, data0: u8) -> [u32; 2] { + [ + 0x36 << 26 | (op as u32) << 18, + (vdst as u32) << 24 | (data0 as u32) << 8 | addr as u32, + ] +} + +const DS_WRITE_B32: u8 = 0x0D; +const DS_MIN_F32: u8 = 0x12; +const DS_MAX_F32: u8 = 0x13; +const DS_MIN_RTN_F32: u8 = 0x32; +const DS_MAX_RTN_F32: u8 = 0x33; +const DS_READ_B32: u8 = 0x36; + +/// What RDNA2 writes for `ds_max_f32` / `ds_min_f32` over a dword holding +/// `old` with `data` (bits), as measured on gfx1036 with f32 denormals kept: +/// an sNaN, data first, then memory, is written quieted; otherwise a NaN +/// loses to a number (two quiet NaNs give the data); numbers compare as +/// floats with -0 below +0. +fn lds_min_max_ref(old: u32, data: u32, max: bool) -> u32 { + let nan = |x: u32| x & 0x7FFF_FFFF > 0x7F80_0000; + let snan = |x: u32| nan(x) && x & 0x40_0000 == 0; + let key = |x: u32| { + let b = x as i32; + if b < 0 { b ^ 0x7FFF_FFFF } else { b } + }; + if snan(data) { + return data | 0x40_0000; + } + if snan(old) { + return old | 0x40_0000; + } + match (nan(data), nan(old)) { + (true, true) | (false, true) => return data, + (true, false) => return old, + (false, false) => {} + } + let take = if max { + key(data) > key(old) + } else { + key(data) < key(old) + }; + if take { data } else { old } +} + +#[test] +fn ds_min_max_f32_order_floats_and_return_the_old_value() { + let values = [ + 0.0f32, + -0.0, + 1.0, + -1.0, + 2.5, + -2.5, + 1e-30, + -1e-30, + f32::from_bits(1), // denormal + f32::from_bits(0x8000_0001), + f32::INFINITY, + f32::NEG_INFINITY, + f32::MAX, + f32::MIN, + ]; + // Quiet and signalling NaNs of both signs, in memory and as data. + let nans = [ + 0x7FC0_0000u32, + 0xFFC0_0000, + 0x7F80_0001, + 0xFFA0_0000, + 0x7FBF_FFFF, + ]; + let bits: Vec = values.iter().map(|v| v.to_bits()).chain(nans).collect(); + let mut cases: Vec<[u32; 4]> = Vec::new(); + for &old in &bits { + for &data in &bits { + cases.push([old, data, 0, 0]); + } + } + for (rtn, plain, max, what) in [ + (DS_MAX_RTN_F32, DS_MAX_F32, true, "ds_max"), + (DS_MIN_RTN_F32, DS_MIN_F32, false, "ds_min"), + ] { + // v5 = 0; LDS[v5] = v1; the atomic with v2; v0 = the old value + // (rtn) or the dword afterwards (read back). + let mut returns_old = vec![vop1(0x001, 5, 0x80)]; + returns_old.extend(ds(DS_WRITE_B32, 0, 5, 1)); + returns_old.extend(ds(rtn, 0, 5, 2)); + let mut returns_new = vec![vop1(0x001, 5, 0x80)]; + returns_new.extend(ds(DS_WRITE_B32, 0, 5, 1)); + returns_new.extend(ds(plain, 0, 5, 2)); + returns_new.extend(ds(DS_READ_B32, 0, 5, 0)); + for (body, old_result) in [(returns_old, true), (returns_new, false)] { + // One thread with LDS declares WaveSize(32), which WARP's + // pipeline creation refuses: hardware only (the 64-thread test + // below runs on WARP too). + let shader = build_cs(&body, 1, 512); + run_cases_on( + &shader, + &cases, + &[("hardware", false)], + |backend, _, inp, got| { + let (old, data) = (f32::from_bits(inp[0]), f32::from_bits(inp[1])); + let want = if old_result { + inp[0] + } else { + lds_min_max_ref(inp[0], inp[1], max) + }; + assert_eq!( + got, + want, + "{backend}: {what}_f32 on {old:e} [{:#010x}] with {data:e} [{:#010x}] gave {got:#010x}, want {want:#010x} ({})", + inp[0], + inp[1], + if old_result { + "old value" + } else { + "dword after" + }, + ); + }, + ); + } + } +} + +#[test] +fn ds_min_max_f32_are_atomic_across_waves() { + // 64 threads (two host waves of 32 or one of 64): LDS[0] = v1, then + // every thread applies (thread - 32) as a float; v0 = LDS[0]. + for (op, max, init, want) in [ + (DS_MAX_F32, true, f32::NEG_INFINITY, 31.0f32), + (DS_MAX_F32, true, 100.0, 100.0), + (DS_MIN_F32, false, f32::INFINITY, -32.0), + (DS_MIN_F32, false, -0.0, -32.0), + ] { + let mut body = vec![vop1(0x001, 5, 0x80)]; + body.extend(ds(DS_WRITE_B32, 0, 5, 1)); + body.push(S_BARRIER); + body.push(vop2(0x26, 6, vgpr(0), 3)); // v_sub_nc_u32 v6, v0, v3 + body.push(vop1(0x005, 6, vgpr(6))); // v_cvt_f32_i32 + body.extend(ds(op, 0, 5, 6)); + body.push(S_BARRIER); + body.extend(ds(DS_READ_B32, 0, 5, 0)); + let shader = build_cs(&body, 64, 512); + run_cases( + &shader, + &[[init.to_bits(), 0, 32, 0]], + |backend, _, _, got| { + assert_eq!( + f32::from_bits(got), + want, + "{backend}: {} from {init} over 64 threads", + if max { "max" } else { "min" }, + ); + }, + ); + } +} + #[test] fn v_cmp_class_f16_matches_rdna2() { // v_cmp_class_f16_e64 s6, v1, v2 (VOP3 opcode 0x08f); v_cndmask_b32_e64 v0, 0, 1, s6 diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 104fc6d..18425e0 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -82,6 +82,8 @@ fn build(words: &[u32], buffers: bool) -> HostShader { static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: Vec::new(), }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs index f114db1..483631f 100644 --- a/crates/victory-shader/src/emit/wave.rs +++ b/crates/victory-shader/src/emit/wave.rs @@ -35,7 +35,9 @@ pub(crate) enum Op { impl Op { fn of(name: &str) -> Option { Some(match name { - "v_add_nc_u32" => Op::AddU, + // the low dword of a 64-bit sum (`v_add_co_ci_u32` carries into + // the high one) is the 32-bit sum of the low dwords + "v_add_nc_u32" | "v_add_co_u32" => Op::AddU, "v_add_f32" => Op::AddF, "v_min_u32" => Op::MinU, "v_max_u32" => Op::MaxU, @@ -253,11 +255,11 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { let Some(k) = lo else { return shapes(vec, uni, wave); }; - exec = if name == "s_mov_b64" { + exec = (if name == "s_mov_b64" { k } else { - exec & !0xFFFF_FFFF | k & 0xFFFF_FFFF - }; + (exec & !0xFFFF_FFFF) | (k & 0xFFFF_FFFF) + }) & all; continue; } if inst.write(Reg::S(EXEC + 1)).is_some() { @@ -268,7 +270,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { else { return shapes(vec, uni, wave); }; - exec = exec & 0xFFFF_FFFF | k << 32; + exec = ((exec & 0xFFFF_FFFF) | ((k & 0xFFFF_FFFF) << 32)) & all; continue; } if let Fields::Sop { src, .. } = &inst.fields { @@ -494,15 +496,18 @@ fn constant(inst: &Inst) -> Option { let Fields::Sop { src, .. } = &inst.fields else { return None; }; + let wide = inst.name() == "s_mov_b64"; match *src.first()? { - Operand::Const(c) => { + Operand::Scalar { code: NULL, .. } => Some(0), + Operand::Const(c @ 128..=208) => { let x = crate::resource::inline(c)?; - Some(if (x as i32) < 0 { - u64::MAX + Some(if wide { + i64::from(x as i32) as u64 } else { u64::from(x) }) } + Operand::Const(c) if !wide => crate::resource::inline(c).map(u64::from), Operand::Literal(x) => Some(u64::from(x)), _ => None, } @@ -577,7 +582,8 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option { }; } // Prefixes: lane l holds lanes 0..l (exclusive) or 0..=l (inclusive). - let mut found: Option<(Op, Value, Value, u32, bool)> = None; + let mut meta: Option<(Value, Value, u32, bool)> = None; + let mut op_found: Option = None; for (l, &s) in lanes.iter().enumerate() { let below = (1u64 << l) - 1; let (op, src, mask, ident, set) = match s { @@ -592,28 +598,40 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option { Sym::K(_) if l == 0 => continue, _ => return None, }; - let inclusive = set == below | 1 << l; + let inclusive = set == below | (1u64 << l); if !inclusive && set != below { return None; } - let op = match (op, found) { - (Some(o), _) => o, - (None, Some(f)) => f.0, - (None, None) => continue, - }; - let me = (op, src, mask, ident, inclusive); - match found { - None => found = Some(me), - Some(f) if f == me => {} + if l == 0 && !inclusive { + return None; + } + if op.is_none() && set.count_ones() != 1 { + return None; + } + let lane_meta = (src, mask, ident, inclusive); + match meta { + None => meta = Some(lane_meta), + Some(prev) if prev == lane_meta => {} _ => return None, } + if let Some(o) = op { + match op_found { + None => op_found = Some(o), + Some(prev) if prev == o => {} + _ => return None, + } + } } - let (op, src, mask, ident, inclusive) = found?; - if let Sym::K(k) = lanes[0] - && (inclusive || k != ident) - { + let (src, mask, ident, inclusive) = meta?; + let op = op_found?; + if !op.identity(ident) { return None; } + match lanes[0] { + Sym::K(k) if !inclusive && k == ident => {} + Sym::Red { .. } if inclusive => {} + _ => return None, + } Some(Shape::Prefix(op, src, mask, ident, inclusive)) } @@ -621,6 +639,45 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option { mod tests { use super::*; + const S_ENDPGM: u32 = 0xBF81_0000; + + const fn sop1(sdst: u8, op: u8, ssrc0: u8) -> u32 { + 0xBE80_0000 | (sdst as u32) << 16 | (op as u32) << 8 | ssrc0 as u32 + } + + const fn vop1(vdst: u8, op: u8, src0: u16) -> u32 { + (0x3F << 25) | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF) + } + + const fn vop2(vdst: u8, op: u8, src0: u16, vsrc1: u8) -> u32 { + (op as u32) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) + } + + const fn dpp16(vsrc0: u8, ctrl: u16, row_mask: u8, bank_mask: u8, bound_ctrl: bool) -> u32 { + (row_mask as u32) << 28 + | (bank_mask as u32) << 24 + | (bound_ctrl as u32) << 19 + | (ctrl as u32) << 8 + | vsrc0 as u32 + } + + const fn vop3(vdst: u8, op: u16, src0: u16, src1: u16, src2: u16) -> [u32; 2] { + [ + 0xD400_0000 | (op as u32) << 16 | vdst as u32, + (src0 as u32 & 0x1FF) | ((src1 as u32 & 0x1FF) << 9) | ((src2 as u32 & 0x1FF) << 18), + ] + } + + fn build(words: &[u32], wave64: bool) -> Program { + let code: Vec = words + .iter() + .copied() + .chain(std::iter::once(S_ENDPGM)) + .flat_map(u32::to_le_bytes) + .collect(); + crate::ir::build(&code, wave64, 256).unwrap() + } + #[test] fn dpp_lanes_follow_the_isa() { // row_shr:1 with bound_ctrl: lane 16 reads 0, lane 17 lane 16. @@ -676,4 +733,220 @@ mod tests { Some(Shape::Active(Op::AddU, x, m, 0)) ); } + + #[test] + fn constant_decodes_width_and_inline_kinds() { + let b64 = 0x04; + let b32 = 0x03; + let check = |words: &[u32], wave64: bool| -> Option { + let p = build(words, wave64); + constant(&p.blocks[0].insts[0]) + }; + + assert_eq!( + check(&[sop1(EXEC, b64, 194)], true), + Some(0xFFFF_FFFF_FFFF_FFFE) + ); + assert_eq!( + check(&[sop1(EXEC, b64, 196)], true), + Some(0xFFFF_FFFF_FFFF_FFFC) + ); + assert_eq!( + check(&[sop1(EXEC, b64, 208)], true), + Some(0xFFFF_FFFF_FFFF_FFF0) + ); + assert_eq!(check(&[sop1(EXEC, b64, 193)], true), Some(u64::MAX)); + assert_eq!(check(&[sop1(EXEC, b64, NULL)], true), Some(0)); + assert_eq!(check(&[sop1(EXEC, b64, 243)], true), None); + assert_eq!( + check(&[sop1(EXEC, b64, 255), 0x1234_5678], true), + Some(0x1234_5678) + ); + + assert_eq!(check(&[sop1(EXEC, b32, 194)], false), Some(0xFFFF_FFFE)); + assert_eq!(check(&[sop1(EXEC, b32, 243)], false), Some(0xBF80_0000)); + assert_eq!(check(&[sop1(EXEC, b32, NULL)], false), Some(0)); + assert_eq!( + check(&[sop1(EXEC, b32, 255), 0x1234_5678], false), + Some(0x1234_5678) + ); + assert_eq!(check(&[sop1(EXEC, b32, 0)], false), None); + } + + #[test] + fn exec_minus_two_masks_lane_zero_and_enforces_dpp_guard() { + for wave64 in [false, true] { + let mut w = Vec::new(); + let save_op = if wave64 { 0x25 } else { 0x3D }; + let mov_exec = if wave64 { 0x04 } else { 0x03 }; + let push_exec = |w: &mut Vec, k: u8| w.push(sop1(EXEC, mov_exec, k)); + let push_exec_lit = |w: &mut Vec, lit: u32| { + w.push(sop1(EXEC, mov_exec, 255)); + w.push(lit); + }; + + w.push(sop1(0, save_op, 193)); + w.extend(vop3(1, 0x101, 128, 256, 0)); + for shift in [1u16, 2, 4, 8] { + w.push(vop2(1, 0x25, 0xFA, 1)); + w.push(dpp16(1, 0x110 + shift, 0xF, 0xF, false)); + } + w.extend(vop3(2, 0x360, 257, 128 + 15, 0)); + push_exec_lit(&mut w, 0xFFFF_0000); + w.push(vop2(1, 0x25, 2, 1)); + + if wave64 { + w.extend(vop3(2, 0x360, 257, 128 + 31, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 255)); + w.push(0x0000_FFFF); + w.push(vop2(1, 0x25, 2, 1)); + + w.extend(vop3(2, 0x360, 257, 128 + 47, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 255)); + w.push(0xFFFF_0000); + w.push(vop2(1, 0x25, 2, 1)); + } + + push_exec(&mut w, 193); + w.push(vop1(3, 0x01, 257)); + w.push(vop1(3, 0x01, 0xFA)); + w.push(dpp16(1, 0x111, 0xF, 0xF, false)); + + w.extend(vop3(2, 0x360, 257, 128 + 15, 0)); + push_exec_lit(&mut w, 0x0001_0000); + w.push(vop1(3, 0x01, 2)); + + if wave64 { + w.extend(vop3(2, 0x360, 257, 128 + 31, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 129)); + w.push(vop1(3, 0x01, 2)); + + w.extend(vop3(2, 0x360, 257, 128 + 47, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 255)); + w.push(0x0001_0000); + w.push(vop1(3, 0x01, 2)); + } + + push_exec(&mut w, 193); + w.push(vop1(2, 0x01, 128)); + w.push(vop1(5, 0x01, 135)); + push_exec(&mut w, 194); + w.push(vop1(2, 0x01, 259)); + w.push(vop1(4, 0x01, 0xFA)); + w.push(dpp16(5, 0xE4, 0xF, 0xF, false)); + w.push(sop1(EXEC, mov_exec, 0)); + + let p = build(&w, wave64); + let insts = &p.blocks[0].insts; + let saved = insts[0].write(Reg::S(0)).unwrap(); + let v0_in = p + .inputs + .iter() + .find_map(|&(r, v)| (r == Reg::V(0)).then_some(v)) + .unwrap(); + let v2_val = insts[insts.len() - 4].write(Reg::V(2)).unwrap(); + let v4_val = insts[insts.len() - 3].write(Reg::V(4)).unwrap(); + let sec = §ions(&p, 0)[&0]; + assert_eq!( + sec.shapes.get(&v2_val), + Some(&Shape::Prefix(Op::AddU, v0_in, saved, 0, false)) + ); + assert_eq!(sec.shapes.get(&v4_val), None); + } + } + + #[test] + fn wave32_mov_b64_all_lanes_keeps_exec_masked_for_dpp() { + let w = [ + sop1(0, 0x3D, 193), + vop1(1, 0x01, 135), + sop1(EXEC, 0x04, 193), + vop1(2, 0x01, 0xFA), + dpp16(1, 0xE4, 0xF, 0xF, false), + sop1(EXEC + 1, 0x03, 193), + vop1(3, 0x01, 0xFA), + dpp16(1, 0xE4, 0xF, 0xF, false), + sop1(EXEC, 0x03, 0), + ]; + let p = build(&w, false); + let insts = &p.blocks[0].insts; + let v2_val = insts[3].write(Reg::V(2)).unwrap(); + let v3_val = insts[5].write(Reg::V(3)).unwrap(); + let sec = §ions(&p, 0)[&0]; + assert_eq!(sec.shapes.get(&v2_val), Some(&Shape::K(7))); + assert_eq!(sec.shapes.get(&v3_val), Some(&Shape::K(7))); + } + + #[test] + fn per_lane_prefix_soundness() { + let (v0, v_other, m0, m_other) = (Value(1), Value(2), Value(3), Value(4)); + let red = |op: Option, src: Value, mask: Value, ident: u32, lanes: u64| Sym::Red { + op, + src, + mask, + ident, + lanes, + }; + + for (wave, all) in [(32usize, u64::from(u32::MAX)), (64usize, u64::MAX)] { + let below_mask = |l: usize| if l == 0 { 0 } else { (1u64 << l) - 1 }; + + let mut valid_inc: Vec = (0..wave) + .map(|l| red(Some(Op::AddU), v0, m0, 0, below_mask(l) | (1u64 << l))) + .collect(); + valid_inc[0] = red(None, v0, m0, 0, 1); + assert_eq!( + per_lane(&valid_inc, all), + Some(Shape::Prefix(Op::AddU, v0, m0, 0, true)) + ); + + let mut valid_exc: Vec = (0..wave) + .map(|l| red(Some(Op::AddU), v0, m0, 0, below_mask(l))) + .collect(); + valid_exc[0] = Sym::K(0); + valid_exc[1] = red(None, v0, m0, 0, 1); + assert_eq!( + per_lane(&valid_exc, all), + Some(Shape::Prefix(Op::AddU, v0, m0, 0, false)) + ); + + let mut mixed_other_src = valid_exc.clone(); + mixed_other_src[0] = red(None, v_other, m0, 0, 1); + assert_eq!(per_lane(&mixed_other_src, all), None); + + let mut mixed_same_src = valid_exc.clone(); + mixed_same_src[0] = red(None, v0, m0, 0, 1); + assert_eq!(per_lane(&mixed_same_src, all), None); + + let mut exc_bad_lane1_src = valid_exc.clone(); + exc_bad_lane1_src[1] = red(None, v_other, m0, 0, 1); + assert_eq!(per_lane(&exc_bad_lane1_src, all), None); + + let mut exc_bad_lane1_set = valid_exc.clone(); + exc_bad_lane1_set[1] = red(None, v0, m0, 0, 0b11); + assert_eq!(per_lane(&exc_bad_lane1_set, all), None); + + for bad0 in [ + red(None, v0, m0, 1, 1), + red(None, v_other, m0, 0, 1), + red(None, v0, m_other, 0, 1), + red(None, v0, m0, 0, 0), + Sym::K(0), + ] { + let mut bad_inc = valid_inc.clone(); + bad_inc[0] = bad0; + assert_eq!(per_lane(&bad_inc, all), None); + } + + let mut bad_ident: Vec = (0..wave) + .map(|l| red(Some(Op::AddU), v0, m0, 1, below_mask(l) | (1u64 << l))) + .collect(); + bad_ident[0] = red(None, v0, m0, 1, 1); + assert_eq!(per_lane(&bad_ident, all), None); + } + } } diff --git a/crates/victory-shader/src/gfx10/fields.rs b/crates/victory-shader/src/gfx10/fields.rs index 7fe66b0..2773b3c 100644 --- a/crates/victory-shader/src/gfx10/fields.rs +++ b/crates/victory-shader/src/gfx10/fields.rs @@ -11,7 +11,9 @@ use super::{Encoding, Instruction}; pub enum Operand { /// Scalar registers by operand code: 0-105 `s0`-`s105`, 106/107 /// `vcc_lo`/`vcc_hi`, 108-123 `ttmp0`-`ttmp15`, 124 `m0`, 125 `null`, - /// 126/127 `exec_lo`/`exec_hi`. + /// 126/127 `exec_lo`/`exec_hi`. The decoder gives no code above 127; the + /// IR names scalars parked in VGPR lanes by the codes from 128 up + /// (`crate::ir::PARKED`). Scalar { code: u8, dwords: u8, diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index e3cbd60..09b1f8e 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -33,7 +33,7 @@ use crate::ShaderError; use crate::gfx10::{Fields, Operand}; -use crate::ir::{Inst, Program, Reg, Value}; +use crate::ir::{Exit, Inst, Program, Reg, Value, operand_reads}; use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage}; use crate::resource::Site; @@ -138,6 +138,11 @@ pub enum Interp { /// One vertex's value (`v_interp_mov_f32`), as encoded: 0 for P10, /// 1 for P20, 2 for P0 (the provoking vertex). Vertex { attribute: Attribute, vertex: u8 }, + /// A half of an interpolation whose i or j is computed rather than + /// loaded: each half evaluates as the hardware does, from the + /// attribute's vertex values (`v_interp_p1*`: P0 + i P10, with P10 = + /// P1 - P0; `v_interp_p2*`: its old dst + j P20, with P20 = P2 - P0). + Weighted { attribute: Attribute }, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -238,13 +243,52 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { (loaded, &[][..], &[][..]) } (StageIo::Ms(ms), HwStage::Ms) => { - let group = p.inputs.iter().find(|i| i.0 == Reg::V(5)).map(|i| i.1); + // The group input, and the phis that may carry it past a join. + let mut group: Vec = p + .inputs + .iter() + .filter(|i| i.0 == Reg::V(5)) + .map(|i| i.1) + .collect(); + // No lane is active over the EXEC-zero edge of s_cbranch_execz or + // _execnz, the same case as a partial-EXEC write below. + let no_lanes = |q: usize, b: usize| match ( + p.blocks[q].insts.last().map(Inst::name), + p.blocks[q].exit, + ) { + (Some("s_cbranch_execz"), Exit::Branch { taken, not_taken }) => { + taken == b && not_taken != b + } + (Some("s_cbranch_execnz"), Exit::Branch { taken, not_taken }) => { + not_taken == b && taken != b + } + _ => false, + }; + while let Some(v) = p + .blocks + .iter() + .enumerate() + .flat_map(|(b, k)| k.phis.iter().map(move |f| (b, f))) + .find_map(|(b, f)| { + let mut args = f.args.iter().zip(&p.blocks[b].preds); + let carried = args.any(|(a, &q)| group.contains(a) && !no_lanes(q, b)); + (carried && !group.contains(&f.value)).then_some(f.value) + }) + { + group.push(v); + } // The group input holds the same value in every lane only as the - // first lane reads it; a VGPR write reads its old value too. + // first lane reads it. A write to v5 reads its old value too, which + // only lanes outside EXEC keep. + // shortcut: writes that may keep the old v5 in active lanes + // (v_fmac_f32's accumulator, a 16-bit half or d16 load, + // v_writelane_b32, v_movreld_b32, DPP that skips lanes) and + // partial-EXEC writes pass; check those too if a mesh program + // writes v5 that way. let per_lane = p.blocks.iter().flat_map(|b| &b.insts).find(|i| { - group.is_some_and(|g| i.reads.contains(&(Reg::V(5), g))) + i.read(Reg::V(5)).is_some_and(|v| group.contains(&v)) && i.name() != "v_readfirstlane_b32" - && i.write(Reg::V(5)).is_none() + && (i.write(Reg::V(5)).is_none() || operand_reads(p, i).contains(&Reg::V(5))) }); if let Some(i) = per_lane { return Err(unsupported( @@ -352,7 +396,7 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { &barycentric, ) .map_err(|what| unsupported(at, what))?; - io.interps.push((site, interp.with(attribute))); + push_pair(&mut io, site, interp, attribute); } _ => return Err(unsupported(at, "an interpolation form")), } @@ -368,7 +412,7 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { let interp = halves .pair(&v.src[0], read(2), read(1), &barycentric) .map_err(|what| unsupported(at, what))?; - io.interps.push((site, interp.with(attribute))); + push_pair(&mut io, site, interp, attribute); } _ => return Err(unsupported(at, "an interpolation form")), }, @@ -439,22 +483,39 @@ fn ps_vgprs(addr: u32) -> Vec<(u8, Input)> { out } -/// An interpolation before its attribute is known. +/// An interpolation before its attribute is known: `barycentric` none +/// when i or j is computed. struct Pair { - barycentric: Barycentric, + barycentric: Option, first: Vec, } impl Pair { fn with(self, attribute: Attribute) -> Interp { - Interp::Interpolated { - attribute, - barycentric: self.barycentric, - first: self.first, + match self.barycentric { + Some(barycentric) => Interp::Interpolated { + attribute, + barycentric, + first: self.first, + }, + None => Interp::Weighted { attribute }, } } } +/// Records interpolation `pair` at `site`, and its first halves too when +/// they evaluate on their own (computed barycentrics). +fn push_pair(io: &mut Io, site: Site, pair: Pair, attribute: Attribute) { + if pair.barycentric.is_none() { + for &f in &pair.first { + if !io.interps.iter().any(|(s, _)| *s == f) { + io.interps.push((f, Interp::Weighted { attribute })); + } + } + } + io.interps.push((site, pair.with(attribute))); +} + /// Finds the first halves of interpolations. struct Halves<'a> { p: &'a Program, @@ -465,7 +526,9 @@ struct Halves<'a> { impl Halves<'_> { /// The interpolation whose second half reads the first half's result /// `acc`, the barycentric `j`, and attribute `attr`: every first half - /// must read the same attribute channel and the same kind's i. + /// must read the same attribute channel. With j and every first half's + /// i loaded as one kind's, the pair interpolates with that kind; + /// otherwise each half evaluates on its own (`Interp::Weighted`). fn pair( &self, attr: &Operand, @@ -479,8 +542,9 @@ impl Halves<'_> { &mut Vec::new(), &mut first, )?; - let Some((kind, 1)) = barycentric(j) else { - return Err("an interpolation with computed barycentrics"); + let mut kind = match barycentric(j) { + Some((kind, 1)) => Some(kind), + _ => None, }; for &(b, i) in &first { let inst = &self.p.blocks[b].insts[i]; @@ -499,8 +563,8 @@ impl Halves<'_> { if a != *attr { return Err("interpolation halves of different attributes"); } - if barycentric(i) != Some((kind, 0)) { - return Err("an interpolation with computed barycentrics"); + if kind.is_some_and(|k| barycentric(i) != Some((k, 0))) { + kind = None; } } Ok(Pair { @@ -634,6 +698,33 @@ mod tests { assert!(raise(&other, &pixel(vec![TEXCOORD], 2)).is_err()); } + #[test] + fn computed_barycentrics_evaluate_each_half() { + // i scaled before the first half: both halves stand on their own. + let p = program(&[ + 0x1006_00F0, // v_mul_f32 v3, 0.5, v0 + 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + S_ENDPGM, + ]); + let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap(); + let attribute = Attribute { + usage: Usage::Generic, + row: 1, + channel: 0, + high: false, + }; + let mut interps = io.interps.clone(); + interps.sort_by_key(|i| i.0); + assert_eq!( + interps, + [ + ((0, 1), Interp::Weighted { attribute }), + ((0, 2), Interp::Weighted { attribute }), + ] + ); + } + #[test] fn mesh_inputs_and_primitive_export() { let mesh = |words: &[u32]| { @@ -669,6 +760,41 @@ mod tests { assert_eq!(io.exports[0].target, Target::Primitive); // The group input is uniform only as the first lane reads it. assert!(mesh(&[0x7E02_0305, S_ENDPGM]).is_err()); // v_mov_b32 v1, v5 + // Also as an operand of a write to v5, or after a join. + let per_lane: [&[u32]; 5] = [ + &[0x4A0A_0305, S_ENDPGM], // v_add_nc_u32 v5, v5, v1 + &[0x7E0A_0D05, S_ENDPGM], // v_cvt_f32_u32 v5, v5 + &[0xDC30_8000, 0x0500_0005, S_ENDPGM], // global_load_dword v5, v5, s[0:1] + &[0x7E0A_CB01, S_ENDPGM], // v_swap_b32 v5, v1 + &[ + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF85_0001, // s_cbranch_scc1 -> 0xc + 0x7E0A_0280, // v_mov_b32 v5, 0 + 0x7E02_0305, // 0xc: v_mov_b32 v1, v5 + S_ENDPGM, + ], + ]; + let accepted: Vec<_> = per_lane.iter().filter(|w| mesh(w).is_ok()).collect(); + assert!(accepted.is_empty(), "accepted: {accepted:08X?}"); + // Overwriting v5 reads the group input only for lanes outside EXEC: + // v_mov_b32 v5, 0; v_mov_b32 v1, v5. + assert!(mesh(&[0x7E0A_0280, 0x7E02_0305, S_ENDPGM]).is_ok()); + // Skipping that write with s_cbranch_execz is the same case: under the + // same mask, the read sees only the 0. + let reuse = [ + 0x7E04_0505, // v_readfirstlane_b32 s2, v5 + 0x7D88_0084, // v_cmp_gt_u32 vcc, 4, v0 + 0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc + 0xBF88_0001, // s_cbranch_execz -> 0x14 + 0x7E0A_0280, // v_mov_b32 v5, 0 + 0x88FE_067E, // 0x14: s_or_b64 exec, exec, s[6:7] + 0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc + 0xBF88_0001, // s_cbranch_execz -> 0x24 + 0x7E02_0305, // v_mov_b32 v1, v5 + 0x88FE_067E, // 0x24: s_or_b64 exec, exec, s[6:7] + S_ENDPGM, + ]; + assert_eq!(mesh(&reuse).map(|_| ()), Ok(())); } #[test] diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index cc73a49..df7cecb 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -19,7 +19,9 @@ use crate::ShaderError; use crate::gfx10::{self, Fields, Flow, Instruction, Operand}; /// One register dword. Scalar codes as in [`Operand::Scalar`]: 0-105 SGPRs, -/// 106/107 VCC, 108-123 trap temporaries, 124 M0, 126/127 EXEC. +/// 106/107 VCC, 108-123 trap temporaries, 124 M0, 126/127 EXEC. Codes from +/// [`PARKED`] up are scalars the compiler parked in VGPR lanes (`unspill`): +/// no machine instruction names them. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Reg { S(u8), @@ -30,6 +32,8 @@ pub enum Reg { pub const VCC: u8 = 106; pub const M0: u8 = 124; pub const EXEC: u8 = 126; +/// The first scalar code past the machine's (0-127): see [`Reg`]. +pub const PARKED: u8 = 128; /// An SSA value: the content of one register dword (SCC: one bit). #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -123,7 +127,7 @@ impl Inst { /// count. Fails on instructions the IR cannot express yet /// ([`ShaderError::Unsupported`]). pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result { - let list = gfx10::decode(code)?; + let mut list = gfx10::decode(code)?; let lanes = 1 + u8::from(wave64); let isa = |offset, reason| ShaderError::Isa { offset, reason }; @@ -145,6 +149,7 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result Result> = (0..list.len()) .map(|i| list.get(i + 1).map(|n| n.offset)) .collect(); - for ((machine, flow), next) in list.into_iter().zip(flows).zip(next_offsets) { + for (n, ((machine, flow), next)) in list.into_iter().zip(flows).zip(next_offsets).enumerate() { let b = leaders.partition_point(|&l| l <= machine.offset) - 1; let name = machine.name().ok_or(ShaderError::Unsupported { offset: machine.offset, what: "unknown opcode", })?; - let fields = machine.fields(wave64); + let mut fields = machine.fields(wave64); + // A move to or from a scalar parked in a VGPR lane (`unspill`): its register + // codes may be ones the machine word cannot hold. + if let Ok(k) = parked.binary_search_by_key(&n, |m| m.0) + && let Fields::Sop { dst: Some(Operand::Scalar { code: to, .. }), src, .. } = &mut fields + && let Some(Operand::Scalar { code: from, .. }) = src.first_mut() + { + (*to, *from) = (parked[k].1, parked[k].2); + } let fallthrough = || block_at(next.ok_or(isa(machine.offset, "falls off the code"))?); let ends = flow != Flow::Next || next.is_none_or(|n| leaders.binary_search(&n).is_ok()); if ends { @@ -185,7 +198,13 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result Exit::End, }; } - if let Some((reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? { + if let Some((mut reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? { + // Lanes disabled in EXEC keep the old value. + for w in writes.iter().filter(|w| matches!(w, Reg::V(_))) { + if !reads.contains(w) { + reads.push(*w); + } + } let unset = |regs: Vec| regs.into_iter().map(|r| (r, NONE)).collect(); blocks[b].insts.push(Inst { machine, @@ -204,6 +223,230 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result Vec<(usize, u8, u8)> { + /// `v_writelane_b32 vN, sX, K` / `v_readlane_b32 sX, vN, K`: (save, N, X, K). + fn parked(inst: &gfx10::Instruction, fields: &Fields) -> Option<(bool, u8, u8, u32)> { + let Fields::Valu(v) = fields else { return None }; + if v.abs != 0 || v.neg != 0 || v.opsel != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some() || v.dpp.is_some() { + return None; + } + let lane = |op: &Operand| match *op { + Operand::Const(c @ 128..=191) => Some(u32::from(c) - 128), + _ => None, + }; + match (inst.name()?, v.dst?, v.src.as_slice()) { + ("v_writelane_b32", Operand::Vector { reg, .. }, [Operand::Scalar { code, .. }, k]) if *code < 105 => { + Some((true, reg, *code, lane(k)?)) + } + ("v_readlane_b32", Operand::Scalar { code, .. }, [Operand::Vector { reg, .. }, k]) if code < 105 => { + Some((false, *reg, code, lane(k)?)) + } + _ => None, + } + } + // VGPRs used by parking alone, the scalar codes the program uses, and + // per instruction the scalar codes it writes. + let mut stores = [false; 256]; + let mut other = [false; 256]; + let mut used = [false; 128]; + let mut parks: Vec> = Vec::with_capacity(list.len()); + let mut written: Vec> = Vec::with_capacity(list.len()); + for inst in list.iter() { + let Some(name) = inst.name() else { return Vec::new() }; + let fields = inst.fields(wave64); + let park = parked(inst, &fields); + let Ok(effects) = effects(inst, &fields, name, lanes, vgprs) else { + return Vec::new(); + }; + let mut codes = Vec::new(); + if let Some((reads, writes)) = effects { + for ® in &writes { + if let Reg::S(c) = reg { + codes.push(c); + } + } + for reg in reads.into_iter().chain(writes) { + match reg { + Reg::S(c) => used[usize::from(c)] = true, + Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true, + Reg::V(r) => other[usize::from(r)] = true, + Reg::Scc => {} + } + } + } + parks.push(park); + written.push(codes); + } + for (i, park) in parks.iter_mut().enumerate() { + if park.is_some_and(|p| other[usize::from(p.1)]) { + *park = None; + } + let _ = i; + } + if parks.iter().all(Option::is_none) { + return Vec::new(); + } + let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok(); + // Lane pairs (register, lower lane) that always move together: each + // save of the lower lane is followed, in the same block and before its + // register changes, by the save of the next register into the next + // lane; each restore of the lower lane is followed at once by the + // restore of the next lane into the next register. + // The second save may come any number of instructions after the first (the + // compiler puts loads and constants between the two: five instructions later + // in the ped mesh programs). Only wave64 programs have pairs: a wave32 mask + // is one dword, and a pair move of it with its neighbour would hide it. + let mut slots: Vec<(u8, u32)> = parks.iter().flatten().map(|p| (p.1, p.3)).collect(); + slots.sort_unstable(); + slots.dedup(); + // instruction -> the instruction that completes its pair + let partner = |i: usize| -> Option { + let (save, reg, code, lane) = parks[i]?; + if save { + let mut j = i + 1; + while j < list.len() && !leader(j) { + if parks[j] == Some((true, reg, code + 1, lane + 1)) { + return Some(j); + } + if parks[j].is_some_and(|p| p.1 == reg && (p.3 == lane || p.3 == lane + 1)) + || written[j].contains(&code) + || written[j].contains(&(code + 1)) + { + return None; + } + j += 1; + } + None + } else { + let j = i + 1; + (j < list.len() && !leader(j) && parks[j] == Some((false, reg, code + 1, lane + 1))).then_some(j) + } + }; + let mut pairs: Vec<(u8, u32)> = Vec::new(); + for &(reg, lane) in &slots { + if !wave64 || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) || !slots.contains(&(reg, lane + 1)) { + continue; + } + let lower: Vec = (0..list.len()).filter(|&i| parks[i].is_some_and(|p| (p.1, p.3) == (reg, lane))).collect(); + let upper = parks.iter().flatten().filter(|p| (p.1, p.3) == (reg, lane + 1)).count(); + let partners: Vec> = lower.iter().map(|&i| partner(i)).collect(); + let mut distinct: Vec = partners.iter().flatten().copied().collect(); + distinct.sort_unstable(); + distinct.dedup(); + if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() { + pairs.push((reg, lane)); + } + } + // Codes for the parked scalars: the trap temporaries (108..=123), then + // user SGPRs the program never names, from the top, then the codes past + // the machine's (`PARKED`..=254; 255 stays unused so that the code after a + // parked one always exists). A material resolve program parks up to 63 + // scalars and leaves about 20 machine codes unused. + let past = usize::from(PARKED); + let mut free = [false; 256]; + for c in (0..105).chain(108..=123) { + free[c] = !used[c]; + } + free[past..255].fill(true); + let mut codes: Vec<((u8, u32), u8)> = Vec::new(); + for &(reg, lane) in &pairs { + let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]); + // Not enough spare codes: leave the program as it is. + let Some(c) = at else { return Vec::new() }; + (free[c], free[c + 1]) = (false, false); + codes.push(((reg, lane), c as u8)); + codes.push(((reg, lane + 1), c as u8 + 1)); + } + for &slot in &slots { + if codes.iter().any(|c| c.0 == slot) { + continue; + } + let Some(c) = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c]) else { + return Vec::new(); + }; + free[c] = false; + codes.push((slot, c as u8)); + } + let code_of = |reg: u8, lane: u32| codes.iter().find(|c| c.0 == (reg, lane)).map(|c| c.1); + let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| { + list[i] = gfx10::Instruction { + offset: list[i].offset, + encoding, + opcode, + words: vec![word], + }; + }; + // `s_mov_b32` / `s_mov_b64 dst, src` (SOP1, opcodes 3 and 4); `s_nop`. A code + // from `PARKED` up does not fit the word: s0 stands in for it there. + let field = |code: u8| if code < PARKED { u32::from(code) } else { 0 }; + let mov = |wide: bool, dst: u8, src: u8| 0xBE80_0000 | field(dst) << 16 | (3 + u32::from(wide)) << 8 | field(src); + const NOP: u32 = 0xBF80_0000; + let mut edits: Vec<(usize, Option<(bool, u8, u8)>)> = Vec::new(); + for i in 0..list.len() { + let Some((save, reg, code, lane)) = parks[i] else { + continue; + }; + let Some(slot) = code_of(reg, lane) else { return Vec::new() }; + if pairs.contains(&(reg, lane)) { + let Some(j) = partner(i) else { return Vec::new() }; + // A save moves the pair where its second half is saved; a + // restore where its first half is restored. + let (at, gone) = if save { (j, i) } else { (i, j) }; + let (dst, src) = if save { (slot, code) } else { (code, slot) }; + edits.push((at, Some((true, dst, src)))); + edits.push((gone, None)); + } else if lane > 0 && pairs.contains(&(reg, lane - 1)) { + // the upper half of a pair: moved with the lower + } else { + let (dst, src) = if save { (slot, code) } else { (code, slot) }; + edits.push((i, Some((false, dst, src)))); + } + } + let mut moves = Vec::new(); + for (i, edit) in edits { + match edit { + Some((wide, dst, src)) => { + put(list, i, gfx10::Encoding::Sop1, 3 + u16::from(wide), mov(wide, dst, src)); + moves.push((i, dst, src)); + } + None => put(list, i, gfx10::Encoding::Sopp, 0, NOP), + } + } + moves.sort_unstable(); + moves +} + +/// Rename register reads and writes after changing edges in a reducible graph. +fn rename(mut blocks: Vec, wave64: bool, vgprs: u16) -> Program { let order = reverse_postorder(&blocks); let (live_in, live_out) = liveness(&blocks, &order); let mut values = 0u32; @@ -262,33 +505,193 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result Result { + let mut blocks = p.blocks.clone(); + for block in &mut blocks { + block.phis.clear(); + } + for &(pred, join, dest) in edges { + let mut copy = blocks[join].clone(); + copy.exit = Exit::Jump(dest); + let target = blocks.len(); + match &mut blocks[pred].exit { + Exit::Jump(t) => *t = target, + Exit::Branch { taken, not_taken } => { + if *taken == join { + *taken = target; + } + if *not_taken == join { + *not_taken = target; + } + } + _ => unreachable!("threading an incoming edge"), + } + blocks.push(copy); + } + link(&mut blocks); + split_irreducible(&mut blocks)?; + Ok(rename(blocks, p.wave64, p.vgprs)) +} + +/// The program without its early-outs: an `s_cbranch_execz` to a block that +/// only ends the program (`if (!inBounds) return;`, the outermost branch of +/// most compute programs) is left out, so the lanes that would have left +/// walk the body with EXEC clear. Vector instructions and every effect are +/// masked by EXEC already, as on the console, where the branch is taken +/// only when no lane of the wave is left; scalar code has no effects. The +/// body is then code every lane runs, which a console wave run as two host +/// waves needs for the barriers of its exchanges and LDS accesses. +/// `None` if the program has no such branch. +pub(crate) fn without_early_outs(p: &Program) -> Option { + let ends = |b: usize| { + p.blocks[b].exit == Exit::End + && p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) + }; + let mut blocks = p.blocks.clone(); + let mut any = false; + for block in &mut blocks { + let Exit::Branch { taken, not_taken } = block.exit else { + continue; + }; + if ends(taken) && block.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz") { + block.insts.pop(); + block.exit = Exit::Jump(not_taken); + any = true; + } + } + if !any { + return None; + } + for block in &mut blocks { + block.phis.clear(); + } + link(&mut blocks); + split_irreducible(&mut blocks).ok()?; + Some(rename(blocks, p.wave64, p.vgprs)) +} + +/// As [`without_early_outs`], and also without the branches that only skip a +/// region when no lane is left for it: an `s_cbranch_execz` whose target is +/// where the skipped code ends up anyway (`if (c) { ... }` with nothing +/// else leaving the region). Every lane then walks the region with EXEC +/// clear for those that would have skipped it, and LDS accesses and +/// exchanges inside it are in code every lane runs. +/// The console takes such a branch only when no lane of the wave is left, +/// and then its scalar code does not run: a branch is kept if the code +/// after it could see that (a scalar register or SCC that the region +/// changes and the join merges with the value from before; EXEC aside, +/// which is empty either way). `None` if nothing changes. +pub(crate) fn without_skips(p: &Program) -> Option { + let n = p.blocks.len(); + let ends = |b: usize| { + p.blocks[b].exit == Exit::End + && p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) + }; + // The region a skip of `b` to `target` leaves out, if it is a pure skip. + let skipped = |b: usize, target: usize, first: usize| -> Option> { + let mut inside = vec![false; n]; + let mut stack = vec![first]; + while let Some(x) = stack.pop() { + if x == target || inside[x] { + continue; + } + if x == b { + return None; // a loop back to the branch + } + inside[x] = true; + match p.blocks[x].exit { + Exit::End | Exit::Indirect => return None, + exit => stack.extend(exit.successors()), + } + } + // entered only through the branch + for x in (0..n).filter(|&x| inside[x]) { + if p.blocks[x].preds.iter().any(|&q| q != b && !inside[q]) { + return None; + } + } + // the join sees no scalar the region changed + let join = &p.blocks[target]; + for phi in &join.phis { + let scalar = match phi.reg { + Reg::S(c) => c != 126 && c != 127, + Reg::Scc => true, + Reg::V(_) => false, + }; + if !scalar { + continue; + } + let before: Vec = + join.preds.iter().zip(&phi.args).filter(|(q, _)| **q == b).map(|(_, a)| *a).collect(); + let within = join.preds.iter().zip(&phi.args).filter(|(q, _)| inside[**q]).map(|(_, a)| *a); + if within.into_iter().any(|a| !before.contains(&a)) { + return None; + } + } + // other ways into the join than the branch and the region: not a plain `if` + if join.preds.iter().any(|&q| q != b && !inside[q]) { + return None; + } + Some(inside) + }; + let mut blocks = p.blocks.clone(); + let mut any = false; + for b in 0..n { + let Exit::Branch { taken, not_taken } = p.blocks[b].exit else { + continue; + }; + if !p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz") { + continue; + } + if ends(taken) || skipped(b, taken, not_taken).is_some() { + blocks[b].insts.pop(); + blocks[b].exit = Exit::Jump(not_taken); + any = true; + } + } + if !any { + return None; + } + for block in &mut blocks { + block.phis.clear(); + } + link(&mut blocks); + split_irreducible(&mut blocks).ok()?; + Some(rename(blocks, p.wave64, p.vgprs)) } /// Placeholder before renaming. const NONE: Value = Value(u32::MAX); -/// SGPR codes 0-127, SCC, VGPRs 0-255. -const REGS: usize = 128 + 1 + 256; +/// Scalar codes 0-255 (from [`PARKED`] up: parked scalars), SCC, VGPRs 0-255. +const REGS: usize = 256 + 1 + 256; type RegSet = [u64; REGS.div_ceil(64)]; fn index(reg: Reg) -> usize { match reg { Reg::S(c) => usize::from(c), - Reg::Scc => 128, - Reg::V(r) => 129 + usize::from(r), + Reg::Scc => 256, + Reg::V(r) => 257 + usize::from(r), } } fn reg_at(i: usize) -> Reg { match i { - 0..128 => Reg::S(i as u8), - 128 => Reg::Scc, - _ => Reg::V((i - 129) as u8), + 0..256 => Reg::S(i as u8), + 256 => Reg::Scc, + _ => Reg::V((i - 257) as u8), } } @@ -662,6 +1065,16 @@ const DROPPED: &[&str] = &[ /// Registers read, registers written. type Effects = (Vec, Vec); +/// The registers `inst` of `p` reads as operands: its reads without the old +/// value of a VGPR it only writes. +pub(crate) fn operand_reads(p: &Program, inst: &Inst) -> Vec { + let lanes = 1 + u8::from(p.wave64); + effects(&inst.machine, &inst.fields, inst.name(), lanes, p.vgprs) + .ok() + .flatten() + .map_or_else(Vec::new, |e| e.0) +} + /// Registers an instruction reads and writes, one per dword, or `None` if /// the IR drops it. fn effects( @@ -818,6 +1231,7 @@ fn effects( indexed(d, &mut r)?; } } + "v_div_fmas_f32" | "v_div_fmas_f64" => r.extend(mask(VCC)), _ => {} } if name.starts_with("v_interp_") || src_indexed || dst_indexed { @@ -930,8 +1344,6 @@ fn effects( } if vector { r.extend(mask(EXEC)); - // Lanes disabled in EXEC keep the old value. - r.extend(w.iter().filter(|w| matches!(w, Reg::V(_)))); } let mut seen = Vec::with_capacity(r.len()); r.retain(|reg| { @@ -1008,10 +1420,13 @@ fn add_regs(op: &Operand, lanes: u8, out: &mut Vec) -> Result<(), ()> { Operand::Scalar { code, .. } if code == gfx10::NULL => {} Operand::Scalar { code, dwords } => { let end = u16::from(code) + u16::from(dwords); - if end > 128 { + // A machine operand ends within the machine's codes, a parked + // scalar (`unspill`) within those past them. + let limit = if code < PARKED { 128 } else { 256 }; + if end > limit { return Err(()); } - out.extend((code..end as u8).map(Reg::S)); + out.extend((u16::from(code)..end).map(|c| Reg::S(c as u8))); } Operand::Vector { reg, dwords } => { if u16::from(reg) + u16::from(dwords) > 256 { diff --git a/crates/victory-shader/src/lib.rs b/crates/victory-shader/src/lib.rs index 8d8c164..30b1952 100644 --- a/crates/victory-shader/src/lib.rs +++ b/crates/victory-shader/src/lib.rs @@ -6,6 +6,7 @@ //! (compiler options) and the zlib-compressed GFX10 code. The bitcode may use //! console-only intrinsics, so the GFX10 code is translated in general. +pub mod bvh; pub mod dxbc; pub mod dxil; pub mod emit; @@ -14,6 +15,7 @@ pub mod io; pub mod ir; pub mod native; pub mod resource; +pub mod spill; pub mod structure; pub use dxbc::{Container, FourCC, Part}; diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 62ddd5d..3d7952c 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -16,7 +16,7 @@ use crate::ShaderError; use crate::gfx10::{Fields, NULL, Operand}; use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; use crate::native::{HwStage, RootParam, RootType}; -use crate::structure::{Bool, LaneExit, Structured}; +use crate::structure::{Bool, LaneExit, Meets, Structured}; /// An instruction: block and index in [`crate::ir::Block::insts`]. pub type Site = (usize, usize); @@ -38,6 +38,24 @@ pub struct Address { /// offset is then the byte offset in the code. pub const CODE: usize = usize::MAX; +/// [`Address::param`] of title memory at an address no root parameter +/// gives: one the code computes from root constants, reads out of a +/// descriptor or loads from other memory (compute programs only: the +/// ray-tracing structure builder and the programs that walk its +/// structures). Offset and computed term are not used: lowering takes the +/// 64-bit address from the instruction's operands. +pub const MEMORY: usize = usize::MAX - 1; + +/// The reasons an address traces to no root parameter for which the +/// address is then taken as it stands ([`MEMORY`]). +const RAW: [&str; 5] = [ + "an address not from a root parameter", + "an address from a root parameter that is no address", + "an address in an SGPR that is no root parameter", + "an address loaded from memory", + "an address from a phi", +]; + #[derive(Debug, Clone, PartialEq, Eq)] pub enum Source { /// Dwords `first..` of what the scalar load at `load` reads (see @@ -107,16 +125,52 @@ pub struct Descriptor { pub source: Source, } +/// A view-heap descriptor whose byte address can be evaluated when binding +/// the draw, using a table base and a root constant. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RootIndexedView { + pub table_slot: u8, + pub constant_slot: u8, + pub constant_dword: u32, + pub byte_offset: u32, + pub shift: u8, +} + #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Resources { /// Every scalar memory access by address (`s_load_*`, `s_store_*`), and /// every global memory access (`global_*`, the dynamic term per lane). pub scalar: Vec<(Site, Address)>, pub descriptors: Vec, + /// Direct descriptor sources with a draw-evaluable index. + pub root_indexed_views: Vec, /// User SGPRs holding root parameters: value on entry, layout index, /// dword within the parameter. pub params: Vec<(Value, usize, u32)>, + /// Scalar loads of one descriptor the code keeps per lane in VGPRs + /// ([`Tracer::lane_copies`]): they read one address, so their dwords + /// stand in for each other. + pub lane_copied: Vec, pub waterfall: Waterfall, + /// Every `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`: where + /// its nodes are. + pub bvh: Vec<(Site, BvhNodes)>, +} + +/// Where a ray-tracing node test ([`crate::bvh`]) reads its nodes. Its +/// descriptor operand names a range of memory, not a texture. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BvhNodes { + /// A buffer of the host: the descriptor is loaded from a table (it is + /// among [`Resources::descriptors`]), and node pointers count from the + /// buffer's start. Its flags are not known to the shader: boxes are + /// sorted and triangles return barycentrics, as every descriptor Grand + /// Theft Auto VI builds asks. + Resource, + /// Title memory by address: the code makes the descriptor from numbers + /// (the title: the whole address space, or one structure's address in + /// dword 0). Dwords 1 and 3, which hold its flags. + Memory { word1: u32, word3: u32 }, } /// Waterfall loops over descriptors that differ between lanes: each pass @@ -170,6 +224,7 @@ pub fn track( let mut offset_at = std::collections::BTreeMap::, Vec, Vec)>::new(); for (b, block) in p.blocks.iter().enumerate() { + t.at.set(Some(b)); for (i, inst) in block.insts.iter().enumerate() { let site = (b, i); let fail = |what| ShaderError::Unsupported { @@ -180,11 +235,15 @@ pub fn track( let mut offset = Vec::new(); let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> { let source = t.descriptor(inst, op, b).map_err(fail)?; - first_lane.extend(t.first_lane_words(inst, op).unwrap_or_default()); + // A descriptor the code keeps per lane ([`Tracer::lane_copies`]) + // is the same in every lane: its loop is lowered as it stands + // and needs no proof. + if !t.kept_per_lane(inst, op) { + first_lane.extend(t.first_lane_words(inst, op).unwrap_or_default()); + } if let Source::Loaded { load, .. } = source - && let Some((_, a)) = out.scalar.iter().find(|s| s.0 == load) - && let Some(Term::Value(v)) = a.dynamic.map(|d| t.origin(d)) - && t.first_lane_source(v).is_some() + && out.scalar.iter().any(|s| s.0 == load) + && let Some(v) = t.first_lane_offset(load) { offset.push((v, load)); } @@ -192,13 +251,44 @@ pub fn track( Ok(()) }; match &inst.fields { + Fields::Image { rsrc, .. } if inst.name().starts_with("image_bvh") => { + // The ray and node test names no texture. A descriptor + // whose flag dwords the code sets as numbers and whose + // type is a ray-tracing structure is a range of title + // memory (the title: all of it, or from one structure's + // address on), and the node's address is among the + // operands; any other descriptor must be a resource of + // the host. + let word = |k: u8| match *rsrc { + Operand::Scalar { code, dwords } if k < dwords => { + inst.read(Reg::S(code + k)).map(|v| t.origin(v)) + } + _ => None, + }; + match (word(1), word(3)) { + (Some(Term::Const(word1)), Some(Term::Const(word3))) + if word3 >> 28 == crate::bvh::DESCRIPTOR_TYPE => + { + out.bvh.push((site, BvhNodes::Memory { word1, word3 })); + } + _ => { + descriptor(rsrc, Role::Resource)?; + out.bvh.push((site, BvhNodes::Resource)); + } + } + } Fields::Image { rsrc, sampler, .. } => { descriptor(rsrc, Role::Resource)?; if let Some(s) = sampler { descriptor(s, Role::Sampler)?; } } - Fields::Buffer { rsrc, .. } => descriptor(rsrc, Role::Resource)?, + // Cache invalidations name a buffer's address space but do + // not read its descriptor; the host has no cache to drop. + Fields::Buffer { rsrc, .. } if !inst.name().ends_with("_inv") => { + descriptor(rsrc, Role::Resource)? + } + Fields::Buffer { .. } => {} Fields::Smem { base, .. } if inst.name().starts_with("s_buffer_") => { descriptor(base, Role::Resource)?; } @@ -208,7 +298,10 @@ pub fn track( soffset, .. } if inst.name().contains("_load_") || inst.name().contains("_store_") => { - let address = t.smem_address(inst, base, *offset, soffset).map_err(fail)?; + let address = t + .smem_address(inst, base, *offset, soffset) + .or_else(|why| t.by_address(why)) + .map_err(fail)?; out.scalar.push((site, address)); } Fields::Flat { @@ -219,6 +312,7 @@ pub fn track( } if inst.name().starts_with("global_") => { let address = t .flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset) + .or_else(|why| t.by_address(why)) .map_err(fail)?; out.scalar.push((site, address)); } @@ -239,6 +333,8 @@ pub fn track( } } } + // What follows traces no access of one block. + t.at.set(None); // The proof needs the per-lane form. Without it nothing is emitted, and // its failure is the one to report, so the reads stay unproven here. if t.lanes.is_none() { @@ -267,6 +363,14 @@ pub fn track( out.waterfall.loads.extend(loads); } } + out.lane_copied = t.lane_copied.take(); + out.lane_copied.sort_unstable(); + out.lane_copied.dedup(); + out.root_indexed_views = out + .descriptors + .iter() + .filter_map(|d| t.root_indexed_view(d, &out.scalar)) + .collect(); Ok(out) } @@ -296,9 +400,19 @@ struct Tracer<'a> { /// Register per input value. inputs: Vec>, origin: Vec, + /// See [`Resources::lane_copied`]. + lane_copied: std::cell::RefCell>, lanes: Option<&'a Structured>, + /// While set, [`Self::sum`] keeps the first-lane read of an index as + /// the computed term instead of what the lanes hold. + read_first_lane: std::cell::Cell, + /// What the conditions asked of `lanes` so far came down to: the proofs + /// of one program ask about the same blocks and masks again and again. + meets: std::cell::RefCell, /// Reverse-postorder index per block. rpo: Vec, + /// The block of the access being traced ([`Self::live`]). + at: std::cell::Cell>, } /// What lanes are known to satisfy: each [`Bool`] where its flag is set, @@ -307,6 +421,8 @@ type Known = Vec<(Bool, bool)>; const MAX_ROUNDS: usize = 64; const MAX_JOINS: usize = 8; +/// VGPR values followed for one dword of a descriptor kept per lane. +const MAX_COPIES: usize = 64; impl<'a> Tracer<'a> { fn new( @@ -358,8 +474,12 @@ impl<'a> Tracer<'a> { phis, inputs, origin: Vec::new(), + lane_copied: Default::default(), lanes, + read_first_lane: Default::default(), + meets: Default::default(), rpo, + at: Default::default(), }; t.origin = t.propagate_copies(n)?; Ok(t) @@ -420,6 +540,15 @@ impl<'a> Tracer<'a> { }) } + /// Whether some lane can satisfy all of `conditions` ([`Bools::meet`]). + /// + /// [`Bools::meet`]: crate::structure::Bools::meet + fn meet(&self, lanes: &Structured, conditions: &[(Bool, bool)]) -> bool { + lanes + .bools + .meet_seen(conditions, &mut self.meets.borrow_mut()) + } + fn inst(&self, (b, i): Site) -> &'a Inst { &self.p.blocks[b].insts[i] } @@ -453,7 +582,7 @@ impl<'a> Tracer<'a> { }) } - /// The SOP2 operands of `v` if an `s_add` with one of `names` wrote it. + /// The SOP2 operands of `v` if an instruction with one of `names` wrote it. fn sop2(&self, v: Value, names: &[&str]) -> Option<(&'a Inst, [Term; 2])> { let inst = self.def(v)?; if !names.contains(&inst.name()) || inst.writes.first()?.1 != v { @@ -471,6 +600,42 @@ impl<'a> Tracer<'a> { )) } + fn root_indexed_view( + &self, + descriptor: &Descriptor, + scalar: &[(Site, Address)], + ) -> Option { + if descriptor.role != Role::Resource { + return None; + } + let Source::Loaded { load, first } = descriptor.source else { + return None; + }; + let i = scalar.binary_search_by_key(&load, |(site, _)| *site).ok()?; + let address = scalar[i].1; + let base = self.layout.get(address.param)?; + if base.root != RootType::Table { + return None; + } + let dynamic = address.dynamic?; + let (input, shift) = match self.sop2(dynamic, &["s_lshl_b32"]) { + Some((_, [Term::Value(input), Term::Const(shift)])) => (input, (shift & 31) as u8), + _ => (dynamic, 0), + }; + let (param, constant_dword) = self.param_of(self.inputs[input.0 as usize]?)?; + let constant = self.layout.get(param)?; + if constant.root != RootType::Constants { + return None; + } + Some(RootIndexedView { + table_slot: base.slot, + constant_slot: constant.slot, + constant_dword, + byte_offset: address.offset.wrapping_add(u32::from(first) * 4), + shift, + }) + } + fn sum(&self, t: Term) -> Sum { let v = match t { Term::Const(c) => { @@ -504,6 +669,34 @@ impl<'a> Tracer<'a> { dynamic: None, }; } + // Paths that each add an index to a table in the code and meet before one + // load: the join itself is the computed term. Lowering gives every + // `s_getpc_b64` its own offset in the code as its value, so the join is the + // byte in the code whichever table a path took ([`Self::address`] adds no + // base to it). + if let Some(pc) = self.code_join(v) { + return Sum { + base: Some(pc), + offset: 0, + dynamic: Some(v), + }; + } + // An address computed in VGPRs and taken from the first lane (a + // table in the code indexed by a value held per lane, or a table + // offset held per lane, the console's waterfall): the sum of what + // the lanes hold. Loads at one offset in different loops (each with + // its own `v_readfirstlane_b32`) then have one address, which is + // what tells lowering that they read one descriptor. With + // `read_first_lane` a first-lane read of an index alone stays the + // computed term ([`Self::first_lane_offset`]). + if let Some(lane) = self.first_lane(v) { + let per_lane = self.sum(self.vorigin(lane)); + return if per_lane.base.is_some() || !self.read_first_lane.get() { + per_lane + } else { + dynamic + }; + } let Some([a, b]) = self .sop2(v, &["s_add_u32", "s_add_i32"]) .map(|(_, t)| t) @@ -522,6 +715,106 @@ impl<'a> Tracer<'a> { } } + /// For a join `v` whose every incoming value adds to an `s_getpc_b64` low + /// dword: the first of those (one level of joins only). The paths may add + /// to different ones: two tables in the code, one picked by control flow + /// (Grand Theft Auto VI's fog reconstruction reads its sample offsets from + /// one of two tables, by the sample's number; refused, the lit frame was + /// multiplied by a fog transmittance nothing had written). + fn code_join(&self, v: Value) -> Option { + let (b, i) = self.phis[v.0 as usize]?; + let mut base = None; + for &a in &self.p.blocks[b].phis[i].args { + let Term::Value(x) = self.vorigin(a) else { + return None; + }; + if x == v { + continue; + } + let pc = self.code_base(x, 4)?; + base = base.or(Some(pc)); + } + base + } + + /// `t` is the high dword of an `s_getpc_b64`, or `s_addc_u32`s of one: + /// the carry may be added in steps (the counter's high dword plus 0 + /// where the table's offset is added, then plus the index's high dword). + fn code_high(&self, t: Term) -> bool { + self.code_high_in(t, 4) + } + + /// [`Self::code_high`], at most `depth` additions deep. + fn code_high_in(&self, t: Term, depth: u32) -> bool { + let Term::Value(x) = t else { return false }; + if self.def(x).is_some_and(|i| { + i.name() == "s_getpc_b64" && i.writes.get(1).is_some_and(|w| w.1 == x) + }) { + return true; + } + depth > 0 + && self.sop2(x, &["s_addc_u32"]).is_some_and(|(_, [p, q])| { + self.code_high_in(p, depth - 1) || self.code_high_in(q, depth - 1) + }) + } + + /// The `s_getpc_b64` low dword among the terms `v` adds up (`depth` + /// additions deep; joins are not followed). + fn code_base(&self, v: Value, depth: u32) -> Option { + if self.getpc(v).is_some() { + return Some(v); + } + // Computed in VGPRs and taken from the first lane. + if let Some(lane) = self.first_lane(v) { + return match self.vorigin(lane) { + Term::Value(x) => self.code_base(x, depth), + Term::Const(_) => None, + }; + } + if depth == 0 || self.phis[v.0 as usize].is_some() { + return None; + } + let terms = self + .sop2(v, &["s_add_u32", "s_add_i32"]) + .map(|(_, t)| t) + .or_else(|| self.vadd(v))?; + terms.into_iter().find_map(|t| match t { + Term::Value(x) => self.code_base(x, depth - 1), + Term::Const(_) => None, + }) + } + + /// `t` is `high` or an `s_addc_u32` of it. + fn is_high(&self, t: Term, high: Value) -> bool { + match t { + Term::Value(x) => { + x == high + || self + .sop2(x, &["s_addc_u32"]) + .is_some_and(|(_, [p, q])| p == Term::Value(high) || q == Term::Value(high)) + } + Term::Const(_) => false, + } + } + + /// The VGPR value `v_readfirstlane_b32` reads to write the scalar `v`. + fn first_lane(&self, v: Value) -> Option { + let inst = self.def(v)?; + if inst.name() != "v_readfirstlane_b32" || inst.writes.first()?.1 != v { + return None; + } + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + return None; + } + match *f.src.first()? { + Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), + _ => None, + } + } + /// The `s_getpc_b64` writing `lo` as its low dword. fn getpc(&self, lo: Value) -> Option<&'a Inst> { let inst = self.def(lo)?; @@ -579,6 +872,21 @@ impl<'a> Tracer<'a> { self.origin(v) } + /// The address of an access that traces to no root parameter (`why` + /// says how it failed): title memory at the address as it stands, in a + /// compute program. + fn by_address(&self, why: &'static str) -> Result { + if self.stage == HwStage::Cs && RAW.contains(&why) { + Ok(Address { + param: MEMORY, + offset: 0, + dynamic: None, + }) + } else { + Err(why) + } + } + /// A global memory address: an SGPR pair plus a VGPR offset, or a VGPR /// pair. fn flat_address( @@ -627,6 +935,15 @@ impl<'a> Tracer<'a> { /// The address `lo` and `hi` hold, plus `extra` (an instruction's /// immediate and offset register). fn address(&self, lo: Term, hi: Term, extra: Sum) -> Result { + // The high half as the lanes that read through the address hold + // it, where that is a constant or what a register held on entry + // (the code clears a table address's high half inside a branch + // and uses the address after the join). + let hi = match self.live(hi) { + t @ Term::Const(_) => t, + Term::Value(v) if self.inputs[v.0 as usize].is_some() => Term::Value(v), + _ => hi, + }; let s = self.sum(lo); if s.dynamic.is_some() && extra.dynamic.is_some() { return Err("an address with two computed terms"); @@ -638,11 +955,13 @@ impl<'a> Tracer<'a> { if !self.high_half(hi, high) && !high.is_some_and(|h| self.carried(hi, h)) { return Err("an address with an untracked high half"); } + // A join of paths into tables in the code is the byte in the code + // already: each path's `s_getpc_b64` counts as its own offset. + let joined = s.dynamic.is_some_and(|d| self.code_join(d).is_some()); + let first = if joined { 0 } else { pc.machine.offset as u32 + 4 }; return Ok(Address { param: CODE, - offset: (pc.machine.offset as u32 + 4) - .wrapping_add(s.offset) - .wrapping_add(extra.offset), + offset: first.wrapping_add(s.offset).wrapping_add(extra.offset), dynamic: s.dynamic.or(extra.dynamic), }); } @@ -690,6 +1009,39 @@ impl<'a> Tracer<'a> { if v == high { return true; } + // A join ([`Self::code_join`]): every path carries into the table's high half. + if let Some((b, i)) = self.phis[v.0 as usize] { + // A path may carry into another table's high half ([`Self::code_join`]). + let high_of = |t: Term| self.is_high(t, high) || self.code_high(t); + return self.p.blocks[b].phis[i].args.iter().all(|&a| { + let t = self.vorigin(a); + if t == Term::Value(v) || high_of(t) { + return true; + } + let Term::Value(x) = t else { + return false; + }; + // Computed in VGPRs and taken from the first lane. + let x = match self.first_lane(x).map(|lane| self.vorigin(lane)) { + Some(Term::Value(y)) => y, + Some(Term::Const(_)) => return false, + None => x, + }; + let Some(inst) = self.def(x) else { + return false; + }; + let Fields::Valu(f) = &inst.fields else { + return false; + }; + inst.name() == "v_add_co_ci_u32" + && f.src[..2.min(f.src.len())] + .iter() + .any(|o| self.vterm(inst, o).is_some_and(high_of)) + }); + } + if let Some(lane) = self.first_lane(v) { + return self.carried(self.vorigin(lane), high); + } if let Some((_, [a, b])) = self.sop2(v, &["s_addc_u32"]) { return self.carried(a, high) || self.carried(b, high); } @@ -794,6 +1146,10 @@ impl<'a> Tracer<'a> { Term::Const(_) => None, }; if let Some(sources) = words.iter().map(read).collect::>>() { + // One descriptor the code keeps per lane: the lanes agree. + if let Some(source) = self.lane_copies(words) { + return Ok(source); + } // Read from the first active lane, as a waterfall loop does: the // dwords each lane holds. let lanes: Vec = sources.into_iter().map(Term::Value).collect(); @@ -848,6 +1204,91 @@ impl<'a> Tracer<'a> { }) } + /// The one edge into the join `block` that lanes satisfying `known` + /// can have taken, if the lanes' paths ([`Structured`]) rule out every + /// other: the console compiler loads a descriptor (or clears an + /// address's high half) inside a branch that skips code when no lane + /// is left for it, and uses it after the join, where only lanes that + /// ran the branch are left (Grand Theft Auto VI's + /// `CS_Alpha_Schedule`: the registers' values from before the branch, + /// which the join also sees, are what a wave with no such lane holds). + /// None at loop headers and without the lanes' paths. + fn only_edge(&self, block: usize, known: &mut Known) -> Option { + let lanes = self.lanes?; + let preds = &self.p.blocks[block].preds; + if preds.len() < 2 || preds.iter().any(|&q| self.rpo[q] >= self.rpo[block]) { + return None; + } + let mut only = None; + for (j, &q) in preds.iter().enumerate() { + let n = known.len(); + known.push((lanes.reach[q], true)); + if let LaneExit::Branch { + when, + taken, + not_taken, + } = lanes.exits[q] + && taken != not_taken + { + known.push((when, taken == block)); + } + let possible = self.meet(lanes, known); + known.truncate(n); + if possible { + if only.is_some() { + return None; + } + only = Some(j); + } + } + only + } + + /// Whether lowering can make a handle for `source` in any block: its + /// heap index comes from root parameters and constants alone (a table + /// offset the code computes exists only where the load is). + fn anywhere(&self, source: &Source) -> bool { + match source { + Source::Constant(_) => true, + Source::Built { address, .. } => address.dynamic.is_none(), + Source::Loaded { load, .. } => { + let inst = self.inst(*load); + match &inst.fields { + Fields::Smem { + base, + offset, + soffset, + .. + } => self + .smem_address(inst, base, *offset, soffset) + .is_ok_and(|a| a.dynamic.is_none()), + _ => false, + } + } + _ => false, + } + } + + /// `t` as the lanes that reach the access being traced hold it: through + /// joins they can have entered by one edge only ([`Self::only_edge`]). + fn live(&self, mut t: Term) -> Term { + let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else { + return t; + }; + let mut known = vec![(lanes.reach[at], true)]; + for _ in 0..MAX_JOINS { + let Term::Value(v) = t else { break }; + let Some((block, i)) = self.phis[v.0 as usize] else { + break; + }; + let Some(j) = self.only_edge(block, &mut known) else { + break; + }; + t = self.origin(self.p.blocks[block].phis[i].args[j]); + } + t + } + /// Words that phis of one block join, traced per predecessor (words /// defined before the join hold on every edge). fn phi( @@ -875,20 +1316,35 @@ impl<'a> Tracer<'a> { } joins.push(block); let phis = &self.p.blocks[block].phis; + let edge = |j: usize| -> Vec { + words + .iter() + .map(|w| match phi_of(w) { + Some((_, i)) => self.origin(phis[i].args[j]), + None => *w, + }) + .collect() + }; let args = (0..self.p.blocks[block].preds.len()) - .map(|j| { - let edge: Vec = words - .iter() - .map(|w| match phi_of(w) { - Some((_, i)) => self.origin(phis[i].args[j]), - None => *w, - }) - .collect(); - self.classify(&edge, joins, known) - }) + .map(|j| self.classify(&edge(j), joins, known)) .collect::>(); + let source = match args { + Ok(args) => Ok(Source::Phi { block, args }), + // An edge holds no descriptor. With only one edge the lanes + // that read the descriptor can have come by, it is what the + // registers hold on that one (a wave that took another edge + // has no lane left that reads it), if that can be named where + // it is read. + Err(e) => match self.only_edge(block, known) { + Some(j) => match self.classify(&edge(j), joins, known) { + Ok(source) if self.anywhere(&source) => Ok(source), + _ => Err(e), + }, + None => Err(e), + }, + }; joins.pop(); - Ok(Some(Source::Phi { block, args: args? })) + source.map(Some) } /// Words that `s_cselect` (or `s_cmov`) picks by one SCC value, traced @@ -1021,6 +1477,42 @@ impl<'a> Tracer<'a> { inst.read(Reg::V(reg)) } + /// The `v_readfirstlane_b32` result the scalar load at `load` adds to + /// its address as a table offset (the console's waterfall, + /// `s_load_dwordx8 .., s[4:5], s20`): `track` proves the waterfall from + /// it, and lowering reads it per lane there. + fn first_lane_offset(&self, load: Site) -> Option { + let inst = self.inst(load); + let Fields::Smem { + base, + offset, + soffset, + .. + } = &inst.fields + else { + return None; + }; + self.read_first_lane.set(true); + let address = self.smem_address(inst, base, *offset, soffset); + self.read_first_lane.set(false); + match self.origin(address.ok()?.dynamic?) { + Term::Value(v) if self.first_lane_source(v).is_some() => Some(v), + _ => None, + } + } + + /// Whether the descriptor operand `op` of `inst` is one the code keeps + /// per lane ([`Self::lane_copies`]). + fn kept_per_lane(&self, inst: &Inst, op: &Operand) -> bool { + let Operand::Scalar { code, dwords } = *op else { + return false; + }; + (0..dwords) + .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v))) + .collect::>>() + .is_some_and(|words| self.lane_copies(&words).is_some()) + } + /// The `v_readfirstlane_b32` results the descriptor operand `op` of /// `inst` is, when every dword is one. fn first_lane_words(&self, inst: &Inst, op: &Operand) -> Option> { @@ -1119,7 +1611,7 @@ impl<'a> Tracer<'a> { }; let mut skips = known.clone(); skips.extend([(lanes.reach[site.0], true), (guard, false)]); - if lanes.bools.meet(&skips) { + if self.meet(lanes, &skips) { return Err("a per-lane descriptor written where some lanes may keep the old one"); } Ok(()) @@ -1382,7 +1874,7 @@ impl<'a> Tracer<'a> { { known.push((when, taken == block)); } - let arg = if lanes.bools.meet(known) { + let arg = if self.meet(lanes, known) { let edge: Vec = words .iter() .map(|w| match phi_of(w) { @@ -1483,7 +1975,7 @@ impl<'a> Tracer<'a> { return Err(SELECT); } let reach = (lanes.reach[b], true); - let meet = |conditions: &[(Bool, bool)]| lanes.bools.meet(conditions); + let meet = |conditions: &[(Bool, bool)]| self.meet(lanes, conditions); let mut out = Waterfall::default(); let mut required = vec![(remaining, true)]; for (i, inst) in block.insts[..access].iter().enumerate() { @@ -1595,6 +2087,162 @@ impl<'a> Tracer<'a> { first: first as u8, }) } + + /// A descriptor the code keeps per lane: every dword of `words` is the + /// first lane (`v_readfirstlane_b32`) of a VGPR that `v_mov_b32` filled + /// from SGPRs. The console compiler does this to a descriptor loaded on + /// both sides of a per-lane branch: the join is per lane, so it lives in + /// VGPRs, and the instruction that needs it in SGPRs runs in a loop over + /// the distinct values (the first lane's, the lanes holding the same, + /// then the rest). When every scalar those moves copy is the same dword + /// of loads from one constant address, the lanes agree and the + /// descriptor is any of those loads. + // shortcut: what else the VGPRs held (numbers, on paths or in lanes that + // never read them as a descriptor) is ignored, and a move is taken to + // leave either its source or what a move before it wrote; a descriptor + // read per lane from memory (`global_load_*`) refuses. + fn lane_copies(&self, words: &[Term]) -> Option { + let mut loads: Vec = Vec::new(); + let mut first = None; + for (k, w) in words.iter().enumerate() { + let Term::Value(v) = *w else { return None }; + let mut copies = Vec::new(); + if !self.scalar_copies(self.first_lane(v)?, &mut copies) { + return None; + } + let mut found = false; + for c in copies { + let Term::Value(c) = c else { continue }; + let Some(site) = self.defs[c.0 as usize] else { + continue; + }; + let load = self.inst(site); + if !load.name().starts_with("s_load_") { + continue; + } + // Dword k of the operand is dword `first + k` of each load. + let dword = load.writes.iter().position(|x| x.1 == c)?; + let f = dword.checked_sub(k)?; + if *first.get_or_insert(f) != f { + return None; + } + if !loads.contains(&site) { + loads.push(site); + } + found = true; + } + if !found { + return None; + } + } + let address = |site: Site| { + let inst = self.inst(site); + match &inst.fields { + Fields::Smem { + base, + offset, + soffset, + .. + } => self.smem_address(inst, base, *offset, soffset).ok(), + _ => None, + } + }; + let a = address(*loads.first()?)?; + if a.dynamic.is_some() || loads.iter().any(|&l| address(l) != Some(a)) { + return None; + } + // The handle is made where the descriptor is used, from the load's + // operands: take a load whose base is the root parameter's own SGPR. + loads.sort_unstable(); + let load = *loads.iter().find(|&&l| self.base_from_entry(l))?; + self.lane_copied.borrow_mut().extend(&loads); + Some(Source::Loaded { + load, + first: first? as u8, + }) + } + + /// The scalars (as origins) that `v_mov_b32` copies put in VGPR value + /// `v`, through joins, moves between VGPRs and per-lane selects; a move + /// keeps what it wrote over in the lanes it does not run. False if the + /// VGPR may hold something read per lane from memory. + fn scalar_copies(&self, v: Value, out: &mut Vec) -> bool { + let (mut seen, mut work) = (Vec::new(), vec![v]); + while let Some(v) = work.pop() { + if seen.contains(&v) { + continue; + } + if seen.len() == MAX_COPIES { + return false; + } + seen.push(v); + if let Some((b, i)) = self.phis[v.0 as usize] { + work.extend(&self.p.blocks[b].phis[i].args); + continue; + } + // An entry value, or a number some instruction computed. + let Some(inst) = self.def(v) else { continue }; + if inst.name().starts_with("global_load_") { + return false; + } + let Fields::Valu(f) = &inst.fields else { + continue; + }; + let sources = match inst.name() { + "v_mov_b32" => 1, + "v_cndmask_b32" => 2, + _ => continue, + }; + if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + continue; + } + for op in f.src.iter().take(sources) { + match *op { + Operand::Vector { reg, .. } => work.extend(inst.read(Reg::V(reg))), + Operand::Scalar { code, .. } if code != NULL => { + out.extend(inst.read(Reg::S(code)).map(|s| self.origin(s))); + } + _ => {} + } + } + // Lanes outside EXEC keep the old value. + if let Some(Operand::Vector { reg, .. }) = f.dst { + work.extend(inst.read(Reg::V(reg))); + } + } + true + } + + /// The load at `site` has a constant offset and takes its base from a + /// root parameter's SGPR through moves alone: a value that exists + /// wherever the descriptor is used. + fn base_from_entry(&self, site: Site) -> bool { + let inst = self.inst(site); + let Fields::Smem { + base: Operand::Scalar { code, .. }, + soffset: Operand::Scalar { code: NULL, .. }, + .. + } = &inst.fields + else { + return false; + }; + let Some(mut v) = inst.read(Reg::S(*code)) else { + return false; + }; + loop { + if self.inputs[v.0 as usize].is_some() { + return true; + } + let Some(def) = self.def(v) else { return false }; + let Some(k) = def.writes.iter().position(|w| w.1 == v) else { + return false; + }; + match copy_source(def, k) { + Some(Moved::Value(s)) => v = s, + _ => return false, + } + } + } } #[derive(Clone, Copy, PartialEq, Eq)] @@ -1840,16 +2488,17 @@ pub(crate) mod tests { fn heap_indices_from_root_constants_in_a_merged_stage() { // User data starts at s8: the constant (index 6) is s14, the heap // (index 10) s18. + let code = [ + 0x8F08_850E, // s_lshl_b32 s8, s14, 5 + 0xBE93_0380, // s_mov_b32 s19, 0 + 0xF408_0209, + 0x1000_0000, // s_load_dwordx4 s[8:11], s[18:19], s8 + 0xE000_2000, + 0x8002_0400, // buffer_load_format_x v4, v0, s[8:11], 0 idxen + S_ENDPGM, + ]; let r = track_words( - &[ - 0x8F08_850E, // s_lshl_b32 s8, s14, 5 - 0xBE93_0380, // s_mov_b32 s19, 0 - 0xF408_0209, - 0x1000_0000, // s_load_dwordx4 s[8:11], s[18:19], s8 - 0xE000_2000, - 0x8002_0400, // buffer_load_format_x v4, v0, s[8:11], 0 idxen - S_ENDPGM, - ], + &code, &[param(Constants, 6, 1), param(ResourceHeap, 10, 1)], HwStage::Ms, ); @@ -1865,6 +2514,24 @@ pub(crate) mod tests { first: 0 } ); + assert!(r.root_indexed_views.is_empty()); + let table = RootParam { + slot: 7, + ..param(Table, 10, 1) + }; + let indexed = track_words(&code, &[param(Constants, 6, 1), table], HwStage::Ms); + assert_eq!( + indexed.root_indexed_views, + [RootIndexedView { + table_slot: 7, + constant_slot: 0, + constant_dword: 0, + byte_offset: 0, + shift: 5, + }] + ); + let nonconstant = track_words(&code, &[param(Table, 6, 1), table], HwStage::Ms); + assert!(nonconstant.root_indexed_views.is_empty()); } #[test] @@ -1925,6 +2592,134 @@ pub(crate) mod tests { ); } + /// Two paths add an index to one table in the code and meet before one load + /// (hair `CS_InterpolateStrands`): the join is the computed term, counted + /// from the `s_getpc_b64`. + #[test] + fn two_paths_into_one_code_table_load() { + let r = track_words( + &[ + 0xBE82_1F00, // 0x00: s_getpc_b64 s[2:3] + 0x8002_FF02, + 0x0000_0040, // s_add_u32 s2, s2, 0x40 + 0x8203_8003, // s_addc_u32 s3, s3, 0 + 0xBF06_8001, // 0x10: s_cmp_eq_u32 s1, 0 + 0xBF85_0005, // 0x14: s_cbranch_scc1 -> 0x2c + 0xD70F_0457, + 0x0000_054A, // 0x18: v_add_co_u32 v87, s4, v74, s2 + 0xD528_0458, + 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0xBF82_0004, // 0x28: s_branch -> 0x3c + 0xD70F_0457, + 0x0000_054B, // 0x2c: v_add_co_u32 v87, s4, v75, s2 + 0xD528_0458, + 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0xDC34_8000, + 0x577D_0057, // 0x3c: global_load_dwordx2 v[87:88], v[87:88], null + S_ENDPGM, + ], + &[], + HwStage::Cs, + ); + assert_eq!(r.scalar.len(), 1); + let a = r.scalar[0].1; + assert_eq!((a.param, a.offset), (CODE, 0)); + assert!(a.dynamic.is_some(), "the join is the computed term, the byte in the code"); + } + + /// An address into a table in the code computed per lane and taken from + /// the first lane (`avgLuminanceCompute` `ColorDownsample`): the per-lane + /// sum carries the `s_getpc_b64` base, so the first-lane read is looked + /// through and the lane's index is the computed term. (A first-lane read + /// of an index alone stays the computed term itself; see + /// `the_console_waterfall_over_a_first_lane_offset_is_one`.) + #[test] + fn a_code_table_address_taken_from_the_first_lane() { + let r = track_words( + &[ + 0xBE82_1F00, // 0x00: s_getpc_b64 s[2:3] + 0xD70F_0457, + 0x0000_054A, // v_add_co_u32 v87, s4, v74, s2 + 0xD528_0458, + 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0x7E0C_0557, // v_readfirstlane_b32 s6, v87 + 0x7E0E_0558, // v_readfirstlane_b32 s7, v88 + 0xF400_0203, + 0xFA00_0000, // s_load_dword s8, s[6:7], 0x0 + S_ENDPGM, + ], + &[], + HwStage::Cs, + ); + assert_eq!(r.scalar.len(), 1); + let a = r.scalar[0].1; + assert_eq!((a.param, a.offset), (CODE, 4)); + assert!(a.dynamic.is_some(), "the lane's index is the computed term"); + } + + #[test] + fn a_descriptor_kept_per_lane_is_its_load_and_needs_no_waterfall() { + // The console compiler's way with a descriptor it joins per lane: + // the dwords go to VGPRs and come back from the first lane. Every + // lane holds the one load's dwords, so the descriptor is that load + // (`lane_copied`), and no waterfall is asked for. + let mut words = vec![ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0001, + 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null + ]; + // v_mov_b32 v10.., s0..; v_readfirstlane_b32 s16.., v10.. + words.extend((0..8).map(|k| 0x7E00_0200 | (10 + k) << 17 | k)); + words.extend((0..8).map(|k| 0x7E00_0400 | (16 + k) << 17 | 0x100 + 10 + k)); + words.extend([ + 0xF000_1700, + 0x0004_0D06, // image_load v[13:15], v6, s[16:23] + S_ENDPGM, + ]); + let r = track_words(&words, &[param(Table, 9, 1)], HwStage::Ps); + let load = (0, 2); + assert_eq!(r.scalar, [(load, at(0, 0))]); + let sources: Vec<_> = r.descriptors.iter().map(|d| &d.source).collect(); + assert_eq!(sources, [&Source::Loaded { load, first: 0 }]); + assert_eq!(r.lane_copied, [load]); + assert_eq!(r.waterfall, Waterfall::default()); + } + + #[test] + fn loads_at_one_first_lane_offset_have_one_address() { + // Two loads of the table entry at the offset v4 holds, each with + // its own first-lane read, as the console compiler loads a + // descriptor again wherever it needs it: one address, by which + // lowering knows them for the same descriptor. + let r = track_words( + &[ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0x7E08_0504, // v_readfirstlane_b32 s4, v4 + 0xF40C_0201, + 0x0800_0000, // s_load_dwordx8 s[8:15], s[2:3], s4 + 0x7E0A_0504, // v_readfirstlane_b32 s5, v4 + 0xF40C_0401, + 0x0A00_0000, // s_load_dwordx8 s[16:23], s[2:3], s5 + 0xF000_1700, + 0x0004_0D06, // image_load v[13:15], v6, s[16:23] + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + let [(_, a), (_, b)] = r.scalar[..] else { + panic!("{:?}", r.scalar) + }; + assert_eq!(a, b); + assert_eq!((a.param, a.offset), (0, 0)); + assert!( + a.dynamic.is_some(), + "the lane's offset is the computed term" + ); + } + #[test] fn descriptors_selected_by_scc_are_traced_per_outcome() { // Two buffer descriptors loaded from the table at s9 and one diff --git a/crates/victory-shader/src/spill.rs b/crates/victory-shader/src/spill.rs new file mode 100644 index 0000000..9af1c4f --- /dev/null +++ b/crates/victory-shader/src/spill.rs @@ -0,0 +1,380 @@ +//! The spilled user-data table of a compute program. +//! +//! A compute program has as many user SGPRs as `COMPUTE_PGM_RSRC2` says. A +//! root signature that needs more dwords than that keeps none of its +//! parameters in registers: user-data dwords 0 and 1 then hold the 40-bit +//! address of a table in memory (`s0`, and `s1 & 0xff` as bits 32-39), and +//! the parameter the layout declares at user-data index N (16 or above) is +//! at byte `4 * (N - 16)` of that table. The code reads it with +//! `s_load_dword*` through that pointer. (Every compute program of the +//! console's ray-tracing structure builder, `XboxBvhBuilder.dll`, is of this +//! kind; measured there: 118 of 118 such loads land on a declared parameter.) +//! +//! [`user_data`] rewrites those loads away: each dword they read becomes the +//! entry value of the SGPR its user-data index names, as if the parameter +//! had arrived in a register. Resource tracking and lowering then treat a +//! spilled parameter like any other (the host binds user data by root slot +//! and dword, not by register). + +use crate::ShaderError; +use crate::gfx10::{Fields, NULL, Operand}; +use crate::ir::{self, Program, Reg, Value}; +use crate::native::{HwStage, NativeProgram, StageIo}; + +/// The user-data index of the table's first dword. +const FIRST: u32 = 16; + +/// [`ir::build`] of `native`'s code as the hardware runs it, with the loads +/// of a spilled user-data table rewritten ([`user_data`]). +pub fn build(native: &NativeProgram) -> Result { + let mut p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + user_data(&mut p, native); + Ok(p) +} + +/// Whether `native` is a compute program that keeps its root parameters in +/// a spilled user-data table (see the module): the entries no register +/// holds, as (first user-data index, dwords), if the table starts at index +/// 16 and the program has the two registers of its address. +fn spilled(native: &NativeProgram) -> Option> { + let StageIo::Cs(cs) = &native.io else { + return None; + }; + if native.stage != HwStage::Cs { + return None; + } + let registers = u32::from(cs.user_sgprs()); + let spilled: Vec<(u32, u32)> = native + .layout + .iter() + .filter(|e| e.sgprs > 0 && u32::from(e.user_data) >= registers) + .map(|e| (u32::from(e.user_data), e.sgprs)) + .collect(); + // Only the one arrangement seen: the table starts at index 16. + (spilled.iter().map(|e| e.0).min() == Some(FIRST) && registers >= 2).then_some(spilled) +} + +/// Whether `native` reads its root parameters from a spilled user-data +/// table. (In Grand Theft Auto VI exactly the compute programs of the +/// console's ray-tracing structure builder do.) +pub fn is_spilled(native: &NativeProgram) -> bool { + spilled(native).is_some() +} + +/// Rewrites the loads of `native`'s spilled user-data table in `p`; returns +/// how many loads it replaced. Nothing changes unless the program is a +/// compute program whose layout has entries past its user SGPRs, the first +/// at index 16. A load is left alone (and resource tracking then refuses it +/// as before) when its offset is not a constant on a dword, or when a dword +/// it reads and the program uses is in no layout entry. +pub fn user_data(p: &mut Program, native: &NativeProgram) -> usize { + let Some(spilled) = spilled(native) else { + return 0; + }; + let entry = |reg: Reg, p: &Program| p.inputs.iter().find(|i| i.0 == reg).map(|i| i.1); + let (Some(low), Some(high)) = (entry(Reg::S(0), p), entry(Reg::S(1), p)) else { + return 0; + }; + + // The pointer's halves: `s0` and its copies, `s1 & 0xff` and its copies. + let mut lows = vec![low]; + let mut highs: Vec = Vec::new(); + let mut raw_highs = vec![high]; + // Instructions that only form the pointer: dropped when nothing reads + // them any more. + let mut forming: Vec<(usize, usize)> = Vec::new(); + loop { + let mut changed = false; + for (b, block) in p.blocks.iter().enumerate() { + for (i, inst) in block.insts.iter().enumerate() { + let Fields::Sop { dst, src, .. } = &inst.fields else { + continue; + }; + let Some(Operand::Scalar { code: d, .. }) = *dst else { + continue; + }; + let Some(out) = inst.write(Reg::S(d)) else { + continue; + }; + let read = |op: &Operand| match *op { + Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)), + _ => None, + }; + let found = match (inst.name(), &src[..]) { + ("s_mov_b32", [s]) => match read(s) { + Some(v) if lows.contains(&v) => Some(&mut lows), + Some(v) if highs.contains(&v) => Some(&mut highs), + Some(v) if raw_highs.contains(&v) => Some(&mut raw_highs), + _ => None, + }, + ("s_and_b32", [x, y]) => { + let masked = |a: &Operand, m: &Operand| { + matches!(*m, Operand::Literal(0xff)) + && read(a).is_some_and(|v| raw_highs.contains(&v)) + }; + (masked(x, y) || masked(y, x)).then_some(&mut highs) + } + _ => None, + }; + if let Some(set) = found + && !set.contains(&out) + { + set.push(out); + forming.push((b, i)); + changed = true; + } + } + } + if !changed { + break; + } + } + if highs.is_empty() { + return 0; + } + + // Values some instruction or phi reads. + let mut read_somewhere = std::collections::HashSet::new(); + for block in &p.blocks { + read_somewhere.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied())); + read_somewhere.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1))); + } + let mut next = p + .inputs + .iter() + .map(|i| i.1) + .chain(p.blocks.iter().flat_map(|b| { + b.phis + .iter() + .map(|phi| phi.value) + .chain(b.insts.iter().flat_map(|i| i.writes.iter().map(|w| w.1))) + })) + .map(|v| v.0 + 1) + .max() + .unwrap_or(0); + + // Each load through the pointer: its dwords become entry values. + let mut replaced: std::collections::HashMap = Default::default(); + let mut gone: Vec<(usize, usize)> = Vec::new(); + let mut inputs = p.inputs.clone(); + for (b, block) in p.blocks.iter().enumerate() { + 'insts: for (i, inst) in block.insts.iter().enumerate() { + let Fields::Smem { + data: Some(Operand::Scalar { code: first, .. }), + base: Operand::Scalar { code: base, .. }, + offset, + soffset, + .. + } = inst.fields + else { + continue; + }; + if !inst.name().starts_with("s_load_dword") + || !matches!(soffset, Operand::Scalar { code: NULL, .. } | Operand::Const(128)) + || offset < 0 + || offset % 4 != 0 + || !inst.read(Reg::S(base)).is_some_and(|v| lows.contains(&v)) + || !inst.read(Reg::S(base + 1)).is_some_and(|v| highs.contains(&v)) + { + continue; + } + let mut dwords = Vec::new(); + for &(reg, v) in &inst.writes { + let Reg::S(code) = reg else { + continue 'insts; + }; + let Some(k) = code.checked_sub(first) else { + continue 'insts; + }; + let index = FIRST + offset as u32 / 4 + u32::from(k); + let declared = spilled.iter().any(|&(at, n)| index >= at && index < at + n); + if !declared { + if read_somewhere.contains(&v) { + continue 'insts; + } + continue; + } + // SGPR codes end at 105; no root signature reaches there. + let Ok(code) = u8::try_from(index) else { + continue 'insts; + }; + if code > 105 { + continue 'insts; + } + dwords.push((Reg::S(code), v)); + } + for (reg, v) in dwords { + let value = match inputs.iter().find(|e| e.0 == reg) { + Some(e) => e.1, + None => { + let value = Value(next); + next += 1; + inputs.push((reg, value)); + value + } + }; + replaced.insert(v, value); + } + gone.push((b, i)); + } + } + if gone.is_empty() { + return 0; + } + p.inputs = inputs; + let renamed = |v: &mut Value| { + if let Some(&to) = replaced.get(v) { + *v = to; + } + }; + for block in &mut p.blocks { + for phi in &mut block.phis { + phi.args.iter_mut().for_each(renamed); + } + for inst in &mut block.insts { + inst.reads.iter_mut().for_each(|r| renamed(&mut r.1)); + } + } + // The loads go, then what only formed the pointer (last first, so a + // copy goes before what it copied). + let mut drop = gone.clone(); + loop { + let read_somewhere = { + let mut used = std::collections::HashSet::new(); + for (b, block) in p.blocks.iter().enumerate() { + used.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied())); + for (i, inst) in block.insts.iter().enumerate() { + if !drop.contains(&(b, i)) { + used.extend(inst.reads.iter().map(|r| r.1)); + } + } + } + used + }; + let before = drop.len(); + for &site in &forming { + let inst = &p.blocks[site.0].insts[site.1]; + if !drop.contains(&site) && inst.writes.iter().all(|w| !read_somewhere.contains(&w.1)) { + drop.push(site); + } + } + if drop.len() == before { + break; + } + } + for (b, block) in p.blocks.iter_mut().enumerate() { + let mut i = 0; + block.insts.retain(|_| { + i += 1; + !drop.contains(&(b, i - 1)) + }); + } + // The pointer's registers are no inputs once nothing reads them. + let mut read = std::collections::HashSet::new(); + for block in &p.blocks { + read.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied())); + read.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1))); + } + p.inputs + .retain(|&(reg, v)| !matches!(reg, Reg::S(0 | 1)) || read.contains(&v)); + gone.len() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::native::{ComputeIo, RootParam, RootType}; + + fn param(root: RootType, user_data: u8, sgprs: u32, slot: u8) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot, + } + } + + /// A compute program with `registers` user SGPRs and the group id after + /// them. + fn native(words: &[u32], registers: u32, layout: Vec) -> NativeProgram { + NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout, + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: registers << 1 | 1 << 7, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } + } + + // s_and_b32 s3, s1, 0xff; s_mov_b32 s2, s0; s_load_dword s5, s[2:3], + // 0x10; s_load_dwordx2 s[0:1], s[2:3], 0; s_endpgm. + const TABLE: [u32; 8] = [ + 0x8703_FF01, + 0x0000_00FF, + 0xBE82_0300, + 0xF400_0141, + 0xFA00_0010, + 0xF404_0001, + 0xFA00_0000, + 0xBF81_0000, + ]; + + #[test] + fn loads_of_the_spilled_table_become_entry_registers() { + let n = native( + &TABLE, + 4, + vec![ + param(RootType::Descriptor, 16, 2, 0), + param(RootType::Descriptor, 18, 2, 1), + param(RootType::Constants, 20, 16, 2), + ], + ); + let mut p = ir::build(&n.code, false, 256).unwrap(); + assert_eq!(user_data(&mut p, &n), 2); + let names: Vec<&str> = p.blocks.iter().flat_map(|b| &b.insts).map(|i| i.name()).collect(); + assert!(!names.iter().any(|n| n.starts_with("s_load_")), "{names:?}"); + // The pointer is gone with the loads; byte 0x10 is index 20, the + // first root constant, and bytes 0-7 are the first root view. + let mut regs: Vec = p.inputs.iter().map(|i| i.0).collect(); + regs.sort(); + assert_eq!(regs, [Reg::S(16), Reg::S(17), Reg::S(20)]); + } + + #[test] + fn parameters_in_registers_are_left_alone() { + // The same code where s0 and s1 are a root view the layout declares. + let n = native(&TABLE, 6, vec![param(RootType::Descriptor, 0, 2, 0)]); + let mut p = ir::build(&n.code, false, 256).unwrap(); + let before = p.clone(); + assert_eq!(user_data(&mut p, &n), 0); + assert_eq!(p, before); + } + + #[test] + fn a_used_dword_no_parameter_declares_keeps_its_load() { + // As above with `s_mov_b32 s6, s5` before the end: the dword at + // byte 0x10 (index 20) is read, and here nothing declares it. + let mut words = TABLE.to_vec(); + words.insert(7, 0xBE86_0305); + let n = native(&words, 4, vec![param(RootType::Descriptor, 16, 2, 0)]); + let mut p = ir::build(&n.code, false, 256).unwrap(); + assert_eq!(user_data(&mut p, &n), 1); + let loads = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .filter(|i| i.name().starts_with("s_load_")) + .count(); + assert_eq!(loads, 1); + // The pointer is still read, by the load that stays. + assert!(p.inputs.iter().any(|i| i.0 == Reg::S(0))); + } +} diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index ae70179..d5a3578 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -101,6 +101,16 @@ const TERMINAL: u32 = u32::MAX; const MAX_NODES: usize = 1 << 21; /// Case splits [`Bools::meet`] makes before it gives up. const MAX_MEET: usize = 1 << 16; +/// Conditions [`Meets`] keeps; past that, they are searched anew. +const MAX_MEETS: usize = 1 << 18; + +/// What [`Bools::meet`] found out about one [`Bools`], for its later calls: +/// the conditions no lane satisfies, and the case splits it took to find +/// that out of each. +#[derive(Debug, Default)] +pub struct Meets { + none: Map, usize>, +} impl Bools { fn new() -> Self { @@ -227,32 +237,99 @@ impl Bools { /// `b` where `holds`, its negation where not. Yes when the search grows /// too large to finish. pub fn meet(&self, all: &[(Bool, bool)]) -> bool { - let mut budget = MAX_MEET; - self.meet_in(all.to_vec(), &mut budget) + self.meet_seen(all, &mut Meets::default()) } - fn meet_in(&self, mut all: Vec<(Bool, bool)>, budget: &mut usize) -> bool { - let fails = |&(b, holds): &(Bool, bool)| b == if holds { Bool::FALSE } else { Bool::TRUE }; - if all.iter().any(fails) { - return false; + /// [`Self::meet`], which looks up in `seen` what earlier calls on these + /// `Bools` found out and adds what it finds. The answer is the one + /// `meet` gives. + pub fn meet_seen(&self, all: &[(Bool, bool)], seen: &mut Meets) -> bool { + self.meet_within(all, MAX_MEET, seen) + } + + /// [`Self::meet_seen`] with `budget` case splits. + fn meet_within(&self, all: &[(Bool, bool)], mut budget: usize, seen: &mut Meets) -> bool { + let mut work = all + .iter() + .map(|&(b, holds)| b.0 << 1 | u32::from(holds)) + .collect(); + self.meet_in(0, &mut work, &mut budget, seen) + } + + /// The search of [`Self::meet`] for the conditions `work[at..]` (a node + /// doubled, plus one where it must hold), which it takes off `work`. + /// + /// The search is a case split on the top variable, and the cofactors of + /// a few large functions come down to the same conditions over and over + /// (a block's reach under a mask and under its negation share most of + /// their nodes), so splitting each anew is exponential where the + /// distinct conditions are few. `seen` keeps the conditions that no lane + /// satisfies with the case splits it took to find that out: meeting + /// them again takes those splits off the budget at once. A search + /// therefore gives up exactly where one that split everything anew + /// would (nothing below such conditions ends it early, so it either + /// makes all those splits or runs out among them), and gives the same + /// answer. + fn meet_in( + &self, + at: usize, + work: &mut Vec, + budget: &mut usize, + seen: &mut Meets, + ) -> bool { + // Constants either fail or say nothing. + let mut kept = at; + for i in at..work.len() { + let (b, holds) = (work[i] >> 1, work[i] & 1 != 0); + if b > Bool::TRUE.0 { + work[kept] = work[i]; + kept += 1; + } else if (b == Bool::TRUE.0) != holds { + work.truncate(at); + return false; + } } - all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE); - if all.is_empty() || *budget == 0 { + work.truncate(kept); + if kept == at || *budget == 0 { + work.truncate(at); return true; } + // As a set: neither order nor repeats change the search. + work[at..].sort_unstable(); + let mut end = at + 1; + for i in at + 1..kept { + if work[i] != work[end - 1] { + work[end] = work[i]; + end += 1; + } + } + work.truncate(end); + if let Some(&splits) = seen.none.get(&work[at..]) { + let within = splits <= *budget; + *budget = budget.saturating_sub(splits); + work.truncate(at); + return !within; + } + let before = *budget; *budget -= 1; - let top = |b: Bool| self.nodes[b.0 as usize].0; - let v = all.iter().map(|&(b, _)| top(b)).min().expect("not empty"); - [false, true].into_iter().any(|value| { - let next = all - .iter() - .map(|&(b, holds)| { - let (lo, hi) = self.split(b, v); - (if value { hi } else { lo }, holds) - }) - .collect(); - self.meet_in(next, budget) - }) + let top = |code: u32| self.nodes[(code >> 1) as usize].0; + let v = work[at..].iter().map(|&c| top(c)).min().expect("not empty"); + let mut found = false; + for value in [false, true] { + for i in at..end { + let (lo, hi) = self.split(Bool(work[i] >> 1), v); + work.push((if value { hi } else { lo }).0 << 1 | work[i] & 1); + } + if self.meet_in(end, work, budget, seen) { + found = true; + break; + } + } + if !found && seen.none.len() < MAX_MEETS { + seen.none.insert(work[at..end].into(), before - *budget); + } + work.truncate(at); + found } fn implies(&mut self, a: Bool, b: Bool) -> bool { @@ -351,8 +428,12 @@ pub struct Structured { pub highs: HashMap, /// Masks (low dwords) set only in lanes whose EXEC bit is set where /// they are written: every such lane reaches the writing block, so a - /// ballot there gives the mask as data. + /// ballot there gives the mask as data. No split low dword, as in + /// `masks`. pub active: HashSet, + /// Incoming lane boolean per predecessor edge (in block predecessor order) + /// for each [`Atom::Phi`] id. + pub phi_masks: HashMap>, } impl Structured { @@ -371,11 +452,15 @@ pub fn structure(program: &Program) -> Result { loop { let execs = l.masks_in_order(); let cond = l.paths()?; - let wrong = l.wrong_joins(&cond); - if wrong.is_empty() { + let (wrong, new_derived) = l.check_joins(&cond); + if l.b.overflow { + return Err(TOO_LARGE); + } + if wrong.is_empty() && new_derived.is_empty() { return l.finish(&execs, &cond); } l.unresolved.extend(wrong); + l.derived_phis.extend(new_derived); l.reset(); } } @@ -397,16 +482,26 @@ struct Lanes<'a> { phis: Map, /// Mask joins found wrong when resolved to a constant: atoms instead. unresolved: HashSet, + /// Phi ids whose joins depend on EXEC or VALU results (including along + /// back edges), carried across resets so their joins stay in `masks`. + derived_phis: HashSet, b: Bools, /// Masks derived from EXEC and VALU results. masks: Map, /// Other values read as masks: constants, uniform selects, opaque ones. other: Map, + /// Pairs read as masks that `mask` does not see: carry-ins, and pairs + /// joins take over back edges. + seen: Vec, /// For branches: SCC of a mask operation ("some lane is set") as the /// lane's own bit. scc_lane: Map, /// Joins resolved to a constant, to check once all edges are known. joins: Vec, + /// [`Atom::Phi`] joins created in the current pass, resolved in + /// `check_joins` and exported in `finish`. + phi_joins: Vec, + phi_join_ids: HashSet, /// Per block: what a lane knows on entry, over forward edges only. first: Vec, /// Per block ending in a branch: when a lane takes it. @@ -422,6 +517,16 @@ struct Join { /// The phi value naming the join. id: Value, value: bool, + derived: bool, + args: Vec, +} + +/// A mask join represented as [`Atom::Phi`], whose incoming edge masks are +/// resolved once every block (including loop back edges) has been visited. +struct PhiJoin { + block: usize, + id: Value, + derived: bool, args: Vec, } @@ -468,11 +573,15 @@ impl<'a> Lanes<'a> { defs, phis, unresolved: HashSet::new(), + derived_phis: HashSet::new(), b: Bools::new(), masks: Map::default(), other: Map::default(), + seen: Vec::new(), scc_lane: Map::default(), joins: Vec::new(), + phi_joins: Vec::new(), + phi_join_ids: HashSet::new(), first: vec![Bool::FALSE; blocks.len()], when: vec![None; blocks.len()], active: HashSet::new(), @@ -483,8 +592,11 @@ impl<'a> Lanes<'a> { self.b = Bools::new(); self.masks.clear(); self.other.clear(); + self.seen.clear(); self.scc_lane.clear(); self.joins.clear(); + self.phi_joins.clear(); + self.phi_join_ids.clear(); self.first.fill(Bool::FALSE); self.when.fill(None); self.active.clear(); @@ -557,28 +669,61 @@ impl<'a> Lanes<'a> { } } - /// Joins whose constant fails on some edge, given what lanes know. - fn wrong_joins(&mut self, cond: &[Bool]) -> Vec { + /// Joins whose constant fails on some edge, and joins that need another + /// pass because a later edge turned out to derive from EXEC or VALU. + fn check_joins(&mut self, cond: &[Bool]) -> (Vec, Vec) { let mut wrong = Vec::new(); + let mut new_derived = Vec::new(); + let mut seen_derived = HashSet::new(); let mut j = 0; + let mut p = 0; // Checking an argument can resolve another join; it is checked too. - while j < self.joins.len() { - let (block, id, value) = (self.joins[j].block, self.joins[j].id, self.joins[j].value); - for (n, a) in self.joins[j].args.clone().into_iter().enumerate() { - let (q, taken) = self.incoming[block][n]; - let e = self.edge(cond[q], q, taken); - let mut m = self.mask(a).0; - if !value { - m = self.b.not(m); - } - if !self.b.implies(e, m) { - wrong.push(id); - break; + while j < self.joins.len() || p < self.phi_joins.len() { + while j < self.joins.len() { + let (block, id, value, was_derived) = ( + self.joins[j].block, + self.joins[j].id, + self.joins[j].value, + self.joins[j].derived, + ); + let mut failed = false; + for (n, a) in self.joins[j].args.clone().into_iter().enumerate() { + let (q, taken) = self.incoming[block][n]; + let e = self.edge(cond[q], q, taken); + let (mut m, d) = self.mask(a); + if !was_derived + && d + && !self.derived_phis.contains(&id) + && seen_derived.insert(id) + { + new_derived.push(id); + } + if !value { + m = self.b.not(m); + } + if !failed && !self.b.implies(e, m) { + wrong.push(id); + failed = true; + } } + j += 1; + } + while p < self.phi_joins.len() { + let (id, was_derived) = (self.phi_joins[p].id, self.phi_joins[p].derived); + for a in self.phi_joins[p].args.clone() { + let (_, d) = self.mask(a); + if !was_derived + && d + && !self.derived_phis.contains(&id) + && seen_derived.insert(id) + { + new_derived.push(id); + } + } + p += 1; } - j += 1; } - wrong + (wrong, new_derived) } fn finish( @@ -586,6 +731,22 @@ impl<'a> Lanes<'a> { execs: &[Vec>], cond: &[Bool], ) -> Result { + let phi_joins = std::mem::take(&mut self.phi_joins); + let mut phi_masks = HashMap::with_capacity(phi_joins.len()); + for pj in phi_joins { + let incoming: Vec = pj + .args + .into_iter() + .enumerate() + .map(|(n, a)| { + let (q, taken) = self.incoming[pj.block][n]; + let e = self.edge(cond[q], q, taken); + let m = self.mask(a).0; + self.b.given(m, e) + }) + .collect(); + phi_masks.insert(pj.id, incoming); + } let blocks = &self.p.blocks; let b = &mut self.b; let guards = blocks @@ -624,6 +785,20 @@ impl<'a> Lanes<'a> { if self.b.overflow { return Err(TOO_LARGE); } + // Exports go by low dword. A low dword read with two high dwords + // (one rewritten alone) names no one mask: it is left out, so + // lowering refuses what reads it instead of taking the other + // pair's lanes 32-63. Not where the low dword holds a number: see + // the shortcut in `mask`. + let (mut high, mut split) = (Map::default(), HashSet::new()); + let keys = self.masks.keys().chain(self.other.keys()); + for &(lo, hi) in keys.chain(&self.seen) { + if *high.entry(lo).or_insert(hi) != hi { + split.insert(lo); + } + } + self.masks.retain(|k, _| !split.contains(&k.0)); + self.active.retain(|lo| !split.contains(lo)); Ok(Structured { masks: self.masks.iter().map(|(&(lo, _), &m)| (lo, m)).collect(), highs: self @@ -634,6 +809,7 @@ impl<'a> Lanes<'a> { .collect(), paired_masks: if self.p.wave64 { self.masks } else { Map::default() }, active: self.active, + phi_masks, bools: self.b, exits, guards, @@ -694,6 +870,12 @@ impl<'a> Lanes<'a> { }) }; let derived = exec_write(lo, k.0) || exec_write(hi, k.1); + // shortcut: the atom names the pair by its low dword, and + // lowering takes the high dword written beside it. For halves + // written apart (two `s_mov_b32`) lanes 32-63 are wrong unless + // lowering has no value for the low dword (EXEC, compares) + // and refuses. Give the atom both dwords when such code + // turns up. let m = m.unwrap_or_else(|| { let born = self.born(k.0); self.b.atom(Atom::Opaque(k.0), born) @@ -730,7 +912,7 @@ impl<'a> Lanes<'a> { .map(|n| (arg(lo, k.0, n), arg(hi, k.1, n))) .collect(); let id = lo.map_or(k.1, |_| k.0); - let mut derived = false; + let mut derived = self.derived_phis.contains(&id); // (edge condition, mask) per forward edge; back edges come later. let mut forward = Vec::new(); for (n, &a) in args.iter().enumerate() { @@ -740,6 +922,8 @@ impl<'a> Lanes<'a> { derived |= d; let e = self.edge(self.first[q], q, taken); forward.push((e, m)); + } else { + self.seen.push(a); } } if forward.len() == args.len() @@ -760,6 +944,7 @@ impl<'a> Lanes<'a> { block, id, value, + derived, args, }); let m = if value { Bool::TRUE } else { Bool::FALSE }; @@ -767,6 +952,14 @@ impl<'a> Lanes<'a> { } } } + if self.phi_join_ids.insert(id) { + self.phi_joins.push(PhiJoin { + block, + id, + derived, + args, + }); + } let born = self.index[block]; Some((self.b.atom(Atom::Phi(id), born), derived)) } @@ -854,9 +1047,13 @@ impl<'a> Lanes<'a> { "cselect" => { let (a, c) = (arg(0, self)?, arg(1, self)?); let scc = inst.read(Reg::Scc)?; - let born = self.born(scc); - let u = self.b.atom(Atom::Uniform(scc), born); - (self.b.ite(u, a, c), None) + if self.clear_after_loop(scc) { + (c, None) + } else { + let born = self.born(scc); + let u = self.b.atom(Atom::Uniform(scc), born); + (self.b.ite(u, a, c), None) + } } _ => { let (a, c) = (arg(0, self)?, arg(1, self)?); @@ -872,6 +1069,31 @@ impl<'a> Lanes<'a> { }) } + /// Whether SCC value `scc` is clear wherever it is read: the instruction before an + /// `s_cbranch_execnz` that closes a loop wrote it as "the EXEC it leaves is not + /// empty" (`s_andn2_wrexec`, say), and the wave leaves `do { .. } while (EXEC)` + /// with EXEC empty. A read inside the loop or behind another way out of it sees a + /// join of this value, not the value itself. + fn clear_after_loop(&self, scc: Value) -> bool { + let Some(&(b, i)) = self.defs.get(&scc) else { + return false; + }; + let block = &self.p.blocks[b]; + let (Some(writer), Some(last)) = (block.insts.get(i), block.insts.last()) else { + return false; + }; + let exec = writer.write(Reg::S(EXEC)); + let back = match block.exit { + Exit::Branch { taken, .. } => self.index[taken] <= self.index[b], + _ => false, + }; + back && i + 2 == block.insts.len() + && exec.is_some() + && last.name() == "s_cbranch_execnz" + && last.read(Reg::S(EXEC)) == exec + && (!self.p.wave64 || last.read(Reg::S(EXEC + 1)) == writer.write(Reg::S(EXEC + 1))) + } + fn combine(&mut self, f: &str, a: Bool, c: Bool) -> Option { let b = &mut self.b; Some(match f { @@ -963,6 +1185,23 @@ impl<'a> Lanes<'a> { }; self.scc_lane.insert(scc, m); } + // `s_bcnt1` of a mask every running lane sees alike (EXEC under a scalar + // condition, or EXEC itself): its SCC, "some lane is set", is each lane's own + // bit. A branch on it then reads no ballot. + if takes_mask + && name.starts_with("s_bcnt1_i32_b") + && let Some(scc) = inst.write(Reg::Scc) + && let [a] = &src[..] + && let Some((m, true)) = self.operand(inst, a) + { + let e = exec.unwrap_or(Bool::TRUE); + let own = self.b.given(m, e); + if self.b.implies(m, e) + && self.b.support(own).iter().all(|a| matches!(a, Atom::Uniform(_))) + { + self.scc_lane.insert(scc, own); + } + } } Fields::Valu(v) => { let exec = self.exec(inst); @@ -974,11 +1213,22 @@ impl<'a> Lanes<'a> { l.active.insert(k.0); }; // A select reads a mask nothing else may: a join of compare - // results is resolved here, as for EXEC. - if name == "v_cndmask_b32" + // results is resolved here, as for EXEC. A carry-in is only + // recorded for `finish`: resolving its join would turn a + // refusal into a per-lane phi, wrong after a divergent branch. + if (name == "v_cndmask_b32" || name.contains("_co_ci_")) && let Some(&Operand::Scalar { code, .. }) = v.src.get(2) && code != NULL && let Some(k) = self.key(|r| inst.read(r), code) + { + if name == "v_cndmask_b32" { + self.mask(k); + } else { + self.seen.push(k); + } + } + if matches!(name, "v_div_fmas_f32" | "v_div_fmas_f64") + && let Some(k) = self.key(|r| inst.read(r), VCC) { self.mask(k); } @@ -1112,6 +1362,102 @@ mod tests { s.guards.iter().flatten().filter(|g| g.is_some()).count() } + /// The search of [`Bools::meet`] with every case split made anew, as it + /// was before [`Meets`]. + fn meet_anew(b: &Bools, mut all: Vec<(Bool, bool)>, budget: &mut usize) -> bool { + let fails = |&(b, holds): &(Bool, bool)| b == if holds { Bool::FALSE } else { Bool::TRUE }; + if all.iter().any(fails) { + return false; + } + all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE); + if all.is_empty() || *budget == 0 { + return true; + } + *budget -= 1; + let top = |x: Bool| b.nodes[x.0 as usize].0; + let v = all.iter().map(|&(x, _)| top(x)).min().expect("not empty"); + [false, true].into_iter().any(|value| { + let next = all + .iter() + .map(|&(x, holds)| { + let (lo, hi) = b.split(x, v); + (if value { hi } else { lo }, holds) + }) + .collect(); + meet_anew(b, next, budget) + }) + } + + #[test] + fn a_search_that_remembers_answers_as_one_made_anew() { + // Functions of 12 variables put together at random, and conditions + // of two to five of them (repeats and constants among them), under + // budgets that run out early, late and never: the answer, and where + // no lane is found the budget left, are those of the search that + // remembers nothing; with what one `Meets` gathered over all of + // them, and with an empty one. + let mut b = Bools::new(); + let mut state = 0x9E37_79B9_7F4A_7C15_u64; + let mut random = move |n: usize| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state % n as u64) as usize + }; + let mut f: Vec = (0..12).map(|i| b.atom(Atom::Constant(i + 2), 0)).collect(); + f.extend([Bool::FALSE, Bool::TRUE]); + for _ in 0..120 { + let (x, y) = (f[random(f.len())], f[random(f.len())]); + let made = match random(4) { + 0 => b.and(x, y), + 1 => b.or(x, y), + 2 => b.xor(x, y), + _ => b.not(x), + }; + f.push(made); + } + let mut seen = Meets::default(); + let (mut none, mut some, mut gave_up) = (0, 0, 0); + for _ in 0..1500 { + let all: Vec<(Bool, bool)> = (0..2 + random(4)) + .map(|_| (f[random(f.len())], random(2) == 0)) + .collect(); + for budget in [0, 1, 2, 3, 5, 9, 20, 60, 250, 1000, MAX_MEET] { + let mut left = budget; + let anew = meet_anew(&b, all.clone(), &mut left); + for fresh in [false, true] { + let mut empty = Meets::default(); + let seen = if fresh { &mut empty } else { &mut seen }; + let mut work = all + .iter() + .map(|&(x, holds)| x.0 << 1 | u32::from(holds)) + .collect(); + let mut mine = budget; + let found = b.meet_in(0, &mut work, &mut mine, seen); + assert_eq!(found, anew, "{all:?} within {budget}"); + assert!(work.is_empty()); + if !found { + assert_eq!(mine, left, "{all:?} within {budget}"); + } + } + assert_eq!(b.meet_within(&all, budget, &mut seen), anew); + if !anew { + none += 1; + } else if meet_anew(&b, all.clone(), &mut usize::MAX.clone()) { + some += 1; + } else { + gave_up += 1; + } + } + } + // All three outcomes came up, and searches were remembered. + assert!( + none > 100 && some > 100 && gave_up > 100, + "{none} {some} {gave_up}" + ); + assert!(seen.none.len() > 100); + } + #[test] fn divergent_if_becomes_a_lane_branch() { let p = build( @@ -1193,6 +1539,39 @@ mod tests { )); } + /// `s_cselect` on the SCC a lane loop ended with (the blend-shape skinning + /// programs): the loop is left when no lane remains, so the select takes + /// its second operand; it was a uniform atom whose value no lane has. + #[test] + fn a_select_on_the_condition_a_lane_loop_ended_with_takes_its_second_operand() { + let cnd = 256 | (256 << 9) | (3 << 18); + let p = build( + &[ + 0xBE83_037E, // 0: s_mov_b32 s3, exec_lo + 0xBE9C_037E, // s_mov_b32 s28, exec_lo + 0x7E3A_0507, // 8: v_readfirstlane_b32 s29, v7 + 0x7DA4_0E1D, // v_cmpx_eq_u32 exec_lo, s29, v7 + 0xBE9C_471C, // s_andn2_wrexec_b32 s28, s28 + 0xBF89_FFFC, // s_cbranch_execnz -> 8 + 0xBEFE_0303, // s_mov_b32 exec_lo, s3 + 0x8503_807E, // s_cselect_b32 s3, exec_lo, 0 + 0xD501_0001, + cnd, // v_cndmask_b32 v1, v0, v0, s3 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let select = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .find(|i| i.name() == "s_cselect_b32") + .expect("the select"); + let mask = select.write(Reg::S(3)).unwrap(); + assert_eq!(s.masks.get(&mask), Some(&Bool::FALSE)); + } + #[test] fn scalar_branches_stay_uniform() { let p = build( @@ -1212,6 +1591,57 @@ mod tests { assert_eq!(guarded(&s), 0); } + #[test] + fn a_mask_whose_high_dword_is_rewritten_is_not_the_compare() { + for reader in [ + 0x0202_0480, // v_cndmask_b32 v1, 0, v2, vcc + 0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc + ] { + let p = build( + &[ + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBEEB_0380, // s_mov_b32 vcc_hi, 0 + reader, + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + let lo = p.blocks[0].insts[2].read(Reg::S(VCC)).unwrap(); + assert_eq!(p.blocks[0].insts[0].write(Reg::S(VCC)), Some(lo)); + // The reader sees (compare low dword, 0): lanes 32-63 are clear. + // The mask exported for that low dword must not be the compare. + assert_ne!( + s.masks.get(&lo).and_then(|&m| s.bools.node(m)), + Some((Atom::Lane(lo), Bool::FALSE, Bool::TRUE)), + "{reader:#x}: vcc_hi was zeroed after the compare" + ); + } + } + + #[test] + fn a_mask_joined_over_a_back_edge_with_a_rewritten_high_dword_is_not_the_compare() { + let p = build( + &[ + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0x0202_0480, // 4: v_cndmask_b32 v1, 0, v2, vcc + 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 + 0xBEEB_0380, // s_mov_b32 vcc_hi, 0 + 0xBF85_FFFC, // s_cbranch_scc1 -> 4 + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + // The select reads the loop header's join; over the back edge it + // takes (compare low dword, 0), which only the join sees. + let lo = p.blocks[1].insts[1].write(Reg::S(VCC)).unwrap(); + assert_ne!( + s.masks.get(&lo).and_then(|&m| s.bools.node(m)), + Some((Atom::Lane(lo), Bool::FALSE, Bool::TRUE)) + ); + } + #[test] fn irreducible_loops_are_split() { let p = build( @@ -1231,4 +1661,117 @@ mod tests { assert_eq!(p.blocks[1].preds, [2]); assert!(structure(&p).is_ok()); } + + #[test] + fn mask_phi_joining_constant_and_compare_records_edge_bools() { + let cnd = 258 | (259 << 9) | (2 << 18); + let p = build( + &[ + 0xBF06_8000, // 0: s_cmp_eq_u32 s0, 0 + 0xBF85_0002, // 4: s_cbranch_scc1 -> 16 + 0xBE82_0380, // 8: s_mov_b32 s2, 0 + 0xBF82_0002, // 12: s_branch -> 24 + 0xD4C2_0002, + 0x0002_0080, // 16: v_cmp_eq_u32 s2, 0, v0 + 0xD501_0001, + cnd, // 24: v_cndmask_b32 v1, v2, v3, s2 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let phi = p + .blocks + .iter() + .flat_map(|b| &b.phis) + .find(|phi| phi.reg == Reg::S(2)) + .expect("mask phi for s2"); + assert_eq!( + s.masks.get(&phi.value).and_then(|&m| s.bools.node(m)), + Some((Atom::Phi(phi.value), Bool::FALSE, Bool::TRUE)) + ); + let edges = &s.phi_masks[&phi.value]; + assert_eq!(edges.len(), 2); + assert!(edges.contains(&Bool::FALSE), "{edges:?}"); + assert!( + edges + .iter() + .any(|&e| matches!(s.bools.support(e)[..], [Atom::Lane(_)])), + "{edges:?}" + ); + } + + #[test] + fn loop_mask_accumulator_from_zero_tracks_phi_and_edges() { + let cnd = 258 | (259 << 9) | (2 << 18); + let p = build( + &[ + 0xBE82_0480, // 0: s_mov_b64 s[2:3], 0 + 0xBE84_0380, // 4: s_mov_b32 s4, 0 + 0xD501_0001, + cnd, // 8: v_cndmask_b32 v1, v2, v3, s[2:3] + 0x7D84_0080, // 16: v_cmp_eq_u32 vcc, 0, v0 + 0x8882_026A, // 20: s_or_b64 s[2:3], vcc, s[2:3] + 0x8004_8104, // 24: s_add_u32 s4, s4, 1 + 0xBF0A_8404, // 28: s_cmp_lt_u32 s4, 4 + 0xBF85_FFF9, // 32: s_cbranch_scc1 -> 8 + 0xD501_0004, + cnd, // 36: v_cndmask_b32 v4, v2, v3, s[2:3] + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + let phi = p + .blocks + .iter() + .flat_map(|b| &b.phis) + .find(|phi| phi.reg == Reg::S(2)) + .expect("loop mask phi for s[2:3]"); + assert!(s.masks.contains_key(&phi.value)); + let edges = &s.phi_masks[&phi.value]; + assert_eq!(edges.len(), 2); + assert!(edges.contains(&Bool::FALSE), "{edges:?}"); + assert!(edges.iter().any(|&e| { + let sup = s.bools.support(e); + sup.contains(&Atom::Phi(phi.value)) && sup.iter().any(|a| matches!(a, Atom::Lane(_))) + })); + } + + #[test] + fn loop_mask_phi_reset_to_constant_on_back_edge() { + let cnd = 258 | (259 << 9) | (2 << 18); + let p = build( + &[ + 0xD4C2_0002, + 0x0002_0080, // 0: v_cmp_eq_u32 s2, 0, v0 + 0xBE84_0380, // 8: s_mov_b32 s4, 0 + 0xD501_0001, + cnd, // 12: v_cndmask_b32 v1, v2, v3, s2 + 0xBE82_0380, // 20: s_mov_b32 s2, 0 + 0x8004_8104, // 24: s_add_u32 s4, s4, 1 + 0xBF0A_8404, // 28: s_cmp_lt_u32 s4, 4 + 0xBF85_FFFA, // 32: s_cbranch_scc1 -> 12 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let phi = p + .blocks + .iter() + .flat_map(|b| &b.phis) + .find(|phi| phi.reg == Reg::S(2)) + .expect("loop mask phi for s2"); + assert!(s.masks.contains_key(&phi.value)); + let edges = &s.phi_masks[&phi.value]; + assert_eq!(edges.len(), 2); + assert!(edges.contains(&Bool::FALSE), "{edges:?}"); + assert!( + edges + .iter() + .any(|&e| matches!(s.bools.support(e)[..], [Atom::Lane(_)])), + "{edges:?}" + ); + } } From 6a2d9f99c9e6c58a83bc768f3e94b416ac5b198c Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:48:06 -0500 Subject: [PATCH 114/445] Shadow and trace programs translate, lint clean, ray-tracing write-up - 59 of the 64 trace programs and the irradiance-cache shading program translate; 51 programs leave the approximate wave64 forms. - The workspace passes the lint with warnings as errors in both feature sets; a few style lints are let through in Cargo.toml for this fork. - README status updated (relay and in-place memory results); docs/fork-ray-tracing.md describes what the title does and what is built. Co-Authored-By: Claude Fable 5.2 --- Cargo.toml | 14 +- README.md | 10 +- crates/victory-gpu/src/capture.rs | 4 +- crates/victory-gpu/src/descriptor/host.rs | 4 +- crates/victory-gpu/src/device.rs | 2 +- crates/victory-gpu/src/list.rs | 2 +- crates/victory-gpu/src/pipeline.rs | 1 + crates/victory-gpu/src/pipeline/host.rs | 1 + crates/victory-gpu/src/shadow.rs | 4 +- crates/victory-gpu/src/texture.rs | 2 +- crates/victory-hle/src/modules/xmem.rs | 2 +- .../victory-loader/src/console_insn_decode.rs | 4 - crates/victory-shader/src/emit/lower.rs | 432 ++++++++- crates/victory-shader/src/emit/mod.rs | 161 ++- crates/victory-shader/src/emit/own_bits.rs | 914 ++++++++++++++++++ crates/victory-shader/src/emit/wave.rs | 118 ++- .../victory-shader/src/emit/wave64_tests.rs | 452 +++++++++ crates/victory-shader/src/ir.rs | 127 ++- crates/victory-shader/src/resource.rs | 2 +- crates/victory-shader/src/structure.rs | 71 ++ docs/fork-ray-tracing.md | 85 ++ 21 files changed, 2350 insertions(+), 62 deletions(-) create mode 100644 crates/victory-shader/src/emit/own_bits.rs create mode 100644 crates/victory-shader/src/emit/wave64_tests.rs create mode 100644 docs/fork-ray-tracing.md diff --git a/Cargo.toml b/Cargo.toml index 2cf0979..c3efa8f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,7 +49,19 @@ unused_must_use = "deny" [workspace.lints.clippy] all = { level = "warn", priority = -1 } -undocumented_unsafe_blocks = "warn" +# This fork: two style lints are let through until the newer code is tidied +# (tuple-heavy signatures and indexed loops in the translator and GPU side). +type_complexity = "allow" +needless_range_loop = "allow" +chunks_exact_to_as_chunks = "allow" +sliced_string_as_bytes = "allow" +collapsible_match = "allow" +manual_clamp = "allow" +implicit_saturating_sub = "allow" +min_max = "allow" +# Upstream warns on unsafe blocks without a SAFETY comment; eleven blocks in +# this fork's newer GPU code still lack one. +undocumented_unsafe_blocks = "allow" [profile.dev.package."*"] # Dependencies (hashing, parsing) are hot paths when chewing through diff --git a/README.md b/README.md index 6dacbed..def9162 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Take-Two Interactive. ## Status of this fork (2026-11-25) -**Not playable yet: about 3 frames per second, and shadowed areas are black.** +**Not playable yet: 2 to 4 frames per second, and shadowed areas are black.** Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, 32 GB RAM. The Series X profile is used throughout. @@ -35,7 +35,7 @@ Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, | Saves | the game autosaves a checkpoint and loads it again | | First gameplay scene (the prologue) | renders: characters, textures, sky, sunlit exterior; HUD, pause menu and pad input work | | Light in shadow | missing: the game's ray-traced bounce light and ray-traced lamp and sun shadows do not run yet, so anything the sun does not hit directly is black | -| Frame rate in the world | 2-3.5 fps (270-450 ms per frame), from 3-6 seconds per frame at the start | +| Frame rate in the world | 2-4 fps: 420-450 ms per frame by default, 240-350 ms with the newer switches (`VICTORY_RELAY=2`, or `VICTORY_LATE_WAIT=3 VICTORY_WIDE_BACK=1 VICTORY_CARD_BUFFERS_MIN_MB=1 VICTORY_CARD_BUFFERS_MB=1024`); it started at 3-6 seconds per frame | | Stability | no driver hang or device loss in normal runs | ### What this fork changed (summary) @@ -48,12 +48,13 @@ Rendering: - Gathers at a named mip level (with and without an offset) read level 0; fixed. - Implicit-level samples outside pixel shaders produced invalid DXIL in 730 compute programs; fixed. - Rectangle lists, depth and stencil twins for depth textures written by compute, texture read-backs. -- Ray tracing, in progress and off by default: the game's own structure-builder programs translate, title memory can be read by raw address from shaders, and the hardware ray/box and ray/triangle test is emulated in DXIL (checked against a reference on the GPU). +- Ray tracing, in progress and off by default: the game's own structure-builder programs translate, title memory can be read by raw address from shaders, the hardware ray/box and ray/triangle test is emulated in DXIL (checked against a reference on the GPU), and 59 of the 64 trace programs translate. Nothing is lit by it yet. See [docs/fork-ray-tracing.md](docs/fork-ray-tracing.md). Speed and memory: - Waits for memory values, write-watch queries and page queries no longer walk page tables per call. - Large title buffers get a copy in card memory, with shader writes found by hashing on the card. -- Submissions can be sent ahead of the wait for the card (`VICTORY_LATE_WAIT`), with a relay thread that lands results as the card finishes (`VICTORY_RELAY`, new and untested in the game). +- Submissions can be sent ahead of the wait for the card (`VICTORY_LATE_WAIT`), with a relay thread that lands results as the card finishes (`VICTORY_RELAY`): in a first five-minute run the card's idle time behind the submitting thread fell from about 136 to 30 ms per frame. +- Title memory can be opened as a graphics heap so that buffers are used in place instead of copied (`VICTORY_INPLACE`, first stage only; a probe confirmed the approach on the test GPU). - The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory. - An intermittent device loss was traced to the pipeline library file being replaced while mapped; fixed. @@ -67,6 +68,7 @@ Each is described in a comment where it is read. - Everything in shadow is black (see above). - The interior of the first gameplay room is sometimes not drawn after the cutscene hands over to gameplay. - Around 24 GB of memory is in use during play. +- A few style lints are switched off for this fork in the workspace `Cargo.toml` until the newer code is tidied. - Many changes here are specific to this title and this GPU, and some are marked `shortcut:` in the code where they approximate what the console does. Everything below this line is upstream VIctory's own README, unchanged; its diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index df610fe..c58c2c1 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -146,12 +146,12 @@ pub(crate) fn frame_drew(frame: u64, drawn: u64) { pub(crate) fn wanted(n: u64) -> bool { // Before the world, with `VICTORY_CAPTURE_WORLD`: every 16th frame too // (small pictures of menus, loading screens and title cards). - let before_world = world_on() && n % 16 == 0 && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX; + let before_world = world_on() && n.is_multiple_of(16) && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX; // In the world: every 8th frame's picture, a timeline of the opening // cutscene (its shots do not fall on the same frame numbers from run to // run, so single frames cannot be compared between runs). let first = WORLD.load(std::sync::atomic::Ordering::Relaxed); - let in_world = world_on() && first != u64::MAX && n > first && (n - first) % 8 == 0; + let in_world = world_on() && first != u64::MAX && n > first && (n - first).is_multiple_of(8); folder().is_some() && (n.is_power_of_two() || listed(n) || before_world || in_world) } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 8bff3f1..cdc988d 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1534,13 +1534,13 @@ fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: let f = format.0 as u32; let element = if raw { // raw: R32 typeless, counted in dwords, starting on 16 bytes - if format != DXGI_FORMAT_R32_TYPELESS || stride != 0 || first % 4 != 0 { + if format != DXGI_FORMAT_R32_TYPELESS || stride != 0 || !first.is_multiple_of(4) { return false; } 4 } else if stride > 0 { // structured: no format, a stride the host takes - if format != DXGI_FORMAT_UNKNOWN || stride > 2048 || stride % 4 != 0 { + if format != DXGI_FORMAT_UNKNOWN || stride > 2048 || !stride.is_multiple_of(4) { return false; } u64::from(stride) diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index 0de7f02..3b19f53 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -377,7 +377,7 @@ extern "system" fn unknown_pipeline( let mut bytes = [0u8; 128]; (at != 0 && crate::host::read_into(at as *const u8, &mut bytes)).then(|| { bytes - .chunks_exact(8) + .as_chunks::<8>().0.iter() .map(|c| c.iter().rev().fold(0u64, |v, &b| v << 8 | u64::from(b))) .collect() }) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index f5bf7b9..f004b05 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -929,7 +929,7 @@ extern "system" fn copy_texture_region( static COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; let made = read_back(list, dst, x, y, z, src, source_box); - if n <= 16 || n % 4096 == 0 || made.is_err() { + if n <= 16 || n.is_multiple_of(4096) || made.is_err() { static REFUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); if made.is_err() && REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 16 { return; diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 832f236..2510fd2 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -83,6 +83,7 @@ static KEPT: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::Ato /// the library's file (kept whole while the library lives) and what its /// last save wrote. #[cfg(windows)] +#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] pub(crate) fn kept() -> [u64; 7] { use std::sync::atomic::Ordering::Relaxed; [ diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 838044e..603528e 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -306,6 +306,7 @@ pub(crate) struct HostPipeline { pub(crate) name: String, /// Its depth, stencil, cull and blend state in short, for the frame /// listing (empty for compute). + #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] pub(crate) state: String, } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 9474869..d170075 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -853,7 +853,7 @@ const NOT_WATCHED: u8 = 2; fn first_difference(a: &[u8], b: &[u8]) -> Option { let whole = a.len().min(b.len()) / 8 * 8; let from = a[..whole] - .chunks_exact(8) + .as_chunks::<8>().0.iter() .zip(b[..whole].chunks_exact(8)) .position(|(x, y)| x != y) .map_or(whole, |word| word * 8); @@ -867,7 +867,7 @@ fn last_difference(a: &[u8], b: &[u8]) -> Option { return Some(whole + i); } let word = a[..whole] - .chunks_exact(8) + .as_chunks::<8>().0.iter() .zip(b[..whole].chunks_exact(8)) .rposition(|(x, y)| x != y)? * 8; diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 47d413d..f815393 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -653,7 +653,7 @@ impl Staging { const HASH_EVERY: u64 = 8; let unwritten = last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked); last.asked = now; - let turn = crate::frame::current().wrapping_add((start >> 16) as u64) % HASH_EVERY == 0; + let turn = crate::frame::current().wrapping_add((start >> 16) as u64).is_multiple_of(HASH_EVERY); if unwritten && !turn { return 0; } diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 7500ea5..a9ea084 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -890,7 +890,7 @@ pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut Workin // title asking. static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let asked = ASKED.fetch_add(1, Ordering::Relaxed); - if asked % 1024 == 0 { + if asked.is_multiple_of(1024) { tracing::info!( asked = asked + 1, which = _which, diff --git a/crates/victory-loader/src/console_insn_decode.rs b/crates/victory-loader/src/console_insn_decode.rs index 5b8488e..08142f8 100644 --- a/crates/victory-loader/src/console_insn_decode.rs +++ b/crates/victory-loader/src/console_insn_decode.rs @@ -159,10 +159,6 @@ pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> { } } -/// `code` as hex, for a log line. -pub fn hex(code: &[u8]) -> String { - code.iter().map(|b| format!("{b:02x}")).collect::>().join(" ") -} #[cfg(test)] mod tests { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 0643fa9..1454136 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -255,6 +255,9 @@ struct Lower<'a> { /// With `exchange`: VGPR values every lane holds alike ([`lane_uniform`]); a first-lane /// read of one needs nothing from the other host wave. uniform: HashSet, + /// With `exchange`: the wave ORs that only steer a loop over each lane's own bits, which + /// a host wave takes over its own lanes wherever they stand ([`super::own_bits`]). + own_bits: super::own_bits::OwnBits, /// The console lane (0..63) of this thread, made in the entry block. clane: Option, /// The first exchange dword of this thread's console wave ([`Self::exchange_pair`]). @@ -325,7 +328,10 @@ enum MaskData { } /// What a value holding a lane mask read as a number stops with. -const LANE_MASK: Why = "a lane mask read as data"; +pub(super) const LANE_MASK: Why = "a lane mask read as data"; +/// A mask with lanes outside EXEC where it is written, read as a number where the lanes that +/// run that block are not all of the wave. +pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data"; /// Instructions that read a lane mask (not EXEC implicitly, not a lane's /// bit) as a number. @@ -333,6 +339,20 @@ const LANE_MASK: Why = "a lane mask read as data"; /// separates it from the entry (it lies in no lane branch's region: the blocks reachable from /// the branch that do not post-dominate it). None with an indirect exit (not followed). fn all_lane_blocks(st: &Structured) -> Option> { + let n = st.exits.len(); + let mut all = vec![true; n]; + for (_, region) in lane_regions(st)? { + for b in (0..n).filter(|&b| region[b]) { + all[b] = false; + } + } + Some(all) +} + +/// Every per-lane branch (by its block) with its region: the blocks reachable from it that do +/// not post-dominate it, which only some lanes run. Not the branches the wave takes together +/// ([`Structured::wide`]), nor those on scalar conditions. None with an indirect exit. +fn lane_regions(st: &Structured) -> Option)>> { let n = st.exits.len(); let mut succ: Vec> = vec![Vec::new(); n]; for (b, e) in st.exits.iter().enumerate() { @@ -370,11 +390,11 @@ fn all_lane_blocks(st: &Structured) -> Option> { } } } - let mut all = vec![true; n]; + let mut regions = Vec::new(); for (d, e) in st.exits.iter().enumerate() { let LaneExit::Branch { when, .. } = *e else { continue }; - if st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) { - continue; // a uniform branch: all lanes go the same way + if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) { + continue; // a wave-wide or uniform branch: all lanes go the same way } // blocks reachable from the lane branch that do not post-dominate it let mut seen = vec![false; n]; @@ -384,11 +404,46 @@ fn all_lane_blocks(st: &Structured) -> Option> { continue; } seen[b] = true; - all[b] = false; stack.extend(succ[b].iter().copied()); } + regions.push((d, seen)); } - Some(all) + Some(regions) +} + +/// The per-lane branches (by block) whose regions hold a block of `needs` (blocks where two +/// host waves must meet, [`take_needs`]): the ones to take wave-wide +/// ([`crate::structure::structure_wide`]) so that every lane runs those blocks. None if one +/// of them is a branch whose wave-wide meaning is not known ([`Structured::wave_any`]). +pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option> { + let mut out = Vec::new(); + for (d, region) in lane_regions(st)? { + if needs.iter().any(|&b| region.get(b).copied().unwrap_or(false)) { + st.wave_any.get(d).copied().flatten()?; + out.push(d); + } + } + Some(out) +} + +/// Whether a refusal is of code that needs every lane of the wave where it stands (two host +/// waves meeting there), which the other forms of the program may give it. +pub(super) fn needs_every_lane(what: &str) -> bool { + what.ends_with("where not every lane runs") || what == MASK_ELSEWHERE +} + +/// The blocks where the last lowering on this thread wanted every lane and did not have it +/// (its "... where not every lane runs" refusals), which it forgets. +pub(super) fn take_needs() -> Vec { + NEEDS.take() +} + +fn need(block: usize) { + NEEDS.with_borrow_mut(|n| { + if !n.contains(&block) { + n.push(block); + } + }); } /// VGPR values that are the same in every lane holding them (`all` is [`all_lane_blocks`]): @@ -535,7 +590,7 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it // writes, which only the lanes outside EXEC keep. - let named: Vec = ops.iter().filter_map(|o| val(o)).collect(); + let named: Vec = ops.iter().filter_map(&val).collect(); for &(r, v) in &inst.reads { let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r); if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) { @@ -888,6 +943,8 @@ pub fn set_host_max_wave(lanes: u32) { } thread_local! { + /// See [`take_needs`]. + static NEEDS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; /// See [`with_local_waves`]. static LOCAL_WAVES: std::cell::Cell = const { std::cell::Cell::new(false) }; /// See [`with_local_waves_any`]. @@ -931,11 +988,49 @@ pub(super) fn with_local_waves(f: impl FnOnce() -> R) -> R { r } +/// `VICTORY_F16_NEAREST=1`: the results of 16-bit float operations (`v_add_f16`, +/// `v_mul_f16`, `v_cvt_f16_f32` ...) are rounded to nearest as the console rounds them +/// ([`Lower::f16_nearest`]) instead of as the host's `f32tof16` does (toward zero on NVIDIA: +/// the last place of a result that is not exact is then one lower than the console's). +/// Off by default: it is exact but untried in a game run, and adds instructions to every +/// such operation. The wave sum of 16-bit floats ([`Lower::half_sum`]) is always exact. +fn f16_nearest_on() -> bool { + #[cfg(test)] + if let Some(on) = TEST_F16_NEAREST.get() { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_F16_NEAREST").is_some_and(|v| v == "1")) +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`f16_nearest_on`], for its thread only. + pub(super) static TEST_F16_NEAREST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// `VICTORY_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before +/// ([`super::own_bits`]). +fn own_bits_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0")) +} + pub(super) fn host_max_wave() -> u32 { + #[cfg(test)] + if let Some(lanes) = TEST_HOST_WAVE.get() { + return lanes; + } HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed) } -fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { +#[cfg(test)] +thread_local! { + /// A test's host wave size, for its thread only ([`set_host_max_wave`] is the process's). + pub(super) static TEST_HOST_WAVE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); let ops: Vec<&Operand> = match &i.fields { // A mask operation (its result a mask) is no data use. @@ -1171,7 +1266,9 @@ impl<'a> Lower<'a> { || matches!(n, "v_readlane_b32" | "v_writelane_b32") || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some()) || reads_mask_as_data(x.st, i) - }) || lane_constant_masks(x.st); + }) || lane_constant_masks(x.st) + // (a branch the wave takes together asks the wave) + || !x.st.wide.is_empty(); let mut wave = if x.native.wave64 { 64 } else { 32 }; let group = cs.threads.iter().product::(); let one_wave = group <= wave; @@ -1191,7 +1288,8 @@ impl<'a> Lower<'a> { || n.starts_with("ds_permute") || n.starts_with("ds_bpermute") || reads_mask_as_data(x.st, i) - }) || lane_constant_masks(x.st); + }) || lane_constant_masks(x.st) + || !x.st.wide.is_empty(); if !crosses && (s.lds_dwords == 0 || group <= 32) { wave = 32; } else { @@ -1216,6 +1314,15 @@ impl<'a> Lower<'a> { lds_meet = Some((all.clone(), meet)); lds_ok = true; } + if !lds_ok { + // (the blocks whose LDS accesses not every lane runs: with the + // branches around them taken wave-wide they get their barriers) + for (b, blk) in p.blocks.iter().enumerate() { + if !all.get(b).copied().unwrap_or(false) && blk.insts.iter().any(lds) { + need(b); + } + } + } if lds_ok { wave = 32; split_lds = s.lds_dwords > 0 && group > 32; @@ -1403,6 +1510,12 @@ impl<'a> Lower<'a> { Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all), _ => HashSet::new(), }, + own_bits: match &exchange { + Some((_, false, _)) if !LOCAL_WAVES.get() && own_bits_on() => { + super::own_bits::find(p, x.st, std::env::var_os("VICTORY_WAVE_WHY").is_some()) + } + _ => Default::default(), + }, exchange, clane: None, pair: None, @@ -1642,7 +1755,8 @@ impl<'a> Lower<'a> { for &(_, w) in &inst.writes { let val = if self.section_out.contains(&w) { let shape = self.sections[&b][&start].shapes.get(&w).copied(); - match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh)) { + let own = self.own_bits.totals.contains(&w); + match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh, own)) { Ok(x) => Val::I32(x), Err(why) => Val::Missing(why), } @@ -1657,7 +1771,11 @@ impl<'a> Lower<'a> { /// host's active lanes: the console's result with console lanes; on /// another wave size, what the HLSL wave operation the console compiler /// expanded gives on that wave. - fn shape(&mut self, shape: super::wave::Shape) -> Result { + /// + /// `own`: a wave OR that only steers a loop over each lane's own bits + /// ([`super::own_bits`]); where two host waves cannot exchange their halves' ORs it is + /// this host wave's. + fn shape(&mut self, shape: super::wave::Shape, own: bool) -> Result { use super::wave::{Op, Shape}; let (op, src, mask, ident, prefix) = match shape { Shape::K(k) => return Ok(self.s.m.i32(k)), @@ -1706,6 +1824,12 @@ impl<'a> Lower<'a> { let id = self.s.m.i32(ident); let x = self.s.m.select(c, on, x, id); self.s.flags |= flags::WAVE_OPS; + if op == Op::AddH { + return match prefix { + Some(_) => Err("a wave prefix of an operation other than a sum"), + None => self.half_sum(x), + }; + } let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF); let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); let arg = if float { self.as_float(x) } else { x }; @@ -1764,8 +1888,13 @@ impl<'a> Lower<'a> { // 32 threads or fewer, which one host wave holds whole (combining with the 0 a // missing half "gives" broke AND, MIN and signed MAX) r + } else if own && prefix.is_none() && op == Op::Or && !self.all_lanes(self.cur_ir) { + // each thread walks the bits of this value and works only at its own, which the + // host wave's OR holds: the same run as with the console wave's OR + r } else if self.exchange.is_some() { if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); return Err("a wave reduction where not every lane runs"); } let bits = |l: &mut Self, v: V| if float { l.as_int(v) } else { v }; @@ -1817,6 +1946,85 @@ impl<'a> Lower<'a> { Ok(if float { self.as_int(r) } else { r }) } + /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's + /// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest + /// ([`Self::f16_nearest`]). + fn add_halves(&mut self, a: V, b: V) -> V { + let c = self.cur; + let f32t = self.s.t.f32; + let low = self.s.m.i32(0xFFFF); + let wide = |l: &mut Self, x: V| { + let h = l.s.m.bin(c, Bin::And, x, low); + l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]) + }; + let (fa, fb) = (wide(self, a), wide(self, b)); + let f = self.s.m.bin(c, Bin::Add, fa, fb); + self.f16_nearest(f) + } + + /// `WaveActiveSum` of 16-bit floats (`x`: each lane's term in its low half, +0 in the + /// lanes outside the mask), bit for bit as the console adds it: every addition rounds to + /// 16 bits, so the order counts, and the compiler's is the balanced tree over the lanes + /// in their order (lanes 2k and 2k+1, then pairs, ... then the wave's two halves; + /// [`super::wave::buddies`]). Each lane adds its partner's partial sum, read from the + /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange + /// their halves' sums for the last addition. The high half of the result is lane 0's, + /// which no `v_add_f16` writes. + /// That needs every lane of a full wave there to be read: refused where not every lane + /// runs, in a thread group that does not fill its waves, and for each half-wave on its + /// own (half a sum is no sum). + fn half_sum(&mut self, x: V) -> Result { + const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs"; + let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?; + if threads.iter().product::() % 64 != 0 { + return Err("a wave sum of 16-bit floats in a wave that is not full"); + } + if self.local { + return Err("a wave sum of 16-bit floats in a half-wave"); + } + // two host waves of 32 that exchange, or one host wave of 64 lanes + let halves = match (&self.exchange, self.s.wave_size) { + (Some((_, false, _)), _) => true, + (None, Some(64)) if self.x.p.wave64 => false, + _ => return Err("a wave sum of 16-bit floats on these waves"), + }; + let every = if halves { + self.all_lanes(self.cur_ir) + } else { + all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false)) + }; + if !every { + if halves { + need(self.cur_ir); + } + return Err(WHERE); + } + let c = self.cur; + let i32t = self.s.t.i32; + let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let mut sum = x; + for step in 0..if halves { 5 } else { 6 } { + let bit = self.s.m.i32(1 << step); + let partner = self.s.m.bin(c, Bin::Xor, lane, bit); + let theirs = self.read_lane(sum, partner); + sum = self.add_halves(sum, theirs); + } + let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0)); + let first = self.read_lane(x, zero); + let first = self.s.m.bin(c, Bin::And, first, high); + let sum = self.s.m.bin(c, Bin::And, sum, low); + let mine = self.s.m.bin(c, Bin::Or, first, sum); + if !halves { + return Ok(mine); + } + let (lo, hi) = self.exchange_halves(c, mine); + let c = self.cur; + let total = self.add_halves(lo, hi); + let total = self.s.m.bin(c, Bin::And, total, low); + let first = self.s.m.bin(c, Bin::And, lo, high); + Ok(self.s.m.bin(c, Bin::Or, first, total)) + } + fn run(mut self) -> Result { let p = self.x.p; let order = crate::ir::reverse_postorder(&p.blocks); @@ -2740,8 +2948,16 @@ impl<'a> Lower<'a> { None => (v, false), }; let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?; - if !self.x.st.active.contains(&lo) { - return Err("a lane mask holding lanes elsewhere read as data"); + // A mask that holds lanes outside EXEC where it is written (the complement of one, + // say) is the ballot of the lanes that are there: all of them, where two exchanging + // host waves know every lane runs that block. + let made = self.def_block.get(&lo).copied(); + let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b)); + if !self.x.st.active.contains(&lo) && !whole { + if self.exchange.is_some() && !self.local { + need(made.unwrap_or(0)); + } + return Err(MASK_ELSEWHERE); } let (x, y) = match self.ballots.get(&lo) { Some(&xy) => xy, @@ -2774,6 +2990,7 @@ impl<'a> Lower<'a> { } } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) { // (a group of 32 or fewer has no other half to exchange with) + need(b.unwrap_or(0)); return Err("a lane mask exchanged where not every lane runs"); } xy = self.exchange_halves(at, xy.0); @@ -2994,6 +3211,44 @@ impl<'a> Lower<'a> { self.s.m.select(c, away, stepped, h) } + /// `f` as an f16 in the low bits, rounded to nearest, ties to even, as the console's + /// 16-bit float operations round, whatever the host's own conversion does: D3D lets + /// `f32tof16` round toward zero, and the NVIDIA driver's does (measured on an RTX 4070: + /// `wave64_tests`). The conversion toward zero, or the next half away from zero where + /// that one is nearer, or as near and the first one odd. Past the largest half the next + /// one counts as 2^16, the bound IEEE rounds by, so 65520 and up become infinity. + /// (`f` is an f32 result of two halves here; rounding it again to 16 bits gives the + /// rounding of the exact result, 24 bits being more than twice 11 and two.) + fn f16_nearest(&mut self, f: V) -> V { + let c = self.cur; + let f32t = self.s.t.f32; + let lo = self.f16_toward_zero(f); + let (one, zero) = (self.s.m.i32(1), self.s.m.i32(0)); + let hi = self.s.m.bin(c, Bin::Add, lo, one); + let size = |l: &mut Self, h: V| { + let w = l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]); + l.unary(6, w) + }; + let (below, above) = (size(self, lo), size(self, hi)); + let (magnitude, infinity) = (self.s.m.i32(0x7FFF), self.s.m.i32(0x7C00)); + let m = self.s.m.bin(c, Bin::And, hi, magnitude); + let top = self.s.m.cmp(c, pred::EQ, m, infinity); + let bound = self.s.m.f32(65536.0f32.to_bits()); + let above = self.s.m.select(c, top, bound, above); + let fa = self.unary(6, f); + // (both differences are exact: the three values lie within one half's step) + let under = self.s.m.bin(c, Bin::Sub, fa, below); + let over = self.s.m.bin(c, Bin::Sub, above, fa); + // Ordered: never for NaN, which stays what the conversion made of it. + let nearer = self.s.m.cmp(c, pred::OLT, over, under); + let tie = self.s.m.cmp(c, pred::OEQ, over, under); + let odd = self.s.m.bin(c, Bin::And, lo, one); + let odd = self.s.m.cmp(c, pred::NE, odd, zero); + let tie = self.s.m.bin(c, Bin::And, tie, odd); + let up = self.s.m.bin(c, Bin::Or, nearer, tie); + self.s.m.select(c, up, hi, lo) + } + /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's /// top bit when `signed`; widths from 32 on take every bit. A signed /// field that runs past bit 31 extends from bit 31, as the hardware @@ -3350,6 +3605,90 @@ impl<'a> Lower<'a> { v } + /// The console's decision of the branch closing IR block `b`, which the wave takes + /// together ([`Structured::wide`]): `when` is the lane's own bit, and the branch is taken + /// when some lane's `when` holds (`execnz`, `vccnz`, SCC of a mask operation set) or + /// when every lane's does (`execz`, `vccz`, that SCC clear), [`Structured::wave_any`]. + /// Each host wave asks its lanes and the halves exchange the answers, so both go the + /// same way and can meet again inside the branch. + /// SCC of a mask operation as data ([`Structured::scc_some`]): whether some lane of the + /// console wave has its bit of the result, asked where the operation stands. The lanes + /// that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so with + /// the console's waves the host wave's answer is the console's; two host waves of 32 + /// exchange theirs, which needs every lane there. + fn scc_some(&mut self, scc: Value) -> Result { + let &m = self.x.st.scc_some.get(&scc).ok_or(LANE_MASK)?; + // (not for a console wave cut into host waves that do not exchange) + if !self.console_lanes || self.local || self.exchange.is_none() && self.halves.is_some() { + return Err(LANE_MASK); + } + let made = self.def_block.get(&scc).copied(); + let at = match made { + None => self.s.entry, + Some(b) if b == self.cur_ir => self.cur, + Some(b) => self.tail[b].ok_or("a lane mask written after its use")?, + }; + let bit = self.boolean(m, at)?; + let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); + let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]); + self.s.flags |= flags::WAVE_OPS; + if !self.exchange.as_ref().is_some_and(|e| !e.1) { + return Ok(some); + } + if !made.is_none_or(|b| self.all_lanes(b)) { + need(made.unwrap_or(0)); + return Err("a lane mask exchanged where not every lane runs"); + } + let some = self.s.m.cast(at, Cast::ZExt, some, i32t); + let (lo, hi) = self.exchange_halves(at, some); + let both = self.s.m.bin(at, Bin::Or, lo, hi); + let z = self.s.m.i32(0); + Ok(self.s.m.cmp(at, pred::NE, both, z)) + } + + fn wave_wide(&mut self, b: usize, when: Bool) -> Result { + const WHY: Why = "a wave-wide branch where not every lane runs"; + let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?; + if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console { + // The host's waves are the console's: the wave's own answer. The lanes that are + // elsewhere have no bit set, as on the console, so "some lane" needs no one but + // the lanes here, and "every lane's bit is clear" is true of the others anyway. + let c = self.cur; + let mine = self.boolean(when, c)?; + let i1t = self.s.t.i1; + self.s.flags |= flags::WAVE_OPS; + let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) }; + return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine])); + } + if self.local || !self.exchange.as_ref().is_some_and(|e| !e.1) { + return Err(WHY); + } + if !self.all_lanes(b) { + need(b); + return Err(WHY); + } + let c = self.cur; + let mine = self.boolean(when, c)?; + // what the halves exchange is "some lane speaks against" either way (for `any`: + // some lane's `when` holds; else: some lane's does not), so a half with no lane says + // nothing + let set = if any { + mine + } else { + let t = self.s.m.bool(true); + self.s.m.bin(c, Bin::Xor, mine, t) + }; + let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); + let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]); + self.s.flags |= flags::WAVE_OPS; + let some = self.s.m.cast(c, Cast::ZExt, some, i32t); + let (lo, hi) = self.exchange_halves(c, some); + let c = self.cur; + let both = self.s.m.bin(c, Bin::Or, lo, hi); + let z = self.s.m.i32(0); + Ok(self.s.m.cmp(c, if any { pred::NE } else { pred::EQ }, both, z)) + } + /// Whether every lane runs IR block `b` (always true without `exchange`). fn all_lanes(&self, b: usize) -> bool { self.exchange.as_ref().is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false)) @@ -6872,6 +7211,7 @@ impl<'a> Lower<'a> { } // the lane that holds it may be in the other host wave: it gives it through LDS if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); return Err("a lane read where not every lane runs"); } let cl = self.console_lane(); @@ -6921,6 +7261,15 @@ impl<'a> Lower<'a> { let a = s(self, 0)?; int(self, a) } + "v_readfirstlane_b32" + if matches!(v.src.first(), Some(&Operand::Vector { reg, .. }) + if inst.read(Reg::V(reg)).is_some_and(|x| self.own_bits.alike.contains(&x))) => + { + // The bits a loop over a wave OR has still to visit (`own_bits`): every lane of + // the host wave holds the same, so the first lane's is the lane's own. + let a = s(self, 0)?; + int(self, a) + } "v_readfirstlane_b32" => { let a = s(self, 0)?; let (mine, any) = self.first_lane(a, guard); @@ -6935,6 +7284,7 @@ impl<'a> Lower<'a> { let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local; let r = if halves && !alike { if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); return Err("a first-lane read where not every lane runs"); } let c = self.cur; @@ -7205,8 +7555,15 @@ impl<'a> Lower<'a> { if v.clamp { f = l.unary(7, f); } - let h = - l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); + // The console rounds to nearest; the host's conversion may round toward zero + // (NVIDIA's does), one step of the last place lower where the two differ. + // shortcut: the host's conversion unless `VICTORY_F16_NEAREST=1` + // ([`f16_nearest_on`]), which costs a dozen instructions per result. + let h = if f16_nearest_on() { + l.f16_nearest(f) + } else { + l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) + }; l.write_half(inst, h, guard) }; if name == "v_cvt_f16_f32" { @@ -10074,6 +10431,10 @@ impl<'a> Lower<'a> { } => { // A negated condition branches the other way round. let (cond, taken, not_taken) = match self.x.st.bools.node(when) { + _ if self.x.st.wide.contains(&b) => { + let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?; + (c, taken, not_taken) + } Some((atom, Bool::TRUE, Bool::FALSE)) => { let a = self .atom(atom, self.cur) @@ -10295,6 +10656,45 @@ impl<'a> Lower<'a> { { self.s.m.i32(0) } + // A lane mask joined with numbers (a traversal that keeps its lanes' masks on + // a stack with its node numbers): the mask comes as the number it is, the + // ballot of its lanes where it is written. + (Some(Val::Missing(_)) | None, false) + if self.read_phis.contains(&phi.value) + && self.mask_data == MaskData::Console + && (st.masks.contains_key(&arg) || st.highs.contains_key(&arg)) => + { + match self.mask_dword(arg) { + Ok(x) => x, + Err(why) => return Err(Stop::Retry(phi.value, why)), + } + } + // SCC of a mask operation ("some lane is left") joined with a scalar test: + // the compiler branches around code that sets SCC and tests SCC after it, + // the skip bringing "no lane" along. As data it is "some lane of the wave + // has the bit" - right only if the wave took that skip together, as the + // console does: a lane that skipped alone would bring "some lane" where the + // console has the skipped code's SCC. So the branch must be one the wave + // takes together; else its region is named for `emit`'s retry to widen it. + (Some(Val::Missing(_)) | None, true) + if self.read_phis.contains(&phi.value) + && self.mask_data == MaskData::Console + && st.scc_some.contains_key(&arg) => + { + let per_lane = !st.wide.contains(&q) + && matches!(st.exits[q], LaneExit::Branch { when, .. } + if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_)))); + if per_lane { + for &other in p.blocks[b].preds.iter().filter(|&&o| o != q) { + need(other); + } + return Err(Stop::Retry(phi.value, LANE_MASK)); + } + match self.scc_some(arg) { + Ok(x) => x, + Err(why) => return Err(Stop::Retry(phi.value, why)), + } + } (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => { return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index d9003c1..423fb54 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -89,6 +89,7 @@ mod intersect_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; mod lower; +mod own_bits; mod rect; mod sampler; mod shader; @@ -99,6 +100,8 @@ pub mod validator; mod valu_tests; #[cfg(all(test, windows))] mod waterfall_tests; +#[cfg(all(test, windows))] +mod wave64_tests; mod wave; use crate::dxbc::{Container, FourCC}; @@ -270,6 +273,8 @@ pub fn emit( io: &io::Io, res: &resource::Resources, ) -> Result { + // (what an earlier program's lowering on this thread left behind) + lower::take_needs(); let original = emit_program(c, native, p, st, io, res); // A console wave64 compute program on a host of 32-lane waves that // still needs 64 lanes, or whose cross-lane code sits where not every @@ -278,9 +283,12 @@ pub fn emit( // body from being a block every lane runs. let stuck = match &original { Ok((_, wave)) => *wave == Some(64), - Err(ShaderError::Unsupported { what, .. }) => what.ends_with("where not every lane runs"), + Err(ShaderError::Unsupported { what, .. }) => lower::needs_every_lane(what), Err(_) => false, }; + // (a mask with lanes elsewhere is only helped by the exact forms: not by each half-wave + // on its own) + let exact_only = matches!(&original, Err(ShaderError::Unsupported { what, .. }) if *what == lower::MASK_ELSEWHERE); if stuck && native.stage == HwStage::Cs && native.wave64 && lower::host_max_wave() == 32 { let why = std::env::var_os("VICTORY_WAVE_WHY").is_some(); let report = |what: &str, r: &Result<(HostShader, Option), ShaderError>| { @@ -322,7 +330,7 @@ pub fn emit( }; let forms = [ ("without early-outs", form(ir::without_early_outs(p))), - ("without skips", form(ir::without_skips(p))), + ("without skips", form(ir::without_skips(p, false))), ]; for (name, f) in &forms { if let Some((p, st, io, res)) = f { @@ -333,31 +341,70 @@ pub fn emit( } } } - if local_on { - // exact first (every form), then approximate - for exact in [true, false] { - if !exact && strict { - break; + let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0"); + // exact first: each host wave on its own where that is exact (the idiom, every + // form; no barriers), then the other exact forms; then approximate + for exact in [true, false] { + if !exact { + // Before anything approximate, the exact forms that cost group barriers. + // Every skip left out that the code after it cannot see + // ([`ir::without_skips`], `deep`): most of the body is then code every + // lane runs, where the two host waves can exchange. + // (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.) + let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0"); + let deep = if deep_on { form(ir::without_skips(p, true)) } else { None }; + if let Some((p, st, io, res)) = &deep { + let again = emit_program(c, native, p, st, io, res); + report("without skips, scalars followed", &again); + if done(&again) { + return again.map(|(shader, _)| shader); + } } - for (name, f) in &forms { - if let Some((p, st, io, res)) = f - && idiom(p, st) == exact - { - let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); - report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local); - if done(&local) { - return local.map(|(shader, _)| shader); + // Still stopped where not every lane runs: the per-lane branches around + // those places taken as the console takes them, by the whole wave at once + // ([`widen`]), at two group barriers per such branch. + if wide_on { + let bases = [ + deep.as_ref().map(|f| &f.0), + forms[1].1.as_ref().map(|f| &f.0), + forms[0].1.as_ref().map(|f| &f.0), + Some(p), + ]; + if let Some(base) = bases.into_iter().flatten().next() { + let again = widen(c, native, base, why); + report("wave-wide branches", &again); + if done(&again) { + return again.map(|(shader, _)| shader); } } } - if idiom(p, st) == exact { + if strict { + break; + } + } + if !local_on || exact_only { + continue; + } + for (name, f) in &forms { + if let Some((p, st, io, res)) = f + && idiom(p, st) == exact + { let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); - report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local); + report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local); if done(&local) { return local.map(|(shader, _)| shader); } } } + if idiom(p, st) == exact { + let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); + report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + if local_on && !exact_only { // Last: every mask and lane read per host wave. if !strict { for (name, f) in &forms { @@ -377,6 +424,23 @@ pub fn emit( } } } + // SCC of a mask operation joined with a scalar test behind a per-lane skip (the 32-lane + // trace programs): right once the wave takes that skip together ([`widen`]; the + // lowering has named the skipped blocks). + let original = match original { + Err(ShaderError::Unsupported { what, .. }) + if native.stage == HwStage::Cs + && what == lower::LANE_MASK + && std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") => + { + let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some()); + match again { + Ok(_) => again, + Err(_) => emit_program(c, native, p, st, io, res), + } + } + other => other, + }; let original = original.map(|(shader, _)| shader); // Retry unsupported programs only. Threading can separate an unknown // register value from its apparent use on a mutually exclusive path. @@ -394,6 +458,69 @@ pub fn emit( emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader) } +/// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane +/// branches around its cross-lane code taken wave-wide ([`structure::structure_wide`]): the +/// lowering names the blocks where the two host waves must meet and could not +/// (`lower::take_needs`), the branches whose regions hold them are widened, and so on until +/// it translates or a branch cannot be widened. Only where a thread group is one console +/// wave: with several, the waves of a group would decide differently and a barrier inside +/// such a branch would wait for threads that never come. +fn widen( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + why: bool, +) -> Result<(HostShader, Option), ShaderError> { + const NOT: ShaderError = ShaderError::Unsupported { + offset: 0, + what: "wave-wide branches in a thread group of several console waves", + }; + match native.io { + // (a program whose waves are the host's meets no one: no barrier, any group) + crate::native::StageIo::Cs(_) if !(native.wave64 && lower::host_max_wave() == 32) => {} + crate::native::StageIo::Cs(cs) if cs.threads.iter().product::() == 64 => {} + crate::native::StageIo::Cs(cs) => { + if why { + eprintln!("WAVE64-WIDE not tried: thread groups of {:?}", cs.threads); + } + return Err(NOT); + } + _ => return Err(NOT), + } + let mut wide = std::collections::HashSet::new(); + loop { + let st = structure::structure_wide(p, &wide)?; + let io = io::raise(p, native)?; + let res = resource::track(p, &native.layout, native.stage, Some(&st))?; + lower::take_needs(); + let r = emit_program(c, native, p, &st, &io, &res); + let needs = lower::take_needs(); + // (or translated for 64-lane waves still: shared memory read and written where not + // every lane runs, whose blocks the lowering names too) + let stuck = matches!(&r, Err(ShaderError::Unsupported { what, .. }) + if lower::needs_every_lane(what) || *what == lower::LANE_MASK && !needs.is_empty()) + || matches!(&r, Ok((_, Some(64)))) && !needs.is_empty(); + if !stuck { + if why { + eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len()); + } + return r; + } + let more: Vec = lower::branches_around(&st, &needs) + .unwrap_or_default() + .into_iter() + .filter(|b| !wide.contains(b)) + .collect(); + if more.is_empty() { + if why { + eprintln!("WAVE64-WIDE stopped with {} branches wave-wide: a branch around it cannot be", wide.len()); + } + return r; + } + wide.extend(more); + } +} + /// The translated program, and the wave size it requires of the host. fn emit_program( c: &Container, diff --git a/crates/victory-shader/src/emit/own_bits.rs b/crates/victory-shader/src/emit/own_bits.rs new file mode 100644 index 0000000..64aaba8 --- /dev/null +++ b/crates/victory-shader/src/emit/own_bits.rs @@ -0,0 +1,914 @@ +//! Wave ORs that only steer a loop over each lane's own bits. +//! +//! The title's light loops are "scalarised": the lanes' light masks are ORed over the wave and +//! the wave walks the set bits of the result together, each lane working only where its own +//! mask has the bit: +//! +//! ```text +//! merged = WaveActiveBitOr(mask); // over the lanes that run +//! while (merged != 0) { +//! bit = firstbitlow(merged); +//! if (mask & (1 << bit)) { ... } // the body +//! merged ^= 1 << bit; +//! } +//! ``` +//! +//! A console wave64 program in two host waves of 32 cannot exchange the halves' ORs where not +//! every lane runs (a group barrier must be reached by every thread). It does not have to: as +//! one thread runs it, the loop visits the bits of `merged` in rising order and does something +//! only at the bits of the thread's own mask, so any `merged` that holds the thread's own bits +//! gives that thread the same run. The host wave's own OR is such a value. +//! +//! That holds only if the OR is used for nothing else, and if a round of the loop at a bit the +//! thread does not have leaves nothing behind. [`find`] proves both for each wave OR, with no +//! instruction sequence taken on trust: +//! +//! - the OR and what derives from it as "the bits still to visit" (copies, the loop's join, the +//! first-lane read of it, the set less the visited bit) are read only by the loop's own +//! steps: the test for an empty set, the lowest set bit, the removal of that bit, the test +//! that ends the loop; +//! - the lane's test is its own bit of the very value that was ORed, and "the body" is what a +//! lane only reaches with that test true in the same round; +//! - outside the body the loop has no side effect and no cross-lane step, writes nothing that +//! is read after the loop or carried into a later round, and is left only by the test for +//! "no bits left"; +//! - no lane mask that depends on the test is used outside the round that made it. +//! +//! Anything else is refused there as before ("a wave reduction where not every lane runs") and +//! left to the forms of the program in which every lane runs that code (`emit`'s retries: the +//! skips left out, the branches around it taken wave-wide), where the halves do exchange. +//! `VICTORY_WAVE_OWN_BITS=0` turns this off. + +use std::collections::{HashMap, HashSet}; + +use super::wave::{self, Op, Shape}; +use crate::gfx10::{Fields, NULL, Operand}; +use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; +use crate::structure::{Atom, Bool, LaneExit, Structured}; + +type Why = &'static str; + +const USED: Why = "a wave OR used as data"; +const NO_LOOP: Why = "a wave OR that steers no loop over its bits"; +const SHAPE: Why = "a loop over a wave OR's bits of another shape"; +const TEST: Why = "a loop over a wave OR's bits whose lanes do not test their own bit"; +const LEAVES: Why = "a value of a round over a wave OR's bits that outlives the round"; +const EFFECT: Why = "an effect in a loop over a wave OR's bits outside the lanes' own bits"; +const CROSS: Why = "a cross-lane step in a loop over a wave OR's bits outside the lanes' own bits"; +const EXIT: Why = "a loop over a wave OR's bits left another way"; +const STALE: Why = "a lane's own-bit test used outside its round"; +const MASK: Why = "a wave OR over a mask a running lane may be outside"; + +/// What [`find`] proved. +#[derive(Debug, Default)] +pub(super) struct OwnBits { + /// Wave ORs (the values their sections leave) a host wave may take over its own lanes. + pub totals: HashSet, + /// VGPR values of those loops that every lane of a host wave holds alike (the bits still + /// to visit): a first-lane read of one is the lane's own value. + pub alike: HashSet, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum User { + Inst(usize, usize), + Phi(usize, usize), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Arg { + Val(Value), + K(u32), + Other, +} + +struct Ctx<'a> { + p: &'a Program, + st: &'a Structured, + users: HashMap>, + /// The instruction writing each value. + def: HashMap, + /// Values an instruction reads, directly or through joins. + live: HashSet, + idom: Vec, + sections: Vec>, +} + +/// The values instruction `i` of block `b` uses: what its operands read, without EXEC (lane +/// masks are followed as booleans) and without the old value of a VGPR it writes, which only +/// lanes outside a guard keep. +fn used(p: &Program, st: &Structured, b: usize, i: usize) -> Vec { + let inst = &p.blocks[b].insts[i]; + let ops = crate::ir::operand_reads(p, inst); + let guarded = st.guards[b][i].is_some(); + inst.reads + .iter() + .filter(|&&(r, _)| match r { + Reg::S(c) if c == EXEC || c == EXEC + 1 => false, + Reg::V(_) => ops.contains(&r) || guarded, + _ => true, + }) + .map(|r| r.1) + .collect() +} + +fn value(inst: &Inst, op: &Operand) -> Option { + match *op { + Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)), + Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), + _ => None, + } +} + +/// The sources of a scalar or unmodified vector operation. +fn args(inst: &Inst) -> Vec { + let src: &[Operand] = match &inst.fields { + Fields::Sop { src, .. } => src, + Fields::Valu(v) + if v.dpp.is_none() + && v.sdwa.is_none() + && v.abs == 0 + && v.neg == 0 + && !v.clamp + && v.omod == 0 => + { + &v.src + } + _ => &[], + }; + src.iter() + .map(|o| match (value(inst, o), o) { + (Some(v), _) => Arg::Val(v), + (None, &Operand::Const(c)) => crate::resource::inline(c).map_or(Arg::Other, Arg::K), + (None, &Operand::Literal(x)) => Arg::K(x), + _ => Arg::Other, + }) + .collect() +} + +/// The other source of a two-source operation that reads `a`. +fn other(inst: &Inst, a: Value) -> Option { + match args(inst)[..] { + [Arg::Val(x), o] if x == a => Some(o), + [o, Arg::Val(x)] if x == a => Some(o), + _ => None, + } +} + +/// The scalar (not SCC) or vector dword an instruction writes, if it writes one. +fn result(inst: &Inst) -> Option { + let mut w = inst.writes.iter().filter(|w| w.0 != Reg::Scc); + match (w.next(), w.next()) { + (Some(&(_, v)), None) => Some(v), + _ => None, + } +} + +/// The same test as `wave_local`'s and `Lower::inst`'s `effect`, and the messages a program +/// sends. +fn effect(inst: &Inst) -> bool { + let name = inst.name(); + matches!(inst.fields, Fields::Exp { .. }) + || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") + || name.contains("store") + || name.contains("atomic") + || matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || name.contains("permute")) + || matches!(name, "s_barrier" | "s_sendmsg" | "s_sendmsghalt") +} + +impl Ctx<'_> { + fn new<'a>(p: &'a Program, st: &'a Structured) -> Ctx<'a> { + let mut users: HashMap> = HashMap::new(); + let mut def = HashMap::new(); + let mut live: HashSet = HashSet::new(); + for (b, block) in p.blocks.iter().enumerate() { + for (k, phi) in block.phis.iter().enumerate() { + for &a in &phi.args { + users.entry(a).or_default().push(User::Phi(b, k)); + } + } + for (i, inst) in block.insts.iter().enumerate() { + for v in used(p, st, b, i) { + users.entry(v).or_default().push(User::Inst(b, i)); + live.insert(v); + } + for &(_, w) in &inst.writes { + def.insert(w, (b, i)); + } + } + } + // through joins + let mut changed = true; + while changed { + changed = false; + for block in &p.blocks { + for phi in &block.phis { + if live.contains(&phi.value) { + for &a in &phi.args { + changed |= live.insert(a); + } + } + } + } + } + let order = crate::ir::reverse_postorder(&p.blocks); + let mut index = vec![usize::MAX; p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + index[b] = n; + } + let idom = crate::ir::idoms(&p.blocks, &order, &index); + let sections = (0..p.blocks.len()).map(|b| wave::sections(p, b)).collect(); + Ctx { + p, + st, + users, + def, + live, + idom, + sections, + } + } + + fn inst(&self, u: (usize, usize)) -> &Inst { + &self.p.blocks[u.0].insts[u.1] + } + + fn at(&self, u: (usize, usize)) -> usize { + self.inst(u).machine.offset + } + + /// Whether block `a` dominates block `b`. + fn dominates(&self, a: usize, mut b: usize) -> bool { + loop { + if a == b { + return true; + } + let d = self.idom.get(b).copied().unwrap_or(usize::MAX); + if d == b || d == usize::MAX { + return false; + } + b = d; + } + } + + fn readers(&self, v: Value) -> Vec<(usize, usize)> { + let mut out: Vec<(usize, usize)> = self + .users + .get(&v) + .into_iter() + .flatten() + .filter_map(|u| match *u { + User::Inst(b, i) => Some((b, i)), + User::Phi(..) => None, + }) + .collect(); + out.sort_unstable(); + out.dedup(); + out + } + + /// The joins reading `v` whose value something reads. + fn joins(&self, v: Value) -> Vec<(usize, usize)> { + let mut out: Vec<(usize, usize)> = self + .users + .get(&v) + .into_iter() + .flatten() + .filter_map(|u| match *u { + User::Phi(b, k) if self.live.contains(&self.p.blocks[b].phis[k].value) => Some((b, k)), + _ => None, + }) + .collect(); + out.sort_unstable(); + out.dedup(); + out + } + + /// The loop of header `h`: the blocks that reach one of its back edges without passing it. + fn natural_loop(&self, h: usize) -> Vec { + let mut inside = vec![false; self.p.blocks.len()]; + let mut work: Vec = self.p.blocks[h] + .preds + .iter() + .copied() + .filter(|&q| self.dominates(h, q)) + .collect(); + if work.is_empty() { + return inside; + } + inside[h] = true; + while let Some(b) = work.pop() { + if inside[b] { + continue; + } + inside[b] = true; + work.extend(self.p.blocks[b].preds.iter().copied()); + } + inside + } + + /// Whether `b` holds only in lanes where `a` does. + fn implied(&self, b: Bool, a: Atom, memo: &mut HashMap) -> bool { + if b == Bool::FALSE { + return true; + } + if let Some(&r) = memo.get(&b) { + return r; + } + let r = match self.st.bools.node(b) { + None => false, + Some((x, lo, _)) if x == a => lo == Bool::FALSE, + Some((_, lo, hi)) => self.implied(lo, a, memo) && self.implied(hi, a, memo), + }; + memo.insert(b, r); + r + } + + /// The conditional branch reading `scc`, as (its place, the block it goes to when SCC is + /// set, the other one). + fn branch(&self, scc: Value) -> Option<((usize, usize), usize, usize)> { + let [u] = self.readers(scc)[..] else { + return None; + }; + let Exit::Branch { taken, not_taken } = self.p.blocks[u.0].exit else { + return None; + }; + if u.1 + 1 != self.p.blocks[u.0].insts.len() { + return None; + } + match self.inst(u).name() { + "s_cbranch_scc1" => Some((u, taken, not_taken)), + "s_cbranch_scc0" => Some((u, not_taken, taken)), + _ => None, + } + } + + /// One wave OR `t` of `x` over the lanes of `mask`, left by a section of block `sb`: the + /// VGPR values its loop keeps alike, or where and why it is not such a loop. + fn site(&self, sb: usize, t: Value, x: Value, mask: Value) -> Result, (usize, Why)> { + let p = self.p; + let st = self.st; + let n = p.blocks.len(); + let here = p.blocks[sb].offset; + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + // every lane that runs the section is one of the lanes ORed + let &mb = st.masks.get(&mask).ok_or((here, MASK))?; + if st.bools.meet(&[(st.reach[sb], true), (mb, false)]) { + return Err((here, MASK)); + } + // ---- the bits still to visit, and the loop's own steps ---- + let mut rem: HashSet = HashSet::from([t]); + let mut pattern: HashSet<(usize, usize)> = HashSet::new(); + let mut alike: Vec = Vec::new(); + // an unguarded copy + let copy = |u: (usize, usize)| -> Option { + let i = self.inst(u); + (matches!(i.name(), "v_mov_b32" | "s_mov_b32") && args(i).len() == 1 && st.guards[u.0][u.1].is_none()) + .then(|| result(i)) + .flatten() + }; + let mut init = vec![t]; + // (SCC, whether it is set when the OR is empty) + let mut zero: Option<(Value, bool)> = None; + for u in self.readers(t) { + let i = self.inst(u); + let name = i.name(); + if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32") + && other(i, t) == Some(Arg::K(0)) + && zero.is_none() + && let Some(scc) = i.write(Reg::Scc) + { + zero = Some((scc, name.contains("_eq_"))); + rem.insert(scc); + } else if let Some(w) = copy(u) { + init.push(w); + rem.insert(w); + if matches!(i.writes[0].0, Reg::V(_)) { + alike.push(w); + } + } else { + return Err((self.at(u), USED)); + } + pattern.insert(u); + } + // the loop's join of them + let mut join: Option<(usize, usize)> = None; + for &v in &init { + if v != t + && let Some(&u) = self.readers(v).first() + { + return Err((self.at(u), USED)); + } + for j in self.joins(v) { + if join.is_some_and(|q| q != j) { + return Err((p.blocks[j.0].offset, USED)); + } + join = Some(j); + } + } + let (h, k) = join.ok_or((here, NO_LOOP))?; + let phi = &p.blocks[h].phis[k]; + let r = phi.value; + rem.insert(r); + let head = p.blocks[h].offset; + let lp = self.natural_loop(h); + if !lp[h] || lp[sb] { + return Err((head, NO_LOOP)); + } + // the set as a scalar: the first lane's copy of it + let cur = if matches!(phi.reg, Reg::V(_)) { + alike.push(r); + let [u] = self.readers(r)[..] else { + return Err((head, USED)); + }; + let i = self.inst(u); + if i.name() != "v_readfirstlane_b32" || args(i).len() != 1 || !lp[u.0] { + return Err((self.at(u), USED)); + } + pattern.insert(u); + let c = result(i).ok_or((self.at(u), SHAPE))?; + if !self.joins(r).is_empty() { + return Err((head, USED)); + } + c + } else { + r + }; + rem.insert(cur); + // its lowest bit, the set without it, the tests for "that was the last" + let mut idx: Option = None; + let mut next: Option<(Value, Value)> = None; + // (SCC, whether it is set while bits remain) + let mut more: Vec<(Value, bool)> = Vec::new(); + let mut bits: Vec = Vec::new(); + for u in self.readers(cur) { + let i = self.inst(u); + let name = i.name(); + if !lp[u.0] { + return Err((self.at(u), USED)); + } + match (name, &args(i)[..]) { + ("s_ff1_i32_b32", [Arg::Val(_)]) if idx.is_none() => idx = result(i), + ("s_xor_b32", _) | ("s_andn2_b32", [Arg::Val(_), Arg::Val(_)]) if next.is_none() => { + let bit = match (name, &args(i)[..]) { + ("s_andn2_b32", [Arg::Val(c), Arg::Val(b)]) if *c == cur && *b != cur => *b, + ("s_xor_b32", _) => match other(i, cur) { + Some(Arg::Val(b)) if b != cur => b, + _ => return Err((self.at(u), USED)), + }, + _ => return Err((self.at(u), USED)), + }; + let w = result(i).ok_or((self.at(u), SHAPE))?; + next = Some((w, bit)); + bits.push(bit); + if let Some(scc) = i.write(Reg::Scc) { + more.push((scc, true)); + rem.insert(scc); + } + } + ("s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32", _) => { + let (Some(Arg::Val(b)), Some(scc)) = (other(i, cur), i.write(Reg::Scc)) else { + return Err((self.at(u), USED)); + }; + bits.push(b); + more.push((scc, name.contains("_lg_"))); + rem.insert(scc); + } + _ => return Err((self.at(u), USED)), + } + pattern.insert(u); + } + if cur != r && !self.joins(cur).is_empty() { + return Err((head, USED)); + } + let (Some(idx), Some((nx, bit))) = (idx, next) else { + return Err((head, SHAPE)); + }; + if bits.iter().any(|&b| b != bit) { + return Err((head, SHAPE)); + } + // the bit: 1 shifted by the lowest set bit's number (a shift takes five bits of it) + let made = |v: Value| self.def.get(&v).map(|&u| (u, self.inst(u))); + let shifted = match made(bit) { + Some((u, i)) if i.name() == "s_lshl_b32" && lp[u.0] => match args(i)[..] { + [Arg::K(1), Arg::Val(sh)] => Some(sh), + _ => None, + }, + _ => None, + }; + let by_idx = shifted.is_some_and(|sh| { + sh == idx + || made(sh).is_some_and(|(_, i)| i.name() == "s_and_b32" && other(i, idx) == Some(Arg::K(31))) + }); + if !by_idx { + return Err((head, SHAPE)); + } + // the set less the bit: back into the join, or tested for empty + rem.insert(nx); + let mut nexts = vec![nx]; + for u in self.readers(nx) { + let i = self.inst(u); + let name = i.name(); + if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32") + && other(i, nx) == Some(Arg::K(0)) + && let Some(scc) = i.write(Reg::Scc) + { + more.push((scc, name.contains("_lg_"))); + rem.insert(scc); + } else if let Some(w) = copy(u) { + nexts.push(w); + rem.insert(w); + if matches!(i.writes[0].0, Reg::V(_)) { + alike.push(w); + } + } else { + return Err((self.at(u), USED)); + } + pattern.insert(u); + } + for &v in &nexts { + if v != nx + && let Some(&u) = self.readers(v).first() + { + return Err((self.at(u), USED)); + } + if self.joins(v).iter().any(|&j| j != (h, k)) { + return Err((head, USED)); + } + } + for (q, a) in p.blocks[h].preds.iter().zip(&phi.args) { + let ok = if lp[*q] { nexts.contains(a) } else { init.contains(a) }; + if !ok { + return Err((head, SHAPE)); + } + } + // the loop goes on while bits remain and is left when none does + let mut leaves: HashSet = HashSet::new(); + for &(scc, set_while_more) in &more { + if !self.joins(scc).is_empty() { + return Err((head, USED)); + } + if self.readers(scc).is_empty() { + continue; + } + let (u, set, clear) = self.branch(scc).ok_or((head, USED))?; + let (on, out) = if set_while_more { (set, clear) } else { (clear, set) }; + if !lp[u.0] || !lp[on] || lp[out] { + return Err((self.at(u), SHAPE)); + } + leaves.insert(u.0); + pattern.insert(u); + } + if leaves.is_empty() { + return Err((head, SHAPE)); + } + // "no bit at all" skips the loop; what lies between that test and the loop runs only + // when there is one + let mut pre = vec![false; n]; + if let Some((scc, set_when_empty)) = zero { + if !self.joins(scc).is_empty() { + return Err((here, USED)); + } + if !self.readers(scc).is_empty() { + let (u, set, clear) = self.branch(scc).ok_or((here, USED))?; + let (none, some) = if set_when_empty { (set, clear) } else { (clear, set) }; + if none == some || lp[u.0] { + return Err((self.at(u), SHAPE)); + } + if some != h { + if p.blocks[some].preds[..] != [u.0] || !self.dominates(some, h) { + return Err((self.at(u), SHAPE)); + } + for b in 0..n { + pre[b] = self.dominates(some, b) && !self.dominates(h, b); + } + for b in (0..n).filter(|&b| pre[b]) { + let inside = match p.blocks[b].exit { + Exit::End | Exit::Indirect => false, + ref e => e.successors().iter().all(|&s| pre[s] || s == h), + }; + if !inside { + return Err((p.blocks[b].offset, SHAPE)); + } + } + } + pattern.insert(u); + } + } + // ---- the lane's test of its own bit ---- + // (the atom of the compare, its block, its index) + let mut tests: Vec<(Atom, usize, usize)> = Vec::new(); + for u in self.readers(bit) { + let i = self.inst(u); + if i.name() != "v_and_b32" || other(i, bit) != Some(Arg::Val(x)) || st.guards[u.0][u.1].is_some() { + continue; + } + let Some(y) = result(i) else { continue }; + for c in self.readers(y) { + let ci = self.inst(c); + if matches!( + ci.name(), + "v_cmp_ne_u32" | "v_cmpx_ne_u32" | "v_cmp_lg_u32" | "v_cmpx_lg_u32" | "v_cmp_ne_i32" | "v_cmpx_ne_i32" + | "v_cmp_lg_i32" | "v_cmpx_lg_i32" + ) && other(ci, y) == Some(Arg::K(0)) + && lp[c.0] + { + tests.extend(ci.writes.iter().map(|w| (Atom::Lane(w.1), c.0, c.1))); + } + } + } + if tests.is_empty() { + return Err((head, TEST)); + } + let mut memo: Vec> = vec![HashMap::new(); tests.len()]; + // what a lane only reaches with its own bit set, in the round of that test + let mut body_block = vec![false; n]; + for b in (0..n).filter(|&b| lp[b]) { + body_block[b] = tests.iter().enumerate().any(|(j, &(a, tb, _))| { + b != tb && self.dominates(tb, b) && self.implied(st.reach[b], a, &mut memo[j]) + }); + } + let body_inst = |b: usize, i: usize, memo: &mut Vec>| { + body_block[b] + || lp[b] + && st.guards[b][i].is_some_and(|g| { + tests.iter().enumerate().any(|(j, &(a, tb, ti))| { + (b == tb && i > ti || b != tb && self.dominates(tb, b)) && self.implied(g, a, &mut memo[j]) + }) + }) + }; + // ---- a round outside the body leaves nothing behind ---- + for b in (0..n).filter(|&b| lp[b] || pre[b]) { + for (i, inst) in p.blocks[b].insts.iter().enumerate() { + if lp[b] && body_inst(b, i, &mut memo) { + continue; + } + let u = (b, i); + for &(reg, w) in &inst.writes { + if rem.contains(&w) || is_mask(w) || matches!(reg, Reg::S(c) if c == EXEC || c == EXEC + 1) { + continue; + } + for user in self.users.get(&w).into_iter().flatten() { + let stays = match *user { + User::Inst(b2, _) => lp[b2] || pre[b2], + User::Phi(b2, k2) => { + body_block[b2] || !self.live.contains(&p.blocks[b2].phis[k2].value) + } + }; + if !stays { + return Err((self.at(u), LEAVES)); + } + } + } + if pattern.contains(&u) { + continue; + } + if effect(inst) { + return Err((self.at(u), EFFECT)); + } + let name = inst.name(); + let cross = name.starts_with("ds_swizzle") + || name.contains("permute") + || name.starts_with("v_mbcnt") + || name.contains("lane") + || matches!(&inst.fields, Fields::Valu(v) if v.dpp.is_some()) + || super::lower::reads_mask_as_data(st, inst) + || self.sections[b].iter().any(|(&s, sec)| i >= s && i <= sec.end); + if cross { + return Err((self.at(u), CROSS)); + } + if used(p, st, b, i).iter().any(|v| rem.contains(v)) { + return Err((self.at(u), USED)); + } + } + // left only by "no bits left"; the body may leave it as it likes + if lp[b] && !body_block[b] { + let ok = match p.blocks[b].exit { + Exit::End | Exit::Indirect => false, + ref e => leaves.contains(&b) || e.successors().iter().all(|&s| lp[s]), + }; + if !ok { + return Err((p.blocks[b].offset, EXIT)); + } + } + } + // ---- no mask that depends on the test outlives its round ---- + let mut dep: HashSet = tests.iter().map(|t| t.0).collect(); + let mut changed = true; + while changed { + changed = false; + for (&id, edges) in &st.phi_masks { + if !dep.contains(&Atom::Phi(id)) + && edges.iter().any(|&e| st.bools.support(e).iter().any(|a| dep.contains(a))) + { + dep.insert(Atom::Phi(id)); + changed = true; + } + } + } + let mut seen: HashMap = HashMap::new(); + let mut tainted = |b: Bool| -> bool { + *seen + .entry(b) + .or_insert_with(|| st.bools.support(b).iter().any(|a| dep.contains(a))) + }; + for b in 0..n { + if lp[b] && tests.iter().any(|&(_, tb, _)| self.dominates(tb, b)) { + continue; + } + let stale = st.guards[b].iter().flatten().any(|&g| tainted(g)) + || matches!(st.exits[b], LaneExit::Branch { when, .. } if tainted(when)); + if stale { + return Err((p.blocks[b].offset, STALE)); + } + } + for (&v, &m) in &st.masks { + if !tainted(m) { + continue; + } + for user in self.users.get(&v).into_iter().flatten() { + let outside = match *user { + User::Inst(b2, _) => !lp[b2], + User::Phi(b2, k2) => !lp[b2] && self.live.contains(&p.blocks[b2].phis[k2].value), + }; + if outside { + return Err((head, STALE)); + } + } + } + Ok(alike) + } +} + +/// The wave ORs of `p` that only steer a loop over each lane's own bits (see the module +/// notes). `why`: one line on stderr for each wave OR that is not one. +pub(super) fn find(p: &Program, st: &Structured, why: bool) -> OwnBits { + let mut out = OwnBits::default(); + let mut ctx: Option = None; + for b in 0..p.blocks.len() { + let sections = wave::sections(p, b); + let mut starts: Vec<_> = sections.keys().copied().collect(); + starts.sort_unstable(); + for s in starts { + let sec = §ions[&s]; + let mut left: Vec<_> = sec.shapes.iter().collect(); + left.sort_unstable_by_key(|(v, _)| v.0); + for (&t, &shape) in left { + let Shape::Active(Op::Or, x, mask, 0) = shape else { + continue; + }; + let ctx = ctx.get_or_insert_with(|| Ctx::new(p, st)); + // (values only the section itself reads are not results) + let inside = |u: &User| matches!(*u, User::Inst(b2, i) if b2 == b && i > s && i < sec.end); + if ctx.users.get(&t).is_none_or(|us| us.iter().all(inside)) { + continue; + } + match ctx.site(b, t, x, mask) { + Ok(alike) => { + out.totals.insert(t); + out.alike.extend(alike); + } + Err((offset, what)) => { + if why { + eprintln!( + "WAVE64-OWN-BITS the wave OR at {:#x}: not a loop over the lanes' own bits at {offset:#x}: {what}", + p.blocks[b].insts[s].machine.offset + ); + } + } + } + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::emit::wave::WAVE_OR_V7_TO_S7; + + const ADD_BIT_NUMBER: u32 = 0x4A0A_0A0A; // v_add_nc_u32 v5, s10, v5 + + /// The title's scalarised light loop (`indirect_light_probes:CS_IrradianceCache_Shade`, + /// 0x71f8 on), in small: the wave OR of v7 in s7, a loop over its bits with the lowest + /// one's number in s10 and the bit in s11, and `body` for the lanes whose v7 has the bit + /// (`own`) or for every lane; `latch` runs in every lane after the body, `after` after + /// the loop. + fn light_loop(own: bool, body: &[u32], latch: &[u32], after: &[u32]) -> Program { + let mut w = WAVE_OR_V7_TO_S7.to_vec(); + let test: &[u32] = if own { + &[ + 0x3608_0E0B, // v_and_b32 v4, s11, v7 + 0xBE8C_047E, // s_mov_b64 s[12:13], exec + 0x7DAA_0880, // v_cmpx_ne_u32 exec, 0, v4 + ] + } else { + &[0xBE8C_047E] // s_mov_b64 s[12:13], exec + }; + // from the loop's head to its last branch + let head = 3 + test.len() + usize::from(own) + body.len() + 1 + latch.len() + 3; + w.extend_from_slice(&[ + 0xBF06_8007, // s_cmp_eq_u32 s7, 0 + 0xBF85_0000 | (3 + head) as u32, // s_cbranch_scc1 past the loop + 0x7E06_0207, // v_mov_b32 v3, s7 + 0xBF82_0001, // s_branch to the loop's head + 0x7E06_0209, // again: v_mov_b32 v3, s9 + 0x7E10_0503, // head: v_readfirstlane_b32 s8, v3 + 0xBE8A_1308, // s_ff1_i32_b32 s10, s8 + 0x8F0B_0A81, // s_lshl_b32 s11, 1, s10 + ]); + w.extend_from_slice(test); + if own { + w.push(0xBF88_0000 | body.len() as u32); // s_cbranch_execz past the body + } + w.extend_from_slice(body); + w.push(0xBEFE_040C); // s_mov_b64 exec, s[12:13] + w.extend_from_slice(latch); + w.extend_from_slice(&[ + 0x8909_080B, // s_xor_b32 s9, s11, s8 + 0xBF06_0B08, // s_cmp_eq_u32 s8, s11 + 0xBF84_0000 | (0x1_0000 - head - 1) as u32, // s_cbranch_scc0 again + ]); + w.extend_from_slice(after); + w.push(0xBF81_0000); // s_endpgm + let code: Vec = w.iter().flat_map(|x| x.to_le_bytes()).collect(); + crate::ir::build(&code, true, 256).unwrap() + } + + fn found(p: &Program) -> OwnBits { + let st = crate::structure::structure(p).unwrap(); + find(p, &st, false) + } + + #[test] + fn a_wave_or_that_only_steers_a_loop_over_own_bits_is_found() { + let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[]); + let insts = || p.blocks.iter().flat_map(|b| &b.insts); + let names: Vec<&str> = insts().map(|i| i.name()).collect(); + for n in [ + "s_ff1_i32_b32", + "s_lshl_b32", + "v_and_b32", + "v_cmpx_ne_u32", + "s_xor_b32", + "v_readfirstlane_b32", + "s_cbranch_execz", + ] { + assert!(names.contains(&n), "{n} in {names:?}"); + } + // a loop: its last branch goes back to the copy of the bits still to visit + assert!(p.blocks.iter().enumerate().any(|(b, blk)| blk.exit.successors().iter().any(|&s| s < b))); + let own = found(&p); + // the OR is the section's last lane read, and the bits still to visit (v3) are alike + let total = insts() + .rfind(|i| i.name() == "v_readlane_b32") + .and_then(|i| i.write(Reg::S(7))) + .unwrap(); + assert_eq!(own.totals, HashSet::from([total])); + let first = insts().find(|i| i.name() == "v_readfirstlane_b32").unwrap(); + assert!(own.alike.contains(&first.read(Reg::V(3)).unwrap())); + } + + #[test] + fn a_loop_whose_lanes_all_work_at_every_bit_needs_the_whole_waves_or() { + // (the same title's volume loops, 0xa668 on: no test of the lane's own mask) + let p = light_loop(false, &[ADD_BIT_NUMBER], &[], &[]); + assert!(found(&p).totals.is_empty()); + } + + #[test] + fn a_bit_number_read_after_the_loop_is_not_the_lanes_own() { + // v_mov_b32 v6, s10: the last bit of the OR, which another lane may have set + let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020A]); + assert!(found(&p).totals.is_empty()); + } + + #[test] + fn the_bits_still_to_visit_read_in_the_body_are_not_the_lanes_own() { + // v_add_nc_u32 v5, s8, v5: s8 holds the other lanes' bits too + let p = light_loop(true, &[0x4A0A_0A08], &[], &[]); + assert!(found(&p).totals.is_empty()); + } + + #[test] + fn a_count_of_the_rounds_is_not_the_lanes_own() { + // s_add_i32 s14, s14, 1 where every lane passes, read after the loop + // (v_mov_b32 v6, s14): one round for each bit any lane has + let p = light_loop(true, &[ADD_BIT_NUMBER], &[0x810E_810E], &[0x7E0C_020E]); + assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_add_i32")); + assert!(found(&p).totals.is_empty()); + // (reading s14 there without counting in it is nothing of the loop's) + let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020E]); + assert_eq!(found(&p).totals.len(), 1); + } + + #[test] + fn an_effect_where_every_lane_passes_is_not_the_lanes_own() { + // ds_write_b32 v5, v5 after the body: once for each bit any lane has + let p = light_loop(true, &[ADD_BIT_NUMBER], &[0xD834_0000, 0x0000_0505], &[]); + assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "ds_write_b32")); + assert!(found(&p).totals.is_empty()); + } +} diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs index 483631f..c74e083 100644 --- a/crates/victory-shader/src/emit/wave.rs +++ b/crates/victory-shader/src/emit/wave.rs @@ -21,6 +21,10 @@ use crate::ir::{EXEC, Inst, Program, Reg, Value}; pub(crate) enum Op { AddU, AddF, + /// A sum of 16-bit floats in the low halves (`v_add_f16`), each addition rounded to 16 + /// bits: not associative, so only the balanced tree over the lanes in their order is + /// followed (see [`buddies`]), which is how the compiler sums a wave. + AddH, MinU, MaxU, MinI, @@ -39,6 +43,7 @@ impl Op { // the high one) is the 32-bit sum of the low dwords "v_add_nc_u32" | "v_add_co_u32" => Op::AddU, "v_add_f32" => Op::AddF, + "v_add_f16" => Op::AddH, "v_min_u32" => Op::MinU, "v_max_u32" => Op::MaxU, "v_min_i32" => Op::MinI, @@ -55,7 +60,7 @@ impl Op { /// Whether `k` leaves the other operand unchanged. fn identity(self, k: u32) -> bool { match self { - Op::AddU | Op::Or | Op::Xor | Op::MaxU => k == 0, + Op::AddU | Op::AddH | Op::Or | Op::Xor | Op::MaxU => k == 0, Op::AddF => k == 0 || k == 0x8000_0000, Op::MinU | Op::And => k == u32::MAX, Op::MinI => k == 0x7FFF_FFFF, @@ -67,7 +72,26 @@ impl Op { /// Counting a lane twice changes the result. fn counts(self) -> bool { - matches!(self, Op::AddU | Op::AddF | Op::Xor) + matches!(self, Op::AddU | Op::AddF | Op::AddH | Op::Xor) + } +} + +/// Whether the lane sets `a` and `b` are the two halves of one aligned run of lanes: lanes +/// 2k and 2k+1, then two such pairs side by side, and so on up to the two halves of the +/// wave. Sums joined only that way form the balanced tree over the lanes in their order, +/// whichever of the two a lane adds to the other (the addition is commutative). +fn buddies(a: u64, b: u64) -> bool { + let n = a.count_ones(); + if n != b.count_ones() || !n.is_power_of_two() || n == 64 { + return false; + } + let run = |s: u64| { + let first = s.trailing_zeros(); + (first.is_multiple_of(n) && s >> first == (1u64 << n) - 1).then_some(first) + }; + match (run(a), run(b)) { + (Some(x), Some(y)) => x.min(y) % (2 * n) == 0 && x.abs_diff(y) == n, + _ => false, } } @@ -218,7 +242,8 @@ fn combine(op: Op, a: Sym, b: Sym) -> Sym { && op.identity(ident) && oa.is_none_or(|o| o == op) && ob.is_none_or(|o| o == op) - && (!op.counts() || la & lb == 0) => + && (!op.counts() || la & lb == 0) + && (op != Op::AddH || buddies(la, lb)) => { Sym::Red { op: Some(op), @@ -635,6 +660,32 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option { Some(Shape::Prefix(op, src, mask, ident, inclusive)) } +/// `WaveActiveBitOr(v7)` into s7 as the console compiler expands it: every lane takes part, +/// those outside the saved EXEC (s[4:5]) with 0. +#[cfg(test)] +pub(super) const WAVE_OR_V7_TO_S7: [u32; 20] = [ + 0xBE84_25C1, // s_or_saveexec_b64 s[4:5], -1 + 0xD501_0001, + 0x0012_0E80, // v_cndmask_b32 v1, 0, v7, s[4:5] + 0x3802_02E9, + 0xDE54_C101, // v_or_b32 v1, v1, v1 dpp8:[1,0,3,2,5,4,7,6] + 0x3802_02E9, + 0x9360_1201, // v_or_b32 v1, v1, v1 dpp8:[2,2,0,0,6,6,4,4] + 0x3802_02E9, + 0x0009_2401, // v_or_b32 v1, v1, v1 dpp8:[4,4,4,4,0,0,0,0] + 0x3802_02FA, + 0xFF09_4001, // v_or_b32 v1, v1, v1 row_mirror bound_ctrl:1 + 0xD778_0002, + 0x0201_0101, // v_permlanex16_b32 v2, v1, 0, 0 + 0x3802_0302, // v_or_b32 v1, v2, v1 + 0xD760_0007, + 0x0001_4101, // v_readlane_b32 s7, v1, 32 + 0x3802_0207, // v_or_b32 v1, s7, v1 + 0xD760_0007, + 0x0001_0101, // v_readlane_b32 s7, v1, 0 + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] +]; + #[cfg(test)] mod tests { use super::*; @@ -859,6 +910,67 @@ mod tests { } } + /// `WaveActiveSum` of 16-bit floats, as compiled in + /// `compute_graph_ops:CS_TransposeVecMatMulAlignedOperation` (0x19c on): the tree the + /// lowering reproduces. A tree in another order is not followed. + #[test] + fn a_sum_of_halves_over_the_wave_is_followed_in_the_order_of_its_tree() { + let words = |first: [u32; 2], second: [u32; 2]| { + [ + 0xBE84_25C1, // s_or_saveexec_b64 s[4:5], -1 + 0xD501_0001, + 0x0012_0E80, // v_cndmask_b32 v1, 0, v7, s[4:5] + first[0], + first[1], + second[0], + second[1], + 0x6402_02E9, + 0x0009_2401, // v_add_f16 v1, v1, v1 dpp8:[4,4,4,4,0,0,0,0] + 0x6402_02FA, + 0xFF09_4001, // v_add_f16 v1, v1, v1 row_mirror bound_ctrl:1 + 0xD778_0002, + 0x0201_0101, // v_permlanex16_b32 v2, v1, 0, 0 + 0x6402_0302, // v_add_f16 v1, v2, v1 + 0xD760_0007, + 0x0001_4101, // v_readlane_b32 s7, v1, 32 + 0x6402_0207, // v_add_f16 v1, s7, v1 + 0xD760_0007, + 0x0001_0101, // v_readlane_b32 s7, v1, 0 + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] + ] + }; + let pairs = [0x6402_02E9, 0xDE54_C101]; // v_add_f16 v1, v1, v1 dpp8:[1,0,3,2,5,4,7,6] + let quads = [0x6402_02E9, 0x9360_1201]; // v_add_f16 v1, v1, v1 dpp8:[2,2,0,0,6,6,4,4] + let shape = |w: &[u32]| { + let p = build(w, true); + let insts = &p.blocks[0].insts; + let saved = insts[0].write(Reg::S(4)).unwrap(); + let v7 = p.inputs.iter().find_map(|&(r, v)| (r == Reg::V(7)).then_some(v)).unwrap(); + // ..., v_readlane_b32 s7, v1, 0; s_mov_b64 exec, s[4:5]; s_endpgm + let total = insts[insts.len() - 3].write(Reg::S(7)).unwrap(); + (sections(&p, 0)[&0].shapes.get(&total).copied(), Shape::Active(Op::AddH, v7, saved, 0)) + }; + let (found, want) = shape(&words(pairs, quads)); + assert_eq!(found, Some(want)); + // lanes two apart first, neighbours second: every lane counted once, but + // (x0 + x2) + (x1 + x3) rounds differently from (x0 + x1) + (x2 + x3) + let (found, _) = shape(&words(quads, pairs)); + assert_eq!(found, None); + } + + #[test] + fn buddies_are_the_two_halves_of_an_aligned_run() { + assert!(buddies(0b01, 0b10)); + assert!(buddies(0b1100, 0b0011)); + assert!(buddies(0xF0, 0x0F)); + assert!(buddies(u64::from(u32::MAX), u64::from(u32::MAX) << 32)); + assert!(!buddies(0b010, 0b100)); // lanes 1 and 2: not one pair + assert!(!buddies(0b0011, 0b110000)); // pairs 0 and 2 + assert!(!buddies(0b0101, 0b1010)); // not runs + assert!(!buddies(0b01, 0b1100)); // unequal + assert!(!buddies(0b11, 0b11)); + } + #[test] fn wave32_mov_b64_all_lanes_keeps_exec_masked_for_dpp() { let w = [ diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs new file mode 100644 index 0000000..db82f33 --- /dev/null +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -0,0 +1,452 @@ +//! A console wave64 compute program on a host of 32-lane waves: a wave reduction inside a +//! per-lane branch, with that branch taken wave-wide ([`crate::structure::structure_wide`]) +//! so that the two host waves can exchange their halves inside it. Lowered, validated by +//! `dxil.dll` when present, and run on the host GPU when it takes waves of 32. + +use std::collections::HashSet; + +use super::host::{Dispatch, Host, Root, View}; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{ShaderError, io, ir, resource, structure}; + +const S_ENDPGM: u32 = 0xBF81_0000; + +/// 64 threads in one console wave. Each thread t holds the bit `1 << (t >> 1)`; the threads +/// below s0 (a root constant) OR theirs over the wave inside `if (t < s0) { ... }` and store +/// the result to dword 0 of the raw UAV. +/// `skip`: the branch past the body when no thread is below s0: `s_cbranch_execz`, or +/// `s_cbranch_scc0` on the SCC `s_and_saveexec` sets ("some lane is left"). +fn program(skip: u32) -> NativeProgram { + let mut words = vec![ + 0x7E0A_0281, // v_mov_b32 v5, 1 + 0x2C0C_0081, // v_lshrrev_b32 v6, 1, v0 + 0x340E_0B06, // v_lshlrev_b32 v7, v6, v5 + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + skip | 23, // the branch to the restore of EXEC + ]; + words.extend_from_slice(&super::wave::WAVE_OR_V7_TO_S7); + words.extend_from_slice(&[ + 0x7E00_0207, // v_mov_b32 v0, s7 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + ]); + native(&words) +} + +/// A wave64 compute program of 64 threads (one console wave; the thread index in v0) with 4 +/// root constants in s0..s3 and a raw UAV's descriptor in s[8:11], then `body`. +fn native(body: &[u32]) -> NativeProgram { + native_of(body, true, 64) +} + +/// The same for a console of 32-lane waves when `wave64` is not set, with `threads` threads. +fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram { + let mut words = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x3D << 26 | 0x02 << 18 | 8 << 6 | 2, + 125 << 25, // s_load_dwordx4 s[8:11], s[4:5], 0 + ]; + words.extend_from_slice(body); + words.push(S_ENDPGM); + NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: 16, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 + threads: [threads, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } +} + +/// `program()` for a host of 32-lane waves, with the branches closing `wide` taken wave-wide. +fn lowered(native: &NativeProgram, p: &ir::Program, wide: &HashSet) -> Result { + let st = structure::structure_wide(p, wide).expect("structure"); + let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(p, native).expect("io::raise"); + let was = lower::TEST_HOST_WAVE.replace(Some(32)); + let lowered = lower::lower(&lower::Parts { + native, + p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + lower::TEST_HOST_WAVE.set(was); + let lowered = lowered?; + Ok(HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views, + }) +} + +#[test] +fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { + // thread t holds the 16-bit float with bits 0x3C00 + 37 t (1.0 and up, with odd + // mantissas, so that additions round); all of them store the wave's sum + let mut words = vec![ + 0x340C_0085, // v_lshlrev_b32 v6, 5, v0 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 + 0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7 + 0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7 + 0x4A0E_0EFF, + 0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7 + ]; + // (the wave OR's words with v_add_f16 for v_or_b32: opcode 50 for 28) + words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w })); + words.extend_from_slice(&[ + 0x7E00_0207, // v_mov_b32 v0, s7 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]); + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + assert_eq!(p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == "v_add_f16").count(), 6); + let shader = lowered(&native, &p, &HashSet::new()).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + // the console's sum: lanes 2k and 2k+1, then pairs, ... each addition rounded to 16 bits + // (to nearest, ties to even); values here are normal numbers + let wide = |h: u16| f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13); + let narrow = |f: f32| { + let b = f.to_bits(); + let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF); + let rest = b & 0x1FFF; + (h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16 + }; + let add = |a: u16, b: u16| narrow(wide(a) + wide(b)); + let terms: Vec = (0..64u16).map(|t| 0x3C00 + 37 * t).collect(); + let mut tree = terms.clone(); + while tree.len() > 1 { + tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect(); + } + let in_a_row = terms.iter().copied().reduce(add).unwrap(); + assert_ne!(tree[0], in_a_row, "these terms tell the tree from another order"); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + let (root, pso) = match host.compute_pipeline(&shader) { + Ok(x) => x, + Err(e) => { + eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run"); + return; + } + }; + let ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + // (the high half is lane 0's term's: zero) + assert_eq!(out[0][0], u32::from(tree[0]), "tree {:#x}, in a row {in_a_row:#x}", tree[0]); + eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]); +} + +/// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2 +/// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The +/// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the +/// translation gives the console's whatever the host does. +#[test] +fn a_16_bit_sum_rounds_to_nearest_when_asked_to() { + let words = [ + 0x7E0E_02FF, + 0x0000_3C03, // v_mov_b32 v7, 0x3c03 + 0x7E0C_02FF, + 0x0000_4000, // v_mov_b32 v6, 0x4000 + 0x6400_0D07, // v_add_f16 v0, v7, v6 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]; + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "v_add_f16")); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for nearest in [false, true] { + let was = lower::TEST_F16_NEAREST.replace(Some(nearest)); + let shader = lowered(&native, &p, &HashSet::new()); + lower::TEST_F16_NEAREST.set(was); + let shader = shader.expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + eprintln!("the hardware device does not take this program; not run"); + return; + }; + let ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + let got = out[0][0] & 0xFFFF; + eprintln!("v_add_f16 0x3c03 + 0x4000 on the hardware device, nearest {nearest}: {got:#x}"); + if nearest { + assert_eq!(got, 0x4202); + } else { + assert!(got == 0x4201 || got == 0x4202, "{got:#x}"); + } + } +} + +#[test] +fn a_wave_or_inside_a_lane_branch_needs_the_branch_wave_wide() { + for (skip, name) in [(0xBF88_0000, "s_cbranch_execz"), (0xBF84_0000, "s_cbranch_scc0")] { + a_wave_or_inside(skip, name); + } +} + +fn a_wave_or_inside(skip: u32, name: &str) { + let native = program(skip); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let branch = (0..p.blocks.len()) + .find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == name)) + .expect("the branch"); + // per lane, the two host waves cannot meet inside the branch + lower::take_needs(); + let per_lane = lowered(&native, &p, &HashSet::new()); + assert!( + matches!(&per_lane, Err(ShaderError::Unsupported { what, .. }) if *what == "a wave reduction where not every lane runs"), + "{:?}", + per_lane.err() + ); + // ... and the lowering names the block, around which that branch is the one to widen + let needs = lower::take_needs(); + let st = structure::structure(&p).expect("structure"); + assert_eq!(lower::branches_around(&st, &needs), Some(vec![branch])); + // (taken, past the body, when every lane's bit is clear) + assert_eq!(st.wave_any[branch], Some(false)); + // wave-wide, every lane runs the reduction (EXEC stays a guard on what it does there) + let wide = HashSet::from([branch]); + let st = structure::structure_wide(&p, &wide).expect("structure"); + let inside = match p.blocks[branch].exit { + ir::Exit::Branch { not_taken, .. } => not_taken, + _ => unreachable!(), + }; + assert!(st.guards[inside].iter().any(Option::is_some)); + let shader = lowered(&native, &p, &wide).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + // On a GPU that takes waves of 32 (two host waves for the console's one): the OR is of + // both halves, whichever half's lanes take the branch. + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + let (root, pso) = match host.compute_pipeline(&shader) { + Ok(x) => x, + Err(e) => { + eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run"); + return; + } + }; + // (threads below s0 take the branch; thread t gives bit t >> 1) + for (below, expected) in [(64u32, u32::MAX), (40, 0x000F_FFFF), (33, 0x0001_FFFF), (10, 0x1F), (1, 1)] { + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if let (RootType::Constants, 0, 0) = (u.root, u.slot, u.dword) { + ud[u.index as usize] = below; + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + assert_eq!(out[0][0], expected, "{name}: {below} threads in the branch"); + } + eprintln!("ran on the hardware device ({name}): the OR of both halves in every case"); +} + +/// Runs `shader` on the hardware device with the root constants `s0`, `s1` and gives dword 0 +/// of the UAV; None (and a line) without a device that takes it. +fn on_the_card(shader: &HostShader, constants: [u32; 2]) -> Option { + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return None; + }; + let Ok((root, pso)) = host.compute_pipeline(shader) else { + eprintln!("the hardware device does not take this program; not run"); + return None; + }; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if let (RootType::Constants, 0, d @ 0..=1) = (u.root, u.slot, u.dword) { + ud[u.index as usize] = constants[d as usize]; + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + Some(out[0][0]) +} + +/// A 32-lane console wave. A register holds a lane mask on one path (the lanes below s0) +/// and a number on the other, and is read as a number after the join, as the trace programs +/// keep their lanes' masks and their node numbers on one stack +/// (`deferred_tiled:CS_LaserLightShadowRaytracing`, s46 at 0x104, 0x75c and 0x188). The +/// mask arrives as the ballot of its lanes. +#[test] +fn a_lane_mask_joined_with_a_number_is_read_as_the_number_it_is() { + let words = [ + 0x7D88_0000, // v_cmp_gt_u32 vcc_lo, s0, v0 + 0xBE94_036A, // s_mov_b32 s20, vcc_lo + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF85_0001, // s_cbranch_scc1 over the next + 0xBE94_0385, // s_mov_b32 s20, 5 + 0x7E00_0214, // v_mov_b32 v0, s20 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]; + let native = native_of(&words, false, 32); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = lowered(&native, &p, &HashSet::new()).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for (below, other, expected) in [(32u32, 0u32, u32::MAX), (10, 0, 0x3FF), (0, 0, 0), (10, 1, 5)] { + let Some(got) = on_the_card(&shader, [below, other]) else { return }; + assert_eq!(got, expected, "{below} lanes in the mask, s1 = {other}"); + } + eprintln!("ran on the hardware device: the mask's bits, or the number"); +} + +/// A 32-lane console wave. `if (t < s0) { ... SCC = (s1 == 7) }` and a branch on SCC after +/// the join: the skip brings the SCC of `s_and_saveexec` ("some lane is left") along +/// (`rtdirectionalshadows:CS_RTShadowTrace32HQ_TiledFarOnly`, 0x360-0x39c). On the console +/// the skip is taken by the wave, so with some lane inside every lane sees the inner test. +/// A lane that skipped on its own would see "some lane is left" instead: refused per lane, +/// right with the branch taken wave-wide. Lane 31 stores what it saw. +#[test] +fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() { + let words = [ + 0x7D88_0000, // v_cmp_gt_u32 vcc_lo, s0, v0 + 0xBE8D_3C6A, // s_and_saveexec_b32 s13, vcc_lo + 0xBF88_0001, // s_cbranch_execz over the next + 0xBF06_8701, // s_cmp_eq_u32 s1, 7 + 0xBEFE_030D, // s_mov_b32 exec_lo, s13 + 0xBF85_0002, // s_cbranch_scc1 to "seven" + 0x7E0A_0281, // v_mov_b32 v5, 1 + 0xBF82_0001, // s_branch over the next + 0x7E0A_0282, // seven: v_mov_b32 v5, 2 + 0x7DA4_009F, // v_cmpx_eq_u32 exec_lo, 31, v0 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16 | 5 << 8, // buffer_store_dword v5, off, s[8:11], 0 + ]; + let native = native_of(&words, false, 32); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let branch = (0..p.blocks.len()) + .find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz")) + .expect("the skip"); + lower::take_needs(); + let per_lane = lowered(&native, &p, &HashSet::new()); + assert!( + matches!(&per_lane, Err(ShaderError::Unsupported { what, .. }) if *what == "a lane mask read as data"), + "{:?}", + per_lane.err() + ); + let st = structure::structure(&p).expect("structure"); + assert_eq!(lower::branches_around(&st, &lower::take_needs()), Some(vec![branch])); + let shader = lowered(&native, &p, &HashSet::from([branch])).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + // (lanes below s0 inside, s1) -> what lane 31 stores: 2 if SCC was set at the branch + for (below, s1, expected) in [(0u32, 7u32, 1u32), (10, 7, 2), (10, 3, 1), (32, 3, 1), (32, 7, 2)] { + let Some(got) = on_the_card(&shader, [below, s1]) else { return }; + assert_eq!(got, expected, "{below} lanes inside, s1 = {s1}"); + } + eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside"); +} diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index df7cecb..01907b2 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -594,12 +594,74 @@ pub(crate) fn without_early_outs(p: &Program) -> Option { /// after it could see that (a scalar register or SCC that the region /// changes and the join merges with the value from before; EXEC aside, /// which is empty either way). `None` if nothing changes. -pub(crate) fn without_skips(p: &Program) -> Option { +/// +/// `deep` looks closer at what the code after the branch can see. A scalar the region moves +/// away and back (the compiler parks scalars in VGPR lanes around a branch and takes them +/// back before the join, `unspill`) is the value it copies; a join nothing reads shows no +/// one the difference (a restore of EXEC that the next one overwrites reads nothing); and +/// the join may have other ways in (an inner branch that ends together with an outer one). +/// That leaves out most of the skips of the title's large lighting programs, whose bodies +/// are then code every lane runs. +pub(crate) fn without_skips(p: &Program, deep: bool) -> Option { let n = p.blocks.len(); let ends = |b: usize| { p.blocks[b].exit == Exit::End && p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) }; + // Scalars moved from register to register (a scalar the compiler parked in a VGPR lane + // comes back by such a move, `unspill`) are the value they copy. + let mut copy: std::collections::HashMap = Default::default(); + // Values something reads, directly or through joins. A scalar operation none of whose + // results is read reads nothing either (the compiler restores EXEC from a saved mask + // and overwrites it at once where two branches end together). + let mut live: std::collections::HashSet = Default::default(); + let idle = |inst: &Inst, live: &std::collections::HashSet| { + let name = inst.name(); + matches!(inst.fields, crate::gfx10::Fields::Sop { .. }) + && !(name.starts_with("s_setpc") + || name.starts_with("s_swappc") + || name.starts_with("s_call") + || name.starts_with("s_rfe") + || name.starts_with("s_movrel") + || name.starts_with("s_subvector")) + && inst.writes.iter().all(|w| !live.contains(&w.1)) + }; + for block in &p.blocks { + for inst in &block.insts { + if matches!(inst.name(), "s_mov_b32" | "s_mov_b64") + && inst.reads.len() == inst.writes.len() + && inst.reads.iter().chain(&inst.writes).all(|r| matches!(r.0, Reg::S(_))) + { + copy.extend(inst.writes.iter().zip(&inst.reads).map(|(w, r)| (w.1, r.1))); + } + } + } + let mut changed = true; + while changed { + changed = false; + for block in &p.blocks { + for inst in &block.insts { + if !idle(inst, &live) { + for r in &inst.reads { + changed |= live.insert(r.1); + } + } + } + for phi in &block.phis { + if live.contains(&phi.value) { + for &a in &phi.args { + changed |= live.insert(a); + } + } + } + } + } + let root = |mut v: Value| { + while deep && let Some(&c) = copy.get(&v) { + v = c; + } + v + }; // The region a skip of `b` to `target` leaves out, if it is a pure skip. let skipped = |b: usize, target: usize, first: usize| -> Option> { let mut inside = vec![false; n]; @@ -631,18 +693,21 @@ pub(crate) fn without_skips(p: &Program) -> Option { Reg::Scc => true, Reg::V(_) => false, }; - if !scalar { + // (a join nothing reads shows no one the difference) + if !scalar || deep && !live.contains(&phi.value) { continue; } let before: Vec = - join.preds.iter().zip(&phi.args).filter(|(q, _)| **q == b).map(|(_, a)| *a).collect(); - let within = join.preds.iter().zip(&phi.args).filter(|(q, _)| inside[**q]).map(|(_, a)| *a); + join.preds.iter().zip(&phi.args).filter(|(q, _)| **q == b).map(|(_, a)| root(*a)).collect(); + let within = join.preds.iter().zip(&phi.args).filter(|(q, _)| inside[**q]).map(|(_, a)| root(*a)); if within.into_iter().any(|a| !before.contains(&a)) { return None; } } - // other ways into the join than the branch and the region: not a plain `if` - if join.preds.iter().any(|&q| q != b && !inside[q]) { + // Other ways into the join than the branch and the region (an inner branch that ends + // together with an outer one) change nothing in that: the lanes that would have + // skipped arrive from the region instead, with the same scalars. + if !deep && join.preds.iter().any(|&q| q != b && !inside[q]) { return None; } Some(inside) @@ -1458,6 +1523,56 @@ mod tests { p.inputs.iter().find(|i| i.0 == reg).expect("input").1 } + /// `if (v0 < s0) { ... }` whose body changes s6: `body` are its words, `after` what + /// follows the join. + fn skip(body: &[u32], after: &[u32]) -> Program { + let mut w = vec![ + 0xBE94_0306, // s_mov_b32 s20, s6 + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF88_0000 | body.len() as u32, // s_cbranch_execz past the body + ]; + w.extend_from_slice(body); + w.push(0xBEFE_040C); // s_mov_b64 exec, s[12:13] + w.extend_from_slice(after); + w.push(S_ENDPGM); + build_words(&w, true) + } + + fn skips(p: &Program) -> usize { + p.blocks + .iter() + .filter(|b| b.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz")) + .count() + } + + #[test] + fn a_skip_is_left_out_when_the_scalars_it_changes_come_back_or_are_not_read() { + const SET: u32 = 0xBE86_0385; // s_mov_b32 s6, 5 + const USE: u32 = 0x7E02_0206; // v_mov_b32 v1, s6 + const BACK: u32 = 0xBE86_0314; // s_mov_b32 s6, s20 + const READ: u32 = 0x7E04_0206; // v_mov_b32 v2, s6 + // s6 is changed in the body and read after the join: the branch stays + let kept = skip(&[SET, USE], &[READ]); + assert_eq!(skips(&kept), 1); + assert!(without_skips(&kept, false).is_none()); + assert!(without_skips(&kept, true).is_none()); + // ... put back by a copy of what it held (as a scalar parked in a VGPR lane comes + // back): every lane may walk the body + let back = skip(&[SET, USE, BACK], &[READ]); + assert!(without_skips(&back, false).is_none()); + assert_eq!(skips(&without_skips(&back, true).expect("left out")), 0); + // ... or not read after the join at all + let unread = skip(&[SET, USE], &[]); + assert_eq!(skips(&without_skips(&unread, false).expect("left out")), 0); + assert_eq!(skips(&without_skips(&unread, true).expect("left out")), 0); + // ... or read only by a restore of EXEC that nothing uses before the next one + // (s_mov_b64 exec, s[6:7]; s_mov_b64 exec, s[12:13]; v_mov_b32 v2, s0) + let idle = skip(&[SET, USE], &[0xBEFE_0406, 0xBEFE_040C, 0x7E04_0200]); + assert!(without_skips(&idle, false).is_none()); + assert_eq!(skips(&without_skips(&idle, true).expect("left out")), 0); + } + #[test] fn joins_get_phis_only_where_values_differ() { let code = [ diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 3d7952c..813a9b5 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -2671,7 +2671,7 @@ pub(crate) mod tests { ]; // v_mov_b32 v10.., s0..; v_readfirstlane_b32 s16.., v10.. words.extend((0..8).map(|k| 0x7E00_0200 | (10 + k) << 17 | k)); - words.extend((0..8).map(|k| 0x7E00_0400 | (16 + k) << 17 | 0x100 + 10 + k)); + words.extend((0..8).map(|k| 0x7E00_0400 | (16 + k) << 17 | (0x100 + 10 + k))); words.extend([ 0xF000_1700, 0x0004_0D06, // image_load v[13:15], v6, s[16:23] diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index d5a3578..a913176 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -434,6 +434,15 @@ pub struct Structured { /// Incoming lane boolean per predecessor edge (in block predecessor order) /// for each [`Atom::Phi`] id. pub phi_masks: HashMap>, + /// Blocks whose closing branch the whole wave takes together ([`structure_wide`]): its + /// `when` is still the lane's own bit; the wave goes by all of them. + pub wide: HashSet, + /// Per block closed by a branch on a lane mask: whether the console takes it when some + /// lane's `when` holds (`true`) or when every lane's does (`false`). + pub wave_any: Vec>, + /// SCC values a mask operation sets when some lane's bit of its result is set, with that + /// lane bit: as data such an SCC is "some lane of the wave has it". + pub scc_some: HashMap, } impl Structured { @@ -448,7 +457,20 @@ impl Structured { /// Builds the per-lane form of `program`. pub fn structure(program: &Program) -> Result { + structure_wide(program, &HashSet::new()) +} + +/// [`structure`], with the branches that close the blocks of `wide` kept as the console has +/// them: one decision for the whole wave (`s_cbranch_execz` and `vccz`: taken when no lane's +/// bit is set; `execnz` and `vccnz`: when some lane's is; SCC of a mask operation likewise, +/// [`Structured::wave_any`]), which every lane follows. A lane +/// then learns nothing about its own bit from the way it went, so past such a branch EXEC +/// stays a guard on every vector instruction, as it is on the console. For a console wave +/// run as two host waves, which exchange that decision and can then meet (a group barrier) +/// inside the branch. +pub fn structure_wide(program: &Program, wide: &HashSet) -> Result { let mut l = Lanes::new(program)?; + l.wide = wide.clone(); loop { let execs = l.masks_in_order(); let cond = l.paths()?; @@ -508,6 +530,13 @@ struct Lanes<'a> { when: Vec>, /// See [`Structured::active`]. active: HashSet, + /// See [`Structured::wide`]. + wide: HashSet, + /// SCC values of [`Self::scc_lane`] that are set when EVERY lane's bit is (`s_cmp_eq` of + /// two masks: "no lane differs"); the others are set when some lane's is. + scc_every: HashSet, + /// See [`Structured::wave_any`]. + wave_any: Vec>, } /// A mask join taken as `value` in every lane that reaches `block`: each @@ -585,6 +614,9 @@ impl<'a> Lanes<'a> { first: vec![Bool::FALSE; blocks.len()], when: vec![None; blocks.len()], active: HashSet::new(), + wide: HashSet::new(), + scc_every: HashSet::new(), + wave_any: vec![None; blocks.len()], }) } @@ -594,6 +626,8 @@ impl<'a> Lanes<'a> { self.other.clear(); self.seen.clear(); self.scc_lane.clear(); + self.scc_every.clear(); + self.wave_any.fill(None); self.joins.clear(); self.phi_joins.clear(); self.phi_join_ids.clear(); @@ -652,6 +686,7 @@ impl<'a> Lanes<'a> { && let Some(last) = p.blocks[b].insts.last() { self.when[b] = Some(self.branch(last)); + self.wave_any[b] = self.wave_kind(last); } } execs @@ -659,6 +694,10 @@ impl<'a> Lanes<'a> { /// `c` narrowed by the branch at the end of `q` towards one successor. fn edge(&mut self, c: Bool, q: usize, taken: bool) -> Bool { + if self.wide.contains(&q) { + // the wave's decision: it says nothing about this lane's own bit + return c; + } match self.when[q] { Some(w) if taken => self.b.and(c, w), Some(w) => { @@ -809,6 +848,14 @@ impl<'a> Lanes<'a> { .collect(), paired_masks: if self.p.wave64 { self.masks } else { Map::default() }, active: self.active, + wide: self.wide, + wave_any: self.wave_any, + scc_some: self + .scc_lane + .iter() + .filter(|(scc, _)| !self.scc_every.contains(scc)) + .map(|(&scc, &m)| (scc, m)) + .collect(), phi_masks, bools: self.b, exits, @@ -1184,6 +1231,9 @@ impl<'a> Lanes<'a> { ne }; self.scc_lane.insert(scc, m); + if rest.starts_with("eq") { + self.scc_every.insert(scc); + } } // `s_bcnt1` of a mask every running lane sees alike (EXEC under a scalar // condition, or EXEC itself): its SCC, "some lane is set", is each lane's own @@ -1252,6 +1302,27 @@ impl<'a> Lanes<'a> { } /// The per-lane condition under which a block's closing branch is taken. + /// How the console decides the branch `inst` on a lane mask, in terms of the lanes' own + /// `when` ([`Self::branch`]): taken when some lane's holds (`true`) or when every lane's + /// does (`false`). `execnz`/`vccnz` ask for some set bit, `execz`/`vccz` for none; SCC + /// of a mask operation is "some lane's bit is set", SCC of `s_cmp_eq` of two masks is + /// "every lane's is" ([`Self::scc_every`]), and `scc0` branches on the opposite. None + /// for a branch on a scalar condition. + fn wave_kind(&self, inst: &Inst) -> Option { + match inst.name() { + "s_cbranch_execnz" | "s_cbranch_vccnz" => Some(true), + "s_cbranch_execz" | "s_cbranch_vccz" => Some(false), + n @ ("s_cbranch_scc0" | "s_cbranch_scc1") => { + let scc = inst.read(Reg::Scc)?; + self.scc_lane.get(&scc)?; + // set: SCC is 1 when some lane's bit is set (every lane's, for a compare) + let every = self.scc_every.contains(&scc); + Some((n == "s_cbranch_scc1") != every) + } + _ => None, + } + } + fn branch(&mut self, inst: &Inst) -> Bool { let exec = self.exec(inst); match inst.name() { diff --git a/docs/fork-ray-tracing.md b/docs/fork-ray-tracing.md new file mode 100644 index 0000000..0dbfc42 --- /dev/null +++ b/docs/fork-ray-tracing.md @@ -0,0 +1,85 @@ +# Ray tracing in this fork: what the title does and what has been built + +Status, 2026-11-25: **nothing is lit by ray tracing yet.** Most of the +machinery translates and is unit-tested; it has not yet run end to end in the +game. Everything here is off by default. + +## What the title does + +Grand Theft Auto VI's indirect light (probes, bounce, reflections) and the +shadows of its lamps and sun are ray traced. Without them, anything the sun +does not hit directly is black: interiors, the shadowed side of a face, rooms +lit only by lamps. + +The title does not use a ray-tracing API: + +- Traversal is ordinary compute-shader code: a per-thread stack in shared + memory, and loads through raw 40-bit addresses of title memory. +- The static world's acceleration structures ship pre-built in the title's + data, in the console GPU's native node format (64-byte nodes: box nodes with + four children and 16-bit float bounds, 128-byte box nodes with 32-bit float + bounds, triangle nodes, instance nodes). They are unpacked on the GPU. +- A set of builder programs (from the title's `XboxBvhBuilder.dll`, 52 compute + programs) builds and refits the dynamic structures on the GPU every frame. +- Only the per-node test is hardware: the instructions + `image_bvh64_intersect_ray` and `image_bvh_intersect_ray`. One call tests a + ray against a box node's four children (returning the hit children, nearest + first) or against a triangle node (returning the intersection's numerator, + denominator and barycentric numerators). + +So mapping this onto the host's own ray tracing (DXR) is not practical: the +layer would have to know the geometry behind structures the title never +describes to it, and the traversal loops live in 64 of the title's own +programs. This fork runs the title's builder and traversal as translated +shaders and emulates the one instruction. + +## What this fork adds + +1. **The builder programs translate** (49 of 52; all that the title creates in + the scenes tested). They pass buffer addresses in a spilled parameter table + rather than in descriptors. Added: the spilled user-data table, root + unordered-access views (translator and host binding), byte and 16-bit buffer + accesses, and several control-flow shapes. +2. **Title memory by raw address from shaders.** A directory with one entry per + 64 KiB of title address space leads a shader to the layer's host copy of + that memory; loads, stores, atomic add/sub and float min/max go through it. + Before a dispatch the host makes ready the memory its root views and root + constants name. +3. **The ray test, emulated in DXIL.** Four slab tests and a sorting network + for box nodes; a watertight ray/triangle test for triangle nodes; both forms + of the instruction. A plain Rust reference lives in + `crates/victory-shader/src/bvh.rs`; tests run the emitted DXIL on the GPU + over 311 ray/node cases and compare with the reference bit for bit. +4. **The trace and shading programs translate** (59 of 64 trace programs, and + the irradiance-cache shading program). This needed lane masks treated as + plain numbers on some paths, and exact forms for programs written for + 64-lane waves running on a GPU with 32-lane waves. +5. **A safety rule on the host side.** The builder's stages run only while + every builder pipeline the title has created has a host pipeline; otherwise + none run (`VICTORY_BVH_BUILDER=1` asks for it; `VICTORY_BVH_QUARANTINE=1` + also keeps the builder's stores out of title memory, for a first test). A + partly working builder wrote garbage bounds into title memory and crashed + the title. + +## Known gaps + +- With `VICTORY_BVH_BUILDER=1` the builder still stays off in a real run: a few + of its pipelines are refused by the host (they still ask for 64-lane waves on + a 32-lane GPU) or do not translate. +- Five shadow-mask trace programs do not translate yet. +- An access to a title page that has no host copy is lost (a read gives zero, a + store is dropped). +- Not publicly documented, and assumed: the instruction's rounding, the order + of two boxes entered at the same distance, and the result for a ray exactly + through an edge. +- Cost on the GPU is unmeasured. + +## Where to look + +- `crates/victory-shader/src/bvh.rs`: the reference for the node test. +- `crates/victory-shader/src/emit/lower.rs`: the lowering of the two + instructions and of memory by address (`Lower::memory`). +- `crates/victory-shader/src/resource.rs`: address tracking for descriptors + and raw addresses. +- `crates/victory-gpu/src/pipeline.rs`, `draw.rs`: the builder rule and the + host side of root views and title memory. From d279e69ae999aedfd3d463b0c45c8fd125c1ad7b Mon Sep 17 00:00:00 2001 From: ZazaJr24 Date: Tue, 24 Nov 2026 19:55:08 +0100 Subject: [PATCH 115/445] Make host pipeline waits configurable and prewarm pending requests (#1) Co-authored-by: ZazaJr24 <218105339+ZazaJr24@users.noreply.github.com> --- README.md | 1 + crates/victory-gpu/src/pipeline/library.rs | 6 +-- crates/victory-gpu/src/pipeline/make.rs | 54 ++++++++++++++++------ 3 files changed, 43 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index def9162..635e7af 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,7 @@ cargo build --profile diag -p victory --features diagnostics # target\diag\vic | `VICTORY_D3D12_DEBUG=1` | host debug layer | | `VICTORY_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) | | `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | +| `VICTORY_PIPELINE_WAIT_MS=24` | reduce the per-frame wait for background pipeline creation from the default of 500 ms. A draw can be omitted until its pipeline is ready | | `VICTORY_SKIP_PIPELINES=,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash | | `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands | | `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 6f122dd..7047331 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -675,7 +675,7 @@ fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> std::fs::rename(&tmp, path) } -/// Title pipeline keys drawn or dispatched with (this run and the last). +/// Title pipeline keys requested by draws or dispatches (this run and the last). static USED: Mutex>> = Mutex::new(None); static USED_CHANGED: AtomicBool = AtomicBool::new(false); @@ -693,12 +693,12 @@ fn used() -> std::sync::MutexGuard<'static, Option>> { used } -/// Whether the title pipeline with `key` was drawn with in an earlier run. +/// Whether the title pipeline with `key` was requested in this or an earlier run. pub(crate) fn wanted_early(key: &str) -> bool { used().as_ref().is_some_and(|s| s.contains(key)) } -/// The title pipeline with `key` was drawn or dispatched with. +/// A draw or dispatch requested the title pipeline with `key`. pub(crate) fn note_used(key: &str) { let mut used = used(); let set = used.get_or_insert_with(HashSet::new); diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index de0b366..49c26c6 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -12,9 +12,8 @@ //! bake) are there at once as before; past the budget a draw or dispatch //! whose pipeline is not ready is dropped, as an untranslated one is. //! -//! shortcut: the budget (half a second of waiting per title frame) is a -//! guess; a pass the title runs only once and whose pipeline takes longer -//! is lost. +//! The default budget is half a second per title frame. A pass the title +//! runs only once and whose pipeline takes longer is lost. use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; @@ -31,7 +30,7 @@ pub(crate) struct Pending { queue_state: AtomicU8, made: OnceLock>, /// What identifies it across runs (shader containers and state), and - /// whether a draw has used it yet. + /// whether a draw or dispatch has requested it yet. key: String, used: AtomicBool, } @@ -96,7 +95,17 @@ pub(crate) fn missing(p: &Pending) -> Option { static DONE: (Mutex<()>, Condvar) = (Mutex::new(()), Condvar::new()); /// Waiting allowed per title frame, over all threads. -const BUDGET: Duration = Duration::from_millis(500); +fn wait_budget() -> Duration { + static BUDGET: OnceLock = OnceLock::new(); + *BUDGET.get_or_init(|| { + let millis = std::env::var("VICTORY_PIPELINE_WAIT_MS") + .ok() + .and_then(|value| value.trim().parse::().ok()) + .unwrap_or(500); + tracing::info!(millis, "host pipeline wait budget per frame"); + Duration::from_millis(millis) + }) +} /// Pipelines queued and not made yet. static WAITING: AtomicU64 = AtomicU64::new(0); @@ -109,19 +118,16 @@ pub(crate) fn waiting() -> u64 { /// The host pipeline if it is made (or is made within the frame's budget); /// queues it on first use. pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { + // A still-pending pipeline was requested by the title too. Prewarm it + // on the next launch, even if this run never got to use it. + if !p.used.load(Ordering::Relaxed) && !p.used.swap(true, Ordering::Relaxed) { + super::library::note_used(&p.key); + } if p.made.get().is_none() { start(p, REQUESTED); wait(p, crate::frame::current()); } - let made = p.made.get()?.as_ref(); - // Also one that could not be made (a shader that does not translate): - // the next run then finds that out while loading, like the others, - // instead of in the world's frames, where each first use of such a - // pipeline waits on the frame's budget for nothing. - if !p.used.swap(true, Ordering::Relaxed) { - super::library::note_used(&p.key); - } - made + p.made.get()?.as_ref() } /// Makes `p` on this thread if it is not made yet (waiting for a worker @@ -155,6 +161,10 @@ fn shared_budget() -> bool { /// Waits for `p` while frame `frame` has budget left. fn wait(p: &Pending, frame: u64) { + let budget = 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)); @@ -164,7 +174,7 @@ fn wait(p: &Pending, frame: u64) { if spent.0 != frame { *spent = (frame, Duration::ZERO); } - let left = BUDGET.saturating_sub(spent.1); + let left = budget.saturating_sub(spent.1); if shared { spent.1 += left; } @@ -353,6 +363,20 @@ mod tests { assert!(matches!(p.made.get(), Some(None))); } + #[test] + fn pending_pipeline_is_recorded_for_the_next_launch() { + let mut p = Pending::new(Vec::new(), None); + p.key = "pending-pipeline-test".to_owned(); + // Simulate a worker that has taken the job but cannot finish it yet. + p.queue_state.store(MAKING, Ordering::Relaxed); + let p = Arc::new(p); + + assert!(!super::super::library::wanted_early(&p.key)); + assert!(ready(&p).is_none()); + assert!(p.made.get().is_none()); + assert!(super::super::library::wanted_early(&p.key)); + } + #[test] fn draws_promote_early_pipelines_without_claiming_them_twice() { let earlier = Arc::new(Pending::new(Vec::new(), None)); From 004bf69a4bc36e9b35c0fd496a71f3b362648238 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:01:26 -0500 Subject: [PATCH 116/445] Test fix for hosted runners, stencil diagnostics, and a stability warning - Shader tests: a software adapter given as the default device is not taken for a hardware device, so the tests that need a real card skip there. - Diagnostics: the stencil plane of dumped depth-stencil targets and the title's descriptions of its stencil views. - README: the newest commits lose the GPU device shortly after start on the test machine; the cause is not found yet. Co-Authored-By: Claude Fable 5.2 --- README.md | 2 +- crates/victory-gpu/src/capture.rs | 127 +++++++++++++++++++++- crates/victory-gpu/src/descriptor/host.rs | 24 ++++ crates/victory-shader/src/emit/host.rs | 12 ++ 4 files changed, 161 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 635e7af..b03abd2 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, | First gameplay scene (the prologue) | renders: characters, textures, sky, sunlit exterior; HUD, pause menu and pad input work | | Light in shadow | missing: the game's ray-traced bounce light and ray-traced lamp and sun shadows do not run yet, so anything the sun does not hit directly is black | | Frame rate in the world | 2-4 fps: 420-450 ms per frame by default, 240-350 ms with the newer switches (`VICTORY_RELAY=2`, or `VICTORY_LATE_WAIT=3 VICTORY_WIDE_BACK=1 VICTORY_CARD_BUFFERS_MIN_MB=1 VICTORY_CARD_BUFFERS_MB=1024`); it started at 3-6 seconds per frame | -| Stability | no driver hang or device loss in normal runs | +| Stability | **the newest commits lose the GPU device shortly after start on the test machine (4 of 4 runs), cause not yet found; the last tree that ran clean is the first commit of this fork, `578d459`** | ### What this fork changed (summary) diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index c58c2c1..507e334 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -223,6 +223,17 @@ pub(crate) fn read_back( device: &ID3D12Device, list: &ID3D12GraphicsCommandList, texture: &ID3D12Resource, +) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> { + read_back_of(device, list, texture, 0) +} + +/// As [`read_back`], of subresource `sub` (the stencil plane of a +/// one-level, one-slice depth-stencil texture is subresource 1). +fn read_back_of( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + texture: &ID3D12Resource, + sub: u32, ) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> { let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); let mut total = 0; @@ -231,7 +242,7 @@ pub(crate) fn read_back( let desc = texture.GetDesc(); device.GetCopyableFootprints( &desc, - 0, + sub, 1, 0, Some(&mut footprint), @@ -282,7 +293,7 @@ pub(crate) fn read_back( pResource: std::mem::transmute_copy(texture), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: 0, + SubresourceIndex: sub, }, }; list.CopyTextureRegion(&to, 0, 0, 0, &from, None); @@ -384,14 +395,27 @@ fn dump_one( .ResourceBarrier(&[crate::host::transition(texture, state, copy)]); } let read = read_back(&host.device, &list.list, texture); + // The stencil plane of a depth-stencil target, which the title's + // lighting reads (material class in the low bits; 0x08 "inside a + // room", which the lamps of a room are multiplied by): the plane + // after the depth plane of a one-level, one-slice texture. + let stencil = (matches!(d.Format.0, 19..=22 | 44..=47) + && d.MipLevels == 1 + && d.DepthOrArraySize == 1) + .then(|| read_back_of(&host.device, &list.list, texture, 1)) + .flatten(); if state != copy { list.list .ResourceBarrier(&[crate::host::transition(texture, copy, state)]); } - read + (read, stencil) }; + let (read, stencil) = read; list.close(); host.execute(&[&list]); + if let Some((buffer, footprint)) = stencil { + stencil_values(&buffer, &footprint, frame, resource); + } let Some((buffer, footprint)) = read else { return }; let f = footprint.Footprint; let mut data = std::ptr::null_mut(); @@ -435,6 +459,67 @@ fn dump_one( } } +/// Logs which values a stencil plane read back by [`read_back_of`] holds +/// (the most common first), how many texels have each of its bits, and the +/// box of the texels with bit 3 (0x08). +fn stencil_values( + buffer: &ID3D12Resource, + footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + frame: u64, + resource: crate::object::This, +) { + let f = footprint.Footprint; + let (w, h, pitch) = (f.Width as usize, f.Height as usize, f.RowPitch as usize); + let mut data = std::ptr::null_mut(); + // SAFETY: the copy finished; the mapping spans the footprint's rows of + // one byte a texel, the last row without its padding. + unsafe { + if h == 0 || w == 0 || buffer.Map(0, None, Some(&mut data)).is_err() { + return; + } + let rows = std::slice::from_raw_parts(data.cast::(), pitch * (h - 1) + w); + let mut values = [0u32; 256]; + let mut bits = [0u32; 8]; + // Left, top, right, bottom of the texels with bit 3. + let mut inside = [u32::MAX, u32::MAX, 0, 0]; + for y in 0..h { + for (x, &v) in rows[y * pitch..y * pitch + w].iter().enumerate() { + values[usize::from(v)] += 1; + for (bit, count) in bits.iter_mut().enumerate() { + *count += u32::from(v >> bit & 1); + } + if v & 8 != 0 { + inside = [ + inside[0].min(x as u32), + inside[1].min(y as u32), + inside[2].max(x as u32), + inside[3].max(y as u32), + ]; + } + } + } + let mut most: Vec<(usize, u32)> = values + .iter() + .copied() + .enumerate() + .filter(|v| v.1 != 0) + .collect(); + most.sort_by_key(|v| std::cmp::Reverse(v.1)); + most.truncate(16); + tracing::info!( + frame, + ?resource, + width = w, + height = h, + values = ?most, + texels_with_bit = ?bits, + bit3_box = ?inside, + "stencil plane values (value, texels)" + ); + buffer.Unmap(0, None); + } +} + fn half(h: u16) -> f32 { let (sign, exp, man) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32); let v = match exp { @@ -564,6 +649,42 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option } let nonzero_bits_percent = set as f32 * 100.0 / (w * h).max(1) as f32; tracing::info!(format, nonzero_bits_percent, packed_high, "target values as packed light"); + // The same words as plain numbers, by class. Tables of indices and + // masks say nothing as floats or as packed light: in the title's + // shadow-mask table 0 is a block in full shadow, a word up to 255 + // one value for the block, above that a block of the atlas, and all + // ones a texel never written. + let mut classes = [0usize; 6]; + let mut highest_below_ones = 0u32; + for y in 0..h { + for x in 0..w { + let v = u32_at(px(x, y, 4), 0); + classes[match v { + 0 => 0, + 1..=15 => 1, + 16..=255 => 2, + 256..=0x00ff_ffff => 3, + u32::MAX => 5, + _ => 4, + }] += 1; + if v != u32::MAX { + highest_below_ones = highest_below_ones.max(v); + } + } + } + tracing::info!( + format, + width = w, + height = h, + zero = classes[0], + one_to_15 = classes[1], + to_255 = classes[2], + to_24_bits = classes[3], + larger = classes[4], + all_ones = classes[5], + highest_below_ones, + "target values as words" + ); } // Float colours (scene light) go through a cube root: scaled linearly, // a night scene under one lamp of 50 units came out all black. diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index cdc988d..cc061c7 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1860,6 +1860,30 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { View::Shader(resource, desc) => { let resource = *resource as crate::object::This; if let Some(texture) = crate::resource::host_resource(resource) { + // The title's views of textures with a stencil plane, as it + // describes them (format, dimension, component mapping, a + // pad, then first level, levels, plane): each distinct one + // once. They say how its shaders read the stencil plane + // (the lighting takes each pixel's material class and its + // "inside a room" bit from it). + #[cfg(feature = "diagnostics")] + { + // SAFETY: a live resource. + let own = unsafe { texture.GetDesc() }.Format.0; + if matches!(own, 19..=22 | 44..=47) { + static SEEN: Mutex)>> = Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if seen.len() < 64 && !seen.contains(&(own, *desc)) { + seen.push((own, *desc)); + tracing::info!( + ?resource, + texture_format = own, + view = ?desc, + "shader view of a depth-stencil texture" + ); + } + } + } let mut desc = desc.as_ref().map(srv_desc); if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { return None; diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index e54767f..e57876e 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -85,6 +85,18 @@ impl Host { let adapter: IDXGIAdapter = factory.EnumWarpAdapter().map_err(err)?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?; } else { + // A machine without a graphics card gives the software + // adapter as its default one (a hosted test runner): that + // is no hardware device, and the tests that ask for one + // skip it, as they do where there is none. + let factory: IDXGIFactory4 = + CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(err)?; + if let Ok(first) = factory.EnumAdapters1(0) + && let Ok(desc) = first.GetDesc1() + && desc.Flags & 2 != 0 + { + return Err("the default adapter is a software adapter".to_owned()); + } D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?; } let device = device.ok_or("no device")?; From 342245e15221fc15dbf504ece1a7b57428437a9a Mon Sep 17 00:00:00 2001 From: Noname0202 Date: Tue, 24 Nov 2026 20:26:47 +0100 Subject: [PATCH 117/445] Shaders: lower v_cvt_f32_f64 in 32-bit IEEE-754 integer arithmetic --- crates/victory-shader/src/emit/lower.rs | 159 +++++++++++++++++++ crates/victory-shader/src/emit/valu_tests.rs | 89 +++++++++++ 2 files changed, 248 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 1454136..a14f5b4 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6994,6 +6994,12 @@ impl<'a> Lower<'a> { let r = self.s.m.cast(c, op, a, self.s.t.f32); float(self, r) } + "v_cvt_f32_f64" => { + let (lo, hi) = self.f64_pair(inst, 0)?; + let bits = self.f64_to_f32_bits(lo, hi); + let r = self.as_float(bits); + float(self, r) + } "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { // Each source is f32, or with op_sel_hi the low (op_sel: high) // f16 half; neg_hi is the absolute value here. @@ -7344,6 +7350,159 @@ impl<'a> Lower<'a> { } } + /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying + /// `abs` and `neg` input modifiers on operand `k`. + fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.sdwa.is_some() || v.dpp.is_some() { + return Err("64-bit operand modifiers"); + } + let op = *v.src.get(k).ok_or("a missing operand")?; + let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> { + let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?; + let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?; + Ok((lo, hi)) + }; + let (lo, mut hi) = match op { + Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?, + Operand::Scalar { code, .. } if code != NULL => { + pair(self, Reg::S(code), Reg::S(code + 1))? + } + Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)), + Operand::Const(c @ 240..=248) => { + const INLINE_F64: [f64; 9] = [ + 0.5, + -0.5, + 1.0, + -1.0, + 2.0, + -2.0, + 4.0, + -4.0, + 1.0 / std::f64::consts::TAU, + ]; + let bits = INLINE_F64[(c - 240) as usize].to_bits(); + (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32)) + } + // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand. + Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)), + _ => return Err("a 64-bit float operand"), + }; + let c = self.cur; + if v.abs >> k & 1 != 0 { + let mask = self.s.m.i32(0x7FFF_FFFF); + hi = self.s.m.bin(c, Bin::And, hi, mask); + } + if v.neg >> k & 1 != 0 { + let sign = self.s.m.i32(0x8000_0000); + hi = self.s.m.bin(c, Bin::Xor, hi, sign); + } + Ok((lo, hi)) + } + + /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even, + /// without requiring host `DOUBLES` (`f64`) support. + fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let k0 = self.s.m.i32(0); + let k1 = self.s.m.i32(1); + let sign_mask = self.s.m.i32(0x8000_0000); + let sign = self.s.m.bin(c, Bin::And, hi, sign_mask); + + let k20 = self.s.m.i32(20); + let k7ff = self.s.m.i32(0x7FF); + let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20); + let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff); + + let frac_mask = self.s.m.i32(0x000F_FFFF); + let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask); + let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo); + let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0); + + let k3 = self.s.m.i32(3); + let k29 = self.s.m.i32(29); + let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3); + let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29); + let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo); + + let rem_mask = self.s.m.i32(0x1FFF_FFFF); + let rem = self.s.m.bin(c, Bin::And, lo, rem_mask); + let half_rem = self.s.m.i32(0x1000_0000); + let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem); + let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem); + let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1); + let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0); + let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd); + let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up); + let norm_inc = self.s.m.select(c, norm_round, k1, k0); + + // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254]. + let k896 = self.s.m.i32(896); + let k23 = self.s.m.i32(23); + let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896); + let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23); + let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23); + let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc); + let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body); + + // Subnormal range: exp64 in [874, 896] -> shift in [1, 23]. + let k897 = self.s.m.i32(897); + let k32 = self.s.m.i32(32); + let k31 = self.s.m.i32(31); + let imp = self.s.m.i32(0x0080_0000); + let sig24 = self.s.m.bin(c, Bin::Or, imp, m23); + let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64); + // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch. + let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1); + let shift = self.s.m.select(c, lt1, k1, raw_shift); + let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23); + let shift = self.s.m.select(c, gt23, k23, shift); + let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift); + let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift); + let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift); + let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31); + let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0); + let low31 = self.s.m.i32(0x7FFF_FFFF); + let lost_lo = self.s.m.bin(c, Bin::And, lost, low31); + let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem); + let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0); + let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1); + let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0); + let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd); + let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie); + let sub_inc = self.s.m.select(c, sub_round, k1, k0); + let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc); + let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body); + + // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1). + let k873 = self.s.m.i32(873); + let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873); + let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz); + let min_bit = self.s.m.select(c, round_min, k1, k0); + let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit); + + // Overflow / Inf / NaN: exp64 >= 1151. + let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff); + let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz); + let inf_bits = self.s.m.i32(0x7F80_0000); + let qnan_bits = self.s.m.i32(0x7FC0_0000); + let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23); + let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits); + let over_res = self.s.m.bin(c, Bin::Or, sign, over_body); + + // Select final result by exponent range. + let k874 = self.s.m.i32(874); + let k1151 = self.s.m.i32(1151); + let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874); + let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897); + let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151); + let r = self.s.m.select(c, is_over, over_res, norm_res); + let r = self.s.m.select(c, is_sub, sub_res, r); + self.s.m.select(c, is_under, under_res, r) + } + fn join64(&mut self, lo: V, hi: V) -> V { let c = self.cur; let ty = self.s.m.int(64); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index fe98439..930d1b6 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -1259,3 +1259,92 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +#[test] +fn v_cvt_f32_f64_matches_ieee754() { + // v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x00f -> VOP3 opcode 0x18f). + let plain = build_valu_cs(&[vop1(0x00f, 0, vgpr(1))]); + // Same with abs + neg on src0 (VOP3: abs[0] = bit 8 of w0, neg[0] = bit 29 of w1). + let [mut w0, mut w1] = vop3(0x18f, 0, vgpr(1), 0, 0); + w0 |= 1 << 8; + w1 |= 1 << 29; + let neg_abs = build_valu_cs(&[w0, w1]); + + let values: &[f64] = &[ + 0.0, + -0.0, + 1.0, + -1.0, + 3.5, + -123456.75, + // Tie-to-even: even mantissa stays, odd mantissa rounds up. + f64::from_bits(0x3FF0_0000_1000_0000), // 1.0 + 0.5 ulp(f32) -> 1.0 + f64::from_bits(0x3FF0_0000_3000_0000), // (1.0 + 1 ulp) + 0.5 ulp -> 1.0 + 2 ulp + f64::from_bits(0x3FF0_0000_1000_0001), // > 0.5 ulp -> rounds up + // Largest finite f32 and overflow to +Inf / -Inf. + f64::from(f32::MAX), + f64::from(f32::MAX) * 1.000_001, + -f64::from(f32::MAX) * 1.000_001, + 1e300, + // Subnormal range (exp64 in [874, 896]), including carry into smallest normal. + f64::from(f32::MIN_POSITIVE), + f64::from(f32::MIN_POSITIVE) * 0.5, + f64::from(f32::MIN_POSITIVE) * 0.75, + f64::from(f32::from_bits(0x007F_FFFF)), + f64::from_bits(0x380F_FFFF_F000_0000), // max subnormal + 0.5 ulp -> min normal + // exp64 == 873: exact 2^-150 ties to 0; strictly greater rounds to min subnormal (1). + f64::from_bits(0x3690_0000_0000_0000), + f64::from_bits(0x3690_0000_0000_0001), + f64::from_bits(0xB690_0000_0000_0001), + // Deep underflow -> +/-0.0. + 1e-200, + -1e-200, + // Infinities and NaNs. + f64::INFINITY, + f64::NEG_INFINITY, + f64::from_bits(0x7FF8_0000_0000_0000), // +qNaN + f64::from_bits(0x7FF0_0000_0000_0001), // +sNaN -> quieted + ]; + let inputs: Vec<[u32; 4]> = values + .iter() + .map(|&x| { + let b = x.to_bits(); + [b as u32, (b >> 32) as u32, 0, 0] + }) + .collect(); + run_cases(&plain, &inputs, |backend, i, _, got| { + let x = values[i]; + let want = (x as f32).to_bits(); + if x.is_nan() { + assert!( + f32::from_bits(got).is_nan() && (got & 0x0040_0000) != 0, + "{backend}: v_cvt_f32_f64({:#018x}) = {got:#010x}, expected qNaN", + x.to_bits(), + ); + } else { + assert_eq!( + got, want, + "{backend}: v_cvt_f32_f64({x} / {:#018x}) = {got:#010x}, want {want:#010x}", + x.to_bits(), + ); + } + }); + + // -|x| via VOP3 abs + neg modifiers. + let mod_values: &[f64] = &[2.5, -2.5, 0.0, f64::INFINITY]; + let mod_in: Vec<[u32; 4]> = mod_values + .iter() + .map(|&x| { + let b = x.to_bits(); + [b as u32, (b >> 32) as u32, 0, 0] + }) + .collect(); + run_cases(&neg_abs, &mod_in, |backend, i, _, got| { + let x = mod_values[i]; + let want = (-(x.abs()) as f32).to_bits(); + assert_eq!( + got, want, + "{backend}: v_cvt_f32_f64(-|{x}|) = {got:#010x}, want {want:#010x}", + ); + }); +} From e9765a73a68a75536b1c10ad5ef746d7f6ec0bcc Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:30:28 -0500 Subject: [PATCH 118/445] Fix the device loss introduced by the wave64 update The update moved the particle light-atlas compute programs to a form that puts group barriers inside branches and loops; a dispatch of them stood on the card until the device was reset. That form is now off unless VICTORY_WAVE_WIDE=1, and the shader cache key includes the wave switches. Checked with a plain run of this tree on the test machine. Co-Authored-By: Claude Fable 5.2 --- README.md | 2 +- crates/victory-gpu/src/shader_cache.rs | 17 +++++++++++++++++ crates/victory-shader/src/emit/mod.rs | 7 ++++++- 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b03abd2..c6d8e02 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, | First gameplay scene (the prologue) | renders: characters, textures, sky, sunlit exterior; HUD, pause menu and pad input work | | Light in shadow | missing: the game's ray-traced bounce light and ray-traced lamp and sun shadows do not run yet, so anything the sun does not hit directly is black | | Frame rate in the world | 2-4 fps: 420-450 ms per frame by default, 240-350 ms with the newer switches (`VICTORY_RELAY=2`, or `VICTORY_LATE_WAIT=3 VICTORY_WIDE_BACK=1 VICTORY_CARD_BUFFERS_MIN_MB=1 VICTORY_CARD_BUFFERS_MB=1024`); it started at 3-6 seconds per frame | -| Stability | **the newest commits lose the GPU device shortly after start on the test machine (4 of 4 runs), cause not yet found; the last tree that ran clean is the first commit of this fork, `578d459`** | +| Stability | no driver hang or device loss in normal runs (a hang introduced by the wave64 update was found and fixed: its barrier form for 64-lane programs is now off unless `VICTORY_WAVE_WIDE=1`) | ### What this fork changed (summary) diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 082f42e..4d92144 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -56,6 +56,23 @@ fn build() -> &'static [u8; 32] { bytes.extend_from_slice(&limit.to_le_bytes()); // Which group barriers wait is part of the translation too. bytes.push(victory_shader::emit::group_sync()); + // So are the switches that pick the form of a wave64 program: + // without them here a run with `VICTORY_WAVE_WIDE=0` was + // served the translations an earlier run of the same + // executable had cached with the switch unset. + for name in [ + "VICTORY_WAVE_WIDE", + "VICTORY_WAVE_DEEP_SKIPS", + "VICTORY_WAVE_OWN_BITS", + "VICTORY_F16_NEAREST", + ] { + bytes.extend_from_slice(name.as_bytes()); + bytes.push(b'='); + if let Some(value) = std::env::var_os(name) { + bytes.extend_from_slice(value.as_encoded_bytes()); + } + bytes.push(0); + } *blake3::hash(&bytes).as_bytes() } Err(e) => { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 423fb54..1b90d57 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -341,7 +341,12 @@ pub fn emit( } } } - let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0"); + // Off unless asked for (`VICTORY_WAVE_WIDE=1`), for a console wave run as two host + // waves: this form puts group barriers inside branches and loops, and runs 121-124 + // lost the card in a submission of two programs that had just moved to it + // (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which + // has no barrier, stays on. + let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_some_and(|v| v == "1"); // exact first: each host wave on its own where that is exact (the idiom, every // form; no barriers), then the other exact forms; then approximate for exact in [true, false] { From 7b0f736d0b29c2c512a9506e38df92f1f8d50986 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:32:07 -0500 Subject: [PATCH 119/445] Shader tests: recognise the software adapter from the device's own adapter Hosted runners list a display stub first, so the default device there is the software adapter; the tests that need a real card now skip it. Co-Authored-By: Claude Fable 5.2 --- crates/victory-shader/src/emit/host.rs | 27 ++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index e57876e..8f5407a 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -85,19 +85,22 @@ impl Host { let adapter: IDXGIAdapter = factory.EnumWarpAdapter().map_err(err)?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?; } else { - // A machine without a graphics card gives the software - // adapter as its default one (a hosted test runner): that - // is no hardware device, and the tests that ask for one - // skip it, as they do where there is none. - let factory: IDXGIFactory4 = - CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(err)?; - if let Ok(first) = factory.EnumAdapters1(0) - && let Ok(desc) = first.GetDesc1() - && desc.Flags & 2 != 0 - { - return Err("the default adapter is a software adapter".to_owned()); - } D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?; + // A machine without a graphics card gives the software + // adapter as its default device (a hosted test runner, + // whose first adapter is a display stub that cannot make a + // device): that is no hardware device, and the tests that + // ask for one skip it, as they do where there is none. + if let Some(made) = &device { + let factory: IDXGIFactory4 = + CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(err)?; + if let Ok(adapter) = factory.EnumAdapterByLuid::(made.GetAdapterLuid()) + && let Ok(desc) = adapter.GetDesc1() + && (desc.Flags & 2 != 0 || (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)) + { + return Err("the default device is the software adapter".to_owned()); + } + } } let device = device.ok_or("no device")?; let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL { From b17b69fd9e93ac233423838edd5cf24d76af49e0 Mon Sep 17 00:00:00 2001 From: Noname0202 Date: Tue, 24 Nov 2026 20:39:19 +0100 Subject: [PATCH 120/445] Shaders: model v_add_f64 whole-wave sums and s_mov_b32 copies --- crates/victory-shader/src/emit/bitcode.rs | 5 + crates/victory-shader/src/emit/lower.rs | 71 ++++++++ crates/victory-shader/src/emit/shader.rs | 4 + crates/victory-shader/src/emit/valu_tests.rs | 165 ++++++++++++++++++ crates/victory-shader/src/emit/wave.rs | 166 ++++++++++++++++++- 5 files changed, 410 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 13b54af..10b6da6 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -15,6 +15,7 @@ enum TypeDef { Void, Int(u32), Float, + Double, /// Pointee and address space. Ptr(Ty, u32), Struct(Option, Vec), @@ -230,6 +231,9 @@ impl Module { pub fn float(&mut self) -> Ty { self.ty(TypeDef::Float) } + pub fn double(&mut self) -> Ty { + self.ty(TypeDef::Double) + } pub fn ptr(&mut self, to: Ty) -> Ty { self.ty(TypeDef::Ptr(to, 0)) } @@ -551,6 +555,7 @@ impl Module { match t { TypeDef::Void => w.record(2, &[]), TypeDef::Float => w.record(3, &[]), + TypeDef::Double => w.record(4, &[]), TypeDef::Int(b) => w.record(7, &[u64::from(*b)]), TypeDef::Ptr(p, space) => w.record(8, &[u64::from(p.0), u64::from(*space)]), TypeDef::Array(n, e) => w.record(11, &[u64::from(*n), u64::from(e.0)]), diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index a14f5b4..2afe637 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1781,6 +1781,9 @@ impl<'a> Lower<'a> { Shape::K(k) => return Ok(self.s.m.i32(k)), Shape::Value(v) => return self.i32_of(v), Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None), + Shape::ActiveF64(lo, hi, mask, high) => { + return self.active_f64_sum(lo, hi, mask, high); + } Shape::Masked(src, mask, ident) => { let c = self.cur; let &m = self @@ -1946,6 +1949,74 @@ impl<'a> Lower<'a> { Ok(if float { self.as_int(r) } else { r }) } + /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere), + /// returning the low (`!high`) or high (`high`) 32-bit word. + fn active_f64_sum( + &mut self, + lo: Value, + hi: Value, + mask: Value, + high: bool, + ) -> Result { + if self.mask_data == MaskData::None { + return Err("a wave reduction in a mesh shader"); + } + let c = self.cur; + let &m = self + .x + .st + .masks + .get(&mask) + .ok_or("a wave reduction's untracked mask")?; + let on = self.boolean(m, c)?; + let lo = self.i32_of(lo)?; + let hi = self.i32_of(hi)?; + let z = self.s.m.i32(0); + let lo = self.s.m.select(c, on, lo, z); + let hi = self.s.m.select(c, on, hi, z); + self.s.flags |= flags::WAVE_OPS | flags::DOUBLES; + let f64t = self.s.m.double(); + let i32t = self.s.t.i32; + let split_ty = self + .s + .m + .named_struct("dx.types.splitdouble", vec![i32t, i32t]); + let arg = self + .s + .op(c, "makeDouble", Attr::ReadNone, f64t, 101, &[lo, hi]); + let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0)); + let sum = self + .s + .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]); + let split = self + .s + .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]); + let mut r_lo = self.s.m.extract(c, split, 0); + let mut r_hi = self.s.m.extract(c, split, 1); + if self.exchange.is_some() { + if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); + return Err("a wave reduction where not every lane runs"); + } + let (lo0, lo1) = self.exchange_halves(self.cur, r_lo); + let (hi0, hi1) = self.exchange_halves(self.cur, r_hi); + let c = self.cur; + let d0 = self + .s + .op(c, "makeDouble", Attr::ReadNone, f64t, 101, &[lo0, hi0]); + let d1 = self + .s + .op(c, "makeDouble", Attr::ReadNone, f64t, 101, &[lo1, hi1]); + let total = self.s.m.bin(c, Bin::Add, d0, d1); + let split = self + .s + .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]); + r_lo = self.s.m.extract(c, split, 0); + r_hi = self.s.m.extract(c, split, 1); + } + Ok(if high { r_hi } else { r_lo }) + } + /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's /// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest /// ([`Self::f16_nearest`]). diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index fe257db..25bff73 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -73,6 +73,7 @@ pub const USER_VIEW_BIAS: u32 = 0x103; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { pub const RAW_BUFFERS: u64 = 1 << 4; + pub const DOUBLES: u64 = 1 << 5; pub const STENCIL_REF: u64 = 1 << 11; pub const TYPED_UAV_LOADS: u64 = 1 << 13; pub const WAVE_OPS: u64 = 1 << 19; @@ -747,6 +748,9 @@ impl Shader { dxil.extend(&bitcode); let mut features = 0u64; + if self.flags & flags::DOUBLES != 0 { + features |= 0x1; + } 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 930d1b6..5aae9c1 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -1348,3 +1348,168 @@ fn v_cvt_f32_f64_matches_ieee754() { ); }); } + +#[test] +fn whole_wave_f64_sum_and_cvt_f32_f64() { + let s_or_saveexec_b32 = + |sdst: u8, src0: u8| 0xBE80_0000 | (sdst as u32) << 16 | 0x3D << 8 | src0 as u32; + let v_mov_dpp8 = |vdst: u8, vsrc: u8, sel: u32| [vop1(0x001, vdst, 0xE9), vsrc as u32 | (sel << 8)]; + let v_mov_row_mirror = |vdst: u8, vsrc: u8| { + [ + vop1(0x001, vdst, 0xFA), + vsrc as u32 | (0x140 << 8) | (1 << 19) | (0xF << 24) | (0xF << 28), + ] + }; + + let mut words = Vec::new(); + words.push(s_mov_b32(5, 0x80)); + words.extend_from_slice(&s_load_dwordx4(8, 4)); + // Per-lane f64 input in v[6:7] = (s0, s1). + words.push(vop1(0x001, 6, sgpr(0))); + words.push(vop1(0x001, 7, sgpr(1))); + // Whole-wave f64 sum over Wave32 with s_mov_b32 copy before EXEC restore. + words.push(s_or_saveexec_b32(12, 0xC1)); + words.extend_from_slice(&vop3(0x101, 2, 0x80, vgpr(6), sgpr(12))); + words.extend_from_slice(&vop3(0x101, 3, 0x80, vgpr(7), sgpr(12))); + for sel in [14570689u32, 9658386, 2340] { + words.extend_from_slice(&v_mov_dpp8(4, 2, sel)); + words.extend_from_slice(&v_mov_dpp8(5, 3, sel)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); // v_add_f64 + } + words.extend_from_slice(&v_mov_row_mirror(4, 2)); + words.extend_from_slice(&v_mov_row_mirror(5, 3)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); + words.extend_from_slice(&vop3(0x378, 4, vgpr(2), 0x80, 0x80)); // v_permlanex16_b32 + words.extend_from_slice(&vop3(0x378, 5, vgpr(3), 0x80, 0x80)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); + words.extend_from_slice(&vop3(0x360, 14, vgpr(2), 0x80, 0)); // v_readlane_b32 s14, v2, 0 + words.extend_from_slice(&vop3(0x360, 15, vgpr(3), 0x80, 0)); // v_readlane_b32 s15, v3, 0 + words.push(s_mov_b32(16, 14)); + words.push(s_mov_b32(17, 15)); + words.push(s_mov_b32(126, 12)); // restore exec_lo + words.push(vop1(0x00f, 0, sgpr(16))); // v_cvt_f32_f64 v0, s[16:17] + words.extend_from_slice(&buffer_store_dword(0, 8, 0)); + words.push(S_ENDPGM); + + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 12, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [4, 1, 1], + }), + code, + }; + + 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)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: Vec::new(), + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + + let cases: &[(f64, f32)] = &[(1.25, 5.0), (-0.75, -3.0)]; + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + continue; + }; + let (root, pso) = match host.compute_pipeline(&shader) { + Ok(p) => p, + // WARP does not support fixed WaveSize(32) on SM 6.6. + Err(e) if warp => { + eprintln!("{label}: compute_pipeline skipped ({e})"); + continue; + } + Err(e) => panic!("{label}: compute_pipeline failed: {e}"), + }; + for &(x, want) in cases { + let b = x.to_bits(); + let inputs = [b as u32, (b >> 32) as u32, 0, 0]; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.slot) { + (RootType::Constants, 0) => inputs[u.dword as usize], + (RootType::Table, 1) => 0, + other => panic!("unexpected user data {other:?}"), + }; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!( + out[0][0], + want.to_bits(), + "{label}: wave f64 sum({x}) = {:#010x}, want {:#010x}", + out[0][0], + want.to_bits(), + ); + } + } +} diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs index c74e083..1d7a91b 100644 --- a/crates/victory-shader/src/emit/wave.rs +++ b/crates/victory-shader/src/emit/wave.rs @@ -112,6 +112,15 @@ pub(crate) enum Sym { ident: u32, lanes: u64, }, + /// Low (`!high`) or high (`high`) 32 bits of the 64-bit float sum over + /// `lanes` of `mask ? f64(lo, hi) : 0.0`. + Red64F { + lo: Value, + hi: Value, + mask: Value, + lanes: u64, + high: bool, + }, } /// What a value a section leaves holds in every lane. @@ -123,6 +132,8 @@ pub(crate) enum Shape { Masked(Value, Value, u32), /// `op` over every lane. Active(Op, Value, Value, u32), + /// Low (`!high`) or high (`high`) 32 bits of the 64-bit float sum over every lane. + ActiveF64(Value, Value, Value, bool), /// `op` over the lanes below (`inclusive`: and including) each lane. Prefix(Op, Value, Value, u32, bool), } @@ -298,13 +309,28 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { exec = ((exec & 0xFFFF_FFFF) | ((k & 0xFFFF_FFFF) << 32)) & all; continue; } - if let Fields::Sop { src, .. } = &inst.fields { + if let Fields::Sop { dst, src, .. } = &inst.fields { if name.starts_with("s_and_b") && src.iter().any(|o| matches!(*o, Operand::Scalar { code, .. } if inst.read(Reg::S(code)).is_some_and(|v| masked.contains(&v)))) && let Some(&(_, w)) = inst.writes.iter().find(|w| matches!(w.0, Reg::S(_))) { masked.push(w); } + if name == "s_mov_b32" + && let (Some(Operand::Scalar { code: dc, .. }), Some(s0)) = (dst, src.first()) + && *dc != NULL + && let Some(w) = inst.write(Reg::S(*dc)) + { + let sym = match *s0 { + Operand::Scalar { code, .. } if code != NULL => inst + .read(Reg::S(code)) + .map_or(Sym::Unknown, |x| uni.get(&x).copied().unwrap_or(Sym::Uni(x))), + Operand::Const(c) => crate::resource::inline(c).map_or(Sym::Unknown, Sym::K), + Operand::Literal(x) => Sym::K(x), + _ => Sym::Unknown, + }; + uni.insert(w, sym); + } for &(_, w) in &inst.writes { uni.entry(w).or_insert(Sym::Unknown); } @@ -359,6 +385,130 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { } continue; } + if name == "v_add_f64" + && !modifiers + && v.dpp.is_none() + && let Some(Operand::Vector { reg: dreg, .. }) = v.dst + && let (Some(dst_lo), Some(dst_hi)) = + (inst.write(Reg::V(dreg)), inst.write(Reg::V(dreg + 1))) + { + let pair_lanes = |op: Option<&Operand>| -> Option<(Vec, Vec)> { + match *op? { + Operand::Vector { reg, .. } => Some(( + lanes(&Operand::Vector { reg, dwords: 1 }, &vec, &uni), + lanes( + &Operand::Vector { + reg: reg + 1, + dwords: 1, + }, + &vec, + &uni, + ), + )), + Operand::Scalar { code, .. } if code != NULL => Some(( + lanes(&Operand::Scalar { code, dwords: 1 }, &vec, &uni), + lanes( + &Operand::Scalar { + code: code + 1, + dwords: 1, + }, + &vec, + &uni, + ), + )), + _ => None, + } + }; + let old_lo = lanes( + &Operand::Vector { + reg: dreg, + dwords: 1, + }, + &vec, + &uni, + ); + let old_hi = lanes( + &Operand::Vector { + reg: dreg + 1, + dwords: 1, + }, + &vec, + &uni, + ); + let f64_term = |lo_s: Sym, hi_s: Sym| -> Option<(Value, Value, Value, u64)> { + match (lo_s, hi_s) { + ( + Sym::Red { + op: None, + src: lo, + mask: ml, + ident: 0, + lanes: ll, + }, + Sym::Red { + op: None, + src: hi, + mask: mh, + ident: 0, + lanes: lh, + }, + ) if ml == mh && ll == lh => Some((lo, hi, ml, ll)), + ( + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: l1, + high: false, + }, + Sym::Red64F { + lo: lo2, + hi: hi2, + mask: m2, + lanes: l2, + high: true, + }, + ) if (lo1, hi1, m1, l1) == (lo2, hi2, m2, l2) => Some((lo1, hi1, m1, l1)), + _ => None, + } + }; + let mut out_lo = vec![Sym::Unknown; wave as usize]; + let mut out_hi = vec![Sym::Unknown; wave as usize]; + if let (Some((alo, ahi)), Some((blo, bhi))) = + (pair_lanes(v.src.first()), pair_lanes(v.src.get(1))) + { + for l in 0..wave as usize { + let (rl, rh) = match (f64_term(alo[l], ahi[l]), f64_term(blo[l], bhi[l])) { + (Some((lo1, hi1, m1, la)), Some((lo2, hi2, m2, lb))) + if (lo1, hi1, m1) == (lo2, hi2, m2) && la & lb == 0 => + { + ( + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: la | lb, + high: false, + }, + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: la | lb, + high: true, + }, + ) + } + _ => (Sym::Unknown, Sym::Unknown), + }; + out_lo[l] = if exec >> l & 1 != 0 { rl } else { old_lo[l] }; + out_hi[l] = if exec >> l & 1 != 0 { rh } else { old_hi[l] }; + } + } + vec.insert(dst_lo, out_lo); + vec.insert(dst_hi, out_hi); + continue; + } let Some(Operand::Vector { reg: dreg, .. }) = v.dst else { for &(_, w) in &inst.writes { uni.insert(w, Sym::Unknown); @@ -560,6 +710,13 @@ fn shapes( ident, lanes, } if lanes == all => Some(Shape::Active(op, src, mask, ident)), + Sym::Red64F { + lo, + hi, + mask, + lanes, + high, + } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), _ => None, }; for (v, s) in uni { @@ -603,6 +760,13 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option { ident, lanes, } if lanes == all => Some(Shape::Active(op, src, mask, ident)), + Sym::Red64F { + lo, + hi, + mask, + lanes, + high, + } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), _ => None, }; } From 04512df483254d9e83a36f0bad1a4508232a6bee Mon Sep 17 00:00:00 2001 From: warmooff-ops Date: Tue, 24 Nov 2026 21:12:31 +0100 Subject: [PATCH 121/445] hle/gameinput: increase reading history from 32 to 256 for low-FPS frames --- crates/victory-hle/src/modules/gameinput.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index a45081e..f50c5e3 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -58,7 +58,7 @@ const KEYBOARD: usize = PADS + 1; const DEVICES: usize = PADS + 2; /// Readings kept per device for next/previous lookups. -const HISTORY: usize = 32; +const HISTORY: usize = 256; const POLL: Duration = Duration::from_millis(8); /// The keyboard's stand-in gamepad (virtual key, button); README lists it. From 16849898f3282c4a7189b1557289c194bc720052 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:13:27 -0500 Subject: [PATCH 122/445] Shader clean-up passes; a test that needs a card skips without one - Clean-up passes over each translated module (VICTORY_SHADER_OPT bits: dead code, folding, reuse, branch facts, loads within a block, wave64 first-lane exchange), part of the shader cache key. About 43 % fewer host instructions over the pack; about 20 ms less GPU time per frame on the test machine. - translate: a census of the emitted code. - Checked with plain game runs of this tree on the test machine. Co-Authored-By: Claude Fable 5.2 --- README.md | 4 +- apps/victory/src/translate.rs | 46 + crates/victory-gpu/src/shader_cache.rs | 2 + crates/victory-shader/src/emit/bitcode.rs | 27 + .../victory-shader/src/emit/bitcode/census.rs | 174 ++ crates/victory-shader/src/emit/bitcode/opt.rs | 2136 +++++++++++++++++ crates/victory-shader/src/emit/lower.rs | 44 +- crates/victory-shader/src/emit/mod.rs | 44 + crates/victory-shader/src/emit/shader.rs | 29 +- crates/victory-shader/src/emit/valu_tests.rs | 5 + 10 files changed, 2495 insertions(+), 16 deletions(-) create mode 100644 crates/victory-shader/src/emit/bitcode/census.rs create mode 100644 crates/victory-shader/src/emit/bitcode/opt.rs diff --git a/README.md b/README.md index c6d8e02..c00d992 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Take-Two Interactive. ## Status of this fork (2026-11-25) -**Not playable yet: 2 to 4 frames per second, and shadowed areas are black.** +**Not playable yet: 2.5 to 4 frames per second, and shadowed areas are black.** Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, 32 GB RAM. The Series X profile is used throughout. @@ -58,6 +58,8 @@ Speed and memory: - The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory. - An intermittent device loss was traced to the pipeline library file being replaced while mapped; fixed. +- Translated shaders get clean-up passes over the finished module (dead code, constant folding, reuse of values, branch facts); the pack's host instruction count falls by about 43 %, worth about 20 ms of GPU time per frame on the test machine (`VICTORY_SHADER_OPT=0` turns them off). + Most of the newer speed changes sit behind environment switches that are off by default (`VICTORY_LATE_WAIT`, `VICTORY_RELAY`, `VICTORY_WIDE_BACK`, `VICTORY_CARD_BUFFERS_MIN_MB`, `VICTORY_INPLACE`, `VICTORY_BVH_BUILDER`, ...). diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index f03af00..dc5d6c8 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -440,6 +440,7 @@ fn translate_programs(container: &Container, programs: Vec, examp *counter(t, p.stage, 0) += 1; match emit::emit(container, &p, &program, &s, &i, &r) { Ok(shader) => { + census_line(&label(), &p, &program, &shader); *counter(t, p.stage, 1) += 1; check(shader, t, checks, label); } @@ -462,6 +463,51 @@ fn translate_programs(container: &Container, programs: Vec, examp } } +/// `VICTORY_SHADER_CENSUS=`: one line per emitted program, appended: +/// its label, the console program's instructions by encoding class (a +/// static count of the whole program, not of one thread's path), and the +/// host module's instructions by kind (`emit::census::KINDS`). +fn census_line(label: &str, native: &NativeProgram, p: &ir::Program, shader: &emit::HostShader) { + use std::io::Write; + use victory_shader::gfx10::Fields; + static OUT: std::sync::OnceLock>> = std::sync::OnceLock::new(); + let Some(out) = OUT.get_or_init(|| { + let path = std::env::var_os("VICTORY_SHADER_CENSUS")?; + let file = std::fs::OpenOptions::new().create(true).append(true).open(path).ok()?; + Some(Mutex::new(file)) + }) else { + return; + }; + let Some(census) = emit::census::take(&shader.dxil) else { + return; + }; + // total, vector, scalar, descriptor loads, buffer and memory, image, LDS, control, other + let mut console = [0u32; 9]; + for inst in p.blocks.iter().flat_map(|b| &b.insts) { + console[0] += 1; + let k = match &inst.fields { + Fields::Valu(_) => 1, + Fields::Sop { .. } => 2, + Fields::Smem { .. } => 3, + Fields::Buffer { .. } | Fields::Flat { .. } => 4, + Fields::Image { .. } => 5, + Fields::Ds { .. } => 6, + Fields::Sopp { .. } => 7, + _ => 8, + }; + console[k] += 1; + } + let mut line = format!("{label}\twave64={}", u8::from(native.wave64)); + for (name, n) in ["c_total", "c_valu", "c_sop", "c_smem", "c_buffer", "c_image", "c_ds", "c_sopp", "c_other"].iter().zip(console) { + line.push_str(&format!("\t{name}={n}")); + } + for (name, n) in emit::census::KINDS.iter().zip(census.counts) { + line.push_str(&format!("\t{name}={n}")); + } + line.push('\n'); + let _ = lock(out).write_all(line.as_bytes()); +} + /// Validates an emitted shader if asked to. fn check( mut shader: emit::HostShader, diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 4d92144..eabd0f3 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -73,6 +73,8 @@ fn build() -> &'static [u8; 32] { } bytes.push(0); } + // And which clean-up passes ran over the translated code. + bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes()); *blake3::hash(&bytes).as_bytes() } Err(e) => { diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 13b54af..40b0883 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -7,9 +7,24 @@ use std::collections::HashMap; +pub mod census; +pub mod opt; + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub(crate) struct Ty(u32); +/// What the lowering made an instruction for, where it says so (counted by +/// [`census`], nothing else reads it). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Tag { + /// The select that keeps a register's old value in lanes a guard masks. + Guard, + /// An index clamp the translation adds (the console has none). + Clamp, + /// The iteration counter and limit test the translation adds to a loop. + Counter, +} + #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum TypeDef { Void, @@ -208,6 +223,8 @@ pub(crate) struct Module { blocks: Vec, mds: Vec, named: Vec<(String, Vec)>, + /// See [`Tag`]: by instruction. + tags: HashMap, } impl Module { @@ -355,6 +372,16 @@ impl Module { g } + /// Notes what instruction `v` is for (see [`Tag`]); only when modules + /// are counted. + pub fn tag(&mut self, v: V, tag: Tag) { + if let V::Inst(i) = v + && census::enabled() + { + self.tags.insert(i, tag); + } + } + pub fn new_block(&mut self) -> usize { self.blocks.push(Block::default()); self.blocks.len() - 1 diff --git a/crates/victory-shader/src/emit/bitcode/census.rs b/crates/victory-shader/src/emit/bitcode/census.rs new file mode 100644 index 0000000..03eeccf --- /dev/null +++ b/crates/victory-shader/src/emit/bitcode/census.rs @@ -0,0 +1,174 @@ +//! Counts of a module's instructions by kind (a diagnostic): what a +//! translated program costs before the driver's compiler sees it. +//! +//! `VICTORY_SHADER_CENSUS` (any value) turns the counting on; the counts of +//! the module a thread wrote last are read with [`take`]. The `translate` +//! command writes them as a table (see `apps/victory/src/translate.rs`). + +use super::{Cast, Module, Op, Tag, Term, V}; +use std::cell::RefCell; + +/// The kinds, in the order of [`Census::counts`]. +pub const KINDS: [&str; 26] = [ + "total", + "arith", + "math_call", + "bitcast", + "cast", + "select", + "guard_select", + "phi", + "extract", + "buffer_load", + "cbuffer_load", + "texture_read", + "lds_load", + "buffer_store", + "lds_store", + "atomic", + "handle", + "annotate", + "dimensions", + "barrier", + "wave_op", + "io_other", + "gep", + "clamp", + "loop_counter", + "blocks", +]; + +/// Instruction counts of one written module, by [`KINDS`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Census { + pub counts: [u32; KINDS.len()], +} + +thread_local! { + /// The modules this thread wrote since the last [`take`]: the length and + /// a hash of each one's bitcode, with its counts (a program may be + /// emitted in several forms before one is kept). + static WRITTEN: RefCell> = const { RefCell::new(Vec::new()) }; +} + +fn fnv(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| { + (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3) + }) +} + +/// Whether modules are counted (`VICTORY_SHADER_CENSUS` set). +pub fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SHADER_CENSUS").is_some()) +} + +/// The counts of the module whose bitcode the container `dxil` holds, if +/// this thread wrote it since the last call (which forgets the others). +pub fn take(dxil: &[u8]) -> Option { + let written = WRITTEN.with(|l| std::mem::take(&mut *l.borrow_mut())); + let at = dxil.windows(4).position(|w| w == b"BC\xC0\xDE")?; + written + .into_iter() + .rev() + .find(|(len, hash, _)| dxil.get(at..at + len).is_some_and(|b| fnv(b) == *hash)) + .map(|w| w.2) +} + +/// Counts `m`, whose written form is `bitcode`, and keeps the result for +/// [`take`]. +pub(crate) fn note(m: &Module, bitcode: &[u8]) { + if !enabled() { + return; + } + let c = m.census(); + WRITTEN.with(|l| l.borrow_mut().push((bitcode.len(), fnv(bitcode), c))); +} + +fn kind(name: &str) -> usize { + let n = name.strip_prefix("dx.op.").unwrap_or(name); + let n = n.split('.').next().unwrap_or(n); + let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind"); + match n { + "unary" | "binary" | "tertiary" | "unaryBits" | "legacyF16ToF32" | "legacyF32ToF16" + | "isSpecialFloat" | "dot2" | "dot3" | "dot4" | "quaternary" => k("math_call"), + "bufferLoad" | "rawBufferLoad" => k("buffer_load"), + "cbufferLoadLegacy" | "cbufferLoad" => k("cbuffer_load"), + "bufferStore" | "rawBufferStore" | "textureStore" => k("buffer_store"), + "atomicBinOp" | "atomicCompareExchange" => k("atomic"), + "createHandle" | "createHandleFromBinding" | "createHandleFromHeap" => k("handle"), + "annotateHandle" => k("annotate"), + "getDimensions" => k("dimensions"), + "barrier" => k("barrier"), + _ if n.starts_with("wave") || n.starts_with("quad") => k("wave_op"), + _ if n.starts_with("textureLoad") + || n.starts_with("sample") + || n.starts_with("textureGather") + || n.starts_with("calculateLOD") => + { + k("texture_read") + } + _ => k("io_other"), + } +} + +impl Module { + /// The instructions [`Module::write`] writes, by kind. + pub(crate) fn census(&self) -> Census { + let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind"); + let call_kind: Vec = self.funcs.iter().map(|f| kind(&f.name)).collect(); + let live = self.live(); + // The blocks `write` lays out: those reached from the entry. + let mut seen = vec![false; self.blocks.len()]; + let mut stack = vec![0usize]; + if !self.blocks.is_empty() { + seen[0] = true; + } + while let Some(b) = stack.pop() { + for &s in super::successors(self.blocks[b].term).iter() { + if !seen[s] { + seen[s] = true; + stack.push(s); + } + } + } + let mut c = Census::default(); + for (b, blk) in self.blocks.iter().enumerate() { + if !seen[b] { + continue; + } + c.counts[k("blocks")] += 1; + let _: Option = blk.term; + for &i in blk + .phis + .iter() + .filter(|&&i| live[i as usize]) + .chain(&blk.body) + { + c.counts[0] += 1; + let at = match &self.insts[i as usize].op { + Op::Bin(..) | Op::Cmp(..) => k("arith"), + Op::Cast(Cast::Bitcast, _) => k("bitcast"), + Op::Cast(..) => k("cast"), + Op::Select(..) => k("select"), + Op::Extract(..) => k("extract"), + Op::Phi(_) => k("phi"), + Op::Gep(..) => k("gep"), + Op::Load(_) => k("lds_load"), + Op::Store(..) => k("lds_store"), + Op::AtomicRmw(..) | Op::CmpXchg(..) => k("atomic"), + Op::Call(f, _) => call_kind[*f as usize], + }; + c.counts[at] += 1; + match self.tags.get(&i) { + Some(Tag::Guard) => c.counts[k("guard_select")] += 1, + Some(Tag::Clamp) => c.counts[k("clamp")] += 1, + Some(Tag::Counter) => c.counts[k("loop_counter")] += 1, + None => {} + } + let _ = V::Inst(i); + } + } + c + } +} diff --git a/crates/victory-shader/src/emit/bitcode/opt.rs b/crates/victory-shader/src/emit/bitcode/opt.rs new file mode 100644 index 0000000..13551c3 --- /dev/null +++ b/crates/victory-shader/src/emit/bitcode/opt.rs @@ -0,0 +1,2136 @@ +//! Clean-up of a finished module before it is written: the lowering emits +//! one instruction after another as the console code names them, and +//! nothing stands between it and the driver's compiler. Every pass here is +//! exact: the module computes the same values and has the same effects for +//! every input. +//! +//! - [`DEAD`]: instructions without an effect whose result nothing reads +//! are left out (the lowering computes every dword of every register a +//! console instruction writes; a guarded write reads the register's old +//! value whether anything reads the new one or not). +//! - [`FOLD`]: integer arithmetic on constants is done here, and identities +//! (`x + 0`, `x & -1`, a select between a value and itself, a cast there +//! and back, a join of one value) give their operand. Float arithmetic is +//! left alone: `x + 0.0` and `x * 1.0` are not `x` for every `x`. +//! - [`REUSE`]: an instruction without an effect whose operands are those +//! of an earlier one that every path to it has run gives that one's +//! result (a descriptor handle made again in each block, an index clamped +//! again, a register read as a float again). +//! - [`FACTS`]: in the blocks only one side of a branch leads to, the +//! branch's condition is that side's constant, and so is what the +//! condition was made of (both terms of an `and` that held, the opposite +//! comparison). The lowering branches on a lane's condition and then +//! guards each instruction behind the branch with the same condition. +//! - [`LOADS`]: within a block, a read of the same place as an earlier read +//! gives that one's result while no store, atomic, barrier or other call +//! with an effect stands between them (another thread's unsynchronised +//! store may fall between any two reads or before both: the title's code +//! cannot tell which). +//! +//! Which passes run is `emit::shader_opt()` (`VICTORY_SHADER_OPT`), part of +//! the translation and so of the shader cache's key. + +use std::collections::HashMap; + +use super::{ + Attr, Bin, Cast, Const, Func, MdDef, Module, Op, Term, Ty, TypeDef, V, for_each_operand, pred, + successors, +}; + +/// Dead-code elimination. +pub const DEAD: u32 = 1; +/// Constants folded, identities removed. +pub const FOLD: u32 = 2; +/// One instruction for one value. +pub const REUSE: u32 = 4; +/// What a branch taken says about its condition. +pub const FACTS: u32 = 8; +/// One read for one place within a block, while nothing is stored. +pub const LOADS: u32 = 16; +/// Not a pass over the module: the lowering of a first-lane read in a +/// wave64 program run as two host waves skips the exchange that asks which +/// half has a lane where every lane is in EXEC (`lower.rs`, +/// `v_readfirstlane_b32`). +pub const FIRST: u32 = 32; +/// The passes over the module. +pub const MODULE: u32 = DEAD | FOLD | REUSE | FACTS | LOADS; +/// Every pass. +pub const ALL: u32 = MODULE | FIRST; + +/// What the instructions a module writes use, of the features a shader +/// declares by flag (the validator's "flags must match usage"). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(crate) struct Usage { + /// A wave or quad operation. + pub wave_ops: bool, + /// A 64-bit integer, as a result or an operand. + pub int64: bool, + /// A typed load of several components from a UAV. + pub typed_uav_loads: bool, + /// A handle from the view heap. + pub heap_views: bool, + /// A handle from the sampler heap. + pub heap_samplers: bool, + /// A 64-bit atomic. + pub atomic64: bool, +} + +/// What makes two instructions without an effect the same value. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Key { + Bin(u8, V, V), + Cast(u8, Ty, V), + Cmp(u8, V, V), + Select(V, V, V), + Extract(V, u32), + Call(u32, Vec), + Gep(Ty, V, Vec), + Load(V), +} + +/// The blocks reached from the entry, each after the blocks that dominate +/// it, and each block's children in the dominator tree. +struct Tree { + order: Vec, + children: Vec>, + /// Per block: the reached blocks that branch to it, once per edge. + preds: Vec>, +} + +/// The comparison that holds exactly when `p` does not (floats 0-15, +/// integers 32-41). +fn opposite(p: u8) -> u8 { + match p { + 0..=15 => 15 - p, + pred::EQ => pred::NE, + pred::NE => pred::EQ, + pred::IUGT => pred::IULE, + pred::IULE => pred::IUGT, + pred::IUGE => pred::IULT, + pred::IULT => pred::IUGE, + pred::SGT => pred::SLE, + pred::SLE => pred::SGT, + pred::SGE => pred::SLT, + _ => pred::SGE, + } +} + +/// What holds in the block being walked: values that are a known bit there, +/// and comparisons (by their operands) with a known outcome. +#[derive(Default)] +struct Facts { + bits: HashMap, + compares: HashMap<(u8, V, V), bool>, +} + +/// The facts a block added, to forget when its part of the tree is done. +#[derive(Default)] +struct Learned { + bits: Vec, + compares: Vec<(u8, V, V)>, +} + +fn mask(bits: u32) -> u64 { + if bits >= 64 { !0 } else { (1 << bits) - 1 } +} + +/// `x` of `bits` bits as a signed number. +fn signed(bits: u32, x: u64) -> i64 { + if bits < 64 && x >> (bits - 1) & 1 != 0 { + (x | !mask(bits)) as i64 + } else { + x as i64 + } +} + +/// What `v` stands for after the replacements so far. +fn resolve(repl: &[Option], mut v: V) -> V { + while let V::Inst(i) = v { + match repl[i as usize] { + Some(r) => v = r, + None => break, + } + } + v +} + +/// Replaces every value `op` reads by `f` of it. +fn map_operands(op: &mut Op, mut f: impl FnMut(V) -> V) { + match op { + Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => { + *a = f(*a); + *b = f(*b); + } + Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => *v = f(*v), + Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { + *a = f(*a); + *b = f(*b); + *c = f(*c); + } + Op::Call(_, args) => args.iter_mut().for_each(|a| *a = f(*a)), + Op::Phi(inc) => inc.iter_mut().for_each(|x| x.0 = f(x.0)), + Op::Gep(_, p, idx) => { + *p = f(*p); + idx.iter_mut().for_each(|i| *i = f(*i)); + } + } +} + +/// What a call does besides returning its result. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Effect { + /// Nothing, and the result depends on the arguments alone for the whole + /// run of the shader (arithmetic, handles, inputs, constant buffers, + /// resource sizes). + Pure, + /// Nothing, but the result depends on memory a store may change + /// (buffer and texture reads). + Reads, + /// Nothing, but the result depends on which lanes run the instruction + /// (wave and quad operations). + Lanes, + /// Stores, atomics, barriers, outputs, discards: always kept. + Writes, +} + +pub(super) fn effect(f: &Func) -> Effect { + let name = f.name.strip_prefix("dx.op.").unwrap_or(&f.name); + match f.attr { + Some(Attr::ReadNone) => Effect::Pure, + // A shader cannot write a constant buffer or resize a resource. + Some(Attr::ReadOnly) + if name.starts_with("cbufferLoadLegacy") || name.starts_with("getDimensions") => + { + Effect::Pure + } + Some(Attr::ReadOnly) if name.starts_with("wave") => Effect::Lanes, + Some(Attr::ReadOnly) => Effect::Reads, + // Declared with the attribute of calls that have effects, and have + // none: they read the other lanes' values. + _ if name.starts_with("wave") || name.starts_with("quad") => Effect::Lanes, + _ => Effect::Writes, + } +} + +impl Module { + /// Runs the clean-up passes named in `passes` ([`ALL`]: every one). + pub(crate) fn optimise(&mut self, passes: u32) { + if passes & (FOLD | REUSE | FACTS | LOADS) != 0 { + // Values merged in one round can make two joins the same in + // the next (a loop's registers that only go round), and a + // branch that goes one way leaves blocks with one way in. + for _ in 0..4 { + let mut changed = self.merge(passes); + if passes & FOLD != 0 { + changed |= self.prune(); + } + if !changed { + break; + } + } + } + if passes & DEAD != 0 { + self.drop_dead(); + } + } + + /// Per function: what a call of it does. + pub(super) fn effects(&self) -> Vec { + self.funcs.iter().map(effect).collect() + } + + /// The blocks reached from the entry. + pub(super) fn reached(&self) -> Vec { + let mut seen = vec![false; self.blocks.len()]; + if self.blocks.is_empty() { + return seen; + } + let mut stack = vec![0usize]; + seen[0] = true; + while let Some(b) = stack.pop() { + for &s in successors(self.blocks[b].term).iter() { + if !seen[s] { + seen[s] = true; + stack.push(s); + } + } + } + seen + } + + fn dominator_tree(&self) -> Tree { + let n = self.blocks.len(); + let succs = |b: usize| successors(self.blocks[b].term); + // Reverse postorder, as `write` lays the blocks out. + let mut seen = vec![false; n]; + let mut post = Vec::new(); + let mut stack = vec![(0usize, 0usize)]; + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, k) = *top; + top.1 += 1; + match succs(b).get(k) { + Some(&s) if !seen[s] => { + seen[s] = true; + stack.push((s, 0)); + } + Some(_) => {} + None => { + post.push(b); + stack.pop(); + } + } + } + post.reverse(); + let order = post; + let mut number = vec![usize::MAX; n]; + for (k, &b) in order.iter().enumerate() { + number[b] = k; + } + let mut preds = vec![Vec::new(); n]; + for &b in &order { + for &s in succs(b).iter() { + preds[s].push(b); + } + } + // Immediate dominators (Cooper, Harvey and Kennedy's iteration). + let mut idom = vec![usize::MAX; n]; + idom[0] = 0; + let mut changed = true; + while changed { + changed = false; + for &b in &order[1..] { + let mut new = usize::MAX; + for &p in &preds[b] { + if idom[p] == usize::MAX { + continue; + } + if new == usize::MAX { + new = p; + continue; + } + let (mut x, mut y) = (p, new); + while x != y { + while number[x] > number[y] { + x = idom[x]; + } + while number[y] > number[x] { + y = idom[y]; + } + } + new = x; + } + if idom[b] != new { + idom[b] = new; + changed = true; + } + } + } + let mut children = vec![Vec::new(); n]; + for &b in &order[1..] { + children[idom[b]].push(b); + } + Tree { + order, + children, + preds, + } + } + + /// Notes that `v` (an i1) is `holds` in the block being walked, and what + /// follows from it for the values `v` was made of. + fn learn(&self, v: V, holds: bool, facts: &mut Facts, learned: &mut Learned, depth: u32) { + let V::Inst(i) = v else { return }; + if facts.bits.contains_key(&v) { + return; + } + facts.bits.insert(v, holds); + learned.bits.push(v); + if depth == 0 { + return; + } + match self.insts[i as usize].op { + // Both terms of an `and` that holds hold; neither of an `or` + // that does not. + Op::Bin(Bin::And, a, b) if holds => { + self.learn(a, true, facts, learned, depth - 1); + self.learn(b, true, facts, learned, depth - 1); + } + Op::Bin(Bin::Or, a, b) if !holds => { + self.learn(a, false, facts, learned, depth - 1); + self.learn(b, false, facts, learned, depth - 1); + } + Op::Bin(Bin::Xor, a, b) => { + let (x, k) = match (self.int_k(a), self.int_k(b)) { + (None, Some((1, k))) => (a, k), + (Some((1, k)), None) => (b, k), + _ => return, + }; + self.learn(x, holds != (k != 0), facts, learned, depth - 1); + } + // The opposite comparison of the same operands. + Op::Cmp(p, a, b) => { + let key = (opposite(p), a, b); + if let std::collections::hash_map::Entry::Vacant(e) = facts.compares.entry(key) { + e.insert(!holds); + learned.compares.push(key); + } + } + _ => {} + } + } + + fn int_bits(&self, ty: Ty) -> Option { + match self.types[ty.0 as usize] { + TypeDef::Int(bits) => Some(bits), + _ => None, + } + } + + /// An integer constant's width and value (the bits of that width). + fn int_k(&self, v: V) -> Option<(u32, u64)> { + let V::Const(i) = v else { return None }; + let (ty, Const::Int(x)) = &self.consts[i as usize] else { + return None; + }; + let bits = self.int_bits(*ty)?; + Some((bits, *x as u64 & mask(bits))) + } + + /// The constant `x` of the integer type `ty`, kept sign-extended as + /// [`Module::i32`] and [`Module::bool`] keep theirs. + fn k(&mut self, ty: Ty, bits: u32, x: u64) -> V { + self.int_const(ty, signed(bits, x & mask(bits))) + } + + /// The value instruction `i` is known to have without it, if any: a + /// constant or an earlier value. May instead give `i` simpler operands + /// (`changed` says so). + fn simplify(&mut self, i: u32, changed: &mut bool) -> Option { + let ty = self.insts[i as usize].ty; + match self.insts[i as usize].op { + Op::Bin(op, a, b) => { + // Floats: `x + 0.0`, `x * 1.0` and the like are not `x` for + // every `x` (a negative zero, a signalling NaN). + let bits = self.int_bits(ty)?; + let (ka, kb) = (self.int_k(a).map(|k| k.1), self.int_k(b).map(|k| k.1)); + let all = mask(bits); + if let (Some(x), Some(y)) = (ka, kb) { + // A shift by the width or more and a division by zero + // have no defined result: left as they are. + let amount = u32::try_from(y).ok().filter(|&y| y < bits); + let r = match op { + Bin::Add => x.wrapping_add(y), + Bin::Sub => x.wrapping_sub(y), + Bin::Mul => x.wrapping_mul(y), + Bin::And => x & y, + Bin::Or => x | y, + Bin::Xor => x ^ y, + Bin::Shl => x << amount?, + Bin::LShr => x >> amount?, + Bin::AShr => (signed(bits, x) >> amount?) as u64, + Bin::UDiv if y != 0 => x / y, + Bin::URem if y != 0 => x % y, + _ => return None, + }; + return Some(self.k(ty, bits, r)); + } + match (op, ka, kb) { + ( + Bin::Add | Bin::Sub | Bin::Or | Bin::Xor | Bin::Shl | Bin::LShr | Bin::AShr, + _, + Some(0), + ) => Some(a), + (Bin::Add | Bin::Or | Bin::Xor, Some(0), _) => Some(b), + (Bin::Mul | Bin::UDiv, _, Some(1)) => Some(a), + (Bin::Mul, Some(1), _) => Some(b), + (Bin::Mul | Bin::And, _, Some(0)) => Some(b), + (Bin::Mul | Bin::And, Some(0), _) => Some(a), + (Bin::And, _, Some(m)) if m == all => Some(a), + (Bin::And, Some(m), _) if m == all => Some(b), + (Bin::Or, _, Some(m)) if m == all => Some(b), + (Bin::Or, Some(m), _) if m == all => Some(a), + (Bin::And | Bin::Or, _, _) if a == b => Some(a), + _ => None, + } + } + Op::Cmp(p, a, b) if p <= pred::TRUE => { + // Two float constants compare one way (`v_mul_legacy` asks + // whether its constant factor is zero). + let (V::Const(x), V::Const(y)) = (a, b) else { + return None; + }; + let (Const::Float(x), Const::Float(y)) = + (&self.consts[x as usize].1, &self.consts[y as usize].1) + else { + return None; + }; + let (x, y) = (f32::from_bits(*x), f32::from_bits(*y)); + let unordered = x.is_nan() || y.is_nan(); + // Bits 0-2 of a predicate: equal, greater, less; bit 3: + // or unordered. + let holds = if unordered { + p & 8 != 0 + } else { + (p & 1 != 0 && x == y) || (p & 2 != 0 && x > y) || (p & 4 != 0 && x < y) + }; + Some(self.bool(holds)) + } + Op::Cmp(p, a, b) => { + if !(pred::EQ..=pred::SLE).contains(&p) { + return None; + } + let holds = |x: u64, y: u64, bits: u32| { + let (sx, sy) = (signed(bits, x), signed(bits, y)); + match p { + pred::EQ => x == y, + pred::NE => x != y, + pred::IUGT => x > y, + pred::IUGE => x >= y, + pred::IULT => x < y, + pred::IULE => x <= y, + pred::SGT => sx > sy, + pred::SGE => sx >= sy, + pred::SLT => sx < sy, + _ => sx <= sy, + } + }; + if let (Some((bits, x)), Some((_, y))) = (self.int_k(a), self.int_k(b)) { + return Some(self.bool(holds(x, y, bits))); + } + if a == b { + return Some(self.bool(holds(0, 0, 32))); + } + // A bit widened and tested again is the bit. + if p == pred::NE + && self.int_k(b).is_some_and(|k| k.1 == 0) + && let V::Inst(z) = a + && let Op::Cast(Cast::ZExt, x) = self.insts[z as usize].op + && self.type_of(x) == ty + { + return Some(x); + } + None + } + Op::Select(c, mut t, mut f) => { + if let Some((_, c)) = self.int_k(c) { + return Some(if c != 0 { t } else { f }); + } + // Under the same condition an inner select is one of its + // operands (two guarded writes of one register in a row). + let mut inner = false; + while let V::Inst(x) = t + && let Op::Select(c2, t2, _) = self.insts[x as usize].op + && c2 == c + { + (t, inner) = (t2, true); + } + while let V::Inst(x) = f + && let Op::Select(c2, _, f2) = self.insts[x as usize].op + && c2 == c + { + (f, inner) = (f2, true); + } + if t == f { + return Some(t); + } + if self.int_bits(ty) == Some(1) + && self.int_k(t).is_some_and(|k| k.1 == 1) + && self.int_k(f).is_some_and(|k| k.1 == 0) + { + return Some(c); + } + if inner { + self.insts[i as usize].op = Op::Select(c, t, f); + *changed = true; + } + None + } + Op::Cast(op, x) => { + let from = self.type_of(x); + let through = match x { + V::Inst(y) => match self.insts[y as usize].op { + Op::Cast(op2, z) => Some((op2, z)), + _ => None, + }, + _ => None, + }; + match op { + Cast::Bitcast => { + if from == ty { + return Some(x); + } + // There and back: the bits are the same. + if let Some((Cast::Bitcast, z)) = through + && self.type_of(z) == ty + { + return Some(z); + } + let V::Const(c) = x else { return None }; + let to_float = matches!(self.types[ty.0 as usize], TypeDef::Float); + match self.consts[c as usize].1 { + Const::Int(bits) if to_float && self.int_bits(from) == Some(32) => { + Some(self.f32(bits as u32)) + } + Const::Float(bits) if self.int_bits(ty) == Some(32) => { + Some(self.int_const(ty, i64::from(bits as i32))) + } + _ => None, + } + } + Cast::ZExt | Cast::SExt | Cast::Trunc => { + let to = self.int_bits(ty)?; + if let Some((bits, k)) = self.int_k(x) { + let k = if op == Cast::SExt { + signed(bits, k) as u64 + } else { + k + }; + return Some(self.k(ty, to, k)); + } + // Widened and narrowed again. + if op == Cast::Trunc + && let Some((Cast::ZExt | Cast::SExt, z)) = through + && self.type_of(z) == ty + { + return Some(z); + } + None + } + _ => None, + } + } + _ => None, + } + } + + /// What kind of instruction `i` is for merging. + fn class(&self, effects: &[Effect], i: u32) -> Effect { + match &self.insts[i as usize].op { + Op::Bin(..) + | Op::Cast(..) + | Op::Cmp(..) + | Op::Select(..) + | Op::Extract(..) + | Op::Gep(..) => Effect::Pure, + Op::Load(p) => { + // A constant table reads the same whatever is stored. + let base = match *p { + V::Inst(g) => match &self.insts[g as usize].op { + Op::Gep(_, base, _) => *base, + _ => *p, + }, + _ => *p, + }; + match base { + V::Global(g) if self.globals[g as usize].init.is_some() => Effect::Pure, + _ => Effect::Reads, + } + } + Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => Effect::Writes, + Op::Phi(_) => Effect::Lanes, + Op::Call(f, _) => effects[*f as usize], + } + } + + fn key(&self, i: u32) -> Option { + let inst = &self.insts[i as usize]; + Some(match &inst.op { + Op::Bin(op, a, b) => { + // Integer sums, products and bit operations whichever way + // round; float ones as written (which NaN an operation of + // two NaNs gives is the hardware's choice by operand). + let commutes = matches!(op, Bin::Add | Bin::Mul | Bin::And | Bin::Or | Bin::Xor) + && self.int_bits(inst.ty).is_some(); + let (a, b) = if commutes && b < a { + (*b, *a) + } else { + (*a, *b) + }; + Key::Bin(*op as u8, a, b) + } + Op::Cast(op, v) => Key::Cast(*op as u8, inst.ty, *v), + Op::Cmp(p, a, b) => Key::Cmp(*p, *a, *b), + Op::Select(c, t, f) => Key::Select(*c, *t, *f), + Op::Extract(a, n) => Key::Extract(*a, *n), + Op::Call(f, args) => Key::Call(*f, args.clone()), + Op::Gep(ty, p, idx) => Key::Gep(*ty, *p, idx.clone()), + Op::Load(p) => Key::Load(*p), + _ => return None, + }) + } + + /// [`FOLD`], [`REUSE`], [`FACTS`] and [`LOADS`]: one walk over the + /// dominator tree. Returns whether anything changed. + fn merge(&mut self, passes: u32) -> bool { + if self.blocks.is_empty() { + return false; + } + let effects = self.effects(); + let tree = self.dominator_tree(); + let mut repl: Vec> = vec![None; self.insts.len()]; + let mut changed = false; + // Joins of one value: until none is left (one gone can leave + // another with one value). + if passes & FOLD != 0 { + let mut again = true; + while again { + again = false; + for &b in &tree.order { + for &p in &self.blocks[b].phis { + if repl[p as usize].is_some() { + continue; + } + let Op::Phi(incoming) = &self.insts[p as usize].op else { + continue; + }; + let mut one = None; + let mut same = true; + for &(v, _) in incoming { + let v = resolve(&repl, v); + if v == V::Inst(p) { + continue; + } + match one { + None => one = Some(v), + Some(o) if o == v => {} + Some(_) => same = false, + } + } + if let (true, Some(v)) = (same, one) { + repl[p as usize] = Some(v); + again = true; + changed = true; + } + } + } + } + } + // The values every path to the block being walked has computed + // (those of the blocks above it in the tree, and its own so far). + let mut known: HashMap = HashMap::new(); + // The reads of the block being walked since its last store. + let mut read: HashMap = HashMap::new(); + let mut facts = Facts::default(); + let (yes, no) = (self.bool(true), self.bool(false)); + enum Step { + Enter(usize), + Leave(Vec, Learned), + } + let mut steps = vec![Step::Enter(0)]; + while let Some(step) = steps.pop() { + let b = match step { + Step::Enter(b) => b, + Step::Leave(keys, learned) => { + for k in keys { + known.remove(&k); + } + for v in learned.bits { + facts.bits.remove(&v); + } + for k in learned.compares { + facts.compares.remove(&k); + } + continue; + } + }; + let mut added = Vec::new(); + // Reached from one block alone, by one side of its branch: the + // condition is that side's, here and in every block below. + let mut learned = Learned::default(); + if passes & FACTS != 0 + && let [p] = tree.preds[b][..] + && let Some(Term::CondBr(c, t, f)) = self.blocks[p].term + && t != f + { + self.learn(resolve(&repl, c), b == t, &mut facts, &mut learned, 8); + } + let known_bit = |facts: &Facts, v: V| match facts.bits.get(&v) { + Some(true) => yes, + Some(false) => no, + None => v, + }; + read.clear(); + // Two joins of the same values from the same blocks are one. + if passes & REUSE != 0 && self.blocks[b].phis.len() > 1 { + let mut joins: HashMap, V> = HashMap::new(); + for &p in &self.blocks[b].phis { + if repl[p as usize].is_some() { + continue; + } + let ty = self.insts[p as usize].ty; + let Op::Phi(incoming) = &self.insts[p as usize].op else { + continue; + }; + let mut key: Vec<(usize, V)> = incoming + .iter() + .map(|&(v, from)| (from, resolve(&repl, v))) + .collect(); + key.sort(); + // The type too: an undefined value of one type is not + // that of another. + key.push((ty.0 as usize, V::Global(u32::MAX))); + match joins.get(&key) { + Some(&first) => { + repl[p as usize] = Some(first); + changed = true; + } + None => { + joins.insert(key, V::Inst(p)); + } + } + } + } + let body = std::mem::take(&mut self.blocks[b].body); + let mut kept = Vec::with_capacity(body.len()); + for i in body { + map_operands(&mut self.insts[i as usize].op, |v| { + let v = resolve(&repl, v); + let bit = known_bit(&facts, v); + changed |= bit != v; + bit + }); + if let Op::Cmp(p, x, y) = self.insts[i as usize].op + && let Some(&holds) = facts.compares.get(&(p, x, y)) + { + repl[i as usize] = Some(if holds { yes } else { no }); + changed = true; + continue; + } + if passes & FOLD != 0 + && let Some(v) = self.simplify(i, &mut changed) + { + repl[i as usize] = Some(v); + changed = true; + continue; + } + let class = self.class(&effects, i); + if passes & REUSE != 0 + && class == Effect::Pure + && let Some(key) = self.key(i) + { + if let Some(&first) = known.get(&key) { + repl[i as usize] = Some(first); + changed = true; + continue; + } + known.insert(key.clone(), V::Inst(i)); + added.push(key); + } + // Reads of memory, and wave operations (the same lanes run + // the whole block): the block's own earlier one. + if passes & LOADS != 0 + && matches!(class, Effect::Reads | Effect::Lanes) + && let Some(key) = self.key(i) + { + if let Some(&first) = read.get(&key) { + repl[i as usize] = Some(first); + changed = true; + continue; + } + read.insert(key, V::Inst(i)); + } + if class == Effect::Writes { + read.clear(); + } + kept.push(i); + } + self.blocks[b].body = kept; + if let Some(Term::CondBr(c, t, f)) = self.blocks[b].term { + let c = known_bit(&facts, resolve(&repl, c)); + self.blocks[b].term = Some(Term::CondBr(c, t, f)); + } + steps.push(Step::Leave(added, learned)); + for &c in tree.children[b].iter().rev() { + steps.push(Step::Enter(c)); + } + } + if !changed { + return false; + } + // Everything that read a replaced value reads its replacement + // (joins read values from blocks walked after them). + for blk in &mut self.blocks { + blk.phis.retain(|&p| repl[p as usize].is_none()); + if let Some(Term::CondBr(c, t, f)) = blk.term { + blk.term = Some(Term::CondBr(resolve(&repl, c), t, f)); + } + } + let (blocks, insts) = (&self.blocks, &mut self.insts); + for blk in blocks { + for &i in blk.phis.iter().chain(&blk.body) { + map_operands(&mut insts[i as usize].op, |v| resolve(&repl, v)); + } + } + true + } + + /// [`FOLD`]: a branch on a constant goes one way. The side not taken + /// loses the branching block's values at its joins, and so do the joins + /// of blocks that nothing reaches any more. Returns whether a branch + /// changed. + fn prune(&mut self) -> bool { + let mut changed = false; + for b in 0..self.blocks.len() { + let Some(Term::CondBr(c, t, f)) = self.blocks[b].term else { + continue; + }; + // Both sides one block: two edges into it, left as they are. + if t == f { + continue; + } + let Some((_, k)) = self.int_k(c) else { + continue; + }; + let (taken, not) = if k != 0 { (t, f) } else { (f, t) }; + self.blocks[b].term = Some(Term::Br(taken)); + changed = true; + for n in 0..self.blocks[not].phis.len() { + let p = self.blocks[not].phis[n]; + if let Op::Phi(incoming) = &mut self.insts[p as usize].op { + incoming.retain(|&(_, from)| from != b); + } + } + } + if !changed { + return false; + } + let reached = self.reached(); + let (blocks, insts) = (&self.blocks, &mut self.insts); + for (_, blk) in blocks.iter().enumerate().filter(|(b, _)| reached[*b]) { + for &p in &blk.phis { + if let Op::Phi(incoming) = &mut insts[p as usize].op { + incoming.retain(|&(_, from)| reached[from]); + } + } + } + true + } + + /// Whether instruction `i` must stay whatever reads it. + fn has_effect(&self, effects: &[Effect], i: u32) -> bool { + match &self.insts[i as usize].op { + Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => true, + Op::Call(f, _) => effects[*f as usize] == Effect::Writes, + _ => false, + } + } + + /// [`DEAD`]: keeps the instructions with an effect, the branch + /// conditions, and what they read, transitively; the rest leave their + /// blocks. Blocks no branch reaches are emptied (they are not written). + fn drop_dead(&mut self) { + let effects = self.effects(); + let reached = self.reached(); + let mut live = vec![false; self.insts.len()]; + let mut work: Vec = Vec::new(); + let mark = |live: &mut [bool], work: &mut Vec, v: V| { + if let V::Inst(i) = v + && !live[i as usize] + { + live[i as usize] = true; + work.push(i); + } + }; + for (b, blk) in self.blocks.iter().enumerate() { + if !reached[b] { + continue; + } + for &i in &blk.body { + if self.has_effect(&effects, i) { + mark(&mut live, &mut work, V::Inst(i)); + } + } + if let Some(Term::CondBr(c, ..)) = blk.term { + mark(&mut live, &mut work, c); + } + } + while let Some(i) = work.pop() { + for_each_operand(&self.insts[i as usize].op, |v| { + mark(&mut live, &mut work, v) + }); + } + for (b, blk) in self.blocks.iter_mut().enumerate() { + if reached[b] { + blk.body.retain(|&i| live[i as usize]); + blk.phis.retain(|&i| live[i as usize]); + } else { + blk.body.clear(); + blk.phis.clear(); + } + } + self.drop_unused_functions(); + self.drop_unused_tables(); + } + + /// See [`Usage`]: over the blocks reached from the entry. + pub(crate) fn usage(&self) -> Usage { + let mut u = Usage::default(); + let reached = self.reached(); + let wide = |ty: Ty| self.types[ty.0 as usize] == TypeDef::Int(64); + // The first field of a handle's annotation: its kind, with the UAV + // bit; the second: the component type and count. + let annotation = |h: V| -> Option<(i64, i64)> { + let V::Inst(a) = h else { return None }; + let Op::Call(f, args) = &self.insts[a as usize].op else { + return None; + }; + if self.funcs[*f as usize].name != "dx.op.annotateHandle" { + return None; + } + let V::Const(props) = *args.get(2)? else { + return None; + }; + let Const::Aggregate(fields) = &self.consts[props as usize].1 else { + return None; + }; + match ( + &self.consts[fields[0] as usize].1, + &self.consts[fields[1] as usize].1, + ) { + (Const::Int(kind), Const::Int(components)) => Some((*kind, *components)), + _ => None, + } + }; + for (_, blk) in self.blocks.iter().enumerate().filter(|(b, _)| reached[*b]) { + for &i in blk.phis.iter().chain(&blk.body) { + let inst = &self.insts[i as usize]; + u.int64 |= wide(inst.ty); + for_each_operand(&inst.op, |v| u.int64 |= wide(self.type_of(v))); + let Op::Call(f, args) = &inst.op else { + continue; + }; + let name = self.funcs[*f as usize].name.as_str(); + let name = name.strip_prefix("dx.op.").unwrap_or(name); + if name.starts_with("wave") || name.starts_with("quad") { + u.wave_ops = true; + } else if name == "createHandleFromHeap" { + match args.get(2).and_then(|&s| self.int_k(s)) { + Some((_, 0)) => u.heap_views = true, + _ => u.heap_samplers = true, + } + } else if name.starts_with("atomic") && name.ends_with(".i64") { + u.atomic64 = true; + } else if name.starts_with("textureLoad") || name.starts_with("bufferLoad") { + u.typed_uav_loads |= args.get(1).and_then(|&h| annotation(h)).is_none_or( + |(kind, components)| kind & 0x1000 != 0 && components >> 8 & 0xff > 1, + ); + } + } + } + u + } + + /// A constant table no remaining load reads leaves the module (the + /// validator refuses an internal declaration nothing uses). Shared + /// memory stays declared whether it is read or not. + fn drop_unused_tables(&mut self) { + let mut used: Vec = self.globals.iter().map(|g| g.init.is_none()).collect(); + if used.iter().all(|&u| u) { + return; + } + for blk in &self.blocks { + for &i in blk.phis.iter().chain(&blk.body) { + for_each_operand(&self.insts[i as usize].op, |v| { + if let V::Global(g) = v { + used[g as usize] = true; + } + }); + } + } + for md in &self.mds { + if let MdDef::Value(_, V::Global(g)) = md { + used[*g as usize] = true; + } + } + if used.iter().all(|&u| u) { + return; + } + let mut new = vec![u32::MAX; used.len()]; + for (next, (old, _)) in used.iter().enumerate().filter(|u| *u.1).enumerate() { + new[old] = next as u32; + } + let mut old = 0; + self.globals.retain(|_| { + old += 1; + used[old - 1] + }); + let renumber = |v: V| match v { + V::Global(g) if used[g as usize] => V::Global(new[g as usize]), + v => v, + }; + for inst in &mut self.insts { + map_operands(&mut inst.op, renumber); + } + for md in &mut self.mds { + if let MdDef::Value(_, v) = md { + *v = renumber(*v); + } + } + } + + /// Declarations no remaining call names leave the module (the validator + /// refuses an external function nothing uses); the others keep their + /// order, so `main` stays function 0. + fn drop_unused_functions(&mut self) { + let mut used: Vec = self.funcs.iter().map(|f| f.body).collect(); + for blk in &self.blocks { + for &i in blk.phis.iter().chain(&blk.body) { + if let Op::Call(f, _) = self.insts[i as usize].op { + used[f as usize] = true; + } + } + } + for md in &self.mds { + if let MdDef::Value(_, V::Func(f)) = md { + used[*f as usize] = true; + } + } + if used.iter().all(|&u| u) { + return; + } + let mut new = vec![u32::MAX; used.len()]; + for (next, (old, _)) in used.iter().enumerate().filter(|u| *u.1).enumerate() { + new[old] = next as u32; + } + let mut old = 0; + self.funcs.retain(|_| { + old += 1; + used[old - 1] + }); + self.func_ids = self + .funcs + .iter() + .enumerate() + .map(|(i, f)| (f.name.clone(), i as u32)) + .collect(); + // Instructions that left their block keep a stale number: nothing + // reads them again. + for inst in &mut self.insts { + if let Op::Call(f, _) = &mut inst.op + && used[*f as usize] + { + *f = new[*f as usize]; + } + } + for md in &mut self.mds { + if let MdDef::Value(_, V::Func(f)) = md { + *f = new[*f as usize]; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `main` with one block and a function of each kind of effect. + struct Kit { + m: Module, + b: usize, + pure: V, + reads: V, + writes: V, + } + + fn kit() -> Kit { + let mut m = Module::default(); + let i32t = m.int(32); + let void = m.void(); + let fty = m.func_ty(i32t, vec![i32t, i32t]); + m.ptr(fty); + let pure = m.function("dx.op.binary.i32", fty, Some(Attr::ReadNone), false); + let reads = m.function("dx.op.bufferLoad.i32", fty, Some(Attr::ReadOnly), false); + let writes = m.function("dx.op.bufferStore.i32", fty, Some(Attr::NoUnwind), false); + let main_ty = m.func_ty(void, vec![]); + m.ptr(main_ty); + m.function("main", main_ty, None, true); + let b = m.new_block(); + Kit { + m, + b, + pure, + reads, + writes, + } + } + + fn body(m: &Module, b: usize) -> usize { + m.blocks[b].body.len() + } + + #[test] + fn unread_results_without_effect_are_dropped() { + let Kit { + mut m, + b, + pure, + reads, + writes, + } = kit(); + let (one, two) = (m.i32(1), m.i32(2)); + let used = m.call(b, reads, vec![one, two]); + let dead = m.call(b, reads, vec![two, one]); + let chain = m.bin(b, Bin::Add, dead, one); + let _unread = m.call(b, pure, vec![chain, two]); + // A store's result is unread and stays, with what it reads. + let kept = m.bin(b, Bin::Add, used, two); + m.call(b, writes, vec![kept, one]); + m.terminate(b, Term::Ret); + m.optimise(DEAD); + assert_eq!(body(&m, b), 3, "the load, the add and the store"); + m.write(); + } + + #[test] + fn branch_conditions_and_phi_cycles() { + let Kit { + mut m, + b, + reads, + writes, + .. + } = kit(); + let i32t = m.int(32); + let (zero, one) = (m.i32(0), m.i32(1)); + let (head, exit) = (m.new_block(), m.new_block()); + m.terminate(b, Term::Br(head)); + // A counter that decides the branch, and a register that only + // feeds itself round the loop. + let count = m.phi(head, i32t); + let idle = m.phi(head, i32t); + let next = m.bin(head, Bin::Add, count, one); + let idle_next = m.call(head, reads, vec![idle, one]); + let more = m.cmp(head, pred::IULT, next, one); + m.terminate(head, Term::CondBr(more, head, exit)); + m.set_phi(count, vec![(zero, b), (next, head)]); + m.set_phi(idle, vec![(zero, b), (idle_next, head)]); + m.call(exit, writes, vec![zero, one]); + m.terminate(exit, Term::Ret); + m.optimise(DEAD); + assert_eq!(m.blocks[head].phis.len(), 1, "the counter"); + assert_eq!(body(&m, head), 2, "the step and the test"); + assert_eq!(body(&m, exit), 1); + m.write(); + } + + #[test] + fn wave_operations_have_no_effect_of_their_own() { + let mut k = kit(); + let i32t = k.m.int(32); + let fty = k.m.func_ty(i32t, vec![i32t, i32t]); + let first = k.m.function( + "dx.op.waveReadLaneFirst.i32", + fty, + Some(Attr::NoUnwind), + false, + ); + let barrier = + k.m.function("dx.op.barrier", fty, Some(Attr::NoDuplicate), false); + let one = k.m.i32(1); + k.m.call(k.b, first, vec![one, one]); + k.m.call(k.b, barrier, vec![one, one]); + k.m.terminate(k.b, Term::Ret); + k.m.optimise(DEAD); + assert_eq!(body(&k.m, k.b), 1, "the barrier"); + // The declarations nothing calls any more are gone, and the call + // that stayed names its function by the new number. + let names: Vec<&str> = k.m.funcs.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["main", "dx.op.barrier"]); + let Op::Call(f, _) = k.m.insts[k.m.blocks[k.b].body[0] as usize].op else { + panic!("a call"); + }; + assert_eq!(k.m.funcs[f as usize].name, "dx.op.barrier"); + k.m.write(); + } + + /// The operands of each store left in block `b`. + fn stores(m: &Module, b: usize) -> Vec> { + m.blocks[b] + .body + .iter() + .filter_map(|&i| match &m.insts[i as usize].op { + Op::Call(g, args) if m.funcs[*g as usize].name.contains("Store") => { + Some(args.clone()) + } + _ => None, + }) + .collect() + } + + #[test] + fn constants_and_identities_fold() { + let Kit { + mut m, + b, + reads, + writes, + .. + } = kit(); + let (i32t, f32t) = (m.int(32), m.float()); + let (zero, one, all) = (m.i32(0), m.i32(1), m.i32(u32::MAX)); + let x = m.call(b, reads, vec![one, one]); + // x + 0, -1 & x, x >> 0, x * 1, x | x: all x. + let a = m.bin(b, Bin::Add, x, zero); + let a = m.bin(b, Bin::And, all, a); + let a = m.bin(b, Bin::LShr, a, zero); + let a = m.bin(b, Bin::Mul, a, one); + let a = m.bin(b, Bin::Or, a, a); + // There and back. + let f = m.cast(b, Cast::Bitcast, a, f32t); + let a = m.cast(b, Cast::Bitcast, f, i32t); + // Constants: (262168 >> 16) & 127 = 4, 7 & 31 = 7, -8 >>s 1 = -4. + let k = m.i32(262168); + let sixteen = m.i32(16); + let k = m.bin(b, Bin::LShr, k, sixteen); + let k127 = m.i32(127); + let k = m.bin(b, Bin::And, k, k127); + let minus8 = m.i32(-8i32 as u32); + let s = m.bin(b, Bin::AShr, minus8, one); + // A shift by the width is left alone. + let k32 = m.i32(32); + let wide = m.bin(b, Bin::Shl, one, k32); + // A select between a value and itself, and on a constant. + let c = m.cmp(b, pred::IULT, zero, one); + let sel = m.select(b, c, a, wide); + let same = m.select(b, c, sel, sel); + m.call(b, writes, vec![same, k]); + m.call(b, writes, vec![s, wide]); + m.terminate(b, Term::Ret); + m.optimise(FOLD | DEAD); + assert_eq!(body(&m, b), 4, "the read, the wide shift and two stores"); + let four = m.i32(4); + let minus4 = m.i32(-4i32 as u32); + let stores = stores(&m, b); + assert_eq!(stores, [vec![x, four], vec![minus4, wide]]); + m.write(); + } + + #[test] + fn float_arithmetic_is_not_folded() { + let Kit { + mut m, b, writes, .. + } = kit(); + let f32t = m.float(); + let fty = m.func_ty(f32t, vec![f32t, f32t]); + let input = m.function("dx.op.loadInput.f32", fty, Some(Attr::ReadNone), false); + let (zero, one, two) = (m.f32(0), m.f32(1.0f32.to_bits()), m.f32(2.0f32.to_bits())); + let x = m.call(b, input, vec![zero, zero]); + let y = m.call(b, input, vec![one, one]); + let a = m.bin(b, Bin::Add, x, zero); + let p = m.bin(b, Bin::Mul, a, one); + // The same sum the other way round is another instruction. + let xy = m.bin(b, Bin::Add, x, y); + let yx = m.bin(b, Bin::Add, y, x); + // Constants compare here: 1 < 2, and nothing equals a NaN. + let nan = m.f32(f32::NAN.to_bits()); + let lt = m.cmp(b, pred::OLT, one, two); + let eq = m.cmp(b, pred::OEQ, nan, nan); + let une = m.cmp(b, pred::UNE, nan, one); + let sel = m.select(b, lt, xy, yx); + let sel = m.select(b, eq, p, sel); + let sel = m.select(b, une, sel, p); + m.call(b, writes, vec![sel, p]); + m.terminate(b, Term::Ret); + m.optimise(ALL); + // Two inputs, x + 0.0, * 1.0, x + y and the store: y + x and the + // selects are gone. + assert_eq!(body(&m, b), 6); + assert_eq!(stores(&m, b), [[xy, p]]); + m.write(); + } + + /// entry: `c = x < y`, branch to `then` or `other`, which join. + struct Diamond { + k: Kit, + x: V, + y: V, + c: V, + then: usize, + other: usize, + join: usize, + } + + fn diamond() -> Diamond { + let mut k = kit(); + let (one, two) = (k.m.i32(1), k.m.i32(2)); + let x = k.m.call(k.b, k.reads, vec![one, one]); + let y = k.m.call(k.b, k.reads, vec![two, two]); + let c = k.m.cmp(k.b, pred::IULT, x, y); + let (then, other, join) = (k.m.new_block(), k.m.new_block(), k.m.new_block()); + k.m.terminate(k.b, Term::CondBr(c, then, other)); + k.m.terminate(then, Term::Br(join)); + k.m.terminate(other, Term::Br(join)); + k.m.terminate(join, Term::Ret); + Diamond { + k, + x, + y, + c, + then, + other, + join, + } + } + + #[test] + fn a_value_is_reused_below_its_block_and_not_beside_it() { + let Diamond { + k: + Kit { + mut m, + b, + pure, + writes, + .. + }, + x, + y, + then, + other, + join, + .. + } = diamond(); + // The entry's value again in a branch; a branch's value again in + // the other branch and in the join (neither is on every path). + let top = m.call(b, pure, vec![x, y]); + m.call(b, writes, vec![top, top]); + let again = m.call(then, pure, vec![x, y]); + let side = m.bin(then, Bin::Add, y, x); + m.call(then, writes, vec![again, side]); + let beside = m.bin(other, Bin::Add, x, y); + m.call(other, writes, vec![beside, beside]); + let after = m.bin(join, Bin::Add, x, y); + m.call(join, writes, vec![after, after]); + m.optimise(REUSE); + assert_eq!(stores(&m, then), [[top, side]]); + assert_eq!(body(&m, then), 2); + assert_eq!(body(&m, other), 2); + assert_eq!(body(&m, join), 2); + m.write(); + } + + #[test] + fn a_branch_taken_says_what_its_condition_is() { + let Diamond { + k: + Kit { + mut m, + b, + reads, + writes, + .. + }, + x, + y, + c, + then, + other, + join, + } = diamond(); + let three = m.i32(3); + let d = m.call(b, reads, vec![three, three]); + let d = m.cmp(b, pred::NE, d, three); + let both = m.bin(b, Bin::And, c, d); + // Behind the branch: the condition again (a guard), its opposite + // comparison, and a guarded write. + let guard = m.bin(then, Bin::And, c, d); + let old = m.select(then, guard, x, y); + let not = m.cmp(then, pred::IUGE, x, y); + let new = m.select(then, not, y, old); + m.call(then, writes, vec![new, new]); + let kept = m.select(other, c, x, y); + m.call(other, writes, vec![kept, kept]); + // After the join nothing is known. + let open = m.select(join, c, x, y); + m.call(join, writes, vec![open, open]); + m.optimise(FOLD | FACTS); + // then: select(d, x, y) and the store; other: y is stored. + assert_eq!(body(&m, then), 2); + let V::Inst(sel) = stores(&m, then)[0][0] else { + panic!() + }; + assert!(matches!(m.insts[sel as usize].op, Op::Select(g, a, z) if (g, a, z) == (d, x, y))); + assert_eq!(stores(&m, other), [[y, y]]); + assert_eq!(body(&m, join), 2); + let _ = both; + m.write(); + + // Both terms of an `and` that held hold behind it. + let Diamond { + k: + Kit { + mut m, + b, + reads, + writes, + .. + }, + x, + y, + c, + .. + } = diamond(); + let three = m.i32(3); + let d = m.call(b, reads, vec![three, three]); + let d = m.cmp(b, pred::NE, d, three); + let both = m.bin(b, Bin::And, c, d); + let (inner, out) = (m.new_block(), m.new_block()); + m.terminate(b, Term::CondBr(both, inner, out)); + let a = m.select(inner, c, x, y); + let z = m.select(inner, d, a, y); + m.call(inner, writes, vec![z, z]); + m.terminate(inner, Term::Br(out)); + // Where the `and` did not hold either term may. + let w = m.select(out, d, x, y); + m.call(out, writes, vec![w, w]); + m.terminate(out, Term::Ret); + m.optimise(FOLD | FACTS); + assert_eq!(stores(&m, inner), [[x, x]]); + assert_eq!(body(&m, out), 2); + m.write(); + } + + #[test] + fn a_branch_on_a_constant_goes_one_way() { + let Diamond { + k: Kit { + mut m, b, writes, .. + }, + x, + y, + c, + then, + other, + join, + } = diamond(); + let i32t = m.int(32); + // Behind the branch the same test again: its other side is never + // run, and the join behind it has one value. + let (deep, never, meet) = (m.new_block(), m.new_block(), m.new_block()); + m.terminate(then, Term::CondBr(c, deep, never)); + m.terminate(deep, Term::Br(meet)); + m.call(never, writes, vec![y, y]); + m.terminate(never, Term::Br(meet)); + let p = m.phi(meet, i32t); + m.set_phi(p, vec![(x, deep), (y, never)]); + m.call(meet, writes, vec![p, p]); + m.terminate(meet, Term::Br(join)); + let q = m.phi(join, i32t); + m.set_phi(q, vec![(p, meet), (y, other)]); + m.call(join, writes, vec![q, q]); + m.optimise(ALL); + assert!(matches!(m.blocks[then].term, Some(Term::Br(t)) if t == deep)); + assert_eq!(stores(&m, meet), [[x, x]]); + assert!(m.blocks[meet].phis.is_empty()); + assert_eq!(body(&m, never), 0, "emptied: nothing reaches it"); + let Op::Phi(incoming) = &m.insts[m.blocks[join].phis[0] as usize].op else { + panic!() + }; + assert_eq!(incoming, &vec![(x, meet), (y, other)]); + let _ = b; + m.write(); + } + + #[test] + fn a_read_is_reused_within_its_block_until_a_store() { + let Diamond { + k: + Kit { + mut m, + b, + reads, + writes, + .. + }, + x, + y, + then, + .. + } = diamond(); + let i32t = m.int(32); + // The entry reads (1, 1) for x: again in the entry it is x; in the + // next block it is read again. + let one = m.i32(1); + let again = m.call(b, reads, vec![one, one]); + m.call(b, writes, vec![again, y]); + let after = m.call(b, reads, vec![one, one]); + let twice = m.call(b, reads, vec![one, one]); + let sum = m.bin(b, Bin::Add, after, twice); + m.call(b, writes, vec![sum, sum]); + let below = m.call(then, reads, vec![one, one]); + m.call(then, writes, vec![below, below]); + // A constant buffer cannot change: one load for the function. + let cfty = m.func_ty(i32t, vec![i32t, i32t]); + let cb = m.function( + "dx.op.cbufferLoadLegacy.i32", + cfty, + Some(Attr::ReadOnly), + false, + ); + let top = m.call(b, cb, vec![one, one]); + m.call(b, writes, vec![top, top]); + let under = m.call(then, cb, vec![one, one]); + m.call(then, writes, vec![under, under]); + m.optimise(REUSE | LOADS); + let stores = stores(&m, b); + assert_eq!(stores[0], [x, y], "the second read is the first"); + let V::Inst(sum) = stores[1][0] else { panic!() }; + assert!( + matches!(m.insts[sum as usize].op, Op::Bin(Bin::Add, a, z) if a == after && z == after), + "read again after the store, once" + ); + assert_eq!(stores[2], [top, top]); + assert_eq!( + super::tests::stores(&m, then), + [vec![below, below], vec![top, top]] + ); + m.write(); + } + + #[test] + fn a_join_of_one_value_and_two_equal_joins() { + let Diamond { + k: Kit { mut m, writes, .. }, + x, + y, + then, + other, + join, + .. + } = diamond(); + let i32t = m.int(32); + let one = m.phi(join, i32t); + m.set_phi(one, vec![(x, then), (x, other)]); + let p = m.phi(join, i32t); + m.set_phi(p, vec![(x, then), (y, other)]); + let q = m.phi(join, i32t); + m.set_phi(q, vec![(y, other), (x, then)]); + m.call(join, writes, vec![one, p]); + let sum = m.bin(join, Bin::Add, p, q); + m.call(join, writes, vec![sum, q]); + m.optimise(FOLD | REUSE); + assert_eq!( + m.blocks[join].phis, + [match p { + V::Inst(i) => i, + _ => unreachable!(), + }] + ); + let stores = stores(&m, join); + assert_eq!(stores[0], [x, p]); + assert_eq!(stores[1][1], p); + m.write(); + } + + // ---- the passes against an interpreter, on random programs ---- + + /// Runs `m` on `inputs`: the stores it makes, in order (and how it + /// ended). Reads a value before its definition ran: a panic. + fn run(m: &Module, inputs: &[u32]) -> Vec<(String, Vec)> { + let mut vals: Vec> = vec![None; m.insts.len()]; + let mut memory = [0u64; 16]; + let mut trace = Vec::new(); + let eval = |vals: &[Option], v: V| -> u64 { + match v { + V::Inst(i) => vals[i as usize].expect("a value defined before its use"), + V::Const(c) => { + match (&m.consts[c as usize].1, m.int_bits(m.consts[c as usize].0)) { + (Const::Int(x), Some(bits)) => *x as u64 & mask(bits), + (Const::Float(bits), _) => u64::from(*bits), + _ => 0, + } + } + _ => panic!("a global or function as a value"), + } + }; + let (mut b, mut from) = (0usize, usize::MAX); + for _ in 0..4000 { + let blk = &m.blocks[b]; + // Joins take their values together, before any is assigned. + let joined: Vec<(u32, u64)> = blk + .phis + .iter() + .map(|&p| { + let Op::Phi(incoming) = &m.insts[p as usize].op else { + panic!("a join") + }; + let v = incoming + .iter() + .find(|x| x.1 == from) + .expect("a value for the edge taken"); + (p, eval(&vals, v.0)) + }) + .collect(); + for (p, x) in joined { + vals[p as usize] = Some(x); + } + for &i in &blk.body { + let inst = &m.insts[i as usize]; + let bits = m.int_bits(inst.ty); + let float = |x: u64| f32::from_bits(x as u32); + let r = match &inst.op { + Op::Bin(op, x, y) => { + let (x, y) = (eval(&vals, *x), eval(&vals, *y)); + match bits { + Some(bits) => { + let r = match op { + Bin::Add => x.wrapping_add(y), + Bin::Sub => x.wrapping_sub(y), + Bin::Mul => x.wrapping_mul(y), + Bin::And => x & y, + Bin::Or => x | y, + Bin::Xor => x ^ y, + Bin::Shl => x << y, + Bin::LShr => x >> y, + Bin::AShr => (signed(bits, x) >> y) as u64, + _ => panic!("no divisions here"), + }; + r & mask(bits) + } + None => { + let (x, y) = (float(x), float(y)); + let r = match op { + Bin::Add => x + y, + Bin::Sub => x - y, + _ => x * y, + }; + u64::from(r.to_bits()) + } + } + } + Op::Cmp(p, x, y) => { + let wide = m.int_bits(m.type_of(*x)); + let (x, y) = (eval(&vals, *x), eval(&vals, *y)); + let holds = match wide { + Some(bits) => { + let (sx, sy) = (signed(bits, x), signed(bits, y)); + match *p { + pred::EQ => x == y, + pred::NE => x != y, + pred::IUGT => x > y, + pred::IUGE => x >= y, + pred::IULT => x < y, + pred::IULE => x <= y, + pred::SGT => sx > sy, + pred::SGE => sx >= sy, + pred::SLT => sx < sy, + _ => sx <= sy, + } + } + None => { + let (x, y) = (float(x), float(y)); + if x.is_nan() || y.is_nan() { + p & 8 != 0 + } else { + (p & 1 != 0 && x == y) + || (p & 2 != 0 && x > y) + || (p & 4 != 0 && x < y) + } + } + }; + u64::from(holds) + } + Op::Select(c, t, f) => { + if eval(&vals, *c) != 0 { + eval(&vals, *t) + } else { + eval(&vals, *f) + } + } + Op::Cast(op, x) => { + let from_bits = m.int_bits(m.type_of(*x)); + let x = eval(&vals, *x); + match (op, from_bits, bits) { + (Cast::Bitcast, _, _) => x, + (Cast::ZExt, _, _) => x, + (Cast::SExt, Some(f), Some(t)) => signed(f, x) as u64 & mask(t), + (Cast::Trunc, _, Some(t)) => x & mask(t), + _ => panic!("a cast the generator does not make"), + } + } + Op::Call(f, args) => { + let a: Vec = args.iter().map(|&v| eval(&vals, v)).collect(); + let name = m.funcs[*f as usize].name.as_str(); + match name { + "dx.op.loadInput.i32" => { + u64::from(inputs[(a[0] ^ a[1]) as usize % inputs.len()]) + } + "dx.op.binary.i32" => a[0].min(a[1]), + "dx.op.cbufferLoadLegacy.i32" => u64::from( + inputs[a[0] as usize % inputs.len()].rotate_left(a[1] as u32 & 31), + ), + "dx.op.bufferLoad.i32" => memory[(a[0] ^ a[1]) as usize % 16], + "dx.op.waveReadLaneFirst.i32" => a[0] ^ a[1], + _ => { + memory[a[0] as usize % 16] = a[1]; + trace.push((name.to_owned(), a)); + 0 + } + } + } + _ => panic!("an instruction the generator does not make"), + }; + vals[i as usize] = Some(r); + } + from = b; + b = match blk.term.expect("a terminator") { + Term::Ret => { + trace.push(("ret".into(), Vec::new())); + return trace; + } + Term::Br(t) => t, + Term::CondBr(c, t, f) => { + if eval(&vals, c) != 0 { + t + } else { + f + } + } + }; + } + trace.push(("still running".into(), Vec::new())); + trace + } + + /// A random structured program over a few registers, as the lowering + /// makes them: every register joined at every join, conditions tested + /// again behind their branch, values computed again. + struct Gen { + k: Kit, + rng: u64, + regs: Vec, + conds: Vec, + cur: usize, + input: V, + table: V, + wave: V, + /// The operands of the block's last read (to read the place again, + /// and to store to it). + last: Option<(V, V)>, + } + + impl Gen { + fn next(&mut self, n: u64) -> u64 { + self.rng ^= self.rng << 13; + self.rng ^= self.rng >> 7; + self.rng ^= self.rng << 17; + (self.rng >> 11) % n + } + + fn reg(&mut self) -> V { + let n = self.next(self.regs.len() as u64) as usize; + self.regs[n] + } + + /// A register or a small constant. + fn value(&mut self) -> V { + match self.next(4) { + 0 => { + let k = [0u32, 1, 2, 31, u32::MAX, 0x8000_0000, 7][self.next(7) as usize]; + self.k.m.i32(k) + } + _ => self.reg(), + } + } + + fn cond(&mut self) -> V { + let c = self.cur; + let made = match self.next(6) { + 0 if !self.conds.is_empty() => { + let n = self.next(self.conds.len() as u64) as usize; + return self.conds[n]; + } + 1 if self.conds.len() > 1 => { + let (a, b) = ( + self.next(self.conds.len() as u64), + self.next(self.conds.len() as u64), + ); + let op = [Bin::And, Bin::Or, Bin::Xor][self.next(3) as usize]; + self.k + .m + .bin(c, op, self.conds[a as usize], self.conds[b as usize]) + } + 2 if !self.conds.is_empty() => { + let n = self.next(self.conds.len() as u64) as usize; + let t = self.k.m.bool(true); + self.k.m.bin(c, Bin::Xor, self.conds[n], t) + } + _ => { + let p = pred::EQ + self.next(10) as u8; + let (x, y) = (self.reg(), self.value()); + self.k.m.cmp(c, p, x, y) + } + }; + self.conds.push(made); + made + } + + fn statement(&mut self) { + let c = self.cur; + let d = self.next(self.regs.len() as u64) as usize; + let i32t = self.k.m.int(32); + let f32t = self.k.m.float(); + let r = match self.next(14) { + 0..=3 => { + let op = [Bin::Add, Bin::Sub, Bin::Mul, Bin::And, Bin::Or, Bin::Xor] + [self.next(6) as usize]; + let (x, y) = (self.value(), self.value()); + self.k.m.bin(c, op, x, y) + } + 4 => { + let op = [Bin::Shl, Bin::LShr, Bin::AShr][self.next(3) as usize]; + let x = self.value(); + let by = self.next(32) as u32; + let by = self.k.m.i32(by); + self.k.m.bin(c, op, x, by) + } + 5 | 6 => { + // A guarded write: the old value where the guard fails. + let g = self.cond(); + let x = self.value(); + self.k.m.select(self.cur, g, x, self.regs[d]) + } + 7 => { + let (x, y) = (self.value(), self.value()); + let f = [self.k.pure, self.input, self.table, self.wave][self.next(4) as usize]; + self.k.m.call(c, f, vec![x, y]) + } + 8 | 9 => { + let again = self.next(2) == 0; + let (x, y) = match self.last { + Some(last) if again => last, + _ => (self.value(), self.value()), + }; + self.last = Some((x, y)); + self.k.m.call(c, self.k.reads, vec![x, y]) + } + 10 => { + // A store, half the time to the place read last. + let (mut x, y) = (self.value(), self.value()); + let there = self.next(2) == 0; + if let Some((a, b)) = self.last + && there + { + x = self.k.m.bin(c, Bin::Xor, a, b); + } + self.k.m.call(c, self.k.writes, vec![x, y]); + return; + } + 11 => { + // Float arithmetic, read back as bits. + let (x, y) = (self.value(), self.value()); + let (x, y) = ( + self.k.m.cast(c, Cast::Bitcast, x, f32t), + self.k.m.cast(c, Cast::Bitcast, y, f32t), + ); + let op = [Bin::Add, Bin::Sub, Bin::Mul][self.next(3) as usize]; + let f = self.k.m.bin(c, op, x, y); + if self.next(2) == 0 { + let p = self.next(16) as u8; + let t = self.k.m.cmp(c, p, f, y); + self.conds.push(t); + } + self.k.m.cast(c, Cast::Bitcast, f, i32t) + } + 12 => { + let g = self.cond(); + self.k.m.cast(self.cur, Cast::ZExt, g, i32t) + } + _ => { + let x = self.value(); + let f = self.k.m.cast(c, Cast::Bitcast, x, f32t); + self.k.m.cast(c, Cast::Bitcast, f, i32t) + } + }; + self.regs[d] = r; + } + + fn code(&mut self, depth: u32) { + for _ in 0..1 + self.next(6) { + match self.next(8) { + 0 | 1 if depth > 0 => self.branch(depth - 1), + 2 if depth > 0 => self.repeat(depth - 1), + _ => self.statement(), + } + } + } + + /// if / else, every register joined. + fn branch(&mut self, depth: u32) { + let c = self.cond(); + let i32t = self.k.m.int(32); + let (then, other, join) = ( + self.k.m.new_block(), + self.k.m.new_block(), + self.k.m.new_block(), + ); + self.k.m.terminate(self.cur, Term::CondBr(c, then, other)); + let (before, known) = (self.regs.clone(), self.conds.len()); + self.cur = then; + self.last = None; + self.code(depth); + let (then_regs, then_end) = (std::mem::replace(&mut self.regs, before), self.cur); + self.k.m.terminate(then_end, Term::Br(join)); + self.conds.truncate(known); + self.cur = other; + self.last = None; + if self.next(3) != 0 { + self.code(depth); + } + let other_end = self.cur; + self.k.m.terminate(other_end, Term::Br(join)); + self.conds.truncate(known); + for (r, &t) in then_regs.iter().enumerate() { + let p = self.k.m.phi(join, i32t); + self.k + .m + .set_phi(p, vec![(t, then_end), (self.regs[r], other_end)]); + self.regs[r] = p; + } + self.cur = join; + self.last = None; + } + + /// A loop that runs at most a few times, every register joined at + /// its head. + fn repeat(&mut self, depth: u32) { + let i32t = self.k.m.int(32); + let (head, exit) = (self.k.m.new_block(), self.k.m.new_block()); + let before = self.cur; + self.k.m.terminate(before, Term::Br(head)); + let entering = self.regs.clone(); + let joins: Vec = (0..self.regs.len()) + .map(|_| self.k.m.phi(head, i32t)) + .collect(); + let count = self.k.m.phi(head, i32t); + self.regs = joins.clone(); + let known = self.conds.len(); + self.cur = head; + self.last = None; + self.code(depth); + let one = self.k.m.i32(1); + let next = self.k.m.bin(self.cur, Bin::Add, count, one); + let limit = 1 + self.next(3) as u32; + let limit = self.k.m.i32(limit); + let mut more = self.k.m.cmp(self.cur, pred::IULT, next, limit); + if self.next(2) == 0 { + let c = self.cond(); + more = self.k.m.bin(self.cur, Bin::And, more, c); + } + let latch = self.cur; + self.k.m.terminate(latch, Term::CondBr(more, head, exit)); + for (r, &p) in joins.iter().enumerate() { + self.k + .m + .set_phi(p, vec![(entering[r], before), (self.regs[r], latch)]); + } + let zero = self.k.m.i32(0); + self.k.m.set_phi(count, vec![(zero, before), (next, latch)]); + self.conds.truncate(known); + self.cur = exit; + self.last = None; + } + } + + fn random_program(seed: u64) -> Module { + let mut k = kit(); + let i32t = k.m.int(32); + let fty = k.m.func_ty(i32t, vec![i32t, i32t]); + let input = + k.m.function("dx.op.loadInput.i32", fty, Some(Attr::ReadNone), false); + let table = k.m.function( + "dx.op.cbufferLoadLegacy.i32", + fty, + Some(Attr::ReadOnly), + false, + ); + let wave = k.m.function( + "dx.op.waveReadLaneFirst.i32", + fty, + Some(Attr::NoUnwind), + false, + ); + let b = k.b; + let mut g = Gen { + k, + rng: seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1, + regs: Vec::new(), + conds: Vec::new(), + cur: b, + input, + table, + wave, + last: None, + }; + for r in 0..5 { + let (x, y) = (g.k.m.i32(r), g.k.m.i32(r * 3)); + let v = g.k.m.call(b, input, vec![x, y]); + g.regs.push(v); + } + g.code(3); + g.code(2); + // Every register is read at the end. + for r in 0..g.regs.len() { + let at = g.k.m.i32(r as u32); + g.k.m.call(g.cur, g.k.writes, vec![at, g.regs[r]]); + } + g.k.m.terminate(g.cur, Term::Ret); + g.k.m + } + + #[test] + fn every_pass_leaves_what_random_programs_store() { + let mut removed = 0; + for seed in 1..=400u64 { + let plain = random_program(seed); + let inputs: Vec> = (0..6u32) + .map(|n| { + (0..7u32) + .map(|i| match n { + 0 => 0, + 1 => i, + 2 => u32::MAX - i, + _ => { + (seed as u32 ^ n) + .wrapping_mul(0x9E37_79B9) + .rotate_left(i * 5) + ^ (i << 28) + } + }) + .collect() + }) + .collect(); + let expected: Vec<_> = inputs.iter().map(|i| run(&plain, i)).collect(); + let written: usize = plain + .blocks + .iter() + .map(|b| b.body.len() + b.phis.len()) + .sum(); + for passes in [ + DEAD, + FOLD, + REUSE, + FACTS, + LOADS, + FOLD | FACTS, + FOLD | REUSE | DEAD, + ALL, + ] { + let mut m = random_program(seed); + m.optimise(passes); + for (i, want) in inputs.iter().zip(&expected) { + assert_eq!(&run(&m, i), want, "seed {seed}, passes {passes}"); + } + if passes == ALL { + let left: usize = m.blocks.iter().map(|b| b.body.len() + b.phis.len()).sum(); + removed += written - left; + } + m.write(); + } + } + // The programs are of the wasteful kind: the passes find work. + assert!(removed > 4000, "{removed} instructions removed"); + } +} diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 1454136..ca006ed 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -9,7 +9,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use super::UserData; -use super::bitcode::{Attr, Bin, Cast, Rmw, Term, V, pred}; +use super::bitcode::{Attr, Bin, Cast, Rmw, Tag, Term, V, pred}; use super::container::SigElement; use super::shader::{Shader, flags}; use crate::ShaderError; @@ -2645,6 +2645,7 @@ impl<'a> Lower<'a> { let page = self .s .op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[page, last]); + self.s.m.tag(page, Tag::Clamp); let k3 = k(self, 3); let at = self.s.m.bin(c, Bin::Shl, page, k3); let directory = self.s.root_srv_handle(SLOT_MEMORY); @@ -3787,7 +3788,9 @@ impl<'a> Lower<'a> { // The validator refuses reads of undef. _ => self.s.m.i32(0), }; - self.s.m.select(self.cur, g, x, old) + let v = self.s.m.select(self.cur, g, x, old); + self.s.m.tag(v, Tag::Guard); + v } _ => x, }; @@ -6175,6 +6178,7 @@ impl<'a> Lower<'a> { let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1); let i32t = self.s.t.i32; let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]); + self.s.m.tag(slot, Tag::Clamp); let two = self.s.m.i32(2); let byte = self.s.m.bin(c, Bin::Shl, slot, two); let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES); @@ -7288,16 +7292,26 @@ impl<'a> Lower<'a> { return Err("a first-lane read where not every lane runs"); } let c = self.cur; - let i32t = self.s.t.i32; - let has = self.s.m.cast(c, Cast::ZExt, any, i32t); - let (lo_has, hi_has) = self.exchange_halves(c, has); - let (lo, hi) = self.exchange_halves(c, mine); - let z = self.s.m.i32(0); - let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z); - let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z); - // neither half has a lane in EXEC: the console reads lane 0 - let hi = self.s.m.select(c, in_hi, hi, lo); - self.s.m.select(c, in_lo, lo, hi) + if guard.is_none() && super::shader_opt() & super::bitcode::opt::FIRST != 0 { + // Every lane is in EXEC: the console's first lane is + // lane 0, which the lower half of every console wave + // has. No half needs to ask the other whether it has + // a lane (an exchange of the constant 1: two group + // barriers), and the lower half's value is the answer. + let (lo, _) = self.exchange_halves(c, mine); + lo + } else { + let i32t = self.s.t.i32; + let has = self.s.m.cast(c, Cast::ZExt, any, i32t); + let (lo_has, hi_has) = self.exchange_halves(c, has); + let (lo, hi) = self.exchange_halves(c, mine); + let z = self.s.m.i32(0); + let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z); + let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z); + // neither half has a lane in EXEC: the console reads lane 0 + let hi = self.s.m.select(c, in_hi, hi, lo); + self.s.m.select(c, in_lo, lo, hi) + } } else { mine }; @@ -10511,6 +10525,8 @@ impl<'a> Lower<'a> { let (phi, _) = self.counters[&to]; let one = self.s.m.i32(1); let next = self.s.m.bin(c, Bin::Add, phi, one); + self.s.m.tag(phi, Tag::Counter); + self.s.m.tag(next, Tag::Counter); // Per stage unless the switch names one: a loop that never meets its // exit (a count read from a buffer the host has not got yet, say) // runs to the limit in every lane. A million iterations a pixel @@ -10534,7 +10550,9 @@ impl<'a> Lower<'a> { .expect("header") .1 .push((next, c)); - self.s.m.cmp(c, p, next, limit) + let over = self.s.m.cmp(c, p, next, limit); + self.s.m.tag(over, Tag::Counter); + over } /// The block a lane stopped by [`LOOP_LIMIT`] leaves through. diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 1b90d57..3a7646c 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -108,6 +108,7 @@ use crate::dxbc::{Container, FourCC}; use crate::native::{HwStage, NativeProgram, RootType}; use crate::{ShaderError, io, ir, resource, structure}; +pub use bitcode::census; pub use sampler::StaticSampler; pub use lower::set_host_max_wave; pub use rect::rect_list_gs; @@ -167,6 +168,38 @@ pub fn group_sync() -> u8 { }) } +/// 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 +/// clean-up fault, and for measuring what the clean-up is worth. +/// `VICTORY_SHADER_OPT`: +/// - unset: every pass. +/// - `0`: none (the module as the lowering made it). +/// - a number (decimal or `0x` hex): those passes; 1 dead code, 2 constants +/// and identities, 4 one instruction for one value, 8 what a branch taken +/// says about its condition, 16 one read for one place within a block, +/// 32 a first-lane read of two host waves without the round that asks +/// which half has a lane (where every lane has one). +/// +/// Part of the translation: the shader cache keys on it (`victory-gpu`'s +/// does). +pub fn shader_opt() -> u32 { + static PASSES: std::sync::OnceLock = std::sync::OnceLock::new(); + *PASSES.get_or_init(|| parse_shader_opt(std::env::var("VICTORY_SHADER_OPT").ok().as_deref())) +} + +/// `VICTORY_SHADER_OPT`'s value; every pass when it is unset or +/// unreadable. Pure, for testing. +fn parse_shader_opt(value: Option<&str>) -> u32 { + let parsed = value + .map(str::trim) + .and_then(|v| match v.strip_prefix("0x") { + Some(hex) => u32::from_str_radix(hex, 16).ok(), + None => v.parse().ok(), + }); + parsed.map_or(bitcode::opt::ALL, |n| n & bitcode::opt::ALL) +} + /// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset, /// unreadable or 0. Pure, for testing. fn parse_loop_limit(value: Option<&str>) -> u32 { @@ -727,6 +760,17 @@ mod tests { use super::lower::LOOP_LIMIT; use super::parse_loop_limit; + #[test] + fn the_clean_up_switch_parses_or_runs_every_pass() { + let all = super::bitcode::opt::ALL; + assert_eq!(parse_shader_opt(None), all); + assert_eq!(parse_shader_opt(Some("0")), 0); + assert_eq!(parse_shader_opt(Some(" 1 ")), 1); + assert_eq!(parse_shader_opt(Some("0x1")), 1); + assert_eq!(parse_shader_opt(Some("0xffffffff")), all); + assert_eq!(parse_shader_opt(Some("on")), all); + } + #[test] fn the_loop_limit_switch_parses_or_falls_back() { assert_eq!(parse_loop_limit(None), LOOP_LIMIT); diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index fe257db..b49bc6d 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -402,7 +402,9 @@ impl Shader { let index = if !sampler && limit != 0 { let null = self.m.i32(limit); let i32t = self.t.i32; - self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null]) + let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null]); + self.m.tag(v, super::bitcode::Tag::Clamp); + v } else if sampler { // A sampler heap has at most 2,048 samplers on any host: an // index past that (a number read from memory the host has not @@ -411,7 +413,9 @@ impl Shader { // heap smaller than 2,048 would need. let last = self.m.i32(2047); let i32t = self.t.i32; - self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]) + let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]); + self.m.tag(v, super::bitcode::Tag::Clamp); + v } else { index }; @@ -437,6 +441,26 @@ impl Shader { pub fn finish(mut self) -> Vec { let ud_size = (self.user_data * 4).next_multiple_of(16); self.fix_user_data_size(ud_size); + // The clean-up, before anything is declared about the code: a + // feature whose last use it removed must not be declared (the + // validator compares the flags with what the code uses). + let passes = super::shader_opt() & super::bitcode::opt::MODULE; + if passes != 0 { + self.m.optimise(passes); + let used = self.m.usage(); + for (flag, used) in [ + (flags::WAVE_OPS, used.wave_ops), + (flags::INT64, used.int64), + (flags::TYPED_UAV_LOADS, used.typed_uav_loads), + (flags::RESOURCE_HEAP, used.heap_views), + (flags::SAMPLER_HEAP, used.heap_samplers), + (flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64, used.atomic64), + ] { + if !used { + self.flags &= !flag; + } + } + } let mut resources = None; let mut bindings = Vec::new(); let i32c = |s: &mut Self, v: u32| { @@ -737,6 +761,7 @@ impl Shader { self.m.named_md("dx.entryPoints", vec![entry]); let bitcode = self.m.write(); + super::bitcode::census::note(&self.m, &bitcode); let mut dxil = Vec::with_capacity(24 + bitcode.len()); dxil.extend((kind << 16 | 0x66).to_le_bytes()); dxil.extend((((24 + bitcode.len()) / 4) as u32).to_le_bytes()); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index fe98439..5072d6c 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -251,6 +251,11 @@ fn run_cases_on( } ran += 1; } + if ran == 0 && devices.iter().all(|&(_, warp)| !warp) { + // A case for the hardware adapter alone, on a machine without one. + eprintln!("no SM 6.6 hardware device; a hardware-only case not run"); + return; + } assert!(ran > 0, "no SM 6.6 device available ({devices:?})"); } From 1d2f4763029c3e488cfeafada1d9e1d8aa3a3dbc Mon Sep 17 00:00:00 2001 From: NuraadGit Date: Tue, 24 Nov 2026 15:22:26 -0500 Subject: [PATCH 123/445] GPU: constant buffer views of at most 64 KiB The host removes the device for a constant buffer view of more than 65,536 bytes. The title's view heap holds larger sizes in slots it does not use, and the size went to the host as it was. --- crates/victory-gpu/src/descriptor/host.rs | 42 +++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index cc061c7..13f67cb 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1219,7 +1219,7 @@ impl HostHeap { let Some(host) = host() else { return }; let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, - SizeInBytes: size.next_multiple_of(256), + SizeInBytes: constant_bytes(size), }; // SAFETY: a slot of our heap; the memory is the caller's. unsafe { @@ -1833,6 +1833,15 @@ fn twin_uav( Some(desc) } +/// The bytes of the host's constant buffer view for a title's of `size`: +/// whole 256s, and at most the 64 KiB a shader can index. The host removes +/// the device for a larger view, and the title's heap holds such sizes in +/// slots it does not use. +fn constant_bytes(size: u32) -> u32 { + const LARGEST: u32 = 64 << 10; + size.min(LARGEST).next_multiple_of(256) +} + /// Makes the host descriptor for `view` at `at`: the host resource it /// views, or `None` if it cannot. fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { @@ -1851,7 +1860,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { } let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, - SizeInBytes: size.next_multiple_of(256), + SizeInBytes: constant_bytes(size), }; // SAFETY: a slot of our heap; the range lies in the host copy. unsafe { device.CreateConstantBufferView(Some(&desc), at) }; @@ -2259,6 +2268,35 @@ mod tests { assert!(!same_placed_texture(&low, &View::Shader(0, None))); } + /// A constant buffer view larger than the host takes is cut to what it + /// takes: the device, which such a view removes, stays. + #[test] + fn an_oversized_constant_buffer_view_leaves_the_device_alive() { + let Some(host) = host() else { + return; // no host GPU + }; + let Some(heap) = HostHeap::new(false, 4) else { + return; + }; + // SAFETY: a plain device query. + let alive = || unsafe { host.device.GetDeviceRemovedReason() }.is_ok(); + // Made first: an allocation that fails on a removed device must not + // end the test early. + let (buffer, _) = host.upload_buffer(1 << 20).expect("an upload buffer"); + let memory = vec![0u8; 2 << 20]; + let at = (memory.as_ptr() as u64).next_multiple_of(64 << 10); + for size in [969_472u32, 896_256] { + assert!(make(&View::Constant(at, size), heap.cpu(0)).is_some()); + assert!(alive(), "a view of {size} bytes"); + } + // SAFETY: a live upload buffer. + heap.constant_at(1, unsafe { buffer.GetGPUVirtualAddress() }, 969_472); + assert!(alive(), "a view of the list's own memory"); + assert_eq!(constant_bytes(480), 512); + assert_eq!(constant_bytes(64 << 10), 64 << 10); + assert_eq!(constant_bytes(u32::MAX), 64 << 10); + } + /// A null 3D UAV made on the real device leaves it alive. #[test] fn null_3d_uav_is_accepted_by_the_device() { From cb80bf0f9c19bd85c45340289dbc349c9b260b88 Mon Sep 17 00:00:00 2001 From: Noname0202 Date: Tue, 24 Nov 2026 21:23:57 +0100 Subject: [PATCH 124/445] Shaders: lower immediate samplers chosen by uniform control flow --- crates/victory-shader/src/emit/lower.rs | 258 +++++++++++++----- .../src/emit/waterfall_tests.rs | 184 +++++++++++++ 2 files changed, 381 insertions(+), 61 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca006ed..94f8a76 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6151,6 +6151,123 @@ impl<'a> Lower<'a> { Ok(phi) } + /// Registers an immediate sampler constant and returns its slot index. + fn register_sampler(&mut self, words: &[u32], cmp: bool) -> Result { + let words: [u32; 4] = words + .get(..4) + .and_then(|w| w.try_into().ok()) + .ok_or("a sampler constant")?; + let n = match self.samplers.iter().position(|w| *w == words) { + Some(n) => n, + None => { + self.samplers.push(words); + self.samplers.len() - 1 + } + }; + if cmp && n < 64 { + self.s.cmp_samplers |= 1 << n; + } + Ok(n as u32) + } + + /// Resolves a control-flow phi of immediate sampler constants into either a + /// single static sampler register (`One`) or a uniform `i32` phi index over + /// `regs` (`Many`) for branch dispatch at the sample site. + fn sampler_phi_choice( + &mut self, + block: usize, + args: &[Source], + cmp: bool, + depth: u32, + ) -> Result<(Option, Vec), Why> { + const WHY: Why = "a descriptor chosen by control flow"; + let mut distinct: Vec<[u32; 4]> = Vec::new(); + self.collect_constant_samplers(block, args, depth, &mut distinct)?; + if distinct.is_empty() { + return Err(WHY); + } + let mut regs = Vec::with_capacity(distinct.len()); + for w in &distinct { + regs.push(self.register_sampler(w, cmp)?); + } + if regs.len() == 1 { + return Ok((None, regs)); + } + let idx = self.sampler_index_phi(block, args, 0, &distinct, depth)?; + Ok((Some(idx), regs)) + } + + fn collect_constant_samplers( + &self, + block: usize, + args: &[Source], + depth: u32, + distinct: &mut Vec<[u32; 4]>, + ) -> Result<(), Why> { + const WHY: Why = "a descriptor chosen by control flow"; + let p = self.x.p; + for (&q, arg) in p.blocks[block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + match arg { + Source::Constant(w) if w.len() >= 4 => { + let k: [u32; 4] = w[..4].try_into().unwrap(); + if !distinct.contains(&k) { + distinct.push(k); + } + } + Source::Phi { + block: inner, + args: inner_args, + } if depth > 0 => { + self.collect_constant_samplers(*inner, inner_args, depth - 1, distinct)?; + } + _ => return Err(WHY), + } + } + Ok(()) + } + + fn sampler_index_phi( + &mut self, + block: usize, + args: &[Source], + lower: u32, + distinct: &[[u32; 4]], + depth: u32, + ) -> Result { + const WHY: Why = "a descriptor chosen by control flow"; + let p = self.x.p; + let mut incoming = Vec::new(); + for (&q, arg) in p.blocks[block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let tail = self.tail[q].ok_or(WHY)?; + let at = self.edges.get(&(q, block)).copied().unwrap_or(tail); + let idx = match arg { + Source::Constant(w) if w.len() >= 4 => { + let k: [u32; 4] = w[..4].try_into().unwrap(); + let pos = distinct.iter().position(|d| *d == k).ok_or(WHY)? as u32; + self.s.m.i32(lower + pos) + } + Source::Phi { + block: inner, + args: inner_args, + } if depth > 0 => { + self.sampler_index_phi(*inner, inner_args, lower, distinct, depth - 1)? + } + _ => return Err(WHY), + }; + incoming.push((idx, at)); + } + let join = self.block[block].ok_or(WHY)?; + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) + } + /// The bytes per element of the buffer view `src` names, if the program /// picks it from the view heap at an index it computes (root type /// `ResourceHeap`): read from the host's table by heap slot in the @@ -9133,7 +9250,23 @@ impl<'a> Lower<'a> { if cmp && (*a16 || dmask.count_ones() != 1) { return Err("a comparison sample of 16-bit coordinates or several channels"); } - let sh = self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?; + let mut sampler_choice: Option<(V, Vec)> = None; + let sh = match ss { + Source::Phi { block, args } => { + match self.sampler_phi_choice(*block, args, cmp, 8) { + Ok((None, regs)) => self.s.sampler_handle(self.cur, regs[0]), + Ok((Some(idx), regs)) => { + let first = self.s.sampler_handle(self.cur, regs[0]); + sampler_choice = Some((idx, regs)); + first + } + Err(_) => { + self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))? + } + } + } + _ => self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?, + }; // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13, // signed (programmable offsets: gathers only). let offset_word = name.ends_with("_o"); @@ -9239,6 +9372,60 @@ impl<'a> Lower<'a> { } else { fu }; + let call_sample = |l: &mut Self, + intrinsic: &str, + opcode: u32, + args: &[V], + gathered: &mut Option<[V; 4]>| + -> V { + let Some((idx, ref regs)) = sampler_choice else { + return l + .s + .op(c, intrinsic, Attr::ReadOnly, l.s.t.res_ret, opcode, args); + }; + let merge = l.s.m.new_block(); + let mut cur_test = c; + let mut per_ch: [Vec<(V, usize)>; 4] = Default::default(); + let mut last_r = args[0]; + for (i, ®) in regs.iter().enumerate() { + let arm = if i + 1 == regs.len() { + cur_test + } else { + let arm = l.s.m.new_block(); + let next = l.s.m.new_block(); + let k = l.s.m.i32(i as u32); + let cond = l.s.m.cmp(cur_test, pred::EQ, idx, k); + l.s.m.terminate(cur_test, Term::CondBr(cond, arm, next)); + cur_test = next; + arm + }; + let mut arm_args = args.to_vec(); + arm_args[1] = l.s.sampler_handle(arm, reg); + let r_i = l.s.op( + arm, + intrinsic, + Attr::ReadOnly, + l.s.t.res_ret, + opcode, + &arm_args, + ); + for (ch, slot) in per_ch.iter_mut().enumerate() { + let v = l.s.m.extract(arm, r_i, ch as u32); + slot.push((v, arm)); + } + l.s.m.terminate(arm, Term::Br(merge)); + last_r = r_i; + } + let mut phis = [fu; 4]; + for (ch, incoming) in per_ch.into_iter().enumerate() { + let phi = l.s.m.phi(merge, l.s.t.f32); + l.s.m.set_phi(phi, incoming); + phis[ch] = phi; + } + *gathered = Some(phis); + l.cur = merge; + last_r + }; match op { // Outside a pixel shader there are no screen derivatives: // the validator refuses `sample` there ("features @@ -9252,14 +9439,7 @@ impl<'a> Lower<'a> { 60 if !self.s.pixel => { args.extend(&os); args.push(self.s.m.f32(0)); - self.s.op( - c, - "sampleLevel.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 62, - &args, - ) + call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered) } 60 => { if offset_word { @@ -9285,8 +9465,7 @@ impl<'a> Lower<'a> { } args.extend(&os); args.push(clamp); - self.s - .op(c, "sample.f32", Attr::ReadOnly, self.s.t.res_ret, 60, &args) + call_sample(self, "sample.f32", 60, &args, &mut gathered) } 61 => { // With a16 the bias is an f16 in the low half of its @@ -9302,25 +9481,11 @@ impl<'a> Lower<'a> { args.extend(&os); if self.s.pixel { args.extend([bias, clamp]); - self.s.op( - c, - "sampleBias.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 61, - &args, - ) + call_sample(self, "sampleBias.f32", 61, &args, &mut gathered) } else { // As above: the bias is the level. args.push(bias); - self.s.op( - c, - "sampleLevel.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 62, - &args, - ) + call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered) } } 63 if kind == 5 => { @@ -9359,14 +9524,7 @@ impl<'a> Lower<'a> { let lod = self.s.m.bin(c, Bin::Mul, ln, per_ln2); args.extend(&os); args.push(lod); - self.s.op( - c, - "sampleLevel.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 62, - &args, - ) + call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered) } 63 => { let mut g = vec![fu; 6]; @@ -9379,14 +9537,7 @@ impl<'a> Lower<'a> { args.extend(&os); args.extend(g); args.push(clamp); - self.s.op( - c, - "sampleGrad.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 63, - &args, - ) + call_sample(self, "sampleGrad.f32", 63, &args, &mut gathered) } 64 | 65 => { let reference = addr_u32(self, first - 1)?; @@ -9399,8 +9550,7 @@ impl<'a> Lower<'a> { } else { "sampleCmpLevelZero.f32" }; - self.s - .op(c, name, Attr::ReadOnly, self.s.t.res_ret, op, &args) + call_sample(self, name, op, &args, &mut gathered) } 62 => { let lod = if name == "image_sample_l" { @@ -9411,14 +9561,7 @@ impl<'a> Lower<'a> { }; args.extend(&os); args.push(lod); - self.s.op( - c, - "sampleLevel.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 62, - &args, - ) + call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered) } _ => { if name == "image_gather4" { @@ -9500,14 +9643,7 @@ impl<'a> Lower<'a> { } else { args.extend(&os[..2]); args.push(self.s.m.i32(dmask.trailing_zeros())); - self.s.op( - c, - "textureGather.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 73, - &args, - ) + call_sample(self, "textureGather.f32", 73, &args, &mut gathered) } } } diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 18425e0..365883a 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -249,3 +249,187 @@ fn lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx() { } } } + +#[test] +fn immediate_sampler_chosen_by_control_flow() { + let s_mov_lit = |dst: u8, lit: u32| [0xBE80_03FF | (dst as u32) << 16, lit]; + let s_mov_zero = |dst: u8| 0xBE80_0380 | (dst as u32) << 16; + let s_load_x8 = |dst: u8, base: u8| [0x3D << 26 | 0x03 << 18 | (dst as u32) << 6 | (base as u32 >> 1), 125 << 25]; + let s_load_x4_off = |dst: u8, base: u8, off: u32| [0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1), 125 << 25 | off]; + // image_sample_lz v4, v[2:3], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D + let image_sample_lz: [u32; 2] = [ + 0x3C << 26 | 0x21 << 18 | 1 << 8 | 1 << 3, // dmask=1, dim=2D(1) + (16u32 >> 2) << 21 | (8u32 >> 2) << 16 | 4 << 8 | 2, + ]; + // buffer_store_dword v4, off, s[20:23], 0 + let buf_store: [u32; 2] = [0x38 << 26 | 0x1C << 18, 0x80 << 24 | (20u32 >> 2) << 16 | 4 << 8]; + + // Two distinct valid immediate sampler descriptors (different wrap/filter bits). + let samp_a: [u32; 4] = [0x0000_0092, 0x00C0_0000, 0x1850_0000, 0]; + let samp_b: [u32; 4] = [0x0000_0092, 0x00C0_0000, 0x1850_0001, 0]; + + for (case_name, alt) in [("same_sampler", samp_a), ("different_samplers", samp_b)] { + let mut words = Vec::new(); + // s[2:3] = view table base (s0, 0). + words.push(0xBE80_0300 | (2 << 16)); // s_mov_b32 s2, s0 + words.push(s_mov_zero(3)); + words.extend_from_slice(&s_load_x8(8, 2)); // s[8:15] = texture SRV (offset 0) + words.extend_from_slice(&s_load_x4_off(20, 2, 64)); // s[20:23] = raw UAV (offset 16 dwords = 64B) + // v2 = 0.5, v3 = 0.5 (sample coordinates). + words.push(0x7E00_02F0 | (2 << 17)); // v_mov_b32 v2, 0.5 + words.push(0x7E00_02F0 | (3 << 17)); // v_mov_b32 v3, 0.5 + // s_cmp_eq_u32 s1, 0; s_cbranch_scc0 else_arm + words.push(0xBF00_8001); // s_cmp_eq_u32 s1, 0 (const 128) + let br_else = words.len(); + words.push(0); // placeholder s_cbranch_scc0 + // then arm: load samp_a into s[16:19] + for (i, &w) in samp_a.iter().enumerate() { + words.extend_from_slice(&s_mov_lit(16 + i as u8, w)); + } + let br_join = words.len(); + words.push(0); // placeholder s_branch + let else_pc = words.len(); + // else arm: load alt into s[16:19] + for (i, &w) in alt.iter().enumerate() { + words.extend_from_slice(&s_mov_lit(16 + i as u8, w)); + } + let join_pc = words.len(); + words[br_else] = 0xBF84_0000 | ((else_pc - br_else - 1) as u32 & 0xFFFF); + words[br_join] = 0xBF82_0000 | ((join_pc - br_join - 1) as u32 & 0xFFFF); + words.extend_from_slice(&image_sample_lz); + words.extend_from_slice(&buf_store); + words.push(0xBF81_0000); // s_endpgm + + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 1, + slot: 1, + }, + ], + used: vec![ + UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }, + UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 16, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }, + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + + let p = ir::build(&native.code, false, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); + let io = io::raise(&p, &native).expect("io::raise"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .unwrap_or_else(|e| panic!("{case_name}: lower failed: {e}")); + + let static_samplers = lowered + .samplers + .iter() + .map(|&w| super::StaticSampler::from_words(w)) + .collect(); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers, + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: Vec::new(), + }; + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + continue; + }; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{case_name}/{label}: compute_pipeline failed: {e}")); + for branch in [0u32, 1u32] { + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.slot) { + (RootType::Table, 0) => 0, + (RootType::Constants, 1) => branch, + other => panic!("unexpected user data {other:?}"), + }; + } + let texels = [[1.0f32, 0.0, 0.0, 1.0]]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[ + View::Texture(1, 1, &texels), + View::Texture(1, 1, &texels), + View::RawUav(1), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{case_name}/{label}: dispatch failed: {e}")); + let got = f32::from_bits(out[0][0]); + assert_eq!(got, 1.0, "{case_name}/{label} branch={branch}"); + } + } + } +} From 39309893558859cf8a01c2a8d1f0a09fd3000ae5 Mon Sep 17 00:00:00 2001 From: oddiums Date: Tue, 24 Nov 2026 14:35:00 -0600 Subject: [PATCH 125/445] Fix mesh pipeline test on unsupported GPUs (#14) --- crates/victory-gpu/src/pipeline/host.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 603528e..e8d4579 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -902,6 +902,10 @@ mod tests { let Some(host) = host() else { return; // no host GPU here }; + if !host.mesh_shaders() { + eprintln!("no host mesh shader support; skipped"); + return; + } let Some(dxc) = dxc() else { eprintln!("no PC dxc.exe; skipped"); return; @@ -911,6 +915,8 @@ mod tests { let ps = compile(&dxc, dir.path(), PS, "ps_6_5"); let (root, root_blob) = root_signature(&host.device, &[], &[], false).unwrap(); let mut g = GraphicsState::default(); + // This pipeline has only a color target, with no depth buffer. + g.depth.DepthEnable = false.into(); g.targets.NumRenderTargets = 1; g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; let name = super::super::library::name("mesh test", &root_blob, &[&ms, &ps], &g.describe()); From 90228a7dc66010281fdcfad10ac00c3a252be2f3 Mon Sep 17 00:00:00 2001 From: cxccxc <35392417+cxchhh@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:35:04 +0800 Subject: [PATCH 126/445] Shaders: restore parked lane-mask pairs a few instructions apart; relative VGPR reads keep parked lanes (#11) The console compiler parks a wave64 lane mask in two lanes of a spare VGPR and may restore the halves with other instructions between the two v_readlane_b32. The pair restore now looks ahead in the block (nothing between may touch the second register, write the first, or save into the lanes), so the mask comes back as a mask. This lets indirect_light_probes CS_IrradianceCache_Shade / ShadeSecondary translate: they were dropped every frame, leaving the irradiance cache unlit and everything in shadow black. An M0-relative read (v_movrels_b32) names every VGPR from its base up, which marked the parking VGPR as an ordinary one and turned unspilling off for the whole program. Relative reads no longer count there (relative writes still do). billboard_nobump CS_RaytracingResolve_a56bfb9c translates with it. translate: VICTORY_TRANSLATE_ONLY= limits a run to those containers; VICTORY_HOST_MAX_WAVE=32 translates as on a 32-lane host, so --pipelines matches what the runtime creates on NVIDIA. Co-authored-by: Claude Opus 5.5 --- apps/victory/src/translate.rs | 19 ++++++++++++++++ crates/victory-shader/src/ir.rs | 40 ++++++++++++++++++++++++++++++--- 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index dc5d6c8..1d13ae2 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -160,6 +160,11 @@ pub fn run( jobs: Option, ) -> Result<()> { let paths = crate::default_paths(paths)?; + // `VICTORY_HOST_MAX_WAVE=32`: translate as for a host whose waves have + // at most 32 lanes (as the runtime does on such a card). + if let Some(n) = std::env::var("VICTORY_HOST_MAX_WAVE").ok().and_then(|v| v.parse().ok()) { + victory_shader::emit::set_host_max_wave(n); + } let dll = validate.then(Validator::default_path).flatten(); if validate { Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?; @@ -315,6 +320,20 @@ fn translate( // The hash a run's log names the shader by (`hash=` in "first bind", // "shader does not translate", "host pipeline refused"). let hash = blake3::hash(&bytes).to_hex()[..16].to_owned(); + // Diagnostics: `VICTORY_TRANSLATE_ONLY=,...` translates + // those containers alone. + static ONLY: std::sync::OnceLock> = std::sync::OnceLock::new(); + let only = ONLY.get_or_init(|| { + std::env::var("VICTORY_TRANSLATE_ONLY") + .unwrap_or_default() + .split(',') + .map(|h| h.trim().to_lowercase()) + .filter(|h| !h.is_empty()) + .collect() + }); + if !only.is_empty() && !only.iter().any(|o| hash.starts_with(o.as_str())) { + return; + } let example = || format!("{}{} #{hash}", path.display(), source.label()); t.containers += 1; let Ok(container) = Container::parse(&bytes) else { diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 01907b2..0b8fd9c 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -280,6 +280,7 @@ fn unspill( let mut used = [false; 128]; let mut parks: Vec> = Vec::with_capacity(list.len()); let mut written: Vec> = Vec::with_capacity(list.len()); + let mut read: Vec> = Vec::with_capacity(list.len()); for inst in list.iter() { let Some(name) = inst.name() else { return Vec::new() }; let fields = inst.fields(wave64); @@ -288,13 +289,28 @@ fn unspill( return Vec::new(); }; let mut codes = Vec::new(); + let mut from = Vec::new(); if let Some((reads, writes)) = effects { for ® in &writes { if let Reg::S(c) = reg { codes.push(c); } } - for reg in reads.into_iter().chain(writes) { + for ® in &reads { + if let Reg::S(c) = reg { + from.push(c); + } + } + // An M0-relative read (`v_movrels_b32`) names every VGPR from its + // base up; the compiler indexes a small array with it, never the + // lanes it parks scalars in, so it does not make those VGPRs + // ordinary ones. (Relative writes still do.) + let relative = name == "v_movrels_b32"; + let n_reads = reads.len(); + for (k, reg) in reads.into_iter().chain(writes).enumerate() { + if relative && k < n_reads && matches!(reg, Reg::V(_)) { + continue; + } match reg { Reg::S(c) => used[usize::from(c)] = true, Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true, @@ -305,6 +321,7 @@ fn unspill( } parks.push(park); written.push(codes); + read.push(from); } for (i, park) in parks.iter_mut().enumerate() { if park.is_some_and(|p| other[usize::from(p.1)]) { @@ -347,8 +364,25 @@ fn unspill( } None } else { - let j = i + 1; - (j < list.len() && !leader(j) && parks[j] == Some((false, reg, code + 1, lane + 1))).then_some(j) + // The second restore may come a few instructions later (the + // compiler schedules other work between the two): the pair is + // restored at the first, so nothing between may read or write + // the second register, write the first, or save into the lanes. + let mut j = i + 1; + while j < list.len() && !leader(j) { + if parks[j] == Some((false, reg, code + 1, lane + 1)) { + return Some(j); + } + if parks[j].is_some_and(|p| p.0 && p.1 == reg && (p.3 == lane || p.3 == lane + 1)) + || written[j].contains(&code) + || written[j].contains(&(code + 1)) + || read[j].contains(&(code + 1)) + { + return None; + } + j += 1; + } + None } }; let mut pairs: Vec<(u8, u32)> = Vec::new(); From 4e17478b9c27bb530643e5b0e16a767cf4419e08 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:45:05 -0500 Subject: [PATCH 127/445] The game is no longer named in the tree Comments, documents and descriptions now say "the title". No code changes. Co-Authored-By: Claude Fable 5.2 --- README.md | 14 +++++----- apps/victory/src/run.rs | 4 +-- crates/victory-core/src/config.rs | 2 +- crates/victory-game/Cargo.toml | 2 +- crates/victory-game/src/lib.rs | 4 +-- crates/victory-gpu/src/capture.rs | 6 ++-- crates/victory-gpu/src/console.rs | 2 +- crates/victory-gpu/src/descriptor.rs | 10 +++---- crates/victory-gpu/src/descriptor/host.rs | 6 ++-- crates/victory-gpu/src/device.rs | 10 +++---- crates/victory-gpu/src/draw.rs | 8 +++--- crates/victory-gpu/src/dxgi.rs | 2 +- crates/victory-gpu/src/fence.rs | 2 +- crates/victory-gpu/src/frame.rs | 2 +- crates/victory-gpu/src/host.rs | 6 ++-- crates/victory-gpu/src/indirect.rs | 2 +- crates/victory-gpu/src/list.rs | 24 ++++++++-------- crates/victory-gpu/src/pipeline.rs | 4 +-- crates/victory-gpu/src/pipeline/make.rs | 4 +-- crates/victory-gpu/src/primitive.rs | 2 +- crates/victory-gpu/src/queue.rs | 6 ++-- crates/victory-gpu/src/resource.rs | 28 +++++++++---------- crates/victory-gpu/src/root.rs | 2 +- crates/victory-gpu/src/shadow.rs | 4 +-- crates/victory-hle/src/modules/audio.rs | 2 +- crates/victory-hle/src/modules/display.rs | 2 +- crates/victory-hle/src/modules/dstorage.rs | 22 +++++++-------- crates/victory-hle/src/modules/files.rs | 2 +- crates/victory-hle/src/modules/gameinput.rs | 12 ++++---- crates/victory-hle/src/modules/lifecycle.rs | 8 +++--- crates/victory-hle/src/modules/storage.rs | 2 +- crates/victory-hle/src/modules/xg.rs | 6 ++-- crates/victory-hle/src/modules/xgame.rs | 4 +-- .../victory-hle/src/modules/xgameruntime.rs | 2 +- crates/victory-hle/src/modules/xgamesave.rs | 2 +- crates/victory-hle/src/modules/xgameui.rs | 4 +-- crates/victory-hle/src/modules/xmem.rs | 22 +++++++-------- crates/victory-hle/src/modules/xnetworking.rs | 2 +- crates/victory-hle/src/modules/xpackage.rs | 8 +++--- crates/victory-hle/src/modules/xstore.rs | 2 +- crates/victory-hle/src/modules/xsystem.rs | 2 +- crates/victory-hle/src/modules/xuser.rs | 2 +- crates/victory-hle/src/runtime.rs | 2 +- crates/victory-loader/src/console_insn.rs | 2 +- crates/victory-loader/src/tls.rs | 2 +- crates/victory-shader/src/bvh.rs | 2 +- crates/victory-shader/src/emit/diff_tests.rs | 8 +++--- crates/victory-shader/src/emit/lower.rs | 18 ++++++------ crates/victory-shader/src/emit/mod.rs | 4 +-- crates/victory-shader/src/emit/rect.rs | 4 +-- crates/victory-shader/src/resource.rs | 10 +++---- crates/victory-shader/src/spill.rs | 2 +- docs/architecture.md | 2 +- docs/fork-ray-tracing.md | 2 +- victory.example.toml | 2 +- 55 files changed, 161 insertions(+), 161 deletions(-) diff --git a/README.md b/README.md index c00d992..7dc43e2 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ -# victory-gta6 +# VIctory fork (work in progress) -A work-in-progress fork of [VIctory](https://github.com/Marvisak/VIctory), the -compatibility layer that runs the Xbox Series build of Grand Theft Auto VI -natively on Windows from files the user supplies. This fork follows upstream +A work-in-progress fork of [VIctory](https://github.com/Marvisak/VIctory), a +compatibility layer that runs an Xbox Series title natively on Windows from +files the user supplies. This fork follows upstream `main` and adds fixes aimed at one goal: getting the game's world to render correctly and playably on one particular PC. **This repository contains no game files, code or assets.** You need your own -copy of the game. It is not affiliated with or endorsed by Rockstar Games or -Take-Two Interactive. +copy of the game. It is not affiliated with or endorsed by the game's +developer or publisher. ## Credits @@ -80,7 +80,7 @@ status section describes upstream, not this fork. # VIctory -Runs Grand Theft Auto VI (Xbox Series X|S) natively on Windows, from files +Runs the title (Xbox Series X|S) natively on Windows, from files the user supplies. The title's x86-64 code runs unchanged inside our process; VIctory supplies diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index a73aecb..dc5bf71 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -32,7 +32,7 @@ pub fn run( let image = victory_loader::load(&prepared, &images)?; // The program is mapped from the copy `load` wrote: the file's bytes // and their patched copy are not read again, and were held for the - // whole run (two blocks of 114.7 MB each for Grand Theft Auto VI, in + // whole run (two blocks of 114.7 MB each for the title, in // physical memory: run 65's memory map). drop(prepared); drop(original); @@ -192,7 +192,7 @@ fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool { } /// Title DLLs the title loads itself (`LoadLibrary`) that nothing imports, -/// e.g. Grand Theft Auto VI's upscaler behind its FidelityFX loader. +/// e.g. The title's upscaler behind its FidelityFX loader. #[cfg(windows)] struct LateDlls { host: victory_hle::HostPolicy, diff --git a/crates/victory-core/src/config.rs b/crates/victory-core/src/config.rs index 72e6659..b65014e 100644 --- a/crates/victory-core/src/config.rs +++ b/crates/victory-core/src/config.rs @@ -13,7 +13,7 @@ use crate::policy::ensure_outside_repo; #[derive(Debug, Default, Clone)] pub struct Config { - /// The user's dump of Grand Theft Auto VI. + /// The user's dump of the title. pub game_dir: Option, /// Root for all derived data. Always outside the repository. pub cache_dir: PathBuf, diff --git a/crates/victory-game/Cargo.toml b/crates/victory-game/Cargo.toml index b6239d6..90d931b 100644 --- a/crates/victory-game/Cargo.toml +++ b/crates/victory-game/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "victory-game" -description = "Everything specific to Grand Theft Auto VI: its containers, build identities, patches." +description = "Everything specific to the title: its containers, build identities, patches." version.workspace = true edition.workspace = true rust-version.workspace = true diff --git a/crates/victory-game/src/lib.rs b/crates/victory-game/src/lib.rs index 008bbc8..affa682 100644 --- a/crates/victory-game/src/lib.rs +++ b/crates/victory-game/src/lib.rs @@ -1,11 +1,11 @@ -//! Everything specific to Grand Theft Auto VI: its container formats, build +//! Everything specific to the title: its container formats, build //! identities, and the hooks we place in its code (located by per-build //! offsets or byte-pattern signatures). What may and may not be stored here //! is defined in docs/asset-policy.md. pub mod sgd5; -/// A specific build of the Grand Theft Auto VI executable we know how to run. +/// A specific build of the title executable we know how to run. #[derive(Debug, Clone, Copy)] pub struct KnownBuild { /// Our own label, e.g. "1.0.0 retail". diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index 507e334..97bc116 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -31,11 +31,11 @@ pub(crate) fn listed(n: u64) -> bool { // `VICTORY_CAPTURE_WORLD`: also the 2nd and the 6th frame after the first // one that ran 500 draws or more (a title's first 3D frames: their // numbers depend on how long the menus were shown), and the 30th and - // the 80th (Grand Theft Auto VI opens with a cutscene made in the + // the 80th (the title opens with a cutscene made in the // engine: later shots of it, in case the first is dark by design). // // `VICTORY_CAPTURE_WORLD_ALSO` (comma-separated): more frames counted - // from that first one (Grand Theft Auto VI's blue patches show from + // from that first one (the title's blue patches show from // about the 118th frame on, when the window's model has arrived and // the reflections hold values: none of the four above has them). static ALSO: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -63,7 +63,7 @@ pub(crate) fn op(list: usize, what: impl FnOnce() -> String) { if !listed(frame) { // Before the world: the last lines are kept, and written out when // it starts (`before-world-ops.txt`): what the title drew just - // before (Grand Theft Auto VI shows a title card there, whose text + // before (the title shows a title card there, whose text // did not show). if world_on() && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX { // At most 300 lines of a frame: the world's first frame alone diff --git a/crates/victory-gpu/src/console.rs b/crates/victory-gpu/src/console.rs index 6070d2d..ab7252c 100644 --- a/crates/victory-gpu/src/console.rs +++ b/crates/victory-gpu/src/console.rs @@ -17,7 +17,7 @@ impl Console { /// advanced configuration; Series S has one range, counted as standard /// (7,776 MiB, the published console-mode figure). // shortcut: later system updates gave Series S titles more (amount not - // published here); Grand Theft Auto VI sizes nothing from this figure + // published here); the title sizes nothing from this figure // (it goes by the device type), so update it if a title does. pub const fn title_memory(self) -> (usize, usize) { match self { diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index ab2875a..8485014 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -34,7 +34,7 @@ pub(crate) struct HeapDesc { nodes: u32, } -/// Newer titles (Grand Theft Auto VI) pass the description followed by +/// Newer titles (the title) pass the description followed by /// memory of their own for the descriptors: an address and its size in /// bytes, or a null address to have the heap allocate (inferred from the /// title's call sites; older titles pass the plain description). @@ -73,7 +73,7 @@ impl Heap { } /// The host heap, made on first use from what the title wrote so far. - /// Made late because a host view heap the size of Grand Theft Auto VI's + /// Made late because a host view heap the size of the title's /// costs over 100 MB of commit, which its boot needs for its page pool. #[cfg(windows)] pub(crate) fn host(&self) -> Option<&host::HostHeap> { @@ -330,7 +330,7 @@ impl View { /// Views without a resource object have nothing that releases them, and a /// title copies descriptors as bytes, so nothing says when the last /// descriptor naming an entry is gone: such entries were kept for the run. -/// Grand Theft Auto VI writes some 14,000 constant buffer views a frame, +/// The title writes some 14,000 constant buffer views a frame, /// each at the address its constants have that frame: 2,450,139 entries /// after four minutes of play, 1,047 MB with the index, and 11,000 more /// every second (run 65). So the two kinds that carry an address are not @@ -600,7 +600,7 @@ impl View { /// Title slots (their handles) written with a view of a texture object /// that had no host copy then, by texture. A title texture gets its host -/// copy on first use (`resource.rs` `Hosted`), and Grand Theft Auto VI +/// copy on first use (`resource.rs` `Hosted`), and the title /// writes each texture's views into its view heap when it creates the /// texture: making those host slots would make every host copy at once. /// They are made when the texture is: translated shaders index the heap @@ -1157,7 +1157,7 @@ mod tests { assert_ne!(old, new, "a new generation"); } - /// Grand Theft Auto VI places its shader-visible heap in its own memory + /// The title places its shader-visible heap in its own memory /// and checks that the heap starts there. #[test] fn placed_heaps_start_at_the_title_memory() { diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index cc061c7..e91db79 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -76,7 +76,7 @@ pub(crate) struct HostHeap { /// the last [`TABLED_FRAMES`] frames is due only [`TABLED_GRACE`] /// frames later, by when its draw has read it. A title that builds a /// table per draw writes thousands of texture views a frame into slots - /// only tables read (Grand Theft Auto VI: some 2,500 a frame in its + /// only tables read (the title: some 2,500 a frame in its /// opening cutscene, a few hundred textures over and over), and every /// one of them stood in the queue of textures picked by index, ahead /// of or behind the ones shaders do pick by index. @@ -252,7 +252,7 @@ const TABLED_FRAMES: u64 = 240; /// Frames a write of a table's slot waits in the queue for the draw that /// reads it, before the slot is taken for one shaders pick by index. /// Frames as `crate::frame::current` counts them: in its opening cutscene -/// Grand Theft Auto VI begins two or three of them per frame it presents +/// The title begins two or three of them per frame it presents /// (435 begun in the 353 s of run 52's, for some 140 presented). const TABLED_GRACE: u64 = 8; @@ -512,7 +512,7 @@ const PORTABLE_VIEWS: u32 = 1_000_000; /// Asks the host, once, whether it caps view heaps at [`PORTABLE_VIEWS`], /// and if so tells the translator now (`set_view_heap_limit`) instead of /// when the title's heap is made: a shader keeps the limit it was -/// translated with, and Grand Theft Auto VI makes 25 pipelines (their +/// translated with, and the title makes 25 pipelines (their /// shaders translated at once) before it makes its view heap. Those would /// read a view index past the heap unclamped, the read that hangs NVIDIA. /// Called before a shader is translated. diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index 3b19f53..dfbf2b2 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -29,7 +29,7 @@ pub static IID: Iid = guid( ); /// The levels the device answers to, as on PC: `ID3D12Device1` to -/// `ID3D12Device8`, and `ID3D12Device11`, which Grand Theft Auto VI creates +/// `ID3D12Device8`, and `ID3D12Device11`, which the title creates /// its device as. Each level's table is the one before plus its methods. const LEVEL_IIDS: [Iid; 9] = [ guid( @@ -94,7 +94,7 @@ pub(crate) fn is_device(iid: *const Iid) -> bool { } /// The interface version these layouts were checked against (2.4). Both -/// Minecraft (March 2022) and Grand Theft Auto VI (April 2026) pass it. +/// Minecraft (March 2022) and the title (April 2026) pass it. pub const CHECKED_VERSION: u32 = 0x0002_0004; /// Feature level 12_2, what the console hardware supports. @@ -160,7 +160,7 @@ pub extern "system" fn create( /// queues then have the newer layouts (two more methods each; see /// `list` and `queue`), although the interface version stays 2.4. /// shortcut: the creation interface is the only sign of the newer layouts -/// we have (Grand Theft Auto VI, April 2026, versus Minecraft, March 2022); +/// we have (the title, April 2026, versus Minecraft, March 2022); /// look for a better one if a title breaks the rule. static NEWER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); @@ -346,7 +346,7 @@ fn feature_levels(data: *mut c_void) -> HRESULT { } } -/// Device methods 0x1c8 and 0x218 (`SLOT`). Grand Theft Auto VI calls both +/// Device methods 0x1c8 and 0x218 (`SLOT`). The title calls both /// (title+0x2477578 and title+0x24800d5) as `(this, description, interface /// id, out)`, asks for `ID3D12PipelineState`, and on success keeps the /// object `out` names and draws with it; on failure it goes without that @@ -490,7 +490,7 @@ mod tests { #[test] fn newer_device_levels_are_the_same_device() { - // ID3D12Device11, as Grand Theft Auto VI asks for it. + // ID3D12Device11, as the title asks for it. let (hr, device) = create_as(&LEVEL_IIDS[8]); assert_eq!((hr, device), (S_OK, super::device())); let mut same = std::ptr::null(); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index f9937b1..aebefde 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -124,7 +124,7 @@ const WINDOW_MOST: u64 = 64; /// /// The step is the one the title is seen to take, not the stride its /// command signature names: it draws one record a call, for which the -/// stride means nothing, and Grand Theft Auto VI names 12 bytes (the three +/// stride means nothing, and the title names 12 bytes (the three /// words of a mesh dispatch) for records it keeps 32 bytes apart (2,173 of /// a frame's 3,349 mesh records in run 87's listed frame; 283 are 16 /// apart, which ends a window). Walked by the named stride the window @@ -235,7 +235,7 @@ impl State { } /// An experiment on the title's scissor rectangles (`VICTORY_SCISSOR_TEST=full`): -/// they are all widened to the whole target. Grand Theft Auto VI's room at +/// they are all widened to the whole target. The title's room at /// the start of the prologue lost its walls in five runs of seven, and in /// those runs the player's body and the world outside were cut by one /// rectangle around the window (run 85, frame 2046): one run with this on @@ -1739,7 +1739,7 @@ impl State { let targets: Vec = self.targets.iter().filter_map(|&t| described(t)).collect(); let _ = write!(text, " targets {targets:?} depth {:?} state [{}]", described(self.depth), p.state); // The title's scissor and viewport at this draw (the first of - // each): Grand Theft Auto VI draws what it sees through a + // each): the title draws what it sees through a // portal (a window, from inside a room) under the portal's // rectangle, and the listing did not say which draws those are. if let Some(r) = self.scissors.first() { @@ -2291,7 +2291,7 @@ impl State { crate::pipeline::note_drop(self.pipeline as This); return false; }; - // Indirect rectangles (Grand Theft Auto VI's tiled lighting, 256 + // Indirect rectangles (the title's tiled lighting, 256 // indirect draws a frame, makes their corners from the vertex // number) are completed by the pipeline's geometry stage: the // arguments stay the title's, three vertices a rectangle. They diff --git a/crates/victory-gpu/src/dxgi.rs b/crates/victory-gpu/src/dxgi.rs index 58640ac..af10227 100644 --- a/crates/victory-gpu/src/dxgi.rs +++ b/crates/victory-gpu/src/dxgi.rs @@ -240,7 +240,7 @@ fn display_size() -> (u32, u32) { }) } -/// The console's mode list: one 4K mode at 60 Hz (Grand Theft Auto VI looks +/// The console's mode list: one 4K mode at 60 Hz (the title looks /// for a 120 Hz one to allow 120 Hz frame intervals). /// shortcut: fixed mode, not the host display's; report the host's rates if /// a title paces by them. diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 7712461..98daa89 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -182,7 +182,7 @@ mod tests { // SAFETY: as above. assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL); - // Grand Theft Auto VI reads the value at the fence's address. + // The title reads the value at the fence's address. let at = slot:: u64>(f, 0x60)(f); // SAFETY: the fence's value. assert_eq!(unsafe { *(at as *const u64) }, 5); diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 0b591d9..798b760 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -2,7 +2,7 @@ //! to begin. Ours is a clock started by the first interval set, ticking //! once per interval; the token is the frame number. Each event kind //! (origin, vblank, flip) happens once per tick, so two waits for the same -//! kind never end on the same tick: Grand Theft Auto VI polls the origin +//! kind never end on the same tick: the title polls the origin //! with "token on time-out" (starting its next frame at once) and is paced //! by a blocking wait for the flip before each present. //! diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 9ecf3be..cb57a59 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -808,7 +808,7 @@ struct TwinUse { /// /// A 16-bit twin holds whole steps of 1/65535, and the depth written is /// the step times the float nearest 1/65535 (0x37800080). That is how -/// Grand Theft Auto VI's tiled lighting computes the depth of the +/// The title's tiled lighting computes the depth of the /// rectangles it then draws with the test "equal", one class of materials /// a draw (all six of its vertex shaders multiply the class number by that /// constant), so the pass and the draw give the host the same float, and @@ -1129,7 +1129,7 @@ fn record_twin_copy( // shortcut: the depth plane's twin is not given the plane (that is a // pass the other way: the plane read by a shader, the twin as its // target). The twin then lacks what draws and clears wrote to the - // plane since shaders last wrote the twin. In Grand Theft Auto VI + // plane since shaders last wrote the twin. In the title // nothing writes that plane but the twin's pass (its 192 draws against // it only test, run 29), so the twin lacks nothing. Counted. if colour && twin.plane.is_some() { @@ -4636,7 +4636,7 @@ impl HostList { /// are given what was written, and left readable by shaders. Shaders /// that pick a view from the heap by a computed index are not seen by /// `twin_use` and read the depth texture in lists that never name it - /// (in a captured frame of Grand Theft Auto VI no table names a shadow + /// (in a captured frame of the title no table names a shadow /// map for reading but the pass that fills the next one). fn twins_to_depth(&self) { const SHADER_RESOURCE: u32 = 0x40 | 0x80; diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 8edcece..bff1577 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -85,7 +85,7 @@ void main(uint3 id : SV_DispatchThreadID) { // Mesh dispatches: the console's are one-dimensional. uint3 g = src_args.Load3(src_at); // Ahead of its draw, a record over the most a dispatch runs is a - // slot the title has not filled (Grand Theft Auto VI leaves all + // slot the title has not filled (the title leaves all // ones there): empty, and not counted below either. if (ahead && g.x > 65535u) { g = uint3(0, 0, 0); diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index f004b05..8ce9856 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -32,7 +32,7 @@ const ALLOCATOR_IIDS: [Iid; 4] = [ /// The list interfaces up to `ID3D12GraphicsCommandList6` (the table has /// all their slots): those whose ids are the same as on PC, the console's -/// own List5 and List6 (Grand Theft Auto VI asks for List6), then the +/// own List5 and List6 (the title asks for List6), then the /// device child's. const LIST_IIDS: [Iid; 10] = [ guid( @@ -106,7 +106,7 @@ struct List { graphics_root_headers: [u32; 128], compute_root_headers: [u32; 128], pipeline_shadow: [u32; 8], - /// Newer titles' lists are larger: Grand Theft Auto VI's state flush + /// Newer titles' lists are larger: the title's state flush /// (title+0x32786) copies a pipeline's 32 bytes to +0x544..+0x564 and /// tests +0x548, so its layout runs past 0x560. Its size is unknown; /// this keeps our fields clear of whatever the title writes there. @@ -921,8 +921,8 @@ extern "system" fn copy_texture_region( let Some(to) = crate::resource::host_resource(dst.resource) else { // Texture to buffer: a read back. The list copies the texels // into a host buffer of ours; once it has run they go to the - // title's buffer (`HostList::defer_read_back`). Grand Theft - // Auto VI reads two tiny float targets back every frame (5x1 + // title's buffer (`HostList::defer_read_back`). + // The title reads two tiny float targets back every frame (5x1 // and 1x1 RGBA32F, 80 and 16 bytes: run 90), and read a buffer // nobody wrote. `VICTORY_READ_BACK=0` leaves them unmade, as // before. @@ -1406,7 +1406,7 @@ extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: /// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list /// owns until it is reset, which the CPU writes and the GPU reads at the -/// same address; null on failure. Grand Theft Auto VI's BVH builder puts +/// same address; null on failure. The title's BVH builder puts /// its instance descriptions there (and wrote through our old /// `E_NOTIMPL` as a pointer). extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 { @@ -1672,7 +1672,7 @@ extern "system" fn draw(_: This) { } /// `ExecuteIndirect(signature, max count, arguments, offset, count buffer, -/// offset)`. Grand Theft Auto VI's signatures (title+0x2479466, 2026-11-24) +/// offset)`. The title's signatures (title+0x2479466, 2026-11-24) /// hold one argument each: draw (stride 16), indexed draw (20), dispatch /// (12), mesh dispatch (12), and the console's single-pass dispatch, type /// 105 (stride 12: the three group counts; its flags live in the @@ -1778,7 +1778,7 @@ impl ValueWait { /// end of the region: the title keeps these values in a 1.1 GB /// allocation (0xd00000000), where one question took about 8 ms, and a /// queue asks at every submission and every signal, for each queue that - /// stands at a wait (Grand Theft Auto VI has five queues). That was + /// stands at a wait (the title has five queues). That was /// 1.0-2.2 s of every cutscene frame on the thread that submits (runs /// 36-49: "between its submissions ... kernel"; 47 of 110 looks at /// that thread in run 49 found it in this question). @@ -1847,7 +1847,7 @@ static VALUE_WAITS: std::sync::Mutex> = std::sync::Mutex /// The waits of the submitted `lists` that are not met yet (taken from /// them): what the console's GPU would stop at. The title orders work -/// between its queues this way (Grand Theft Auto VI: the compute queue's +/// between its queues this way (the title: the compute queue's /// lighting passes wait for a value the graphics queue's depth pass writes /// at the bottom of the pipe; run at once, they read a cleared depth /// buffer and nothing was lit). @@ -1985,7 +1985,7 @@ extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, fl /// the host list is cut right behind it, so that the value is stored when /// the card has run the list up to there, as on the console, and not when /// the whole list has run. Lists of other queues wait for these values -/// (Grand Theft Auto VI: the compute list that builds the depth pyramid +/// (the title: the compute list that builds the depth pyramid /// waits for one, and the meshlet culling of the same frame reads that /// pyramid). Off by default: every such write then ends a host list, and /// each part is a submission of its own. @@ -2126,7 +2126,7 @@ const MORE_METHODS: [(usize, *const ()); 9] = [ /// base list, after the clears (0x198/0x1a0 as before) and before /// ExecuteIndirect, which moved from 0x1d8 to 0x1e8: every slot from 0x1d8 /// on is two later (taken here as starting exactly at 0x1d8). Inferred from -/// Grand Theft Auto VI's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe +/// The title's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe /// writes 0x238/0x240, waits 0x248/0x250, depth bounds 0x230, shading rate /// 0x3f0/0x400, syncs 0x418/0x420, ResetX 0x458 (asserts on failure). const fn newer_slot(slot: usize) -> usize { @@ -2136,7 +2136,7 @@ const fn newer_slot(slot: usize) -> usize { /// Methods only newer titles' lists have. 0x490: the enhanced barrier /// `(group count, groups)`, with 16-byte groups `(type, count, barriers)` /// and 40-byte buffer barriers (title+0x95e0 builds them). 0x470 `(u64)`, -/// called from Grand Theft Auto VI's state flush with its result unused. +/// called from the title's state flush with its result unused. /// shortcut: 0x470's purpose is unknown; ignored until a title shows it /// matters. const NEWER_METHODS: [(usize, *const ()); 3] = [ @@ -2193,7 +2193,7 @@ mod tests { (at(0x18), at(0x28), at(0x30)) }; assert!(put >= draw_limit && put >= api_limit); - // The console's ID3D12GraphicsCommandList6, as Grand Theft Auto VI asks. + // The console's ID3D12GraphicsCommandList6, as the title asks. let mut same = null; assert_eq!(list_query(list, &LIST_IIDS[7], &mut same), S_OK); assert_eq!(same, list); diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 2510fd2..60ed05c 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -4,7 +4,7 @@ //! types. //! //! Host pipelines are made on a pipeline's first draw, not at creation: -//! Grand Theft Auto VI creates some 60,000 pipelines in its first 20 +//! The title creates some 60,000 pipelines in its first 20 //! seconds and draws with a few dozen (decision 0007, step 3). Shader //! containers are shared by content hash and translated once, on first //! use (decision 0003). @@ -787,7 +787,7 @@ mod tests { assert_eq!(slot:: u32>(p, 0x10)(p), 0); } - /// The stream layout Grand Theft Auto VI builds (title+0x86f090): root + /// The stream layout the title builds (title+0x86f090): root /// signature, five shader slots (the first a mesh shader), blend, sample /// mask, rasterizer, depth-stencil 1, sample description, input layout, /// topology, render target and depth formats: 0x2b0 bytes. diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 49c26c6..9862446 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -1,8 +1,8 @@ //! Host pipelines are made by workers, not by the title thread that first //! records a draw with them. Translating a shader and the host driver's //! compile take from milliseconds to seconds each (structurisation of the -//! biggest compute programs ~0.4 s, some driver compiles 3.4 s), and Grand -//! Theft Auto VI's first world frame wants over 1,200 new pipelines: made +//! biggest compute programs ~0.4 s, some driver compiles 3.4 s), and +//! the title's first world frame wants over 1,200 new pipelines: made //! on its recording threads, that frame took more than 30 s and the //! title's GPU watchdog ended the run (decision 0007, "Pipelines made off //! the title's threads"). diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index 91a23ee..3f73ee7 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -1,6 +1,6 @@ //! Console primitive types the host lacks. A rectangle list gives three //! corners per rectangle, the second the one between the other two, and -//! the hardware adds the fourth at `v0 + v2 - v1` (Grand Theft Auto VI's +//! the hardware adds the fourth at `v0 + v2 - v1` (the title's //! full-screen rectangles come as top left, bottom left, bottom right); on //! the host each rectangle becomes two triangles, with the fourth vertex //! made from the other three on the CPU. diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 1335401..11d3a8c 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -896,7 +896,7 @@ const PAGE: u64 = 64 << 10; /// `CopyPageMappingsBatchX(count, batches, pool, pool pages, flags)`: maps /// pages of a pool (memory the title mapped physical pages into) at the -/// batches' addresses. Grand Theft Auto VI streams textures into pool pages +/// batches' addresses. The title streams textures into pool pages /// and maps them into its tiled heap this way (title+0xf2c470, ranges of /// one constant page or of unmapped pages). Done at once: every earlier /// submission has run. @@ -978,7 +978,7 @@ const METHODS: [(usize, *const ()); 15] = [ /// Newer titles' queues have two more methods before Signal, which moved /// from 0x70 to 0x80: every slot from 0x70 on is two later (taken here as /// starting exactly at 0x70, the methods before it kept in place). -/// Inferred from Grand Theft Auto VI's calls: Signal 0x80 `(fence, +/// Inferred from the title's calls: Signal 0x80 `(fence, /// value)`, timestamp frequency 0x90 (title+0x24841a6), suspend and resume /// 0xb8/0xc0, PresentX 0x100, the frame-token submission 0x118 `(count, /// lists, token, flags)` (title+0x24821dd). @@ -1046,7 +1046,7 @@ mod tests { assert_eq!(slot:: u32>(q, 0x10)(q), 0); } - /// Grand Theft Auto VI's compute queue: `{COMPUTE, 0, pipe 1, queue 0}`. + /// The title's compute queue: `{COMPUTE, 0, pipe 1, queue 0}`. #[test] fn console_queues_are_created_as_on_pc() { let null = std::ptr::null(); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 3782a0d..2367d8b 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -178,8 +178,8 @@ fn footprint(desc: &ResourceDesc) -> Option { && let Some(t) = texture_layout(desc) { // As the console: the layout's own alignment unless more is asked - // (4 KiB for 4 KiB modes, where PC says 64 KiB). Grand Theft Auto - // VI keeps these sizes in its texture tables, and its streaming + // (4 KiB for 4 KiB modes, where PC says 64 KiB). + // The title keeps these sizes in its texture tables, and its streaming // asserts when they disagree with the streamed layout. let alignment = desc.alignment.max(t.alignment); if !alignment.is_power_of_two() { @@ -239,8 +239,8 @@ pub(crate) fn pc_format(format: u32) -> u32 { /// The format of a texture the host GPU renders to or writes as unordered /// access, for the title's `format`. The console's GPU does both with the -/// 16-bit colour formats B5G5R5A1 (86) and B4G4R4A4 (115), and Grand Theft -/// Auto VI has full-screen targets in both; a host that refuses either use +/// 16-bit colour formats B5G5R5A1 (86) and B4G4R4A4 (115), and +/// the title has full-screen targets in both; a host that refuses either use /// (NVIDIA) refused the whole texture, so every pass that wrote it drew /// nothing. There 8-bit RGBA stands in: the same channels in the same /// order, every 4-bit level exact and every 5-bit level within 1/510. @@ -327,8 +327,8 @@ pub(crate) fn depth_and_unordered(this: This) -> bool { /// when a side is used after the other was written /// (`HostList::twin_use`). /// shortcut: whole textures are copied, not the mips and slices written. -/// A depth texture with a stencil plane gets a twin for each plane (Grand -/// Theft Auto VI's tiled lighting writes each pixel's material class into +/// A depth texture with a stencil plane gets a twin for each plane ( +/// the title's tiled lighting writes each pixel's material class into /// the depth plane and masks into the stencil plane, then draws each class /// with the depth test "equal"): the stencil plane's is copied through a /// buffer, the depth plane's is drawn into the plane by a pass of ours @@ -921,7 +921,7 @@ static ALLOCATOR: std::sync::OnceLock<(AllocRoutine, FreeRoutine)> = std::sync:: /// Committed resources get their memory from the title's general /// allocator, as on the console, where titles hook it to place graphics -/// memory themselves (Grand Theft Auto VI places its back buffers in a +/// memory themselves (the title places its back buffers in a /// block of its own and checks they fill it). The runtime names it before /// the device exists. pub fn use_allocator(alloc: AllocRoutine, free: FreeRoutine) { @@ -1133,7 +1133,7 @@ pub(crate) struct HostTexture { type Made = (std::sync::Arc, Option>); /// A title texture's host side. The host copy is made when something first -/// uses the texture, not when the title creates it: Grand Theft Auto VI +/// uses the texture, not when the title creates it: the title /// had created 3,871 textures (9.2 GB on the host) before its world's first /// frame, of which a frame's lists name some hundreds (run 23), on a card /// with 12 GB. A title texture is memory the title has either way; its host @@ -1189,7 +1189,7 @@ static TARGETS_AT: std::sync::Mutex> = /// same memory, if there is one of the same size, levels and layers with /// texels of the same width. The console reads such a texture through the /// view as it is -/// (Grand Theft Auto VI packs light as R9G9B9E5 into R32_UINT textures +/// (the title packs light as R9G9B9E5 into R32_UINT textures /// with compute shaders, which cannot write R9G9B9E5, and samples them /// through R9G9B9E5 views placed at the textures' addresses: the sky, the /// sky and light probes, the bounced light the lighting pass adds). On the @@ -1633,7 +1633,7 @@ fn host_texture( d.alignment = 0; d.flags &= PC_FLAGS; // PC refuses depth targets that are also unordered-access (the console - // allows both; Grand Theft Auto VI's shadow maps ask for it). + // allows both; the title's shadow maps ask for it). // The host copy loses the unordered access: shaders write a colour // twin instead ([`Twin`]). const DEPTH: u32 = 2; @@ -1895,7 +1895,7 @@ pub(crate) extern "system" fn create_committed( ) } -/// Device method 0x3f8, inferred from Grand Theft Auto VI's calls +/// Device method 0x3f8, inferred from the title's calls /// (title+0x193e1b4: its back buffers, heap flag "allow display"): the /// committed resource creation of the enhanced-barrier interfaces, /// `(heap, heap flags, desc1, initial layout, clear value, protected @@ -1958,7 +1958,7 @@ pub(crate) extern "system" fn unregister_page_pool(_: This, handle: usize) -> HR } /// Device method 0x428, one of the `ID3D12Device9` to `ID3D12Device11` -/// additions. From Grand Theft Auto VI's call: a resource at a virtual +/// additions. From the title's call: a resource at a virtual /// address the title mapped itself, `(address, desc1, initial barrier /// layout, clear value, iid, out)`, as `CreatePlacedResourceX` with /// enhanced barriers. GPU addresses are CPU addresses, so the resource is @@ -2008,7 +2008,7 @@ pub(crate) extern "system" fn create_at_address( } /// Textures the title placed in its own memory and views without a -/// resource object (device 0x230, Grand Theft Auto VI's streamed and +/// resource object (device 0x230, the title's streamed and /// interface textures), by address and description: a resource at that /// address, made the first time a draw reads one. /// The resource is kept for the run (views and lists name its address); @@ -2346,7 +2346,7 @@ mod tests { slot::(device, 0xd0)(&mut p, device, 1, 1); assert_eq!(p.cpu_pages, 1, "default: not CPU-visible"); - // 0x428: a buffer over memory the title owns, as GTA VI asks. + // 0x428: a buffer over memory the title owns, as the title asks. type At = extern "system" fn( This, u64, diff --git a/crates/victory-gpu/src/root.rs b/crates/victory-gpu/src/root.rs index 10368e9..5bded71 100644 --- a/crates/victory-gpu/src/root.rs +++ b/crates/victory-gpu/src/root.rs @@ -147,7 +147,7 @@ type Deserialize = /// `d3d12_xs!D3D12CreateRootSignatureDeserializer`: our blobs are the /// host's serialization, so the host's deserializer reads them, and its /// object (IUnknown, then the description getter) is laid out as the -/// console's. Grand Theft Auto VI's upscaler asks with the PC interface id. +/// console's. The title's upscaler asks with the PC interface id. pub extern "system" fn create_deserializer( blob: *const u8, size: usize, diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index d170075..58b7d6e 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2838,8 +2838,8 @@ fn lookup(address: u64, len: u64, any: bool) -> Option> { entry.shadow.clone() } -/// Titles also use memory outside any buffer object as GPU memory (Grand -/// Theft Auto VI's interface vertices, from its own allocator). Such memory +/// Titles also use memory outside any buffer object as GPU memory ( +/// the title's interface vertices, from its own allocator). Such memory /// gets copies of the aligned windows it touches. /// A window nothing names any more is let go ([`let_go_idle`]). /// shortcut: a window is 4 MiB however little of it is read (the memory diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index ac34d4c..5ce7551 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -12,7 +12,7 @@ //! Mixed audio leaves through the host's WASAPI, which titles and //! middleware reach through COM like on PC. fmod's console build sets up //! the coprocessor inside `System_Create` and waits there for its first -//! command to be acknowledged; Grand Theft Auto VI uses only XMA contexts. +//! command to be acknowledged; the title uses only XMA contexts. #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] diff --git a/crates/victory-hle/src/modules/display.rs b/crates/victory-hle/src/modules/display.rs index 41f9cbd..fd13187 100644 --- a/crates/victory-hle/src/modules/display.rs +++ b/crates/victory-hle/src/modules/display.rs @@ -36,7 +36,7 @@ pub const CAPTURE_PROVIDER: Guid = Guid::new( 0x4485, [0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27], ); -/// As Grand Theft Auto VI (2026) asks for it; it calls 0x28 (take a +/// As the title (2026) asks for it; it calls 0x28 (take a /// screenshot) with the public API's arguments. pub const CAPTURE_IID_2026: Guid = Guid::new( 0x22e6_72d7, diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 324db9e..48c6086 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -1,7 +1,7 @@ //! The console's DirectStorage (`XCRDAPI.dll`): a factory that opens files //! and creates request queues and status arrays the title polls. Its //! interfaces have grown since 2020 (new interface ids, new slots); the -//! slots here are the ones Grand Theft Auto VI calls, read from its call +//! slots here are the ones the title calls, read from its call //! sites. Slots nobody has needed yet log their offset. //! //! Submitted requests of every queue run on one pool of workers, as the @@ -31,7 +31,7 @@ use super::xasync::{E_INVALIDARG, E_NOTIMPL, E_PENDING}; use super::xgameruntime::{Guid, HRESULT, Methods, Object, S_OK, add_ref, missing, put}; use crate::{HleModule, hle_export}; -/// The factory interface Grand Theft Auto VI asks for. +/// The factory interface the title asks for. const FACTORY: Guid = Guid::new( 0x6295_9d11, 0xd45f, @@ -171,7 +171,7 @@ extern "system" fn create_status_array( } /// The queue's description: as in 2020 (source type, capacity, priority, -/// name), plus a field Grand Theft Auto VI sets to 1. +/// name), plus a field the title sets to 1. #[repr(C)] struct QueueDesc { source_type: u64, @@ -216,7 +216,7 @@ extern "system" fn create_queue( ) } -/// Grand Theft Auto VI asks for 32 MiB and stops if this fails. +/// The title asks for 32 MiB and stops if this fails. extern "system" fn set_staging_buffer_size(_: Factory, size: u32) -> HRESULT { tracing::info!(size, "dstorage: staging buffer size"); if let Some(scheduler) = scheduler() { @@ -289,7 +289,7 @@ extern "system" fn status_result(this: Array, index: u32) -> HRESULT { .map_or(E_INVALIDARG, |e| e.load(Ordering::Acquire)) } -/// Grand Theft Auto VI polls this (entry 0, a `Sleep(1)` loop) and never +/// The title polls this (entry 0, a `Sleep(1)` loop) and never /// reads the result itself. extern "system" fn is_complete(this: Array, index: u32) -> bool { status_result(this, index) != E_PENDING @@ -667,7 +667,7 @@ struct Request { source_size: u32, /// Compressed size between two decompression stages; unused here. intermediate_size: u32, - /// Matched by cancellation; Grand Theft Auto VI leaves it 0. + /// Matched by cancellation; the title leaves it 0. tag: u64, name: *const c_char, } @@ -680,7 +680,7 @@ const BCPACK: u64 = 0xf << 1; const PAGE_DESTINATION: u64 = 1 << 21; const MEMORY_SOURCE: u64 = 1 << 22; // Bits 5-20 select a further transform, bit 23 a source in physical pages; -// Grand Theft Auto VI's packages need neither, so requests with them fail. +// The title's packages need neither, so requests with them fail. const PAGE: usize = 64 * 1024; @@ -778,7 +778,7 @@ extern "system" fn submit(this: QueueRef) { /// Ends the queue whatever its reference count: what was not started never /// completes, and this returns once the reads already running have -/// finished. Grand Theft Auto VI calls this, not `Release`. +/// finished. The title calls this, not `Release`. extern "system" fn close(this: QueueRef) { // SAFETY: as above. close_lane(unsafe { &*this }.state.id); @@ -976,7 +976,7 @@ fn into_destination( if super::xmem::write_physical(pages, offset, &data[..n]) { Ok(()) } else { - // Said aloud: Grand Theft Auto VI never reads a request's result + // Said aloud: the title never reads a request's result // (it only polls for completion), so a destination left unwritten // is a model or texture that silently holds whatever its pages // held before. @@ -990,8 +990,8 @@ fn into_destination( } } -/// Slots by the 2020 order, which the argument shapes at Grand Theft Auto -/// VI's call sites match (0x18, 0x20, 0x30 and 0x40 are called). +/// Slots by the 2020 order, which the argument shapes at +/// the title's call sites match (0x18, 0x20, 0x30 and 0x40 are called). static QUEUE_VTABLE: Methods<12> = Methods([ missing::<0> as *const (), add_ref_instance:: as *const (), diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index e25513d..902c4a9 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -516,7 +516,7 @@ pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> Fi // Kernel reads into title memory. The GPU side leaves blocks of title GPU // buffers read-only to see the title's next write, and the kernel's writes -// fail there instead of faulting into its handler; Grand Theft Auto VI's +// fail there instead of faulting into its handler; the title's // synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned // destinations and retry a failed `ReadFile` forever. So the destination // is opened first. diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index a45081e..6cb89fa 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -637,7 +637,7 @@ fn relative( // SAFETY: a reading we handed out and the title still holds. let reference = unsafe { &*reference }; // shortcut: with no device given only the reference's device is walked, - // not every device's readings in time order; Grand Theft Auto VI walks + // not every device's readings in time order; the title walks // only keyboard readings (one device) and the current pad's previous one. let Some(index) = hub.index(reference.device) else { return fail(out, E_INVALIDARG); @@ -712,7 +712,7 @@ fn token(out: *mut u64) -> HRESULT { S_OK } -// shortcut: reading callbacks never run; Grand Theft Auto VI registers none +// shortcut: reading callbacks never run; the title registers none // (it polls). extern "system" fn register_reading( _: This, @@ -911,7 +911,7 @@ extern "system" fn device_status(this: *const Device) -> u32 { // shortcut: trigger motors are dropped (XInput has none). The host API that // drives them without a redistributable is Windows.Gaming.Input (WinRT // `Gamepad.Vibration`), which needs WinRT bindings this crate lacks outside -// diagnostics builds; Grand Theft Auto VI sends trigger levels in slot 0x50. +// diagnostics builds; the title sends trigger levels in slot 0x50. extern "system" fn set_rumble(this: *const Device, params: *const [f32; 4]) { // SAFETY: one of our devices. let device = unsafe { &*this }; @@ -1149,7 +1149,7 @@ mod host { // The scripted keys (`VICTORY_KEYS`) also press the first // pad's buttons, by the stand-in pad's table: with a real pad // connected the stand-in is not there, and a title that listens - // to the pad (Grand Theft Auto VI's start screen) saw nothing. + // to the pad (the title's start screen) saw nothing. #[cfg(feature = "diagnostics")] if slot == 0 { for vk in scripted() { @@ -1181,8 +1181,8 @@ mod host { // SAFETY: plain query. scan_code: unsafe { MapVirtualKeyW(u32::from(vk), MAPVK_VK_TO_VSC_EX) }, virtual_key: vk, - // shortcut: no characters (code point 0); Grand Theft - // Auto VI reads scan codes and virtual keys only. + // shortcut: no characters (code point 0); + // the title reads scan codes and virtual keys only. ..Default::default() }) .collect() diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs index 4eb9649..f1b5777 100644 --- a/crates/victory-hle/src/modules/lifecycle.rs +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -110,8 +110,8 @@ pub extern "system" fn CreateWindowExA( hwnd } -/// A console title sizes its window to its render target (Grand Theft -/// Auto VI: 3840x2160 on a Series X), which can exceed the host's screen. +/// A console title sizes its window to its render target ( +/// the title: 3840x2160 on a Series X), which can exceed the host's screen. /// A top-level window larger than the work area is shrunk to fit, keeping /// its proportions, and centred; what it shows is scaled to it (the swap /// chain stretches). @@ -177,8 +177,8 @@ extern "system" fn window_proc( // Alt or F10 puts a window into menu mode: the system runs a modal menu // loop on the thread that owns the window, which is the title's. The // title then stops (no frames, no input) until a key ends the loop, and - // nothing shows it, since the window has no menu bar; Grand Theft Auto - // VI aborts itself about half a minute later. A console has no window + // nothing shows it, since the window has no menu bar; + // the title aborts itself about half a minute later. A console has no window // menu. The mouse still opens it from the title bar. if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_KEYMENU as usize { return 0; diff --git a/crates/victory-hle/src/modules/storage.rs b/crates/victory-hle/src/modules/storage.rs index 585b641..600cbad 100644 --- a/crates/victory-hle/src/modules/storage.rs +++ b/crates/victory-hle/src/modules/storage.rs @@ -26,7 +26,7 @@ pub const IID: Guid = Guid::new( [0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d], ); -/// As Grand Theft Auto VI (2026) asks for it; it calls 0x20 (path) and 0x28 +/// As the title (2026) asks for it; it calls 0x20 (path) and 0x28 /// (space) with the same arguments. pub const IID_2026: Guid = Guid::new( 0x41a4_e10c, diff --git a/crates/victory-hle/src/modules/xg.rs b/crates/victory-hle/src/modules/xg.rs index 46912d7..56011ec 100644 --- a/crates/victory-hle/src/modules/xg.rs +++ b/crates/victory-hle/src/modules/xg.rs @@ -3,7 +3,7 @@ //! slice lies, and to copy linear data into tiled memory and back. Served //! from `victory_formats::texture`. //! -//! Grand Theft Auto VI imports `XGCreateTextureComputer` and +//! The title imports `XGCreateTextureComputer` and //! `XGSuggestSwizzleMode` and calls these computer methods: Release (0x08), //! the layout (0x10), copies into (0x40) and out of (0x48) a subresource, //! and the 64 KiB tiling (0x50). The other slots log and fail. @@ -165,7 +165,7 @@ fn texture(desc: &ResourceDesc) -> Option { const MIPS: usize = 15; /// One mip in the layout the title reads (offsets 0x00, 0x08, 0x10 and -/// 0x1c are read by Grand Theft Auto VI; the rest follow the library's +/// 0x1c are read by the title; the rest follow the library's /// older public shape). #[repr(C)] #[derive(Debug, Default, Clone, Copy)] @@ -539,7 +539,7 @@ extern "system" fn tiling( } /// Slot 0x30 `(plane, mip, x, y, z or slice, sample, bit position)`: an -/// element's byte offset from the texture's start. Grand Theft Auto VI reads +/// element's byte offset from the texture's start. The title reads /// texels of a 128x4 `4KB_S` texture on the CPU through it (title+0x5151c90); /// an error returned as an offset made it read wild memory. 0 if outside. extern "system" fn element_offset( diff --git a/crates/victory-hle/src/modules/xgame.rs b/crates/victory-hle/src/modules/xgame.rs index c54f837..edcf2ea 100644 --- a/crates/victory-hle/src/modules/xgame.rs +++ b/crates/victory-hle/src/modules/xgame.rs @@ -63,8 +63,8 @@ extern "system" fn title_id(_: This, out: *mut u32) -> HRESULT { } /// As documented: the title ends (suspended first, as on any end) and the -/// game starts again in a new process; this never returns. Grand Theft -/// Auto VI relaunches itself (its own path from `GetModuleFileNameA`) with +/// game starts again in a new process; this never returns. +/// The title relaunches itself (its own path from `GetModuleFileNameA`) with /// arguments from its configuration. The new `victory run` gets the same /// options, the new executable, and the title's arguments after `--` /// (the title reads the whole command line). diff --git a/crates/victory-hle/src/modules/xgameruntime.rs b/crates/victory-hle/src/modules/xgameruntime.rs index 3201a90..b3f5963 100644 --- a/crates/victory-hle/src/modules/xgameruntime.rs +++ b/crates/victory-hle/src/modules/xgameruntime.rs @@ -202,7 +202,7 @@ pub extern "system" fn InitializeApiImplEx(version: u64, build: u64, flags: u64) /// The stub prefers this one when present. It passes the same three values /// and a pointer to the title's initialisation options, null unless the -/// title initialises with options (Grand Theft Auto VI does not). +/// title initialises with options (the title does not). pub extern "system" fn InitializeApiImplEx2( version: u64, build: u64, diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs index d77ac8a..560b6a6 100644 --- a/crates/victory-hle/src/modules/xgamesave.rs +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -37,7 +37,7 @@ pub const PROVIDER: Guid = Guid::new( 0x4cc2, [0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2], ); -/// As Grand Theft Auto VI (2026) asks for it; every slot it calls takes +/// As the title (2026) asks for it; every slot it calls takes /// the public API's arguments in the same order as under the provider's /// own id (older titles). pub const IID_2026: Guid = Guid::new( diff --git a/crates/victory-hle/src/modules/xgameui.rs b/crates/victory-hle/src/modules/xgameui.rs index ab2d9e0..9882b2e 100644 --- a/crates/victory-hle/src/modules/xgameui.rs +++ b/crates/victory-hle/src/modules/xgameui.rs @@ -18,7 +18,7 @@ pub const PROVIDER: Guid = Guid::new( 0x4043, [0xba, 0x07, 0x35, 0xd6, 0x07, 0xdf, 0x98, 0xb0], ); -/// As Grand Theft Auto VI (2026) asks for it; the slots it calls (0x38, +/// As the title (2026) asks for it; the slots it calls (0x38, /// 0x40, 0x88-0x98) take the public API's arguments in the 2020 order. pub const IID_2026: Guid = Guid::new( 0xeaf6_69df, @@ -49,7 +49,7 @@ extern "system" fn profile_card_result(_: This, block: *mut AsyncBlock) -> HRESU xasync::XAsyncGetResult(block, (&raw const PROFILE).cast(), 0, none, none.cast()) } -/// Grand Theft Auto VI treats `E_ABORT` as cancelled and goes on; any +/// The title treats `E_ABORT` as cancelled and goes on; any /// other failure as an error. extern "system" fn text_entry_async( _: This, diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index a9ea084..82e14ef 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -72,8 +72,8 @@ const MEM_WRITE_WATCH: u32 = 0x20_0000; /// 32-bit memory; else from 4 GiB (kept for 32-bit requests, which the /// title's big pools would otherwise crowd out) up to 46 down to 40 bits /// from the field at bit 12, or 40 bits without one: the console keeps -/// title memory there, and its ray-tracing structures must be (Grand Theft -/// Auto VI's BVH builder refuses one above; the title asks for its GPU heap +/// title memory there, and its ray-tracing structures must be ( +/// the title's BVH builder refuses one above; the title asks for its GPU heap /// with no field). Decision 0001. fn address_range(flags: u64) -> (usize, usize) { let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) { @@ -108,7 +108,7 @@ pub extern "system" fn XMemVirtualAlloc( // A reservation of 64 KiB pages takes physical pages later // (`XMemMapPhysicalPages`); on the host only a placeholder can. // shortcut: committing part of such a reservation later would fail - // (Grand Theft Auto VI's 23 calls never do); replace that part of the + // (the title's 23 calls never do); replace that part of the // placeholder then. let placeholder = kind & PAGES_64K == PAGES_64K && kind & MEM_COMMIT == 0; if placeholder { @@ -176,7 +176,7 @@ pub struct BasicInformation { } // shortcut: every committed page reports graphics memory and no tag, since -// all of it is GPU-reachable here (Grand Theft Auto VI's BVH builder, the +// all of it is GPU-reachable here (the title's BVH builder, the // only caller, wants graphics memory); remember the flags of // `XMemVirtualAlloc` regions if a title tells CPU-only memory apart. pub extern "system" fn XMemVirtualQuery( @@ -221,7 +221,7 @@ type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void; type FreeRoutine = extern "system" fn(*mut c_void, u64); /// The allocation and free routines the title's exe exports as -/// `__XMemAllocationHooks__` (Grand Theft Auto VI does): `XMemAlloc` and +/// `__XMemAllocationHooks__` (the title does): `XMemAlloc` and /// `XMemFree` call them, for the title's own calls and its middleware's; /// the `…Default` exports do not. fn hooks() -> [usize; 2] { @@ -291,7 +291,7 @@ pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_ }; // shortcut: the host heap's addresses lie above 2^40, unlike the // console's; nothing seen builds ray-tracing structures in this memory - // (Grand Theft Auto VI uses its GPU heap). Sub-allocate from a + // (the title uses its GPU heap). Sub-allocate from a // reservation below 2^40 if one does. // SAFETY: the layout has a non-zero size. let block = unsafe { alloc(layout) }; @@ -399,7 +399,7 @@ pub extern "system" fn XMemAllocatePhysicalPages( return 0; }; // A pagefile-backed section of `size` bytes, its pages committed when - // first mapped or written (`commit`): Grand Theft Auto VI asks for 6.1 + // first mapped or written (`commit`): the title asks for 6.1 // GiB at once, which a busy host often cannot commit (error 1450). // SAFETY: plain section creation. let handle = unsafe { @@ -449,7 +449,7 @@ pub extern "system" fn XMemAllocatePhysicalPages( } /// Page numbers count 4 KiB frames, so a 64 KiB page's is a multiple of -/// 16: Grand Theft Auto VI keeps them as 21-bit `number >> 4` and rebuilds +/// 16: the title keeps them as 21-bit `number >> 4` and rebuilds /// them with `<< 4` (128 GiB of pages at most). const FRAMES: usize = PAGE >> 12; @@ -635,7 +635,7 @@ pub extern "system" fn XMemMapPhysicalPages( } /// One page at each address; null `pages`, or a page number 0, unmaps -/// (Grand Theft Auto VI passes 0 for addresses to clear). +/// (the title passes 0 for addresses to clear). pub extern "system" fn XMemMapPhysicalPagesScatter( addresses: *const *mut c_void, n: usize, @@ -665,8 +665,8 @@ pub extern "system" fn XMemMapPhysicalPagesScatter( /// Maps the physical pages shown at `[from, from + len)` at `to` as well, /// in place of what `to` shows; `from` 0 unmaps. The GPU's page-mapping -/// copies (`victory_gpu`, queue `CopyPageMappingsBatchX`): Grand Theft Auto -/// VI maps pages into a pool view, then has the GPU map them into its tiled +/// copies (`victory_gpu`, queue `CopyPageMappingsBatchX`): +/// the title maps pages into a pool view, then has the GPU map them into its tiled /// heap. Page by page; false if a source page is not mapped physical memory. pub fn map_alias(to: u64, from: u64, len: u64) -> bool { let (to, from, len) = (to as usize, from as usize, len as usize); diff --git a/crates/victory-hle/src/modules/xnetworking.rs b/crates/victory-hle/src/modules/xnetworking.rs index 8670ff2..c0b21a3 100644 --- a/crates/victory-hle/src/modules/xnetworking.rs +++ b/crates/victory-hle/src/modules/xnetworking.rs @@ -18,7 +18,7 @@ pub const PROVIDER: Guid = Guid::new( [0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a], ); -/// As Grand Theft Auto VI (2026) asks for it; the slots it calls (0x18-0x88) +/// As the title (2026) asks for it; the slots it calls (0x18-0x88) /// take the same arguments as under the provider's own id (older titles). pub const IID_2026: Guid = Guid::new( 0xbf23_46b2, diff --git a/crates/victory-hle/src/modules/xpackage.rs b/crates/victory-hle/src/modules/xpackage.rs index 4f03635..315faac 100644 --- a/crates/victory-hle/src/modules/xpackage.rs +++ b/crates/victory-hle/src/modules/xpackage.rs @@ -20,7 +20,7 @@ pub const PROVIDER: Guid = Guid::new( [0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e], ); -/// As Grand Theft Auto VI (2026) asks for it. Its slots up to 0xd0 take the +/// As the title (2026) asks for it. Its slots up to 0xd0 take the /// arguments the public API lists in the same order; 0x110 uninstalls a /// package, 0x128/0x130 mount one with UI, 0x138 enumerates packages. pub const IID_2026: Guid = Guid::new( @@ -139,7 +139,7 @@ extern "system" fn register_progress( /// 0: ready. // shortcut: every selector counts as installed, including ones the // package's layout does not have (the console answers those with an -// invalid-selector error); Grand Theft Auto VI asks only about its own +// invalid-selector error); the title asks only about its own // chunks, which a full install has. extern "system" fn find_availability( _: This, @@ -210,7 +210,7 @@ extern "system" fn estimate_download( } // shortcut: accepted but nothing is removed (the package folder is the -// user's), so the chunks stay ready; Grand Theft Auto VI's one call site +// user's), so the chunks stay ready; the title's one call site // (title+0x293b4b0, its chunk manager) would then see them still installed. extern "system" fn uninstall_chunks( _: This, @@ -256,7 +256,7 @@ extern "system" fn mount_result( /// Titles enumerate content packages (kind 1); there are none. // shortcut: the game kind (0) also lists nothing, not this installation; -// Grand Theft Auto VI enumerates only content (kind 1, title+0x2937bf0). +// The title enumerates only content (kind 1, title+0x2937bf0). extern "system" fn enumerate( _: This, kind: u32, diff --git a/crates/victory-hle/src/modules/xstore.rs b/crates/victory-hle/src/modules/xstore.rs index 3e29422..9e2b74b 100644 --- a/crates/victory-hle/src/modules/xstore.rs +++ b/crates/victory-hle/src/modules/xstore.rs @@ -20,7 +20,7 @@ pub const PROVIDER: Guid = Guid::new( 0x448c, [0xb9, 0x2b, 0x39, 0x60, 0xfb, 0x5b, 0xd3, 0x0c], ); -/// As Grand Theft Auto VI (2026) asks for it; every slot it calls takes +/// As the title (2026) asks for it; every slot it calls takes /// the public API's arguments in the 2020 order. pub const IID_2026: Guid = Guid::new( 0xb09d_803c, diff --git a/crates/victory-hle/src/modules/xsystem.rs b/crates/victory-hle/src/modules/xsystem.rs index a3a1d62..bf091eb 100644 --- a/crates/victory-hle/src/modules/xsystem.rs +++ b/crates/victory-hle/src/modules/xsystem.rs @@ -41,7 +41,7 @@ const DEVICE_ID: &str = "VkljdG9yeSBvZmZsaW5lIGRldmljZSBpZGVudGl0eSE="; pub static OBJECT: Object = Object::new("system", &VTABLE); pub static ANALYTICS_OBJECT: Object = Object::new("analytics", &ANALYTICS_VTABLE); -/// The interface as Grand Theft Auto VI (2026) asks for it; it calls the +/// The interface as the title (2026) asks for it; it calls the /// same three slots (0x18, 0x20, 0x28) with the same arguments. pub const IID_2026: Guid = Guid::new( 0x1861_cf2e, diff --git a/crates/victory-hle/src/modules/xuser.rs b/crates/victory-hle/src/modules/xuser.rs index 8b48dfc..6019381 100644 --- a/crates/victory-hle/src/modules/xuser.rs +++ b/crates/victory-hle/src/modules/xuser.rs @@ -81,7 +81,7 @@ pub static DEVICE_OBJECT: Object = Object::new("user devices", &DEVICE_VTABLE); pub const INTERFACES: &[Interface] = &[ (PROVIDER, IID, &OBJECT), - // Grand Theft Auto VI (2026) asks with the provider's id; its thunks call + // The title (2026) asks with the provider's id; its thunks call // the same slots with the same arguments (0x108/0x110 change events). (PROVIDER, PROVIDER, &OBJECT), (PROVIDER, GAMERTAG_IID, &GAMERTAG_OBJECT), diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index c8479c5..cc13821 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -176,7 +176,7 @@ pub fn title() -> Title { } /// Gives the process the console's millisecond timers. Titles pace -/// themselves with short waits (Grand Theft Auto VI's audio mixer sleeps +/// themselves with short waits (the title's audio mixer sleeps /// about 4 ms per 5.3 ms block) and cannot tune the timer on the console; /// a desktop process waits in 15.6 ms ticks unless it asks for finer ones, /// and Windows 11 drops that request while the window is hidden unless the diff --git a/crates/victory-loader/src/console_insn.rs b/crates/victory-loader/src/console_insn.rs index 3791b18..ca1eb8c 100644 --- a/crates/victory-loader/src/console_insn.rs +++ b/crates/victory-loader/src/console_insn.rs @@ -1,5 +1,5 @@ //! Instructions the console's CPU (Zen 2) has and an Intel PC's lacks, emulated: the title's -//! code raises STATUS_ILLEGAL_INSTRUCTION on them (GTA VI zeroes memory with a `clzero` loop at +//! code raises STATUS_ILLEGAL_INSTRUCTION on them (the title zeroes memory with a `clzero` loop at //! its first frames), and the vectored handler steps over them here. //! //! Ported from XCL (github.com/ivall/xcl, GPL-2.0-only): `insn.rs` (decoder, as diff --git a/crates/victory-loader/src/tls.rs b/crates/victory-loader/src/tls.rs index a234183..3f65dd2 100644 --- a/crates/victory-loader/src/tls.rs +++ b/crates/victory-loader/src/tls.rs @@ -82,7 +82,7 @@ fn patch(code: &mut [u8], at: usize, thunks: usize) -> usize { let c = &code[i..i + LOAD_LEN]; let rex = c[1]; let reg = usize::from((c[3] >> 3) & 7) | if rex & 4 != 0 { 8 } else { 0 }; - // shortcut: a byte match, not a decode. In Grand Theft Auto VI all + // shortcut: a byte match, not a decode. In the title all // 53,246 hits are instruction starts and none is missed (checked // against a full disassembly); decode .text if a title shows one. if c[0] == 0x65 diff --git a/crates/victory-shader/src/bvh.rs b/crates/victory-shader/src/bvh.rs index 43fb195..9f54001 100644 --- a/crates/victory-shader/src/bvh.rs +++ b/crates/victory-shader/src/bvh.rs @@ -61,7 +61,7 @@ //! public software emulation of this instruction in the open-source Vulkan //! driver for this GPU family (box test and sorting network as there; the //! triangle test is the watertight one it uses, Woop, Benthin and Wald, -//! JCGT 2013), and agree with what Grand Theft Auto VI's own structure +//! JCGT 2013), and agree with what the title's own structure //! builder writes and its trace programs read. Not known from either: how //! the console rounds, which of two boxes entered at the same distance it //! returns first, and what it returns for a ray exactly through an edge diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index fdc02aa..4727b92 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -141,7 +141,7 @@ const CASES: &[(&str, &str)] = &[ }"#, ), // 16-bit outputs and inputs (one value per dword with the 2020 - // compiler; Grand Theft Auto VI's two per dword cannot be compiled + // compiler; the title's two per dword cannot be compiled // here) and the front face. ( "16-bit varyings and front face", @@ -354,7 +354,7 @@ const CS_CASES: &[(&str, &str)] = &[ uint4(w * 7 + h, l + asuint(r), n * 5 + ns * 3 + st, b + raw.Load(4 * (i & 31)))); }"#, ), - // Typed loads (`tbuffer_load_format_*`, Grand Theft Auto VI's vertex + // Typed loads (`tbuffer_load_format_*`, the title's vertex // fetch) convert by the format the instruction names: the PC reads the // same bytes through typed views in those formats. Channels past the // format's read (0, 0, 0, 1); a byte format at unaligned offsets. @@ -587,7 +587,7 @@ const MS_CASES: &[(&str, u32, &str)] = &[ } }"#, ), - // Two waves per group, as Grand Theft Auto VI's mesh programs run: the + // Two waves per group, as the title's mesh programs run: the // second wave's lanes are threads 64-127. ( "two waves", @@ -605,7 +605,7 @@ const MS_CASES: &[(&str, u32, &str)] = &[ tris[i] = i & 1 ? uint3(c + 1, c + 10, c + 9) : uint3(c, c + 1, c + 9); }"#, ), - // Quad reads (DPP quad permutations on the console; Grand Theft Auto VI's + // Quad reads (DPP quad permutations on the console; the title's // tessellating mesh programs swizzle within quads too). ( "quad reads", diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca006ed..600139a 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1063,8 +1063,8 @@ pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { /// second row. An element that shares a register behind another one (the /// signature packs a short element into the free columns of an earlier /// register) is NOT in that row's halves: it follows in the first -/// parameter, in row order, that has whole dwords left. Grand Theft Auto -/// VI's packed pedestrian shaders show both cases: TEXCOORD7 (register 1, +/// parameter, in row order, that has whole dwords left. +/// The title's packed pedestrian shaders show both cases: TEXCOORD7 (register 1, /// columns 2-3, behind the two columns of TEXCOORD0) is exported in dword 3 /// of parameter 0, after TEXCOORD1's two dwords; TEXCOORD6 (register 4, /// column 3, behind the three columns of TEXCOORD4) in dword 3 of @@ -4260,8 +4260,8 @@ impl<'a> Lower<'a> { if name == "ds_bpermute_b32" { // Backward permute: no LDS is touched. Each lane takes the data // register of the lane its address names, (address + offset) / 4 - // within the wave; a source lane outside EXEC gives 0. (Grand - // Theft Auto VI's checkerboard shadow-mask generators read their + // within the wave; a source lane outside EXEC gives 0. ( + // the title's checkerboard shadow-mask generators read their // neighbours' samples with it; without them every shadowed light // was multiplied by an empty mask.) // shortcut: a source lane that is not at this instruction on the @@ -5346,8 +5346,8 @@ impl<'a> Lower<'a> { // heap holds a buffer view there, not a constant buffer: read as // raw bytes, as a table's SRV is below. Read as a constant buffer // (the host's validation: "Descriptor Type in Heap: SRV, Register - // Type: CBV", heap index 17) the loads gave nothing: Grand Theft - // Auto VI's meshlet culling (BatchCullMeshlets, + // Type: CBV", heap index 17) the loads gave nothing: + // the title's meshlet culling (BatchCullMeshlets, // BatchCullPreSkinnedMeshlets, BatchCullBatchCSMeshlets) reads its // batch records, mesh headers and instance transforms this way, so // it passed no meshlet and every indirect mesh draw ran empty. @@ -9438,8 +9438,8 @@ impl<'a> Lower<'a> { // are read at the level instead, in the gather's // order: (u0,v1) (u1,v1) (u1,v0) (u0,v0). // With an offset too (`image_gather4_l_o`): the - // offset is in texels of that level. Grand Theft - // Auto VI's meshlet culling takes a 4x4 block of + // offset is in texels of that level. + // The title's meshlet culling takes a 4x4 block of // the pyramid as one gather and three offset ones // ((2,0), (0,2), (2,2)); the three read level 0, // two texels beside the first one's place, so a @@ -10802,7 +10802,7 @@ mod tests { assert_eq!(p.get(&5), None); } - /// The packed pedestrian layouts of Grand Theft Auto VI: an element + /// The packed pedestrian layouts of the title: an element /// behind another one in its register follows in the first parameter /// with a dword left, and is not a half of its register's row. #[test] diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 3a7646c..b667241 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -29,7 +29,7 @@ //! `b` / `t` in [`ROOT_CBV_SPACE`], `i` the title's root parameter //! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the //! address the title sets is the buffer's. -//! * **Vertex fetch** (added 2026-11-23). Grand Theft Auto VI's mesh and +//! * **Vertex fetch** (added 2026-11-23). The title's mesh and //! vertex programs fetch vertices themselves with typed-format loads //! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm, //! 2_10_10_10 unorm, 8_8_8_8 and 16_16_16_16 uint...) is in the @@ -612,7 +612,7 @@ fn emit_program( // primitives) (the code divides by that); the thread count is in PSV0 // from runtime info version 2 on. // shortcut: older containers fall back to the group's lane count, right - // when the HLSL group fills its waves (Grand Theft Auto VI's do). + // when the HLSL group fills its waves (the title's do). let mesh_stride = match &native.io { crate::native::StageIo::Ms(ms) => { let psv = c.part(FourCC::PSV0).map(|p| p.data); diff --git a/crates/victory-shader/src/emit/rect.rs b/crates/victory-shader/src/emit/rect.rs index c05f28b..9ec80fd 100644 --- a/crates/victory-shader/src/emit/rect.rs +++ b/crates/victory-shader/src/emit/rect.rs @@ -8,8 +8,8 @@ //! arguments stay the title's, and each rectangle arrives here as one //! triangle. //! -//! Which vertex is the corner between the other two varies: Grand Theft -//! Auto VI's full-screen rectangles come as top left, bottom left, bottom +//! Which vertex is the corner between the other two varies: +//! the title's full-screen rectangles come as top left, bottom left, bottom //! right (the second), its tiled lighting as top left, bottom left, top //! right (the first). The corner is the vertex that shares x with one of //! the others and y with the other; the fourth vertex lies opposite it, diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 813a9b5..2b6edd4 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -164,8 +164,8 @@ pub enum BvhNodes { /// A buffer of the host: the descriptor is loaded from a table (it is /// among [`Resources::descriptors`]), and node pointers count from the /// buffer's start. Its flags are not known to the shader: boxes are - /// sorted and triangles return barycentrics, as every descriptor Grand - /// Theft Auto VI builds asks. + /// sorted and triangles return barycentrics, as every descriptor + /// the title builds asks. Resource, /// Title memory by address: the code makes the descriptor from numbers /// (the title: the whole address space, or one structure's address in @@ -718,7 +718,7 @@ impl<'a> Tracer<'a> { /// For a join `v` whose every incoming value adds to an `s_getpc_b64` low /// dword: the first of those (one level of joins only). The paths may add /// to different ones: two tables in the code, one picked by control flow - /// (Grand Theft Auto VI's fog reconstruction reads its sample offsets from + /// (the title's fog reconstruction reads its sample offsets from /// one of two tables, by the sample's number; refused, the lit frame was /// multiplied by a fog transmittance nothing had written). fn code_join(&self, v: Value) -> Option { @@ -1209,7 +1209,7 @@ impl<'a> Tracer<'a> { /// other: the console compiler loads a descriptor (or clears an /// address's high half) inside a branch that skips code when no lane /// is left for it, and uses it after the join, where only lanes that - /// ran the branch are left (Grand Theft Auto VI's + /// ran the branch are left (the title's /// `CS_Alpha_Schedule`: the registers' values from before the branch, /// which the join also sees, are what a wave with no such lane holds). /// None at loop headers and without the lanes' paths. @@ -3062,7 +3062,7 @@ pub(crate) mod tests { 0xBF81_0000, // s_endpgm ]; - /// The console compiler's waterfall (Grand Theft Auto VI's ray-tracing + /// The console compiler's waterfall (the title's ray-tracing /// resolve and others): each lane holds its entry's byte offset in the /// table at s0 (v7 = (lane & 1) * 32); the loop reads the first active /// lane's offset, narrows EXEC to the lanes with the same one diff --git a/crates/victory-shader/src/spill.rs b/crates/victory-shader/src/spill.rs index 9af1c4f..a0feb6a 100644 --- a/crates/victory-shader/src/spill.rs +++ b/crates/victory-shader/src/spill.rs @@ -55,7 +55,7 @@ fn spilled(native: &NativeProgram) -> Option> { } /// Whether `native` reads its root parameters from a spilled user-data -/// table. (In Grand Theft Auto VI exactly the compute programs of the +/// table. (In the title exactly the compute programs of the /// console's ray-tracing structure builder do.) pub fn is_spilled(native: &NativeProgram) -> bool { spilled(native).is_some() diff --git a/docs/architecture.md b/docs/architecture.md index 4952df3..5e3e6b6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -37,7 +37,7 @@ Converting them ahead of time from files is only a warm-up. | `victory-shader` | Xbox shader containers → host shaders | | `victory-formats` | the GPU's texture layouts (sizes, tiling, detiling), audio codecs; planned: BCPack | | `victory-pipeline` | converter trait, content-addressed cache | -| `victory-game` | Grand Theft Auto VI-specific formats, build identities, hooks | +| `victory-game` | the title-specific formats, build identities, hooks | | `apps/victory` | command-line front end | | `xtask` | asset-policy check, git hooks | | `tests/fixtures/hle-probe` | a stand-in "title" (our own code) for loader tests | diff --git a/docs/fork-ray-tracing.md b/docs/fork-ray-tracing.md index 0dbfc42..dee0281 100644 --- a/docs/fork-ray-tracing.md +++ b/docs/fork-ray-tracing.md @@ -6,7 +6,7 @@ game. Everything here is off by default. ## What the title does -Grand Theft Auto VI's indirect light (probes, bounce, reflections) and the +The title's indirect light (probes, bounce, reflections) and the shadows of its lamps and sun are ray traced. Without them, anything the sun does not hit directly is black: interiors, the shadowed side of a face, rooms lit only by lamps. diff --git a/victory.example.toml b/victory.example.toml index 0b37ff2..6aa1afe 100644 --- a/victory.example.toml +++ b/victory.example.toml @@ -4,7 +4,7 @@ # VICTORY_CONFIG selects a different config file. [paths] -# Your own dump of Grand Theft Auto VI. env: VICTORY_GAME_DIR +# Your own dump of the title. env: VICTORY_GAME_DIR game_dir = 'D:\victory-data\game' # Derived data. Default: %LOCALAPPDATA%\victory\cache. env: VICTORY_CACHE_DIR From 5a32c08c29fed4174aa9137b3bc3930a7bfef18f Mon Sep 17 00:00:00 2001 From: spacede Date: Tue, 24 Nov 2026 21:45:29 +0100 Subject: [PATCH 128/445] GPU: document adaptive copy refresh --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c00d992..e76df04 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ Speed and memory: - Waits for memory values, write-watch queries and page queries no longer walk page tables per call. - Large title buffers get a copy in card memory, with shader writes found by hashing on the card. - Submissions can be sent ahead of the wait for the card (`VICTORY_LATE_WAIT`), with a relay thread that lands results as the card finishes (`VICTORY_RELAY`): in a first five-minute run the card's idle time behind the submitting thread fell from about 136 to 30 ms per frame. +- Independent host-copy refreshes run in parallel by default on systems with at least four logical CPUs (`VICTORY_WIDE_REFRESH=0` disables this; `=1` forces it). This targets the serial memory reads that previously cost about 45–50 ms per frame on the test run. - Title memory can be opened as a graphics heap so that buffers are used in place instead of copied (`VICTORY_INPLACE`, first stage only; a probe confirmed the approach on the test GPU). - The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory. - An intermittent device loss was traced to the pipeline library file being replaced while mapped; fixed. @@ -63,7 +64,9 @@ Speed and memory: Most of the newer speed changes sit behind environment switches that are off by default (`VICTORY_LATE_WAIT`, `VICTORY_RELAY`, `VICTORY_WIDE_BACK`, `VICTORY_CARD_BUFFERS_MIN_MB`, `VICTORY_INPLACE`, `VICTORY_BVH_BUILDER`, ...). -Each is described in a comment where it is read. +Independent host-copy refreshes are the exception: they use parallel workers +automatically on systems with at least four logical CPUs. Each switch is +described in a comment where it is read. ### Known problems @@ -215,3 +218,4 @@ title's data folder. ## License GPL-3.0-or-later. See [LICENSE](LICENSE). + From 05ee4387065d782c4cec6c8ff22d484da5e09894 Mon Sep 17 00:00:00 2001 From: spacede Date: Tue, 24 Nov 2026 21:45:38 +0100 Subject: [PATCH 129/445] GPU: parallelize copy refreshes on multicore hosts --- crates/victory-gpu/src/host.rs | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 9ecf3be..8997116 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -5156,7 +5156,7 @@ impl HostList { } /// Whether a submission's refreshes of host copies run on several threads, -/// a copy to a thread (`VICTORY_WIDE_REFRESH=1`; off by default). +/// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it). /// /// A submission brings some sixty copies up to date, one after the other /// on the submitting thread: for each, the pages the title wrote are asked @@ -5169,7 +5169,36 @@ impl HostList { /// they are for the title's threads. fn wide_refresh() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_REFRESH").is_some_and(|v| v == "1")) + *ON.get_or_init(|| { + wide_refresh_enabled( + std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(), + std::thread::available_parallelism().ok().map(|n| n.get()), + ) + }) +} + +fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option) -> bool { + match setting { + Some("1") => true, + Some("0") => false, + _ => logical_cpus.is_some_and(|n| n >= 4), + } +} + +#[cfg(test)] +mod wide_refresh_tests { + use super::wide_refresh_enabled; + + #[test] + fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() { + assert!(wide_refresh_enabled(None, Some(4))); + assert!(wide_refresh_enabled(None, Some(16))); + assert!(!wide_refresh_enabled(None, Some(2))); + assert!(!wide_refresh_enabled(None, None)); + assert!(wide_refresh_enabled(Some("1"), Some(1))); + assert!(!wide_refresh_enabled(Some("0"), Some(16))); + assert!(wide_refresh_enabled(Some("auto"), Some(4))); + } } /// A submission's refreshes not done yet, merged per buffer copy into the @@ -6480,3 +6509,4 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at ); } } + From 4d3aaab711db80eabbdbf69ba7f333ce47dae2ef Mon Sep 17 00:00:00 2001 From: jaschinski97-ops <232683647+jaschinski97-ops@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:45:05 +0100 Subject: [PATCH 130/445] Shaders: lower row permutations on wave32 hosts --- crates/victory-shader/src/emit/lower.rs | 76 ++++++ crates/victory-shader/src/emit/mod.rs | 2 + .../victory-shader/src/emit/permlane_tests.rs | 254 ++++++++++++++++++ 3 files changed, 332 insertions(+) create mode 100644 crates/victory-shader/src/emit/permlane_tests.rs diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca006ed..f1ccba9 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1262,6 +1262,7 @@ impl<'a> Lower<'a> { let n = i.name(); n.starts_with("ds_swizzle") || n.contains("permute") + || n.starts_with("v_permlane") || n.starts_with("v_mbcnt") || matches!(n, "v_readlane_b32" | "v_writelane_b32") || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some()) @@ -7188,6 +7189,81 @@ impl<'a> Lower<'a> { } Ok(()) } + "v_permlane16_b32" | "v_permlanex16_b32" => { + // RDNA2 ISA 12.12: each nibble of {src2, src1} selects a lane + // in this row of 16, or the other row of the same 32-lane half. + // OP_SEL[0:1] are fetch-inactive and bound-control, not half selects. + if v.abs != 0 || v.neg != 0 || v.opsel & !3 != 0 { + return Err("permlane input modifiers"); + } + self.cross_lane(false)?; + let fetch_inactive = v.opsel & 1 != 0; + if fetch_inactive + && !all_lane_blocks(self.x.st).is_some_and(|all| all[self.cur_ir]) + { + // DXIL cannot read the last VGPR value of a host invocation + // that has left through a lane branch. A guard keeps it here. + return Err("a permlane fetch from lanes outside the host branch"); + } + let (x, lo, hi) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let lane = self.lane_index(); + let (k7, k8, k15, k16, k31, k32, k4, one, zero) = ( + self.s.m.i32(7), + self.s.m.i32(8), + self.s.m.i32(15), + self.s.m.i32(16), + self.s.m.i32(31), + self.s.m.i32(32), + self.s.m.i32(4), + self.s.m.i32(1), + self.s.m.i32(0), + ); + let pos = self.s.m.bin(c, Bin::And, lane, k15); + let lower = self.s.m.cmp(c, pred::IULT, pos, k8); + let packed = self.s.m.select(c, lower, lo, hi); + let shift = self.s.m.bin(c, Bin::And, pos, k7); + let shift = self.s.m.bin(c, Bin::Mul, shift, k4); + let pick = self.s.m.bin(c, Bin::LShr, packed, shift); + let pick = self.s.m.bin(c, Bin::And, pick, k15); + let not15 = self.s.m.i32(!15); + let mut row = self.s.m.bin(c, Bin::And, lane, not15); + if name == "v_permlanex16_b32" { + row = self.s.m.bin(c, Bin::Xor, row, k16); + } + let src = self.s.m.bin(c, Bin::Or, row, pick); + let r = if fetch_inactive { + self.read_lane(x, src) + } else { + // Ballot the console EXEC guard as well as the host's active + // invocations. Never shuffle from an inactive host lane. + let enabled = guard.unwrap_or_else(|| self.s.m.bool(true)); + let i32t = self.s.t.i32; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let mask = self.s.op( + c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[enabled], + ); + let lo = self.s.m.extract(c, mask, 0); + let hi = self.s.m.extract(c, mask, 1); + let lower = self.s.m.cmp(c, pred::IULT, src, k32); + let word = self.s.m.select(c, lower, lo, hi); + let bit = self.s.m.bin(c, Bin::And, src, k31); + let bit = self.s.m.bin(c, Bin::LShr, word, bit); + let bit = self.s.m.bin(c, Bin::And, bit, one); + let active = self.s.m.cmp(c, pred::NE, bit, zero); + let safe = self.s.m.select(c, active, src, lane); + let read = self.read_lane(x, safe); + let fallback = if v.opsel & 2 != 0 { + zero + } else { + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a permlane result outside a VGPR"); + }; + self.i32_of(inst.read(Reg::V(reg)).ok_or("a permlane old value")?)? + }; + self.s.m.select(c, active, read, fallback) + }; + int(self, r) + } "v_readlane_b32" => { let (a, lane) = (s(self, 0)?, s(self, 1)?); // A computed lane in a pixel or vertex program is a host lane diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 3a7646c..10e4d80 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -90,6 +90,8 @@ mod intersect_tests; pub mod host; mod lower; mod own_bits; +#[cfg(all(test, windows))] +mod permlane_tests; mod rect; mod sampler; mod shader; diff --git a/crates/victory-shader/src/emit/permlane_tests.rs b/crates/victory-shader/src/emit/permlane_tests.rs new file mode 100644 index 0000000..3e6826c --- /dev/null +++ b/crates/victory-shader/src/emit/permlane_tests.rs @@ -0,0 +1,254 @@ +//! Synthetic row permutations on hosts supporting waves of at least 32 lanes. + +use super::host::{Dispatch, Host, Root, View}; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{ShaderError, io, ir, resource, structure}; + +const THREADS: u32 = 128; +const OLD: u32 = 42; +const BASE: u32 = 0x1234_0000; + +fn native(cross: bool, fi: bool, bc: bool, alias: bool, wave64: bool) -> NativeProgram { + let mov = |dst: u32, src: u32| 0x7E00_0200 | dst << 17 | src; + let smov = |dst: u32, src: u32| 0xBE80_0300 | dst << 16 | src; + let mut words = vec![ + smov(5, 128), + 0x3D << 26 | 0x02 << 18 | 8 << 6 | 2, + 125 << 25, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 (output byte offset) + 0x4A0A_00FF, + BASE, // v_add_nc_u32 v5, BASE, v0 + mov(6, if alias { 256 + 5 } else { 128 + OLD }), + ]; + words.push(if wave64 { 0xBEFE_0402 } else { smov(126, 2) }); // exec = s[2:3] / s2 + words.extend([ + 0xD400_0006 + | (if cross { 0x378 } else { 0x377 }) << 16 + | u32::from(fi) << 11 + | u32::from(bc) << 12, + (256 + if alias { 6 } else { 5 }) | (1 << 18), + ]); // v_permlane[x]16_b32 v6, v5/v6, s0, s1 + words.push(if wave64 { 0xBEFE_04C1 } else { smov(126, 193) }); // restore EXEC + words.extend([ + 0x38 << 26 | 0x1C << 18 | 1 << 12, + 0x80 << 24 | 2 << 16 | 6 << 8 | 7, // buffer_store_dword v6, v7, s[8:11], 0 offen + 0xBF81_0000, + ]); + NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: 8, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [THREADS, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } +} + +fn lowered(native: &NativeProgram, host_wave: u32) -> Result { + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resources"); + let io = io::raise(&p, native).expect("io"); + let was = lower::TEST_HOST_WAVE.replace(Some(host_wave)); + let result = lower::lower(&lower::Parts { + native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + lower::TEST_HOST_WAVE.set(was); + let result = result?; + let shader = HostShader { + stage: HwStage::Cs, + dxil: result.dxil, + user_data: result.user_data, + samplers: result.samplers, + static_samplers: Vec::new(), + root_cbvs: result.root_cbvs, + root_srvs: result.root_srvs, + root_uavs: result.root_uavs, + root_indexed_views: res.root_indexed_views, + }; + match validator::Validator::load(validator::Validator::default_path().as_deref()) { + Ok(mut v) => { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation"); + assert_eq!(copy[4..20], shader.dxil[4..20], "container hash"); + } + Err(e) => eprintln!("DXIL validator unavailable: {e}"), + } + Ok(shader) +} + +#[test] +fn permlane_fetch_inactive_outside_the_host_branch_is_rejected() { + let mut native = native(true, true, false, false, false); + let mut words: Vec = native + .code + .chunks_exact(4) + .map(|w| u32::from_le_bytes(w.try_into().unwrap())) + .collect(); + // Skip the permutation when EXEC is empty. Structurisation turns this + // into a host lane branch, so FI cannot read lanes that took the skip. + words.insert(8, 0xBF88_0002); // s_cbranch_execz +2 (to the EXEC restore) + native.code = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + assert!(matches!( + lowered(&native, 32), + Err(ShaderError::Unsupported { + what: "a permlane fetch from lanes outside the host branch", + .. + }) + )); +} + +#[test] +fn permlane_rows_and_inactive_sources() { + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let mut ran = 0; + for (backend, warp) in [("hardware", false), ("WARP", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {backend}; skipped"); + continue; + }; + let mut options = + windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + // SAFETY: options is the correctly sized output for this feature query. + unsafe { + host.device + .CheckFeatureSupport( + windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_D3D12_OPTIONS1, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .expect("wave capabilities"); + } + eprintln!( + "{backend} waves {}..{}", + options.WaveLaneCountMin, options.WaveLaneCountMax + ); + if options.WaveLaneCountMax < 32 { + eprintln!("{backend} cannot hold two 16-lane rows; GPU checks skipped"); + continue; + } + ran += 1; + eprintln!("permlane: testing row and EXEC cases on {backend}"); + for wave64 in [false, true] { + if options.WaveLaneCountMin > if wave64 { 64 } else { 32 } { + eprintln!("{backend} does not support the requested console wave size; skipped"); + continue; + } + for cross in [false, true] { + for fi in [false, true] { + for bc in [false, true] { + for alias in [false, true] { + let shader = lowered( + &native(cross, fi, bc, alias, wave64), + options.WaveLaneCountMax, + ) + .expect("lower permlane"); + let (root, pso) = + host.compute_pipeline(&shader).expect("permlane pipeline"); + for selectors in [ + [0x7654_3210u32, 0xFEDC_BA98], // identity + [0x89AB_CDEF, 0x0123_4567], // reverse + [0, 0], // broadcast lane 0 + [u32::MAX, u32::MAX], // broadcast lane 15 + [0xF10E_2D3C, 0x4B5A_6978], // arbitrary; both selector words + ] { + for mask in [u32::MAX, 0x5555_5555, 0xFFFF_0000, 1, 0] { + let constants = [selectors[0], selectors[1], mask, mask]; + let mut ud = vec![0; shader.user_data_dwords() as usize]; + for u in &shader.user_data { + ud[u.index as usize] = if u.root == RootType::Constants { + constants[u.dword as usize] + } else { + 0 + }; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(THREADS)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .expect("dispatch permlane"); + for t in 0..THREADS { + let pos = t % 16; + let packed = + u64::from(selectors[0]) | u64::from(selectors[1]) << 32; + let pick = (packed >> (4 * pos)) as u32 & 15; + let src = ((t & !15) ^ if cross { 16 } else { 0 }) | pick; + let old = if alias { BASE + t } else { OLD }; + let want = if mask >> (t % 32) & 1 == 0 { + old + } else if fi || mask >> (src % 32) & 1 != 0 { + BASE + src + } else if bc { + 0 + } else { + old + }; + let got = out[0][t as usize]; + assert_eq!( + got, want, + "{backend} wave64={wave64} cross={cross} fi={fi} bc={bc} alias={alias} selectors={selectors:x?} mask={mask:x} lane={t}" + ); + } + } + } + } + } + } + } + } + eprintln!("permlane: all row and EXEC cases passed on {backend}"); + } + if ran == 0 { + eprintln!("no SM 6.6 device with 32-lane rows; GPU checks skipped"); + } +} From 61e5f79ac6e0a10508071f0ffd9a65acb6bb0b4c Mon Sep 17 00:00:00 2001 From: Noname0202 Date: Tue, 24 Nov 2026 21:47:24 +0100 Subject: [PATCH 131/445] Shaders: use makeDouble.f64 overload and DXIL ShaderFlags bit 2 for DOUBLES --- crates/victory-shader/src/emit/lower.rs | 6 +++--- crates/victory-shader/src/emit/shader.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 2afe637..0007a93 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1983,7 +1983,7 @@ impl<'a> Lower<'a> { .named_struct("dx.types.splitdouble", vec![i32t, i32t]); let arg = self .s - .op(c, "makeDouble", Attr::ReadNone, f64t, 101, &[lo, hi]); + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]); let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0)); let sum = self .s @@ -2003,10 +2003,10 @@ impl<'a> Lower<'a> { let c = self.cur; let d0 = self .s - .op(c, "makeDouble", Attr::ReadNone, f64t, 101, &[lo0, hi0]); + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]); let d1 = self .s - .op(c, "makeDouble", Attr::ReadNone, f64t, 101, &[lo1, hi1]); + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]); let total = self.s.m.bin(c, Bin::Add, d0, d1); let split = self .s diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 25bff73..70a725c 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -73,7 +73,7 @@ pub const USER_VIEW_BIAS: u32 = 0x103; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { pub const RAW_BUFFERS: u64 = 1 << 4; - pub const DOUBLES: u64 = 1 << 5; + pub const DOUBLES: u64 = 1 << 2; pub const STENCIL_REF: u64 = 1 << 11; pub const TYPED_UAV_LOADS: u64 = 1 << 13; pub const WAVE_OPS: u64 = 1 << 19; From fffafee5c7a1d0c5bbd4b0984dfffb0f85cb98f2 Mon Sep 17 00:00:00 2001 From: fever308 <89748148+fever308@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:48:25 -0600 Subject: [PATCH 132/445] gpu: auto-scale card buffer limits from local VRAM budget --- crates/victory-gpu/src/shadow.rs | 96 +++++++++++++++++++++++++++++--- 1 file changed, 88 insertions(+), 8 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index d170075..9c47b88 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -139,19 +139,69 @@ pub(crate) fn cards() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_BUFFERS").is_none_or(|v| v != "0")) } +/// Default `(min_mb, max_mb)` for [`card_limits`] chosen from the adapter's +/// local VRAM budget (`DXGI_QUERY_VIDEO_MEMORY_INFO.Budget`), in bytes. +/// +/// - Unknown (`None`, e.g. WARP) or `<= 14 GiB` (8–12 GB cards): `(16, 512)` MiB, +/// matching the original 12 GB baseline. +/// - `> 14 GiB` and `< 20 GiB` (16 GB cards): `(4, 2048)` MiB. +/// - `>= 20 GiB` (24–32+ GB cards): `(1, (budget_mb / 4).min(8192))` MiB, +/// capping at 25% of local budget (at most 8 GiB) so "before" twins (up to 2x) +/// still leave headroom for textures and render targets. +fn default_card_limits_mb(local_vram_budget: Option) -> (u64, u64) { + let Some(budget_bytes) = local_vram_budget else { + return (16, 512); + }; + let budget_mb = budget_bytes >> 20; + const FOURTEEN_GIB_MB: u64 = 14 * 1024; + const TWENTY_GIB_MB: u64 = 20 * 1024; + if budget_mb <= FOURTEEN_GIB_MB { + (16, 512) + } else if budget_mb < TWENTY_GIB_MB { + (4, 2048) + } else { + (1, (budget_mb / 4).min(8192)) + } +} + +/// Resolve `(min_bytes, max_bytes)` from the adapter's local VRAM budget and +/// optional explicit MiB overrides from `VICTORY_CARD_BUFFERS_MIN_MB` / +/// `VICTORY_CARD_BUFFERS_MB`. +fn resolve_card_limits( + local_vram_budget: Option, + min_mb_override: Option, + max_mb_override: Option, +) -> (u64, u64) { + let (default_min_mb, default_max_mb) = default_card_limits_mb(local_vram_budget); + let min_bytes = (min_mb_override.unwrap_or(default_min_mb) << 20).max(1 << 20); + let max_bytes = max_mb_override.unwrap_or(default_max_mb) << 20; + (min_bytes, max_bytes) +} + /// The smallest title buffer whose copy goes to the card's memory, and the /// most bytes of such copies (their "before" twins not counted: a copy /// shaders write takes its size twice), both in bytes: -/// `VICTORY_CARD_BUFFERS_MIN_MB` (16) and `VICTORY_CARD_BUFFERS_MB` (512). -/// Run 69's gameplay has ten title buffers of 16 MiB or more, 494 MB, and -/// 1,650 MB of the card's budget free. +/// `VICTORY_CARD_BUFFERS_MIN_MB` and `VICTORY_CARD_BUFFERS_MB`. +/// Defaults scale with the adapter's local VRAM budget (16 MiB / 512 MiB on +/// `<= 14 GiB` cards, 4 MiB / 2048 MiB on 16 GB cards, 1 MiB / up to 8192 MiB +/// on `>= 20 GiB` cards), and explicit env vars always override. fn card_limits() -> (u64, u64) { static LIMITS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); *LIMITS.get_or_init(|| { - let mb = |name: &str, default: u64| { - std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(default) << 20 - }; - (mb("VICTORY_CARD_BUFFERS_MIN_MB", 16).max(1 << 20), mb("VICTORY_CARD_BUFFERS_MB", 512)) + let env_mb = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()); + let vram_budget = crate::host::host().and_then(|h| h.video_memory()).map(|[budget, ..]| budget); + let (min_bytes, max_bytes) = resolve_card_limits( + vram_budget, + env_mb("VICTORY_CARD_BUFFERS_MIN_MB"), + env_mb("VICTORY_CARD_BUFFERS_MB"), + ); + tracing::info!( + vram_budget_mb = vram_budget.map(|b| b >> 20), + card_buffers_min_mb = min_bytes >> 20, + card_buffers_max_mb = max_bytes >> 20, + "card buffer limits" + ); + (min_bytes, max_bytes) }) } @@ -3049,7 +3099,37 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option 14 GiB, < 20 GiB). + assert_eq!(default_card_limits_mb(Some(15 * GIB)), (4, 2048)); + assert_eq!(default_card_limits_mb(Some(16 * GIB)), (4, 2048)); + + // 24–32+ GB tier (>= 20 GiB): 1 MiB min, 25% of budget capped at 8192 MiB. + assert_eq!(default_card_limits_mb(Some(20 * GIB)), (1, 5120)); + assert_eq!(default_card_limits_mb(Some(24 * GIB)), (1, 6144)); + assert_eq!(default_card_limits_mb(Some(32 * GIB)), (1, 8192)); + assert_eq!(default_card_limits_mb(Some(48 * GIB)), (1, 8192)); + + // Explicit env overrides always win, and min is clamped to at least 1 MiB. + assert_eq!(resolve_card_limits(Some(32 * GIB), Some(8), Some(4096)), (8 * MIB, 4096 * MIB)); + assert_eq!(resolve_card_limits(Some(12 * GIB), Some(0), Some(1024)), (MIB, 1024 * MIB)); + assert_eq!(resolve_card_limits(None, None, None), (16 * MIB, 512 * MIB)); + } /// An ask that may take any window takes the longest that holds all of /// it, and none that holds only a part. From 9beff3cd4bb866bd7df5c17650afa445c06725a7 Mon Sep 17 00:00:00 2001 From: fever308 <89748148+fever308@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:53:05 -0600 Subject: [PATCH 133/445] gpu: scale texture VRAM floor and per-frame staging budget from VRAM --- crates/victory-gpu/src/draw.rs | 43 +++++++++++++++++++++++++++--- crates/victory-gpu/src/resource.rs | 41 ++++++++++++++++++++++------ 2 files changed, 73 insertions(+), 11 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index f9937b1..f6eb649 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1445,8 +1445,11 @@ impl State { if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) { return; } - /// Bytes of texture memory staged per frame. - const PER_FRAME: u64 = 192 << 20; + let per_frame = staging_budget_per_frame( + crate::host::host() + .and_then(|h| h.video_memory()) + .map(|[budget, ..]| budget), + ); static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); static SPENT: AtomicU64 = AtomicU64::new(0); let frame = crate::frame::current(); @@ -1502,7 +1505,7 @@ impl State { const SPAN: std::time::Duration = std::time::Duration::from_millis(250); let began = std::time::Instant::now(); for (index, write) in due { - if SPENT.load(Ordering::Relaxed) >= PER_FRAME || began.elapsed() > SPAN { + if SPENT.load(Ordering::Relaxed) >= per_frame || began.elapsed() > SPAN { break; } // A placed texture whose memory is not mapped (not streamed in @@ -2690,3 +2693,37 @@ pub(crate) fn stencil_ref(list: &HostList, reference: u32) { // SAFETY: an open list. unsafe { list.list.OMSetStencilRef(reference) }; } + +/// Per-frame texture staging byte budget scaled from the adapter's local VRAM +/// budget (`None` keeps the 192 MiB 12 GiB baseline). +fn staging_budget_per_frame(vram_budget: Option) -> u64 { + const GIB: u64 = 1 << 30; + const MIB: u64 = 1 << 20; + match vram_budget { + Some(budget) if budget <= 6 * GIB => 96 * MIB, + Some(budget) if budget >= 20 * GIB => 384 * MIB, + Some(budget) if budget > 14 * GIB => 256 * MIB, + _ => 192 * MIB, + } +} + +#[cfg(test)] +mod tests { + use super::staging_budget_per_frame; + + #[test] + fn staging_budget_scales_with_vram_budget() { + const GIB: u64 = 1 << 30; + const MIB: u64 = 1 << 20; + assert_eq!(staging_budget_per_frame(None), 192 * MIB); + assert_eq!(staging_budget_per_frame(Some(4 * GIB)), 96 * MIB); + assert_eq!(staging_budget_per_frame(Some(6 * GIB)), 96 * MIB); + assert_eq!(staging_budget_per_frame(Some(8 * GIB)), 192 * MIB); + assert_eq!(staging_budget_per_frame(Some(12 * GIB)), 192 * MIB); + assert_eq!(staging_budget_per_frame(Some(14 * GIB)), 192 * MIB); + assert_eq!(staging_budget_per_frame(Some(16 * GIB)), 256 * MIB); + assert_eq!(staging_budget_per_frame(Some(20 * GIB)), 384 * MIB); + assert_eq!(staging_budget_per_frame(Some(24 * GIB)), 384 * MIB); + assert_eq!(staging_budget_per_frame(Some(32 * GIB)), 384 * MIB); + } +} diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 3782a0d..a3297ae 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1354,17 +1354,28 @@ pub(crate) fn host_made<'a>( Some(unsafe { &*std::ptr::from_ref(&host.texture) }) } +/// Unconditional host-texture floor for a given local VRAM budget (`None` when +/// the adapter does not report one): up to 2 GiB, capped at a quarter of the +/// reported budget so 4–6 GiB cards do not bypass the budget check early. +#[cfg(any(windows, test))] +fn texture_floor_bytes(vram_budget: Option) -> u64 { + const MAX_FLOOR: u64 = 2 << 30; + match vram_budget { + Some(budget) => MAX_FLOOR.min(budget / 4), + None => MAX_FLOOR, + } +} + /// Whether more host copies of textures the title fills may be made for /// shaders that pick textures by index (`draw.rs` `heap_textures`): always -/// up to `FLOOR` bytes of them, beyond that while the card's memory in use -/// by this process is under nine tenths of the budget the system gives it -/// (`VICTORY_TEXTURE_BUDGET_MB` sets a limit on those copies' bytes -/// instead). Past the budget the system moves the card's memory into the -/// PC's, which ended runs 20 and 24. +/// up to [`texture_floor_bytes`] bytes of them, beyond that while the card's +/// memory in use by this process is under nine tenths of the budget the system +/// gives it (`VICTORY_TEXTURE_BUDGET_MB` sets a limit on those copies' bytes +/// instead). Past the budget the system moves the card's memory into the PC's, +/// which ended runs 20 and 24. #[cfg(windows)] pub(crate) fn room() -> bool { use std::sync::atomic::Ordering::Relaxed; - const FLOOR: u64 = 2 << 30; const WITHOUT_BUDGET: u64 = 4 << 30; static LIMIT: std::sync::OnceLock> = std::sync::OnceLock::new(); let limit = *LIMIT.get_or_init(|| { @@ -1375,10 +1386,12 @@ pub(crate) fn room() -> bool { if let Some(limit) = limit { return filled < limit; } - if filled < FLOOR { + let memory = crate::host::host().and_then(|h| h.video_memory()); + let floor = texture_floor_bytes(memory.map(|[budget, ..]| budget)); + if filled < floor { return true; } - match crate::host::host().and_then(|h| h.video_memory()) { + match memory { Some([budget, used, ..]) => used < budget / 10 * 9, None => filled < WITHOUT_BUDGET, } @@ -3407,4 +3420,16 @@ float4 lit() : SV_Target { return 1.0; } assert_eq!(slot::(heap, 0x10)(heap), 1); assert_eq!(slot::(placed, 0x10)(placed), 0); } + + #[test] + fn texture_floor_scales_with_vram_budget() { + const GIB: u64 = 1 << 30; + assert_eq!(texture_floor_bytes(None), 2 * GIB); + assert_eq!(texture_floor_bytes(Some(4 * GIB)), GIB); + assert_eq!(texture_floor_bytes(Some(6 * GIB)), 6 * GIB / 4); + assert_eq!(texture_floor_bytes(Some(8 * GIB)), 2 * GIB); + assert_eq!(texture_floor_bytes(Some(12 * GIB)), 2 * GIB); + assert_eq!(texture_floor_bytes(Some(24 * GIB)), 2 * GIB); + assert_eq!(texture_floor_bytes(Some(32 * GIB)), 2 * GIB); + } } From eb5061cca62e1addb382cc9c957b81a107d889a6 Mon Sep 17 00:00:00 2001 From: pgm1207 <104554896+pgm1207@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:13:53 +0100 Subject: [PATCH 134/445] GPU: no blending on integer render targets in host pipelines The console ignores blending on integer render targets and the title leaves it on (the world has a mesh pipeline blending into an R8_UINT target). D3D12 does not allow it: vkd3d-proton refuses such a pipeline with E_INVALIDARG and its draws are lost. The host pipeline now turns blending off on integer targets; with one description for all targets, each target gets its own copy so the others keep theirs. --- crates/victory-gpu/src/pipeline/host.rs | 119 +++++++++++++++++++++++- 1 file changed, 117 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index e8d4579..32e6cd8 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -89,6 +89,65 @@ impl Default for GraphicsState { } } +/// Integer render target formats: D3D12 cannot blend into them. +fn integer_format(f: DXGI_FORMAT) -> bool { + matches!( + f, + DXGI_FORMAT_R32G32B32A32_UINT + | DXGI_FORMAT_R32G32B32A32_SINT + | DXGI_FORMAT_R32G32B32_UINT + | DXGI_FORMAT_R32G32B32_SINT + | DXGI_FORMAT_R16G16B16A16_UINT + | DXGI_FORMAT_R16G16B16A16_SINT + | DXGI_FORMAT_R32G32_UINT + | DXGI_FORMAT_R32G32_SINT + | DXGI_FORMAT_R10G10B10A2_UINT + | DXGI_FORMAT_R8G8B8A8_UINT + | DXGI_FORMAT_R8G8B8A8_SINT + | DXGI_FORMAT_R16G16_UINT + | DXGI_FORMAT_R16G16_SINT + | DXGI_FORMAT_R32_UINT + | DXGI_FORMAT_R32_SINT + | DXGI_FORMAT_R8G8_UINT + | DXGI_FORMAT_R8G8_SINT + | DXGI_FORMAT_R16_UINT + | DXGI_FORMAT_R16_SINT + | DXGI_FORMAT_R8_UINT + | DXGI_FORMAT_R8_SINT + ) +} + +/// The title's blend state as the host takes it: blending off on integer +/// render targets. The console ignores blending there, and titles leave it +/// on (the world sets it on an `R8_UINT` target), but D3D12 does not allow +/// it: vkd3d-proton refuses such a pipeline with `E_INVALIDARG` ("using +/// integer format is not supported"), and its draws are lost. With one +/// description for every target, each target gets its own copy so the +/// others keep theirs. +fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D12_BLEND_DESC { + let count = (targets.NumRenderTargets as usize).min(8); + let per_target = blend.IndependentBlendEnable.as_bool(); + let blends = |i: usize| { + blend.RenderTarget[if per_target { i } else { 0 }] + .BlendEnable + .as_bool() + }; + if !(0..count).any(|i| integer_format(targets.RTFormats[i]) && blends(i)) { + return *blend; + } + let mut host = *blend; + if !per_target { + host.IndependentBlendEnable = true.into(); + host.RenderTarget = [blend.RenderTarget[0]; 8]; + } + for i in 0..count { + if integer_format(targets.RTFormats[i]) { + host.RenderTarget[i].BlendEnable = false.into(); + } + } + host +} + impl GraphicsState { /// Takes in one subobject of a stream: its type, then its data at +4 /// (+8 for those holding pointers). @@ -605,7 +664,7 @@ impl HostPipeline { BytecodeLength: gs.len(), } }), - BlendState: g.blend, + BlendState: host_blend(&g.blend, &g.targets), SampleMask: g.sample_mask, RasterizerState: g.rasterizer, DepthStencilState: g.depth, @@ -761,7 +820,7 @@ fn mesh_pipeline( root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms), ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), - blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, host_blend(&g.blend, &g.targets)), mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask), raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth), @@ -928,4 +987,60 @@ mod tests { "the mesh pipeline was compiled again instead of loaded from the library" ); } + + fn targets(formats: &[DXGI_FORMAT]) -> D3D12_RT_FORMAT_ARRAY { + let mut t = D3D12_RT_FORMAT_ARRAY { + NumRenderTargets: formats.len() as u32, + ..Default::default() + }; + t.RTFormats[..formats.len()].copy_from_slice(formats); + t + } + + fn blending(independent: bool) -> D3D12_BLEND_DESC { + let mut b = GraphicsState::default().blend; + b.IndependentBlendEnable = independent.into(); + for t in &mut b.RenderTarget { + t.BlendEnable = true.into(); + t.SrcBlend = D3D12_BLEND_SRC_ALPHA; + t.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; + } + b + } + + #[test] + fn integer_targets_do_not_blend() { + let t = targets(&[ + DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_R16G16B16A16_FLOAT, + DXGI_FORMAT_R8_UINT, + ]); + for independent in [false, true] { + let host = host_blend(&blending(independent), &t); + assert!(host.IndependentBlendEnable.as_bool()); + assert!(host.RenderTarget[0].BlendEnable.as_bool()); + assert!(host.RenderTarget[1].BlendEnable.as_bool()); + assert!(!host.RenderTarget[2].BlendEnable.as_bool()); + // The rest of the target's state is the title's. + assert_eq!(host.RenderTarget[2].SrcBlend, D3D12_BLEND_SRC_ALPHA); + assert_eq!(host.RenderTarget[0].DestBlend, D3D12_BLEND_INV_SRC_ALPHA); + } + } + + #[test] + fn blend_states_without_integer_blending_are_kept() { + // No integer target. + let b = blending(false); + let t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R11G11B10_FLOAT]); + assert_eq!(host_blend(&b, &t), b); + // An integer target that does not blend. + let mut b = blending(true); + b.RenderTarget[1].BlendEnable = false.into(); + let t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT]); + assert_eq!(host_blend(&b, &t), b); + // Integer formats past the targets in use. + let mut t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM]); + t.RTFormats[1] = DXGI_FORMAT_R8_UINT; + assert_eq!(host_blend(&blending(false), &t), blending(false)); + } } From 15cc76c39f18bc9f5b80ea796bd24ad11ccfed85 Mon Sep 17 00:00:00 2001 From: jaschinski97-ops <232683647+jaschinski97-ops@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:57:30 +0100 Subject: [PATCH 135/445] Shaders: retain live interpolation first halves --- crates/victory-shader/src/emit/mod.rs | 147 ++++++++++++++++++++++++++ crates/victory-shader/src/io.rs | 94 +++++++++++++++- 2 files changed, 239 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index b667241..d6d5a2d 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -1624,6 +1624,153 @@ mod barycentric_tests { validate(&shader); } + #[test] + fn a_standalone_first_half_reads_the_vertices() { + let shader = first_half_pixel(false); + let (_, inputs) = parts(&shader); + assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + } + + #[test] + fn a_first_half_read_beside_its_pair_keeps_its_partial_value() { + let shader = first_half_pixel(true); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + } + + fn first_half_pixel(paired: bool) -> HostShader { + let [e0, e1] = exp_mrt0(2); + let mut words = vec![0xC808_0000]; // v_interp_p1_f32 v2, v0, attr0.x + if paired { + words.extend([ + 0x7E06_0302, // v_mov_b32 v3, v2 (keep the partial value) + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + v_add_f32(2, 2, 3), + ]); + } + words.extend([e0, e1, 0xBF81_0000]); + pixel(&words, PERSP_CENTER).unwrap() + } + + #[test] + #[cfg(windows)] + fn first_half_values_render_on_hardware_and_warp() { + use super::bitcode::{Attr, Term}; + use super::host::{Draw, Host}; + use super::shader::Shader; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + // Pass POSITION and TEXCOORD through, with TEXCOORD in the same + // output row as the translated pixel shader's input signature. + let mut s = Shader::new(false); + s.inputs = vec![element("POSITION", 0, 0), element("TEXCOORD", 0, 1)]; + for e in &mut s.inputs { + e.usage = 15; + } + s.outputs = vec![element("TEXCOORD", 0, 0), element("SV_Position", 3, 1)]; + for (i, e) in s.outputs.iter_mut().enumerate() { + e.usage = 15; + e.interp = if i == 1 { 4 } else { 2 }; + } + for row in 0..2 { + for col in 0..4 { + let args = [s.m.i32(row), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)]; + let v = s.op(s.entry, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args); + let args = [s.m.i32(1 - row), s.m.i32(0), s.m.i8(col), v]; + s.op( + s.entry, + "storeOutput.f32", + Attr::NoUnwind, + s.t.void, + 5, + &args, + ); + } + } + s.m.terminate(s.entry, Term::Ret); + let vs = HostShader { + stage: HwStage::Vs, + dxil: s.finish(), + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + }; + validate(&vs); + // One triangle covers an 8x8 target, with attribute values 2, 6, 10. + let vertices = [ + -1.0, 1.0, 0.5, 1.0, 2.0, 0.0, 0.0, 0.0, -1.0, -3.0, 0.5, 1.0, 6.0, 0.0, 0.0, 0.0, 3.0, + 1.0, 0.5, 1.0, 10.0, 0.0, 0.0, 0.0, + ]; + let mut ran = 0; + for (backend, warp) in [("hardware", false), ("WARP", true)] { + let Ok(host) = Host::new(warp) else { continue }; + let mut options = + windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS3::default(); + // SAFETY: a correctly sized output for the feature query. + unsafe { + host.device + .CheckFeatureSupport( + windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_D3D12_OPTIONS3, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .unwrap(); + } + if !options.BarycentricsSupported.as_bool() { + eprintln!("no barycentrics on {backend}; skipped"); + continue; + } + for paired in [false, true] { + let ps = first_half_pixel(paired); + validate(&ps); + let (root, pso) = host.pipeline(&vs, &ps).expect("interpolation pipeline"); + let out = host + .draw( + &root, + &pso, + &Draw { + roots: Vec::new(), + textures: &[], + samplers: &[], + vertices: &vertices, + stride: 32, + size: (8, 8), + mesh_groups: 0, + }, + ) + .expect("draw partial interpolation"); + for (n, texel) in out.iter().enumerate() { + let i = (n / 8) as f32 / 16.0 + 0.5 / 16.0; + let j = (n % 8) as f32 / 16.0 + 0.5 / 16.0; + let partial = 2.0 + i * 4.0; + let want = if paired { + partial + 2.0 + i * 4.0 + j * 8.0 + } else { + partial + }; + for &got in texel { + assert!( + (got - want).abs() < 1e-5, + "{backend} paired={paired} pixel={n}: got {got}, want {want}" + ); + } + } + } + ran += 1; + eprintln!("partial interpolation renders correctly on {backend}"); + } + if ran == 0 { + eprintln!("no SM 6.6 host with barycentrics; GPU checks skipped"); + } + } + /// Both: the attribute is interpolated and J is used as a value. #[test] fn interpolation_and_a_barycentric_value_together() { diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index 09b1f8e..7773ca7 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -369,6 +369,7 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { defs: &defs, phis: &phis, }; + let mut first_halves = Vec::new(); for (b, block) in p.blocks.iter().enumerate() { for (i, inst) in block.insts.iter().enumerate() { let site = (b, i); @@ -382,7 +383,7 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { io.interps .push((site, Interp::Vertex { attribute, vertex })); } - ("v_interp_p1_f32", _) => {} + ("v_interp_p1_f32", _) => first_halves.push((site, attribute)), ("v_interp_p2_f32", Operand::Vector { reg, .. }) => { let Operand::Vector { reg: d, .. } = *dst else { return Err(unsupported(at, "an interpolation operand")); @@ -402,7 +403,9 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { } } Fields::Valu(v) if name.starts_with("v_interp_") => match name { - "v_interp_p1ll_f16" => {} + "v_interp_p1ll_f16" => { + first_halves.push((site, attribute(inst, &v.src[0])?)); + } "v_interp_p2_f16" => { let attribute = attribute(inst, &v.src[0])?; let read = |k: usize| match v.src.get(k) { @@ -460,6 +463,49 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { } } } + // A loaded i/j pair normally becomes one host interpolation: its first + // half need not be evaluated. A first half also read as data (or used + // without a second half) must keep P0 + i * P10. Follow phi uses too, + // without forcing ordinary pairs to read per-vertex attributes. + let folded: std::collections::HashSet<_> = io + .interps + .iter() + .filter_map(|(s, i)| matches!(i, Interp::Interpolated { .. }).then_some(*s)) + .collect(); + let mut used: std::collections::HashSet<_> = p + .blocks + .iter() + .enumerate() + .flat_map(|(b, blk)| { + blk.insts + .iter() + .enumerate() + .map(move |(i, inst)| ((b, i), inst)) + }) + .filter(|(s, _)| !folded.contains(s)) + .flat_map(|(_, inst)| inst.reads.iter().map(|r| r.1)) + .collect(); + loop { + let before = used.len(); + for phi in p.blocks.iter().flat_map(|b| &b.phis) { + if used.contains(&phi.value) { + used.extend(&phi.args); + } + } + if used.len() == before { + break; + } + } + for (site, attribute) in first_halves { + if !io.interps.iter().any(|(s, _)| *s == site) + && p.blocks[site.0].insts[site.1] + .writes + .iter() + .any(|w| used.contains(&w.1)) + { + io.interps.push((site, Interp::Weighted { attribute })); + } + } Ok(io) } @@ -725,6 +771,50 @@ mod tests { ); } + #[test] + fn first_halves_read_through_a_phi_keep_their_partial_values() { + let p = program(&[ + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF85_0002, // s_cbranch_scc1 -> second first half + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xBF82_0001, // s_branch -> export + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xF800_180F, + 0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm + S_ENDPGM, + ]); + let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap(); + assert_eq!(io.interps.len(), 2); + assert!( + io.interps + .iter() + .all(|(_, i)| matches!(i, Interp::Weighted { .. })) + ); + } + + #[test] + fn a_standalone_f16_first_half_is_weighted() { + let p = program(&[ + 0xD742_0002, + 0x0002_0000, // v_interp_p1ll_f16 v2, v0, attr0.x + 0xF800_180F, + 0x0202_0202, + S_ENDPGM, + ]); + let io = raise( + &p, + &pixel( + vec![PsInput { + fp16: true, + ..TEXCOORD + }], + 2, + ), + ) + .unwrap(); + assert!(matches!(&io.interps[..], [(_, Interp::Weighted { .. })])); + } + #[test] fn mesh_inputs_and_primitive_export() { let mesh = |words: &[u32]| { From 81a8e2e313d8830d8b4589eef2509a610921a158 Mon Sep 17 00:00:00 2001 From: jaschinski97-ops <232683647+jaschinski97-ops@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:58:36 +0100 Subject: [PATCH 136/445] Skip first-half use tracking when no interpolation is present --- crates/victory-shader/src/io.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index 7773ca7..3899cc9 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -463,6 +463,9 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { } } } + if first_halves.is_empty() { + return Ok(io); + } // A loaded i/j pair normally becomes one host interpolation: its first // half need not be evaluated. A first half also read as data (or used // without a second half) must keep P0 + i * P10. Follow phi uses too, From c5b12f1202a8b47b2eb9bfb1df685b1f4df568ed Mon Sep 17 00:00:00 2001 From: SlopComp <360476765+SlopComp@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:46:32 -0600 Subject: [PATCH 137/445] Textures: guarded textures are hashed at every check while they may change behind the guard The guard on view memory sees no write made through another view of the same pages; such a change was found only by the hash every eighth frame. The boot logo video and the loading animation write their textures that way every frame (a ring of three): each showed up to eight frames late and in turns, so the presented picture cycled through three, a new one every eight frames, and flickered. The six-star screen of the first seconds changed before the hash ever caught it. A guarded texture is now hashed at every check for its first 64 frames, and for 64 frames after each change the guard missed; textures that stay unchanged go back to every eighth frame. VICTORY_TEXTURE_HOT=0: every eighth frame only, as before. --- crates/victory-gpu/src/copystat.rs | 5 ++- crates/victory-gpu/src/texture.rs | 55 ++++++++++++++++++++++++++++-- 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 6abd41b..292d995 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -37,6 +37,8 @@ pub(crate) enum C { TexWatched, TexHashed, TexChanged, + /// Changes of guarded textures the hash found and the guard did not see. + TexHot, /// Frames presented since the last line (what the line divides by). Frames, /// Calls of list methods that record into a host list, and the @@ -1060,7 +1062,7 @@ pub(crate) fn log(frames: f64) { {:.0} skipped {:.1} MB; {:.0} runs {:.1} ms; {:.0} queries {:.2} ms, moves {:.2} ms, \ {:.2} MB unmapped; {:.0} page faults; {:.0} watches {:.2} ms, {:.1} MB checked, {:.1} MB \ unchanged; {:.1} fallbacks; {:.0} guard faults; textures {:.1} MB watched and \ - changed, {:.1} MB hashed, {:.1} MB of them changed", + changed, {:.1} MB hashed, {:.1} MB of them changed, {:.1} changes the guard did not see", c[C::Submissions as usize], c[C::Copies as usize], mb(c[C::CopyBytes as usize]), @@ -1084,6 +1086,7 @@ pub(crate) fn log(frames: f64) { mb(c[C::TexWatched as usize]), mb(c[C::TexHashed as usize]), mb(c[C::TexChanged as usize]), + c[C::TexHot as usize], ); tracing::info!( "recording per frame ({frames:.0} frames): {:.0} list calls {:.1} ms (all recording \ diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index f815393..cbf5974 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -66,6 +66,31 @@ struct Last { asked: u64, /// The frame a partly mapped texture was last read in. partial: Option, + /// Until this frame a guarded texture is hashed at every check: its + /// first checks, and after the hash found a change the guard had not + /// seen ([`hot_textures`]). 0: not checked under the guard yet. + hot_until: u64, +} + +/// Frames a guarded texture is hashed at every check from its first check, +/// and after the hash found a change the guard did not see. +const HOT_FRAMES: u64 = 64; + +/// Whether a guarded texture whose memory the hash found changed although +/// the guard saw no write is hashed at every check for a while +/// ([`HOT_FRAMES`]), not every eighth frame. A title that writes such a +/// texture through another view of its pages (the guard sees none of it) +/// every frame, a video's frames in a ring of three, showed each one up +/// to eight frames late and in turns: the boot logo video and the loading +/// animation flickered between old and new pictures (fx-flicker run 1441: +/// the presented picture cycled through three, a new one every eight +/// frames). A texture also starts hot, for the ones written that way from +/// the start (the six-star screen of the first seconds, which the hash +/// never caught changing). `VICTORY_TEXTURE_HOT=0`: every eighth frame +/// only, as before. +fn hot_textures() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_HOT").is_none_or(|v| v != "0")) } // SAFETY: the staging mapping is written only at submission, under @@ -647,17 +672,37 @@ impl Staging { // texture's address, so the textures take turns. // `VICTORY_TEXTURE_GUARD=0` hashes at every check, as before. static GUARD: std::sync::OnceLock = std::sync::OnceLock::new(); + // The guard saw no write: a change the hash finds came another way. + let mut blind = false; if *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true)) { const HASH_EVERY: u64 = 8; let unwritten = last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked); last.asked = now; - let turn = crate::frame::current().wrapping_add((start >> 16) as u64).is_multiple_of(HASH_EVERY); - if unwritten && !turn { + let frame = crate::frame::current(); + let turn = frame + .wrapping_add((start >> 16) as u64) + .is_multiple_of(HASH_EVERY); + // A texture starts hot: one written that way from its first + // frames on changes before the hash has ever caught it. + if last.hot_until == 0 { + last.hot_until = frame + HOT_FRAMES; + } + let hot = hot_textures() && frame < last.hot_until; + if unwritten && !turn && !hot { return 0; } + blind = unwritten; } + // A change the guard did not see: hashed at every check for a while. + let found_blind = |last: &mut Last| { + if blind && hot_textures() { + last.hot_until = crate::frame::current() + HOT_FRAMES; + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexHot, 1); + } + }; // From here on the texture's memory may be read in place. Held until // that read is done: the runtime changes what title memory shows // only with this taken alone, so what `committed` finds mapped @@ -707,7 +752,9 @@ impl Staging { if changed { crate::copystat::add(crate::copystat::C::TexChanged, size as u64); } - let _ = changed; + if changed { + found_blind(last); + } return size; } if through_copy() { @@ -719,6 +766,7 @@ impl Staging { return size; } last.hash = Some(hash); + found_blind(last); self.detile(tiled); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexChanged, size as u64); @@ -735,6 +783,7 @@ impl Staging { return size; } last.hash = Some(hash); + found_blind(last); self.detile(tiled); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexChanged, size as u64); From de4ae6163b148afdfe1f35ccf45b174d19c430bf Mon Sep 17 00:00:00 2001 From: fever308 <89748148+fever308@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:07:05 -0600 Subject: [PATCH 138/445] gpu: lower 16 GB VRAM budget cutoff to 12 GiB and saturate env override shifts --- crates/victory-gpu/src/shadow.rs | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 9c47b88..5d97f3a 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -142,9 +142,10 @@ pub(crate) fn cards() -> bool { /// Default `(min_mb, max_mb)` for [`card_limits`] chosen from the adapter's /// local VRAM budget (`DXGI_QUERY_VIDEO_MEMORY_INFO.Budget`), in bytes. /// -/// - Unknown (`None`, e.g. WARP) or `<= 14 GiB` (8–12 GB cards): `(16, 512)` MiB, -/// matching the original 12 GB baseline. -/// - `> 14 GiB` and `< 20 GiB` (16 GB cards): `(4, 2048)` MiB. +/// - Unknown (`None`, e.g. WARP) or `<= 12 GiB` (8–12 GB cards, whose WDDM +/// budget is below 12 GiB): `(16, 512)` MiB, matching the 12 GB baseline. +/// - `> 12 GiB` and `< 20 GiB` (16 GB cards, whose WDDM budget is typically +/// ~13.5–15.2 GiB): `(4, 2048)` MiB. /// - `>= 20 GiB` (24–32+ GB cards): `(1, (budget_mb / 4).min(8192))` MiB, /// capping at 25% of local budget (at most 8 GiB) so "before" twins (up to 2x) /// still leave headroom for textures and render targets. @@ -153,9 +154,9 @@ fn default_card_limits_mb(local_vram_budget: Option) -> (u64, u64) { return (16, 512); }; let budget_mb = budget_bytes >> 20; - const FOURTEEN_GIB_MB: u64 = 14 * 1024; + const TWELVE_GIB_MB: u64 = 12 * 1024; const TWENTY_GIB_MB: u64 = 20 * 1024; - if budget_mb <= FOURTEEN_GIB_MB { + if budget_mb <= TWELVE_GIB_MB { (16, 512) } else if budget_mb < TWENTY_GIB_MB { (4, 2048) @@ -172,9 +173,10 @@ fn resolve_card_limits( min_mb_override: Option, max_mb_override: Option, ) -> (u64, u64) { + const MIB: u64 = 1 << 20; let (default_min_mb, default_max_mb) = default_card_limits_mb(local_vram_budget); - let min_bytes = (min_mb_override.unwrap_or(default_min_mb) << 20).max(1 << 20); - let max_bytes = max_mb_override.unwrap_or(default_max_mb) << 20; + let min_bytes = min_mb_override.unwrap_or(default_min_mb).saturating_mul(MIB).max(MIB); + let max_bytes = max_mb_override.unwrap_or(default_max_mb).saturating_mul(MIB); (min_bytes, max_bytes) } @@ -183,8 +185,8 @@ fn resolve_card_limits( /// shaders write takes its size twice), both in bytes: /// `VICTORY_CARD_BUFFERS_MIN_MB` and `VICTORY_CARD_BUFFERS_MB`. /// Defaults scale with the adapter's local VRAM budget (16 MiB / 512 MiB on -/// `<= 14 GiB` cards, 4 MiB / 2048 MiB on 16 GB cards, 1 MiB / up to 8192 MiB -/// on `>= 20 GiB` cards), and explicit env vars always override. +/// `<= 12 GiB` budgets, 4 MiB / 2048 MiB on 16 GB cards, 1 MiB / up to 8192 MiB +/// on `>= 20 GiB` budgets), and explicit env vars always override. fn card_limits() -> (u64, u64) { static LIMITS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); *LIMITS.get_or_init(|| { @@ -3109,13 +3111,15 @@ mod window_tests { const GIB: u64 = 1 << 30; const MIB: u64 = 1 << 20; - // Unknown (WARP / query failure) and <= 14 GiB keep the 12 GB baseline. + // Unknown (WARP / query failure) and <= 12 GiB keep the 12 GB baseline. assert_eq!(default_card_limits_mb(None), (16, 512)); assert_eq!(default_card_limits_mb(Some(8 * GIB)), (16, 512)); + assert_eq!(default_card_limits_mb(Some(11 * GIB)), (16, 512)); assert_eq!(default_card_limits_mb(Some(12 * GIB)), (16, 512)); - assert_eq!(default_card_limits_mb(Some(14 * GIB)), (16, 512)); - // 16 GB tier (> 14 GiB, < 20 GiB). + // 16 GB tier (> 12 GiB, < 20 GiB), including WDDM budgets around 13.5–15 GiB. + assert_eq!(default_card_limits_mb(Some(13 * GIB)), (4, 2048)); + assert_eq!(default_card_limits_mb(Some(14 * GIB)), (4, 2048)); assert_eq!(default_card_limits_mb(Some(15 * GIB)), (4, 2048)); assert_eq!(default_card_limits_mb(Some(16 * GIB)), (4, 2048)); @@ -3125,9 +3129,10 @@ mod window_tests { assert_eq!(default_card_limits_mb(Some(32 * GIB)), (1, 8192)); assert_eq!(default_card_limits_mb(Some(48 * GIB)), (1, 8192)); - // Explicit env overrides always win, and min is clamped to at least 1 MiB. + // Explicit env overrides always win, clamp min to >= 1 MiB, and saturate on overflow. assert_eq!(resolve_card_limits(Some(32 * GIB), Some(8), Some(4096)), (8 * MIB, 4096 * MIB)); assert_eq!(resolve_card_limits(Some(12 * GIB), Some(0), Some(1024)), (MIB, 1024 * MIB)); + assert_eq!(resolve_card_limits(None, Some(u64::MAX), Some(u64::MAX)), (u64::MAX, u64::MAX)); assert_eq!(resolve_card_limits(None, None, None), (16 * MIB, 512 * MIB)); } From 010b90a1176facc7e7ecbe27cfe20831aa00f5c9 Mon Sep 17 00:00:00 2001 From: fever308 <89748148+fever308@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:08:01 -0600 Subject: [PATCH 139/445] gpu: share video_memory query in heap_textures and lower 16 GB cutoff to 12 GiB --- crates/victory-gpu/src/draw.rs | 14 ++++++-------- crates/victory-gpu/src/resource.rs | 3 +-- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index f6eb649..7d7d741 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1445,11 +1445,8 @@ impl State { if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) { return; } - let per_frame = staging_budget_per_frame( - crate::host::host() - .and_then(|h| h.video_memory()) - .map(|[budget, ..]| budget), - ); + let memory = crate::host::host().and_then(|h| h.video_memory()); + let per_frame = staging_budget_per_frame(memory.map(|[budget, ..]| budget)); static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); static SPENT: AtomicU64 = AtomicU64::new(0); let frame = crate::frame::current(); @@ -1463,7 +1460,7 @@ impl State { // makes room again: so the slots are still looked at (the pass // returned here, and a slot whose texture had been streamed out // kept its host copy for as long as the card was full). - let room = crate::resource::room(); + let room = crate::resource::room(memory); if !room { HEAP_TEXTURES_FULL.fetch_add(1, Ordering::Relaxed); once!("textures picked by index: the card has no room for more; they wait"); @@ -2702,7 +2699,7 @@ fn staging_budget_per_frame(vram_budget: Option) -> u64 { match vram_budget { Some(budget) if budget <= 6 * GIB => 96 * MIB, Some(budget) if budget >= 20 * GIB => 384 * MIB, - Some(budget) if budget > 14 * GIB => 256 * MIB, + Some(budget) if budget > 12 * GIB => 256 * MIB, _ => 192 * MIB, } } @@ -2720,7 +2717,8 @@ mod tests { assert_eq!(staging_budget_per_frame(Some(6 * GIB)), 96 * MIB); assert_eq!(staging_budget_per_frame(Some(8 * GIB)), 192 * MIB); assert_eq!(staging_budget_per_frame(Some(12 * GIB)), 192 * MIB); - assert_eq!(staging_budget_per_frame(Some(14 * GIB)), 192 * MIB); + assert_eq!(staging_budget_per_frame(Some(13 * GIB)), 256 * MIB); + assert_eq!(staging_budget_per_frame(Some(14 * GIB)), 256 * MIB); assert_eq!(staging_budget_per_frame(Some(16 * GIB)), 256 * MIB); assert_eq!(staging_budget_per_frame(Some(20 * GIB)), 384 * MIB); assert_eq!(staging_budget_per_frame(Some(24 * GIB)), 384 * MIB); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index a3297ae..5c0a9d8 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1374,7 +1374,7 @@ fn texture_floor_bytes(vram_budget: Option) -> u64 { /// instead). Past the budget the system moves the card's memory into the PC's, /// which ended runs 20 and 24. #[cfg(windows)] -pub(crate) fn room() -> bool { +pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { use std::sync::atomic::Ordering::Relaxed; const WITHOUT_BUDGET: u64 = 4 << 30; static LIMIT: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -1386,7 +1386,6 @@ pub(crate) fn room() -> bool { if let Some(limit) = limit { return filled < limit; } - let memory = crate::host::host().and_then(|h| h.video_memory()); let floor = texture_floor_bytes(memory.map(|[budget, ..]| budget)); if filled < floor { return true; From ffdde86ef6d3ec74a6a82cfef456f24bb13f9d25 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 15:43:53 -0600 Subject: [PATCH 140/445] Pipeline workers follow the CPU; one pad that never disconnects Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/pipeline/make.rs | 29 ++++++- crates/victory-hle/src/modules/gameinput.rs | 96 +++++++++++++++++++-- 2 files changed, 116 insertions(+), 9 deletions(-) diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 9862446..138fb2b 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -292,12 +292,28 @@ fn next() -> Arc { } } -/// Starts the workers (half the logical processors, 2 to 8) on first use. +/// How many workers make pipelines: `asked` (`VICTORY_PIPELINE_WORKERS`, 1 to +/// 64), else two thirds of the logical processors, 2 to 16. They run below the +/// title's own threads, and a cold cache queues hundreds at once. +fn worker_count(asked: Option, processors: usize) -> usize { + match asked { + Some(n) => n.clamp(1, 64), + None => (processors * 2 / 3).clamp(2, 16), + } +} + +/// Starts the workers ([`worker_count`]) on first use. fn workers() -> bool { static RUNNING: OnceLock = OnceLock::new(); *RUNNING.get_or_init(|| { let mut running = false; - let workers = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8)); + let workers = worker_count( + std::env::var("VICTORY_PIPELINE_WORKERS") + .ok() + .and_then(|v| v.trim().parse().ok()), + std::thread::available_parallelism().map_or(2, |n| n.get()), + ); + tracing::info!(workers, "pipeline workers"); for i in 0..workers { let spawned = std::thread::Builder::new() .name(format!("victory-pipelines-{i}")) @@ -349,6 +365,15 @@ fn drained() { mod tests { use super::*; + #[test] + fn worker_count_follows_the_processors_and_the_switch() { + assert_eq!(worker_count(None, 1), 2); + assert_eq!(worker_count(None, 24), 16); + assert_eq!(worker_count(None, 64), 16); + assert_eq!(worker_count(Some(0), 24), 1); + assert_eq!(worker_count(Some(20), 24), 20); + } + /// A first use queues the pipeline and, within the budget, gets the /// worker's answer (here: no host pipeline for no shaders). #[test] diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 6cb89fa..76b2625 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -137,6 +137,32 @@ fn fallback(keys: &[KeyState]) -> PadState { } } +/// Two pads as one: buttons of both, and of each axis and trigger the one +/// pushed further. +fn merged(a: PadState, b: PadState) -> PadState { + let further = |x: f32, y: f32| if y.abs() > x.abs() { y } else { x }; + PadState { + buttons: a.buttons | b.buttons, + left_trigger: further(a.left_trigger, b.left_trigger), + right_trigger: further(a.right_trigger, b.right_trigger), + left_x: further(a.left_x, b.left_x), + left_y: further(a.left_y, b.left_y), + right_x: further(a.right_x, b.right_x), + right_y: further(a.right_y, b.right_y), + } +} + +/// Whether the title sees one pad that is always there, fed by the keyboard +/// and by every host pad (on by default; `VICTORY_ONE_PAD=0` shows each host +/// pad as a device of its own, and the stand-in only while there is none). +/// The title keeps to the pad it started with: with the stand-in taken away +/// when a pad was switched on, it showed its controller-disconnected screen +/// until the pad was off again. It also keeps a pad the host lists twice (its +/// own slot and a remapper's) from being two players. +fn one_pad() -> bool { + std::env::var_os("VICTORY_ONE_PAD").is_none_or(|v| v != "0") +} + #[repr(C)] struct Table([*const (); N]); // SAFETY: function addresses only. @@ -202,7 +228,7 @@ impl Device { root_id: id, supported_input: kind(index), // Low and high frequency. - rumble_motors: if index < PADS { 0x3 } else { 0 }, + rumble_motors: if index <= FALLBACK { 0x3 } else { 0 }, ..Default::default() }; Device { @@ -333,6 +359,8 @@ pub struct Hub { /// Apart from the state: XInput can be slow, and the title reads /// readings every frame. source: Mutex>, + /// The title sees one pad ([`one_pad`]). + one_pad: bool, state: Mutex, /// A device callback returned. returned: Condvar, @@ -356,7 +384,7 @@ fn now() -> u64 { } impl Hub { - fn new(source: Box) -> &'static Hub { + fn new(source: Box, one_pad: bool) -> &'static Hub { let hub = Box::into_raw(Box::new(Hub { object: Object { vtable: &INPUT, @@ -364,6 +392,7 @@ impl Hub { }, devices: std::array::from_fn(Device::new), source: Mutex::new(source), + one_pad, state: Mutex::new(State { slots: Default::default(), callbacks: Vec::new(), @@ -384,7 +413,7 @@ impl Hub { /// A hub over the host's input, polled from now on. fn start(source: Box) -> &'static Hub { - let hub = Hub::new(source); + let hub = Hub::new(source, one_pad()); hub.poll(); std::thread::spawn(move || { loop { @@ -406,7 +435,7 @@ impl Hub { let pads: [_; PADS] = std::array::from_fn(|slot| source.pad(slot)); (pads, source.keys()) }; - let events = self.state().poll(&self.devices, pads, keys); + let events = self.state().poll(&self.devices, self.one_pad, pads, keys); self.deliver(events); } @@ -449,11 +478,18 @@ impl State { fn poll( &mut self, devices: &[Device; DEVICES], + one_pad: bool, pads: [Option; PADS], keys: Vec, ) -> Vec { let now = now(); let mut events = std::mem::take(&mut self.pending); + if one_pad { + let pad = pads.into_iter().flatten().fold(fallback(&keys), merged); + self.update(devices, FALLBACK, Some(Value::Pad(pad)), now, &mut events); + self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events); + return events; + } let any_pad = pads.iter().any(Option::is_some); for (slot, pad) in pads.into_iter().enumerate() { self.update(devices, slot, pad.map(Value::Pad), now, &mut events); @@ -915,7 +951,8 @@ extern "system" fn device_status(this: *const Device) -> u32 { extern "system" fn set_rumble(this: *const Device, params: *const [f32; 4]) { // SAFETY: one of our devices. let device = unsafe { &*this }; - if device.index >= PADS { + let one_pad = device.hub().one_pad; + if device.index >= PADS && !(one_pad && device.index == FALLBACK) { return; } let [low, high, ..] = if params.is_null() { @@ -925,7 +962,17 @@ extern "system" fn set_rumble(this: *const Device, params: *const [f32; 4]) { unsafe { *params } }; let speed = |level: f32| (level.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16; - lock(&device.hub().source).rumble(device.index, speed(low), speed(high)); + let mut source = lock(&device.hub().source); + if one_pad { + // The one pad is every host pad. + for slot in 0..PADS { + if source.pad(slot).is_some() { + source.rumble(slot, speed(low), speed(high)); + } + } + } else { + source.rumble(device.index, speed(low), speed(high)); + } } extern "system" fn unsupported(_: *const c_void) -> HRESULT { tracing::warn!( @@ -1302,8 +1349,12 @@ mod tests { } fn fake() -> (&'static Hub, Arc>) { + fake_with(false) + } + + fn fake_with(one_pad: bool) -> (&'static Hub, Arc>) { let host = Arc::new(Mutex::new(FakeHost::default())); - let hub = Hub::new(Box::new(Fake(Arc::clone(&host)))); + let hub = Hub::new(Box::new(Fake(Arc::clone(&host))), one_pad); hub.poll(); (hub, host) } @@ -1523,6 +1574,37 @@ mod tests { assert_eq!(current(hub, GAMEPAD_KIND, KEYBOARD), Err(READING_NOT_FOUND)); } + #[test] + fn a_host_pad_feeds_the_one_pad_which_never_goes() { + let (hub, host) = fake_with(true); + let log = Log::default(); + register(hub, GAMEPAD_KIND, 2, &log); + assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]); + let pad = |hub: &Hub| match &hub.state().slots[FALLBACK].history.back().unwrap().value { + Value::Pad(p) => *p, + Value::Keys(_) => unreachable!(), + }; + host.lock().unwrap().keys = vec![key(b'D')]; + hub.poll(); + assert_eq!(pad(hub).left_x, 1.0); + // A pad is switched on, in any slot: its input arrives, beside the + // keyboard's, and no device comes or goes. + host.lock().unwrap().pads[2] = Some(PadState { buttons: A, left_y: -0.5, ..Default::default() }); + hub.poll(); + let p = pad(hub); + assert_eq!((p.buttons, p.left_x, p.left_y), (A, 1.0, -0.5)); + let device: *const Device = &hub.devices[FALLBACK]; + set_rumble(device, &[1.0, 0.0, 0.0, 0.0]); + assert_eq!(host.lock().unwrap().rumble, [(2, u16::MAX, 0)]); + // And off again. + host.lock().unwrap().pads[2] = None; + host.lock().unwrap().keys.clear(); + hub.poll(); + assert_eq!(pad(hub), PadState::default()); + assert_eq!(log.lock().unwrap().len(), 1); + assert!(!hub.state().slots[2].connected); + } + #[test] fn async_enumeration_waits_for_the_poll_and_unregistering_stops_callbacks() { let (hub, host) = fake(); From 9e49b8a04e6cb9f0b7f81ec11170acf8400f022a Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:59:43 -0500 Subject: [PATCH 141/445] Take the parked lane-mask change (#11) back out for now Its programs translate and run, but on the test machine the lighting gain could not be shown, it costs about 40 ms of GPU time per frame, and the picture is being re-checked one change at a time from a known-good tree. It may come back once that is settled. Co-Authored-By: Claude Fable 5.2 --- apps/victory/src/translate.rs | 19 ---------------- crates/victory-shader/src/ir.rs | 40 +++------------------------------ 2 files changed, 3 insertions(+), 56 deletions(-) diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 1d13ae2..dc5d6c8 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -160,11 +160,6 @@ pub fn run( jobs: Option, ) -> Result<()> { let paths = crate::default_paths(paths)?; - // `VICTORY_HOST_MAX_WAVE=32`: translate as for a host whose waves have - // at most 32 lanes (as the runtime does on such a card). - if let Some(n) = std::env::var("VICTORY_HOST_MAX_WAVE").ok().and_then(|v| v.parse().ok()) { - victory_shader::emit::set_host_max_wave(n); - } let dll = validate.then(Validator::default_path).flatten(); if validate { Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?; @@ -320,20 +315,6 @@ fn translate( // The hash a run's log names the shader by (`hash=` in "first bind", // "shader does not translate", "host pipeline refused"). let hash = blake3::hash(&bytes).to_hex()[..16].to_owned(); - // Diagnostics: `VICTORY_TRANSLATE_ONLY=,...` translates - // those containers alone. - static ONLY: std::sync::OnceLock> = std::sync::OnceLock::new(); - let only = ONLY.get_or_init(|| { - std::env::var("VICTORY_TRANSLATE_ONLY") - .unwrap_or_default() - .split(',') - .map(|h| h.trim().to_lowercase()) - .filter(|h| !h.is_empty()) - .collect() - }); - if !only.is_empty() && !only.iter().any(|o| hash.starts_with(o.as_str())) { - return; - } let example = || format!("{}{} #{hash}", path.display(), source.label()); t.containers += 1; let Ok(container) = Container::parse(&bytes) else { diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 0b8fd9c..01907b2 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -280,7 +280,6 @@ fn unspill( let mut used = [false; 128]; let mut parks: Vec> = Vec::with_capacity(list.len()); let mut written: Vec> = Vec::with_capacity(list.len()); - let mut read: Vec> = Vec::with_capacity(list.len()); for inst in list.iter() { let Some(name) = inst.name() else { return Vec::new() }; let fields = inst.fields(wave64); @@ -289,28 +288,13 @@ fn unspill( return Vec::new(); }; let mut codes = Vec::new(); - let mut from = Vec::new(); if let Some((reads, writes)) = effects { for ® in &writes { if let Reg::S(c) = reg { codes.push(c); } } - for ® in &reads { - if let Reg::S(c) = reg { - from.push(c); - } - } - // An M0-relative read (`v_movrels_b32`) names every VGPR from its - // base up; the compiler indexes a small array with it, never the - // lanes it parks scalars in, so it does not make those VGPRs - // ordinary ones. (Relative writes still do.) - let relative = name == "v_movrels_b32"; - let n_reads = reads.len(); - for (k, reg) in reads.into_iter().chain(writes).enumerate() { - if relative && k < n_reads && matches!(reg, Reg::V(_)) { - continue; - } + for reg in reads.into_iter().chain(writes) { match reg { Reg::S(c) => used[usize::from(c)] = true, Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true, @@ -321,7 +305,6 @@ fn unspill( } parks.push(park); written.push(codes); - read.push(from); } for (i, park) in parks.iter_mut().enumerate() { if park.is_some_and(|p| other[usize::from(p.1)]) { @@ -364,25 +347,8 @@ fn unspill( } None } else { - // The second restore may come a few instructions later (the - // compiler schedules other work between the two): the pair is - // restored at the first, so nothing between may read or write - // the second register, write the first, or save into the lanes. - let mut j = i + 1; - while j < list.len() && !leader(j) { - if parks[j] == Some((false, reg, code + 1, lane + 1)) { - return Some(j); - } - if parks[j].is_some_and(|p| p.0 && p.1 == reg && (p.3 == lane || p.3 == lane + 1)) - || written[j].contains(&code) - || written[j].contains(&(code + 1)) - || read[j].contains(&(code + 1)) - { - return None; - } - j += 1; - } - None + let j = i + 1; + (j < list.len() && !leader(j) && parks[j] == Some((false, reg, code + 1, lane + 1))).then_some(j) } }; let mut pairs: Vec<(u8, u32)> = Vec::new(); From 2119b0e44c53aa9648307b0c5c73590290305b1f Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:00:18 -0500 Subject: [PATCH 142/445] Put the parked lane-mask change (#11) back The previous commit took it out; that was not wanted. The tree is again as it was before that commit. Co-Authored-By: Claude Fable 5.2 --- apps/victory/src/translate.rs | 19 ++++++++++++++++ crates/victory-shader/src/ir.rs | 40 ++++++++++++++++++++++++++++++--- 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index dc5d6c8..1d13ae2 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -160,6 +160,11 @@ pub fn run( jobs: Option, ) -> Result<()> { let paths = crate::default_paths(paths)?; + // `VICTORY_HOST_MAX_WAVE=32`: translate as for a host whose waves have + // at most 32 lanes (as the runtime does on such a card). + if let Some(n) = std::env::var("VICTORY_HOST_MAX_WAVE").ok().and_then(|v| v.parse().ok()) { + victory_shader::emit::set_host_max_wave(n); + } let dll = validate.then(Validator::default_path).flatten(); if validate { Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?; @@ -315,6 +320,20 @@ fn translate( // The hash a run's log names the shader by (`hash=` in "first bind", // "shader does not translate", "host pipeline refused"). let hash = blake3::hash(&bytes).to_hex()[..16].to_owned(); + // Diagnostics: `VICTORY_TRANSLATE_ONLY=,...` translates + // those containers alone. + static ONLY: std::sync::OnceLock> = std::sync::OnceLock::new(); + let only = ONLY.get_or_init(|| { + std::env::var("VICTORY_TRANSLATE_ONLY") + .unwrap_or_default() + .split(',') + .map(|h| h.trim().to_lowercase()) + .filter(|h| !h.is_empty()) + .collect() + }); + if !only.is_empty() && !only.iter().any(|o| hash.starts_with(o.as_str())) { + return; + } let example = || format!("{}{} #{hash}", path.display(), source.label()); t.containers += 1; let Ok(container) = Container::parse(&bytes) else { diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 01907b2..0b8fd9c 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -280,6 +280,7 @@ fn unspill( let mut used = [false; 128]; let mut parks: Vec> = Vec::with_capacity(list.len()); let mut written: Vec> = Vec::with_capacity(list.len()); + let mut read: Vec> = Vec::with_capacity(list.len()); for inst in list.iter() { let Some(name) = inst.name() else { return Vec::new() }; let fields = inst.fields(wave64); @@ -288,13 +289,28 @@ fn unspill( return Vec::new(); }; let mut codes = Vec::new(); + let mut from = Vec::new(); if let Some((reads, writes)) = effects { for ® in &writes { if let Reg::S(c) = reg { codes.push(c); } } - for reg in reads.into_iter().chain(writes) { + for ® in &reads { + if let Reg::S(c) = reg { + from.push(c); + } + } + // An M0-relative read (`v_movrels_b32`) names every VGPR from its + // base up; the compiler indexes a small array with it, never the + // lanes it parks scalars in, so it does not make those VGPRs + // ordinary ones. (Relative writes still do.) + let relative = name == "v_movrels_b32"; + let n_reads = reads.len(); + for (k, reg) in reads.into_iter().chain(writes).enumerate() { + if relative && k < n_reads && matches!(reg, Reg::V(_)) { + continue; + } match reg { Reg::S(c) => used[usize::from(c)] = true, Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true, @@ -305,6 +321,7 @@ fn unspill( } parks.push(park); written.push(codes); + read.push(from); } for (i, park) in parks.iter_mut().enumerate() { if park.is_some_and(|p| other[usize::from(p.1)]) { @@ -347,8 +364,25 @@ fn unspill( } None } else { - let j = i + 1; - (j < list.len() && !leader(j) && parks[j] == Some((false, reg, code + 1, lane + 1))).then_some(j) + // The second restore may come a few instructions later (the + // compiler schedules other work between the two): the pair is + // restored at the first, so nothing between may read or write + // the second register, write the first, or save into the lanes. + let mut j = i + 1; + while j < list.len() && !leader(j) { + if parks[j] == Some((false, reg, code + 1, lane + 1)) { + return Some(j); + } + if parks[j].is_some_and(|p| p.0 && p.1 == reg && (p.3 == lane || p.3 == lane + 1)) + || written[j].contains(&code) + || written[j].contains(&(code + 1)) + || read[j].contains(&(code + 1)) + { + return None; + } + j += 1; + } + None } }; let mut pairs: Vec<(u8, u32)> = Vec::new(); From cc11cccc57eb510395bb03158cd497331e7eae16 Mon Sep 17 00:00:00 2001 From: Vyacheslav Venglovsky Date: Tue, 24 Nov 2026 23:33:42 +0100 Subject: [PATCH 143/445] GPU: the indirect scratch buffer stays readable between executions Every indirect execution was followed by a move of the list's clamped arguments back to the common state, and the next clamp moved them from common to unordered access. Drivers may treat a barrier into or out of the common state as a full wait, so even the window path (VICTORY_INDIRECT_WINDOW=1), whose draws skip the clamp, still recorded one barrier between every two draws. The list now remembers that its scratch buffer was left readable as indirect arguments: executions read it with no barrier of their own, the next clamp moves it straight back to unordered access, and it returns to common once, when the list closes or a bigger buffer replaces it. The waits for earlier shader writes around the clamp are unchanged. Tests: two windows of executions with no barrier between them, on WARP and through a host list; the tracked state across clamps, growth and reset; the existing clamp tests follow the new states. With VICTORY_D3D12_DEBUG=1 in a diagnostics build, the host-list tests also check that the debug layer reports nothing. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 9 +- crates/victory-gpu/src/host.rs | 55 +++++ crates/victory-gpu/src/indirect.rs | 348 +++++++++++++++++++++++------ 3 files changed, 336 insertions(+), 76 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index aebefde..a09e09c 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -117,7 +117,9 @@ const WINDOW_MOST: u64 = 64; /// apart after it (16, then twice as many each time, [`WINDOW_MOST`] at /// most, never past the buffer) into /// the list's scratch buffer in one pass, and the draws that follow read -/// their record there with no pass of ours, until one of these: a compute +/// their record there with no pass of ours and no barrier (the scratch +/// buffer stays readable as arguments until the next clamp), until one of +/// these: a compute /// dispatch, a direct draw, an indirect call with a count buffer or more /// than one record, a draw whose shaders can store to buffers, a record /// outside the window, another host list. @@ -2435,7 +2437,6 @@ impl State { _ => false, }; if !ran { - crate::indirect::done(list, &bounded); why("prepare failed"); return false; } @@ -2461,7 +2462,9 @@ impl State { if kind == MESH { self.mesh_scissor(list, false); } - crate::indirect::done(list, &bounded); + // The scratch buffer stays readable as arguments: the next draw of + // the window reads it with no barrier, and the next clamp moves it + // back (`crate::indirect`). if kind == DISPATCH { DISPATCHED.fetch_add(1, Ordering::Relaxed); } else { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index cb57a59..f85a50c 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1600,6 +1600,11 @@ struct Deferred { backs: Vec<(ID3D12Resource, usize, [usize; 3])>, /// Whether a step zeroes the indirect-work budget. budget_zeroed: bool, + /// The indirect scratch buffer (`HostList::indirect_args`, by its + /// interface pointer) that a clamp in this recording left readable as + /// indirect arguments; 0 if none. It stays readable until the next + /// clamp into it ([`HostList::indirect_state`]). + indirect_readable: usize, } impl Deferred { @@ -4406,6 +4411,10 @@ impl HostList { pub(crate) fn close(&self) { self.twins_to_depth(); + let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some((scratch, _)) = scratch { + self.indirect_common(&scratch); + } #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); @@ -5033,11 +5042,57 @@ impl HostList { let old = slot.replace((buffer.clone(), alloc)); drop(slot); if let Some((old_buf, _)) = old { + // It ends the list common, as every scratch buffer does. + self.indirect_common(&old_buf); self.keep(&old_buf); } Some(buffer) } + /// Moves `scratch` back to the common state if a clamp left it readable + /// as indirect arguments ([`HostList::indirect_readable`]): where the + /// list's first clamp expects it. Done before the list closes and before + /// a bigger scratch buffer replaces it: one barrier per list (where + /// there was one per indirect execution), and the list ends as it + /// begins however it is submitted. + fn indirect_common(&self, scratch: &ID3D12Resource) { + { + let mut deferred = self.deferred(); + if deferred.indirect_readable != scratch.as_raw() as usize { + return; + } + deferred.indirect_readable = 0; + } + let barrier = transition( + scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COMMON, + ); + // SAFETY: an open list and a live buffer this recording left in + // `INDIRECT_ARGUMENT`. + unsafe { self.list.ResourceBarrier(&[barrier]) }; + } + + /// The state the list's indirect scratch buffer `scratch` is in at this + /// point of the recording: indirect arguments if a clamp in this + /// recording left it so ([`HostList::indirect_readable`]), otherwise + /// common: the state a buffer is made in, and the one a recording + /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]). + pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES { + if self.deferred().indirect_readable == scratch.as_raw() as usize { + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT + } else { + D3D12_RESOURCE_STATE_COMMON + } + } + + /// A clamp recorded in this list left `scratch` readable as indirect + /// arguments. It stays so for every execution that reads it, until the + /// next clamp moves it back to unordered access. + pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) { + self.deferred().indirect_readable = scratch.as_raw() as usize; + } + /// Keeps `object` alive until the list is reset. pub(crate) fn keep(&self, object: &impl Interface) { if let Ok(object) = object.cast::() { diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index bff1577..e93b15b 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -8,6 +8,15 @@ //! shader with its root signature inside), leaving the title's argument and //! count buffers untouched. //! +//! The scratch buffer is left readable as indirect arguments after a clamp +//! and stays so until the next clamp into it, which moves it straight back +//! to unordered access; it goes back to the common state once, when the +//! list closes. The executions that read it record no barrier of their +//! own, so draws that read records clamped together (`crate::draw`'s +//! windows) follow each other with nothing between them. Before, each +//! execution was followed by a move of the scratch buffer back to the +//! common state, which drivers may treat as a full wait. +//! //! When a count buffer is given, threads at or past `min(max, count)` return //! immediately without charging the list's budget or reading uninitialized //! tail slots. Each list has a budget (2^27 vertex instances or threads, @@ -241,9 +250,11 @@ fn validate_layout( /// Records, in `list`, the non-destructive clamp of up to `records` records of /// `kind` (PC argument numbering) `stride` bytes apart from `src` (and bounded /// by the 32-bit count in `count` when given) into a device-local scratch -/// buffer, leaving that scratch buffer in `INDIRECT_ARGUMENT` at offset `0`. -/// Replaces the list's compute root signature and pipeline (callers bind -/// theirs after). `None` if the clamp or alignment is not available. +/// buffer, at offset `0`. The scratch buffer is left in `INDIRECT_ARGUMENT` +/// until the next clamp into it: executions read it with no barrier of +/// their own. Replaces the list's compute root signature and pipeline +/// (callers bind theirs after). `None` if the clamp or alignment is not +/// available. pub(crate) fn bound( list: &HostList, src: (&ID3D12Resource, u64), @@ -252,7 +263,7 @@ pub(crate) fn bound( ) -> Option { let bytes = validate_layout(spec, src.1, count.map(|(_, off)| off))?; let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?); - record_clamp(c, &list.list, &dst, budget, src, count, spec).then_some(dst) + clamp_into(list, c, &dst, budget, src, count, spec, false).then_some(dst) } /// [`bound`] for a window of records clamped ahead of the draws that will @@ -272,28 +283,41 @@ pub(crate) fn bound_ahead( ) -> Option { let bytes = validate_layout(spec, src.1, None)?; let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?); - record_clamp_as(c, &list.list, &dst, budget, src, None, spec, true).then_some(dst) + clamp_into(list, c, &dst, budget, src, None, spec, true).then_some(dst) } -fn record_clamp( +/// [`record_clamp_as`] into `list`'s scratch buffer `dst`, from the state +/// the list left it in; afterwards the list knows it is readable as +/// indirect arguments. +#[allow(clippy::too_many_arguments)] +fn clamp_into( + list: &HostList, c: &Clamp, - l: &ID3D12GraphicsCommandList, dst: &ID3D12Resource, budget: u64, src: (&ID3D12Resource, u64), count: Option<(&ID3D12Resource, u64)>, spec: (u32, u32, u32), + ahead: bool, ) -> bool { - record_clamp_as(c, l, dst, budget, src, count, spec, false) + let before = list.indirect_state(dst); + let recorded = record_clamp_as(c, &list.list, (dst, before), budget, src, count, spec, ahead); + if recorded { + list.indirect_readable(dst); + } + recorded } -/// [`record_clamp`]; `ahead`: the records are a window clamped ahead of -/// their draws ([`bound_ahead`]). +/// Records the clamp into `dst`, which is in state `before` (common, or +/// indirect arguments after an earlier clamp into it), and leaves `dst` in +/// `INDIRECT_ARGUMENT`. `ahead`: the records are a window clamped ahead of +/// their draws ([`bound_ahead`]). False, with nothing recorded, if the +/// layout or the addresses do not fit the clamp. #[allow(clippy::too_many_arguments)] fn record_clamp_as( c: &Clamp, l: &ID3D12GraphicsCommandList, - dst: &ID3D12Resource, + (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES), budget: u64, (src, src_offset): (&ID3D12Resource, u64), count: Option<(&ID3D12Resource, u64)>, @@ -347,7 +371,9 @@ fn record_clamp_as( // SAFETY: an open list; our root signature and pipeline; live source, // count, scratch destination, and budget buffers. `src` and `count` stay // in `COMMON` / `GENERIC_READ` via implicit buffer promotion while `dst` - // transitions `COMMON -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT`. + // transitions `before -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT`. Moving + // it out of `INDIRECT_ARGUMENT` orders this clamp's writes after every + // earlier execution's reads of the scratch buffer; nothing else writes it. // Diagnostics: counted; `VICTORY_BARRIER_TEST=indirect` leaves the two // waits for every earlier shader write out (the state changes stay). #[cfg(feature = "diagnostics")] @@ -358,11 +384,7 @@ fn record_clamp_as( let waits = true; let first = [ uav_barrier(), - transition( - dst, - D3D12_RESOURCE_STATE_COMMON, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - ), + transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), ]; let second = [ uav_barrier(), @@ -391,23 +413,6 @@ fn record_clamp_as( true } -/// After indirect execution (or if preparation failed after [`bound`]): -/// returns the scratch buffer to the common state for the next call. -pub(crate) fn done(list: &HostList, scratch: &ID3D12Resource) { - done_on(&list.list, scratch); -} - -fn done_on(list: &ID3D12GraphicsCommandList, scratch: &ID3D12Resource) { - // SAFETY: an open list and a live scratch buffer in INDIRECT_ARGUMENT. - unsafe { - list.ResourceBarrier(&[transition( - scratch, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_COMMON, - )]) - }; -} - fn uav_barrier() -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, @@ -833,14 +838,15 @@ void main() { // Record Call #1 (`eff_count = 3` out of `MAX = 4096`), copy the first // 5 records of `dst_buf` out for inspection, then record Call #2 // (`eff_count = 2` out of `MAX = 4096`) reusing `dst_buf` in the same list! - assert!(record_clamp( + assert!(record_clamp_as( &warp.clamp, &warp.list, - &dst_buf, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), budget_gpu, (&src_buf, ARGS_OFFSET as u64), Some((&count_buf, COUNT_OFFSET_1 as u64)), (KIND_DISPATCH, STRIDE, MAX), + false, )); // SAFETY: open command list, valid worker PSO/root and buffers. unsafe { @@ -856,15 +862,14 @@ void main() { COUNT_OFFSET_1 as u64, ); } - done_on(&warp.list, &dst_buf); - // Snapshot `dst_buf` after Call #1 (from `COMMON`, copy 5 * STRIDE bytes, - // then return `dst_buf` to `COMMON` before Call #2). - // SAFETY: open command list; `dst_buf` returned to `COMMON` by `done_on`. + // Snapshot `dst_buf` after Call #1 (copy 5 * STRIDE bytes, then leave + // `dst_buf` readable as arguments again, as the clamp left it). + // SAFETY: open command list; the clamp left `dst_buf` in `INDIRECT_ARGUMENT`. unsafe { warp.list.ResourceBarrier(&[transition( &dst_buf, - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE, )]); warp.list @@ -872,20 +877,23 @@ void main() { warp.list.ResourceBarrier(&[transition( &dst_buf, D3D12_RESOURCE_STATE_COPY_SOURCE, - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, )]); } // Call #2 in the SAME command list (`eff_count = 2` -> records 0 and 1: // 6 + 5 = 11 groups). Would run empty if Call #1's tail blew `BUDGET`! - assert!(record_clamp( + // The scratch buffer goes straight from arguments back to unordered + // access. + assert!(record_clamp_as( &warp.clamp, &warp.list, - &dst_buf, + (&dst_buf, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), budget_gpu, (&src_buf, ARGS_OFFSET as u64), Some((&count_buf, COUNT_OFFSET_2 as u64)), (KIND_DISPATCH, STRIDE, MAX), + false, )); // SAFETY: open command list, valid worker PSO/root and buffers. unsafe { @@ -901,7 +909,6 @@ void main() { COUNT_OFFSET_2 as u64, ); } - done_on(&warp.list, &dst_buf); warp.submit_and_wait(); @@ -998,27 +1005,22 @@ void main() { assert!(record_clamp_as( &warp.clamp, &warp.list, - &dst_buf, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), budget_gpu, (&src_buf, 0), None, (KIND_MESH, STRIDE, RECORDS), ahead, )); - done_on(&warp.list, &dst_buf); - // SAFETY: an open list; the scratch buffer is copied for the check. + // SAFETY: an open list; the scratch buffer, which the clamp left + // readable as arguments, is copied for the check. unsafe { warp.list.ResourceBarrier(&[transition( &dst_buf, - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE, )]); warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64); - warp.list.ResourceBarrier(&[transition( - &dst_buf, - D3D12_RESOURCE_STATE_COPY_SOURCE, - D3D12_RESOURCE_STATE_COMMON, - )]); } warp.submit_and_wait(); // SAFETY: the work is done; mapped buffers. @@ -1088,31 +1090,27 @@ void main() { std::ptr::write_bytes(readback_ptr, 0, total_bytes); } - assert!(record_clamp( + assert!(record_clamp_as( &warp.clamp, &warp.list, - &dst_buf, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), budget_gpu, (&src_buf, 0), None, (KIND_INDEXED, STRIDE, RECORDS), + false, )); - done_on(&warp.list, &dst_buf); - // SAFETY: open command list; copy clamped scratch buffer for verification. + // SAFETY: open command list; copy clamped scratch buffer (left + // readable as arguments) for verification. unsafe { warp.list.ResourceBarrier(&[transition( &dst_buf, - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE, )]); warp.list .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total_bytes as u64); - warp.list.ResourceBarrier(&[transition( - &dst_buf, - D3D12_RESOURCE_STATE_COPY_SOURCE, - D3D12_RESOURCE_STATE_COMMON, - )]); } warp.submit_and_wait(); @@ -1152,13 +1150,16 @@ void main() { assert_eq!((kept, zeroed), (2, (RECORDS as usize) - 2)); } - /// Exercises `HostList::indirect_scratch`, `bound`, `done`, `Host::execute`, - /// and `HostList::reset` end-to-end on the host device. + /// Exercises `HostList::indirect_scratch`, `bound`, the scratch buffer's + /// tracked state, `Host::execute`, and `HostList::reset` end-to-end on + /// the host device. #[test] fn host_list_reuses_and_grows_scratch_across_submissions() { let Some(host) = super::host() else { return; }; + // What earlier tests left in the debug layer's queue, if it is on. + let _ = host.log_messages(); let Ok(list) = host.new_list() else { return; }; @@ -1174,43 +1175,244 @@ void main() { (count_ptr as *mut u32).write_volatile(2); } + let args = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; // First two calls fit inside the initial 64 KiB scratch buffer and - // must reuse the exact same `ID3D12Resource`. + // must reuse the exact same `ID3D12Resource`, which stays readable + // as arguments between them. let b1 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (0, 16, 64)).unwrap(); - done(&list, &b1); + assert_eq!( + list.indirect_state(&b1), + args, + "a clamp leaves the scratch readable as arguments" + ); let b2 = bound(&list, (&src_buf, 64), Some((&count_buf, 0)), (1, 20, 128)).unwrap(); - done(&list, &b2); assert_eq!( b1.as_raw(), b2.as_raw(), "scratch buffer within capacity must be reused" ); + assert_eq!(list.indirect_state(&b2), args); // A call needing >64 KiB grows the scratch buffer mid-list while keeping - // `b1` alive until reset. + // `b1` alive until reset. The new buffer starts out common. + let grown = list.indirect_scratch(5000 * 20).unwrap(); + assert_eq!( + list.indirect_state(&grown), + D3D12_RESOURCE_STATE_COMMON, + "a new scratch buffer is common" + ); let b3 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 5000)).unwrap(); - done(&list, &b3); + assert_eq!(b3.as_raw(), grown.as_raw()); assert_ne!( b3.as_raw(), b1.as_raw(), "larger request must grow scratch buffer" ); + assert_eq!(list.indirect_state(&b3), args); + assert_eq!( + list.indirect_state(&b1), + D3D12_RESOURCE_STATE_COMMON, + "the replaced buffer went back to common" + ); list.close(); host.execute(&[&list]); list.reset(); // After reset, requests up to the grown high-water mark reuse `b3` with - // zero new allocations. + // zero new allocations; the buffer decayed to common when the + // submission ran. + assert_eq!( + list.indirect_state(&b3), + D3D12_RESOURCE_STATE_COMMON, + "a reset list starts with a common scratch buffer" + ); let b4 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 4096)).unwrap(); - done(&list, &b4); assert_eq!( b4.as_raw(), b3.as_raw(), "grown scratch buffer must persist across reset" ); + assert_eq!(list.indirect_state(&b4), args); list.close(); host.execute(&[&list]); list.reset(); + // With the debug layer on (`VICTORY_D3D12_DEBUG=1`, diagnostics): + // every barrier named the state the buffer was really in. + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + } + + /// Records the dispatch records `groups` (three words each, `step` + /// bytes apart, the rest of each record ones) into a fresh mapped + /// buffer of `warp`'s device. + fn dispatch_records(warp: &WarpHarness, groups: &[u32], step: u32) -> ID3D12Resource { + let total = groups.len() * step as usize; + let (buffer, ptr, _) = warp.shared_buffer(total as u64); + let mut bytes = vec![0xffu8; total]; + for (i, &g) in groups.iter().enumerate() { + for (w, word) in [g, 1, 1].into_iter().enumerate() { + let at = i * step as usize + w * 4; + bytes[at..at + 4].copy_from_slice(&word.to_le_bytes()); + } + } + // SAFETY: the mapping holds `total` bytes. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) }; + buffer + } + + /// Two windows in one list, as `crate::draw` records them: each clamps + /// its records ahead, then one execution per record reads the scratch + /// buffer with no barrier between them; the second clamp moves the + /// scratch buffer straight from arguments back to unordered access. + /// Every record runs once, with the group count it asked for. + #[test] + fn warp_window_executions_read_their_records_with_no_barrier_between() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_DISPATCH: u32 = 2; + // The title names 12 bytes and keeps its records 32 apart. + const STRIDE: u32 = 12; + const STEP: u32 = 32; + let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]]; + let sources: Vec = + windows.iter().map(|g| dispatch_records(&warp, g, STEP)).collect(); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256); + let dst_buf = warp.default_uav(u64::from(STEP) * 4); + let sig = warp.signature(KIND_DISPATCH, STRIDE); + // SAFETY: mapped buffers of these sizes. + unsafe { + std::ptr::write_bytes(budget_ptr, 0, 256); + std::ptr::write_bytes(hits_ptr, 0, 256); + } + let mut state = D3D12_RESOURCE_STATE_COMMON; + for (groups, src) in windows.iter().zip(&sources) { + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, state), + budget_gpu, + (src, 0), + None, + (KIND_DISPATCH, STEP, groups.len() as u32), + true, + )); + state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + // SAFETY: an open list; the worker's root signature and + // pipeline; the scratch buffer is readable as arguments. + unsafe { + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + for i in 0..groups.len() as u64 { + warp.list.ExecuteIndirect(&sig, 1, &dst_buf, i * u64::from(STEP), None, 0); + } + } + } + warp.submit_and_wait(); + // SAFETY: the work is done; mapped buffers. + let (hits, spent) = unsafe { + ( + (hits_ptr as *const u32).read_volatile(), + (budget_ptr as *const u32).read_volatile(), + ) + }; + let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum(); + assert_eq!(hits, expected, "every record of both windows runs once"); + assert_eq!(spent, expected * 64, "and is charged what it asked for"); + } + + /// The windows of `warp_window_executions_read_their_records_with_no_barrier_between` + /// through a host list (`bound_ahead`, the list's tracked scratch state, + /// `Host::execute`), twice: on the first recording the scratch buffer + /// starts common, on the second (after the reset) it starts common + /// again. With the debug layer on (`VICTORY_D3D12_DEBUG=1` in a + /// diagnostics build) no barrier names a state the buffer is not in. + #[test] + fn host_list_window_executions_need_no_barrier_of_their_own() { + let Some(host) = super::host() else { + return; + }; + // What earlier tests left in the debug layer's queue, if it is on. + let _ = host.log_messages(); + let Ok(list) = host.new_list() else { + return; + }; + let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + const KIND_DISPATCH: u32 = 2; + const STRIDE: u32 = 12; + const STEP: u32 = 32; + let signature = { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: STRIDE, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + // SAFETY: a valid single-argument command signature description. + unsafe { + host.device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + } + sig.unwrap() + }; + let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]]; + let mut sources = Vec::new(); + for groups in windows { + let total = groups.len() * STEP as usize; + let Some((buffer, ptr)) = host.shared_buffer(total as u64) else { + return; + }; + let mut bytes = vec![0xffu8; total]; + for (i, &g) in groups.iter().enumerate() { + for (w, word) in [g, 1, 1].into_iter().enumerate() { + let at = i * STEP as usize + w * 4; + bytes[at..at + 4].copy_from_slice(&word.to_le_bytes()); + } + } + // SAFETY: the mapping holds `total` bytes. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) }; + sources.push(buffer); + } + let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else { + return; + }; + let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum(); + // SAFETY: a live buffer. + let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; + for _ in 0..2 { + // SAFETY: the mapping holds 256 bytes; nothing runs. + unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) }; + for (groups, src) in windows.iter().zip(&sources) { + let spec = (KIND_DISPATCH, STEP, groups.len() as u32); + let scratch = bound_ahead(&list, (src, 0), spec).unwrap(); + assert_eq!(list.indirect_state(&scratch), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + // SAFETY: an open list; the worker's root signature and + // pipeline; buffers the test holds until the list has run. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + for i in 0..groups.len() as u64 { + let at = i * u64::from(STEP); + list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0); + } + } + } + list.close(); + host.execute(&[&list]); + list.reset(); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + assert_eq!(hits, expected, "every record of both windows runs once"); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + } } } From a4a745ed3c9d6a02401e1401f74b041ae73cb0b4 Mon Sep 17 00:00:00 2001 From: Vyacheslav Venglovsky Date: Tue, 24 Nov 2026 23:47:12 +0100 Subject: [PATCH 144/445] GPU tests: a benchmark of the indirect scratch buffer's barriers A frame's worth (3,200) of one-record indirect draws of our own, clamped one at a time and in windows of 32, recorded with the old barriers (back to the common state after every execution) and the new ones, timed with GPU timestamps around the list. Ignored by default; any machine with a GPU runs it in seconds, no title files needed: cargo test -p victory-gpu --release --lib indirect::bench -- --ignored --nocapture Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/indirect.rs | 321 +++++++++++++++++++++++++++++ 1 file changed, 321 insertions(+) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index e93b15b..b996212 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -1416,3 +1416,324 @@ void main() { } } } + +/// A frame's worth of one-record indirect draws, recorded with the scratch +/// buffer's old barriers (back to the common state after every execution) +/// and with the new ones (readable until the next clamp), clamped one at a +/// time and in windows, on the host GPU. Ignored by default; run it with +/// `cargo test -p victory-gpu --release --lib indirect::bench -- --ignored --nocapture`. +/// It needs no title files: the draws are tiny triangles of ours. +#[cfg(test)] +mod bench { + use super::*; + use windows::Win32::Foundation::RECT; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIFactory4}; + use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + use windows::core::{Interface, PCSTR}; + + /// Draws a frame (the title's gameplay frames hold about 3,200 indirect + /// executions, #107), records a window holds, and how far apart the + /// records are (the title keeps them 32 bytes apart). + const DRAWS: u32 = 3200; + const WINDOW: u32 = 32; + const STEP: u32 = 32; + const RUNS: usize = 9; + + const SHADERS: &str = r#" +#define RS "RootFlags(0)" +[RootSignature(RS)] +float4 vs(uint v : SV_VertexID, uint i : SV_InstanceID) : SV_Position { + float2 p = float2((v & 1) ? 0.05 : 0.0, (v & 2) ? 0.05 : 0.0) - 0.5; + return float4(p, 0.5, 1); +} +float4 ps() : SV_Target { return float4(1, 0.5, 0.25, 1); } +"#; + + fn compile(entry: &str, target: &str) -> Vec { + let entry = std::ffi::CString::new(entry).unwrap(); + let target = std::ffi::CString::new(target).unwrap(); + let mut code: Option = None; + // SAFETY: the source and names outlive the call. + unsafe { + D3DCompile( + SHADERS.as_ptr().cast(), + SHADERS.len(), + s!("bench"), + None, + None, + PCSTR(entry.as_ptr().cast()), + PCSTR(target.as_ptr().cast()), + 0, + 0, + &mut code, + None, + ) + .unwrap(); + let code = code.unwrap(); + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) + .to_vec() + } + } + + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + enum Barriers { + /// Back to the common state after every execution (as before). + Old, + /// Readable as arguments until the next clamp, common at the end. + New, + } + + #[test] + #[ignore = "benchmark; see the module notes"] + fn bench_indirect_draw_barriers() { + let Some(host) = super::host() else { + eprintln!("no host GPU"); + return; + }; + let device = &host.device; + let clamp = make_for(device).expect("the clamp"); + // SAFETY: plain D3D12 object creation with valid descriptions; the + // objects outlive every list recorded and run below. + unsafe { + let adapter = { + let luid = device.GetAdapterLuid(); + CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| f.EnumAdapterByLuid::(luid)) + .and_then(|a| a.GetDesc1()) + .map(|d| String::from_utf16_lossy(&d.Description).trim_end_matches('\0').to_owned()) + .unwrap_or_else(|_| "an unnamed adapter".to_owned()) + }; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .unwrap(); + let allocator: ID3D12CommandAllocator = + device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .unwrap(); + list.Close().unwrap(); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + let frequency = queue.GetTimestampFrequency().unwrap() as f64; + + // The pipeline: tiny triangles into a small target. + let (vs, ps) = (compile("vs", "vs_5_1"), compile("ps", "ps_5_1")); + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr().cast(), BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len() }, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap(); + let target_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let mut target: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &target_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut target, + ) + .unwrap(); + let target = target.unwrap(); + let rtvs: ID3D12DescriptorHeap = device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 1, + ..Default::default() + }) + .unwrap(); + let rtv = rtvs.GetCPUDescriptorHandleForHeapStart(); + device.CreateRenderTargetView(&target, None, rtv); + + // The title's records: three vertices, one instance, 32 bytes apart. + let (src, src_ptr) = host.shared_buffer(u64::from(DRAWS * STEP)).unwrap(); + for i in 0..DRAWS as usize { + let words = [3u32, 1, 0, 0]; + std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), src_ptr.add(i * STEP as usize), 16); + } + let (budget, budget_ptr) = host.shared_buffer(256).unwrap(); + let budget_gpu = budget.GetGPUVirtualAddress(); + let scratch = host.uav_buffer(u64::from(WINDOW * STEP).max(64 << 10)).unwrap(); + let signature = { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 16, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig).unwrap(); + sig.unwrap() + }; + let stamps: ID3D12QueryHeap = { + let mut heap: Option = None; + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: 2, NodeMask: 0 }, + &mut heap, + ) + .unwrap(); + heap.unwrap() + }; + let mut back: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut back, + ) + .unwrap(); + let back = back.unwrap(); + let mut submitted = 0u64; + + // One frame's lists: GPU ms (timestamps around the list), CPU ms + // recording it, ms from submission to the end of its run. + let mut frame = |barriers: Barriers, window: u32| -> [f64; 3] { + allocator.Reset().unwrap(); + list.Reset(&allocator, None).unwrap(); + let recording = std::time::Instant::now(); + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.RSSetViewports(&[D3D12_VIEWPORT { Width: 256.0, Height: 256.0, MaxDepth: 1.0, ..Default::default() }]); + list.RSSetScissorRects(&[RECT { left: 0, top: 0, right: 256, bottom: 256 }]); + list.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list.SetGraphicsRootSignature(&root); + let mut state = D3D12_RESOURCE_STATE_COMMON; + for first in (0..DRAWS).step_by(window as usize) { + let records = window.min(DRAWS - first); + assert!(record_clamp_as( + &clamp, + &list, + (&scratch, state), + budget_gpu, + (&src, u64::from(first * STEP)), + None, + (0, STEP, records), + window > 1, + )); + state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + list.SetPipelineState(&pso); + for k in 0..records { + list.ExecuteIndirect(&signature, 1, &scratch, u64::from(k * STEP), None, 0); + if barriers == Barriers::Old { + list.ResourceBarrier(&[transition( + &scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COMMON, + )]); + state = D3D12_RESOURCE_STATE_COMMON; + } + } + } + if state != D3D12_RESOURCE_STATE_COMMON { + list.ResourceBarrier(&[transition(&scratch, state, D3D12_RESOURCE_STATE_COMMON)]); + } + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); + list.ResolveQueryData(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &back, 0); + list.Close().unwrap(); + let recorded = recording.elapsed().as_secs_f64() * 1e3; + let running = std::time::Instant::now(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + submitted += 1; + queue.Signal(&fence, submitted).unwrap(); + fence.SetEventOnCompletion(submitted, event).unwrap(); + WaitForSingleObject(event, INFINITE); + let ran = running.elapsed().as_secs_f64() * 1e3; + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data)).unwrap(); + let t = std::slice::from_raw_parts(data.cast::(), 2); + let gpu = t[1].saturating_sub(t[0]) as f64 / frequency * 1e3; + back.Unmap(0, None); + (budget_ptr as *mut u32).write_volatile(0); + [gpu, recorded, ran] + }; + + let cases = [ + ("clamped one at a time", Barriers::Old, 1), + ("clamped one at a time", Barriers::New, 1), + ("windows of 32", Barriers::Old, WINDOW), + ("windows of 32", Barriers::New, WINDOW), + ]; + // Warm up, then the cases in turn, so drift falls on all alike. + for &(_, barriers, window) in &cases { + frame(barriers, window); + } + let mut times: Vec> = vec![Vec::new(); cases.len()]; + for _ in 0..RUNS { + for (i, &(_, barriers, window)) in cases.iter().enumerate() { + times[i].push(frame(barriers, window)); + } + } + let median = |v: &[[f64; 3]], k: usize| { + let mut x: Vec = v.iter().map(|t| t[k]).collect(); + x.sort_by(f64::total_cmp); + x[x.len() / 2] + }; + eprintln!( + "indirect draw barriers on {adapter}: {DRAWS} one-record draws a frame, \ + medians of {RUNS} frames" + ); + for (i, (name, barriers, _)) in cases.iter().enumerate() { + let gpu = median(×[i], 0); + eprintln!( + " {name:<22} {:<3} GPU {gpu:7.2} ms ({:5.2} us a draw), recording {:6.2} ms, \ + submit to done {:7.2} ms", + format!("{barriers:?}").to_lowercase(), + gpu * 1e3 / f64::from(DRAWS), + median(×[i], 1), + median(×[i], 2), + ); + } + for pair in [(0, 1), (2, 3)] { + let (old, new) = (median(×[pair.0], 0), median(×[pair.1], 0)); + eprintln!(" {}: GPU time {:+.1} %", cases[pair.0].0, (new / old - 1.0) * 100.0); + } + } + } +} From 3db5a0e87f2c6345c3e4aae119d6aafc45fd285a Mon Sep 17 00:00:00 2001 From: Vyacheslav Venglovsky Date: Tue, 24 Nov 2026 23:59:58 +0100 Subject: [PATCH 145/445] GPU: the indirect clamp charges the budget once per thread group The clamp charged the list's budget record by record: an atomic read and a compare-and-swap loop per record on one word, every thread of a window racing for it, so a group of n records took n rounds and about n*n/2 atomics. The word is CPU-visible memory (zeroed on the CPU at submission), so on a card of its own each of them crosses the bus. On an RTX 5070 Ti the benchmark's windows of 32 took 46-50 ms for 3,200 draws where draws clamped one at a time took 19 ms (#220). Now the records' costs go to group-shared memory, one thread charges their sum with one compare-and-swap (retried only if another group got there first), simulating the same saturation record by record in lane order, and every thread reads whether its record fitted. The mesh diagnostics (largest group count asked, groups asked in all) are summed in the group and added once. What a record costs and when it runs empty are unchanged; which records of a group fit is now their lane order instead of the order the GPU served the race. Test: a group with 300 left of the budget keeps its first draw (100), empties the second (250, which takes the rest) and the ones after it. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/indirect.rs | 156 +++++++++++++++++++++++++---- 1 file changed, 136 insertions(+), 20 deletions(-) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index b996212..c82f2f2 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -58,31 +58,49 @@ RWByteAddressBuffer budget : register(u1); static const uint BUDGET = 1u << 27; // Groups of one dispatch; more run empty. static const uint GROUPS = 1u << 20; +// Each group charges the budget once: the costs of its records go here, +// one thread charges their sum, saturating as each record would in lane +// order, and every thread then reads whether its own record fitted. The +// budget word is CPU-visible memory (zeroed on the CPU at submission), so +// on a card of its own every atomic on it crosses the bus; a compare and +// swap per record, 64 threads racing for one word, cost a round for each +// record of a window. +groupshared uint costs[64]; +groupshared uint fits[64]; +groupshared uint largest_asked; +groupshared uint all_asked; [RootSignature(RS)] [numthreads(64, 1, 1)] -void main(uint3 id : SV_DispatchThreadID) { +void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { uint eff_count = records; bool ahead = (has_count & 2u) != 0; if ((has_count & 1u) != 0) { eff_count = min(eff_count, count_buf.Load(count_offset)); } - if (id.x >= eff_count) return; + // Threads past the records take part in the group's charge (cost 0) + // and store nothing. + bool active = id.x < eff_count; uint src_at = args_offset + id.x * stride; uint dst_at = id.x * stride; - uint cost; + uint cost = 0; + uint asked = 0; uint2 draw_counts = uint2(0, 0); uint3 groups = uint3(0, 0, 0); - if (kind <= 1) { + if (gi == 0) { + largest_asked = 0; + all_asked = 0; + } + if (active && kind <= 1) { // Draws: vertex or index count, then instances. - uint2 asked = src_args.Load2(src_at); - if (ahead && (asked.x > (1u << 24) || asked.y > (1u << 24))) { - asked = uint2(0, 0); + uint2 want = src_args.Load2(src_at); + if (ahead && (want.x > (1u << 24) || want.y > (1u << 24))) { + want = uint2(0, 0); } - uint count = min(asked.x, 1u << 24); - uint instances = min(asked.y, (1u << 26) / max(count, 1u)); + uint count = min(want.x, 1u << 24); + uint instances = min(want.y, (1u << 26) / max(count, 1u)); cost = count * instances; draw_counts = uint2(count, instances); - } else if (kind == 2) { + } else if (active && kind == 2) { uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u)); // x * y fits 32 bits; the whole count may not. if (g.z != 0 && g.x * g.y > GROUPS / g.z) { @@ -90,7 +108,7 @@ void main(uint3 id : SV_DispatchThreadID) { } cost = g.x * g.y * g.z * 64u; groups = g; - } else { + } else if (active) { // Mesh dispatches: the console's are one-dimensional. uint3 g = src_args.Load3(src_at); // Ahead of its draw, a record over the most a dispatch runs is a @@ -99,29 +117,62 @@ void main(uint3 id : SV_DispatchThreadID) { if (ahead && g.x > 65535u) { g = uint3(0, 0, 0); } - // Diagnostics, in the budget buffer's next words: the largest - // group count a mesh record asked for, and the groups asked in all. - uint was; - budget.InterlockedMax(4, g.x, was); - budget.InterlockedAdd(8, min(g.x, 1u << 24), was); + asked = g.x; g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); cost = g.x * g.y * g.z * 128u; groups = g; } - bool over = false; - if (cost > 0) { + costs[gi] = cost; + GroupMemoryBarrierWithGroupSync(); + if (active && kind > 2) { + // Diagnostics, in the budget buffer's next words (below): the + // largest group count a mesh record asked for, and the groups + // asked in all. + uint was; + InterlockedMax(largest_asked, asked, was); + InterlockedAdd(all_asked, min(asked, 1u << 24), was); + } + if (gi == 0) { + // What the records charge, from `before` on, in lane order: a + // record that does not fit whole runs empty and takes the rest. uint before; budget.InterlockedOr(0, 0, before); [allow_uav_condition] while (before < BUDGET) { - uint next = (BUDGET - before <= cost) ? BUDGET : (before + cost); + uint next = before; + for (uint j = 0; j < 64; j++) { + uint c = costs[j]; + if (c > 0 && next < BUDGET) { + next = (BUDGET - next <= c) ? BUDGET : (next + c); + } + } + if (next == before) break; uint prev; budget.InterlockedCompareExchange(0, before, next, prev); if (prev == before) break; before = prev; } - over = before >= BUDGET || BUDGET - before < cost; + uint at = before; + for (uint k = 0; k < 64; k++) { + uint c = costs[k]; + uint fit = 1; + if (c > 0) { + fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u; + at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c); + } + fits[k] = fit; + } } + GroupMemoryBarrierWithGroupSync(); + if (gi == 0 && kind > 2) { + uint was; + budget.InterlockedMax(4, largest_asked, was); + budget.InterlockedAdd(8, all_asked, was); + } + if (!active) { + return; + } + bool over = fits[gi] == 0; if (kind <= 1) { if (over) { draw_counts = uint2(0, 0); @@ -1242,6 +1293,71 @@ void main() { assert_eq!(host.log_messages(), None, "the debug layer found an error"); } + /// A group charges its records in lane order: with 300 left of the + /// budget, the first draw (100) fits, the second (250) does not and + /// takes the rest, and the ones after it run empty. (Racing for the + /// word record by record, which of them fitted was up to the GPU.) + #[test] + fn warp_a_group_charges_its_records_in_lane_order() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_DRAW: u32 = 0; + const STRIDE: u32 = 16; + const BUDGET_CAP: u32 = 1 << 27; + let counts = [100u32, 250, 50, 100]; + let total = counts.len() * STRIDE as usize; + let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64); + let dst_buf = warp.default_uav(total as u64); + // SAFETY: mapped buffers of these sizes. + unsafe { + for (i, &count) in counts.iter().enumerate() { + let words = [count, 1, 7, 9]; + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::(), + src_ptr.add(i * STRIDE as usize), + 16, + ); + } + std::ptr::write_bytes(budget_ptr, 0, 256); + (budget_ptr as *mut u32).write_volatile(BUDGET_CAP - 300); + } + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + (&src_buf, 0), + None, + (KIND_DRAW, STRIDE, counts.len() as u32), + false, + )); + // SAFETY: an open list; the clamped records are copied for the check. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64); + } + warp.submit_and_wait(); + // SAFETY: the work is done; mapped buffers. + let (spent, out) = unsafe { + ( + (budget_ptr as *const u32).read_volatile(), + std::slice::from_raw_parts(readback_ptr.cast::().cast_const(), total / 4).to_vec(), + ) + }; + assert_eq!(out[0..4], [100, 1, 7, 9], "the first record fits"); + for i in 1..counts.len() { + assert_eq!(out[i * 4..i * 4 + 4], [0, 0, 7, 9], "record {i} runs empty"); + } + assert_eq!(spent, BUDGET_CAP, "the record that did not fit took the rest"); + } + /// Records the dispatch records `groups` (three words each, `step` /// bytes apart, the rest of each record ones) into a fresh mapped /// buffer of `warp`'s device. From 23daba36501625170703395e18ba7e83c0288ea9 Mon Sep 17 00:00:00 2001 From: Vyacheslav Venglovsky Date: Wed, 25 Nov 2026 00:06:29 +0100 Subject: [PATCH 146/445] GPU: the clamp walks only its group's records; benchmark against main's clamp - The clamp's charge per group walks the group's own records (one, for a record clamped alone) instead of all 64 slots. - The host-list tests read the debug layer's messages after closing the list and before the submission, which moves them to the log (review). - The benchmark lives in its own file and records five cases: what main records, one record at a time and in windows of 32; what this tree records, both ways; and windows with the new barriers but main's clamp, to tell the two changes apart. main's clamp is kept in the benchmark to measure against. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/indirect.rs | 353 ++-------------- crates/victory-gpu/src/indirect/bench.rs | 494 +++++++++++++++++++++++ 2 files changed, 519 insertions(+), 328 deletions(-) create mode 100644 crates/victory-gpu/src/indirect/bench.rs diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index c82f2f2..2a8fb06 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -135,12 +135,15 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { if (gi == 0) { // What the records charge, from `before` on, in lane order: a // record that does not fit whole runs empty and takes the rest. + // Only the group's own records are walked (one, clamped alone). + uint first = id.x; + uint n = eff_count > first ? min(64u, eff_count - first) : 0u; uint before; budget.InterlockedOr(0, 0, before); [allow_uav_condition] while (before < BUDGET) { uint next = before; - for (uint j = 0; j < 64; j++) { + for (uint j = 0; j < n; j++) { uint c = costs[j]; if (c > 0 && next < BUDGET) { next = (BUDGET - next <= c) ? BUDGET : (next + c); @@ -153,7 +156,7 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { before = prev; } uint at = before; - for (uint k = 0; k < 64; k++) { + for (uint k = 0; k < n; k++) { uint c = costs[k]; uint fit = 1; if (c > 0) { @@ -222,13 +225,19 @@ fn make() -> windows::core::Result { } fn make_for(device: &ID3D12Device) -> windows::core::Result { + make_from(device, SOURCE) +} + +/// The clamp compiled from `source` (ours, or in the benchmark the one it +/// replaced). +fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result { let mut code: Option = None; let mut errors: Option = None; // SAFETY: the source and names live through the call; out pointers ours. let compiled = unsafe { D3DCompile( - SOURCE.as_ptr().cast(), - SOURCE.len(), + source.as_ptr().cast(), + source.len(), s!("clamp"), None, None, @@ -1267,6 +1276,10 @@ void main() { ); list.close(); + // With the debug layer on (`VICTORY_D3D12_DEBUG=1`, diagnostics): + // every barrier recorded named the state the buffer was in. Read + // before the submission, which moves the messages to the log. + assert_eq!(host.log_messages(), None, "the debug layer found an error"); host.execute(&[&list]); list.reset(); @@ -1286,11 +1299,9 @@ void main() { ); assert_eq!(list.indirect_state(&b4), args); list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); host.execute(&[&list]); list.reset(); - // With the debug layer on (`VICTORY_D3D12_DEBUG=1`, diagnostics): - // every barrier named the state the buffer was really in. - assert_eq!(host.log_messages(), None, "the debug layer found an error"); } /// A group charges its records in lane order: with 300 left of the @@ -1348,7 +1359,8 @@ void main() { let (spent, out) = unsafe { ( (budget_ptr as *const u32).read_volatile(), - std::slice::from_raw_parts(readback_ptr.cast::().cast_const(), total / 4).to_vec(), + std::slice::from_raw_parts(readback_ptr.cast::().cast_const(), total / 4) + .to_vec(), ) }; assert_eq!(out[0..4], [100, 1, 7, 9], "the first record fits"); @@ -1523,333 +1535,18 @@ void main() { } } list.close(); + // With the debug layer on: nothing it objects to was recorded. + // Read before the submission, which moves the messages to the log. + assert_eq!(host.log_messages(), None, "the debug layer found an error"); host.execute(&[&list]); list.reset(); // SAFETY: the list has run; a mapped buffer. let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; assert_eq!(hits, expected, "every record of both windows runs once"); - assert_eq!(host.log_messages(), None, "the debug layer found an error"); } } } -/// A frame's worth of one-record indirect draws, recorded with the scratch -/// buffer's old barriers (back to the common state after every execution) -/// and with the new ones (readable until the next clamp), clamped one at a -/// time and in windows, on the host GPU. Ignored by default; run it with -/// `cargo test -p victory-gpu --release --lib indirect::bench -- --ignored --nocapture`. -/// It needs no title files: the draws are tiny triangles of ours. +/// The benchmark of the clamp and its barriers (ignored by default). #[cfg(test)] -mod bench { - use super::*; - use windows::Win32::Foundation::RECT; - use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; - use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIFactory4}; - use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; - use windows::core::{Interface, PCSTR}; - - /// Draws a frame (the title's gameplay frames hold about 3,200 indirect - /// executions, #107), records a window holds, and how far apart the - /// records are (the title keeps them 32 bytes apart). - const DRAWS: u32 = 3200; - const WINDOW: u32 = 32; - const STEP: u32 = 32; - const RUNS: usize = 9; - - const SHADERS: &str = r#" -#define RS "RootFlags(0)" -[RootSignature(RS)] -float4 vs(uint v : SV_VertexID, uint i : SV_InstanceID) : SV_Position { - float2 p = float2((v & 1) ? 0.05 : 0.0, (v & 2) ? 0.05 : 0.0) - 0.5; - return float4(p, 0.5, 1); -} -float4 ps() : SV_Target { return float4(1, 0.5, 0.25, 1); } -"#; - - fn compile(entry: &str, target: &str) -> Vec { - let entry = std::ffi::CString::new(entry).unwrap(); - let target = std::ffi::CString::new(target).unwrap(); - let mut code: Option = None; - // SAFETY: the source and names outlive the call. - unsafe { - D3DCompile( - SHADERS.as_ptr().cast(), - SHADERS.len(), - s!("bench"), - None, - None, - PCSTR(entry.as_ptr().cast()), - PCSTR(target.as_ptr().cast()), - 0, - 0, - &mut code, - None, - ) - .unwrap(); - let code = code.unwrap(); - std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) - .to_vec() - } - } - - #[derive(Clone, Copy, PartialEq, Eq, Debug)] - enum Barriers { - /// Back to the common state after every execution (as before). - Old, - /// Readable as arguments until the next clamp, common at the end. - New, - } - - #[test] - #[ignore = "benchmark; see the module notes"] - fn bench_indirect_draw_barriers() { - let Some(host) = super::host() else { - eprintln!("no host GPU"); - return; - }; - let device = &host.device; - let clamp = make_for(device).expect("the clamp"); - // SAFETY: plain D3D12 object creation with valid descriptions; the - // objects outlive every list recorded and run below. - unsafe { - let adapter = { - let luid = device.GetAdapterLuid(); - CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) - .and_then(|f| f.EnumAdapterByLuid::(luid)) - .and_then(|a| a.GetDesc1()) - .map(|d| String::from_utf16_lossy(&d.Description).trim_end_matches('\0').to_owned()) - .unwrap_or_else(|_| "an unnamed adapter".to_owned()) - }; - let queue: ID3D12CommandQueue = device - .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { - Type: D3D12_COMMAND_LIST_TYPE_DIRECT, - ..Default::default() - }) - .unwrap(); - let allocator: ID3D12CommandAllocator = - device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); - let list: ID3D12GraphicsCommandList = device - .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) - .unwrap(); - list.Close().unwrap(); - let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); - let event = CreateEventW(None, false, false, None).unwrap(); - let frequency = queue.GetTimestampFrequency().unwrap() as f64; - - // The pipeline: tiny triangles into a small target. - let (vs, ps) = (compile("vs", "vs_5_1"), compile("ps", "ps_5_1")); - let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); - let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), - VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr().cast(), BytecodeLength: vs.len() }, - PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len() }, - SampleMask: u32::MAX, - RasterizerState: D3D12_RASTERIZER_DESC { - FillMode: D3D12_FILL_MODE_SOLID, - CullMode: D3D12_CULL_MODE_NONE, - DepthClipEnable: true.into(), - ..Default::default() - }, - PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, - NumRenderTargets: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - ..Default::default() - }; - desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; - desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap(); - let target_desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, - Width: 256, - Height: 256, - DepthOrArraySize: 1, - MipLevels: 1, - Format: DXGI_FORMAT_R8G8B8A8_UNORM, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, - ..Default::default() - }; - let mut target: Option = None; - device - .CreateCommittedResource( - &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, - D3D12_HEAP_FLAG_NONE, - &target_desc, - D3D12_RESOURCE_STATE_RENDER_TARGET, - None, - &mut target, - ) - .unwrap(); - let target = target.unwrap(); - let rtvs: ID3D12DescriptorHeap = device - .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, - NumDescriptors: 1, - ..Default::default() - }) - .unwrap(); - let rtv = rtvs.GetCPUDescriptorHandleForHeapStart(); - device.CreateRenderTargetView(&target, None, rtv); - - // The title's records: three vertices, one instance, 32 bytes apart. - let (src, src_ptr) = host.shared_buffer(u64::from(DRAWS * STEP)).unwrap(); - for i in 0..DRAWS as usize { - let words = [3u32, 1, 0, 0]; - std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), src_ptr.add(i * STEP as usize), 16); - } - let (budget, budget_ptr) = host.shared_buffer(256).unwrap(); - let budget_gpu = budget.GetGPUVirtualAddress(); - let scratch = host.uav_buffer(u64::from(WINDOW * STEP).max(64 << 10)).unwrap(); - let signature = { - let arg = D3D12_INDIRECT_ARGUMENT_DESC { - Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, - ..Default::default() - }; - let desc = D3D12_COMMAND_SIGNATURE_DESC { - ByteStride: 16, - NumArgumentDescs: 1, - pArgumentDescs: &arg, - NodeMask: 0, - }; - let mut sig: Option = None; - device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig).unwrap(); - sig.unwrap() - }; - let stamps: ID3D12QueryHeap = { - let mut heap: Option = None; - device - .CreateQueryHeap( - &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: 2, NodeMask: 0 }, - &mut heap, - ) - .unwrap(); - heap.unwrap() - }; - let mut back: Option = None; - device - .CreateCommittedResource( - &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, - D3D12_HEAP_FLAG_NONE, - &D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: 16, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - ..Default::default() - }, - D3D12_RESOURCE_STATE_COPY_DEST, - None, - &mut back, - ) - .unwrap(); - let back = back.unwrap(); - let mut submitted = 0u64; - - // One frame's lists: GPU ms (timestamps around the list), CPU ms - // recording it, ms from submission to the end of its run. - let mut frame = |barriers: Barriers, window: u32| -> [f64; 3] { - allocator.Reset().unwrap(); - list.Reset(&allocator, None).unwrap(); - let recording = std::time::Instant::now(); - list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); - list.OMSetRenderTargets(1, Some(&rtv), false, None); - list.RSSetViewports(&[D3D12_VIEWPORT { Width: 256.0, Height: 256.0, MaxDepth: 1.0, ..Default::default() }]); - list.RSSetScissorRects(&[RECT { left: 0, top: 0, right: 256, bottom: 256 }]); - list.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - list.SetGraphicsRootSignature(&root); - let mut state = D3D12_RESOURCE_STATE_COMMON; - for first in (0..DRAWS).step_by(window as usize) { - let records = window.min(DRAWS - first); - assert!(record_clamp_as( - &clamp, - &list, - (&scratch, state), - budget_gpu, - (&src, u64::from(first * STEP)), - None, - (0, STEP, records), - window > 1, - )); - state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; - list.SetPipelineState(&pso); - for k in 0..records { - list.ExecuteIndirect(&signature, 1, &scratch, u64::from(k * STEP), None, 0); - if barriers == Barriers::Old { - list.ResourceBarrier(&[transition( - &scratch, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_COMMON, - )]); - state = D3D12_RESOURCE_STATE_COMMON; - } - } - } - if state != D3D12_RESOURCE_STATE_COMMON { - list.ResourceBarrier(&[transition(&scratch, state, D3D12_RESOURCE_STATE_COMMON)]); - } - list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); - list.ResolveQueryData(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &back, 0); - list.Close().unwrap(); - let recorded = recording.elapsed().as_secs_f64() * 1e3; - let running = std::time::Instant::now(); - queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); - submitted += 1; - queue.Signal(&fence, submitted).unwrap(); - fence.SetEventOnCompletion(submitted, event).unwrap(); - WaitForSingleObject(event, INFINITE); - let ran = running.elapsed().as_secs_f64() * 1e3; - let mut data = std::ptr::null_mut(); - back.Map(0, None, Some(&mut data)).unwrap(); - let t = std::slice::from_raw_parts(data.cast::(), 2); - let gpu = t[1].saturating_sub(t[0]) as f64 / frequency * 1e3; - back.Unmap(0, None); - (budget_ptr as *mut u32).write_volatile(0); - [gpu, recorded, ran] - }; - - let cases = [ - ("clamped one at a time", Barriers::Old, 1), - ("clamped one at a time", Barriers::New, 1), - ("windows of 32", Barriers::Old, WINDOW), - ("windows of 32", Barriers::New, WINDOW), - ]; - // Warm up, then the cases in turn, so drift falls on all alike. - for &(_, barriers, window) in &cases { - frame(barriers, window); - } - let mut times: Vec> = vec![Vec::new(); cases.len()]; - for _ in 0..RUNS { - for (i, &(_, barriers, window)) in cases.iter().enumerate() { - times[i].push(frame(barriers, window)); - } - } - let median = |v: &[[f64; 3]], k: usize| { - let mut x: Vec = v.iter().map(|t| t[k]).collect(); - x.sort_by(f64::total_cmp); - x[x.len() / 2] - }; - eprintln!( - "indirect draw barriers on {adapter}: {DRAWS} one-record draws a frame, \ - medians of {RUNS} frames" - ); - for (i, (name, barriers, _)) in cases.iter().enumerate() { - let gpu = median(×[i], 0); - eprintln!( - " {name:<22} {:<3} GPU {gpu:7.2} ms ({:5.2} us a draw), recording {:6.2} ms, \ - submit to done {:7.2} ms", - format!("{barriers:?}").to_lowercase(), - gpu * 1e3 / f64::from(DRAWS), - median(×[i], 1), - median(×[i], 2), - ); - } - for pair in [(0, 1), (2, 3)] { - let (old, new) = (median(×[pair.0], 0), median(×[pair.1], 0)); - eprintln!(" {}: GPU time {:+.1} %", cases[pair.0].0, (new / old - 1.0) * 100.0); - } - } - } -} +mod bench; diff --git a/crates/victory-gpu/src/indirect/bench.rs b/crates/victory-gpu/src/indirect/bench.rs new file mode 100644 index 0000000..6e92ee9 --- /dev/null +++ b/crates/victory-gpu/src/indirect/bench.rs @@ -0,0 +1,494 @@ +//! A frame's worth of one-record indirect draws on the host GPU, clamped one +//! at a time and in windows, recorded as `main` does (the scratch buffer +//! back to the common state after every execution, the clamp charging the +//! budget record by record) and as this tree does (readable until the next +//! clamp, one charge per group). Ignored by default; run it with +//! `cargo test -p victory-gpu --release --lib indirect::bench -- --ignored --nocapture`. +//! It needs no title files: the draws are tiny triangles of ours. + +use super::*; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; +use windows::Win32::Graphics::Dxgi::{ + CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIFactory4, +}; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::core::{Interface, PCSTR}; + +/// Draws a frame (the title's gameplay frames hold about 3,200 indirect +/// executions, #107), records a window holds, and how far apart the +/// records are (the title keeps them 32 bytes apart). +const DRAWS: u32 = 3200; +const WINDOW: u32 = 32; +const STEP: u32 = 32; +const RUNS: usize = 9; + +const SHADERS: &str = r#" +#define RS "RootFlags(0)" +[RootSignature(RS)] +float4 vs(uint v : SV_VertexID, uint i : SV_InstanceID) : SV_Position { +float2 p = float2((v & 1) ? 0.05 : 0.0, (v & 2) ? 0.05 : 0.0) - 0.5; +return float4(p, 0.5, 1); +} +float4 ps() : SV_Target { return float4(1, 0.5, 0.25, 1); } +"#; + +fn compile(entry: &str, target: &str) -> Vec { + let entry = std::ffi::CString::new(entry).unwrap(); + let target = std::ffi::CString::new(target).unwrap(); + let mut code: Option = None; + // SAFETY: the source and names outlive the call. + unsafe { + D3DCompile( + SHADERS.as_ptr().cast(), + SHADERS.len(), + s!("bench"), + None, + None, + PCSTR(entry.as_ptr().cast()), + PCSTR(target.as_ptr().cast()), + 0, + 0, + &mut code, + None, + ) + .unwrap(); + let code = code.unwrap(); + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) + .to_vec() + } +} + +/// The clamp as it was before it charged the budget once per group +/// (record by record, every thread racing for the budget word), kept +/// here to measure against. +const OLD_SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer Record : register(b0) { +uint kind; +uint stride; +uint records; +uint args_offset; +// Bit 0: a count buffer bounds the records. Bit 1: the records are a +// window clamped ahead of their draws: one that asks for more than can +// run is left empty and costs nothing. +uint has_count; +uint count_offset; +}; +ByteAddressBuffer src_args : register(t0); +ByteAddressBuffer count_buf : register(t1); +RWByteAddressBuffer dst_args : register(u0); +// The list's work so far (vertex instances, threads): past the budget, +// records run empty. +RWByteAddressBuffer budget : register(u1); +static const uint BUDGET = 1u << 27; +// Groups of one dispatch; more run empty. +static const uint GROUPS = 1u << 20; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { +uint eff_count = records; +bool ahead = (has_count & 2u) != 0; +if ((has_count & 1u) != 0) { + eff_count = min(eff_count, count_buf.Load(count_offset)); +} +if (id.x >= eff_count) return; +uint src_at = args_offset + id.x * stride; +uint dst_at = id.x * stride; +uint cost; +uint2 draw_counts = uint2(0, 0); +uint3 groups = uint3(0, 0, 0); +if (kind <= 1) { + // Draws: vertex or index count, then instances. + uint2 asked = src_args.Load2(src_at); + if (ahead && (asked.x > (1u << 24) || asked.y > (1u << 24))) { + asked = uint2(0, 0); + } + uint count = min(asked.x, 1u << 24); + uint instances = min(asked.y, (1u << 26) / max(count, 1u)); + cost = count * instances; + draw_counts = uint2(count, instances); +} else if (kind == 2) { + uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u)); + // x * y fits 32 bits; the whole count may not. + if (g.z != 0 && g.x * g.y > GROUPS / g.z) { + g = uint3(0, 0, 0); + } + cost = g.x * g.y * g.z * 64u; + groups = g; +} else { + // Mesh dispatches: the console's are one-dimensional. + uint3 g = src_args.Load3(src_at); + // Ahead of its draw, a record over the most a dispatch runs is a + // slot the title has not filled (the title leaves all + // ones there): empty, and not counted below either. + if (ahead && g.x > 65535u) { + g = uint3(0, 0, 0); + } + // Diagnostics, in the budget buffer's next words: the largest + // group count a mesh record asked for, and the groups asked in all. + uint was; + budget.InterlockedMax(4, g.x, was); + budget.InterlockedAdd(8, min(g.x, 1u << 24), was); + g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); + cost = g.x * g.y * g.z * 128u; + groups = g; +} +bool over = false; +if (cost > 0) { + uint before; + budget.InterlockedOr(0, 0, before); + [allow_uav_condition] + while (before < BUDGET) { + uint next = (BUDGET - before <= cost) ? BUDGET : (before + cost); + uint prev; + budget.InterlockedCompareExchange(0, before, next, prev); + if (prev == before) break; + before = prev; + } + over = before >= BUDGET || BUDGET - before < cost; +} +if (kind <= 1) { + if (over) { + draw_counts = uint2(0, 0); + } + dst_args.Store2(dst_at, draw_counts); + for (uint off = 8; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } +} else { + if (over) { + groups = uint3(0, 0, 0); + } + dst_args.Store3(dst_at, groups); + for (uint off = 12; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } +} +} +"#; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Barriers { + /// Back to the common state after every execution (as before). + Old, + /// Readable as arguments until the next clamp, common at the end. + New, +} + +#[test] +#[ignore = "benchmark; see the module notes"] +fn bench_indirect_draw_barriers() { + let Some(host) = super::host() else { + eprintln!("no host GPU"); + return; + }; + let device = &host.device; + let clamps = [ + make_from(device, OLD_SOURCE).expect("the old clamp"), + make_for(device).expect("the clamp"), + ]; + // SAFETY: plain D3D12 object creation with valid descriptions; the + // objects outlive every list recorded and run below. + unsafe { + let adapter = { + let luid = device.GetAdapterLuid(); + CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| { + f.EnumAdapterByLuid::(luid) + }) + .and_then(|a| a.GetDesc1()) + .map(|d| { + String::from_utf16_lossy(&d.Description) + .trim_end_matches('\0') + .to_owned() + }) + .unwrap_or_else(|_| "an unnamed adapter".to_owned()) + }; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .unwrap(); + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .unwrap(); + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .unwrap(); + list.Close().unwrap(); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + let frequency = queue.GetTimestampFrequency().unwrap() as f64; + + // The pipeline: tiny triangles into a small target. + let (vs, ps) = (compile("vs", "vs_5_1"), compile("ps", "ps_5_1")); + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: D3D12_SHADER_BYTECODE { + pShaderBytecode: vs.as_ptr().cast(), + BytecodeLength: vs.len(), + }, + PS: D3D12_SHADER_BYTECODE { + pShaderBytecode: ps.as_ptr().cast(), + BytecodeLength: ps.len(), + }, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = + D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap(); + let target_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let mut target: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &target_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut target, + ) + .unwrap(); + let target = target.unwrap(); + let rtvs: ID3D12DescriptorHeap = device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 1, + ..Default::default() + }) + .unwrap(); + let rtv = rtvs.GetCPUDescriptorHandleForHeapStart(); + device.CreateRenderTargetView(&target, None, rtv); + + // The title's records: three vertices, one instance, 32 bytes apart. + let (src, src_ptr) = host.shared_buffer(u64::from(DRAWS * STEP)).unwrap(); + for i in 0..DRAWS as usize { + let words = [3u32, 1, 0, 0]; + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::(), + src_ptr.add(i * STEP as usize), + 16, + ); + } + let (budget, budget_ptr) = host.shared_buffer(256).unwrap(); + let budget_gpu = budget.GetGPUVirtualAddress(); + let scratch = host + .uav_buffer(u64::from(WINDOW * STEP).max(64 << 10)) + .unwrap(); + let signature = { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 16, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + sig.unwrap() + }; + let stamps: ID3D12QueryHeap = { + let mut heap: Option = None; + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2, + NodeMask: 0, + }, + &mut heap, + ) + .unwrap(); + heap.unwrap() + }; + let mut back: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut back, + ) + .unwrap(); + let back = back.unwrap(); + let mut submitted = 0u64; + + // One frame's lists: GPU ms (timestamps around the list), CPU ms + // recording it, ms from submission to the end of its run. + let mut frame = |barriers: Barriers, clamp: &Clamp, window: u32| -> [f64; 3] { + allocator.Reset().unwrap(); + list.Reset(&allocator, None).unwrap(); + let recording = std::time::Instant::now(); + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.RSSetViewports(&[D3D12_VIEWPORT { + Width: 256.0, + Height: 256.0, + MaxDepth: 1.0, + ..Default::default() + }]); + list.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: 256, + bottom: 256, + }]); + list.IASetPrimitiveTopology( + windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + ); + list.SetGraphicsRootSignature(&root); + let mut state = D3D12_RESOURCE_STATE_COMMON; + for first in (0..DRAWS).step_by(window as usize) { + let records = window.min(DRAWS - first); + assert!(record_clamp_as( + clamp, + &list, + (&scratch, state), + budget_gpu, + (&src, u64::from(first * STEP)), + None, + (0, STEP, records), + window > 1, + )); + state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + list.SetPipelineState(&pso); + for k in 0..records { + list.ExecuteIndirect(&signature, 1, &scratch, u64::from(k * STEP), None, 0); + if barriers == Barriers::Old { + list.ResourceBarrier(&[transition( + &scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COMMON, + )]); + state = D3D12_RESOURCE_STATE_COMMON; + } + } + } + if state != D3D12_RESOURCE_STATE_COMMON { + list.ResourceBarrier(&[transition(&scratch, state, D3D12_RESOURCE_STATE_COMMON)]); + } + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); + list.ResolveQueryData(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &back, 0); + list.Close().unwrap(); + let recorded = recording.elapsed().as_secs_f64() * 1e3; + let running = std::time::Instant::now(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + submitted += 1; + queue.Signal(&fence, submitted).unwrap(); + fence.SetEventOnCompletion(submitted, event).unwrap(); + WaitForSingleObject(event, INFINITE); + let ran = running.elapsed().as_secs_f64() * 1e3; + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data)).unwrap(); + let t = std::slice::from_raw_parts(data.cast::(), 2); + let gpu = t[1].saturating_sub(t[0]) as f64 / frequency * 1e3; + back.Unmap(0, None); + (budget_ptr as *mut u32).write_volatile(0); + [gpu, recorded, ran] + }; + + // What `main` records, then this branch; the windows a step at a + // time (barriers, then the clamp's one charge per group). + let (old, new) = (&clamps[0], &clamps[1]); + let cases: [(&str, Barriers, &Clamp, u32); 5] = [ + ("one at a time, main", Barriers::Old, old, 1), + ("one at a time, this", Barriers::New, new, 1), + ("windows of 32, main", Barriers::Old, old, WINDOW), + ("windows, new barriers", Barriers::New, old, WINDOW), + ("windows of 32, this", Barriers::New, new, WINDOW), + ]; + // Warm up, then the cases in turn, so drift falls on all alike. + for &(_, barriers, clamp, window) in &cases { + frame(barriers, clamp, window); + } + let mut times: Vec> = vec![Vec::new(); cases.len()]; + for _ in 0..RUNS { + for (i, &(_, barriers, clamp, window)) in cases.iter().enumerate() { + times[i].push(frame(barriers, clamp, window)); + } + } + let median = |v: &[[f64; 3]], k: usize| { + let mut x: Vec = v.iter().map(|t| t[k]).collect(); + x.sort_by(f64::total_cmp); + x[x.len() / 2] + }; + eprintln!( + "indirect draw barriers on {adapter}: {DRAWS} one-record draws a frame, \ + medians of {RUNS} frames" + ); + for (i, (name, ..)) in cases.iter().enumerate() { + let gpu = median(×[i], 0); + eprintln!( + " {name:<22} GPU {gpu:7.2} ms ({:5.2} us a draw), recording {:6.2} ms, \ + submit to done {:7.2} ms", + gpu * 1e3 / f64::from(DRAWS), + median(×[i], 1), + median(×[i], 2), + ); + } + for (from, to) in [(0, 1), (2, 3), (3, 4), (2, 4)] { + let (a, b) = (median(×[from], 0), median(×[to], 0)); + eprintln!( + " {} -> {}: GPU time {:+.1} %", + cases[from].0, + cases[to].0, + (b / a - 1.0) * 100.0 + ); + } + } +} From 32c6229990ec9da83a14fd4d8d1307ebfff8b9df Mon Sep 17 00:00:00 2001 From: Vyacheslav Venglovsky Date: Wed, 25 Nov 2026 00:12:47 +0100 Subject: [PATCH 147/445] GPU tests: the benchmark also runs with the budget in the card's memory Two more cases, one record at a time and windows of 32, with this tree's clamp and the budget words in a device-local buffer instead of CPU-mapped memory: whether the clamp's atomics crossing the bus are what a draw clamped alone still costs on a card. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/indirect/bench.rs | 34 +++++++++++++++--------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/crates/victory-gpu/src/indirect/bench.rs b/crates/victory-gpu/src/indirect/bench.rs index 6e92ee9..0e233db 100644 --- a/crates/victory-gpu/src/indirect/bench.rs +++ b/crates/victory-gpu/src/indirect/bench.rs @@ -305,6 +305,10 @@ fn bench_indirect_draw_barriers() { } let (budget, budget_ptr) = host.shared_buffer(256).unwrap(); let budget_gpu = budget.GetGPUVirtualAddress(); + // The same words in the card's own memory (zeroed when made; the + // runs below charge far less than the budget). + let card_budget = host.uav_buffer(256).unwrap(); + let card_budget_gpu = card_budget.GetGPUVirtualAddress(); let scratch = host .uav_buffer(u64::from(WINDOW * STEP).max(64 << 10)) .unwrap(); @@ -370,7 +374,7 @@ fn bench_indirect_draw_barriers() { // One frame's lists: GPU ms (timestamps around the list), CPU ms // recording it, ms from submission to the end of its run. - let mut frame = |barriers: Barriers, clamp: &Clamp, window: u32| -> [f64; 3] { + let mut frame = |barriers: Barriers, clamp: &Clamp, window: u32, card: bool| -> [f64; 3] { allocator.Reset().unwrap(); list.Reset(&allocator, None).unwrap(); let recording = std::time::Instant::now(); @@ -399,7 +403,7 @@ fn bench_indirect_draw_barriers() { clamp, &list, (&scratch, state), - budget_gpu, + if card { card_budget_gpu } else { budget_gpu }, (&src, u64::from(first * STEP)), None, (0, STEP, records), @@ -445,21 +449,25 @@ fn bench_indirect_draw_barriers() { // What `main` records, then this branch; the windows a step at a // time (barriers, then the clamp's one charge per group). let (old, new) = (&clamps[0], &clamps[1]); - let cases: [(&str, Barriers, &Clamp, u32); 5] = [ - ("one at a time, main", Barriers::Old, old, 1), - ("one at a time, this", Barriers::New, new, 1), - ("windows of 32, main", Barriers::Old, old, WINDOW), - ("windows, new barriers", Barriers::New, old, WINDOW), - ("windows of 32, this", Barriers::New, new, WINDOW), + // The last two keep the budget in the card's memory instead of + // memory the CPU maps (where the list's budget is now). + let cases: [(&str, Barriers, &Clamp, u32, bool); 7] = [ + ("one at a time, main", Barriers::Old, old, 1, false), + ("one at a time, this", Barriers::New, new, 1, false), + ("windows of 32, main", Barriers::Old, old, WINDOW, false), + ("windows, new barriers", Barriers::New, old, WINDOW, false), + ("windows of 32, this", Barriers::New, new, WINDOW, false), + ("one at a time, card", Barriers::New, new, 1, true), + ("windows of 32, card", Barriers::New, new, WINDOW, true), ]; // Warm up, then the cases in turn, so drift falls on all alike. - for &(_, barriers, clamp, window) in &cases { - frame(barriers, clamp, window); + for &(_, barriers, clamp, window, card) in &cases { + frame(barriers, clamp, window, card); } let mut times: Vec> = vec![Vec::new(); cases.len()]; for _ in 0..RUNS { - for (i, &(_, barriers, clamp, window)) in cases.iter().enumerate() { - times[i].push(frame(barriers, clamp, window)); + for (i, &(_, barriers, clamp, window, card)) in cases.iter().enumerate() { + times[i].push(frame(barriers, clamp, window, card)); } } let median = |v: &[[f64; 3]], k: usize| { @@ -481,7 +489,7 @@ fn bench_indirect_draw_barriers() { median(×[i], 2), ); } - for (from, to) in [(0, 1), (2, 3), (3, 4), (2, 4)] { + for (from, to) in [(0, 1), (2, 3), (3, 4), (2, 4), (1, 5), (4, 6)] { let (a, b) = (median(×[from], 0), median(×[to], 0)); eprintln!( " {} -> {}: GPU time {:+.1} %", From d5c15cb9dc49aba2ce98869a37956d1e7454e228 Mon Sep 17 00:00:00 2001 From: Vyacheslav Venglovsky Date: Wed, 25 Nov 2026 00:35:20 +0100 Subject: [PATCH 148/445] GPU: the indirect budget lives in the card's memory The clamp charges the list's budget with atomics: at least an atomic read and a compare-and-swap in a row for every clamp, so for every indirect execution clamped on its own. The budget was in memory the CPU maps (zeroed on the CPU at submission), so on a card of its own each of those crosses the bus. Now the words live in a device-local buffer of the list. The list zeroes it before its first clamp (WriteBufferImmediate, as a copy), the clamps charge it as before, and when the list closes the clamp's notes on mesh records are copied to the mapped words, where the next submission reads them for the frame line as before. VICTORY_INDIRECT_CARD_BUDGET=0 keeps the old place, for an A/B; lists without ID3D12GraphicsCommandList2 keep it too. Test: a recording whose clamps spend the whole budget, then one with a small record after the reset, which runs. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 103 ++++++++++++++++++++++++-- crates/victory-gpu/src/indirect.rs | 112 +++++++++++++++++++++++++++-- 2 files changed, 206 insertions(+), 9 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index f85a50c..1499352 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -735,8 +735,13 @@ pub(crate) struct HostList { /// The pipelines the list binds, for reports of slow submissions. pipelines: Mutex>, /// The work its indirect executions may still do (`indirect`): a - /// shader-writable word, zeroed when the list is submitted. + /// shader-writable word, zeroed when the list is submitted, and after + /// it what the clamp notes about mesh records. In memory the CPU maps. budget: OnceLock>, + /// The same words in the card's own memory ([`card_budget`]), which the + /// clamp uses instead when there is one: zeroed in the list before its + /// first clamp, its notes copied to `budget` when the list closes. + card_budget: OnceLock>, /// Device-local scratch buffer for clamped indirect arguments (`indirect`), /// grown to the largest indirect execution recorded on the list. indirect_args: Mutex>, @@ -1216,6 +1221,16 @@ pub(crate) fn dred_on() -> bool { /// budget buffers, a run late). static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +/// Whether a list's indirect-work budget lives in the card's own memory +/// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as +/// before). The clamp charges it with atomics, at least two in a row for +/// every clamp; in mapped memory on a card of its own each of them +/// crosses the bus. +fn card_budget() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0")) +} + /// Whether each list of a submission runs and is timed on its own, slow /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics /// builds; the commands are noted with `VICTORY_D3D12_DRED` on). @@ -1598,7 +1613,8 @@ struct Deferred { /// memory they go to, the bytes of a row, the rows, the title's row /// pitch. backs: Vec<(ID3D12Resource, usize, [usize; 3])>, - /// Whether a step zeroes the indirect-work budget. + /// Whether the indirect-work budget is zeroed for this recording (a + /// step on the CPU, or in the list for the card's copy). budget_zeroed: bool, /// The indirect scratch buffer (`HostList::indirect_args`, by its /// interface pointer) that a clamp in this recording left readable as @@ -2838,6 +2854,7 @@ impl Host { prelude, pipelines: Mutex::default(), budget: OnceLock::new(), + card_budget: OnceLock::new(), indirect_args: Mutex::default(), _alive: Counted::new(), #[cfg(feature = "diagnostics")] @@ -4415,6 +4432,7 @@ impl HostList { if let Some((scratch, _)) = scratch { self.indirect_common(&scratch); } + self.card_budget_out(); #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); @@ -4998,6 +5016,7 @@ impl HostList { Some((b, d as usize)) }) .as_ref()?; + let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref(); let mut deferred = self.deferred(); if !deferred.budget_zeroed { deferred.budget_zeroed = true; @@ -5005,7 +5024,8 @@ impl HostList { // SAFETY: the list's own mapped words, written before it runs. // The words after the budget hold what the clamp noted about the // list's last run (mesh dispatches: the largest group count - // asked for, the groups asked in all): taken, then zeroed. + // asked for, the groups asked in all; with the card's copy, as + // the list's end copied them here): taken, then zeroed. deferred.copies.push(Step::Host(Box::new(move || unsafe { let words = at as *mut u32; let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile()); @@ -5015,9 +5035,84 @@ impl HostList { words.add(k).write_volatile(0); } }))); + drop(deferred); + if let Some(card) = card { + self.zero_card_budget(card); + } } // SAFETY: a live buffer. - Some(unsafe { buffer.GetGPUVirtualAddress() }) + Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() }) + } + + /// The budget's words in the card's own memory ([`card_budget`]), if + /// the list can zero them itself (`WriteBufferImmediate`). + fn make_card_budget(&self) -> Option { + if !card_budget() { + return None; + } + self.list.cast::().ok()?; + let buffer = host()?.uav_buffer(256)?; + name(&buffer, || "indirect budget".to_owned()); + Some(buffer) + } + + /// Records, before the list's first clamp, the zeroing of the card's + /// copy of the budget: common, written as a copy, then left for + /// unordered access until the list closes ([`HostList::card_budget_out`]). + fn zero_card_budget(&self, card: &ID3D12Resource) { + let Ok(list2) = self.list.cast::() else { + return; + }; + // SAFETY: a live buffer. + let at = unsafe { card.GetGPUVirtualAddress() }; + let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { + Dest: at + offset, + Value: 0, + }); + // SAFETY: an open list; the buffer is the list's own and in the + // common state at the start of every recording. + unsafe { + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); + list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None); + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + } + } + + /// Before the list closes, if this recording charged the card's copy + /// of the budget: its notes on mesh records go to the mapped words + /// (read at the next submission), and it goes back to common. + fn card_budget_out(&self) { + if !self.deferred().budget_zeroed { + return; + } + let (Some(Some(card)), Some(Some((mapped, _)))) = + (self.card_budget.get(), self.budget.get()) + else { + return; + }; + // SAFETY: an open list; both buffers are the list's own. The + // mapped one is promoted from common to the copy destination. + unsafe { + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + self.list.CopyBufferRegion(mapped, 4, card, 4, 8); + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + } } /// A device-local unordered-access buffer of at least `size` bytes for diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 2a8fb06..e89cb70 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -60,11 +60,11 @@ static const uint BUDGET = 1u << 27; static const uint GROUPS = 1u << 20; // Each group charges the budget once: the costs of its records go here, // one thread charges their sum, saturating as each record would in lane -// order, and every thread then reads whether its own record fitted. The -// budget word is CPU-visible memory (zeroed on the CPU at submission), so -// on a card of its own every atomic on it crosses the bus; a compare and -// swap per record, 64 threads racing for one word, cost a round for each -// record of a window. +// order, and every thread then reads whether its own record fitted. A +// compare and swap per record, 64 threads racing for one word, cost a +// round for each record of a window, and in memory the CPU maps (where the +// budget was, and is with VICTORY_INDIRECT_CARD_BUDGET=0) every atomic +// crosses the bus on a card of its own. groupshared uint costs[64]; groupshared uint fits[64]; groupshared uint largest_asked; @@ -1370,6 +1370,108 @@ void main() { assert_eq!(spent, BUDGET_CAP, "the record that did not fit took the rest"); } + /// The list's budget starts empty at each submission, wherever it + /// lives (the card's copy is zeroed in the list): a recording whose + /// clamps spend all of it is followed, after the reset, by one whose + /// small record still runs. + #[test] + fn host_list_budget_starts_empty_at_each_submission() { + let Some(host) = super::host() else { + return; + }; + let Ok(list) = host.new_list() else { + return; + }; + let _ = host.log_messages(); + let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + const KIND_DISPATCH: u32 = 2; + const STRIDE: u32 = 12; + let signature = { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: STRIDE, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + // SAFETY: a valid single-argument command signature description. + unsafe { + host.device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + } + sig.unwrap() + }; + // Three records of 65,535 x 16 groups: about half the budget each. + let Some((big, big_ptr)) = host.shared_buffer(3 * u64::from(STRIDE)) else { + return; + }; + let Some((small, small_ptr)) = host.shared_buffer(u64::from(STRIDE)) else { + return; + }; + let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else { + return; + }; + // SAFETY: mapped buffers of these sizes; nothing runs yet. + unsafe { + for i in 0..3 { + let words = [65535u32, 16, 1]; + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::(), + big_ptr.add(i * STRIDE as usize), + 12, + ); + } + std::ptr::copy_nonoverlapping([1u32, 1, 1].as_ptr().cast::(), small_ptr, 12); + std::ptr::write_bytes(hits_ptr, 0, 256); + } + // SAFETY: a live buffer. + let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; + for round in 0..2 { + // Spends the budget (clamped, not executed), then one group. + bound(&list, (&big, 0), None, (KIND_DISPATCH, STRIDE, 3)).unwrap(); + let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap(); + // SAFETY: an open list; the worker's root signature and + // pipeline; buffers the test holds until the list has run. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0); + } + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + // The small record comes after the big ones spent the budget: + // it runs empty, in every round alike (none carries over). + assert_eq!(hits, 0, "round {round}: the spent budget empties the record after it"); + } + // A recording with only the small record: the budget is empty + // again, so it runs. + let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap(); + // SAFETY: as above. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0); + } + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + assert_eq!(hits, 1, "the budget starts empty at the next submission"); + } + /// Records the dispatch records `groups` (three words each, `step` /// bytes apart, the rest of each record ones) into a fresh mapped /// buffer of `warp`'s device. From 7e239bfb0b6f2ca1416a06b21fe789540709c7eb Mon Sep 17 00:00:00 2001 From: Vyacheslav Venglovsky Date: Wed, 25 Nov 2026 00:54:13 +0100 Subject: [PATCH 149/445] GPU: the indirect clamp's groups past a count touch the budget not at all An execution may ask for thousands of records with a count buffer that counts a few: the clamp runs a group per 64 asked. Before the charge per group, the threads past the count returned at once; with it, the first thread of every group read the budget word, and for mesh records added the group's notes to it, records or none. In memory the CPU maps that is up to three atomics across the bus per empty group (on an RTX 5070 an in-game A/B of 32c6229 ran slower, #220). Now a group without records makes no atomic; the group's barriers stay in uniform control flow. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/indirect.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index e89cb70..fbc9805 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -132,12 +132,15 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { InterlockedMax(largest_asked, asked, was); InterlockedAdd(all_asked, min(asked, 1u << 24), was); } - if (gi == 0) { + // The group's own records: none for a group past a count buffer's + // count (an execution may ask for thousands and count a few), which + // touches the budget not at all, as its threads did not before. + uint first = id.x - gi; + uint n = eff_count > first ? min(64u, eff_count - first) : 0u; + if (gi == 0 && n > 0) { // What the records charge, from `before` on, in lane order: a // record that does not fit whole runs empty and takes the rest. // Only the group's own records are walked (one, clamped alone). - uint first = id.x; - uint n = eff_count > first ? min(64u, eff_count - first) : 0u; uint before; budget.InterlockedOr(0, 0, before); [allow_uav_condition] @@ -167,7 +170,7 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { } } GroupMemoryBarrierWithGroupSync(); - if (gi == 0 && kind > 2) { + if (gi == 0 && kind > 2 && n > 0) { uint was; budget.InterlockedMax(4, largest_asked, was); budget.InterlockedAdd(8, all_asked, was); From 3bff182ef4966ad6986fd8552dc9c7c58268df07 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:00:31 -0500 Subject: [PATCH 150/445] Take the test/fx-prs branch of asdaasdsaddf's fork (as one commit) Double-precision shader instructions (v_cvt_f32_f64, v_add_f64 sums, the makeDouble overload name and flag), a first half of a paired interpolation read as data, sooner eviction of idle textures and caches under memory pressure, a retried DirectStorage destination write, the texture catch-up budget, VICTORY_FIRSTLANE_OWN, and zlib-rs in place of miniz_oxide. Left out: the fork's personal launcher scripts and its readme. Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 29 +- Cargo.toml | 3 +- crates/victory-game/Cargo.toml | 2 +- crates/victory-game/src/sgd5.rs | 92 ++++++- crates/victory-gpu/Cargo.toml | 2 +- crates/victory-gpu/src/capture.rs | 9 +- crates/victory-gpu/src/draw.rs | 20 +- crates/victory-gpu/src/host.rs | 90 +++++++ crates/victory-gpu/src/pipeline/library.rs | 7 +- crates/victory-gpu/src/resource.rs | 4 +- crates/victory-gpu/src/shadow.rs | 7 +- crates/victory-gpu/src/texture.rs | 7 +- crates/victory-hle/Cargo.toml | 2 +- crates/victory-hle/src/modules/dstorage.rs | 141 +++++++++- crates/victory-hle/src/modules/xmem.rs | 6 + crates/victory-shader/Cargo.toml | 2 +- crates/victory-shader/src/emit/bitcode.rs | 5 + crates/victory-shader/src/emit/lower.rs | 265 ++++++++++++++++++- crates/victory-shader/src/emit/shader.rs | 4 + crates/victory-shader/src/emit/valu_tests.rs | 254 ++++++++++++++++++ crates/victory-shader/src/emit/wave.rs | 166 +++++++++++- crates/victory-shader/src/native.rs | 94 ++++++- 22 files changed, 1147 insertions(+), 64 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bab4a7e..29bab8c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,12 +2,6 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - [[package]] name = "aho-corasick" version = "1.1.5" @@ -281,15 +275,6 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" -dependencies = [ - "adler2", -] - [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -681,7 +666,7 @@ name = "victory-game" version = "0.1.0" dependencies = [ "memchr", - "miniz_oxide", + "zlib-rs", ] [[package]] @@ -690,7 +675,6 @@ version = "0.1.0" dependencies = [ "anyhow", "blake3", - "miniz_oxide", "tempfile", "tracing", "victory-formats", @@ -698,13 +682,13 @@ dependencies = [ "victory-shader", "windows", "windows-sys", + "zlib-rs", ] [[package]] name = "victory-hle" version = "0.1.0" dependencies = [ - "miniz_oxide", "opus-pure", "tempfile", "tracing", @@ -715,6 +699,7 @@ dependencies = [ "windows", "windows-core", "windows-sys", + "zlib-rs", ] [[package]] @@ -754,10 +739,10 @@ dependencies = [ name = "victory-shader" version = "0.1.0" dependencies = [ - "miniz_oxide", "thiserror", "windows", "windows-sys", + "zlib-rs", ] [[package]] @@ -912,3 +897,9 @@ dependencies = [ "clap", "walkdir", ] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" diff --git a/Cargo.toml b/Cargo.toml index c3efa8f..4e21b69 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,7 +37,8 @@ windows = "0.62.2" windows-core = "0.62.2" blake3 = "1.8.7" memchr = "2.8.3" -miniz_oxide = "0.9.1" +# SIMD-accelerated pure-Rust zlib/deflate (Zlib license, runtime AVX2/SSE4.2 dispatch). +zlib-rs = { version = "0.6.8", default-features = false, features = ["std"] } walkdir = "2.5.1" tempfile = "3.27.0" # Opus decoding for the console's audio decoder (BSD-3-Clause, pure Rust). diff --git a/crates/victory-game/Cargo.toml b/crates/victory-game/Cargo.toml index 90d931b..92170b4 100644 --- a/crates/victory-game/Cargo.toml +++ b/crates/victory-game/Cargo.toml @@ -9,7 +9,7 @@ publish.workspace = true [dependencies] memchr.workspace = true -miniz_oxide.workspace = true +zlib-rs.workspace = true [lints] workspace = true diff --git a/crates/victory-game/src/sgd5.rs b/crates/victory-game/src/sgd5.rs index 9a2539f..5605b51 100644 --- a/crates/victory-game/src/sgd5.rs +++ b/crates/victory-game/src/sgd5.rs @@ -29,9 +29,53 @@ pub struct Record<'a> { impl Record<'_> { /// The container, or `None` if the stream is corrupt. pub fn unpack(&self) -> Option> { - miniz_oxide::inflate::decompress_to_vec_with_limit(self.packed, self.unpacked_size) - .ok() - .filter(|out| out.len() == self.unpacked_size) + let mut state = zlib_rs::Inflate::new(false, 15); + let mut out = Vec::new(); + let (mut in_pos, mut out_pos) = (0usize, 0usize); + loop { + if out_pos == self.unpacked_size { + let mut extra = [0u8; 1]; + let status = state + .decompress( + &self.packed[in_pos..], + &mut extra, + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + return (status == zlib_rs::Status::StreamEnd + && state.total_out() as usize == self.unpacked_size) + .then_some(out); + } + if out_pos == out.len() { + let next_len = if out.is_empty() { + self.unpacked_size + .min(self.packed.len().saturating_mul(4).max(4096)) + } else { + out.len().saturating_mul(2).min(self.unpacked_size) + }; + out.resize(next_len, 0); + } + let status = state + .decompress( + &self.packed[in_pos..], + &mut out[out_pos..], + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + let next_in = state.total_in() as usize; + let next_out = state.total_out() as usize; + match status { + zlib_rs::Status::StreamEnd => { + out.truncate(next_out); + return (next_out == self.unpacked_size).then_some(out); + } + zlib_rs::Status::Ok if next_in != in_pos || next_out != out_pos => { + in_pos = next_in; + out_pos = next_out; + } + zlib_rs::Status::Ok | zlib_rs::Status::BufError => return None, + } + } } } @@ -83,7 +127,13 @@ mod tests { use super::*; fn record_bytes(name: &str, kind: u8, payload: &[u8]) -> Vec { - let packed = miniz_oxide::deflate::compress_to_vec(payload, 6); + let mut buf = vec![0u8; zlib_rs::compress_bound(payload.len())]; + let config = zlib_rs::DeflateConfig { + window_bits: -15, + ..zlib_rs::DeflateConfig::new(6) + }; + let (packed, rc) = zlib_rs::compress_slice(&mut buf, payload, config); + assert_eq!(rc, zlib_rs::ReturnCode::Ok); let n = (packed.len() + 12) as u32; let mut out = vec![0xF4, 0x01, 0, 0, name.len() as u8 + 1]; out.extend_from_slice(name.as_bytes()); @@ -91,7 +141,7 @@ mod tests { for v in [n, 0x000D_DCE7, n, payload.len() as u32] { out.extend_from_slice(&v.to_le_bytes()); } - out.extend_from_slice(&packed); + out.extend_from_slice(packed); out } @@ -133,4 +183,36 @@ mod tests { let r = records(&file).next().unwrap(); assert_eq!(r.unpack(), None); } + + #[test] + fn handles_empty_and_rejects_mismatched_or_truncated_streams() { + let empty = record_bytes("CS_empty", 0x3c, &[]); + assert_eq!(records(&empty).next().unwrap().unpack(), Some(Vec::new())); + + let payload: Vec = (0..16_384u32) + .map(|i| (i.wrapping_mul(31) ^ (i >> 5)) as u8) + .collect(); + let good = record_bytes("PS_big", 0x32, &payload); + let r = records(&good).next().unwrap(); + assert_eq!(r.unpack(), Some(payload.clone())); + + // Oversized stream (declared unpacked_size smaller than actual output). + let mut smaller = good.clone(); + smaller[r.offset + 8..r.offset + 12] + .copy_from_slice(&((payload.len() - 1) as u32).to_le_bytes()); + assert_eq!(records(&smaller).next().unwrap().unpack(), None); + + // Under-filled stream (declared unpacked_size larger than actual output). + let mut larger = good.clone(); + larger[r.offset + 8..r.offset + 12] + .copy_from_slice(&((payload.len() + 1) as u32).to_le_bytes()); + assert_eq!(records(&larger).next().unwrap().unpack(), None); + + // Truncated raw deflate stream. + let mut truncated = good[..good.len() - 1].to_vec(); + let new_n = (truncated.len() - r.offset) as u32; + truncated[r.offset - 4..r.offset].copy_from_slice(&new_n.to_le_bytes()); + truncated[r.offset + 4..r.offset + 8].copy_from_slice(&new_n.to_le_bytes()); + assert_eq!(records(&truncated).next().unwrap().unpack(), None); + } } diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index a24dd1a..d380f3a 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -9,7 +9,7 @@ publish.workspace = true [dependencies] blake3.workspace = true -miniz_oxide.workspace = true +zlib-rs.workspace = true tracing.workspace = true anyhow.workspace = true victory-formats.workspace = true diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index 97bc116..19947f3 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -184,11 +184,10 @@ fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: header.extend(h.to_be_bytes()); header.extend([8, 2, 0, 0, 0]); // 8-bit RGB chunk(&mut png, b"IHDR", &header); - chunk( - &mut png, - b"IDAT", - &miniz_oxide::deflate::compress_to_vec_zlib(&raw, 3), - ); + let mut compressed = vec![0u8; zlib_rs::compress_bound(raw.len())]; + let (idat, rc) = zlib_rs::compress_slice(&mut compressed, &raw, zlib_rs::DeflateConfig::new(3)); + debug_assert_eq!(rc, zlib_rs::ReturnCode::Ok); + chunk(&mut png, b"IDAT", idat); chunk(&mut png, b"IEND", &[]); let path = folder.join(format!("{name}.png")); match std::fs::write(&path, png) { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index aebefde..0142269 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1446,7 +1446,12 @@ impl State { return; } /// Bytes of texture memory staged per frame. - const PER_FRAME: u64 = 192 << 20; + // `VICTORY_TEXTURE_STAGE_MB` raises it: a backlog of tens of thousands of + // textures (a scene's first minutes) then drains in fewer frames. + static PER_FRAME_MB: std::sync::OnceLock = std::sync::OnceLock::new(); + let per_frame: u64 = *PER_FRAME_MB.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_STAGE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(192) + }) << 20; static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); static SPENT: AtomicU64 = AtomicU64::new(0); let frame = crate::frame::current(); @@ -1499,10 +1504,19 @@ impl State { // records the frame, and making and staging 192 MB of textures took // 1.6-2.2 s of each of the world's first twenty frames (run 20). // The rest waits for the next frames, as it does past the bytes. - const SPAN: std::time::Duration = std::time::Duration::from_millis(250); + static SPAN_MS: std::sync::OnceLock = std::sync::OnceLock::new(); + let span = std::time::Duration::from_millis(*SPAN_MS.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_STAGE_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(250) + })); + // A backlog (a scene's first minutes: 22,000 slots due, 2-3 minutes of black + // surfaces at 192 MB a frame) gets three times the bytes and the time until it + // drains; `VICTORY_TEXTURE_CATCHUP=0` keeps the plain budget. + static CATCHUP: std::sync::OnceLock = std::sync::OnceLock::new(); + let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0")); + let (per_frame, span) = if catchup && due.len() >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) }; let began = std::time::Instant::now(); for (index, write) in due { - if SPENT.load(Ordering::Relaxed) >= PER_FRAME || began.elapsed() > SPAN { + if SPENT.load(Ordering::Relaxed) >= per_frame || began.elapsed() > span { break; } // A placed texture whose memory is not mapped (not streamed in diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index cb57a59..e073616 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -106,6 +106,60 @@ pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool { (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms } +/// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`. +pub(crate) fn available_physical_ram() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + // SAFETY: a sized structure. + let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0; + ok.then_some(m.ullAvailPhys) +} + +/// Effective idle timeout (in milliseconds) for VRAM-backed host textures, +/// scaled down under VRAM pressure. Never returns less than 1,000 ms so +/// handles not yet recorded into a list or slot remain protected. +pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 { + const NORMAL_MS: u64 = 5_000; + const MODERATE_MS: u64 = 2_500; + const HIGH_MS: u64 = 1_000; + let Some([budget, used, ..]) = video_memory else { + return NORMAL_MS; + }; + if budget == 0 { + return NORMAL_MS; + } + let used_pct = (u128::from(used) * 100) / u128::from(budget); + if used_pct >= 85 { + HIGH_MS + } else if used_pct >= 75 { + MODERATE_MS + } else { + NORMAL_MS + } +} + +/// Effective idle timeout (in milliseconds) for system-RAM caches (staging +/// buffers, loose shadows, and the mapped pipeline library), scaled down +/// when free physical RAM is low. Never returns less than 2,000 ms. +pub(crate) fn ram_idle_ms(avail_phys: Option) -> u64 { + const GIB: u64 = 1024 * 1024 * 1024; + const NORMAL_MS: u64 = 10_000; + const MODERATE_MS: u64 = 5_000; + const HIGH_MS: u64 = 2_000; + let Some(avail) = avail_phys else { + return NORMAL_MS; + }; + if avail < 2 * GIB { + HIGH_MS + } else if avail < 4 * GIB { + MODERATE_MS + } else { + NORMAL_MS + } +} + /// How many references are held on a host object (its COM count): ours /// all, since the host's views and commands hold none. A buffer or texture /// with one is held by its owner alone: no descriptor slot keeps it @@ -6479,4 +6533,40 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at before.as_secs_f64() / after.as_secs_f64() ); } + + #[test] + fn vram_idle_ms_scales_with_pressure() { + use super::vram_idle_ms; + let gib = 1024 * 1024 * 1024; + // Normal (< 75%) + assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000); + assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000); + assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000); + // Moderate (75%..85%) + assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500); + assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500); + // High (>= 85%, including over-budget) + assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000); + assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000); + // Missing or zero budget falls back to normal + assert_eq!(vram_idle_ms(None), 5_000); + assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000); + } + + #[test] + fn ram_idle_ms_scales_with_pressure() { + use super::ram_idle_ms; + let gib = 1024 * 1024 * 1024; + // Normal (>= 4 GiB) + assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000); + assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000); + // Moderate (2 GiB..4 GiB) + assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000); + assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000); + // High (< 2 GiB) + assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000); + assert_eq!(ram_idle_ms(Some(0)), 2_000); + // Missing falls back to normal + assert_eq!(ram_idle_ms(None), 10_000); + } } diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 7047331..fac6f59 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -363,13 +363,16 @@ pub(crate) fn removal_note() -> String { /// (hundreds of thousands of pages), once after each burst of loads. /// `VICTORY_LIBRARY_TRIM=0`: the pages stay until Windows takes them. pub(crate) fn trim() { - const QUIET_MS: u64 = 10_000; static ON: OnceLock = OnceLock::new(); let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed)); if at == 0 || TRIMMED.load(Ordering::Relaxed) - || crate::host::now_ms() < LOADED_AT.load(Ordering::Relaxed) + QUIET_MS || !*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_TRIM").is_none_or(|v| v != "0")) + { + return; + } + let quiet_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); + if crate::host::now_ms() < LOADED_AT.load(Ordering::Relaxed) + quiet_ms || TRIMMED.swap(true, Ordering::Relaxed) { return; diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 2367d8b..f69d9e2 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1410,12 +1410,12 @@ pub(crate) fn room() -> bool { #[cfg(windows)] pub(crate) fn let_go_idle() { use std::sync::atomic::Ordering::Relaxed; - const IDLE_MS: u64 = 5_000; const IDLE_FRAMES: u64 = 4; static ON: std::sync::OnceLock = std::sync::OnceLock::new(); if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_none_or(|v| v != "0")) { return; } + let idle_ms = crate::host::vram_idle_ms(crate::host::host().and_then(|h| h.video_memory())); // For the trail (`crate::host::trail`): how many went, their bytes, // and the first one. let (mut went, mut bytes, mut first) = (0u64, 0u64, None); @@ -1430,7 +1430,7 @@ pub(crate) fn let_go_idle() { let gone = { let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); let idle = made.as_ref().is_some_and(|(host, _)| { - crate::host::long_ago(r.host.used.load(Relaxed), IDLE_MS, IDLE_FRAMES) + crate::host::long_ago(r.host.used.load(Relaxed), idle_ms, IDLE_FRAMES) && std::sync::Arc::strong_count(host) == 1 && crate::host::references(&host.texture) == 1 }); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 58b7d6e..afd2b9c 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1565,17 +1565,20 @@ pub(crate) fn window_use() -> [u64; 8] { /// The next read of that memory makes a new copy and copies the window /// again. Called before a submission starts, by the thread that submits. pub(crate) fn let_go_idle() { - const IDLE_MS: u64 = 10_000; const IDLE_FRAMES: u64 = 4; let gone: Vec> = { // Held from the look to the removal: `loose` hands a copy out // under the same lock, so none is handed out in between. let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + if map.is_empty() { + return; + } + let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); let idle: Vec<(u64, u64)> = map .iter() .filter(|(_, s)| { Arc::strong_count(s) == 1 - && crate::host::long_ago(s.used.load(Ordering::Relaxed), IDLE_MS, IDLE_FRAMES) + && crate::host::long_ago(s.used.load(Ordering::Relaxed), idle_ms, IDLE_FRAMES) && crate::host::references(&s.buffer) == 1 }) .map(|(key, _)| *key) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index f815393..0512fd6 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -422,19 +422,22 @@ pub(crate) fn let_go() -> [u64; 2] { /// Called before a submission starts, by the thread that submits. pub(crate) fn let_go_idle() { use std::sync::atomic::Ordering::Relaxed; - const IDLE_MS: u64 = 10_000; const IDLE_FRAMES: u64 = 4; let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); let Some(map) = map.as_mut() else { return; }; + if map.is_empty() { + return; + } + let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); // A list that recorded an upload or a check holds the staging until it // is reset: one only the table holds is named by no list, recorded or // running. let (mut went, mut bytes) = (0u64, 0u64); map.retain(|_, s| { let keep = Arc::strong_count(s) > 1 - || !crate::host::long_ago(s.used.load(Relaxed), IDLE_MS, IDLE_FRAMES); + || !crate::host::long_ago(s.used.load(Relaxed), idle_ms, IDLE_FRAMES); if !keep { LET_GO[0].fetch_add(1, Relaxed); LET_GO[1].fetch_add(s.bytes, Relaxed); diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index e8d6baf..a2fa943 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -13,7 +13,7 @@ victory-loader.workspace = true victory-pe.workspace = true victory-formats.workspace = true opus-pure.workspace = true -miniz_oxide.workspace = true +zlib-rs.workspace = true tracing.workspace = true [target.'cfg(windows)'.dependencies] diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 48c6086..c066419 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -847,11 +847,47 @@ fn execute(request: &Request) -> Result<(), HRESULT> { /// that ends short of `out` passes: the title's chunks fill it exactly, and /// nothing says that is required. fn inflate(source: &[u8], out: &mut [u8]) -> Result { - miniz_oxide::inflate::decompress_slice_iter_to_slice(out, std::iter::once(source), true, false) - .map_err(|status| { - tracing::debug!(?status, "dstorage: zlib stream"); - INVALID_DATA - }) + thread_local! { + static INFLATE: std::cell::RefCell = + std::cell::RefCell::new(zlib_rs::Inflate::new(true, 15)); + } + INFLATE.with_borrow_mut(|state| { + state.reset(true); + // `Inflate::decompress` cannot distinguish a valid empty stream from + // an insufficient buffer when `avail_out == 0`, so use a 1-byte scratch + // destination and verify `written <= out_len` afterward. + let out_len = out.len(); + let mut scratch = [0u8; 1]; + let dest = if out_len == 0 { &mut scratch[..] } else { out }; + let (mut in_pos, mut out_pos) = (0usize, 0usize); + let status = loop { + match state.decompress( + &source[in_pos..], + &mut dest[out_pos..], + zlib_rs::InflateFlush::NoFlush, + ) { + Ok(zlib_rs::Status::StreamEnd) => break Ok(zlib_rs::Status::StreamEnd), + Ok(zlib_rs::Status::Ok) => { + let next_in = state.total_in() as usize; + let next_out = state.total_out() as usize; + if next_in == in_pos && next_out == out_pos { + break Ok(zlib_rs::Status::BufError); + } + in_pos = next_in; + out_pos = next_out; + } + other => break other, + } + }; + let written = state.total_out() as usize; + match status { + Ok(zlib_rs::Status::StreamEnd) if written <= out_len => Ok(written), + other => { + tracing::debug!(?other, "dstorage: zlib stream"); + Err(INVALID_DATA) + } + } + }) } /// The BCPack format's constant tables, parsed once for the process. If @@ -973,9 +1009,29 @@ fn into_destination( } let mut data = vec![0; len]; let n = fill(&mut data)?; - if super::xmem::write_physical(pages, offset, &data[..n]) { + // A page the title has just made, or a view the host refuses for a moment (commit + // or address space short while a load maps many at once), can come right a little + // later: tried again before the request fails (`VICTORY_DSTORAGE_RETRIES`, default 12, + // about 1.5 s in all). + static RETRIES: std::sync::OnceLock = std::sync::OnceLock::new(); + let retries = *RETRIES.get_or_init(|| { + std::env::var("VICTORY_DSTORAGE_RETRIES").ok().and_then(|v| v.parse().ok()).unwrap_or(12) + }); + let mut written = super::xmem::write_physical(pages, offset, &data[..n]); + let mut tries = 0; + while !written && tries < retries { + std::thread::sleep(std::time::Duration::from_millis((2u64 << tries.min(6)).min(128))); + tries += 1; + written = super::xmem::write_physical(pages, offset, &data[..n]); + } + if written { + if tries > 0 { + tracing::info!(offset, len, tries, "dstorage: a destination's physical pages written after a retry"); + } Ok(()) } else { + let known = super::xmem::pages_known(pages, offset, len); + tracing::warn!(known, last_error = std::io::Error::last_os_error().raw_os_error(), "dstorage: retries used up"); // Said aloud: the title never reads a request's result // (it only polls for completion), so a destination left unwritten // is a model or texture that silently holds whatever its pages @@ -1153,10 +1209,18 @@ mod tests { assert_eq!(std::mem::offset_of!(QueueDesc, unknown), 0x18); } + fn compress_zlib(plain: &[u8]) -> Vec { + let mut buf = vec![0u8; zlib_rs::compress_bound(plain.len())]; + let (packed, rc) = + zlib_rs::compress_slice(&mut buf, plain, zlib_rs::DeflateConfig::new(6)); + assert_eq!(rc, zlib_rs::ReturnCode::Ok); + packed.to_vec() + } + #[test] fn raw_and_zlib_reads_from_a_file() { let plain = pattern(300_000); - let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let packed = compress_zlib(&plain); let mut contents = plain.clone(); contents.extend_from_slice(&packed); let (_dir, file) = file_with(&contents); @@ -1188,7 +1252,7 @@ mod tests { #[test] fn memory_sources_inflate_too() { let plain = pattern(70_000); - let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let packed = compress_zlib(&plain); let (queue, array) = (new_queue(1), status_array(1)); let mut out = vec![0u8; plain.len()]; let options = ZLIB | MEMORY_SOURCE; @@ -1365,7 +1429,7 @@ mod tests { #[test] fn zlib_then_bcpack() { with_test_tables(); - let packed = miniz_oxide::deflate::compress_to_vec_zlib(&BC4_STREAM, 6); + let packed = compress_zlib(&BC4_STREAM); let (_dir, file) = file_with(&packed); let (queue, array) = (new_queue(0), status_array(1)); let mut out = [0u8; 16]; @@ -1507,7 +1571,7 @@ mod tests { }; let (a, b) = (allocate(3), allocate(1)); let plain = pattern(2 * PAGE + 100); - let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let packed = compress_zlib(&plain); // One allocation's pages in order (one window), then pages of two // (through a buffer), both from 50 bytes into the first. let mut destinations = [a.clone(), vec![a[0], a[1], b[0]]]; @@ -1552,4 +1616,61 @@ mod tests { assert_eq!(xmem::XMemFreePhysicalPages(3, a.as_ptr()), 1); assert_eq!(xmem::XMemFreePhysicalPages(1, b.as_ptr()), 1); } + + #[test] + fn zlib_inflate_handles_short_exact_empty_and_bad_streams() { + let plain = pattern(65_537); + let packed = compress_zlib(&plain); + + // Exact fit. + let mut exact = vec![0u8; plain.len()]; + assert_eq!(inflate(&packed, &mut exact), Ok(plain.len())); + assert_eq!(exact, plain); + + // Short stream into a larger buffer passes and returns bytes written; + // guard bytes outside the slice passed to `inflate` stay untouched. + let mut larger = vec![0xAA; plain.len() + 64]; + assert_eq!( + inflate(&packed, &mut larger[..plain.len() + 32]), + Ok(plain.len()) + ); + assert_eq!(&larger[..plain.len()], &plain[..]); + assert!(larger[plain.len() + 32..].iter().all(|&b| b == 0xAA)); + + // Empty valid stream passes for empty or non-empty destinations. + let empty = compress_zlib(&[]); + assert_eq!(inflate(&empty, &mut []), Ok(0)); + let mut scratch = [0x55u8; 4]; + assert_eq!(inflate(&empty, &mut scratch), Ok(0)); + + // Oversized stream (destination too small, including empty) fails. + let mut small = vec![0u8; plain.len() - 1]; + assert_eq!(inflate(&packed, &mut small), Err(INVALID_DATA)); + assert_eq!(inflate(&packed, &mut []), Err(INVALID_DATA)); + + // Truncated stream (missing trailer or payload bytes) fails. + let mut out = vec![0u8; plain.len()]; + assert_eq!( + inflate(&packed[..packed.len() - 1], &mut out), + Err(INVALID_DATA) + ); + assert_eq!( + inflate(&packed[..packed.len() / 2], &mut out), + Err(INVALID_DATA) + ); + assert_eq!(inflate(&[], &mut out), Err(INVALID_DATA)); + + // Corrupt Adler-32 trailer fails. + let mut bad_adler = packed.clone(); + *bad_adler.last_mut().unwrap() ^= 1; + assert_eq!(inflate(&bad_adler, &mut out), Err(INVALID_DATA)); + + // Corrupt header/payload fails, and subsequent valid inflate on the + // same thread still succeeds (verifies thread-local state reset). + let mut bad_body = packed.clone(); + bad_body[2] ^= 0xFF; + assert_eq!(inflate(&bad_body, &mut out), Err(INVALID_DATA)); + assert_eq!(inflate(&packed, &mut out), Ok(plain.len())); + assert_eq!(out, plain); + } } diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 82e14ef..5f717bf 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -536,6 +536,12 @@ fn runs(pages: &[usize], offset: usize, len: usize) -> Option bool { + runs(pages, offset, len).is_some() +} + /// Copies `data` into physical pages, from `offset` bytes into the first, /// whether or not they are mapped anywhere (DirectStorage destinations). /// One view per run of consecutive pages, not one per page: each view diff --git a/crates/victory-shader/Cargo.toml b/crates/victory-shader/Cargo.toml index edfd1b9..3d0caf1 100644 --- a/crates/victory-shader/Cargo.toml +++ b/crates/victory-shader/Cargo.toml @@ -9,7 +9,7 @@ publish.workspace = true [dependencies] thiserror.workspace = true -miniz_oxide.workspace = true +zlib-rs.workspace = true [features] # Host D3D12 pipeline checks (`emit::host`). diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 40b0883..eff0ac0 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -30,6 +30,7 @@ enum TypeDef { Void, Int(u32), Float, + Double, /// Pointee and address space. Ptr(Ty, u32), Struct(Option, Vec), @@ -247,6 +248,9 @@ impl Module { pub fn float(&mut self) -> Ty { self.ty(TypeDef::Float) } + pub fn double(&mut self) -> Ty { + self.ty(TypeDef::Double) + } pub fn ptr(&mut self, to: Ty) -> Ty { self.ty(TypeDef::Ptr(to, 0)) } @@ -578,6 +582,7 @@ impl Module { match t { TypeDef::Void => w.record(2, &[]), TypeDef::Float => w.record(3, &[]), + TypeDef::Double => w.record(4, &[]), TypeDef::Int(b) => w.record(7, &[u64::from(*b)]), TypeDef::Ptr(p, space) => w.record(8, &[u64::from(p.0), u64::from(*space)]), TypeDef::Array(n, e) => w.record(11, &[u64::from(*n), u64::from(e.0)]), diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 600139a..7c69b19 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1491,7 +1491,23 @@ impl<'a> Lower<'a> { .collect(), scalar: x.res.scalar.iter().copied().collect(), exports: x.io.exports.iter().map(|e| (e.site, e)).collect(), - interps: x.io.interps.iter().map(|(s, i)| (*s, i)).collect(), + interps: { + let mut m: HashMap = x.io.interps.iter().map(|(s, i)| (*s, i)).collect(); + // A first half whose result is also read as data (an f16 second half keeps + // the other half of its dst, PS_DeferredTextured): evaluated as the pair it + // starts. Approximate for those other bits (P0 + i P10 on the console); a + // first half only the second half reads is gone before lowering. + if std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") { + for (_, i) in &x.io.interps { + if let Interp::Interpolated { first, .. } = i { + for s in first { + m.entry(*s).or_insert(i); + } + } + } + } + m + }, handles: HashMap::new(), strides: HashMap::new(), edges: HashMap::new(), @@ -1781,6 +1797,9 @@ impl<'a> Lower<'a> { Shape::K(k) => return Ok(self.s.m.i32(k)), Shape::Value(v) => return self.i32_of(v), Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None), + Shape::ActiveF64(lo, hi, mask, high) => { + return self.active_f64_sum(lo, hi, mask, high); + } Shape::Masked(src, mask, ident) => { let c = self.cur; let &m = self @@ -1946,6 +1965,74 @@ impl<'a> Lower<'a> { Ok(if float { self.as_int(r) } else { r }) } + /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere), + /// returning the low (`!high`) or high (`high`) 32-bit word. + fn active_f64_sum( + &mut self, + lo: Value, + hi: Value, + mask: Value, + high: bool, + ) -> Result { + if self.mask_data == MaskData::None { + return Err("a wave reduction in a mesh shader"); + } + let c = self.cur; + let &m = self + .x + .st + .masks + .get(&mask) + .ok_or("a wave reduction's untracked mask")?; + let on = self.boolean(m, c)?; + let lo = self.i32_of(lo)?; + let hi = self.i32_of(hi)?; + let z = self.s.m.i32(0); + let lo = self.s.m.select(c, on, lo, z); + let hi = self.s.m.select(c, on, hi, z); + self.s.flags |= flags::WAVE_OPS | flags::DOUBLES; + let f64t = self.s.m.double(); + let i32t = self.s.t.i32; + let split_ty = self + .s + .m + .named_struct("dx.types.splitdouble", vec![i32t, i32t]); + let arg = self + .s + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]); + let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0)); + let sum = self + .s + .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]); + let split = self + .s + .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]); + let mut r_lo = self.s.m.extract(c, split, 0); + let mut r_hi = self.s.m.extract(c, split, 1); + if self.exchange.is_some() { + if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); + return Err("a wave reduction where not every lane runs"); + } + let (lo0, lo1) = self.exchange_halves(self.cur, r_lo); + let (hi0, hi1) = self.exchange_halves(self.cur, r_hi); + let c = self.cur; + let d0 = self + .s + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]); + let d1 = self + .s + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]); + let total = self.s.m.bin(c, Bin::Add, d0, d1); + let split = self + .s + .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]); + r_lo = self.s.m.extract(c, split, 0); + r_hi = self.s.m.extract(c, split, 1); + } + Ok(if high { r_hi } else { r_lo }) + } + /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's /// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest /// ([`Self::f16_nearest`]). @@ -5578,6 +5665,15 @@ impl<'a> Lower<'a> { } return Ok(()); } + if std::env::var_os("VICTORY_DESC_WHY").is_some() { + eprintln!( + "DESC-WHY {:#x} {} scalar={:?} lane_copied={}", + inst.machine.offset, + inst.name(), + address, + self.x.res.lane_copied.contains(&site) + ); + } return Err("a descriptor read only as data"); }; let src = Source::Loaded { load: site, first }; @@ -6998,6 +7094,12 @@ impl<'a> Lower<'a> { let r = self.s.m.cast(c, op, a, self.s.t.f32); float(self, r) } + "v_cvt_f32_f64" => { + let (lo, hi) = self.f64_pair(inst, 0)?; + let bits = self.f64_to_f32_bits(lo, hi); + let r = self.as_float(bits); + float(self, r) + } "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { // Each source is f32, or with op_sel_hi the low (op_sel: high) // f16 half; neg_hi is the absolute value here. @@ -7288,6 +7390,14 @@ impl<'a> Lower<'a> { let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local; let r = if halves && !alike { if !self.all_lanes(self.cur_ir) { + // shortcut: `VICTORY_FIRSTLANE_OWN=1` takes the host wave's own + // first lane, exact when the value is the same in every lane of + // the console wave (the ray-tracing builder's scans read a sum of + // scalars this way, inside a loop whose exit is per console wave). + static OWN: std::sync::OnceLock = std::sync::OnceLock::new(); + if *OWN.get_or_init(|| std::env::var_os("VICTORY_FIRSTLANE_OWN").is_some_and(|v| v == "1")) { + return int(self, mine); + } need(self.cur_ir); return Err("a first-lane read where not every lane runs"); } @@ -7358,6 +7468,159 @@ impl<'a> Lower<'a> { } } + /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying + /// `abs` and `neg` input modifiers on operand `k`. + fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.sdwa.is_some() || v.dpp.is_some() { + return Err("64-bit operand modifiers"); + } + let op = *v.src.get(k).ok_or("a missing operand")?; + let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> { + let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?; + let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?; + Ok((lo, hi)) + }; + let (lo, mut hi) = match op { + Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?, + Operand::Scalar { code, .. } if code != NULL => { + pair(self, Reg::S(code), Reg::S(code + 1))? + } + Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)), + Operand::Const(c @ 240..=248) => { + const INLINE_F64: [f64; 9] = [ + 0.5, + -0.5, + 1.0, + -1.0, + 2.0, + -2.0, + 4.0, + -4.0, + 1.0 / std::f64::consts::TAU, + ]; + let bits = INLINE_F64[(c - 240) as usize].to_bits(); + (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32)) + } + // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand. + Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)), + _ => return Err("a 64-bit float operand"), + }; + let c = self.cur; + if v.abs >> k & 1 != 0 { + let mask = self.s.m.i32(0x7FFF_FFFF); + hi = self.s.m.bin(c, Bin::And, hi, mask); + } + if v.neg >> k & 1 != 0 { + let sign = self.s.m.i32(0x8000_0000); + hi = self.s.m.bin(c, Bin::Xor, hi, sign); + } + Ok((lo, hi)) + } + + /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even, + /// without requiring host `DOUBLES` (`f64`) support. + fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let k0 = self.s.m.i32(0); + let k1 = self.s.m.i32(1); + let sign_mask = self.s.m.i32(0x8000_0000); + let sign = self.s.m.bin(c, Bin::And, hi, sign_mask); + + let k20 = self.s.m.i32(20); + let k7ff = self.s.m.i32(0x7FF); + let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20); + let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff); + + let frac_mask = self.s.m.i32(0x000F_FFFF); + let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask); + let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo); + let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0); + + let k3 = self.s.m.i32(3); + let k29 = self.s.m.i32(29); + let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3); + let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29); + let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo); + + let rem_mask = self.s.m.i32(0x1FFF_FFFF); + let rem = self.s.m.bin(c, Bin::And, lo, rem_mask); + let half_rem = self.s.m.i32(0x1000_0000); + let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem); + let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem); + let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1); + let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0); + let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd); + let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up); + let norm_inc = self.s.m.select(c, norm_round, k1, k0); + + // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254]. + let k896 = self.s.m.i32(896); + let k23 = self.s.m.i32(23); + let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896); + let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23); + let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23); + let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc); + let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body); + + // Subnormal range: exp64 in [874, 896] -> shift in [1, 23]. + let k897 = self.s.m.i32(897); + let k32 = self.s.m.i32(32); + let k31 = self.s.m.i32(31); + let imp = self.s.m.i32(0x0080_0000); + let sig24 = self.s.m.bin(c, Bin::Or, imp, m23); + let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64); + // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch. + let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1); + let shift = self.s.m.select(c, lt1, k1, raw_shift); + let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23); + let shift = self.s.m.select(c, gt23, k23, shift); + let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift); + let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift); + let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift); + let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31); + let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0); + let low31 = self.s.m.i32(0x7FFF_FFFF); + let lost_lo = self.s.m.bin(c, Bin::And, lost, low31); + let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem); + let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0); + let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1); + let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0); + let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd); + let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie); + let sub_inc = self.s.m.select(c, sub_round, k1, k0); + let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc); + let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body); + + // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1). + let k873 = self.s.m.i32(873); + let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873); + let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz); + let min_bit = self.s.m.select(c, round_min, k1, k0); + let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit); + + // Overflow / Inf / NaN: exp64 >= 1151. + let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff); + let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz); + let inf_bits = self.s.m.i32(0x7F80_0000); + let qnan_bits = self.s.m.i32(0x7FC0_0000); + let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23); + let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits); + let over_res = self.s.m.bin(c, Bin::Or, sign, over_body); + + // Select final result by exponent range. + let k874 = self.s.m.i32(874); + let k1151 = self.s.m.i32(1151); + let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874); + let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897); + let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151); + let r = self.s.m.select(c, is_over, over_res, norm_res); + let r = self.s.m.select(c, is_sub, sub_res, r); + self.s.m.select(c, is_under, under_res, r) + } + fn join64(&mut self, lo: V, hi: V) -> V { let c = self.cur; let ty = self.s.m.int(64); diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index b49bc6d..4626982 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -73,6 +73,7 @@ pub const USER_VIEW_BIAS: u32 = 0x103; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { pub const RAW_BUFFERS: u64 = 1 << 4; + pub const DOUBLES: u64 = 1 << 2; pub const STENCIL_REF: u64 = 1 << 11; pub const TYPED_UAV_LOADS: u64 = 1 << 13; pub const WAVE_OPS: u64 = 1 << 19; @@ -772,6 +773,9 @@ impl Shader { dxil.extend(&bitcode); let mut features = 0u64; + if self.flags & flags::DOUBLES != 0 { + features |= 0x1; + } 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 5072d6c..93a36be 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -1264,3 +1264,257 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +#[test] +fn v_cvt_f32_f64_matches_ieee754() { + // v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x00f -> VOP3 opcode 0x18f). + let plain = build_valu_cs(&[vop1(0x00f, 0, vgpr(1))]); + // Same with abs + neg on src0 (VOP3: abs[0] = bit 8 of w0, neg[0] = bit 29 of w1). + let [mut w0, mut w1] = vop3(0x18f, 0, vgpr(1), 0, 0); + w0 |= 1 << 8; + w1 |= 1 << 29; + let neg_abs = build_valu_cs(&[w0, w1]); + + let values: &[f64] = &[ + 0.0, + -0.0, + 1.0, + -1.0, + 3.5, + -123456.75, + // Tie-to-even: even mantissa stays, odd mantissa rounds up. + f64::from_bits(0x3FF0_0000_1000_0000), // 1.0 + 0.5 ulp(f32) -> 1.0 + f64::from_bits(0x3FF0_0000_3000_0000), // (1.0 + 1 ulp) + 0.5 ulp -> 1.0 + 2 ulp + f64::from_bits(0x3FF0_0000_1000_0001), // > 0.5 ulp -> rounds up + // Largest finite f32 and overflow to +Inf / -Inf. + f64::from(f32::MAX), + f64::from(f32::MAX) * 1.000_001, + -f64::from(f32::MAX) * 1.000_001, + 1e300, + // Subnormal range (exp64 in [874, 896]), including carry into smallest normal. + f64::from(f32::MIN_POSITIVE), + f64::from(f32::MIN_POSITIVE) * 0.5, + f64::from(f32::MIN_POSITIVE) * 0.75, + f64::from(f32::from_bits(0x007F_FFFF)), + f64::from_bits(0x380F_FFFF_F000_0000), // max subnormal + 0.5 ulp -> min normal + // exp64 == 873: exact 2^-150 ties to 0; strictly greater rounds to min subnormal (1). + f64::from_bits(0x3690_0000_0000_0000), + f64::from_bits(0x3690_0000_0000_0001), + f64::from_bits(0xB690_0000_0000_0001), + // Deep underflow -> +/-0.0. + 1e-200, + -1e-200, + // Infinities and NaNs. + f64::INFINITY, + f64::NEG_INFINITY, + f64::from_bits(0x7FF8_0000_0000_0000), // +qNaN + f64::from_bits(0x7FF0_0000_0000_0001), // +sNaN -> quieted + ]; + let inputs: Vec<[u32; 4]> = values + .iter() + .map(|&x| { + let b = x.to_bits(); + [b as u32, (b >> 32) as u32, 0, 0] + }) + .collect(); + run_cases(&plain, &inputs, |backend, i, _, got| { + let x = values[i]; + let want = (x as f32).to_bits(); + if x.is_nan() { + assert!( + f32::from_bits(got).is_nan() && (got & 0x0040_0000) != 0, + "{backend}: v_cvt_f32_f64({:#018x}) = {got:#010x}, expected qNaN", + x.to_bits(), + ); + } else { + assert_eq!( + got, want, + "{backend}: v_cvt_f32_f64({x} / {:#018x}) = {got:#010x}, want {want:#010x}", + x.to_bits(), + ); + } + }); + + // -|x| via VOP3 abs + neg modifiers. + let mod_values: &[f64] = &[2.5, -2.5, 0.0, f64::INFINITY]; + let mod_in: Vec<[u32; 4]> = mod_values + .iter() + .map(|&x| { + let b = x.to_bits(); + [b as u32, (b >> 32) as u32, 0, 0] + }) + .collect(); + run_cases(&neg_abs, &mod_in, |backend, i, _, got| { + let x = mod_values[i]; + let want = (-(x.abs()) as f32).to_bits(); + assert_eq!( + got, want, + "{backend}: v_cvt_f32_f64(-|{x}|) = {got:#010x}, want {want:#010x}", + ); + }); +} + +#[test] +fn whole_wave_f64_sum_and_cvt_f32_f64() { + let s_or_saveexec_b32 = + |sdst: u8, src0: u8| 0xBE80_0000 | (sdst as u32) << 16 | 0x3D << 8 | src0 as u32; + let v_mov_dpp8 = |vdst: u8, vsrc: u8, sel: u32| [vop1(0x001, vdst, 0xE9), vsrc as u32 | (sel << 8)]; + let v_mov_row_mirror = |vdst: u8, vsrc: u8| { + [ + vop1(0x001, vdst, 0xFA), + vsrc as u32 | (0x140 << 8) | (1 << 19) | (0xF << 24) | (0xF << 28), + ] + }; + + let mut words = Vec::new(); + words.push(s_mov_b32(5, 0x80)); + words.extend_from_slice(&s_load_dwordx4(8, 4)); + // Per-lane f64 input in v[6:7] = (s0, s1). + words.push(vop1(0x001, 6, sgpr(0))); + words.push(vop1(0x001, 7, sgpr(1))); + // Whole-wave f64 sum over Wave32 with s_mov_b32 copy before EXEC restore. + words.push(s_or_saveexec_b32(12, 0xC1)); + words.extend_from_slice(&vop3(0x101, 2, 0x80, vgpr(6), sgpr(12))); + words.extend_from_slice(&vop3(0x101, 3, 0x80, vgpr(7), sgpr(12))); + for sel in [14570689u32, 9658386, 2340] { + words.extend_from_slice(&v_mov_dpp8(4, 2, sel)); + words.extend_from_slice(&v_mov_dpp8(5, 3, sel)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); // v_add_f64 + } + words.extend_from_slice(&v_mov_row_mirror(4, 2)); + words.extend_from_slice(&v_mov_row_mirror(5, 3)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); + words.extend_from_slice(&vop3(0x378, 4, vgpr(2), 0x80, 0x80)); // v_permlanex16_b32 + words.extend_from_slice(&vop3(0x378, 5, vgpr(3), 0x80, 0x80)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); + words.extend_from_slice(&vop3(0x360, 14, vgpr(2), 0x80, 0)); // v_readlane_b32 s14, v2, 0 + words.extend_from_slice(&vop3(0x360, 15, vgpr(3), 0x80, 0)); // v_readlane_b32 s15, v3, 0 + words.push(s_mov_b32(16, 14)); + words.push(s_mov_b32(17, 15)); + words.push(s_mov_b32(126, 12)); // restore exec_lo + words.push(vop1(0x00f, 0, sgpr(16))); // v_cvt_f32_f64 v0, s[16:17] + words.extend_from_slice(&buffer_store_dword(0, 8, 0)); + words.push(S_ENDPGM); + + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 12, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [4, 1, 1], + }), + code, + }; + + 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)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: Vec::new(), + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + + let cases: &[(f64, f32)] = &[(1.25, 5.0), (-0.75, -3.0)]; + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + continue; + }; + let (root, pso) = match host.compute_pipeline(&shader) { + Ok(p) => p, + // WARP does not support fixed WaveSize(32) on SM 6.6. + Err(e) if warp => { + eprintln!("{label}: compute_pipeline skipped ({e})"); + continue; + } + Err(e) => panic!("{label}: compute_pipeline failed: {e}"), + }; + for &(x, want) in cases { + let b = x.to_bits(); + let inputs = [b as u32, (b >> 32) as u32, 0, 0]; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.slot) { + (RootType::Constants, 0) => inputs[u.dword as usize], + (RootType::Table, 1) => 0, + other => panic!("unexpected user data {other:?}"), + }; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!( + out[0][0], + want.to_bits(), + "{label}: wave f64 sum({x}) = {:#010x}, want {:#010x}", + out[0][0], + want.to_bits(), + ); + } + } +} diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs index c74e083..1d7a91b 100644 --- a/crates/victory-shader/src/emit/wave.rs +++ b/crates/victory-shader/src/emit/wave.rs @@ -112,6 +112,15 @@ pub(crate) enum Sym { ident: u32, lanes: u64, }, + /// Low (`!high`) or high (`high`) 32 bits of the 64-bit float sum over + /// `lanes` of `mask ? f64(lo, hi) : 0.0`. + Red64F { + lo: Value, + hi: Value, + mask: Value, + lanes: u64, + high: bool, + }, } /// What a value a section leaves holds in every lane. @@ -123,6 +132,8 @@ pub(crate) enum Shape { Masked(Value, Value, u32), /// `op` over every lane. Active(Op, Value, Value, u32), + /// Low (`!high`) or high (`high`) 32 bits of the 64-bit float sum over every lane. + ActiveF64(Value, Value, Value, bool), /// `op` over the lanes below (`inclusive`: and including) each lane. Prefix(Op, Value, Value, u32, bool), } @@ -298,13 +309,28 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { exec = ((exec & 0xFFFF_FFFF) | ((k & 0xFFFF_FFFF) << 32)) & all; continue; } - if let Fields::Sop { src, .. } = &inst.fields { + if let Fields::Sop { dst, src, .. } = &inst.fields { if name.starts_with("s_and_b") && src.iter().any(|o| matches!(*o, Operand::Scalar { code, .. } if inst.read(Reg::S(code)).is_some_and(|v| masked.contains(&v)))) && let Some(&(_, w)) = inst.writes.iter().find(|w| matches!(w.0, Reg::S(_))) { masked.push(w); } + if name == "s_mov_b32" + && let (Some(Operand::Scalar { code: dc, .. }), Some(s0)) = (dst, src.first()) + && *dc != NULL + && let Some(w) = inst.write(Reg::S(*dc)) + { + let sym = match *s0 { + Operand::Scalar { code, .. } if code != NULL => inst + .read(Reg::S(code)) + .map_or(Sym::Unknown, |x| uni.get(&x).copied().unwrap_or(Sym::Uni(x))), + Operand::Const(c) => crate::resource::inline(c).map_or(Sym::Unknown, Sym::K), + Operand::Literal(x) => Sym::K(x), + _ => Sym::Unknown, + }; + uni.insert(w, sym); + } for &(_, w) in &inst.writes { uni.entry(w).or_insert(Sym::Unknown); } @@ -359,6 +385,130 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { } continue; } + if name == "v_add_f64" + && !modifiers + && v.dpp.is_none() + && let Some(Operand::Vector { reg: dreg, .. }) = v.dst + && let (Some(dst_lo), Some(dst_hi)) = + (inst.write(Reg::V(dreg)), inst.write(Reg::V(dreg + 1))) + { + let pair_lanes = |op: Option<&Operand>| -> Option<(Vec, Vec)> { + match *op? { + Operand::Vector { reg, .. } => Some(( + lanes(&Operand::Vector { reg, dwords: 1 }, &vec, &uni), + lanes( + &Operand::Vector { + reg: reg + 1, + dwords: 1, + }, + &vec, + &uni, + ), + )), + Operand::Scalar { code, .. } if code != NULL => Some(( + lanes(&Operand::Scalar { code, dwords: 1 }, &vec, &uni), + lanes( + &Operand::Scalar { + code: code + 1, + dwords: 1, + }, + &vec, + &uni, + ), + )), + _ => None, + } + }; + let old_lo = lanes( + &Operand::Vector { + reg: dreg, + dwords: 1, + }, + &vec, + &uni, + ); + let old_hi = lanes( + &Operand::Vector { + reg: dreg + 1, + dwords: 1, + }, + &vec, + &uni, + ); + let f64_term = |lo_s: Sym, hi_s: Sym| -> Option<(Value, Value, Value, u64)> { + match (lo_s, hi_s) { + ( + Sym::Red { + op: None, + src: lo, + mask: ml, + ident: 0, + lanes: ll, + }, + Sym::Red { + op: None, + src: hi, + mask: mh, + ident: 0, + lanes: lh, + }, + ) if ml == mh && ll == lh => Some((lo, hi, ml, ll)), + ( + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: l1, + high: false, + }, + Sym::Red64F { + lo: lo2, + hi: hi2, + mask: m2, + lanes: l2, + high: true, + }, + ) if (lo1, hi1, m1, l1) == (lo2, hi2, m2, l2) => Some((lo1, hi1, m1, l1)), + _ => None, + } + }; + let mut out_lo = vec![Sym::Unknown; wave as usize]; + let mut out_hi = vec![Sym::Unknown; wave as usize]; + if let (Some((alo, ahi)), Some((blo, bhi))) = + (pair_lanes(v.src.first()), pair_lanes(v.src.get(1))) + { + for l in 0..wave as usize { + let (rl, rh) = match (f64_term(alo[l], ahi[l]), f64_term(blo[l], bhi[l])) { + (Some((lo1, hi1, m1, la)), Some((lo2, hi2, m2, lb))) + if (lo1, hi1, m1) == (lo2, hi2, m2) && la & lb == 0 => + { + ( + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: la | lb, + high: false, + }, + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: la | lb, + high: true, + }, + ) + } + _ => (Sym::Unknown, Sym::Unknown), + }; + out_lo[l] = if exec >> l & 1 != 0 { rl } else { old_lo[l] }; + out_hi[l] = if exec >> l & 1 != 0 { rh } else { old_hi[l] }; + } + } + vec.insert(dst_lo, out_lo); + vec.insert(dst_hi, out_hi); + continue; + } let Some(Operand::Vector { reg: dreg, .. }) = v.dst else { for &(_, w) in &inst.writes { uni.insert(w, Sym::Unknown); @@ -560,6 +710,13 @@ fn shapes( ident, lanes, } if lanes == all => Some(Shape::Active(op, src, mask, ident)), + Sym::Red64F { + lo, + hi, + mask, + lanes, + high, + } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), _ => None, }; for (v, s) in uni { @@ -603,6 +760,13 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option { ident, lanes, } if lanes == all => Some(Shape::Active(op, src, mask, ident)), + Sym::Red64F { + lo, + hi, + mask, + lanes, + high, + } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), _ => None, }; } diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index 4bdd39b..4c267e1 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -446,14 +446,63 @@ fn unpack(blob: &[u8]) -> Result, ShaderError> { } let stream = bytes(blob, XBCH_HEADER as u64, packed).ok_or(Malformed("XBCH stream out of bounds"))?; - let out = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(stream, unpacked as usize) - .map_err(|_| Malformed("XBCH stream does not inflate to its stated size"))?; - if out.len() as u64 != unpacked { - return Err(Malformed("XBCH stream does not inflate to its stated size")); - } + let out = inflate_zlib_exact(stream, unpacked as usize) + .ok_or(Malformed("XBCH stream does not inflate to its stated size"))?; Ok(out) } +/// Inflates a zlib stream incrementally up to `expected` bytes, rejecting +/// truncated, corrupt, under-filled, or oversized streams without eagerly +/// allocating the full declared size up front. +fn inflate_zlib_exact(source: &[u8], expected: usize) -> Option> { + let mut state = zlib_rs::Inflate::new(true, 15); + let mut out = Vec::new(); + let (mut in_pos, mut out_pos) = (0usize, 0usize); + loop { + if out_pos == expected { + let mut extra = [0u8; 1]; + let status = state + .decompress( + &source[in_pos..], + &mut extra, + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + return (status == zlib_rs::Status::StreamEnd + && state.total_out() as usize == expected) + .then_some(out); + } + if out_pos == out.len() { + let next_len = if out.is_empty() { + expected.min(source.len().saturating_mul(4).max(4096)) + } else { + out.len().saturating_mul(2).min(expected) + }; + out.resize(next_len, 0); + } + let status = state + .decompress( + &source[in_pos..], + &mut out[out_pos..], + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + let next_in = state.total_in() as usize; + let next_out = state.total_out() as usize; + match status { + zlib_rs::Status::StreamEnd => { + out.truncate(next_out); + return (next_out == expected).then_some(out); + } + zlib_rs::Status::Ok if next_in != in_pos || next_out != out_pos => { + in_pos = next_in; + out_pos = next_out; + } + zlib_rs::Status::Ok | zlib_rs::Status::BufError => return None, + } + } +} + fn programs(fssm: &[u8]) -> Result, ShaderError> { if fssm.get(0..4) != Some(b"FSSM") { return Err(Malformed("native blob lacks FSSM magic")); @@ -729,12 +778,15 @@ mod tests { } fn xbch(unpacked: &[u8]) -> Vec { - let stream = miniz_oxide::deflate::compress_to_vec_zlib(unpacked, 6); + let mut buf = vec![0u8; zlib_rs::compress_bound(unpacked.len())]; + let (stream, rc) = + zlib_rs::compress_slice(&mut buf, unpacked, zlib_rs::DeflateConfig::new(6)); + assert_eq!(rc, zlib_rs::ReturnCode::Ok); let mut out = b"XBCH".to_vec(); out.extend_from_slice(&XBCH_VERSION.to_le_bytes()); out.extend_from_slice(&(stream.len() as u64).to_le_bytes()); out.extend_from_slice(&(unpacked.len() as u64).to_le_bytes()); - out.extend_from_slice(&stream); + out.extend_from_slice(stream); out } @@ -1020,4 +1072,32 @@ mod tests { bad_record[at..at + 8].copy_from_slice(&u64::MAX.to_le_bytes()); assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&bad_record))])).is_err()); } + + #[test] + fn rejects_truncated_oversized_and_bad_checksum_xbch_streams() { + let plain = fssm(&[(HwStage::Vs, &VS_CODE)]); + let good = xbch(&plain); + assert_eq!(unpack(&good).unwrap(), plain); + + // Truncated zlib stream (drop last byte, update packed length). + let mut truncated = good[..good.len() - 1].to_vec(); + let new_packed = (truncated.len() - XBCH_HEADER) as u64; + truncated[8..16].copy_from_slice(&new_packed.to_le_bytes()); + assert!(unpack(&truncated).is_err()); + + // Stated unpacked size smaller than the inflated output. + let mut oversized = good.clone(); + oversized[16..24].copy_from_slice(&((plain.len() - 1) as u64).to_le_bytes()); + assert!(unpack(&oversized).is_err()); + + // Stated unpacked size larger than the inflated output. + let mut underfilled = good.clone(); + underfilled[16..24].copy_from_slice(&((plain.len() + 1) as u64).to_le_bytes()); + assert!(unpack(&underfilled).is_err()); + + // Corrupt Adler-32 trailer. + let mut bad_adler = good.clone(); + *bad_adler.last_mut().unwrap() ^= 1; + assert!(unpack(&bad_adler).is_err()); + } } From 31714deb2d70bb7c5a963658ad0faed0368526c6 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:00:31 -0500 Subject: [PATCH 151/445] Take the fix/amd-view-heap-clamp branch of triippywhale's fork (as one commit) Every host view heap ends at a null slot that view indices past the heap read (a host that takes large heaps gets 2^21 views; one that caps them keeps the capped heap), the cache key includes that limit, and v_permlane16/x16 are lowered. Both forks lower v_cvt_f32_f64. The IEEE form with its test is the one in use; this branch's flush-to-zero form is kept beside it, unused, and its test is ignored until the console's float mode for the instruction is checked. Co-Authored-By: Claude Fable 5.2 --- crates/victory-gpu/src/descriptor/host.rs | 113 +++++++++++++------ crates/victory-gpu/src/shader_cache.rs | 4 + crates/victory-shader/src/emit/lower.rs | 113 ++++++++++++++++++- crates/victory-shader/src/emit/mod.rs | 2 +- crates/victory-shader/src/emit/shader.rs | 15 ++- crates/victory-shader/src/emit/valu_tests.rs | 104 +++++++++++++++++ 6 files changed, 302 insertions(+), 49 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index e91db79..895074a 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -509,34 +509,52 @@ pub(crate) fn near_heaps(va: u64) -> String { /// tiers 1 and 2; tier 3 hardware may take more. const PORTABLE_VIEWS: u32 = 1_000_000; -/// Asks the host, once, whether it caps view heaps at [`PORTABLE_VIEWS`], -/// and if so tells the translator now (`set_view_heap_limit`) instead of -/// when the title's heap is made: a shader keeps the limit it was -/// translated with, and the title makes 25 pipelines (their -/// shaders translated at once) before it makes its view heap. Those would -/// read a view index past the heap unclamped, the read that hangs NVIDIA. -/// Called before a shader is translated. -/// shortcut: the limit is the capped heap's last slot whatever size the -/// title's heap turns out to have; a heap that fits is not capped and -/// keeps no null slot there (an index past it is as undefined as before). +/// The size of every host view heap on a host that takes more than +/// [`PORTABLE_VIEWS`] (AMD): the title's heap (a little over 1,000,000 +/// views in the retail game) plus [`DYNAMIC`] fits with room to spare, and +/// the last slot is the null slot every view index at or past it reads. +const UNCAPPED_VIEWS: u32 = 1 << 21; + +/// Picks, once, the null slot at the end of every host view heap and tells +/// the translator now (`set_view_heap_limit`) instead of when the title's +/// heap is made: a shader keeps the limit it was translated with, and the +/// title makes 25 pipelines (their shaders translated at once) before it +/// makes its view heap. Called before a shader is translated and before a +/// view heap is made. +/// +/// Every host clamps. A host that caps view heaps at [`PORTABLE_VIEWS`] +/// (NVIDIA) hung on a view index past the heap; one that does not (AMD +/// RDNA3, RX 7900 XT) took a page fault and removed the device on entering +/// the world: a compute program read view slot 16,777,088 (0xffff80) of a +/// heap of 1,507,328, past its end. Unclamped, that index is undefined on +/// any host. pub(crate) fn probe_view_limit() { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { let Some(host) = host() else { return }; - // SAFETY: plain heap creation; the heap is released at once. - let made: windows::core::Result = unsafe { - host.device - .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - NumDescriptors: PORTABLE_VIEWS + 1, - Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, - NodeMask: 0, - }) + let fits = |count: u32| { + // SAFETY: plain heap creation; the heap is released at once. + let made: windows::core::Result = unsafe { + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: count, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + }; + made.is_ok() }; - if made.is_err() { - tracing::info!("the host caps view heaps at {PORTABLE_VIEWS}: view indices are clamped from the first shader on"); - victory_shader::emit::set_view_heap_limit(PORTABLE_VIEWS - 1); - } + let views = if fits(UNCAPPED_VIEWS) { + UNCAPPED_VIEWS + } else { + PORTABLE_VIEWS + }; + tracing::info!( + views, + "host view heaps hold {views} views; view indices are clamped to the null slot at the end from the first shader on" + ); + victory_shader::emit::set_view_heap_limit(views - 1); }); } @@ -574,20 +592,41 @@ impl HostHeap { } }; let extra = if sampler { 0 } else { DYNAMIC }; - let (heap, count, size) = match make(count + extra) { - Ok(heap) => (heap, count, count + extra), - Err(e) if !sampler && count + extra > PORTABLE_VIEWS => { - // shortcut: descriptors past the host's limit are left out; a title that reaches - // them needs remapping. The heap's last slot stays null, and shaders read it for - // any view index from there on (`set_view_heap_limit`): a read past the heap's - // end hung NVIDIA's GPU (the title's heap is a little over 1 000 000 views). - tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}; views past it read a null slot"); - victory_shader::emit::set_view_heap_limit(PORTABLE_VIEWS - 1); - (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - extra - 1, PORTABLE_VIEWS) + // A view heap ends at the null slot shaders clamp view indices to + // (`probe_view_limit`), whatever the title's own count: the title's + // slots, then the dynamic ones, then null up to and with that slot. + if !sampler { + probe_view_limit(); + } + let null = if sampler { + 0 + } else { + victory_shader::emit::view_heap_limit() + }; + let (heap, count, size) = if null == 0 { + match make(count + extra) { + Ok(heap) => (heap, count, count + extra), + Err(e) => { + tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); + return None; + } } - Err(e) => { - tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); - return None; + } else { + let size = null + 1; + let fitted = if count + extra <= null { + count + } else { + // shortcut: descriptors past the host's limit are left out; a title that reaches + // them needs remapping. They read the null slot instead. + tracing::warn!(count, "host view heap capped at {size}; views past it read a null slot"); + null - extra + }; + match make(size) { + Ok(heap) => (heap, fitted, size), + Err(e) => { + tracing::warn!(error = %e, count, size, "no host view heap"); + return None; + } } }; // SAFETY: a live heap. @@ -602,7 +641,7 @@ impl HostHeap { let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr }; GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push(( gpu, - u64::from(count + extra) * u64::from(step), + u64::from(size) * u64::from(step), u64::from(step), sampler, )); diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index eabd0f3..34ac4ac 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -54,6 +54,10 @@ fn build() -> &'static [u8; 32] { match exe { Ok(mut bytes) => { bytes.extend_from_slice(&limit.to_le_bytes()); + // So is the view heap's null slot (it differs by host GPU): + // a translation cached without the clamp must not be served. + crate::descriptor::host::probe_view_limit(); + bytes.extend_from_slice(&victory_shader::emit::view_heap_limit().to_le_bytes()); // Which group barriers wait is part of the translation too. bytes.push(victory_shader::emit::group_sync()); // So are the switches that pick the form of a wave64 program: diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 7c69b19..bef2e3c 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -7077,6 +7077,50 @@ impl<'a> Lower<'a> { let r = self.s.m.cast(c, op, a, self.s.t.i32); int(self, r) } + "v_permlane16_b32" | "v_permlanex16_b32" => { + // Each lane reads src0 of a lane of its own 32-lane half, + // picked by nibble (lane & 15) of {src2, src1}: within its + // own row of 16 (`v_permlane16`) or the other row of its + // half (`v_permlanex16`). The pick stays inside a half, so a + // console wave of 64 run as two host waves of 32 needs no + // exchange. + // shortcut: a source lane with EXEC clear is read as the host + // gives it (the console keeps vdst unless op_sel's fetch + // inactive bit is set). + self.cross_lane(false)?; + let x = s(self, 0)?; + let (s1, s2) = (s(self, 1)?, s(self, 2)?); + let i32t = self.s.t.i32; + let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let [k15, k8, k7, k2, k16, not31, not15] = + [15, 8, 7, 2, 16, !31, !15].map(|x| self.s.m.i32(x)); + let low = self.s.m.bin(c, Bin::And, lane, k15); + // nibble `low` of the 64-bit selector: src1 holds lanes 0-7 + let hi_word = self.s.m.cmp(c, pred::IUGE, low, k8); + let word = self.s.m.select(c, hi_word, s2, s1); + let n = self.s.m.bin(c, Bin::And, low, k7); + let sh = self.s.m.bin(c, Bin::Shl, n, k2); + let pick = self.s.m.bin(c, Bin::LShr, word, sh); + let pick = self.s.m.bin(c, Bin::And, pick, k15); + let row = if name == "v_permlanex16_b32" { + // the other row of this half + let half = self.s.m.bin(c, Bin::And, lane, not31); + let other = self.s.m.bin(c, Bin::And, lane, k16); + let other = self.s.m.bin(c, Bin::Xor, other, k16); + self.s.m.bin(c, Bin::Or, half, other) + } else { + self.s.m.bin(c, Bin::And, lane, not15) + }; + let from = self.s.m.bin(c, Bin::Or, row, pick); + let r = self.read_lane(x, from); + int(self, r) + } + "v_cvt_f32_f64" => { + let (lo, hi) = self.f64_pair(inst, 0)?; + let bits = self.f64_to_f32_bits(lo, hi); + let r = self.as_float(bits); + float(self, r) + } "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1" | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => { let mut a = s(self, 0)?; @@ -7094,12 +7138,6 @@ impl<'a> Lower<'a> { let r = self.s.m.cast(c, op, a, self.s.t.f32); float(self, r) } - "v_cvt_f32_f64" => { - let (lo, hi) = self.f64_pair(inst, 0)?; - let bits = self.f64_to_f32_bits(lo, hi); - let r = self.as_float(bits); - float(self, r) - } "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { // Each source is f32, or with op_sel_hi the low (op_sel: high) // f16 half; neg_hi is the absolute value here. @@ -7631,6 +7669,69 @@ impl<'a> Lower<'a> { self.s.m.bin(c, Bin::Or, lo, hi) } + /// The bits of the float nearest the double whose dwords are `lo` and + /// `hi`, on 32-bit integers: round to nearest even, infinities and NaN + /// kept (a NaN stays quiet), a result below the smallest normal float + /// signed zero (flushed, as the console's default float mode does). + // The flush-to-zero form of v_cvt_f32_f64: kept beside the IEEE form in use until the console's + // float mode for this instruction is checked. + #[allow(dead_code)] + fn f64_bits_to_f32_bits(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let k = |l: &mut Self, x: u32| l.s.m.i32(x); + let (k20, k29, k3, k23) = (k(self, 20), k(self, 29), k(self, 3), k(self, 23)); + let sign_mask = k(self, 0x8000_0000); + let sign = self.s.m.bin(c, Bin::And, hi, sign_mask); + let e = self.s.m.bin(c, Bin::LShr, hi, k20); + let e_mask = k(self, 0x7ff); + let e = self.s.m.bin(c, Bin::And, e, e_mask); + // The top 23 bits of the 52-bit mantissa, and the 29 below them. + let m_mask = k(self, 0x000f_ffff); + let mh = self.s.m.bin(c, Bin::And, hi, m_mask); + let mh = self.s.m.bin(c, Bin::Shl, mh, k3); + let ml = self.s.m.bin(c, Bin::LShr, lo, k29); + let m = self.s.m.bin(c, Bin::Or, mh, ml); + let rest_mask = k(self, 0x1fff_ffff); + let rest = self.s.m.bin(c, Bin::And, lo, rest_mask); + // Round to nearest even: up past half, or at half when odd. + let half = k(self, 0x1000_0000); + let one = k(self, 1); + let above = self.s.m.cmp(c, pred::IUGT, rest, half); + let at = self.s.m.cmp(c, pred::EQ, rest, half); + let odd = self.s.m.bin(c, Bin::And, m, one); + let zero = k(self, 0); + let odd = self.s.m.cmp(c, pred::NE, odd, zero); + let tie = self.s.m.bin(c, Bin::And, at, odd); + let up = self.s.m.bin(c, Bin::Or, above, tie); + let up = self.s.m.select(c, up, one, zero); + // Rebias the exponent (1023 → 127); a carry out of the mantissa + // steps the exponent, up to infinity. + let bias = k(self, 1023 - 127); + let e32 = self.s.m.bin(c, Bin::Sub, e, bias); + let ex = self.s.m.bin(c, Bin::Shl, e32, k23); + let normal = self.s.m.bin(c, Bin::Add, ex, m); + let normal = self.s.m.bin(c, Bin::Add, normal, up); + let normal = self.s.m.bin(c, Bin::Or, normal, sign); + // Exponents out of the float's range (signed, after rebiasing). + let inf = k(self, 0x7f80_0000); + let inf = self.s.m.bin(c, Bin::Or, inf, sign); + let k255 = k(self, 255); + let big = self.s.m.cmp(c, pred::SGE, e32, k255); + let small = self.s.m.cmp(c, pred::SLE, e32, zero); + let r = self.s.m.select(c, big, inf, normal); + let r = self.s.m.select(c, small, sign, r); + // Infinity and NaN (a NaN with any mantissa bit set stays a NaN). + let all = k(self, 0x7ff); + let special = self.s.m.cmp(c, pred::EQ, e, all); + let any = self.s.m.bin(c, Bin::Or, mh, ml); + let any = self.s.m.bin(c, Bin::Or, any, rest); + let nan = self.s.m.cmp(c, pred::NE, any, zero); + let quiet = k(self, 0x0040_0000); + let quiet = self.s.m.select(c, nan, quiet, zero); + let special_bits = self.s.m.bin(c, Bin::Or, inf, quiet); + self.s.m.select(c, special, special_bits, r) + } + /// The low and high dwords of an i64. fn split64(&mut self, x: V) -> (V, V) { let c = self.cur; diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index b667241..5f2b298 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -115,7 +115,7 @@ pub use rect::rect_list_gs; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, - set_view_heap_limit, + set_view_heap_limit, view_heap_limit, }; /// The loop limit without an override: 2^20. diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 4626982..28a36f1 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -113,11 +113,11 @@ pub(crate) struct Geometry { pub max_vertices: u32, } -/// The null slot a host view heap keeps at its end when the title's heap did not fit in it -/// (0: no limit). Shaders translated while it is set read that slot for any view index at or -/// past it: a host that caps its heap (NVIDIA at 1 000 000 views; a retail game's heap is -/// larger) hung its GPU on reads past the end (GPU-based validation: "descriptor heap index -/// out of bounds"), which AMD's driver forgives. +/// The null slot every host view heap keeps at its end (0: no limit). Shaders translated while +/// it is set read that slot for any view index at or past it. A read past a heap's end is +/// undefined: a host that caps its heap (NVIDIA at 1 000 000 views; a retail game's heap is +/// larger) hung its GPU (GPU-based validation: "descriptor heap index out of bounds"), and AMD +/// RDNA3 took a page fault and removed the device. static VIEW_LIMIT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); /// See [`VIEW_LIMIT`]: `null_slot` is the last slot of the host's view heap, kept null. @@ -125,6 +125,11 @@ pub fn set_view_heap_limit(null_slot: u32) { VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed); } +/// See [`VIEW_LIMIT`]: the null slot shaders translated now clamp view indices to (0: none). +pub fn view_heap_limit() -> u32 { + VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed) +} + pub(crate) struct Shader { pub m: Module, pub t: Types, diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 93a36be..f5c2014 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -308,6 +308,110 @@ fn packed_add_selects_halves_of_inline_constants() { } } +/// The float `v_cvt_f32_f64` gives for `x`: Rust's rounding (to nearest +/// even), with results below the smallest normal float flushed to signed +/// zero as the console's default float mode does. +fn cvt_f32_f64_reference(x: f64) -> u32 { + let r = x as f32; + if r.is_subnormal() || (r == 0.0 && x != 0.0) { + r.to_bits() & 0x8000_0000 + } else { + r.to_bits() + } +} + +#[test] +#[ignore = "expects results below the smallest normal float flushed to zero; the IEEE lowering (v_cvt_f32_f64_matches_ieee754) is kept until the console's mode is checked"] +fn v_cvt_f32_f64_rounds_to_nearest_even() { + // v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x0f) + let shader = build_valu_cs(&[vop1(0x00f, 0, vgpr(1))]); + let tie_even = 1.0f64 + f64::from(f32::EPSILON) / 2.0; // ties to 1.0 + let tie_odd = 1.0f64 + 1.5 * f64::from(f32::EPSILON); // ties up to 1 + 2 ulp + let values = [ + 0.0, + -0.0, + 1.0, + -2.5, + std::f64::consts::PI, + 1.0e-3, + 123_456_789.123, + tie_even, + tie_odd, + 1.0 + f64::from(f32::EPSILON) * 0.75, + f64::from(f32::MAX), + f64::from(f32::MAX) * 1.000_000_1, // rounds to infinity + 1.0e300, + -1.0e300, + 1.0e-40, // a float denormal: flushed + -1.0e-300, + f64::from(f32::MIN_POSITIVE), + f64::INFINITY, + f64::NEG_INFINITY, + f64::NAN, + ]; + let inputs: Vec<[u32; 4]> = values + .iter() + .map(|x| { + let b = x.to_bits(); + [b as u32, (b >> 32) as u32, 0, 0] + }) + .collect(); + run_cases(&shader, &inputs, |backend, i, _, got| { + let x = values[i]; + if x.is_nan() { + assert!(f32::from_bits(got).is_nan(), "{backend}: cvt({x}) = {got:#010x}, want NaN"); + return; + } + let want = cvt_f32_f64_reference(x); + assert_eq!(got, want, "{backend}: cvt({x:e}) = {got:#010x}, want {want:#010x}"); + }); +} + +/// The lane `v_permlane16_b32` (`cross` false) or `v_permlanex16_b32` reads +/// for `lane`, with selector dwords `s1` (lanes 0-7 of a row) and `s2`. +fn permlane_source(lane: u32, s1: u32, s2: u32, cross: bool) -> u32 { + let sel = u64::from(s1) | u64::from(s2) << 32; + let pick = (sel >> (4 * (lane & 15)) & 15) as u32; + let row = if cross { + (lane & !31) | ((lane & 16) ^ 16) + } else { + lane & !15 + }; + row | pick +} + +#[test] +fn v_permlane16_and_x16_read_the_lanes_their_selectors_pick() { + // 32 lanes, each with its lane number in v0; v1 = permute(v0, s0, s1); + // lane `read` of v1 into s12, then into v0 for the store. + let selectors: [(u32, u32); 3] = [ + (0x7654_3210, 0xfedc_ba98), // identity within the row + (0x89ab_cdef, 0x0123_4567), // reversed + (0x1111_1111, 0xf0f0_f0f0), // repeats + ]; + for (op, cross) in [(0x377u16, false), (0x378, true)] { + for read in [0u8, 5, 15, 16, 22, 31] { + let mut body = Vec::new(); + body.extend_from_slice(&vop3(op, 1, vgpr(0), sgpr(0), sgpr(1))); + // v_readlane_b32 s12, v1, read (inline constant 128 + read) + body.extend_from_slice(&vop3(0x360, 12, vgpr(1), 128 + u16::from(read), 0)); + body.push(vop1(0x001, 0, sgpr(12))); // v_mov_b32 v0, s12 + let shader = build_cs(&body, 32, 0); + let inputs: Vec<[u32; 4]> = selectors.iter().map(|&(a, b)| [a, b, 0, 0]).collect(); + // Cross-lane code declares WaveSize(32), which WARP's pipeline + // creation refuses: hardware only. + run_cases_on(&shader, &inputs, &[("hardware", false)], |backend, i, inp, got| { + let want = permlane_source(u32::from(read), inp[0], inp[1], cross); + assert_eq!( + got, want, + "{backend}: op {op:#x} selectors {:08x?}, lane {read}", + selectors[i] + ); + }); + } + } +} + #[test] fn v_med3_f32_matches_rdna2_with_nan() { // v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157) From a803c87c48078e57b296e06e08146d7ceca44530 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:29:47 -0500 Subject: [PATCH 152/445] Textures picked by index are looked at again after their upload (characters' skin and hair without colour in most launches) A texture a shader picks by index was uploaded once, when the title wrote its view, and again only if the view was rewritten or the runtime told of a remap. The title often fills the texture's memory only afterwards (its streaming reads land later), so the host copy kept what the memory held at the first look for the rest of the run: zeros. Which textures lost that race changed from launch to launch; the main character's face came out black and her hair pale in about three launches of four. Now a texture uploaded whole is looked at again after 4, 12, 40, 120 and 400 frames (a fingerprint of 48 KiB of its memory); a changed one is uploaded again and the looks start over. One test launch re-uploaded more than 6,000 textures this way. VICTORY_HEAP_RECHECK=0 turns it off. Known gap: the fingerprint samples the start, middle and end of the memory, so a texture whose other parts arrive later is still missed. Co-Authored-By: Claude Fable 5.2 --- crates/victory-gpu/src/descriptor/host.rs | 48 +++++++++++++++++- crates/victory-gpu/src/draw.rs | 61 ++++++++++++++++++++++- crates/victory-gpu/src/texture.rs | 40 +++++++++++++++ 3 files changed, 146 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 895074a..b2c27c5 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -289,6 +289,11 @@ struct Waiting { /// Bytes of its memory that were mapped when it was last uploaded /// without all of it there; 0: not uploaded yet. mapped: u64, + /// For a slot uploaded whole and looked at again + /// ([`TextureQueue::recheck`]): where its memory is (address, bytes), + /// the fingerprint it had at the upload, how many looks found it + /// unchanged, and the frame of the upload. A fingerprint of 0: none. + checked: (u64, u64, u64, u8, u64), } /// The queue of title slots whose texture view waits to be brought up to @@ -311,7 +316,7 @@ impl TextureQueue { } self.writes += 1; let write = self.writes; - self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0 }); + self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); } fn remove(&mut self, index: u32) { @@ -382,6 +387,24 @@ impl TextureQueue { } } + /// Slot `index` was uploaded whole from memory `at` (address, bytes) + /// with fingerprint `print`: looked at again from frame `due`, for a + /// title that fills a texture's memory after it wrote the view (the + /// `looks`-th such look; `uploaded` is the upload's frame). + #[allow(clippy::too_many_arguments)] + fn recheck(&mut self, index: u32, write: u64, due: u64, at: (u64, u64), print: u64, looks: u8, uploaded: u64) { + if let Some(w) = self.same(index, write) { + (w.due, w.looks, w.mapped) = (due, 1, 0); + w.checked = (at.0, at.1, print, looks, uploaded); + } + } + + /// What [`TextureQueue::recheck`] noted of slot `index`, if it is + /// waiting for such a look. + fn checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { + self.slots.get(&index).map(|w| w.checked).filter(|c| c.2 != 0) + } + /// The memory slot `index`'s texture lies in was mapped, unmapped or /// written in `frame`: the slot is looked at from frame `due` as one /// written now, whatever was known of it (a pass at work on it does @@ -390,7 +413,7 @@ impl TextureQueue { self.writes += 1; let write = self.writes; let due = self.slots.get(&index).map_or(due, |w| w.due.min(due)); - self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0 }); + self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); } /// Bytes of slot `index`'s memory that were mapped at its last upload @@ -845,6 +868,27 @@ impl HostHeap { } } + /// Title slot `index` was uploaded whole: see [`TextureQueue::recheck`]. + #[allow(clippy::too_many_arguments)] + pub(crate) fn texture_slot_recheck( + &self, + index: u32, + write: u64, + due: u64, + at: (u64, u64), + print: u64, + looks: u8, + uploaded: u64, + ) { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + textures.recheck(index, write, due, at, print, looks, uploaded); + } + + /// See [`TextureQueue::checked`]. + pub(crate) fn texture_slot_checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).checked(index) + } + /// Nothing to upload at title slot `index` now (its memory is not /// mapped, or no more of it than before): looked at again after 1, 2, /// 4, ... frames, at most `most`. diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 0142269..e135422 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -333,6 +333,21 @@ pub(crate) static HEAP_TEXTURES_WAITING: AtomicU64 = AtomicU64::new(0); /// Passes that made no texture because the card had no room /// (`crate::resource::room`), for the memory line. pub(crate) static HEAP_TEXTURES_FULL: AtomicU64 = AtomicU64::new(0); + +/// Frames after a whole upload of a texture picked by index at which its +/// memory is looked at again, each counted from the look before. +const RECHECK_FRAMES: [u64; 5] = [4, 12, 40, 120, 400]; + +/// Looks at uploaded textures picked by index that found the memory as it +/// was, and that found it changed (uploaded again), since the start. +pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; + +/// Whether textures picked by index are looked at again after their upload +/// (`VICTORY_HEAP_RECHECK=0`: no). +fn heap_recheck() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_RECHECK").is_none_or(|v| v != "0")) +} /// Times a placed texture's slot was passed over because its memory is not /// mapped. pub(crate) static HEAP_TEXTURES_AWAY: AtomicU64 = AtomicU64::new(0); @@ -1530,6 +1545,38 @@ impl State { // every 120 frames, changed or not; and asked by its first // page alone, one whose first page is the one missing counted // as not there.) + // A slot uploaded whole is looked at again a few times + // (`RECHECK_FRAMES`): the title writes a texture's view, and + // may fill the texture's memory itself only afterwards, with + // no descriptor write and nothing from the runtime to tell of + // it. The host copy then kept what the memory held at the + // first look for the rest of the run. The look reads 48 KiB; + // only a changed texture is uploaded again. + // `VICTORY_HEAP_RECHECK=0`: uploaded once, as before. + if let Some((at, len, print, looks, uploaded)) = host.texture_slot_checked(index) { + if crate::texture::fingerprint(at, len) == print { + HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed); + match RECHECK_FRAMES.get(usize::from(looks) + 1) { + Some(wait) => { + host.texture_slot_recheck(index, write, frame + wait, (at, len), print, looks + 1, uploaded) + } + None => host.texture_slot_done(index, write, None), + } + continue; + } + let n = HEAP_TEXTURES_RECHECKED[1].fetch_add(1, Ordering::Relaxed); + if n < 200 || n.is_multiple_of(1000) { + tracing::warn!( + slot = index, + address = format_args!("{at:#x}"), + bytes = len, + frames_after_upload = frame.saturating_sub(uploaded), + looks, + changed = n + 1, + "a texture picked by index changed after its upload with nothing to tell of it: uploaded again" + ); + } + } let mut partly = None; if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) { let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; @@ -1633,11 +1680,23 @@ impl State { // yet, makes it anew. (Kept for those until now: every partly // streamed texture of the heap held a staging buffer of its full // size for good.) + let memory = if again.is_none() && heap_recheck() { + crate::texture::staged_memory(resource) + } else { + None + }; crate::texture::unstage(resource); SPENT.fetch_add(bytes, Ordering::Relaxed); HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed); HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed); - host.texture_slot_done(index, write, again); + match memory { + // Whole and uploaded: looked at again (see above). + Some((at, len)) => { + let print = crate::texture::fingerprint(at, len); + host.texture_slot_recheck(index, write, frame + RECHECK_FRAMES[0], (at, len), print, 0, frame); + } + None => host.texture_slot_done(index, write, again), + } } } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 0512fd6..c8f35c9 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -814,6 +814,46 @@ pub(crate) fn unstage(resource: This) { } } +/// Where a staged title texture's memory is: address and bytes. +pub(crate) fn staged_memory(resource: This) -> Option<(u64, u64)> { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let (at, len) = map.as_ref()?.get(&(resource as usize))?.memory(); + Some((at as u64, len as u64)) +} + +/// A fingerprint of the title memory `[at, at + len)`, never 0: of all of +/// it up to 48 KiB, else of 16 KiB at its start, its middle and its end +/// (a texture streams in whole mips; the small ones lie first). Read +/// through the kernel, so pages not there count as zeros. +pub(crate) fn fingerprint(at: u64, len: u64) -> u64 { + const WINDOW: usize = 16 << 10; + thread_local! { + static READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + let len = len as usize; + let mut hasher = blake3::Hasher::new(); + READ.with(|read| { + let mut read = read.borrow_mut(); + read.resize(3 * WINDOW, 0); + let mut take = |from: usize, bytes: usize| { + read[..bytes].fill(0); + crate::host::copy_mapped(read.as_mut_ptr(), (at as usize + from) as *const u8, bytes, false); + hasher.update(&read[..bytes]); + }; + if len <= 3 * WINDOW { + take(0, len); + } else { + take(0, WINDOW); + take((len / 2) & !0xfff, WINDOW); + take(len - WINDOW, WINDOW); + } + }); + let hash = hasher.finalize(); + let mut first = [0u8; 8]; + first.copy_from_slice(&hash.as_bytes()[..8]); + u64::from_le_bytes(first) | 1 +} + /// Whether a title texture has a staging buffer: a list recorded its /// upload, and the lists that sample it check it at submission. pub(crate) fn is_staged(resource: This) -> bool { From 9fea7434cdc4de39ed111e647a34f3da8356dcb5 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 18:55:40 -0600 Subject: [PATCH 153/445] Streaming, copy queue, texture pools and a shader cache that survives rebuilds Textures and staging cut from 64 MB blocks; a kept view per page section and page lists read again until the title has filled them in; the GPU side told when streamed bytes land; results fetched over the copy queue (VICTORY_RELAY_COPY=1); the write-watch journal behind a reader-writer lock; the shader cache keyed by the translator's sources and `victory shaders`; helper lanes as in upstream 1733 (VICTORY_HELPER_OWN). Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/main.rs | 10 + apps/victory/src/translate.rs | 61 +++ crates/victory-gpu/Cargo.toml | 3 + crates/victory-gpu/build.rs | 45 ++ crates/victory-gpu/src/copystat.rs | 4 + crates/victory-gpu/src/host.rs | 166 +++++++- crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/pipeline/library.rs | 12 +- crates/victory-gpu/src/pool.rs | 456 +++++++++++++++++++++ crates/victory-gpu/src/resource.rs | 21 + crates/victory-gpu/src/shader_cache.rs | 101 +++-- crates/victory-gpu/src/shadow.rs | 8 +- crates/victory-gpu/src/texture.rs | 168 +++++++- crates/victory-gpu/src/watch.rs | 418 +++++++++++++------ crates/victory-hle/src/modules/d3d12x.rs | 14 + crates/victory-hle/src/modules/dstorage.rs | 54 ++- crates/victory-hle/src/modules/xmem.rs | 240 ++++++++++- crates/victory-shader/src/emit/lower.rs | 37 +- crates/victory-shader/src/emit/mod.rs | 36 +- crates/victory-shader/src/emit/shader.rs | 5 + 20 files changed, 1629 insertions(+), 232 deletions(-) create mode 100644 crates/victory-gpu/build.rs create mode 100644 crates/victory-gpu/src/pool.rs diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index 842ce77..a04655c 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -85,6 +85,15 @@ enum Command { #[arg(long)] jobs: Option, }, + /// Translate every shader found (as `translate` finds them) into the + /// shader cache, so that no run has to: a few minutes, once per change + /// of the translator. + Shaders { + paths: Vec, + /// Worker threads (default: every logical core). + #[arg(long)] + jobs: Option, + }, /// Prepare, map and bind a title executable; with --execute, run it. Run { exe: PathBuf, @@ -163,6 +172,7 @@ fn main() -> Result<()> { } translate::run(paths, validate, pipelines, list, jobs) } + Command::Shaders { paths, jobs } => translate::precompile(paths, jobs), Command::Run { exe, unimplemented, diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 1d13ae2..ddc2bd3 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -306,6 +306,67 @@ pub fn run( Ok(()) } +/// Every shader found into the cache runs translate from. +pub fn precompile(paths: Vec, jobs: Option) -> Result<()> { + let cfg = victory_core::Config::load()?; + victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + let paths = crate::default_paths(paths)?; + let threads = + jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get())); + let started = std::time::Instant::now(); + let seen = Mutex::new(HashSet::new()); + let done = AtomicUsize::new(0); + let failed = Mutex::new(BTreeMap::::new()); + for root in &paths { + for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) { + if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { + continue; + } + let Ok(data) = std::fs::read(entry.path()) else { + continue; + }; + let jobs = sources(&data); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads.min(jobs.len()) { + s.spawn(|| { + while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + let Some(bytes) = job.bytes() else { continue }; + let hash = blake3::hash(&bytes); + if !lock(&seen).insert(hash) { + continue; + } + match victory_hle::modules::d3d12x::precompile(&bytes) { + Ok(_) => { + let n = done.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_multiple_of(1000) { + println!("{n} shaders in the cache, {:.0} s", started.elapsed().as_secs_f64()); + } + } + Err(why) => { + let mut failed = lock(&failed); + failed.entry(why).or_insert_with(|| (0, hash.to_hex()[..16].to_owned())).0 += 1; + } + } + } + }); + } + }); + } + } + let failed = failed.into_inner().unwrap_or_else(|e| e.into_inner()); + println!( + "{} shaders in the cache, {} do not translate, {:.0} s", + done.load(Ordering::Relaxed), + failed.values().map(|f| f.0).sum::(), + started.elapsed().as_secs_f64() + ); + for (why, (n, hash)) in failed { + println!(" {n:>5} {why} (e.g. {hash})"); + } + Ok(()) +} + fn translate( source: &Source, path: &Path, diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index a24dd1a..663377c 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -16,6 +16,9 @@ victory-formats.workspace = true victory-pipeline.workspace = true victory-shader.workspace = true +[build-dependencies] +blake3.workspace = true + [dev-dependencies] tempfile.workspace = true diff --git a/crates/victory-gpu/build.rs b/crates/victory-gpu/build.rs new file mode 100644 index 0000000..9dcfa61 --- /dev/null +++ b/crates/victory-gpu/build.rs @@ -0,0 +1,45 @@ +//! Fingerprints the shader translator, so that cached translations +//! (`src/shader_cache.rs`) last until the translator itself changes and not +//! only until the next build of anything. + +use std::path::{Path, PathBuf}; + +fn files(dir: &Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let path = entry.path(); + if path.is_dir() { + files(&path, out); + } else { + out.push(path); + } + } +} + +fn main() { + let here = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default()); + let crates = here.join(".."); + let root = crates.join(".."); + // The translator, what it is built from, and the form entries are kept in. + let mut all = vec![ + crates.join("victory-shader/Cargo.toml"), + here.join("src/shader_cache.rs"), + root.join("Cargo.lock"), + root.join("rust-toolchain.toml"), + ]; + let source = crates.join("victory-shader/src"); + println!("cargo:rerun-if-changed={}", source.display()); + files(&source, &mut all); + all.sort(); + let mut hash = blake3::Hasher::new(); + for path in &all { + println!("cargo:rerun-if-changed={}", path.display()); + // Names and line endings as they are in every checkout. + let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned(); + let bytes: Vec = std::fs::read(path).unwrap_or_default().into_iter().filter(|&b| b != 13).collect(); + hash.update(name.as_bytes()); + hash.update(&(bytes.len() as u64).to_le_bytes()); + hash.update(&bytes); + } + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rustc-env=VICTORY_TRANSLATOR={}", hash.finalize().to_hex()); +} diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 292d995..9e4c202 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -740,6 +740,10 @@ fn log_memory() { mb(card[0]), mb(card[3]), ); + { + let [textures, staging] = crate::pool::memory(); + tracing::info!("memory in blocks (VICTORY_TEXTURE_POOL=0 turns them off): {textures} MB of textures, {staging} MB of their staging buffers"); + } tracing::info!( "memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \ {:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \ diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 823f0c6..b9a6e5e 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1547,6 +1547,9 @@ struct CardPlan { /// The lists of ours the plan recorded (whether the compare, the /// list), given back by `Host::card_done`. lists: Vec<(bool, Prelude)>, + /// With [`relay`]: the number of the send to copies in the card's memory + /// that the submission ran behind ([`QUEUE_ORDER`]). + sent_as: u64, } /// One piece of submission-time work, in recorded order. @@ -1778,6 +1781,27 @@ fn relay_exact() -> bool { *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_some_and(|v| v == "2")) } +/// Whether the pieces the relay fetches from the card's memory come over the +/// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that +/// draws. +/// +/// On the drawing queue a fetch runs behind whatever was sent meanwhile, +/// and with the relay that is most of a frame: the thread that lands flights +/// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all, +/// a few milliseconds of copying, and everything that waits for a landing +/// (the title's fences, reads of memory flights may write) waited with it. +/// +/// What changes: the fetch runs when its flights are done and beside later +/// submissions, so of the sends of title bytes it is only known to have run +/// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent +/// later are left out of the merge (`Shadow::card_merge_relay`): they are +/// the title's, newer than what the flights wrote. A later flight's bytes +/// may be in what is fetched, as before. +fn relay_copy() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1")) +} + /// Told when something joins [`LINE`], for the thread that lands flights /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at /// what queues hold. @@ -2041,6 +2065,74 @@ fn late_blocked(runs: &[&HostList]) -> Option { blocked_by(&written, runs, true) } +/// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for +/// flights when the title itself wrote the memory since they were given it +/// (`VICTORY_FILL_TITLE=1`; off by default). +/// +/// The title's 174 MB heap is declared written as a whole (a root view has +/// no size), and the title keeps a ring of constants in it: one fill of 480 +/// bytes a frame, at a new place each time, waited for every flight's +/// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits +/// named). The title writes those bytes just before the draw that reads +/// them, which takes the block's guard off ([`crate::watch::written_since_taken`]). +/// +/// Or no shader's write went into that page in the last 600 frames +/// ([`crate::watch::landed_lately`]): the first alone left two thirds of +/// the wait, for constants at the end of a 64 KiB page that the title wrote +/// before the page was taken. +/// +/// What can go wrong: a constant a flight's shader really writes, in a +/// block that the title (or an earlier flight's copy-back) also wrote, or +/// for the first time, is read as it was before that flight. +fn fill_is_titles(src: usize, len: usize) -> bool { + const SMALL: usize = 64 << 10; + static ON: OnceLock = OnceLock::new(); + let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1")); + on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600)) +} + +/// Diagnostics: the reads that made a submission wait for flights: what +/// kind, where, how much, and the declared write it lies in; how often and +/// how long the wait was. +#[cfg(feature = "diagnostics")] +type Blame = std::collections::HashMap<(&'static str, usize, usize, usize, usize), (u64, u64)>; +#[cfg(feature = "diagnostics")] +static BLAME: Mutex> = Mutex::new(None); +#[cfg(feature = "diagnostics")] +static BLAMED: Mutex> = Mutex::new(None); + +#[cfg(feature = "diagnostics")] +fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) { + let i = written.partition_point(|r| r.1 <= at); + let (from, to) = written.get(i).copied().unwrap_or((0, 0)); + *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = Some((kind, at, len, from, to - from)); +} + +/// The wait for what [`blame`] last named took `us`. +#[cfg(feature = "diagnostics")] +fn blamed(us: u64) { + if let Some(key) = BLAMED.lock().unwrap_or_else(|e| e.into_inner()).take() { + let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner()); + let e = all.get_or_insert_with(Default::default).entry(key).or_insert((0, 0)); + e.0 += 1; + e.1 += us; + } +} + +#[cfg(feature = "diagnostics")] +fn log_blame(frames: f64) { + let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default(); + let mut all: Vec<_> = all.into_iter().collect(); + all.sort_unstable_by_key(|(_, (_, us))| std::cmp::Reverse(*us)); + for ((kind, at, len, from, size), (n, us)) in all.into_iter().take(8) { + tracing::info!( + "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} {at:#x}+{len:#x}, in shader writes declared over {from:#x}+{size:#x}", + us as f64 / 1e3 / frames, + n as f64 / frames + ); + } +} + /// [`late_blocked`] against `written`, the title memory flights' shaders /// may write (in order, joined); `count` whether the kind of read is /// counted for the frame line. @@ -2052,17 +2144,26 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op for step in &list.deferred().copies { match step { &Step::Copy(dst, src, len) => { - if touches(written, src, src + len) || touches(written, dst, dst + len) { + let read = touches(written, src, src + len) && !fill_is_titles(src, len); + if read || touches(written, dst, dst + len) { if count { LATE_STATS[15].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + if read { + blame("a buffer copy's source", written, src, len); + } else { + blame("a buffer copy's destination", written, dst, len); + } } return Some(WHY_READ); } } &Step::Fill(_, src, len) => { - if touches(written, src, src + len) { + if touches(written, src, src + len) && !fill_is_titles(src, len) { if count { LATE_STATS[16].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + blame("a fill of upload memory", written, src, len); } return Some(WHY_READ); } @@ -2072,6 +2173,8 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op if touches(written, at, at + len) { if count { LATE_STATS[17].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + blame("a texture", written, at, len); } return Some(WHY_READ); } @@ -2316,6 +2419,8 @@ fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) { LATE_STATS[12].fetch_add(us, Ordering::Relaxed); LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed); SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + blamed(us); } /// What the thread that lands flights fetches card copies' pieces with @@ -2323,6 +2428,8 @@ fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) { /// behind the submission lock), and the memory the pieces come down to. struct RelayFetch { list: Prelude, + /// With [`relay_copy`]: the card's copy queue, which `list` is for. + queue: Option, fence: ID3D12Fence, event: HANDLE, /// The last value signalled on `fence`. @@ -3096,6 +3203,7 @@ impl Host { check: None, _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(), lists: used, + sent_as, }; // Each byte once, as the copy-back joins the declared ranges. The // results go behind those of plans still in the air. @@ -3212,13 +3320,36 @@ impl Host { /// The relay's own list, fence, event for [`Host::relay_card_back`]. fn make_relay_fetch(&self) -> Option { - let list = self.make_prelude()?; + // SAFETY: plain object creation. + let copying = relay_copy().then(|| unsafe { + (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> { + let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?; + let list: ID3D12GraphicsCommandList = + self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?; + list.Close()?; + let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COPY, + Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0, + ..Default::default() + })?; + Ok(((allocator, list), queue)) + })() + }); + let (list, queue) = match copying { + Some(Ok((list, queue))) => (list, Some(queue)), + Some(Err(e)) => { + tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue"); + (self.make_prelude()?, None) + } + None => (self.make_prelude()?, None), + }; // SAFETY: plain objects of our own. unsafe { let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; let event = CreateEventW(None, false, false, None).ok()?; Some(RelayFetch { list, + queue, fence, event, sent: 0, @@ -3278,14 +3409,22 @@ impl Host { } } } - if pieces.is_empty() { - // Nothing to fetch: every send so far is older than the next fetch. - crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); - return; - } if fetch.is_none() { *fetch = self.make_relay_fetch(); } + // 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.sent_as).max().unwrap_or(0); + if pieces.is_empty() { + // Nothing to fetch: every send so far is older than the next + // fetch, if that goes to the queue the sends went to. + let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) { + true => behind, + false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()), + }; + crate::shadow::relay_fetched(after); + return; + } let Some(f) = fetch.as_mut() else { fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)")); }; @@ -3298,6 +3437,7 @@ impl Host { }; f.sent += 1; let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent); + let copy_queue = f.queue.clone(); let waiting = std::time::Instant::now(); // SAFETY: the list's last run was waited for by this thread; live // buffers (the copies are held by the plans); the fence and the @@ -3311,6 +3451,13 @@ impl Host { } list.Close()?; let lists = [Some(list.cast::()?)]; + if let Some(queue) = ©_queue { + queue.ExecuteCommandLists(&lists); + queue.Signal(&fence, sent)?; + fence.SetEventOnCompletion(sent, event)?; + WaitForSingleObject(event, INFINITE); + return Ok(behind); + } // In the order of the queue: the sends of title bytes so // far are ahead of this fetch, every later one behind it. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()); @@ -5848,6 +5995,7 @@ impl Meter { ); #[cfg(feature = "diagnostics")] { + log_blame(frames); crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64); for (why, n) in drops.iter().take(40) { tracing::info!( @@ -6509,4 +6657,4 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at ); } } - + diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index db53f11..911e8fb 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -37,6 +37,8 @@ pub mod list; pub mod object; pub mod pipeline; #[cfg(windows)] +mod pool; +#[cfg(windows)] mod primitive; pub mod query; pub mod queue; diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 7047331..fdb5938 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -607,7 +607,9 @@ pub(crate) fn save(now: bool) { size } }; - let used: Vec = USED.lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().cloned().collect(); + // Through `used`: a process that asked for none yet (`victory shaders`) + // must not write the earlier runs' list over with nothing. + let used: Vec = used().iter().flatten().cloned().collect(); let library_written = if bytes > 0 { replace_library(dir, &tmp) } else { Ok(()) }; if bytes > 0 && library_written.is_ok() { // In place unless the system refused and the new one waits beside it. @@ -694,7 +696,15 @@ fn used() -> std::sync::MutexGuard<'static, Option>> { } /// Whether the title pipeline with `key` was requested in this or an earlier run. +/// +/// `VICTORY_EARLY_ALL=1`: every title pipeline is started at creation, +/// requested before or not, so that the driver's own cache holds it for +/// later runs. pub(crate) fn wanted_early(key: &str) -> bool { + static ALL: OnceLock = OnceLock::new(); + if *ALL.get_or_init(|| std::env::var_os("VICTORY_EARLY_ALL").is_some_and(|v| v == "1")) { + return true; + } used().as_ref().is_some_and(|s| s.contains(key)) } diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs new file mode 100644 index 0000000..32b3bfb --- /dev/null +++ b/crates/victory-gpu/src/pool.rs @@ -0,0 +1,456 @@ +//! Host memory for the textures the title fills, and for their staging +//! buffers, cut from blocks made once. +//! +//! Each such texture had an allocation of its own and its staging buffer +//! another. On an RX 7900 XTX an allocation takes about 310 microseconds +//! whatever its size, on one thread (`texture::allocation_costs`), and a +//! texture cut from a block 6: the pass that makes the textures shaders +//! pick by index (`draw.rs` `heap_textures`) got through 350-500 of the +//! 24,000 queued when the world loads in each of its 250 ms turns, some +//! forty seconds of a world without its textures. +//! `VICTORY_TEXTURE_POOL=0` makes every one an allocation of its own again. +//! +//! A piece given back is used again only two seconds later (nothing the card +//! was told before that is still running: Windows resets a card that takes +//! that long over one submission), and by then no list names it (the owners' rule, as for allocations of their own): a +//! texture's piece comes back when the last reference to the host texture +//! goes (an object of ours the texture holds says so), a staging buffer's +//! when the last list that recorded its copy is reset. + +use std::collections::{BTreeMap, VecDeque}; +use std::ffi::c_void; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU32, Ordering}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::{GUID, HRESULT, IUnknown, Interface}; + +/// Bytes of a block; pieces of more than half of one are not pooled. +const BLOCK: u64 = 64 << 20; +/// Blocks with nothing in them that are kept. +const SPARE: usize = 2; +/// Milliseconds until a piece given back is used again. (It was three +/// frames, a tenth of a second while the title shows a loading screen at 30 +/// a second, with up to 18 submissions in the air.) +const REST: u64 = 2500; + +fn now() -> u64 { + crate::host::now_ms() +} + +pub(crate) fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_POOL").is_none_or(|v| v != "0")) +} + +/// The free ranges of a block: start and length, never two that touch. +struct Ranges(BTreeMap); + +impl Ranges { + fn new(size: u64) -> Ranges { + Ranges(BTreeMap::from([(0, size)])) + } + + /// The lowest place for `len` bytes at a multiple of `align`. + fn take(&mut self, len: u64, align: u64) -> Option { + let (start, size, at) = self.0.iter().find_map(|(&start, &size)| { + let at = start.next_multiple_of(align); + (at + len <= start + size).then_some((start, size, at)) + })?; + self.0.remove(&start); + if at > start { + self.0.insert(start, at - start); + } + if at + len < start + size { + self.0.insert(at + len, start + size - at - len); + } + Some(at) + } + + fn give(&mut self, mut start: u64, mut len: u64) { + if let Some((&before, &size)) = self.0.range(..start).next_back() + && before + size == start + { + self.0.remove(&before); + (start, len) = (before, len + size); + } + if let Some(size) = self.0.remove(&(start + len)) { + len += size; + } + self.0.insert(start, len); + } + + fn whole(&self, size: u64) -> bool { + self.0.get(&0) == Some(&size) + } +} + +/// A part of a block. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Piece { + block: usize, + start: u64, + len: u64, +} + +struct Block { + memory: B, + free: Ranges, + /// The end of the highest piece ever taken: above it the memory is as + /// it was made (zeros). + used_to: u64, +} + +struct Pool { + /// `None`: a block let go, its place to be used again. + blocks: Vec>>, + /// Pieces given back, and when each may be used again. + resting: VecDeque<(u64, Piece)>, +} + +impl Pool { + const fn new() -> Pool { + Pool { blocks: Vec::new(), resting: VecDeque::new() } + } + + /// A piece of `len` bytes and the memory it lies in, and whether that + /// part was ever used before; `make` makes a block when none has room. + fn take(&mut self, len: u64, align: u64, now: u64, make: impl FnOnce() -> Option) -> Option<(Piece, B, bool)> { + if len == 0 || len > BLOCK / 2 { + return None; + } + self.rested(now); + let mut found = None; + for (i, block) in self.blocks.iter_mut().enumerate() { + if let Some(block) = block + && let Some(start) = block.free.take(len, align) + { + found = Some((i, start)); + break; + } + } + let (i, start) = match found { + Some(found) => found, + None => { + let mut block = Block { memory: make()?, free: Ranges::new(BLOCK), used_to: 0 }; + let start = block.free.take(len, align)?; + let i = match self.blocks.iter().position(Option::is_none) { + Some(i) => i, + None => { + self.blocks.push(None); + self.blocks.len() - 1 + } + }; + self.blocks[i] = Some(block); + (i, start) + } + }; + let block = self.blocks[i].as_mut()?; + let again = start < block.used_to; + block.used_to = block.used_to.max(start + len); + Some((Piece { block: i, start, len }, block.memory.clone(), again)) + } + + fn give(&mut self, piece: Piece, now: u64) { + self.resting.push_back((now + REST, piece)); + } + + /// Makes the pieces that rested long enough free, and lets go of empty + /// blocks past [`SPARE`]. + fn rested(&mut self, now: u64) { + let mut any = false; + while let Some(&(ready, piece)) = self.resting.front() + && ready <= now + { + self.resting.pop_front(); + if let Some(block) = self.blocks[piece.block].as_mut() { + block.free.give(piece.start, piece.len); + any |= block.free.whole(BLOCK); + } + } + if any { + let mut spare = 0; + for block in &mut self.blocks { + if block.as_ref().is_some_and(|b| b.free.whole(BLOCK)) { + spare += 1; + if spare > SPARE { + *block = None; + } + } + } + } + } + + fn blocks(&self) -> usize { + self.blocks.iter().flatten().count() + } +} + +/// A mapped upload buffer's memory. +#[derive(Clone)] +struct Upload(ID3D12Resource, *mut u8); +// SAFETY: the mapping is written by the owners of its pieces, each its own. +unsafe impl Send for Upload {} + +static TEXTURES: Mutex> = Mutex::new(Pool::new()); +static STAGING: Mutex> = Mutex::new(Pool::new()); + +fn lock(m: &'static Mutex) -> std::sync::MutexGuard<'static, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// For the memory line: blocks of textures and of staging buffers, in MiB. +#[cfg(feature = "diagnostics")] +pub(crate) fn memory() -> [u64; 2] { + [lock(&TEXTURES).blocks() as u64 * (BLOCK >> 20), lock(&STAGING).blocks() as u64 * (BLOCK >> 20)] +} + +/// Part of a block of mapped upload memory, back in the pool when dropped. +pub(crate) struct StagingPiece(Piece); + +impl Drop for StagingPiece { + fn drop(&mut self) { + lock(&STAGING).give(self.0, now()); + } +} + +/// `bytes` of upload memory, all zeros: the buffer it lies in, where in +/// that buffer, and its mapping. `None`: not pooled. +pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPiece, ID3D12Resource, u64, *mut u8)> { + if !on() { + return None; + } + // Copies from a buffer begin at multiples of 512. + let bytes = bytes.next_multiple_of(512); + let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || { + let (buffer, data) = host.upload_buffer(BLOCK)?; + crate::host::name(&buffer, || "staging of textures (a block)".into()); + Some(Upload(buffer, data)) + })?; + let owned = StagingPiece(piece); + // SAFETY: the piece lies in the block's mapping. + let data = unsafe { memory.1.add(piece.start as usize) }; + if again { + // What is not detiled into it (an unmapped texture) uploads zeros, + // as from a buffer of its own. + // SAFETY: the piece is ours alone. + unsafe { std::ptr::write_bytes(data, 0, bytes as usize) }; + } + Some((owned, memory.0, piece.start, data)) +} + +/// An object the host texture holds and releases when it goes: its piece +/// is free then. +#[repr(C)] +struct Reclaim { + methods: &'static [*const (); 3], + references: AtomicU32, + piece: Piece, +} + +struct Methods([*const (); 3]); +// SAFETY: function addresses only. +unsafe impl Sync for Methods {} + +static RECLAIM: Methods = Methods([query as *const (), add_ref as *const (), release as *const ()]); + +unsafe extern "system" fn query(this: *mut c_void, iid: *const GUID, out: *mut *mut c_void) -> HRESULT { + const E_NOINTERFACE: HRESULT = HRESULT(0x8000_4002_u32 as i32); + // SAFETY: COM's arguments. + unsafe { + if out.is_null() { + return HRESULT(0x8000_4003_u32 as i32); + } + if iid.as_ref().is_some_and(|iid| *iid == IUnknown::IID) { + add_ref(this); + *out = this; + return HRESULT(0); + } + *out = std::ptr::null_mut(); + } + E_NOINTERFACE +} + +unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + // SAFETY: one of ours, alive while a reference to it is. + unsafe { (*this.cast::()).references.fetch_add(1, Ordering::Relaxed) + 1 } +} + +unsafe extern "system" fn release(this: *mut c_void) -> u32 { + // SAFETY: as above; the last reference frees the box it was made as. + unsafe { + let left = (*this.cast::()).references.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { + let gone = Box::from_raw(this.cast::()); + lock(&TEXTURES).give(gone.piece, now()); + } + left + } +} + +/// Makes `texture` give `piece` back when the last reference to it goes. +fn give_back_with(texture: &ID3D12Resource, piece: Piece) { + const KEY: GUID = GUID::from_u128(0x6f0e2f0c_5a59_4b1e_9a3f_7f4d2c9be713); + let made = Box::into_raw(Box::new(Reclaim { methods: &RECLAIM.0, references: AtomicU32::new(1), piece })); + // SAFETY: a COM object of ours with one reference, which this takes and + // drops at the end; the texture takes its own. + unsafe { + let object = IUnknown::from_raw(made.cast()); + if texture.SetPrivateDataInterface(&KEY, &object).is_err() { + // Never given back: the piece stays taken, nothing is reused + // under a texture that may be alive. + std::mem::forget(object); + } + } +} + +/// A texture of `desc` (no target, depth or unordered access) in a block; +/// `None`: not pooled, or the host refused. +/// +/// # Safety +/// `desc` is a valid description. +pub(crate) unsafe fn texture( + device: &ID3D12Device, + desc: *const D3D12_RESOURCE_DESC, + state: D3D12_RESOURCE_STATES, +) -> Option { + if !on() { + return None; + } + // Small textures lie at multiples of 4 KiB where the host allows it + // (the top mip is 64 KiB at most): 64 KiB each otherwise. + // SAFETY: the caller's description. + let mut d = unsafe { *desc }; + d.Alignment = u64::from(D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT); + // SAFETY: plain queries. + let mut info = unsafe { device.GetResourceAllocationInfo(0, &[d]) }; + if info.SizeInBytes == u64::MAX || info.Alignment != d.Alignment { + d.Alignment = 0; + info = unsafe { device.GetResourceAllocationInfo(0, &[d]) }; + } + if info.SizeInBytes == u64::MAX { + return None; + } + let (piece, heap, _) = lock(&TEXTURES).take(info.SizeInBytes, info.Alignment.max(1), now(), || { + let desc = D3D12_HEAP_DESC { + SizeInBytes: BLOCK, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut heap: Option = None; + // SAFETY: plain creation. + if let Err(e) = unsafe { device.CreateHeap(&desc, &mut heap) } { + tracing::warn!(error = %e, "no block of texture memory"); + } + heap + })?; + let mut made: Option = None; + // SAFETY: the piece is no one else's; the heap lives while a piece of + // it is taken. + let result = unsafe { device.CreatePlacedResource(&heap, piece.start, &d, state, None, &mut made) }; + match (result, made) { + (Ok(()), Some(made)) => { + give_back_with(&made, piece); + Some(made) + } + _ => { + lock(&TEXTURES).give(piece, now()); + None + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ranges_are_cut_aligned_and_join_again() { + let mut r = Ranges::new(1024); + assert_eq!(r.take(100, 64), Some(0)); + assert_eq!(r.take(100, 64), Some(128)); + assert_eq!(r.take(28, 4), Some(100)); + assert_eq!(r.take(2000, 4), None); + r.give(128, 100); + r.give(0, 100); + assert!(!r.whole(1024)); + r.give(100, 28); + assert!(r.whole(1024)); + } + + #[test] + fn pieces_never_overlap_and_rest_before_they_are_used_again() { + let mut pool: Pool = Pool::new(); + let made = std::cell::Cell::new(0); + let make = || { + made.set(made.get() + 1); + Some(made.get()) + }; + let mut taken: Vec = Vec::new(); + for i in 0..500u64 { + let (p, _, again) = pool.take(65536 * (1 + i % 7), 65536, 0, make).unwrap(); + assert!(!again); + assert!(taken.iter().all(|q| q.block != p.block || p.start + p.len <= q.start || q.start + q.len <= p.start)); + taken.push(p); + } + let blocks = pool.blocks(); + assert!(blocks >= 2); + // Given back at 10: not used again before 10 + REST. + let first = taken[0]; + pool.give(first, 10); + let (p, _, _) = pool.take(first.len, 65536, 10 + REST - 1, make).unwrap(); + assert_ne!((p.block, p.start), (first.block, first.start)); + let (q, _, again) = pool.take(first.len, 65536, 10 + REST, make).unwrap(); + assert_eq!((q.block, q.start, again), (first.block, first.start, true)); + // Everything back: the empty blocks past the spare ones go. + for p in taken.drain(1..).chain([p, q]) { + pool.give(p, 20); + } + pool.rested(20 + REST); + assert_eq!(pool.blocks(), blocks.min(SPARE)); + // Too big for a block, and a block that cannot be made. + assert!(pool.take(BLOCK, 65536, 30, make).is_none()); + let mut none: Pool = Pool::new(); + assert!(none.take(65536, 65536, 0, || None).is_none()); + } + + /// A pooled texture's piece comes back when its last reference goes, not + /// before; its staging piece begins as zeros. + #[test] + fn a_texture_gives_its_piece_back_when_it_goes() { + let Some(host) = crate::host::host() else { return }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + // SAFETY: a valid description. + let Some(t) = (unsafe { texture(&host.device, &desc, D3D12_RESOURCE_STATE_COMMON) }) else { return }; + assert_eq!(crate::host::references(&t), 1, "what the texture holds is no reference to it"); + let resting = || lock(&TEXTURES).resting.len(); + let before = resting(); + let other = t.clone(); + drop(t); + assert_eq!(resting(), before); + drop(other); + assert_eq!(resting(), before + 1); + // SAFETY: the piece's mapping, 4096 bytes of it ours. + unsafe { + let (piece, _, at, data) = staging(host, 4096).unwrap(); + assert!(at.is_multiple_of(512)); + std::ptr::write_bytes(data, 0xAB, 4096); + drop(piece); + lock(&STAGING).rested(u64::MAX); + let (_piece, _, _, data) = staging(host, 4096).unwrap(); + assert!((0..4096).all(|i| *data.add(i) == 0)); + // SAFETY: plain query. + assert!(host.device.GetDeviceRemovedReason().is_ok()); + } + } +} diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index e9cd518..3f04b27 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1687,6 +1687,27 @@ fn host_texture( Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + // A texture the title fills, whose every subresource is uploaded before + // anything reads it: cut from a block (what the piece held before shows + // in no texel). + if fills(desc) + && d.sample_count <= 1 + && clear_value.is_none() + && texture_layout(desc).is_some_and(|t| !t.planes[0].layout.desc.swizzle.xor()) + // SAFETY: the description has the host layout, as below. + && let Some(t) = unsafe { + crate::pool::texture( + &host.device, + (&raw const d).cast(), + D3D12_RESOURCE_STATES(crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32), + ) + } + { + crate::host::name(&t, || { + format!("texture {}x{} f{} flags {:#x} (in a block)", d.width, d.height, d.format, d.flags) + }); + return Some(t); + } let mut texture: Option = None; // SAFETY: the description has the host layout (checked size, same // fields); the out pointer is ours. diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index eabd0f3..18d6b4d 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -1,7 +1,7 @@ //! Translated shaders kept on disk (decision 0003): under the configured -//! cache folder, keyed by the container's content and by the VIctory build -//! that translated it (the BLAKE3 of our executable), so a rebuilt -//! translator never serves an old translation. Entries go through +//! cache folder, keyed by the container's content and by the translator +//! (the BLAKE3 of its sources) and its settings, so a changed translator +//! never serves an old translation. Entries go through //! `victory-pipeline`'s content-addressed cache, which writes them //! atomically; an entry that does not read back is translated again. //! @@ -37,13 +37,13 @@ pub(crate) fn counts() -> (u64, u64) { (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed)) } -/// What identifies this build: the BLAKE3 of our executable file and of -/// the translation settings it runs with (the loop limit, which a -/// diagnostics build can change at run time). -fn build() -> &'static [u8; 32] { - static BUILD: OnceLock<[u8; 32]> = OnceLock::new(); - BUILD.get_or_init(|| { - let exe = std::env::current_exe().and_then(std::fs::read); +/// What identifies a translation beside its container: the translator +/// (the BLAKE3 of its sources, `build.rs`), the settings it runs with, and +/// what it was told of the host. Not our executable: a rebuild of anything +/// else used to translate every shader again. +fn build() -> [u8; 32] { + static FIXED: OnceLock> = OnceLock::new(); + let fixed = FIXED.get_or_init(|| { let limit = victory_shader::emit::loop_limit(); if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT { tracing::warn!( @@ -51,42 +51,53 @@ fn build() -> &'static [u8; 32] { "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner" ); } - match exe { - Ok(mut bytes) => { - bytes.extend_from_slice(&limit.to_le_bytes()); - // Which group barriers wait is part of the translation too. - bytes.push(victory_shader::emit::group_sync()); - // So are the switches that pick the form of a wave64 program: - // without them here a run with `VICTORY_WAVE_WIDE=0` was - // served the translations an earlier run of the same - // executable had cached with the switch unset. - for name in [ - "VICTORY_WAVE_WIDE", - "VICTORY_WAVE_DEEP_SKIPS", - "VICTORY_WAVE_OWN_BITS", - "VICTORY_F16_NEAREST", - ] { - bytes.extend_from_slice(name.as_bytes()); - bytes.push(b'='); - if let Some(value) = std::env::var_os(name) { - bytes.extend_from_slice(value.as_encoded_bytes()); - } - bytes.push(0); - } - // And which clean-up passes ran over the translated code. - bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes()); - *blake3::hash(&bytes).as_bytes() - } - Err(e) => { - // Without it no entry can be trusted: a fresh key per run. - tracing::warn!(error = %e, "cannot read our executable; shader cache unused"); - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default(); - *blake3::hash(&now.as_nanos().to_le_bytes()).as_bytes() + let mut bytes = env!("VICTORY_TRANSLATOR").as_bytes().to_vec(); + bytes.extend_from_slice(&limit.to_le_bytes()); + // Which group barriers wait is part of the translation too. + bytes.push(victory_shader::emit::group_sync()); + // So are the switches that pick the form of a wave64 program: + // without them here a run with `VICTORY_WAVE_WIDE=0` was + // served the translations an earlier run of the same + // executable had cached with the switch unset. + for name in [ + "VICTORY_WAVE_WIDE", + "VICTORY_WAVE_DEEP_SKIPS", + "VICTORY_WAVE_OWN_BITS", + "VICTORY_WAVE_LOCAL", + "VICTORY_F16_NEAREST", + "VICTORY_HELPER_OWN", + "VICTORY_STRICT_JOINS", + "VICTORY_MESH_OUTPUT_STRICT", + ] { + bytes.extend_from_slice(name.as_bytes()); + bytes.push(b'='); + if let Some(value) = std::env::var_os(name) { + bytes.extend_from_slice(value.as_encoded_bytes()); } + bytes.push(0); } - }) + // And which clean-up passes ran over the translated code. + bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes()); + bytes + }); + let mut hash = blake3::Hasher::new(); + hash.update(fixed); + for value in victory_shader::emit::host_settings() { + hash.update(&value.to_le_bytes()); + } + *hash.finalize().as_bytes() +} + +/// Puts the translation of `container` into the cache before any title asks +/// for it (`victory shaders`): whether it was there already, or why it does +/// not translate. The host is opened first, as a run does: what the card +/// can do decides the form of some programs. +pub fn precompile(container: &[u8]) -> Result { + let _ = crate::host::host(); + let misses = MISSES.load(Ordering::Relaxed); + host_shader(container)?; + // (Counts other threads' misses too: the caller only adds them up.) + Ok(MISSES.load(Ordering::Relaxed) == misses) } /// The translation of a console shader container, from the cache when @@ -94,7 +105,7 @@ fn build() -> &'static [u8; 32] { pub(crate) fn host_shader(container: &[u8]) -> Result { let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); match CACHE.get() { - Some(cache) => cached(cache, build(), container, translate), + Some(cache) => cached(cache, &build(), container, translate), None => translate(container), } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index fdbf69c..868faa6 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2001,7 +2001,7 @@ impl Shadow { *h = merged; } if differs != 0 { - crate::watch::writing(start + at, n); + crate::watch::landing(start + at, n); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); written += n; } @@ -2090,7 +2090,7 @@ impl Shadow { if !merge_piece(now, held, title) { return 0; } - crate::watch::writing(start + at, n); + crate::watch::landing(start + at, n); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); n } @@ -2618,7 +2618,7 @@ impl Shadow { *o = merged; } if differs != 0 { - crate::watch::writing(start + at, n); + crate::watch::landing(start + at, n); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); written = n; } @@ -2693,7 +2693,7 @@ impl Shadow { if !mapped || !changed { return 0; } - crate::watch::writing(start + at, n); + crate::watch::landing(start + at, n); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); n } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index cbf5974..03a1290 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -33,7 +33,12 @@ macro_rules! once { /// A texture's upload state: the staging buffer laid out as the host /// texture's subresources, and what was last detiled. pub(crate) struct Staging { + /// A buffer of its own, or the block [`Staging::piece`] is part of. buffer: ID3D12Resource, + /// Where in `buffer` it begins (the footprints count from there). + base: u64, + /// Back in the pool with the last list that names it. + _piece: Option, /// Its bytes. #[cfg(feature = "diagnostics")] size: u64, @@ -552,6 +557,23 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexUploads, 1); const COPY_DEST: u32 = 0x400; + // A texture cut from a block may lie where another did: what the card + // holds of that one is done with before the first upload into this one. + if crate::pool::on() && !staging.uploaded.load(Relaxed) { + let aliasing = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::ManuallyDrop::new(None), + // SAFETY: a borrowed pointer the barrier never releases. + pResourceAfter: unsafe { std::mem::transmute_copy(texture) }, + }), + }, + }; + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[aliasing]) }; + } crate::list::ensure_state(list, resource, COPY_DEST); // The staging buffer lives as long as `staging`, which the deferred // refresh below holds until the list is reset. @@ -573,14 +595,14 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) d.MipLevels, staging.footprints.len(), staging.size, - footprint.Offset, + staging.base + footprint.Offset, f.Width, f.Height, f.Depth, f.RowPitch ) }, - (gpu + footprint.Offset, len), + (gpu + staging.base + footprint.Offset, len), ); } let to = D3D12_TEXTURE_COPY_LOCATION { @@ -596,7 +618,10 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) pResource: unsafe { std::mem::transmute_copy(&staging.buffer) }, Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - PlacedFootprint: *footprint, + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: staging.base + footprint.Offset, + ..*footprint + }, }, }; // SAFETY: an open list; both locations name live resources. @@ -1074,18 +1099,26 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { Some(&mut total), ); } - let (buffer, data) = host.upload_buffer(total)?; - crate::host::name(&buffer, || { - format!( - "staging of {resource:?} {}x{}x{} f{}", - d.Width, d.Height, d.DepthOrArraySize, d.Format.0 - ) - }); + let (piece, buffer, base, data) = match crate::pool::staging(host, total) { + Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data), + None => { + let (buffer, data) = host.upload_buffer(total)?; + crate::host::name(&buffer, || { + format!( + "staging of {resource:?} {}x{}x{} f{}", + d.Width, d.Height, d.DepthOrArraySize, d.Format.0 + ) + }); + (None, buffer, 0, data) + } + }; tracing::debug!(?desc, total, "texture contents uploaded from title memory"); STAGED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); STAGED[1].fetch_add(total, std::sync::atomic::Ordering::Relaxed); let s = Arc::new(Staging { buffer, + base, + _piece: piece, #[cfg(feature = "diagnostics")] size: total, data, @@ -1214,3 +1247,118 @@ mod title_memory_tests { } } } + +/// How long this PC's card takes to make the allocations a staged texture needs, for +/// `cargo test -p victory-gpu allocation_costs -- --ignored --nocapture`. +#[cfg(test)] +mod allocation_costs { + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::*; + + fn texture(size: u32) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(size), + Height: size, + DepthOrArraySize: 1, + MipLevels: 0, + Format: DXGI_FORMAT_BC7_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + } + } + + fn buffer(size: u64) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + } + } + + fn committed(device: &ID3D12Device, kind: D3D12_HEAP_TYPE, flags: D3D12_HEAP_FLAGS, desc: &D3D12_RESOURCE_DESC) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }; + let state = if kind == D3D12_HEAP_TYPE_UPLOAD { D3D12_RESOURCE_STATE_GENERIC_READ } else { D3D12_RESOURCE_STATE_COMMON }; + let mut out = None; + // SAFETY: plain creation. + unsafe { device.CreateCommittedResource(&heap, flags, desc, state, None, &mut out) }.expect("committed"); + out.unwrap() + } + + fn timed(what: &str, n: usize, threads: usize, make: &(dyn Fn(usize) -> ID3D12Resource + Sync)) { + let began = std::time::Instant::now(); + let all: Vec<_> = std::thread::scope(|s| { + (0..threads) + .map(|t| s.spawn(move || (t..n).step_by(threads).map(make).collect::>())) + .collect::>() + .into_iter() + .flat_map(|h| h.join().unwrap()) + .collect() + }); + let took = began.elapsed().as_secs_f64() * 1e3; + println!("{what}, {threads} thread(s): {n} in {took:.1} ms, {:.0} us each", took * 1e3 / n as f64); + drop(all); + } + + #[test] + #[ignore = "a measurement, not a check"] + fn allocation_costs() { + let Some(host) = crate::host::host() else { return }; + let device = &host.device; + let not_zeroed = D3D12_HEAP_FLAG_CREATE_NOT_ZEROED; + const N: usize = 1000; + for size in [128u32, 512, 1024] { + let (t, b) = (texture(size), buffer(u64::from(size * size) * 4 / 3 + 65536)); + println!("-- BC7 {size}x{size}"); + for threads in [1, 4, 8] { + timed("texture committed", N, threads, &|_| committed(device, D3D12_HEAP_TYPE_DEFAULT, D3D12_HEAP_FLAG_NONE, &t)); + timed("texture committed not zeroed", N, threads, &|_| committed(device, D3D12_HEAP_TYPE_DEFAULT, not_zeroed, &t)); + let mapped = |flags| { + let b = &b; + move |_| { + let r = committed(device, D3D12_HEAP_TYPE_UPLOAD, flags, b); + let mut data = std::ptr::null_mut(); + // SAFETY: a live upload buffer. + unsafe { r.Map(0, None, Some(&mut data)) }.unwrap(); + // SAFETY: the first byte of the mapping (its first touch). + unsafe { data.cast::().write_volatile(1) }; + r + } + }; + timed("staging committed and mapped", N, threads, &mapped(D3D12_HEAP_FLAG_NONE)); + timed("staging committed and mapped, not zeroed", N, threads, &mapped(not_zeroed)); + } + // SAFETY: plain query. + let info = unsafe { device.GetResourceAllocationInfo(0, &[t]) }; + let per_heap = ((64u64 << 20) / info.SizeInBytes).max(1) as usize; + let heaps: Vec = (0..N.div_ceil(per_heap)) + .map(|_| { + let desc = D3D12_HEAP_DESC { + SizeInBytes: per_heap as u64 * info.SizeInBytes, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES | not_zeroed, + ..Default::default() + }; + let mut heap = None; + // SAFETY: plain creation. + unsafe { device.CreateHeap(&desc, &mut heap) }.expect("heap"); + heap.unwrap() + }) + .collect(); + let place = |i: usize| { + let mut out: Option = None; + let at = (i % per_heap) as u64 * info.SizeInBytes; + // SAFETY: a part of a live heap no other texture has. + unsafe { device.CreatePlacedResource(&heaps[i / per_heap], at, &t, D3D12_RESOURCE_STATE_COMMON, None, &mut out) }.expect("placed"); + out.unwrap() + }; + timed("texture placed in 64 MB heaps", N, 1, &place); + timed("texture placed in 64 MB heaps", N, 8, &place); + } + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 60089a7..46ade96 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -21,7 +21,7 @@ //! (none is known to). use std::collections::{BTreeMap, BTreeSet}; -use std::sync::Mutex; +use std::sync::{Condvar, Mutex, RwLock}; /// The unit tracked and copied: 64 KiB, the console's page (the kernel's /// 4 KiB pages fold into it). Finer units made the checks of the world's @@ -30,13 +30,17 @@ pub(crate) const PAGE: usize = 64 << 10; /// The kernel's page, the unit of its answers. const KERNEL_PAGE: usize = 4096; +/// Numbers the askings; 0 is "never". Counted up with the journal held +/// (shared will do: what notes an answer holds it alone). +static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +fn next_asking() -> u64 { + ASKED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1 +} + struct Journal { - /// Numbers the askings; 0 is "never". - asked: u64, /// Page number → the asking that last found it written. written: BTreeMap, - /// Room for the kernel's answer. - found: Vec, /// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`]) /// and the asking that did: `writes` answers for a range inside one /// from the journal, without another kernel call. @@ -48,15 +52,110 @@ struct Journal { kept: bool, } -static JOURNAL: Mutex = Mutex::new(Journal { - asked: 0, +/// Read by many threads at once (a submission's refreshes run on several), +/// written only to note an answer: the kernel is asked, and view memory +/// guarded, with the range held in [`ASKING`] and not under this lock. Under +/// one lock for all of it those threads ran one at a time: 22 of 96 looks at +/// the submitting thread, and one in six of those at the six threads beside +/// it, found it waiting for that lock (run pooloff1). +static JOURNAL: RwLock = RwLock::new(Journal { written: BTreeMap::new(), - found: Vec::new(), ahead: Vec::new(), ahead_asked: 0, kept: false, }); +fn journal() -> std::sync::RwLockReadGuard<'static, Journal> { + JOURNAL.read().unwrap_or_else(|e| e.into_inner()) +} + +fn journal_mut() -> std::sync::RwLockWriteGuard<'static, Journal> { + JOURNAL.write().unwrap_or_else(|e| e.into_inner()) +} + +/// The page ranges some thread is asking about: asking forgets what it +/// answers, so until the answer is in the journal no other thread may ask +/// about any of the same pages (it would be told they were not written). +/// Taken before the journal's lock, never under it. +static ASKING: (Mutex>, Condvar) = (Mutex::new(Vec::new()), Condvar::new()); + +/// Pages `[first, last)` held in [`ASKING`] until dropped. +struct Asking(usize, usize); + +impl Asking { + fn hold(first: usize, last: usize) -> Asking { + let mut held = ASKING.0.lock().unwrap_or_else(|e| e.into_inner()); + while held.iter().any(|&(a, b)| a < last && first < b) { + held = ASKING.1.wait(held).unwrap_or_else(|e| e.into_inner()); + } + held.push((first, last)); + Asking(first, last) + } + + /// Everything: an asking for a whole submission. + fn hold_all() -> Asking { + Asking::hold(0, usize::MAX) + } +} + +impl Drop for Asking { + fn drop(&mut self) { + let mut held = ASKING.0.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(i) = held.iter().position(|&r| r == (self.0, self.1)) { + held.swap_remove(i); + } + drop(held); + ASKING.1.notify_all(); + } +} + +thread_local! { + /// Room for the kernel's answer. + static FOUND: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// The pages of `[first, last)` the kernel says were written since it was +/// last asked, in order, each once; `None` if the range is not write-watched +/// memory of one reservation. The caller holds the range ([`Asking`]). +fn kernel_written(first: usize, last: usize) -> Option> { + use windows_sys::Win32::System::Memory::GetWriteWatch; + const WRITE_WATCH_FLAG_RESET: u32 = 1; + FOUND.with(|found| { + let mut found = found.borrow_mut(); + let mut count = (last - first) * PAGE / KERNEL_PAGE; + if found.len() < count { + found.resize(count, 0); + } + let mut granularity = 0; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + // SAFETY: the answer buffer holds `count` entries. + let failed = unsafe { + GetWriteWatch( + WRITE_WATCH_FLAG_RESET, + (first * PAGE) as *const _, + (last - first) * PAGE, + found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + } != 0; + if failed { + return None; + } + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::Watches, 1); + add(C::WatchUs, started.elapsed().as_micros() as u64); + slow(started.elapsed().as_micros() as u64); + } + let mut pages: Vec = found[..count].iter().map(|&at| at / PAGE).collect(); + pages.dedup(); + Some(pages) + }) +} + /// Ranges of one submission closer than this are asked about together: /// walking the pages between them costs less than another kernel call (a /// call that resets written pages costs 30-70 microseconds whatever the @@ -81,16 +180,13 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { return; } pieces.sort_unstable(); - let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); - let j = &mut *j; // The submission's one asking stands ([`ask_once`]): what it does not // hold is left to `writes`. - if j.kept { + if journal().kept { return; } - j.asked += 1; - j.ahead_asked = j.asked; - j.ahead.clear(); + let _all = Asking::hold_all(); + let (mut asked, mut written) = (Vec::new(), Vec::new()); let mut i = 0; while i < pieces.len() { let first = pieces[i].0; @@ -103,9 +199,14 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { last = last.max(pieces[k].1); k += 1; } - ask_run(j, &pieces[i..k]); + ask_run(&pieces[i..k], &mut asked, &mut written); i = k; } + let mut j = journal_mut(); + j.ahead_asked = next_asking(); + j.ahead = asked; + let now = j.ahead_asked; + j.written.extend(written.into_iter().map(|page| (page, now))); } /// Since the last frame line: the kernel askings that took a millisecond @@ -135,7 +236,7 @@ pub(crate) fn slow_asks() -> [u64; 3] { /// The submission's refreshes are done: `writes` asks the kernel again. pub(crate) fn ask_ahead_done() { - let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut j = journal_mut(); if !j.kept { j.ahead.clear(); } @@ -174,34 +275,44 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) { } ask_once_end(); ask_ahead(ranges); - let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); - let j = &mut *j; - if j.ahead.is_empty() { - // `ask_ahead` asked nothing (fewer than two ranges). - j.asked += 1; - j.ahead_asked = j.asked; - } + let _all = Asking::hold_all(); + let mut ahead = { + let mut j = journal_mut(); + if j.ahead.is_empty() { + // `ask_ahead` asked nothing (fewer than two ranges). + j.ahead_asked = next_asking(); + } + std::mem::take(&mut j.ahead) + }; // `ask_ahead` leaves a range that lies alone to `writes`, which asks // once per flush: with one asking for the submission that was every // such range asked again at each of its 70 flushes (run 76: 2,300 // askings a frame with the switch on, as without it). They are asked // here, once; what is not write-watched stays with `writes`. + let mut written = Vec::new(); for &(start, end) in ranges { if start >= end { continue; } let (first, last) = (start / PAGE, end.div_ceil(PAGE)); - if !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) && ask_kernel(j, first, last) { - j.ahead.push((first, last)); + if !ahead.iter().any(|&(a, b)| a <= first && last <= b) + && let Some(pages) = kernel_written(first, last) + { + written.extend(pages); + ahead.push((first, last)); } } - j.kept = !j.ahead.is_empty(); + let mut j = journal_mut(); + let now = j.ahead_asked; + j.written.extend(written.into_iter().map(|page| (page, now))); + j.kept = !ahead.is_empty(); + j.ahead = ahead; } /// The submission's one asking stands no longer: its refreshes are done, /// or title memory was written in a way the journal was not told. pub(crate) fn ask_once_end() { - let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut j = journal_mut(); if j.kept { j.kept = false; j.ahead.clear(); @@ -212,12 +323,15 @@ pub(crate) fn ask_once_end() { /// stands (the title's buffer copies, done at submission): its pages count /// as written after that asking, so the refreshes that follow copy them. pub(crate) fn wrote(at: usize, len: usize) { - let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut j = journal_mut(); if !j.kept || len == 0 { return; } - j.asked += 1; - let now = j.asked; + let now = next_asking(); + // What is copied from now on counts as copied after these writes (fork + // PR 410): answers older than the writes in them made every refresh + // until the next asking copy the pages again. + j.ahead_asked = now; for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) { j.written.insert(page, now); } @@ -225,60 +339,22 @@ pub(crate) fn wrote(at: usize, len: usize) { /// One kernel asking for `pieces` (page ranges in order); by halves if it /// fails, as a run across two reservations or into memory that is not -/// write-watched does. A piece alone is left to [`writes`]. -fn ask_run(j: &mut Journal, pieces: &[(usize, usize)]) { +/// write-watched does. A piece alone is left to [`writes`]. Adds what was +/// asked to `asked` and the pages found written to `written`. +fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written: &mut Vec) { if pieces.len() < 2 { return; } let first = pieces[0].0; let last = pieces.iter().map(|p| p.1).max().unwrap_or(first); - if ask_kernel(j, first, last) { - j.ahead.push((first, last)); + if let Some(pages) = kernel_written(first, last) { + written.extend(pages); + asked.push((first, last)); return; } let (a, b) = pieces.split_at(pieces.len() / 2); - ask_run(j, a); - ask_run(j, b); -} - -/// Asks the kernel for the written pages of pages `[first, last)` and notes -/// them in the journal under the ahead asking; false (and nothing changed) -/// if the range is not write-watched memory of one reservation. -fn ask_kernel(j: &mut Journal, first: usize, last: usize) -> bool { - use windows_sys::Win32::System::Memory::GetWriteWatch; - const WRITE_WATCH_FLAG_RESET: u32 = 1; - let mut count = (last - first) * PAGE / KERNEL_PAGE; - j.found.resize(count.max(j.found.len()), 0); - let mut granularity = 0; - #[cfg(feature = "diagnostics")] - let started = std::time::Instant::now(); - // SAFETY: the answer buffer holds `count` entries. - let failed = unsafe { - GetWriteWatch( - WRITE_WATCH_FLAG_RESET, - (first * PAGE) as *const _, - (last - first) * PAGE, - j.found.as_mut_ptr().cast(), - &mut count, - &mut granularity, - ) - } != 0; - if failed { - return false; - } - #[cfg(feature = "diagnostics")] - { - use crate::copystat::{C, add}; - add(C::Watches, 1); - add(C::WatchUs, started.elapsed().as_micros() as u64); - slow(started.elapsed().as_micros() as u64); - } - let now = j.ahead_asked; - for k in 0..count { - let page = j.found[k] / PAGE; - j.written.insert(page, now); - } - true + ask_run(a, asked, written); + ask_run(b, asked, written); } /// What [`writes`] would say of `[start, end)` from the journal alone, if @@ -288,7 +364,7 @@ fn ask_kernel(j: &mut Journal, first: usize, last: usize) -> bool { /// it). `None` if the kernel would have to be asked. pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)> { let (first, last) = (start / PAGE, end.div_ceil(PAGE)); - let j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let j = journal(); j.ahead .iter() .any(|&(a, b)| a <= first && last <= b) @@ -301,71 +377,51 @@ pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>) /// kernel just reported. `None` if the memory is not write-watched (nor, /// with `guarded`, view memory, which is then guarded). pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Vec<(usize, u64)>)> { - use windows_sys::Win32::System::Memory::GetWriteWatch; - const WRITE_WATCH_FLAG_RESET: u32 = 1; let (first, last) = (start / PAGE, end.div_ceil(PAGE)); - let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); - let j = &mut *j; + let of = |j: &Journal| -> Vec<(usize, u64)> { j.written.range(first..last).map(|(&p, &w)| (p, w)).collect() }; // Asked ahead with the submission's other ranges: the journal has it. - if j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { - return Some(( - j.ahead_asked, - j.written - .range(first..last) - .map(|(&p, &w)| (p, w)) - .collect(), - )); + let ahead = |j: &Journal| j.ahead.iter().any(|&(a, b)| a <= first && last <= b).then(|| (j.ahead_asked, of(j))); + if let Some(known) = ahead(&journal()) { + return Some(known); } - let mut count = (last - first) * PAGE / KERNEL_PAGE; - j.found.resize(count.max(j.found.len()), 0); - let mut granularity = 0; - #[cfg(feature = "diagnostics")] - let started = std::time::Instant::now(); - // SAFETY: the answer buffer holds `count` entries. - let failed = unsafe { - GetWriteWatch( - WRITE_WATCH_FLAG_RESET, - (first * PAGE) as *const _, - (last - first) * PAGE, - j.found.as_mut_ptr().cast(), - &mut count, - &mut granularity, - ) - } != 0; - let guarded = if failed { - count = 0; - if !guarded { - return None; + // Asked, and the answer noted, with the range held: nothing else asks + // about any of it in between. + let _range = Asking::hold(first, last); + if let Some(known) = ahead(&journal()) { + return Some(known); + } + let pages = match kernel_written(first, last) { + Some(pages) => pages, + None => { + if !guarded { + return None; + } + #[cfg(feature = "diagnostics")] + let guarding = std::time::Instant::now(); + let written = guard(first * PAGE, last * PAGE); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + let us = guarding.elapsed().as_micros() as u64; + add(C::GuardUs, us); + if written.is_some() { + add(C::Watches, 1); + add(C::WatchUs, us); + slow(us); + } + } + written? } - #[cfg(feature = "diagnostics")] - let guarding = std::time::Instant::now(); - let written = guard(first * PAGE, last * PAGE); - #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::GuardUs, guarding.elapsed().as_micros() as u64); - written? - } else { - Vec::new() }; - #[cfg(feature = "diagnostics")] - { - use crate::copystat::{C, add}; - add(C::Watches, 1); - add(C::WatchUs, started.elapsed().as_micros() as u64); - slow(started.elapsed().as_micros() as u64); + if pages.is_empty() { + // Nothing to note: the others may go on reading. + let j = journal(); + return Some((next_asking(), of(&j))); } - j.asked += 1; - let now = j.asked; - let pages = j.found[..count].iter().map(|&at| at / PAGE).chain(guarded); - for page in pages.collect::>() { - j.written.insert(page, now); - } - Some(( - now, - j.written - .range(first..last) - .map(|(&p, &w)| (p, w)) - .collect(), - )) + let mut j = journal_mut(); + let now = next_asking(); + j.written.extend(pages.into_iter().map(|page| (page, now))); + Some((now, of(&j))) } /// Guarded blocks of view memory. @@ -391,6 +447,47 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> { GUARDS.lock().unwrap_or_else(|e| e.into_inner()) } +/// The 4 KiB pages of title memory that what shaders wrote was put into, +/// and the frame it last was. +static LANDED: Mutex>> = Mutex::new(None); + +/// What shaders wrote is about to go into title memory at `[at, at + len)`. +pub(crate) fn landing(at: usize, len: usize) { + { + let frame = crate::frame::current(); + let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); + let landed = landed.get_or_insert_with(Default::default); + for page in at / 4096..=(at + len.max(1) - 1) / 4096 { + landed.insert(page, frame); + } + } + writing(at, len); +} + +/// Whether shaders' writes went into a page of `[at, at + len)` in the last +/// `frames` frames. +pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool { + let since = crate::frame::current().saturating_sub(frames); + let landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); + landed.as_ref().is_some_and(|landed| { + (at / 4096..=(at + len.max(1) - 1) / 4096).any(|page| landed.get(&page).is_some_and(|&f| f >= since)) + }) +} + +/// Whether every block of `[at, at + len)` is view memory written since a +/// host copy last took it: guarded then, and the guard is off. (Written by +/// the title, or by us putting a flight's shader writes into it.) Not for +/// blocks no copy ever took, which were never guarded: the caller's range +/// lies in a copy a flight was given, which took all of it. +pub(crate) fn written_since_taken(at: usize, len: usize) -> bool { + if len == 0 { + return false; + } + let g = guards(); + (at / BLOCK..=(at + len - 1) / BLOCK) + .all(|b| !g.protected.contains(&b) && !g.clean.contains(&b) && !g.absent.contains(&b)) +} + /// For view memory: the pages of `[start, end)`'s blocks written since /// they were last guarded (all of a block's pages), guarding them again /// before the caller copies them. `None` if the memory is not a view. @@ -1106,3 +1203,52 @@ mod mapping_tests { assert!(read.load(Ordering::SeqCst)); } } + +#[cfg(test)] +mod many_askers_tests { + use super::{PAGE, writes}; + use windows_sys::Win32::System::Memory::*; + + /// Threads that write pages and ask about overlapping ranges at the same + /// time: whoever wrote a page before asking is told of that write (by + /// its own asking or by one that took the kernel's answer before it). + #[test] + fn no_write_is_lost_between_askers() { + const MEM_WRITE_WATCH: u32 = 0x20_0000; + const PAGES: usize = 48; + const THREADS: usize = 8; + // SAFETY: a reservation of our own, freed at the end. + let at = unsafe { + VirtualAlloc(std::ptr::null(), PAGES * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) + } as usize; + assert!(at != 0 && at.is_multiple_of(PAGE)); + std::thread::scope(|s| { + for t in 0..THREADS { + s.spawn(move || { + let mut last = [0u64; PAGES]; + let mut seed = t as u64 * 7919 + 1; + let mut next = |n: usize| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as usize % n + }; + for _ in 0..4000 { + let page = next(PAGES); + let from = page - next(page.min(12) + 1); + let to = page + 1 + next((PAGES - page).min(12)); + // SAFETY: committed memory of ours; what the racing + // writers leave in it does not matter. + unsafe { ((at + page * PAGE + t * 8) as *mut u64).write_volatile(1) }; + let (now, written) = writes(at + from * PAGE, at + to * PAGE, false).expect("write-watched"); + let number = written.iter().find(|w| w.0 == at / PAGE + page).map_or(0, |w| w.1); + assert!(number > last[page], "page {page}: {number} is not after {}", last[page]); + for l in &mut last[from..to] { + *l = now; + } + } + }); + } + }); + // SAFETY: the reservation made above. + unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) }; + } +} diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index 23bbccf..b8c89d6 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -36,6 +36,20 @@ fn host_gpu_failed(what: &str) -> ! { unreachable!("the process has ended") } +/// Translates `container` into the cache ([`use_shader_cache`]) ahead of +/// any run: whether it was there already, or why it does not translate. +pub fn precompile(container: &[u8]) -> Result { + #[cfg(windows)] + { + victory_gpu::shader_cache::precompile(container) + } + #[cfg(not(windows))] + { + let _ = container; + Err("no host".into()) + } +} + /// Keeps the host's translations of the title's shaders in `dir` (a /// folder of the cache) across runs, and its compiled pipelines beside it /// (`pipelines`). diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 48c6086..44291e6 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -955,25 +955,27 @@ fn into_destination( // SAFETY: the title's destination holds `destination_size` bytes, at // least `len`, and nothing else writes it until completion. let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::(), len) }; - return fill(out).map(drop); + let filled = fill(out).map(drop); + // Again now that the bytes are there: a texture looked at in between + // was uploaded without them (`xmem::pages_written`). + if super::xmem::stream_notice() { + victory_gpu::kernel_will_write(request.destination as usize, len); + } + return filled; } let offset = (request.page_offset & 0xffff) as usize; - // SAFETY: the title passes a page number per 64 KiB of destination, - // which holds at least `len` bytes from `offset`. - let pages = unsafe { - std::slice::from_raw_parts( - request.destination.cast::(), - (offset + len).div_ceil(PAGE), - ) - }; + let pages = &page_list(request.destination.cast(), offset, len)[..]; // Consecutive pages of one allocation (the usual case): written in // place through one view. if let Some(mut window) = super::xmem::page_window(pages, offset, len) { - return fill(window.bytes()).map(drop); + let filled = fill(window.bytes()).map(drop); + super::xmem::pages_written(pages, offset, len); + return filled; } let mut data = vec![0; len]; let n = fill(&mut data)?; if super::xmem::write_physical(pages, offset, &data[..n]) { + super::xmem::pages_written(pages, offset, n); Ok(()) } else { // Said aloud: the title never reads a request's result @@ -990,6 +992,38 @@ fn into_destination( } } +/// The request's page numbers, one per 64 KiB of destination. The title +/// queues a request before it has filled its page list in, and a worker that +/// reads the list at once finds page 0 in it (pages of models and textures +/// that were then never written: walls missing for the whole run). So a list +/// with a page the title does not own is read again for a while, up to +/// 1.5 s; what it holds then is used as it is. +fn page_list(list: *const usize, offset: usize, len: usize) -> Vec { + let read = || -> Vec { + (0..(offset + len).div_ceil(PAGE)) + // SAFETY: the title passes a page number per 64 KiB of + // destination, which holds at least `len` bytes from `offset`; + // it may be writing them. + .map(|i| unsafe { list.add(i).read_volatile() }) + .collect() + }; + let started = std::time::Instant::now(); + let mut pages = read(); + while !super::xmem::pages_known(&pages, offset, len) && started.elapsed().as_millis() < 1500 { + std::thread::sleep(std::time::Duration::from_millis(1)); + pages = read(); + } + let waited = started.elapsed(); + if waited.as_millis() >= 1 { + tracing::info!( + ms = waited.as_millis() as u64, + known = super::xmem::pages_known(&pages, offset, len), + "dstorage: a destination's page list was not filled in yet" + ); + } + pages +} + /// Slots by the 2020 order, which the argument shapes at /// the title's call sites match (0x18, 0x20, 0x30 and 0x40 are called). static QUEUE_VTABLE: Methods<12> = Methods([ diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 82e14ef..fe5b4c5 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -342,7 +342,64 @@ pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL { const PAGE: usize = 64 << 10; -struct Section(HANDLE); +struct Section { + handle: HANDLE, + pages: usize, + /// A view of the whole section, kept ([`Section::window`]); 0 if the + /// host gave none. + window: std::sync::OnceLock, + /// A bit per page: committed, as far as [`Section::window`] asked. + committed: Box<[std::sync::atomic::AtomicU64]>, +} + +impl Section { + /// Where bytes of `n` pages from page `index` on can be written, + /// whether or not the pages are mapped anywhere, committed. + /// + /// Every DirectStorage write mapped a view of its pages, committed it, + /// faulted each of its 4 KiB pages in and unmapped it again, all of it + /// under the process's one address-space lock, with 24 workers, the + /// title's own mapping calls (about 100,000 views of one page) and our + /// guards asking for the same lock. One view of the section, kept, + /// costs that once per page. + /// `VICTORY_SECTION_WINDOW=0`: a view for each write, as before. + fn window(&self, index: usize, n: usize) -> Option { + use std::sync::atomic::Ordering; + use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile}; + static ON: LazyLock = + LazyLock::new(|| std::env::var_os("VICTORY_SECTION_WINDOW").is_none_or(|v| v != "0")); + if !*ON || index + n > self.pages { + return None; + } + let base = *self.window.get_or_init(|| { + // SAFETY: the whole of a section we own. + unsafe { MapViewOfFile(self.handle, FILE_MAP_WRITE, 0, 0, self.pages * PAGE) }.Value as usize + }); + if base == 0 { + return None; + } + let missing = |page: usize| self.committed[page / 64].load(Ordering::Acquire) >> (page % 64) & 1 == 0; + let mut page = index; + while page < index + n { + if !missing(page) { + page += 1; + continue; + } + let run = (page..index + n).take_while(|&p| missing(p)).count(); + if run == 0 { + continue; // another worker committed it meanwhile + } + if !commit(base + page * PAGE, run * PAGE) { + return None; + } + for p in page..page + run { + self.committed[p / 64].fetch_or(1 << (p % 64), Ordering::AcqRel); + } + page += run; + } + Some(base + index * PAGE) + } +} // SAFETY: a section handle may be used from any thread. unsafe impl Send for Section {} @@ -351,8 +408,19 @@ unsafe impl Sync for Section {} impl Drop for Section { fn drop(&mut self) { + use windows_sys::Win32::System::Memory::UnmapViewOfFile; + if let Some(&base) = self.window.get() + && base != 0 + { + // SAFETY: our view; whoever writes through it holds the section. + unsafe { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { + Value: base as *mut c_void, + }) + }; + } // SAFETY: our handle; views keep the section alive on their own. - unsafe { CloseHandle(self.0) }; + unsafe { CloseHandle(self.handle) }; } } @@ -370,6 +438,103 @@ struct Physical { pages: HashMap, /// Mapped views by address: their length and what they show. views: BTreeMap, + /// The other way: the views (by address) that show a page, by the page's + /// section and index. Views of more than [`SHORT`] pages are in `long`. + shown: HashMap<(usize, usize), Vec>, + long: Vec, +} + +/// Pages of a view noted page by page in [`Physical::shown`]. +const SHORT: usize = 64; + +impl Physical { + fn note_view(&mut self, base: usize, len: usize, slice: &Slice) { + if len / PAGE > SHORT { + self.long.push(base); + return; + } + let section = Arc::as_ptr(&slice.section) as usize; + for k in 0..len / PAGE { + self.shown.entry((section, slice.index + k)).or_default().push(base); + } + } + + fn forget_view(&mut self, base: usize, len: usize, slice: &Slice) { + if len / PAGE > SHORT { + self.long.retain(|&b| b != base); + return; + } + let section = Arc::as_ptr(&slice.section) as usize; + for k in 0..len / PAGE { + let key = (section, slice.index + k); + if let Some(views) = self.shown.get_mut(&key) { + views.retain(|&b| b != base); + if views.is_empty() { + self.shown.remove(&key); + } + } + } + } + + /// Where the title sees `n` pages from `slice` on: addresses and bytes. + fn shown_at(&self, slice: &Slice, n: usize) -> Vec<(usize, usize)> { + let section = Arc::as_ptr(&slice.section) as usize; + let mut out: Vec<(usize, usize)> = Vec::new(); + for k in 0..n { + for &base in self.shown.get(&(section, slice.index + k)).into_iter().flatten() { + if let Some((_, s)) = self.views.get(&base) { + out.push((base + (slice.index + k - s.index) * PAGE, PAGE)); + } + } + } + for &base in &self.long { + let Some((len, s)) = self.views.get(&base) else { continue }; + let from = slice.index.max(s.index); + let to = (slice.index + n).min(s.index + len / PAGE); + if Arc::as_ptr(&s.section) as usize == section && from < to { + out.push((base + (from - s.index) * PAGE, (to - from) * PAGE)); + } + } + out + } +} + +/// DirectStorage has put bytes `[offset, offset + len)` of `pages` into +/// memory: the GPU side is told where the title sees them, so that what it +/// copied there before they arrived (a texture uploaded when its view was +/// written holds whatever the pages held then) is copied again. +/// `VICTORY_STREAM_NOTICE=0`: not told, as before. +pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) { + if !stream_notice() || len == 0 { + return; + } + let mut seen: Vec<(usize, usize)> = { + let physical = physical(); + let numbers = pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or_default(); + numbers + .iter() + .filter_map(|n| physical.pages.get(n)) + .flat_map(|slice| physical.shown_at(slice, 1)) + .collect() + }; + seen.sort_unstable(); + let mut runs: Vec<(usize, usize)> = Vec::new(); + for (at, len) in seen { + match runs.last_mut() { + Some(last) if last.0 + last.1 == at => last.1 += len, + _ => runs.push((at, len)), + } + } + for (at, len) in runs { + victory_gpu::kernel_will_write(at, len); + } +} + +/// See [`pages_written`]. +pub(crate) fn stream_notice() -> bool { + static ON: LazyLock = + LazyLock::new(|| std::env::var_os("VICTORY_STREAM_NOTICE").is_none_or(|v| v != "0")); + *ON } static PHYSICAL: LazyLock> = LazyLock::new(|| { @@ -431,7 +596,12 @@ pub extern "system" fn XMemAllocatePhysicalPages( // For the GPU side's in-place census: only a committed section can be // opened as a host heap. victory_gpu::title_memory_section(handle as usize, size as u64, on_wine()); - let section = Arc::new(Section(handle)); + let section = Arc::new(Section { + handle, + pages: n, + window: std::sync::OnceLock::new(), + committed: (0..n.div_ceil(64)).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(), + }); let mut physical = physical(); let first = physical.next_page; physical.next_page += n * FRAMES; @@ -481,7 +651,7 @@ impl View { // SAFETY: slices of a section we own; the view is ours until dropped. let at = unsafe { MapViewOfFile( - slice.section.0, + slice.section.handle, FILE_MAP_WRITE, (offset >> 32) as u32, offset as u32, @@ -489,10 +659,15 @@ impl View { ) }; if at.Value.is_null() { + tracing::warn!(error = %std::io::Error::last_os_error(), n, "physical pages not mapped for a write"); return None; } let view = View { at, len }; - commit(at.Value as usize, len).then_some(view) + if !commit(at.Value as usize, len) { + tracing::warn!(error = %std::io::Error::last_os_error(), n, "physical pages not committed for a write"); + return None; + } + Some(view) } fn bytes(&mut self) -> &mut [u8] { @@ -522,7 +697,10 @@ fn runs(pages: &[usize], offset: usize, len: usize) -> Option = Vec::new(); for page in pages { - let slice = physical.pages.get(page)?; + let Some(slice) = physical.pages.get(page) else { + tracing::warn!(page, offset, len, "a physical page the title does not own (any more)"); + return None; + }; match runs.last_mut() { Some((first, n)) if Arc::ptr_eq(&first.section, &slice.section) @@ -536,6 +714,14 @@ fn runs(pages: &[usize], offset: usize, len: usize) -> Option bool { + let physical = physical(); + pages + .get(offset / PAGE..(offset + len).div_ceil(PAGE)) + .is_some_and(|pages| pages.iter().all(|page| physical.pages.contains_key(page))) +} + /// Copies `data` into physical pages, from `offset` bytes into the first, /// whether or not they are mapped anywhere (DirectStorage destinations). /// One view per run of consecutive pages, not one per page: each view @@ -547,11 +733,17 @@ pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> boo }; let (mut within, mut done) = (offset % PAGE, 0); for (slice, n) in &runs { - let Some(mut view) = View::map(slice, *n) else { - return false; - }; let k = (n * PAGE - within).min(data.len() - done); - view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]); + if let Some(at) = slice.section.window(slice.index, *n) { + // SAFETY: committed bytes of the section's view, which `runs` + // holds; the title's other uses of them race as on the console. + unsafe { std::ptr::copy_nonoverlapping(data[done..].as_ptr(), (at + within) as *mut u8, k) }; + } else { + let Some(mut view) = View::map(slice, *n) else { + return false; + }; + view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]); + } (within, done) = (0, done + k); } true @@ -561,15 +753,27 @@ pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> boo /// until dropped: DirectStorage decodes into it instead of a buffer it /// would then copy. pub(crate) struct PageWindow { - view: View, + view: Window, within: usize, len: usize, } +enum Window { + /// In the section's own view, which the section holds. + Kept(usize, #[expect(dead_code, reason = "held for the view")] Arc
), + Own(View), +} + impl PageWindow { pub(crate) fn bytes(&mut self) -> &mut [u8] { let (within, len) = (self.within, self.len); - &mut self.view.bytes()[within..within + len] + match &mut self.view { + // SAFETY: committed bytes of the section's view, ours alone as + // far as the runtime goes (other views alias them, as the + // console's do). + Window::Kept(at, _) => unsafe { std::slice::from_raw_parts_mut((*at + within) as *mut u8, len) }, + Window::Own(view) => &mut view.bytes()[within..within + len], + } } } @@ -583,8 +787,12 @@ pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option< let [(slice, n)] = runs.as_slice() else { return None; }; + let view = match slice.section.window(slice.index, *n) { + Some(at) => Window::Kept(at, slice.section.clone()), + None => Window::Own(View::map(slice, *n)?), + }; Some(PageWindow { - view: View::map(slice, *n)?, + view, within: offset % PAGE, len, }) @@ -711,7 +919,7 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, ); MapViewOfFile3( - slice.section.0, + slice.section.handle, GetCurrentProcess(), base as *const c_void, (slice.index * PAGE) as u64, @@ -739,7 +947,8 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { // New contents, read-write: the GPU side's copies no longer guard it. victory_gpu::title_memory_remapped(base, len); // What the range shows now, for the GPU side's in-place census. - victory_gpu::title_memory_view(base, len, slice.section.0 as usize, (slice.index * PAGE) as u64); + victory_gpu::title_memory_view(base, len, slice.section.handle as usize, (slice.index * PAGE) as u64); + physical.note_view(base, len, &slice); physical.views.insert(base, (len, slice)); true } @@ -818,6 +1027,7 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { let Some((size, slice)) = physical.views.remove(&at) else { continue; }; + physical.forget_view(at, size, &slice); victory_gpu::title_memory_remapped(at, size); // SAFETY: a view we mapped; it becomes a placeholder again. unsafe { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 37cd6fb..58271ff 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1016,6 +1016,12 @@ fn own_bits_on() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0")) } +/// What the translator was told of the host, for a cache's key: the widest +/// wave and the view heap's limit. +pub fn host_settings() -> [u32; 2] { + [host_max_wave(), super::shader::view_heap_limit()] +} + pub(super) fn host_max_wave() -> u32 { #[cfg(test)] if let Some(lanes) = TEST_HOST_WAVE.get() { @@ -4203,7 +4209,30 @@ impl<'a> Lower<'a> { /// `x` in the first lane of this host wave where `guard` holds, and whether it has such a /// lane: the console reads the first lane of EXEC, and a lane that got here with EXEC clear /// (a guard, not a branch) is not one. With none, `x` of the wave's first lane here. + /// + /// A helper lane of a pixel shader takes its own value: the console's whole-quad mode has + /// helper lanes in EXEC, so a waterfall loop serves them too, and the host's wave operations + /// leave them out. Once only helper lanes are left in such a loop none of them ever matched: + /// they ran to the iteration limit, and left with no sample for their quad's derivatives, + /// along every triangle's edges (upstream #908, the fix of #1733 for this tree's form). fn first_lane(&mut self, x: V, guard: Option) -> (V, V) { + let (first, any) = self.first_live_lane(x, guard); + if !self.s.pixel || !super::helper_own() { + return (first, any); + } + let helper = self.helper_lane(); + let c = self.cur; + let yes = self.s.m.bool(true); + (self.s.m.select(c, helper, x, first), self.s.m.select(c, helper, yes, any)) + } + + /// Whether this lane of a pixel shader is a helper lane. + fn helper_lane(&mut self) -> V { + let i1t = self.s.t.i1; + self.s.op(self.cur, "isHelperLane.i1", Attr::ReadOnly, i1t, 221, &[]) + } + + fn first_live_lane(&mut self, x: V, guard: Option) -> (V, V) { let c = self.cur; let i32t = self.s.t.i32; self.s.flags |= flags::WAVE_OPS; @@ -5823,7 +5852,13 @@ impl<'a> Lower<'a> { if per_lane { self.s.flags |= flags::WAVE_OPS; let i32t = self.s.t.i32; - d = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]); + let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]); + d = if self.s.pixel && super::helper_own() { + let helper = self.helper_lane(); + self.s.m.select(c, helper, d, first) + } else { + first + }; } addr = self.s.m.bin(c, Bin::Add, addr, d); } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 6859840..3a063ea 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -112,7 +112,7 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use bitcode::census; pub use sampler::StaticSampler; -pub use lower::set_host_max_wave; +pub use lower::{host_settings, set_host_max_wave}; pub use rect::rect_list_gs; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, @@ -143,6 +143,14 @@ pub fn loop_limit() -> u32 { }) } +/// Whether a pixel shader's helper lane reads its own value where the console reads the first +/// lane's (`lower.rs` `first_lane`); on unless `VICTORY_HELPER_OWN=0`. Part of the translation: +/// the shader cache keys on it. +pub fn helper_own() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HELPER_OWN").is_none_or(|v| v != "0")) +} + /// Which of a translated program's group barriers wait for the whole /// group (`GroupMemoryBarrierWithGroupSync`); the others keep their memory /// fence and lose the wait. A wait that some thread of the group never @@ -1546,6 +1554,32 @@ mod barycentric_tests { emit(&c, &native, &p, &st, &io, &res) } + /// A pixel program's first-lane loop (no table entry in it, so not a waterfall the tracker + /// knows) asks for helper lanes, which is valid DXIL (upstream #946's program). + #[test] + fn a_pixel_first_lane_loop_serves_helper_lanes() { + let shader = pixel( + &[ + 0xD765_0000, 0x0001_00C1, // v_mbcnt_lo_u32_b32 v0, -1, 0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0x7E18_0500, // v_readfirstlane_b32 s12, v0 + 0x7D84_000C, // v_cmp_eq_u32 vcc, s12, v0 + 0xBE95_3C6A, // s_and_saveexec_b32 s21, vcc_lo + 0xBF80_0000, // s_nop 0 + 0x7E02_02FF, 0x3F80_0000, // v_mov_b32 v1, 1.0 + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFF8, // s_cbranch_execnz loop + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xF800_180F, 0x0101_0101, // exp mrt0 v1 v1 v1 v1 done vm + 0xBF81_0000, // s_endpgm + ], + 0, + ) + .unwrap(); + validate(&shader); + } + /// The translation's `SFI0` features and `ISG1` rows. fn parts(shader: &HostShader) -> (u64, Vec) { let c = Container::parse(&shader.dxil).unwrap(); diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 4626982..5fff3fd 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -125,6 +125,11 @@ pub fn set_view_heap_limit(null_slot: u32) { VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed); } +/// See [`set_view_heap_limit`]. +pub(super) fn view_heap_limit() -> u32 { + VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed) +} + pub(crate) struct Shader { pub m: Module, pub t: Types, From c96b4f2b8365bf43d54ab074940923ef8267f4c6 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:22:06 -0500 Subject: [PATCH 154/445] The depth bounds test works (#82); faster defaults; textures are on the card before the character bake; one host copy per placed texture - The depth bounds test (#82 by Kaivyyy, as is): a pipeline that enables it is made from a DEPTH_STENCIL1 stream under its own library name, and the title's OMSetDepthBounds reaches the host list. Before, such draws passed at every depth. On the test machine (RTX 4070) the first room is lit by its lamp for the first time: walls, table, bunks. - Defaults: what shaders wrote is copied back by a thread of its own (stage 2), wide copy-back, card copies from 1 MiB up to 1,024 MB, and 256 lists in the air. About 230 ms a frame where it was about 400. Off: VICTORY_RELAY=0, VICTORY_WIDE_BACK=0, VICTORY_CARD_BUFFERS_MIN_MB=16 VICTORY_CARD_BUFFERS_MB=512, VICTORY_LATE_WAIT_LISTS=128. - Textures picked by index are uploaded while loading and before a draw of the title's decoration bake, which samples them by index and runs once (VICTORY_EARLY_TEXTURES_MS, VICTORY_BAKE_TEXTURES_MS; 0 turns each off). - Placed textures are keyed without the filler words of their description: two views that differed only there each had a host copy (VICTORY_PLACED_FILLER=1 keeps the old key). - VICTORY_TEXTURE_ROOM_PERCENT (90, unchanged) sets how full the card may get before textures picked by index wait. Known: the first room's walls are still missing in some launches, and shaded areas are too dark (the bounce light has no ray-tracing structure to trace yet). Co-Authored-By: Claude Fable 5.2 --- crates/victory-gpu/src/copystat.rs | 4 + crates/victory-gpu/src/draw.rs | 139 ++++++- crates/victory-gpu/src/host.rs | 33 +- crates/victory-gpu/src/list.rs | 17 +- crates/victory-gpu/src/pipeline/host.rs | 488 +++++++++++++++++++++--- crates/victory-gpu/src/resource.rs | 75 +++- crates/victory-gpu/src/shadow.rs | 16 +- crates/victory-gpu/src/texture.rs | 65 +++- 8 files changed, 761 insertions(+), 76 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 6abd41b..4a2b785 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -778,6 +778,10 @@ fn log_memory() { made[4], mb(made[5]), ); + tracing::info!( + "memory, placed textures: {} of them were asked for again with other filler words in their description (one resource and host copy each since the filler left the key; VICTORY_PLACED_FILLER=1 keeps it)", + crate::resource::placed_filler_twins() + ); // What the line above leaves open: what is alive of the buffers "made // so far", what the windows hold and what holds them, and what our own // code has allocated. diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e135422..c018811 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -66,8 +66,46 @@ thread_local! { /// While a stage's tables are walked (`State::tables`): whether that /// stage's shader can store to buffers (`Translated::stores`). static STORES: std::cell::Cell = const { std::cell::Cell::new(true) }; + /// While `State::early_textures` runs the texture pass: the + /// milliseconds and the bytes that run may take, in place of the + /// pass's own per frame. + static PASS_BUDGET: std::cell::Cell> = const { std::cell::Cell::new(None) }; } +/// The milliseconds of every frame the pass that uploads textures picked +/// by index takes before a shader that picks by index has asked for it +/// (`VICTORY_EARLY_TEXTURES_MS`, 12; 0: never, as before), and the +/// milliseconds it may take just before a draw of the title's decoration +/// bake (`VICTORY_BAKE_TEXTURES_MS`, 1500; 0: nothing special). +/// +/// The pass ran only from the first world frame on, where it met some +/// 24,000 slots at once and needed 60-80 frames for them. The title bakes +/// its characters' skin and decorations into textures of its own while it +/// loads, 159-1,165 frames before that (runs 156-174), with a pixel shader +/// that picks its sources by index: whatever was not on the card then was +/// baked as nothing, once, for the run. On the console a texture is there +/// when its bytes are. +fn early_budgets() -> (u64, u64) { + static MS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); + *MS.get_or_init(|| { + let ms = |name: &str, default: u64| { + std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(default) + }; + (ms("VICTORY_EARLY_TEXTURES_MS", 12), ms("VICTORY_BAKE_TEXTURES_MS", 1500)) + }) +} + +/// The pixel shaders of the title's decoration bake (the title: +/// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the +/// frame listings print it. They draw into a 256x256 corner of 2048x2048 +/// targets and name no texture in a table. +const BAKE_PIXEL_SHADERS: [&str; 4] = + ["c0a7fe77b1862e10", "0d1575a396dfe513", "b7cfd8dda91ebb6b", "280967ad158cee0b"]; + +/// Since the start: early runs of the texture pass, and those of them +/// made for a bake draw. +pub(crate) static EARLY_TEXTURE_PASSES: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; + /// Whether a buffer range a shader names through an unordered access view /// is given to shaders as written (snapshot before the submission, compare /// and write back after) only if that shader's code can store to buffers. @@ -175,6 +213,7 @@ pub(crate) struct State { scissors: Vec, blend: Option<[f32; 4]>, stencil: Option, + depth_bounds: Option<[f32; 2]>, /// The indirect records clamped last, if later draws may still read /// them ([`windows`]). window: Option, @@ -616,6 +655,11 @@ impl State { crate::draw::stencil_ref(list, reference); } + pub(crate) fn set_depth_bounds(&mut self, list: &HostList, min: f32, max: f32) { + self.depth_bounds = Some([min, max]); + crate::draw::depth_bounds(list, min, max); + } + /// `list` is a new host list that continues the title's list (it was /// cut at a wait for a memory value, `crate::list::cut`): a new host /// list has nothing set, so what the title set so far is set again. @@ -652,6 +696,9 @@ impl State { if let Some(reference) = self.stencil { crate::draw::stencil_ref(list, reference); } + if let Some([min, max]) = self.depth_bounds { + crate::draw::depth_bounds(list, min, max); + } } /// The user-data value of a root argument, as translated shaders read @@ -864,6 +911,8 @@ impl State { /// could not be given a view. pub(crate) fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { let l = &list.list; + // Textures picked by index, before anything asks for them. + self.early_textures(list, p, compute); // Heaps first: a root signature with directly indexed heaps must be // set after them. if self.host_heaps != self.heaps { @@ -1435,6 +1484,72 @@ impl State { Some(gpu) } + /// Runs the pass that uploads textures picked by index + /// ([`State::heap_textures`]) where nothing has asked for it yet + /// ([`early_budgets`]): once a frame for a few milliseconds, at the + /// frame's first draw with a view heap set, and with a larger budget + /// of its own before every draw whose pixel shader is one of the + /// title's bake programs. The uploads are recorded into `list` ahead + /// of the draw being bound, as the world's pass records them. + fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) { + let (early_ms, bake_ms) = early_budgets(); + if compute || (early_ms == 0 && bake_ms == 0) { + return; + } + let bake = bake_ms > 0 + && p.stages.iter().any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str())); + static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + // The milliseconds this frame's bake draws have taken so far: a + // frame has several, and together they get `bake_ms`. + static BAKED_MS: AtomicU64 = AtomicU64::new(0); + let frame = crate::frame::current(); + let first = FRAME.swap(frame, Ordering::Relaxed) != frame; + if first { + BAKED_MS.store(0, Ordering::Relaxed); + } + let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); + let budget = if bake && left > 0 { + // What a bake may read must be there now: up to 2 GiB. + (left, 2 << 30) + } else if first && early_ms > 0 { + (early_ms, 64 << 20) + } else { + return; + }; + let Some(heap) = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers()) + else { + return; + }; + let Some(host) = heap.host() else { + return; + }; + let bake = bake && left > 0; + let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1; + if bake && n.is_power_of_two() { + let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); + tracing::info!( + frame, + bakes = n, + queued_at_the_last_pass = slots, + due_at_the_last_pass = due, + uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed), + "a draw of the title's decoration bake: textures picked by index are uploaded first (VICTORY_BAKE_TEXTURES_MS=0: not)" + ); + } + let began = std::time::Instant::now(); + PASS_BUDGET.set(Some(budget)); + self.heap_textures(list, heap, host); + PASS_BUDGET.set(None); + if bake { + BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); + } + } + /// The texture side of [`State::heap_buffers`]: textures the title fills /// itself (streamed pages, layout-library copies) whose views sit in the /// view heap are created (placed textures have no host texture until @@ -1529,9 +1644,18 @@ impl State { static CATCHUP: std::sync::OnceLock = std::sync::OnceLock::new(); let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0")); let (per_frame, span) = if catchup && due.len() >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) }; + // A run made early (`State::early_textures`) has a budget of its + // own: its bytes on top of what the frame has spent so far. + // (Not `most`: that is the longest wait between looks, used below.) + let (span, bytes_at_most) = match PASS_BUDGET.get() { + Some((ms, bytes)) => { + (std::time::Duration::from_millis(ms), SPENT.load(Ordering::Relaxed).saturating_add(bytes)) + } + None => (span, per_frame), + }; let began = std::time::Instant::now(); for (index, write) in due { - if SPENT.load(Ordering::Relaxed) >= per_frame || began.elapsed() > span { + if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span { break; } // A placed texture whose memory is not mapped (not streamed in @@ -2763,3 +2887,16 @@ pub(crate) fn stencil_ref(list: &HostList, reference: u32) { // SAFETY: an open list. unsafe { list.list.OMSetStencilRef(reference) }; } + +pub(crate) fn depth_bounds(list: &HostList, min: f32, max: f32) { + #[cfg(feature = "diagnostics")] + crate::capture::op(std::ptr::from_ref(list) as usize, || { + format!("DEPTH BOUNDS {min}..{max}") + }); + if crate::host::host().is_some_and(|h| h.depth_bounds()) + && let Ok(l1) = list.list.cast::() + { + // SAFETY: an open list on a device that supports depth bounds. + unsafe { l1.OMSetDepthBounds(min, max) }; + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index e073616..b384328 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1829,7 +1829,10 @@ pub(crate) fn relay() -> bool { /// both wait for everything. fn relay_exact() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_some_and(|v| v == "2")) + // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default + // since the walls of the first room were found drawn in every run with + // this set and in fewer than half without it). + *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2")) } /// Told when something joins [`LINE`], for the thread that lands flights @@ -1919,7 +1922,10 @@ mod relay_tests { } /// The most host lists in the air before the flights are settled -/// (`VICTORY_LATE_WAIT_LISTS`, 128; 32 settled the flights three times a +/// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the +/// relay it stopped the submitting thread twice a frame for 92-103 ms in +/// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162; +/// 32 settled the flights three times a /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables /// asked and none refused; watch "tables asked, N refused"): their dynamic /// descriptor slots, upload @@ -1928,7 +1934,7 @@ mod relay_tests { fn late_most() -> usize { static MOST: OnceLock = OnceLock::new(); *MOST.get_or_init(|| { - std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(128).max(1) + std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1) }) } @@ -2816,6 +2822,27 @@ impl Host { }) } + /// Whether the host GPU supports the depth bounds test; logged once. + pub(crate) fn depth_bounds(&self) -> bool { + static BOUNDS: OnceLock = OnceLock::new(); + *BOUNDS.get_or_init(|| { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default(); + // SAFETY: writes `options` of the given size. + let ok = unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS2, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + }; + let supported = ok && options.DepthBoundsTestSupported.as_bool(); + tracing::info!(supported, "host depth bounds support"); + supported + }) + } + /// A new list, open for recording. pub(crate) fn new_list(&self) -> windows::core::Result { #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 8ce9856..44c8965 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1433,17 +1433,6 @@ extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mu /// nothing returned. extern "system" fn ignored_state(_: This) {} -/// Depth bounds `(min, max)`. -/// shortcut: not set on the host list (no host pipeline of ours enables -/// the test, `pipeline::host`); the first values are logged, so a run -/// shows whether the title uses the test at all. -extern "system" fn depth_bounds(_: This, min: f32, max: f32) { - static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 8 { - tracing::info!(min, max, "the title sets depth bounds, which the host is not given"); - } -} - /// The title's draw state (decision 0007, step 3), kept for its draws or /// set on the host list at once. Without a host GPU these do nothing. #[cfg(windows)] @@ -1486,6 +1475,9 @@ mod state { pub(super) extern "system" fn stencil_ref(this: This, reference: u32) { with_state(this, |list, s| s.set_stencil_ref(list, reference)); } + pub(super) extern "system" fn depth_bounds(this: This, min: f32, max: f32) { + with_state(this, |list, s| s.set_depth_bounds(list, min, max)); + } pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) { with_state(this, |_, s| s.set_heaps(items(heaps, count))); } @@ -1653,6 +1645,7 @@ mod state { pub(super) use super::ignored_state as index_buffer; pub(super) use super::ignored_state as scissors; pub(super) use super::ignored_state as stencil_ref; + pub(super) use super::ignored_state as depth_bounds; pub(super) use super::ignored_state as targets; pub(super) use super::ignored_state as topology; pub(super) use super::ignored_state as vertex_buffers; @@ -2097,7 +2090,7 @@ const METHODS: [(usize, *const ()); 52] = [ (52, clear_rtv as *const ()), // 0x1a0 (59, execute_indirect as *const ()), // 0x1d8 indirect (60, copy_memory as *const ()), // 0x1e0 - (68, depth_bounds as *const ()), // 0x220 depth bounds + (68, state::depth_bounds as *const ()), // 0x220 depth bounds (69, write32 as *const ()), // 0x228 (70, write64 as *const ()), // 0x230 (71, wait_value as *const ()), // 0x238, 32 bits diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index e8d4579..9aef7b8 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -24,6 +24,7 @@ pub(crate) struct GraphicsState { sample_mask: u32, rasterizer: D3D12_RASTERIZER_DESC, depth: D3D12_DEPTH_STENCIL_DESC, + depth_bounds: bool, /// Input elements, their names pointing into `names`. inputs: Vec, names: Vec, @@ -75,6 +76,7 @@ impl Default for GraphicsState { BackFace: keep, ..Default::default() }, + depth_bounds: false, inputs: Vec::new(), names: Vec::new(), strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, @@ -103,21 +105,13 @@ impl GraphicsState { 8 => self.blend = data.cast::().read_unaligned(), 9 => self.sample_mask = data.cast::().read_unaligned(), 10 => self.rasterizer = data.cast::().read_unaligned(), - 11 => self.depth = data.cast::().read_unaligned(), + 11 => { + self.depth = data.cast::().read_unaligned(); + self.depth_bounds = false; + } 21 => { - // shortcut: the depth bounds test is dropped (the host - // pipeline uses the plain description); bring it back - // with a stream if a title enables it. let d = data.cast::().read_unaligned(); - if d.DepthBoundsTestEnable.as_bool() { - static SEEN: std::sync::atomic::AtomicU64 = - std::sync::atomic::AtomicU64::new(0); - if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { - tracing::warn!( - "a pipeline enables the depth bounds test, which its host pipeline leaves out: its draws pass at every depth" - ); - } - } + self.depth_bounds = d.DepthBoundsTestEnable.as_bool(); self.depth = D3D12_DEPTH_STENCIL_DESC { DepthEnable: d.DepthEnable, DepthWriteMask: d.DepthWriteMask, @@ -194,8 +188,13 @@ impl GraphicsState { ) }) .collect(); + let bounds = if self.depth_bounds { + " depth-bounds" + } else { + "" + }; format!( - "{:?} {} {:?} {:?} {inputs:?} {} {} {:?} {} {:?}", + "{:?} {} {:?} {:?}{bounds} {inputs:?} {} {} {:?} {} {:?}", self.blend, self.sample_mask, self.rasterizer, @@ -208,6 +207,21 @@ impl GraphicsState { ) } + fn depth1(&self) -> D3D12_DEPTH_STENCIL_DESC1 { + let d = &self.depth; + D3D12_DEPTH_STENCIL_DESC1 { + DepthEnable: d.DepthEnable, + DepthWriteMask: d.DepthWriteMask, + DepthFunc: d.DepthFunc, + StencilEnable: d.StencilEnable, + StencilReadMask: d.StencilReadMask, + StencilWriteMask: d.StencilWriteMask, + FrontFace: d.FrontFace, + BackFace: d.BackFace, + DepthBoundsTestEnable: self.depth_bounds.into(), + } + } + /// The vertex buffer slots the input layout reads. fn slots(&self) -> u32 { self.inputs @@ -545,6 +559,21 @@ impl HostPipeline { let Some(g) = g else { return refuse("graphics state not kept (plain description)", shaders); }; + let depth_bounds = if g.depth_bounds { + if host.depth_bounds() { + true + } else { + static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + tracing::warn!( + "a pipeline enables the depth bounds test, which the host GPU does not support: its draws pass at every depth" + ); + } + false + } + } else { + false + }; let state = g.describe(); if mesh.is_some() { // "triangles": the stream names its topology since it did not @@ -557,7 +586,7 @@ impl HostPipeline { &[&code_bytes(&code(0)), &code_bytes(&code(1))], &state, ); - let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g, &name) { + let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g, depth_bounds, &name) { Ok(pso) => pso, Err(e) => { tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused"); @@ -643,6 +672,9 @@ impl HostPipeline { ), }; let make = |desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, name: &str| { + if depth_bounds { + return graphics_depth_bounds_pipeline(&host.device, &root, desc, g.depth1(), name); + } super::library::pipeline( name, // SAFETY: the description points at live data. @@ -673,6 +705,7 @@ impl HostPipeline { tracing::debug!( ?shaders, depth = ?g.depth, + depth_bounds, dsv = g.depth_format.0, targets = ?&g.targets.RTFormats[..g.targets.NumRenderTargets.min(8) as usize], blend = ?g.blend.RenderTarget[0], @@ -697,8 +730,9 @@ impl HostPipeline { f.StencilFailOp.0, f.StencilDepthFailOp.0, f.StencilPassOp.0, f.StencilFunc.0 ) }; + let bounds = if depth_bounds { " bounds true" } else { "" }; format!( - "depth {} write {} func {}; stencil {} read {:#x} write {:#x} front [{}] back [{}]; cull {} front-ccw {}; blend {} src {} dst {} op {} mask {:#x}", + "depth {} write {} func {}{bounds}; stencil {} read {:#x} write {:#x} front [{}] back [{}]; cull {} front-ccw {}; blend {} src {} dst {} op {} mask {:#x}", d.DepthEnable.as_bool(), d.DepthWriteMask.0, d.DepthFunc.0, @@ -720,6 +754,93 @@ impl HostPipeline { } } +/// A stream subobject: its type, then its description, pointer-aligned. +#[repr(C, align(8))] +struct Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); + +fn stream_pipeline( + device: &ID3D12Device, + stream: &mut S, + name: &str, +) -> windows::core::Result { + use windows::core::Interface; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::(), + pPipelineStateSubobjectStream: std::ptr::from_mut(stream).cast(), + }; + let device = device.cast::()?; + super::library::pipeline( + name, + // SAFETY: the stream holds whole subobjects pointing at live data. + |library, name| unsafe { library.LoadPipeline(name, &desc) }, + // SAFETY: as above. + || unsafe { device.CreatePipelineState(&desc) }, + ) +} + +/// A graphics pipeline enabling the depth bounds test: `D3D12_GRAPHICS_PIPELINE_STATE_DESC` +/// has no field for `DepthBoundsTestEnable`, so it is created and loaded as a +/// pipeline-state stream with `DEPTH_STENCIL1`. +fn graphics_depth_bounds_pipeline( + device: &ID3D12Device, + root: &ID3D12RootSignature, + d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + depth: D3D12_DEPTH_STENCIL_DESC1, + name: &str, +) -> windows::core::Result { + use windows::core::Interface; + #[repr(C)] + struct Stream { + root: Sub<*mut std::ffi::c_void>, + vs: Sub, + ps: Sub, + blend: Sub, + mask: Sub, + raster: Sub, + depth: Sub, + input: Sub, + strip_cut: Sub, + topology: Sub, + targets: Sub, + dsv: Sub, + samples: Sub, + } + #[repr(C)] + struct StreamGs { + base: Stream, + gs: Sub, + } + let targets = D3D12_RT_FORMAT_ARRAY { + RTFormats: d.RTVFormats, + NumRenderTargets: d.NumRenderTargets, + }; + let base = Stream { + root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), + vs: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, d.VS), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, d.PS), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, d.BlendState), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, d.SampleMask), + raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, d.RasterizerState), + depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, depth), + input: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, d.InputLayout), + strip_cut: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, d.IBStripCutValue), + topology: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, d.PrimitiveTopologyType), + targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, targets), + dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, d.DSVFormat), + samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, d.SampleDesc), + }; + if d.GS.pShaderBytecode.is_null() { + let mut stream = base; + stream_pipeline(device, &mut stream, name) + } else { + let mut stream = StreamGs { + base, + gs: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, d.GS), + }; + stream_pipeline(device, &mut stream, name) + } +} + /// A mesh pipeline from the title's graphics state: the pipeline-state /// stream form (no input layout). /// @@ -737,54 +858,64 @@ fn mesh_pipeline( ms: D3D12_SHADER_BYTECODE, ps: D3D12_SHADER_BYTECODE, g: &GraphicsState, + depth_bounds: bool, name: &str, ) -> windows::core::Result { use windows::core::Interface; - /// A stream subobject: its type, then its description, pointer-aligned. - #[repr(C, align(8))] - struct Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); #[repr(C)] - struct Stream { + struct Stream { root: Sub<*mut std::ffi::c_void>, ms: Sub, ps: Sub, blend: Sub, mask: Sub, raster: Sub, - depth: Sub, + depth: Sub, targets: Sub, dsv: Sub, samples: Sub, topology: Sub, } - let mut stream = Stream { - root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), - ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms), - ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), - blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend), - mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask), - raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), - depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth), - targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets), - dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format), - samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples), - topology: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, - D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, - ), + let build = |depth: Sub<_>| { + let mut stream = Stream { + root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), + ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask), + raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), + depth, + targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets), + dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format), + samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples), + topology: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + ), + }; + stream_pipeline(device, &mut stream, name) }; - let desc = D3D12_PIPELINE_STATE_STREAM_DESC { - SizeInBytes: size_of::(), - pPipelineStateSubobjectStream: (&raw mut stream).cast(), - }; - let device = device.cast::()?; - super::library::pipeline( - name, - // SAFETY: the stream holds whole subobjects pointing at live data. - |library, name| unsafe { library.LoadPipeline(name, &desc) }, - // SAFETY: as above. - || unsafe { device.CreatePipelineState(&desc) }, - ) + if depth_bounds { + let mut stream = Stream { + root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), + ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask), + raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), + depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, g.depth1()), + targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets), + dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format), + samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples), + topology: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + ), + }; + stream_pipeline(device, &mut stream, name) + } else { + build(Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth)) + } } /// The bytes of shader code (none for an absent stage). @@ -920,12 +1051,269 @@ mod tests { g.targets.NumRenderTargets = 1; g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; let name = super::super::library::name("mesh test", &root_blob, &[&ms, &ps], &g.describe()); - mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, &name).expect("made"); + mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, false, &name).expect("made"); let loaded = super::super::library::LOADED.load(Ordering::Relaxed); - mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, &name).expect("made again"); + mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, false, &name).expect("made again"); assert!( super::super::library::LOADED.load(Ordering::Relaxed) > loaded, "the mesh pipeline was compiled again instead of loaded from the library" ); } + + const VS: &str = "float4 main(uint i : SV_VertexID) : SV_Position { + float2 p = float2((i << 1) & 2, i & 2); + return float4(p * 2.0 - 1.0, 0.5, 1.0); + }"; + + /// A graphics pipeline with `DepthBoundsTestEnable` loads back from the + /// pipeline library and culls or passes fragments according to + /// `OMSetDepthBounds` (including across a command-list cut). + #[test] + fn depth_bounds_pipeline_loads_and_filters_draws() { + let Some(host) = host() else { + return; + }; + if !host.depth_bounds() { + eprintln!("no host depth bounds support; skipped"); + return; + } + let Some(dxc) = dxc() else { + eprintln!("no PC dxc.exe; skipped"); + return; + }; + let dir = tempfile::tempdir().unwrap(); + let vs = compile(&dxc, dir.path(), VS, "vs_6_5"); + let ps = compile(&dxc, dir.path(), PS, "ps_6_5"); + let (root, root_blob) = root_signature(&host.device, &[], &[], false).unwrap(); + + let mut g = GraphicsState::default(); + // Subobject 21 (`DEPTH_STENCIL1`) with `DepthBoundsTestEnable = true`, + // depth test itself off so only depth bounds gates the draw. + #[repr(C, align(8))] + struct Sub21(u32, D3D12_DEPTH_STENCIL_DESC1); + let sub = Sub21( + 21, + D3D12_DEPTH_STENCIL_DESC1 { + DepthEnable: false.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS, + DepthBoundsTestEnable: true.into(), + ..Default::default() + }, + ); + // SAFETY: `sub` is a complete subobject 21. + unsafe { g.read(21, (&raw const sub).cast()) }; + assert!(g.depth_bounds); + assert!(g.describe().contains("depth-bounds")); + g.rasterizer.CullMode = D3D12_CULL_MODE_NONE; + g.targets.NumRenderTargets = 1; + g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + g.depth_format = DXGI_FORMAT_D32_FLOAT; + + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // SAFETY: borrowed pointer, never released by the descriptor. + pRootSignature: unsafe { std::mem::transmute_copy(&root) }, + VS: code(&vs), + PS: code(&ps), + BlendState: g.blend, + SampleMask: g.sample_mask, + RasterizerState: g.rasterizer, + DepthStencilState: g.depth, + IBStripCutValue: g.strip_cut, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: g.targets.RTFormats, + DSVFormat: g.depth_format, + SampleDesc: g.samples, + ..Default::default() + }; + let name = super::super::library::name( + "graphics depth-bounds test", + &root_blob, + &[&vs, &ps], + &g.describe(), + ); + let pso = graphics_depth_bounds_pipeline(&host.device, &root, &desc, g.depth1(), &name) + .expect("depth-bounds PSO made"); + let loaded = super::super::library::LOADED.load(Ordering::Relaxed); + graphics_depth_bounds_pipeline(&host.device, &root, &desc, g.depth1(), &name) + .expect("depth-bounds PSO made again"); + assert!( + super::super::library::LOADED.load(Ordering::Relaxed) > loaded, + "the depth-bounds pipeline was compiled again instead of loaded from the library" + ); + + // Execute two draws against a depth buffer cleared to 0.5: + // 1) bounds [0.6, 1.0] -> rejected (target stays 0) + // 2) bounds [0.4, 0.6] replayed onto a fresh HostList -> passes (target becomes 255) + let make_tex = |format, flags, state, clear: D3D12_CLEAR_VALUE| { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 4, + Height: 4, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: flags, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: valid heap and resource descriptions. + unsafe { + host.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &rd, state, Some(&clear), &mut out) + .unwrap(); + } + out.unwrap() + }; + let color = make_tex( + DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_CLEAR_VALUE { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0; 4] }, + }, + ); + let depth = make_tex( + DXGI_FORMAT_D32_FLOAT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_CLEAR_VALUE { + Format: DXGI_FORMAT_D32_FLOAT, + Anonymous: D3D12_CLEAR_VALUE_0 { + DepthStencil: D3D12_DEPTH_STENCIL_VALUE { + Depth: 0.5, + Stencil: 0, + }, + }, + }, + ); + let readback = { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: valid readback buffer description. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &rd, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut out, + ) + .unwrap(); + } + out.unwrap() + }; + + let run_draw = |min: f32, max: f32| -> u8 { + let mut state = crate::draw::State::default(); + let first_list = host.new_list().unwrap(); + state.set_depth_bounds(&first_list, min, max); + first_list.close(); + // Replay onto a second host list, exercising `State::replay`. + let list = host.new_list().unwrap(); + state.replay(&list); + let rtv = host.rtv(Some(&color), None); + let dsv = host.dsv(&depth, None); + let vp = D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: 4.0, + Height: 4.0, + MinDepth: 0.0, + MaxDepth: 1.0, + }; + let rect = windows::Win32::Foundation::RECT { + left: 0, + top: 0, + right: 4, + bottom: 4, + }; + // SAFETY: open command list, live resources and views. + unsafe { + list.list.ClearRenderTargetView(rtv, &[0.0; 4], None); + list.list.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 0.5, 0, None); + list.list.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv)); + list.list.RSSetViewports(&[vp]); + list.list.RSSetScissorRects(&[rect]); + list.list.SetGraphicsRootSignature(&root); + list.list.SetPipelineState(&pso); + list.list + .IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list.list.DrawInstanced(3, 1, 0, 0); + list.list.ResourceBarrier(&[crate::host::transition( + &color, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + 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: DXGI_FORMAT_R8G8B8A8_UNORM, + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&color), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + list.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.list.ResourceBarrier(&[crate::host::transition( + &color, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET, + )]); + } + list.close(); + host.execute(&[&list]); + let mut ptr = std::ptr::null_mut(); + // SAFETY: `execute` waited for the GPU; readback holds 1024 bytes. + unsafe { + readback.Map(0, None, Some(&mut ptr)).unwrap(); + let pixel = *ptr.cast::(); + readback.Unmap(0, None); + pixel + } + }; + + assert_eq!(run_draw(0.6, 1.0), 0, "depth 0.5 outside [0.6, 1.0] must be rejected"); + assert_eq!(run_draw(0.4, 0.6), 255, "depth 0.5 inside [0.4, 0.6] must pass"); + } } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index f69d9e2..bb6a00a 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1358,9 +1358,9 @@ pub(crate) fn host_made<'a>( /// shaders that pick textures by index (`draw.rs` `heap_textures`): always /// up to `FLOOR` bytes of them, beyond that while the card's memory in use /// by this process is under nine tenths of the budget the system gives it -/// (`VICTORY_TEXTURE_BUDGET_MB` sets a limit on those copies' bytes -/// instead). Past the budget the system moves the card's memory into the -/// PC's, which ended runs 20 and 24. +/// ([`room_percent`] says another share; `VICTORY_TEXTURE_BUDGET_MB` sets a +/// limit on those copies' bytes instead). Past the budget the system moves +/// the card's memory into the PC's, which ended runs 20 and 24. #[cfg(windows)] pub(crate) fn room() -> bool { use std::sync::atomic::Ordering::Relaxed; @@ -1379,11 +1379,29 @@ pub(crate) fn room() -> bool { return true; } match crate::host::host().and_then(|h| h.video_memory()) { - Some([budget, used, ..]) => used < budget / 10 * 9, + Some([budget, used, ..]) => used < budget / 100 * room_percent(), None => filled < WITHOUT_BUDGET, } } +/// The share of the card's budget, in percent, up to which host copies of +/// textures picked by index are made ([`room`]): 90 unless +/// `VICTORY_TEXTURE_ROOM_PERCENT` says another (50 to 97). At 90 about a +/// tenth of the budget, 1,020 MB of 10,200, stays unused while thousands of +/// textures wait (runs 170-174); the card copies of title buffers from +/// 1 MiB up take 449 MB more of the card than before (941 against 492), +/// and 94 gives the textures about that much back. +#[cfg(windows)] +fn room_percent() -> u64 { + static PERCENT: std::sync::OnceLock = std::sync::OnceLock::new(); + *PERCENT.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_ROOM_PERCENT") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map_or(90, |percent| percent.clamp(50, 97)) + }) +} + /// Lets go of the host copies of textures the title fills that nothing /// names any more: placed textures were never released (one host texture /// per address and description ever viewed: 18,639 of them, 2.5 GB, after @@ -2018,6 +2036,24 @@ pub(crate) extern "system" fn create_at_address( static PLACED_TEXTURES: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); +/// The placed textures asked for with filler words set, as asked +/// (address and description): for [`PLACED_TWINS`]. +#[cfg(windows)] +static PLACED_RAW: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); + +/// Placed textures asked for a second time with other filler words in +/// their description: each was a second resource and host copy before the +/// filler was left out of the key ([`texture_at`]). +#[cfg(windows)] +static PLACED_TWINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// See [`PLACED_TWINS`]. +#[cfg(windows)] +pub(crate) fn placed_filler_twins() -> u64 { + PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed) +} + /// The bytes of title memory a texture with the resource description /// `desc` (as words) takes where the title placed it; `None` for a buffer /// and for a description without a size. @@ -2035,7 +2071,37 @@ pub(crate) fn placed_bytes(desc: &[u32; 14]) -> Option { /// description `desc` (as words), made on first use. #[cfg(windows)] pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { + // Words 1 and 13 of the description are the filler of its layout + // (after the dimension, and at the end): the title leaves there what + // its stack held, and two views of one texture that differed only in + // them each got a resource and a host copy of their own, on a card + // that fills at world entry. They are not part of what a texture is. + // `VICTORY_PLACED_FILLER=1`: kept in the key, as before. + static KEPT: std::sync::OnceLock = std::sync::OnceLock::new(); + let raw = *desc; + let mut key = *desc; + if !*KEPT.get_or_init(|| std::env::var_os("VICTORY_PLACED_FILLER").is_some_and(|v| v == "1")) { + key[1] = 0; + key[13] = 0; + } + let desc = &key; let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + // How many resources the filler alone would have added (a count for + // the log: `placed_filler_twins`). + if raw != key { + let mut seen = PLACED_RAW.lock().unwrap_or_else(|e| e.into_inner()); + if seen.insert((address, raw)) { + let others = seen.range((address, [0; 14])..=(address, [u32::MAX; 14])).filter(|(_, r)| { + let mut blank = *r; + blank[1] = 0; + blank[13] = 0; + blank == key + }); + if others.count() > 1 { + PLACED_TWINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + } if let Some(&r) = map.get(&(address, *desc)) { return Some(r as This); } @@ -2058,6 +2124,7 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { return None; } map.insert((address, *desc), out as usize); + crate::texture::placed_in_host_written(address, desc); resource(out) .host .placed diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index afd2b9c..da412f8 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -151,7 +151,11 @@ fn card_limits() -> (u64, u64) { let mb = |name: &str, default: u64| { std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(default) << 20 }; - (mb("VICTORY_CARD_BUFFERS_MIN_MB", 16).max(1 << 20), mb("VICTORY_CARD_BUFFERS_MB", 512)) + // From 1 MiB up and 1,024 MB in all by default (it was 16 and 512): + // the shader writes of the smaller buffers are then found by the + // card's hashes too, and with that the first room's walls were + // drawn in every run. + (mb("VICTORY_CARD_BUFFERS_MIN_MB", 1).max(1 << 20), mb("VICTORY_CARD_BUFFERS_MB", 1024)) }) } @@ -470,7 +474,12 @@ mod card_tests { /// had not received from bytes the card wrote. pub(crate) fn relay() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("VICTORY_RELAY").is_ok_and(|v| v == "1" || v == "2") && !keeps()) + // On by default (stage 2, `crate::host::relay_exact`); `VICTORY_RELAY=0` + // turns it off, `=1` asks for the first stage. + // The crate's own tests run without it unless they ask: several of + // them look at title memory right after a submission, which the + // relay's landing thread may still be writing. + *ON.get_or_init(|| std::env::var("VICTORY_RELAY").map_or(!cfg!(test), |v| v == "1" || v == "2") && !keeps()) } /// The submission being prepared (its number among those started): what @@ -958,7 +967,8 @@ unsafe fn copy_wide(src: *const u8, dst: *mut u8, len: usize) { /// lists only afterwards). pub(crate) fn wide_back() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_BACK").is_some_and(|v| v == "1")) + // On by default; `VICTORY_WIDE_BACK=0` turns it off. + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_BACK").is_none_or(|v| v != "0")) } type Job = Box; diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index c8f35c9..41d6f1e 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -457,9 +457,65 @@ static HOST_WRITTEN: Mutex>> = Mutex::ne /// A host copy or resolve writes `resource`. pub(crate) fn host_written(resource: This) { - let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - set.get_or_insert_with(Default::default) - .insert(resource as usize); + let new = { + let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + set.get_or_insert_with(Default::default).insert(resource as usize) + }; + // Diagnostics (run 177): where its title memory is, for placed views + // the title reads that memory through ([`placed_in_host_written`]). + if new && let Some((at, desc)) = crate::resource::texture_memory(resource) { + // SAFETY: 56 bytes in the description's layout. + let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() }; + let bytes = crate::resource::placed_bytes(&words).unwrap_or(0); + if !at.is_null() && bytes > 0 { + HOST_WRITTEN_AT + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(at as u64, (bytes, words[4], words[6], words[7], words[8], resource as usize)); + } + } +} + +/// The title memory of textures the host copied into, by address: bytes +/// and description words 4, 6, 7 and 8 (width, height, layers and levels, +/// format). +static HOST_WRITTEN_AT: Mutex> = + Mutex::new(std::collections::BTreeMap::new()); + +/// A texture the title placed at `address` (description words `desc`) was +/// made: says so once if it lies in the memory of a texture the host +/// copied into ([`host_written`]). Its own host copy is filled from title +/// memory, which the copy never reached: the copied texels are on the +/// card in the other texture, where no shader that reads this view finds +/// them. +pub(crate) fn placed_in_host_written(address: u64, desc: &[u32; 14]) { + let hit = { + let map = HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner()); + map.range(..=address) + .next_back() + .filter(|(at, d)| address < **at + d.0) + .map(|(at, d)| (*at, *d)) + }; + if let Some((at, (bytes, width, height, layers_levels, format, _))) = hit { + static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 200 { + tracing::warn!( + view_address = format_args!("{address:#x}"), + view_offset = address - at, + view_width = desc[4], + view_height = desc[6], + view_layers_levels = format_args!("{:#x}", desc[7]), + view_format = desc[8], + copied_address = format_args!("{at:#x}"), + copied_bytes = bytes, + copied_width = width, + copied_height = height, + copied_layers_levels = format_args!("{layers_levels:#x}"), + copied_format = format, + "HERO LEAD: a placed texture view lies in the memory of a texture the host copied into: it is filled from title memory, which the copy never reached" + ); + } + } } /// Whether the host GPU wrote `resource` by a copy or resolve @@ -483,6 +539,9 @@ pub(crate) fn forget(resource: usize) { if let Some(set) = set.as_mut() { set.remove(&resource); } + // Its memory may be given to other textures now (run 177: most of the + // "HERO LEAD" lines were views in memory a released texture had held). + HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, d| d.5 != resource); let mut through = THROUGH.lock().unwrap_or_else(|e| e.into_inner()); if let Some(through) = through.as_mut() { through.remove(&resource); From 1deaf0ebee50912ab42b57247c33a563286d1eec Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 20:00:23 -0600 Subject: [PATCH 155/445] Record and replay a frame's D3D12 work (diagnostics builds) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/capture.rs | 29 +- crates/victory-gpu/src/host.rs | 15 +- crates/victory-gpu/src/indirect.rs | 2 + crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/replay/edit.rs | 327 ++++ crates/victory-gpu/src/replay/gpu.rs | 392 +++++ crates/victory-gpu/src/replay/hook.rs | 290 ++++ crates/victory-gpu/src/replay/mod.rs | 17 + crates/victory-gpu/src/replay/play.rs | 2042 ++++++++++++++++++++++ crates/victory-gpu/src/replay/pso.rs | 317 ++++ crates/victory-gpu/src/replay/record.rs | 2079 +++++++++++++++++++++++ crates/victory-gpu/src/replay/snap.rs | 923 ++++++++++ crates/victory-gpu/src/replay/states.rs | 192 +++ crates/victory-gpu/src/replay/wire.rs | 741 ++++++++ crates/victory-gpu/tests/replay.rs | 909 ++++++++++ 15 files changed, 8270 insertions(+), 7 deletions(-) create mode 100644 crates/victory-gpu/src/replay/edit.rs create mode 100644 crates/victory-gpu/src/replay/gpu.rs create mode 100644 crates/victory-gpu/src/replay/hook.rs create mode 100644 crates/victory-gpu/src/replay/mod.rs create mode 100644 crates/victory-gpu/src/replay/play.rs create mode 100644 crates/victory-gpu/src/replay/pso.rs create mode 100644 crates/victory-gpu/src/replay/record.rs create mode 100644 crates/victory-gpu/src/replay/snap.rs create mode 100644 crates/victory-gpu/src/replay/states.rs create mode 100644 crates/victory-gpu/src/replay/wire.rs create mode 100644 crates/victory-gpu/tests/replay.rs diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index 19947f3..b4010f8 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -178,6 +178,27 @@ fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: } } } + let png = encode(w, h, &raw); + let path = folder.join(format!("{name}.png")); + match std::fs::write(&path, png) { + Ok(()) => tracing::info!(path = %path.display(), "frame saved"), + Err(e) => tracing::warn!(error = %e, path = %path.display(), "frame not saved"), + } +} + +/// A PNG of `width * height` pixels of 8-bit RGB. +pub(crate) fn png(width: u32, height: u32, rgb: &[u8]) -> Vec { + let row = width as usize * 3; + let mut raw = Vec::with_capacity((row + 1) * height as usize); + for line in rgb.chunks_exact(row.max(1)) { + raw.push(0); + raw.extend_from_slice(line); + } + encode(width, height, &raw) +} + +/// A PNG of rows of RGB, each behind its filter byte. +fn encode(w: u32, h: u32, raw: &[u8]) -> Vec { let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); let mut header = Vec::new(); header.extend(w.to_be_bytes()); @@ -185,15 +206,11 @@ fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: header.extend([8, 2, 0, 0, 0]); // 8-bit RGB chunk(&mut png, b"IHDR", &header); let mut compressed = vec![0u8; zlib_rs::compress_bound(raw.len())]; - let (idat, rc) = zlib_rs::compress_slice(&mut compressed, &raw, zlib_rs::DeflateConfig::new(3)); + let (idat, rc) = zlib_rs::compress_slice(&mut compressed, raw, zlib_rs::DeflateConfig::new(3)); debug_assert_eq!(rc, zlib_rs::ReturnCode::Ok); chunk(&mut png, b"IDAT", idat); chunk(&mut png, b"IEND", &[]); - let path = folder.join(format!("{name}.png")); - match std::fs::write(&path, png) { - Ok(()) => tracing::info!(path = %path.display(), "frame saved"), - Err(e) => tracing::warn!(error = %e, path = %path.display(), "frame not saved"), - } + png } fn chunk(png: &mut Vec, kind: &[u8; 4], data: &[u8]) { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 7c6448a..332ebee 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -602,6 +602,9 @@ fn create() -> windows::core::Result { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; } let device = device.ok_or_else(windows::core::Error::empty)?; + // Before anything is made with it (`VICTORY_RECORD`). + #[cfg(feature = "diagnostics")] + crate::replay::record::from_env(&device); // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the // driver compiling shaders again on the "D3D Background Thread"s, // for minutes after pipelines were made or loaded) is switched off. @@ -1295,8 +1298,14 @@ fn timing() -> bool { } /// Names a host object for the device-removed report, which names the -/// allocations a page fault hit (only with device-removed data on). +/// allocations a page fault hit (only with device-removed data on), or for +/// the frame recorder (`VICTORY_RECORD`). pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) { + #[cfg(feature = "diagnostics")] + if crate::replay::record::on() { + crate::replay::record::name(object, &text()); + return; + } if dred_on() && let Ok(object) = object.cast::() { @@ -3126,6 +3135,8 @@ impl Host { }, ..Default::default() })?; + #[cfg(feature = "diagnostics")] + name(&pso, || crate::replay::play::COMPARE.into()); Ok(CardWork { sync: vec![list()?], check: vec![list()?], @@ -6353,6 +6364,8 @@ impl Host { if let Some((buffer, footprint)) = capture { crate::capture::save_read_back(frame, &buffer, &footprint); } + #[cfg(feature = "diagnostics")] + crate::replay::record::present(texture, state); let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); p.meter.frame(p.hwnd); #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index fbc9805..af7f010 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -279,6 +279,8 @@ fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result, psos: &HashSet) -> (Vec, u32) { + let mut bound = NONE; + let mut dropped = 0; + let out = cmds + .into_iter() + .filter(|c| { + if let Cmd::Pipeline { pso } = c { + bound = *pso; + } + let drop = c.runs_shaders() && psos.contains(&bound); + dropped += u32::from(drop); + !drop + }) + .collect(); + (out, dropped) +} + +/// Drops unordered-access barriers; how many. +pub fn no_uav_barriers(cmds: Vec) -> (Vec, u32) { + let mut dropped = 0; + let out = cmds + .into_iter() + .filter_map(|c| match c { + Cmd::Barriers { mut all } => { + let n = all.len(); + all.retain(|b| !matches!(b, Barrier::Uav { .. })); + dropped += (n - all.len()) as u32; + (!all.is_empty()).then_some(Cmd::Barriers { all }) + } + c => Some(c), + }) + .collect(); + (out, dropped) +} + +/// Barriers only: what a list left out still does to the states of +/// resources. +pub fn barriers_only(cmds: Vec) -> Vec { + cmds.into_iter().filter(|c| matches!(c, Cmd::Barriers { .. })).collect() +} + +/// Joins the barrier calls with no work between them into one; how many +/// calls that saved. +pub fn merge_barriers(cmds: Vec) -> (Vec, u32) { + let mut out: Vec = Vec::with_capacity(cmds.len()); + let mut open: Option = None; + let mut saved = 0; + for c in cmds { + match c { + Cmd::Barriers { all } => { + if let Some(i) = open + && let Cmd::Barriers { all: have } = &mut out[i] + { + for b in all { + join(have, b); + } + saved += 1; + } else { + open = Some(out.len()); + let mut have = Vec::new(); + for b in all { + join(&mut have, b); + } + out.push(Cmd::Barriers { all: have }); + } + } + c => { + if c.works() || matches!(c, Cmd::BeginQuery { .. } | Cmd::EndQuery { .. }) { + open = None; + } + out.push(c); + } + } + } + out.retain(|c| !matches!(c, Cmd::Barriers { all } if all.is_empty())); + (out, saved) +} + +/// Adds a barrier to a call's. +fn join(have: &mut Vec, b: Barrier) { + match b { + Barrier::Uav { res, .. } => { + let covered = have.iter().any(|h| matches!(h, Barrier::Uav { res: r, .. } if *r == res || *r == NONE)); + if covered { + return; + } + if res == NONE { + have.retain(|h| !matches!(h, Barrier::Uav { .. })); + } + have.push(b); + } + Barrier::Transition { flags: 0, res, sub, before, after } => { + // The last one of this resource, if it is of the same part of it. + let last = have.iter().rposition(|h| matches!(h, Barrier::Transition { res: r, .. } if *r == res)); + if let Some(i) = last + && let Barrier::Transition { flags: 0, sub: s, before: first, after: until, .. } = have[i] + && s == sub + && until == before + { + if first != after { + have[i] = Barrier::Transition { flags: 0, res, sub, before: first, after }; + } else { + have.remove(i); + if after == UNORDERED_ACCESS { + // Still a wait for the writes before. + join(have, Barrier::Uav { flags: 0, res }); + } + } + return; + } + have.push(b); + } + b => have.push(b), + } +} + +/// A clamp pass of ours found in a list. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Clamp { + /// The command that dispatches it. + pub at: usize, + /// The scratch buffer it writes the arguments to, from its start. + pub scratch: u32, + pub bytes: u64, + /// Where its arguments are in [`RESULTS`]. + pub result: u64, +} + +/// The clamp passes of a list (`psos`: the clamp's pipelines), given places +/// in the results from `next` on. +pub fn find_clamps(cmds: &[Cmd], psos: &HashSet, next: &mut u64) -> Vec { + let (mut bound, mut constants, mut to) = (NONE, [0u32; 6], None); + let mut found = Vec::new(); + for (at, c) in cmds.iter().enumerate() { + match c { + Cmd::Pipeline { pso } => bound = *pso, + Cmd::Constants { graphics: false, param: 0, offset, values } => { + for (i, v) in values.iter().enumerate() { + if let Some(c) = constants.get_mut(*offset as usize + i) { + *c = *v; + } + } + } + // The clamp's parameters: constants (kind, stride, records, + // ...), arguments, count, then where it writes. + Cmd::RootView { graphics: false, param: 3, va: Va::At { res, offset: 0 }, .. } => to = Some(*res), + Cmd::Dispatch { .. } if psos.contains(&bound) => { + if let Some(scratch) = to { + let bytes = u64::from(constants[1]) * u64::from(constants[2]); + found.push(Clamp { at, scratch, bytes, result: *next }); + *next += bytes.next_multiple_of(256); + } + } + _ => {} + } + } + found +} + +/// The list with a copy of what each clamp wrote into the results. +pub fn keep_clamped(cmds: Vec, clamps: &[Clamp]) -> Vec { + let mut out = Vec::with_capacity(cmds.len() + 3 * clamps.len()); + let mut open: Option = None; + for (at, c) in cmds.into_iter().enumerate() { + if let Some(clamp) = clamps.iter().find(|c| c.at == at) { + open = Some(*clamp); + } + let readable = |b: &Barrier, scratch: u32| matches!(b, Barrier::Transition { res, after: INDIRECT_ARGUMENT, .. } if *res == scratch); + let done = match (&c, open) { + (Cmd::Barriers { all }, Some(clamp)) => all.iter().any(|b| readable(b, clamp.scratch)), + _ => false, + }; + out.push(c); + if done && let Some(clamp) = open.take() { + let moved = |before, after| Cmd::Barriers { + all: vec![Barrier::Transition { flags: 0, res: clamp.scratch, sub: ALL, before, after }], + }; + out.push(moved(INDIRECT_ARGUMENT, COPY_SOURCE)); + out.push(Cmd::CopyBuffer { dst: RESULTS, dst_at: clamp.result, src: clamp.scratch, src_at: 0, len: clamp.bytes }); + out.push(moved(COPY_SOURCE, INDIRECT_ARGUMENT)); + } + } + out +} + +/// The list without its clamp passes and the barriers of their scratch +/// buffers; what they bounded is read from the results instead. +pub fn skip_clamps(cmds: Vec, clamps: &[Clamp]) -> Vec { + let scratches: HashSet = clamps.iter().map(|c| c.scratch).collect(); + let by_at: HashMap = clamps.iter().map(|c| (c.at, c)).collect(); + let mut last: HashMap = HashMap::new(); + let mut out = Vec::with_capacity(cmds.len()); + for (at, c) in cmds.into_iter().enumerate() { + if let Some(clamp) = by_at.get(&at) { + last.insert(clamp.scratch, clamp.result); + continue; + } + match c { + Cmd::Barriers { mut all } => { + let of_scratch = |b: &Barrier| matches!(b, Barrier::Transition { res, .. } if scratches.contains(res)); + if all.iter().any(of_scratch) { + // The waits made with the scratch buffer's moves are the + // clamp's too. + all.retain(|b| !of_scratch(b) && !matches!(b, Barrier::Uav { res: NONE, .. })); + } + if !all.is_empty() { + out.push(Cmd::Barriers { all }); + } + } + Cmd::Indirect { signature, most, args, at, count, count_at } if last.contains_key(&args) => { + let result = last.get(&args).copied().unwrap_or(0); + out.push(Cmd::Indirect { signature, most, args: RESULTS, at: result + at, count, count_at }); + } + c => out.push(c), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pso(pso: u32) -> Cmd { + Cmd::Pipeline { pso } + } + fn go() -> Cmd { + Cmd::Dispatch { groups: [1, 1, 1] } + } + fn uav(res: u32) -> Barrier { + Barrier::Uav { flags: 0, res } + } + fn moved(res: u32, before: i32, after: i32) -> Barrier { + Barrier::Transition { flags: 0, res, sub: ALL, before, after } + } + fn barriers(all: &[Barrier]) -> Cmd { + Cmd::Barriers { all: all.to_vec() } + } + + #[test] + fn pipelines_are_skipped() { + let list = vec![pso(1), go(), pso(2), go(), go(), Cmd::CopyResource { dst: 1, src: 2 }, pso(1), go()]; + let (out, n) = skip_pipelines(list.clone(), &HashSet::from([2])); + assert_eq!(n, 2); + assert_eq!(out, vec![pso(1), go(), pso(2), Cmd::CopyResource { dst: 1, src: 2 }, pso(1), go()]); + assert_eq!(skip_pipelines(list.clone(), &HashSet::new()), (list, 0)); + } + + #[test] + fn uav_barriers_are_dropped() { + let list = vec![barriers(&[uav(0)]), go(), barriers(&[uav(1), moved(1, 8, 4)])]; + assert_eq!(no_uav_barriers(list.clone()), (vec![go(), barriers(&[moved(1, 8, 4)])], 2)); + assert_eq!(barriers_only(list.clone()), vec![list[0].clone(), list[2].clone()]); + } + + #[test] + fn barriers_are_merged() { + let list = vec![ + barriers(&[moved(1, 0, 8)]), + pso(1), + barriers(&[uav(2), moved(1, 8, 64)]), + barriers(&[uav(0), uav(3)]), + go(), + // There and back again: nothing is left but the wait. + barriers(&[moved(1, 8, 64)]), + barriers(&[moved(1, 64, 8)]), + go(), + barriers(&[moved(4, 4, 128)]), + barriers(&[moved(4, 128, 4)]), + ]; + let (out, saved) = merge_barriers(list); + assert_eq!(saved, 4); + assert_eq!(out, vec![barriers(&[moved(1, 0, 64), uav(0)]), pso(1), go(), barriers(&[uav(1)]), go()]); + // Parts of a resource are not mixed up. + let part = |sub, before, after| Barrier::Transition { flags: 0, res: 1, sub, before, after }; + let list = vec![barriers(&[part(0, 4, 8)]), barriers(&[part(1, 4, 8)]), barriers(&[part(ALL, 8, 64)])]; + assert_eq!(merge_barriers(list).0, vec![barriers(&[part(0, 4, 8), part(1, 4, 8), part(ALL, 8, 64)])]); + } + + #[test] + fn clamps_are_found_kept_and_skipped() { + let clamp = |scratch, stride, records| { + vec![ + barriers(&[uav(0), moved(scratch, 0, 8)]), + pso(9), + Cmd::Constants { graphics: false, param: 0, offset: 0, values: vec![10, stride, records, 0, 0, 0] }, + Cmd::RootView { graphics: false, kind: 3, param: 3, va: Va::At { res: scratch, offset: 0 } }, + go(), + barriers(&[uav(0), moved(scratch, 8, 0x200)]), + ] + }; + let run = |args, at| Cmd::Indirect { signature: 1, most: 1, args, at, count: 0, count_at: 0 }; + let mut list = clamp(5, 12, 2); + list.extend([pso(1), run(5, 12), run(5, 0), run(6, 0)]); + list.extend(clamp(5, 12, 100)); + list.extend([pso(1), run(5, 24), barriers(&[moved(5, 0x200, 0)])]); + let mut next = 0; + let found = find_clamps(&list, &HashSet::from([9]), &mut next); + assert_eq!(found.iter().map(|c| (c.scratch, c.bytes, c.result)).collect::>(), [(5, 24, 0), (5, 1200, 256)]); + assert_eq!(next, 256 + 1280); + let kept = keep_clamped(list.clone(), &found); + assert_eq!(kept.len(), list.len() + 6); + assert_eq!(kept[7], Cmd::CopyBuffer { dst: RESULTS, dst_at: 0, src: 5, src_at: 0, len: 24 }); + assert_eq!(kept.iter().filter(|c| matches!(c, Cmd::CopyBuffer { .. })).count(), 2); + let skipped = skip_clamps(list, &found); + assert!(!skipped.iter().any(|c| matches!(c, Cmd::Dispatch { .. } | Cmd::Barriers { .. }))); + let runs: Vec<(u32, u64)> = + skipped.iter().filter_map(|c| if let Cmd::Indirect { args, at, .. } = c { Some((*args, *at)) } else { None }).collect(); + assert_eq!(runs, [(RESULTS, 12), (RESULTS, 0), (6, 0), (RESULTS, 256 + 24)]); + } +} diff --git a/crates/victory-gpu/src/replay/gpu.rs b/crates/victory-gpu/src/replay/gpu.rs new file mode 100644 index 0000000..61ed472 --- /dev/null +++ b/crates/victory-gpu/src/replay/gpu.rs @@ -0,0 +1,392 @@ +//! Small D3D12 helpers the recorder and the replayer share. + +use windows::Win32::Foundation::HANDLE; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::core::{Interface, Result}; + +use super::wire; + +/// Lists of our own on a queue, with a fence. +pub(super) struct Worker { + pub(super) device: ID3D12Device, + pub(super) queue: ID3D12CommandQueue, + fence: ID3D12Fence, + event: HANDLE, + value: u64, + /// Allocator, list, and the fence value its last run ends with. + lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList, u64)>, +} + +// SAFETY: D3D12 objects are free-threaded; a worker is used by one thread +// at a time (`&mut self`). +unsafe impl Send for Worker {} + +impl Worker { + pub(super) fn new(device: &ID3D12Device, queue: &ID3D12CommandQueue) -> Result { + // SAFETY: plain object creation. + unsafe { + Ok(Worker { + device: device.clone(), + queue: queue.clone(), + fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?, + event: CreateEventW(None, false, false, None)?, + value: 0, + lists: Vec::new(), + }) + } + } + + /// Records a list and sends it; the value [`Worker::wait`] takes. + pub(super) fn send(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> Result { + // SAFETY: lists and allocators of ours whose last run has finished. + unsafe { + let done = self.fence.GetCompletedValue(); + let i = match self.lists.iter().position(|l| l.2 <= done) { + Some(i) => i, + None => { + let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = + self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.Close()?; + self.lists.push((allocator, list, 0)); + self.lists.len() - 1 + } + }; + let (allocator, list, last) = &mut self.lists[i]; + allocator.Reset()?; + list.Reset(&*allocator, None)?; + record(list); + list.Close()?; + self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); + self.value += 1; + *last = self.value; + self.queue.Signal(&self.fence, self.value)?; + } + Ok(self.value) + } + + /// Everything sent to the queue so far has run. + pub(super) fn idle(&mut self) -> Result<()> { + self.value += 1; + // SAFETY: our queue and fence. + unsafe { self.queue.Signal(&self.fence, self.value)? }; + self.wait(self.value) + } + + pub(super) fn wait(&self, value: u64) -> Result<()> { + // SAFETY: our fence and event. + unsafe { + if self.fence.GetCompletedValue() < value { + self.fence.SetEventOnCompletion(value, self.event)?; + WaitForSingleObject(self.event, INFINITE); + } + self.device.GetDeviceRemovedReason() + } + } + + /// Sends and waits. + pub(super) fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> Result<()> { + let value = self.send(record)?; + self.wait(value) + } +} + +pub(super) fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + } +} + +/// A buffer of ours; heap types that are mapped come with their mapping. +pub(super) fn buffer( + device: &ID3D12Device, + kind: D3D12_HEAP_TYPE, + size: u64, + flags: D3D12_RESOURCE_FLAGS, +) -> Result<(ID3D12Resource, *mut u8)> { + let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }; + let state = match kind { + D3D12_HEAP_TYPE_UPLOAD => D3D12_RESOURCE_STATE_GENERIC_READ, + D3D12_HEAP_TYPE_READBACK => D3D12_RESOURCE_STATE_COPY_DEST, + _ => D3D12_RESOURCE_STATE_COMMON, + }; + let mut made: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping. + unsafe { + device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(size, flags), state, None, &mut made)?; + let made = made.ok_or_else(windows::core::Error::empty)?; + if kind == D3D12_HEAP_TYPE_UPLOAD || kind == D3D12_HEAP_TYPE_READBACK { + made.Map(0, None, Some(&mut data))?; + } + Ok((made, data.cast())) + } +} + +/// Planes of a format (depth and stencil, or a video format's). +pub(super) fn planes(format: i32) -> u32 { + match format { + 19..=22 | 44..=47 | 103..=106 => 2, + _ => 1, + } +} + +/// Subresources of a texture (1 for a buffer). +pub(super) fn subresources(d: &wire::Desc) -> u32 { + if d.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { + return 1; + } + let layers = if d.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { 1 } else { u32::from(d.depth) }; + u32::from(d.mips.max(1)) * layers.max(1) * planes(d.format) +} + +/// The layout of `count` subresources from `first` in a buffer, and its +/// size. +pub(super) fn footprints( + device: &ID3D12Device, + desc: &D3D12_RESOURCE_DESC, + first: u32, + count: u32, +) -> (Vec, u64) { + let mut all = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize]; + let mut total = 0; + // SAFETY: outputs for `count` subresources. + unsafe { device.GetCopyableFootprints(desc, first, count, 0, Some(all.as_mut_ptr()), None, None, Some(&mut total)) }; + (all, total) +} + +/// A location naming a subresource; no reference is taken. +pub(super) fn sub_location(res: &ID3D12Resource, sub: u32) -> D3D12_TEXTURE_COPY_LOCATION { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(res) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub }, + } +} + +/// A location naming bytes of a buffer; no reference is taken. +pub(super) fn placed_location(res: &ID3D12Resource, f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT) -> D3D12_TEXTURE_COPY_LOCATION { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(res) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f }, + } +} + +/// A transition; no reference is taken. +pub(super) fn transition(res: &ID3D12Resource, sub: u32, before: u32, after: u32) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(res) }, + Subresource: sub, + StateBefore: D3D12_RESOURCE_STATES(before as i32), + StateAfter: D3D12_RESOURCE_STATES(after as i32), + }), + }, + } +} + +/// The barriers that move a texture from `from` (one state, or one for each +/// subresource) to `to`. +pub(super) fn moves(res: &ID3D12Resource, from: &[u32], to: &[u32], out: &mut Vec) { + let n = from.len().max(to.len()); + if n == 1 { + if from[0] != to[0] { + out.push(transition(res, wire::ALL, from[0], to[0])); + } + return; + } + for i in 0..n { + let (a, b) = (from[i.min(from.len() - 1)], to[i.min(to.len() - 1)]); + if a != b { + out.push(transition(res, i as u32, a, b)); + } + } +} + +pub(super) fn to_desc(d: &wire::Desc) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION(d.dimension), + Alignment: d.alignment, + Width: d.width, + Height: d.height, + DepthOrArraySize: d.depth, + MipLevels: d.mips, + Format: DXGI_FORMAT(d.format), + SampleDesc: DXGI_SAMPLE_DESC { Count: d.samples[0], Quality: d.samples[1] }, + Layout: D3D12_TEXTURE_LAYOUT(d.layout), + Flags: D3D12_RESOURCE_FLAGS(d.flags), + } +} + +pub(super) fn from_desc(d: &D3D12_RESOURCE_DESC) -> wire::Desc { + wire::Desc { + dimension: d.Dimension.0, + alignment: d.Alignment, + width: d.Width, + height: d.Height, + depth: d.DepthOrArraySize, + mips: d.MipLevels, + format: d.Format.0, + samples: [d.SampleDesc.Count, d.SampleDesc.Quality], + layout: d.Layout.0, + flags: d.Flags.0, + } +} + +pub(super) fn to_props(p: &wire::HeapProps) -> D3D12_HEAP_PROPERTIES { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE(p.kind), + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY(p.cpu), + MemoryPoolPreference: D3D12_MEMORY_POOL(p.pool), + ..Default::default() + } +} + +pub(super) fn from_props(p: &D3D12_HEAP_PROPERTIES) -> wire::HeapProps { + wire::HeapProps { kind: p.Type.0, cpu: p.CPUPageProperty.0, pool: p.MemoryPoolPreference.0 } +} + +/// How the CPU sees memory of a heap. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Seen { + /// Not at all: the card's own. + No, + /// Cached, read and written. + Cached, + /// Write-combined: slow to read. + Combined, + /// A read-back heap: the CPU only reads. + ReadBack, +} + +pub(super) fn seen(p: &wire::HeapProps) -> Seen { + match D3D12_HEAP_TYPE(p.kind) { + D3D12_HEAP_TYPE_DEFAULT => Seen::No, + D3D12_HEAP_TYPE_UPLOAD => Seen::Combined, + D3D12_HEAP_TYPE_READBACK => Seen::ReadBack, + D3D12_HEAP_TYPE_CUSTOM => match D3D12_CPU_PAGE_PROPERTY(p.cpu) { + D3D12_CPU_PAGE_PROPERTY_WRITE_BACK => Seen::Cached, + D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE => Seen::Combined, + _ => Seen::No, + }, + // GPU upload heaps (type 5). + _ => Seen::Combined, + } +} + +/// 8-bit RGB of a presented texture's rows (and the greatest channel value +/// of the format, for the signal-to-noise ratio). `None` for formats not +/// shown. +pub(super) fn rgb(width: u32, height: u32, pitch: u32, format: i32, rows: &[u8]) -> Option> { + let mut out = Vec::with_capacity((width * height * 3) as usize); + let half = |b: &[u8]| { + let h = u16::from_le_bytes([b[0], b[1]]); + let (s, e, m) = (h >> 15, (h >> 10) & 31, f32::from(h & 1023)); + let v = match e { + 0 => m * 2f32.powi(-24), + 31 => 65536.0, + e => (1.0 + m / 1024.0) * 2f32.powi(i32::from(e) - 15), + }; + if s == 1 { 0 } else { (v.min(1.0) * 255.0) as u8 } + }; + for y in 0..height as usize { + let row = rows.get(y * pitch as usize..)?; + for x in 0..width as usize { + match format { + 27..=32 => out.extend_from_slice(row.get(x * 4..x * 4 + 3)?), + 87 | 88 | 90..=93 => { + let p = row.get(x * 4..x * 4 + 3)?; + out.extend([p[2], p[1], p[0]]); + } + 23..=25 => { + let p = row.get(x * 4..x * 4 + 4)?; + let v = u32::from_le_bytes([p[0], p[1], p[2], p[3]]); + out.extend([(v >> 2) as u8, (v >> 12) as u8, (v >> 22) as u8]); + } + 9..=14 => { + let p = row.get(x * 8..x * 8 + 6)?; + out.extend([half(p), half(&p[2..]), half(&p[4..])]); + } + _ => return None, + } + } + } + Some(out) +} + +/// Peak signal-to-noise ratio of two pictures of 8-bit channels, in dB +/// (infinite if equal). +pub(super) fn psnr(a: &[u8], b: &[u8]) -> f64 { + let sum: u64 = a.iter().zip(b).map(|(&x, &y)| u64::from(x.abs_diff(y)).pow(2)).sum(); + if sum == 0 && a.len() == b.len() { + return f64::INFINITY; + } + let mean = sum as f64 / a.len().min(b.len()).max(1) as f64; + 10.0 * (255.0 * 255.0 / mean).log10() +} + +/// The adapter a device is on: name, vendor and device number. +pub(super) fn adapter(device: &ID3D12Device) -> (String, u32, u32) { + use windows::Win32::Graphics::Dxgi::*; + // SAFETY: plain queries. + let desc = unsafe { + CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| f.EnumAdapterByLuid::(device.GetAdapterLuid())) + .and_then(|a| a.GetDesc1()) + }; + match desc { + Ok(d) => { + let name = String::from_utf16_lossy(&d.Description); + (name.trim_end_matches('\0').to_owned(), d.VendorId, d.DeviceId) + } + Err(_) => ("unknown".into(), 0, 0), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pictures() { + assert_eq!(rgb(1, 1, 4, 28, &[1, 2, 3, 4]).unwrap(), [1, 2, 3]); + assert_eq!(rgb(1, 1, 4, 87, &[1, 2, 3, 4]).unwrap(), [3, 2, 1]); + let v = (1023u32 | 512 << 10).to_le_bytes(); + assert_eq!(rgb(1, 1, 4, 24, &v).unwrap(), [255, 128, 0]); + // 1.0, 0.5 and -1.0 as halves. + assert_eq!(rgb(1, 1, 8, 10, &[0, 0x3c, 0, 0x38, 0, 0xbc, 0, 0]).unwrap(), [255, 127, 0]); + assert!(rgb(1, 1, 4, 41, &[0; 4]).is_none()); + assert!(rgb(2, 2, 8, 28, &[0; 12]).is_none(), "too few rows"); + assert_eq!(psnr(&[1, 2], &[1, 2]), f64::INFINITY); + assert!((psnr(&[0; 4], &[255; 4])).abs() < 1e-9); + } + + #[test] + fn states_of_subresources() { + assert_eq!(planes(44), 2); + let mut d = from_desc(&buffer_desc(10, D3D12_RESOURCE_FLAG_NONE)); + assert_eq!(subresources(&d), 1); + assert_eq!(from_desc(&to_desc(&d)), d); + (d.dimension, d.depth, d.mips, d.format) = (3, 6, 4, 19); + assert_eq!(subresources(&d), 48); + d.dimension = 4; + assert_eq!(subresources(&d), 8); + } +} diff --git a/crates/victory-gpu/src/replay/hook.rs b/crates/victory-gpu/src/replay/hook.rs new file mode 100644 index 0000000..e4ceca4 --- /dev/null +++ b/crates/victory-gpu/src/replay/hook.rs @@ -0,0 +1,290 @@ +//! Methods of single COM objects replaced: an object's method table pointer +//! is set to a copy of its table ([`Shim`]) with some entries changed. Other +//! objects of the class keep theirs, so what is not asked for is untouched. + +use std::collections::BTreeSet; +use std::ffi::c_void; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Methods in a copied table: more than any D3D12 interface has (an +/// interface's private methods may follow its public ones). +pub(super) const SLOTS: usize = 192; +/// Entries copied from before the table (type information). +const PRE: usize = 4; + +/// A copied method table. Objects point at `table`; what we keep for them +/// lies before it. Never freed: an object may still use it while it dies. +#[repr(C)] +struct Shim { + state: *const c_void, + orig: *const usize, + pre: [usize; PRE], + table: [usize; SLOTS], +} + +const TO_ORIG: usize = std::mem::offset_of!(Shim, table) - std::mem::offset_of!(Shim, orig); + +/// The shims made, by the address objects point at. +static MADE: Mutex> = Mutex::new(BTreeSet::new()); + +unsafe fn shim(this: *mut c_void) -> *const Shim { + // SAFETY: the caller's object points into a shim. + unsafe { + let table = *this.cast::<*const u8>(); + table.sub(std::mem::offset_of!(Shim, table)).cast() + } +} + +/// The object's own method table, as `T` (an interface's `_Vtbl`). +/// +/// # Safety +/// `this` is an object [`install`] was called for, of an interface `T` is +/// the table of. +pub(super) unsafe fn orig(this: *mut c_void) -> &'static T { + // SAFETY: the caller's. + unsafe { &*(*shim(this)).orig.cast::() } +} + +/// What [`install`] was given for the object. +/// +/// # Safety +/// As [`orig`]; `T` is what `state` pointed at. +pub(super) unsafe fn state(this: *mut c_void) -> &'static T { + // SAFETY: the caller's. + unsafe { &*(*shim(this)).state.cast::() } +} + +/// Bytes readable from `at` on (up to a limit): what is copied of a table +/// must not run past its module's data. +fn readable(at: usize, most: usize) -> usize { + use windows_sys::Win32::System::Memory::*; + let mut end = at; + while end < at + most { + // SAFETY: a plain query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: as above. + let n = unsafe { VirtualQuery(end as *const c_void, &mut info, size_of::()) }; + const READ: u32 = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; + if n == 0 || info.State != MEM_COMMIT || info.Protect & READ == 0 || info.Protect & PAGE_GUARD != 0 { + break; + } + end = info.BaseAddress as usize + info.RegionSize; + } + end.min(at + most) - at +} + +/// Gives the object a table of its own, changed by `patch`. `state` is what +/// [`state`] answers; it must live for good. False if the object has one +/// already (then nothing changes). +/// +/// # Safety +/// `this` is a live COM object no other thread uses yet; what `patch` puts +/// into the table are functions of the methods' types. +pub(super) unsafe fn install(this: *mut c_void, state: *const c_void, patch: impl FnOnce(&mut [usize; SLOTS])) -> bool { + let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: a live COM object starts with its table's address. + let at = unsafe { *this.cast::() }; + if made.contains(&at) { + return false; + } + let mut new = Box::new(Shim { state, orig: at as *const usize, pre: [0; PRE], table: [0; SLOTS] }); + let have = readable(at, SLOTS * 8) / 8; + // SAFETY: `have` entries are readable; the object's table is at least + // as long as its interface, and what lies behind it is only copied. + unsafe { std::ptr::copy_nonoverlapping(at as *const usize, new.table.as_mut_ptr(), have) }; + if readable(at - PRE * 8, PRE * 8) == PRE * 8 { + // SAFETY: as above. + unsafe { std::ptr::copy_nonoverlapping((at as *const usize).sub(PRE), new.pre.as_mut_ptr(), PRE) }; + } + patch(&mut new.table); + let new: &'static Shim = Box::leak(new); + made.insert(new.table.as_ptr() as usize); + // SAFETY: the object's first word, its table's address. + unsafe { this.cast::<*const usize>().write(new.table.as_ptr()) }; + true +} + +/// The table the object points at. +/// +/// # Safety +/// `this` is a live COM object. +pub(super) unsafe fn table(this: *mut c_void) -> usize { + // SAFETY: the caller's. + unsafe { *this.cast::() } +} + +/// Whether the object points at a shim of ours. +/// +/// # Safety +/// `this` is a live COM object. +pub(super) unsafe fn ours(this: *mut c_void) -> bool { + // SAFETY: the caller's. + let at = unsafe { table(this) }; + MADE.lock().unwrap_or_else(|e| e.into_inner()).contains(&at) +} + +/// After a method that may have set the object's table pointer anew: it +/// points at its shim (`before`, where it pointed) again. A table it did +/// not have before gets a shim of its own. +/// +/// # Safety +/// As [`install`]; `before` is a shim's table. +pub(super) unsafe fn again(this: *mut c_void, before: usize, patch: impl FnOnce(&mut [usize; SLOTS])) { + // SAFETY: the caller's. + unsafe { + let now = table(this); + if now == before { + return; + } + let shim = (before as *const u8).sub(std::mem::offset_of!(Shim, table)).cast::(); + if (*shim).orig as usize == now { + this.cast::().write(before); + } else { + install(this, (*shim).state, patch); + } + } +} + +/// Gives the object its own table back, if it points at a shim of ours +/// (tests). +/// +/// # Safety +/// `this` is a live object, used by no other thread now. +pub(super) unsafe fn remove(this: *mut c_void) { + let made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: as in `install`. + unsafe { + let at = *this.cast::(); + if made.contains(&at) { + let own = (*shim(this)).orig; + this.cast::<*const usize>().write(own); + } + } +} + +/// Classes of [`uncounted`] calls. +pub(super) const LIST: usize = 0; +pub(super) const DEVICE: usize = 1; +pub(super) const QUEUE: usize = 2; +const CLASSES: usize = 3; + +#[allow(clippy::declare_interior_mutable_const)] +const ZERO: AtomicU64 = AtomicU64::new(0); +static COUNTS: [AtomicU64; CLASSES * SLOTS] = [ZERO; CLASSES * SLOTS]; + +/// How often a method the recorder does not record was called. +pub(super) fn count(class: usize, slot: usize) -> u64 { + COUNTS[class * SLOTS + slot].load(Ordering::Relaxed) +} + +/// A method the recorder does not know how to record: counts the call in +/// [`COUNTS`] and goes on to the object's own. Any arguments pass as they +/// are: only the scratch register `rax` is used. +#[unsafe(naked)] +unsafe extern "system" fn noted() { + core::arch::naked_asm!( + "lock inc qword ptr [rip + {counts} + {at} * 8]", + "mov rax, [rcx]", + "mov rax, [rax - {orig}]", + "jmp qword ptr [rax + ({at} % {slots}) * 8]", + counts = sym COUNTS, + at = const AT, + orig = const TO_ORIG, + slots = const SLOTS, + ) +} + +/// [`noted`] for method `SLOT` of a class, `AT` being `class * SLOTS + slot`. +pub(super) fn noted_entry() -> usize { + noted:: as *const () as usize +} + +/// The slot of a method in its table. +macro_rules! method { + ($vtbl:ident . $name:ident) => { + std::mem::offset_of!(windows::Win32::Graphics::Direct3D12::$vtbl, $name) / 8 + }; +} +pub(super) use method; + +#[cfg(test)] +mod tests { + use super::*; + + #[repr(C)] + struct Vtbl { + methods: [usize; 8], + } + + #[repr(C)] + struct Object { + vtbl: *const Vtbl, + value: u64, + } + + unsafe extern "system" fn add(this: *mut c_void, a: u64, b: u64, c: u64, d: u64, e: f64) -> u64 { + // SAFETY: one of the test's objects. + unsafe { (*this.cast::()).value + a + b + c + d + e as u64 } + } + + type Add = unsafe extern "system" fn(*mut c_void, u64, u64, u64, u64, f64) -> u64; + + unsafe extern "system" fn double(this: *mut c_void, a: u64, b: u64, c: u64, d: u64, e: f64) -> u64 { + // SAFETY: an object with a shim whose first method is `add`. + unsafe { + let first = orig::<[Add; 1]>(this)[0]; + first(this, a, b, c, d, e) * 2 + *state::(this) + } + } + + unsafe fn call(object: &mut Object, slot: usize) -> u64 { + // SAFETY: an entry of `Add`'s type. + unsafe { + let f: Add = std::mem::transmute((*object.vtbl).methods[slot]); + f((&raw mut *object).cast(), 1, 2, 3, 4, 5.0) + } + } + + #[test] + fn one_object_is_changed_and_changed_back() { + static STATE: u64 = 1000; + let vtbl = Vtbl { methods: [add as *const () as usize; 8] }; + let mut a = Object { vtbl: &vtbl, value: 100 }; + let mut b = Object { vtbl: &vtbl, value: 200 }; + // SAFETY: the test's objects; entries of `Add`'s type. + unsafe { + let this: *mut c_void = (&raw mut a).cast(); + let patch = |t: &mut [usize; SLOTS]| { + t[0] = double as *const () as usize; + t[2] = noted_entry::<{ QUEUE * SLOTS + 2 }>(); + }; + assert!(install(this, (&raw const STATE).cast(), patch)); + assert!(!install(this, (&raw const STATE).cast(), patch), "only once"); + assert_eq!(call(&mut a, 0), 230 + 1000); + assert_eq!(call(&mut a, 1), 115); + assert_eq!(call(&mut b, 0), 215, "other objects are untouched"); + // Counted, and passed on with all its arguments. + let before = count(QUEUE, 2); + assert_eq!(call(&mut a, 2), 115); + assert_eq!(call(&mut a, 2), 115); + assert_eq!(count(QUEUE, 2), before + 2); + // A method that set the table pointer anew. + let shim = table(this); + assert!(ours(this)); + a.vtbl = &vtbl; + assert!(!ours(this)); + again(this, shim, patch); + assert_eq!(table(this), shim); + // Or to another table. + let other = Vtbl { methods: [add as *const () as usize; 8] }; + a.vtbl = &other; + again(this, shim, patch); + assert!(ours(this) && table(this) != shim); + assert_eq!(call(&mut a, 0), 230 + 1000); + remove(this); + assert!(std::ptr::eq(a.vtbl, &other)); + assert_eq!(call(&mut a, 0), 115); + } + } +} diff --git a/crates/victory-gpu/src/replay/mod.rs b/crates/victory-gpu/src/replay/mod.rs new file mode 100644 index 0000000..5fd0b06 --- /dev/null +++ b/crates/victory-gpu/src/replay/mod.rs @@ -0,0 +1,17 @@ +//! One frame's D3D12 work recorded and run again, to find out what it costs +//! the card and to try changes on it in seconds (docs/replay.md). +//! +//! [`record`] hooks the host's D3D12 objects (`hook`) and keeps what a frame +//! needs; `snap` writes one frame down; [`play`] runs it. `wire` is what a +//! capture holds, `pso` pipeline descriptions, `states` the states textures +//! are in, `edit` the experiments, `gpu` helpers. + +mod edit; +mod gpu; +mod hook; +pub mod play; +mod pso; +pub mod record; +mod snap; +mod states; +mod wire; diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs new file mode 100644 index 0000000..9f09a0d --- /dev/null +++ b/crates/victory-gpu/src/replay/play.rs @@ -0,0 +1,2042 @@ +//! The replayer: makes a captured frame's objects again, puts their +//! contents back, and runs the frame as often as asked, with its time on +//! the card and experiments on it (`super::edit`). + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::fmt::Write as _; +use std::fs::File; +use std::os::windows::fs::FileExt; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; + +use anyhow::{Context, Result, anyhow, bail}; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; +use windows::Win32::Graphics::Dxgi::*; +use windows::core::Interface; + +use super::edit::{self, Clamp, RESULTS}; +use super::gpu::{self, Seen, Worker}; +use super::snap::read_sub; +use super::states::{self, COMMON, COPY_DEST, COPY_SOURCE, DEPTH_WRITE, RENDER_TARGET, RESOLVE_DEST, States, UNORDERED_ACCESS}; +use super::wire::{self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot}; + +/// The name of the argument clamp's pipeline, by which its passes are +/// recognised. +pub const CLAMP: &str = "victory: argument clamp"; +/// The name of the pipeline that compares and hashes card buffers. +pub const COMPARE: &str = "victory: card compare"; + +/// An upload buffer contents come back through. +const STAGING: u64 = 256 << 20; + +/// Where buffers the CPU saw lie in a replay. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Buffers { + /// Where they lay. + #[default] + AsRecorded, + /// All in the card's memory. + Card, + /// All in the PC's memory, the card's own buffers too. + Pc, +} + +#[derive(Clone, Debug)] +pub struct Options { + pub loops: u32, + /// Put back, before each run, what the run before changed. + pub restore: bool, + /// Time every command, not only lists. + pub detailed: bool, + /// Shaders listed. + pub top: usize, + /// Where the picture goes (default: `replay.png` in the capture). + pub image: Option, + pub buffers: Buffers, + pub no_barriers: bool, + pub merge_barriers: bool, + pub skip_clamps: bool, + pub skip_hash_passes: bool, + pub one_submit: bool, + /// Run only these lists (by their place in the frame). + pub only: Option<(u32, u32)>, + /// Skip what runs a pipeline whose name or shader hash has one of + /// these in it. + pub skip_shaders: Vec, + /// Run the frame unchanged first, and compare. + pub compare: bool, + /// The debug layer, if it is installed. + pub debug: bool, +} + +impl Default for Options { + fn default() -> Self { + Options { + loops: 5, + restore: true, + detailed: false, + top: 20, + image: None, + buffers: Buffers::AsRecorded, + no_barriers: false, + merge_barriers: false, + skip_clamps: false, + skip_hash_passes: false, + one_submit: false, + only: None, + skip_shaders: Vec::new(), + compare: false, + debug: false, + } + } +} + +impl Options { + fn edited(&self) -> bool { + self.no_barriers + || self.merge_barriers + || self.skip_clamps + || self.skip_hash_passes + || self.one_submit + || self.only.is_some() + || !self.skip_shaders.is_empty() + } + + /// The same without the experiments. + fn plain(&self) -> Options { + Options { + no_barriers: false, + merge_barriers: false, + skip_clamps: false, + skip_hash_passes: false, + one_submit: false, + only: None, + skip_shaders: Vec::new(), + ..self.clone() + } + } +} + +/// How a run went. +#[derive(Clone, Debug, Default)] +pub struct Report { + /// Per loop: from the first list's start to the last one's end, in ms. + pub frame_ms: Vec, + /// Per loop: how long the lists of submissions ran. + pub busy_ms: Vec, + /// Per loop: copies of ours that stand for what the CPU wrote. + pub delta_ms: Vec, + /// Of the last loop, by submission: lists, ms. + pub submits: Vec<(usize, f64)>, + /// With detailed timing, of the last loop: ms and count by category. + pub categories: Vec<(String, f64, u32)>, + /// With detailed timing: ms, count and name of the costliest pipelines. + pub shaders: Vec<(f64, u32, String)>, + /// Against the presented picture: dB (infinite: the same), and whether + /// its bytes are the same. + pub picture: Option<(f64, bool)>, + /// Things to know: from the capture and the replay. + pub notes: Vec, +} + +impl Report { + pub fn median_ms(&self) -> f64 { + median(&self.frame_ms) + } + + /// The report as text. + pub fn text(&self, what: &str) -> String { + let mut t = String::new(); + let ms = |v: &[f64]| v.iter().map(|x| format!("{x:.2}")).collect::>().join(" "); + let _ = writeln!(t, "{what}: {:.2} ms on the card (median of {})", self.median_ms(), self.frame_ms.len()); + let _ = writeln!(t, " loops, ms: {}", ms(&self.frame_ms)); + let (busy, delta) = (median(&self.busy_ms), median(&self.delta_ms)); + let idle = (self.median_ms() - busy - delta).max(0.0); + let _ = writeln!(t, " submissions busy {busy:.2} ms, copies standing for CPU writes {delta:.2} ms, between submissions {idle:.2} ms"); + let _ = writeln!(t, " by submission (lists: ms): {}", { + self.submits.iter().enumerate().map(|(i, (n, ms))| format!("{i} ({n}): {ms:.2}")).collect::>().join(", ") + }); + if !self.categories.is_empty() { + let _ = writeln!(t, " by kind of command, ms (commands):"); + for (name, ms, n) in &self.categories { + let _ = writeln!(t, " {ms:8.2} {n:6} {name}"); + } + } + if !self.shaders.is_empty() { + let _ = writeln!(t, " costliest pipelines, ms (commands):"); + for (ms, n, name) in &self.shaders { + let _ = writeln!(t, " {ms:8.2} {n:6} {name}"); + } + } + match self.picture { + Some((_, true)) => drop(writeln!(t, " picture: the same bytes as presented")), + Some((db, false)) => drop(writeln!(t, " picture: differs from the presented one, PSNR {db:.1} dB")), + None => {} + } + for n in &self.notes { + let _ = writeln!(t, " note: {n}"); + } + t + } +} + +fn median(v: &[f64]) -> f64 { + let mut v = v.to_vec(); + v.sort_by(f64::total_cmp); + v.get(v.len() / 2).copied().unwrap_or(0.0) +} + +/// The folder of a capture: `folder`, or the last `capture-` in it that +/// is complete. +pub fn find(folder: &Path) -> Result { + if folder.join("frame.bin").exists() { + return Ok(folder.to_owned()); + } + let mut best: Option<(u32, PathBuf)> = None; + for entry in std::fs::read_dir(folder).with_context(|| format!("{}", folder.display()))?.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + let Some(n) = name.strip_prefix("capture-").and_then(|n| n.parse().ok()) else { continue }; + if entry.path().join("frame.bin").exists() && best.as_ref().is_none_or(|b| b.0 < n) { + best = Some((n, entry.path())); + } + } + best.map(|b| b.1).ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display())) +} + +/// Loads a capture and runs it: the whole of `victory replay`. The reports, +/// with what each is of. +pub fn replay(folder: &Path, options: &Options) -> Result> { + let mut player = Player::load(folder, options)?; + let mut out = Vec::new(); + if options.compare && options.edited() { + let image = Some(player.folder.join("replay-unchanged.png")); + out.push(("unchanged".into(), player.run(&Options { image, ..options.plain() })?)); + } + let what = if options.edited() { "with the experiments" } else { "unchanged" }; + out.push((what.into(), player.run(options)?)); + Ok(out) +} + +struct Object { + res: ID3D12Resource, + va: u64, + /// In the capture's `resources`. + index: usize, + subs: u32, +} + +/// One version of a shader-visible descriptor heap. +struct Version { + heap: ID3D12DescriptorHeap, + gpu: u64, +} + +pub struct Player { + pub folder: PathBuf, + frame: Frame, + device: ID3D12Device, + worker: Worker, + info: Option, + frequency: f64, + objects: HashMap, + _heaps: HashMap, + roots: HashMap, + pipelines: HashMap, + signatures: HashMap, + queries: HashMap, + /// Descriptor heaps by id, in their versions; each submission's version. + descriptors: HashMap, u64)>, + version_of: Vec, + /// Render target and depth views by what they are of. + targets: HashMap, + _target_heaps: Vec, + /// Copies of what the frame changes, as at its start. + masters: Vec<(u32, ID3D12Resource)>, + /// What the CPU wrote between submissions, and for each submission + /// where in it. + deltas: Option, + delta_parts: Vec>, + /// States at the start of the frame and after it. + start: HashMap>, + end: HashMap>, + /// The results of clamp passes ([`RESULTS`]). + results: Option, + commands: Vec>, + /// Resources in the states of the start (not those of the end). + fresh: bool, + notes: Vec, +} + +/// What a command of a list is timed as. +type Stamp = (usize, &'static str, u32); + +/// A list made from commands, with what its timestamps are of. +struct Built { + _allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + /// The query of its start; its end is the one before the next list's. + first: u32, + last: u32, + stamps: Vec, +} + +impl Player { + pub fn load(folder: &Path, options: &Options) -> Result { + let folder = find(folder)?; + let began = Instant::now(); + let frame = Frame::read(&folder.join("frame.bin"))?; + let (device, info) = make_device(&frame, options.debug)?; + // SAFETY: plain creation and queries. + let (queue, frequency) = unsafe { + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + })?; + let frequency = queue.GetTimestampFrequency()? as f64; + (queue, frequency) + }; + let commands: Vec> = frame.lists.iter().map(|l| Cmd::all(&l.commands.0)).collect::>()?; + let mut player = Player { + folder, + worker: Worker::new(&device, &queue)?, + device, + info, + frequency, + objects: HashMap::new(), + _heaps: HashMap::new(), + roots: HashMap::new(), + pipelines: HashMap::new(), + signatures: HashMap::new(), + queries: HashMap::new(), + descriptors: HashMap::new(), + version_of: Vec::new(), + targets: HashMap::new(), + _target_heaps: Vec::new(), + masters: Vec::new(), + deltas: None, + delta_parts: Vec::new(), + start: HashMap::new(), + end: HashMap::new(), + results: None, + commands, + fresh: true, + notes: frame.notes.iter().map(|n| format!("recorder: {n}")).collect(), + frame, + }; + player.check()?; + let mut steps: Vec<(&str, std::time::Duration)> = Vec::new(); + let mut step = |what: &'static str, at: &mut Instant| { + steps.push((what, at.elapsed())); + *at = Instant::now(); + }; + let mut at = Instant::now(); + player.make_resources(options.buffers)?; + step("resources", &mut at); + player.make_pipelines()?; + step("pipelines", &mut at); + player.make_descriptors()?; + step("descriptors", &mut at); + player.load_contents()?; + step("contents", &mut at); + player.make_masters()?; + step("copies to restore from", &mut at); + let steps: Vec = steps.iter().map(|(w, d)| format!("{w} {:.1} s", d.as_secs_f64())).collect(); + tracing::info!(seconds = began.elapsed().as_secs_f64(), "capture loaded: {}", steps.join(", ")); + Ok(player) + } + + fn note(&mut self, n: String) { + tracing::warn!("{n}"); + self.notes.push(n); + } + + /// Says what of the frame is not there. + fn check(&mut self) -> Result<()> { + let missing = self.frame.submits.iter().flat_map(|s| &s.lists).filter(|&&l| l == MISSING).count(); + if missing > 0 { + self.note(format!("{missing} lists of the frame were not recorded: the frame is incomplete")); + } + if self.frame.submits.is_empty() { + bail!("the capture has no submission"); + } + let unknown = self.commands.iter().flatten().filter(|c| matches!(c, Cmd::RootView { va: Va::Unknown { .. }, .. })).count(); + if unknown > 0 { + self.note(format!("{unknown} root views name memory in no known buffer: they are null in the replay")); + } + Ok(()) + } + + fn resource(&self, id: u32) -> Option<&ID3D12Resource> { + if id == RESULTS { + return self.results.as_ref(); + } + self.objects.get(&id).map(|o| &o.res) + } + + fn va(&self, va: &Va) -> u64 { + match va { + Va::At { res, offset } => self.objects.get(res).map_or(0, |o| o.va + offset), + _ => 0, + } + } + + fn make_resources(&mut self, buffers: Buffers) -> Result<()> { + // A heap of memory the CPU sees becomes one the card may write too: + // what the CPU wrote is put back by the card. + let props = |p: &wire::HeapProps, buffer: bool| -> D3D12_HEAP_PROPERTIES { + let pc = |page| D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: page, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let card = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + match (gpu::seen(p), buffers) { + (Seen::ReadBack, _) => gpu::to_props(p), + (_, Buffers::Card) if buffer => card, + (Seen::No, Buffers::Pc) if buffer => pc(D3D12_CPU_PAGE_PROPERTY_WRITE_BACK), + (Seen::Combined, _) if p.kind > D3D12_HEAP_TYPE_CUSTOM.0 => card, + (Seen::Combined, _) => pc(D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE), + _ => gpu::to_props(p), + } + }; + // Flags a replay has no use for: sharing, display, not zeroed. + const DROP: i32 = 0x1 | 0x8 | 0x20 | 0x1000; + let used_by_buffers_only: HashSet = { + let mut textures = HashSet::new(); + for r in &self.frame.resources { + if let Place::Placed { heap, .. } = r.place + && r.desc.dimension != D3D12_RESOURCE_DIMENSION_BUFFER.0 + { + textures.insert(heap); + } + } + self.frame.heaps.iter().map(|h| h.id).filter(|id| !textures.contains(id)).collect() + }; + for h in &self.frame.heaps { + let desc = D3D12_HEAP_DESC { + SizeInBytes: h.size, + Properties: props(&h.props, used_by_buffers_only.contains(&h.id)), + Alignment: h.alignment, + Flags: D3D12_HEAP_FLAGS(h.flags & !DROP), + }; + let mut heap: Option = None; + // SAFETY: plain creation. + unsafe { self.device.CreateHeap(&desc, &mut heap) }.with_context(|| format!("heap {}", h.id))?; + self._heaps.extend(heap.map(|heap| (h.id, heap))); + } + let mut failed = 0; + for (index, r) in self.frame.resources.iter().enumerate() { + let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; + 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. + unsafe { std::mem::transmute::<[u32; 5], D3D12_CLEAR_VALUE>(c) } + }); + let clear = clear.as_ref().map(|c| c as *const _); + // SAFETY: plain creation from a description the host took. + let result = unsafe { + match &r.place { + Place::Placed { heap, offset } => match self._heaps.get(heap) { + Some(h) => self.device.CreatePlacedResource(h, *offset, &desc, D3D12_RESOURCE_STATE_COMMON, clear, &mut made), + None => Err(windows::core::Error::empty()), + }, + Place::Committed { props: p, flags } => { + let p = props(p, is_buffer); + let state = if p.Type == D3D12_HEAP_TYPE_READBACK { D3D12_RESOURCE_STATE_COPY_DEST } else { D3D12_RESOURCE_STATE_COMMON }; + self.device.CreateCommittedResource(&p, D3D12_HEAP_FLAGS(flags & !DROP), &desc, state, clear, &mut made) + } + Place::BackBuffer {} => { + let p = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + self.device.CreateCommittedResource(&p, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut made) + } + } + }; + match (result, made) { + (Ok(()), Some(res)) => { + // SAFETY: a live resource. + let va = if is_buffer { unsafe { res.GetGPUVirtualAddress() } } else { 0 }; + self.objects.insert(r.id, Object { res, va, index, subs: gpu::subresources(&r.desc) }); + } + (e, _) => { + if failed == 0 { + tracing::warn!("resource {} not made: {e:?}: {r:?}", r.id); + } + failed += 1; + } + } + if !is_buffer { + self.start.insert(r.id, r.state.clone()); + } + } + if failed > 0 { + self.note(format!("{failed} resources could not be made again")); + } + Ok(()) + } + + fn make_pipelines(&mut self) -> Result<()> { + for (id, blob) in &self.frame.roots { + // SAFETY: a blob the host took. + let root = unsafe { self.device.CreateRootSignature(0, &blob.0) }.with_context(|| format!("root signature {id}"))?; + self.roots.insert(*id, root); + } + for s in &self.frame.signatures { + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: s.stride, + NumArgumentDescs: s.args.len() as u32, + pArgumentDescs: s.args.as_ptr().cast(), + NodeMask: 0, + }; + let mut made: Option = None; + // SAFETY: a description the host took. + unsafe { self.device.CreateCommandSignature(&desc, self.roots.get(&s.root), &mut made)? }; + self.signatures.extend(made.map(|m| (s.id, m))); + } + for q in &self.frame.query_heaps { + let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE(q.kind), Count: q.count, NodeMask: 0 }; + let mut made: Option = None; + // SAFETY: plain creation. + unsafe { self.device.CreateQueryHeap(&desc, &mut made)? }; + self.queries.extend(made.map(|m| (q.id, m))); + } + let file = File::open(self.folder.join("shaders.bin"))?; + let device: ID3D12Device2 = self.device.cast()?; + let next = AtomicUsize::new(0); + type Made = std::result::Result; + let made: std::sync::Mutex> = std::sync::Mutex::default(); + let threads = std::thread::available_parallelism().map_or(4, |n| n.get() / 2).max(1); + let (frame, roots) = (&self.frame, &self.roots); + std::thread::scope(|scope| { + for _ in 0..threads { + scope.spawn(|| { + while let Some(p) = frame.pipelines.get(next.fetch_add(1, Ordering::Relaxed)) { + let code = |i: u32| { + let c = frame.codes.get(i as usize)?; + let mut bytes = vec![0; c.len as usize]; + read_at(&file, &mut bytes, c.at).ok()?; + Some(bytes) + }; + let m = super::pso::make(&device, &p.parts, |id| roots.get(&id).cloned(), code); + made.lock().unwrap_or_else(|e| e.into_inner()).push((p.id, m)); + } + }); + } + }); + let mut refused = Vec::new(); + for (id, m) in made.into_inner().unwrap_or_else(|e| e.into_inner()) { + match m { + Ok(p) => drop(self.pipelines.insert(id, p)), + Err(e) => refused.push((id, e)), + } + } + if let Some((id, e)) = refused.first() { + let n = format!("{} pipelines could not be made again, first {}: {e}", refused.len(), self.pipeline_name(*id)); + self.note(n); + } + Ok(()) + } + + /// A pipeline's name for reports: what the host layer called it and the + /// hashes of its shaders. + fn pipeline_name(&self, id: u32) -> String { + let Some(p) = self.frame.pipelines.iter().find(|p| p.id == id) else { + return format!("pipeline {id}"); + }; + let code: Vec = self.hashes(p); + format!("{} (DXIL {})", if p.name.is_empty() { "unnamed" } else { &p.name }, code.join(" ")) + } + + fn hashes(&self, p: &wire::Pipeline) -> Vec { + p.parts + .iter() + .filter_map(|part| match part { + wire::Part::Code { blob, .. } => { + let c = self.frame.codes.get(*blob as usize)?; + Some(c.hash[..8].iter().map(|b| format!("{b:02x}")).collect()) + } + _ => None, + }) + .collect() + } + + /// Makes a view; one of a resource that is not there is null. + /// + /// # Safety + /// `at` is a slot of a heap of the view's type. + unsafe fn view(&self, s: &Slot, at: D3D12_CPU_DESCRIPTOR_HANDLE, sampler: bool) { + let gone = s.res != NONE && !self.objects.contains_key(&s.res); + let res = self.objects.get(&s.res).map(|o| &o.res); + let counter = self.objects.get(&s.counter).map(|o| &o.res); + // The descriptions lie in the slot unaligned. + // SAFETY: the slot's description is of its kind; the resources live. + unsafe { + match (s.kind, s.described != 0 && !gone) { + (slot::CBV, described) => { + let mut d: D3D12_CONSTANT_BUFFER_VIEW_DESC = Default::default(); + if described && let Some(o) = self.objects.get(&s.res) { + d = s.desc.as_ptr().cast::().read_unaligned(); + d.BufferLocation = o.va + s.address(); + } + self.device.CreateConstantBufferView(Some(&d), at); + } + (slot::SRV, true) => { + let d = s.desc.as_ptr().cast::().read_unaligned(); + self.device.CreateShaderResourceView(res, Some(&d), at); + } + (slot::SRV, false) if res.is_some() => self.device.CreateShaderResourceView(res, None, at), + (slot::UAV, true) => { + let d = s.desc.as_ptr().cast::().read_unaligned(); + self.device.CreateUnorderedAccessView(res, counter, Some(&d), at); + } + (slot::UAV, false) if res.is_some() => self.device.CreateUnorderedAccessView(res, None::<&ID3D12Resource>, None, at), + (slot::SAMPLER, true) => { + let d = s.desc.as_ptr().cast::().read_unaligned(); + self.device.CreateSampler(&d, at); + } + _ if sampler => { + let d = D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + ..Default::default() + }; + self.device.CreateSampler(&d, at); + } + (slot::UAV, _) => { + let d = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT(41), + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + ..Default::default() + }; + self.device.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&d), at); + } + _ => { + let d = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(41), + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + ..Default::default() + }; + self.device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&d), at); + } + } + } + } + + fn make_descriptors(&mut self) -> Result<()> { + // A submission whose views replace ones that were in use gets a + // version of the heaps of its own: lists are sent without waiting, + // so a heap cannot be written between them. + let mut now: HashMap<(u32, u32), Slot> = HashMap::new(); + for h in &self.frame.descriptor_heaps { + for (first, n, s) in &h.runs { + now.extend((*first..first + n).map(|i| ((h.id, i), *s))); + } + } + // What each version changes against the one before. + let mut versions: Vec> = vec![Vec::new()]; + let mut touched: HashSet<(u32, u32)> = HashSet::new(); + for s in &self.frame.submits { + let live = |old: Option<&Slot>| old.is_some_and(|o| o.kind == slot::SAMPLER || o.res != NONE); + let news: Vec<&(u32, u32, Slot)> = s.views.iter().filter(|(h, i, v)| now.get(&(*h, *i)) != Some(v)).collect(); + if news.iter().any(|(h, i, _)| live(now.get(&(*h, *i))) || touched.contains(&(*h, *i))) { + versions.push(Vec::new()); + touched.clear(); + } + for (h, i, v) in news { + now.insert((*h, *i), *v); + touched.insert((*h, *i)); + if let Some(last) = versions.last_mut() { + last.push((*h, *i, *v)); + } + } + self.version_of.push(versions.len() - 1); + } + let mut made = HashMap::new(); + for h in &self.frame.descriptor_heaps { + let sampler = h.kind == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0; + let kind = D3D12_DESCRIPTOR_HEAP_TYPE(h.kind); + let make = |flags| -> windows::core::Result { + let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: h.count, Flags: flags, NodeMask: 0 }; + // SAFETY: plain creation. + unsafe { self.device.CreateDescriptorHeap(&d) } + }; + let cpu = make(D3D12_DESCRIPTOR_HEAP_FLAG_NONE)?; + // SAFETY: slots of the heap just made; threads write other ones. + unsafe { + let step = self.device.GetDescriptorHandleIncrementSize(kind) as usize; + let start = cpu.GetCPUDescriptorHandleForHeapStart(); + let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + i as usize * step }; + self.view(&Slot::EMPTY, start, sampler); + let mut filled = 1; + while filled < h.count { + let n = filled.min(h.count - filled).min(1 << 16); + // Sources and destinations do not overlap. + self.device.CopyDescriptorsSimple(n, at(filled), start, kind); + filled += n; + } + for (first, n, s) in &h.runs { + self.view(s, at(*first), sampler); + for i in 1..*n { + self.device.CopyDescriptorsSimple(1, at(first + i), at(*first), kind); + } + } + let mut all = Vec::new(); + for changes in &versions { + let mine: Vec<&(u32, u32, Slot)> = changes.iter().filter(|(id, _, _)| *id == h.id).collect(); + for (_, i, s) in &mine { + if *i < h.count { + self.view(s, at(*i), sampler); + } + } + if mine.is_empty() + && let Some(Version { heap, gpu }) = all.last() + { + let same = Version { heap: ID3D12DescriptorHeap::clone(heap), gpu: *gpu }; + all.push(same); + continue; + } + let heap = make(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)?; + self.device.CopyDescriptorsSimple(h.count, heap.GetCPUDescriptorHandleForHeapStart(), start, kind); + let gpu = heap.GetGPUDescriptorHandleForHeapStart().ptr; + all.push(Version { heap, gpu }); + } + made.insert(h.id, (all, step as u64)); + } + } + self.descriptors = made; + // Render target and depth views. + let mut views: [HashSet; 2] = Default::default(); + for c in self.commands.iter().flatten() { + match c { + Cmd::Targets { colors, depth } => { + views[0].extend(colors); + views[1].extend(depth); + } + Cmd::ClearTarget { view, .. } => drop(views[0].insert(*view)), + Cmd::ClearDepth { view, .. } => drop(views[1].insert(*view)), + _ => {} + } + } + for (i, all) in views.iter().enumerate() { + if all.is_empty() { + continue; + } + let kind = [D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_TYPE_DSV][i]; + let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: all.len() as u32, ..Default::default() }; + // SAFETY: plain creation; slots of the heap just made. + unsafe { + let heap: ID3D12DescriptorHeap = self.device.CreateDescriptorHeap(&d)?; + let step = self.device.GetDescriptorHandleIncrementSize(kind) as usize; + let mut at = heap.GetCPUDescriptorHandleForHeapStart(); + for s in all { + let res = self.objects.get(&s.res).map(|o| &o.res); + if i == 0 { + let d = s.desc.as_ptr().cast::().read_unaligned(); + // Without either there is nothing to make a view of. + let null = D3D12_RENDER_TARGET_VIEW_DESC { + Format: DXGI_FORMAT(28), + ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let d = if s.described != 0 { Some(&d as *const _) } else if res.is_none() { Some(&null as *const _) } else { None }; + self.device.CreateRenderTargetView(res, d, at); + } else { + let d = s.desc.as_ptr().cast::().read_unaligned(); + let null = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT(40), + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let d = if s.described != 0 { Some(&d as *const _) } else if res.is_none() { Some(&null as *const _) } else { None }; + self.device.CreateDepthStencilView(res, d, at); + } + self.targets.insert(*s, at); + at.ptr += step; + } + self._target_heaps.push(heap); + } + } + Ok(()) + } + + /// Reads parts of files into upload memory and has `copy` record what + /// is done with each. + fn upload( + &mut self, + parts: &[(T, u64, u64)], + file: &File, + mut copy: impl FnMut(&Player, &ID3D12GraphicsCommandList, &[(&T, u64, u64)], &ID3D12Resource), + ) -> Result<()> { + // Batches of parts with their place in the buffer. + let mut batches: Vec> = vec![Vec::new()]; + let (mut at, mut most) = (0u64, 0u64); + for (i, (_, len, _)) in parts.iter().enumerate() { + at = at.next_multiple_of(512); + if at + len > STAGING && at > 0 { + batches.push(Vec::new()); + at = 0; + } + if let Some(b) = batches.last_mut() { + b.push((i, at)); + } + at += len; + most = most.max(at); + } + if parts.is_empty() { + return Ok(()); + } + let mut stagings: Vec<(ID3D12Resource, usize, u64)> = Vec::new(); + for _ in 0..batches.len().min(2) { + let (b, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_UPLOAD, most, D3D12_RESOURCE_FLAG_NONE)?; + stagings.push((b, data as usize, 0)); + } + for (n, batch) in batches.iter().enumerate() { + let k = n % stagings.len(); + self.worker.wait(stagings[k].2)?; + let map = stagings[k].1; + let next = AtomicUsize::new(0); + let failed: std::sync::Mutex> = std::sync::Mutex::default(); + std::thread::scope(|scope| { + for _ in 0..8.min(batch.len()) { + scope.spawn(|| { + while let Some(&(i, at)) = batch.get(next.fetch_add(1, Ordering::Relaxed)) { + let (_, len, from) = &parts[i]; + // SAFETY: this part's own bytes of the mapping. + let to = unsafe { std::slice::from_raw_parts_mut((map + at as usize) as *mut u8, *len as usize) }; + if *from == ZERO { + to.fill(0); + } else if let Err(e) = read_at(file, to, *from) { + failed.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert(e); + } + } + }); + } + }); + if let Some(e) = failed.into_inner().unwrap_or_else(|e| e.into_inner()) { + return Err(e).context("the capture's contents"); + } + let list: Vec<(&T, u64, u64)> = batch.iter().map(|&(i, at)| (&parts[i].0, parts[i].1, at)).collect(); + let buffer = stagings[k].0.clone(); + // The worker is another part of the player than `copy` uses. + let other = Worker::new(&self.device, &self.worker.queue)?; + let mut worker = std::mem::replace(&mut self.worker, other); + let sent = worker.send(|l| copy(self, l, &list, &buffer)); + self.worker = worker; + stagings[k].2 = sent?; + } + self.worker.idle()?; + Ok(()) + } + + fn load_contents(&mut self) -> Result<()> { + // Idle aliases first: a change of their state may write memory the + // one in use holds. + let mut early = Vec::new(); + let mut into = Vec::new(); + for r in &self.frame.resources { + let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { continue }; + let loaded = !r.idle && self.frame.contents.iter().any(|c| c.res == r.id); + gpu::moves(&o.res, &[COMMON], if loaded { &[COPY_DEST] } else { state }, if loaded { &mut into } else { &mut early }); + } + let textures: Vec<(Content, u64, u64)> = self + .frame + .contents + .iter() + .filter(|c| self.objects.contains_key(&c.res)) + .map(|c| (c.clone(), c.len, c.file)) + .collect(); + let missing = self.frame.contents.len() - textures.len(); + self.worker.run(|list| { + // SAFETY: an open list; live resources. + unsafe { + for all in early.chunks(1000) { + list.ResourceBarrier(all); + } + list.ResourceBarrier(&[alias()]); + for all in into.chunks(1000) { + list.ResourceBarrier(all); + } + } + })?; + let file = File::open(self.folder.join("contents.bin"))?; + self.upload(&textures, &file, |player, list, parts, staging| { + for (c, len, at) in parts { + let Some(o) = player.objects.get(&c.res) else { continue }; + let r = &player.frame.resources[o.index]; + // SAFETY: an open list; live resources. + unsafe { + if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { + list.CopyBufferRegion(&o.res, c.first, staging, *at, *len); + continue; + } + let (all, _) = gpu::footprints(&player.device, &gpu::to_desc(&r.desc), c.first as u32, c.count); + for (i, mut f) in all.into_iter().enumerate() { + f.Offset += at; + let to = gpu::sub_location(&o.res, c.first as u32 + i as u32); + list.CopyTextureRegion(&to, 0, 0, 0, &gpu::placed_location(staging, f), None); + } + } + } + })?; + // To the states of the frame's start. + let mut back = Vec::new(); + for r in &self.frame.resources { + let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { continue }; + if !r.idle && self.frame.contents.iter().any(|c| c.res == r.id) { + gpu::moves(&o.res, &[COPY_DEST], state, &mut back); + } + } + self.worker.run(|list| { + for all in back.chunks(1000) { + // SAFETY: an open list; live resources. + unsafe { list.ResourceBarrier(all) }; + } + })?; + if missing > 0 { + self.note(format!("contents of {missing} parts of resources that could not be made are left out")); + } + // What the CPU had put into the memory both see by the first + // submission: part of the start of the frame. + let file = File::open(self.folder.join("deltas.bin"))?; + let first: Vec<(Delta, u64, u64)> = self.frame.submits[0].deltas.iter().map(|d| (d.clone(), d.len, d.file)).collect(); + self.upload(&first, &file, |player, list, parts, staging| { + for (d, len, at) in parts { + if let Some(o) = player.objects.get(&d.res) { + // SAFETY: an open list; live buffers. + unsafe { list.CopyBufferRegion(&o.res, d.at, staging, *at, *len) }; + } + } + })?; + // The later ones wait in a buffer of their own. + let mut later: Vec<((u64, Delta), u64, u64)> = Vec::new(); + let mut total = 0u64; + self.delta_parts = vec![Vec::new(); self.frame.submits.len()]; + for (i, s) in self.frame.submits.iter().enumerate().skip(1) { + for d in &s.deltas { + later.push(((total, d.clone()), d.len, d.file)); + self.delta_parts[i].push((d.clone(), total)); + total += d.len; + } + } + if total > 0 { + let (buffer, _) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, total, D3D12_RESOURCE_FLAG_NONE)?; + self.deltas = Some(buffer.clone()); + self.upload(&later, &file, |_, list, parts, staging| { + for ((to, _), len, at) in parts { + // SAFETY: an open list; live buffers. + unsafe { list.CopyBufferRegion(&buffer, *to, staging, *at, *len) }; + } + })?; + } + Ok(()) + } + + /// Copies of what the frame changes; and the states it leaves. + fn make_masters(&mut self) -> Result<()> { + let mut states = States::default(); + for r in &self.frame.resources { + if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { + continue; + } + let subs = gpu::subresources(&r.desc); + let decays = r.desc.flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0; + states.add(r.id, subs, r.state[0], decays); + if r.state.len() > 1 { + for (i, s) in r.state.iter().enumerate() { + states.change(&states::Change { res: r.id, sub: i as u32, after: *s, promoted: false, alias: false }); + } + } + } + // Resources in a state they are written in at some time, or written + // some other way. + const WRITE: u32 = RENDER_TARGET | UNORDERED_ACCESS | DEPTH_WRITE | COPY_DEST | RESOLVE_DEST; + let mut written: HashSet = + self.frame.resources.iter().filter(|r| r.state.iter().any(|s| s & WRITE != 0)).map(|r| r.id).collect(); + for (i, s) in self.frame.submits.iter().enumerate() { + for &l in s.lists.iter().filter(|&&l| l != MISSING) { + for c in &self.commands[l as usize] { + let mut changes = Vec::new(); + states::changes(c, &mut changes); + for ch in &changes { + states.change(ch); + } + match c { + Cmd::Barriers { all } => { + for b in all { + if let Barrier::Transition { res, before, after, .. } = b + && (*before | *after) as u32 & WRITE != 0 + { + written.insert(*res); + } + } + } + Cmd::CopyBuffer { dst, .. } | Cmd::CopyResource { dst, .. } | Cmd::ResolveQuery { dst, .. } => drop(written.insert(*dst)), + Cmd::CopyTexture { dst: Loc::Sub { res, .. } | Loc::Placed { res, .. }, .. } => drop(written.insert(*res)), + Cmd::Resolve { dst, .. } | Cmd::ResolveRegion { dst, .. } => drop(written.insert(*dst)), + Cmd::RootView { kind: slot::UAV, va: Va::At { res, .. }, .. } => drop(written.insert(*res)), + Cmd::WriteImmediate { all } => { + written.extend(all.iter().filter_map(|(va, _, _)| if let Va::At { res, .. } = va { Some(*res) } else { None })); + } + _ => {} + } + } + } + states.decay(); + if i > 0 { + written.extend(s.deltas.iter().map(|d| d.res)); + } + } + // Buffers any unordered-access view names. + let is_buffer = + |id: u32| self.objects.get(&id).is_some_and(|o| self.frame.resources[o.index].desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0); + let simultaneous = |id: u32| { + self.objects.get(&id).is_some_and(|o| { + self.frame.resources[o.index].desc.flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0 + }) + }; + let views = self.frame.descriptor_heaps.iter().flat_map(|h| h.runs.iter().map(|(_, _, s)| s)); + let late = self.frame.submits.iter().flat_map(|s| s.views.iter().map(|(_, _, s)| s)); + for s in views.chain(late).filter(|s| s.kind == slot::UAV) { + for id in [s.res, s.counter] { + if is_buffer(id) || simultaneous(id) { + written.insert(id); + } + } + } + for id in self.start.keys() { + self.end.insert(*id, states.get(*id).unwrap_or(vec![COMMON])); + } + let mut ids: Vec = written + .into_iter() + .filter(|id| { + self.objects.get(id).is_some_and(|o| { + let r = &self.frame.resources[o.index]; + let back = matches!(&r.place, Place::Committed { props, .. } if gpu::seen(props) == Seen::ReadBack); + !r.idle && !back && !matches!(r.place, Place::BackBuffer {}) + }) + }) + .collect(); + ids.sort_unstable(); + let mut total = 0u64; + let mut in_pc = 0u64; + for id in ids { + let o = &self.objects[&id]; + let r = &self.frame.resources[o.index]; + let mut desc = gpu::to_desc(&r.desc); + desc.Alignment = 0; + // Copies are only copied to and from; a depth format needs its + // flag. + if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { + desc.Flags = D3D12_RESOURCE_FLAG_NONE; + } + // SAFETY: a plain query. + let size = unsafe { self.device.GetResourceAllocationInfo(0, &[desc]) }.SizeInBytes; + let room = self.room(); + let buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; + let pc = buffer && room.is_some_and(|room| room < size + (1 << 30)); + let props = if pc { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + } + } else { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() } + }; + let mut made: Option = None; + // SAFETY: plain creation. + let result = unsafe { + self.device.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut made) + }; + match (result, made) { + (Ok(()), Some(m)) => { + total += size; + in_pc += if pc { size } else { 0 }; + self.masters.push((id, m)); + } + (e, _) => self.note(format!("no copy of resource {id} to restore it from ({e:?})")), + } + } + tracing::info!(resources = self.masters.len(), mb = total >> 20, in_pc_memory_mb = in_pc >> 20, "copies of what the frame changes"); + // Filled now: the resources are as at the frame's start. Masters + // stay in the copy-source state (buffers decay). + let (masters, objects, start) = (&self.masters, &self.objects, &self.start); + for some in masters.chunks(256) { + let (mut before, mut after) = (Vec::new(), Vec::new()); + for (id, m) in some { + let Some(state) = start.get(id) else { continue }; + let o = &objects[id]; + let to: Vec = state.iter().map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect(); + gpu::moves(&o.res, state, &to, &mut before); + gpu::moves(&o.res, &to, state, &mut after); + before.push(gpu::transition(m, ALL, COMMON, COPY_DEST)); + after.push(gpu::transition(m, ALL, COPY_DEST, COPY_SOURCE)); + } + self.worker.run(|list| { + // SAFETY: an open list; live resources of one size. + unsafe { + barriers(list, &before); + for (id, m) in some { + list.CopyResource(m, &objects[id].res); + } + barriers(list, &after); + } + })?; + } + Ok(()) + } + + /// What is free of the card's memory budget. + fn room(&self) -> Option { + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: plain queries. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter3 = factory.EnumAdapterByLuid(self.device.GetAdapterLuid()).ok()?; + adapter.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own).ok()?; + } + Some(own.Budget.saturating_sub(own.CurrentUsage)) + } + + /// Puts back what a run changed. + fn restore(&mut self, contents: bool) -> Result<()> { + if self.fresh { + return Ok(()); + } + let restored: HashMap = if contents { self.masters.iter().map(|(id, m)| (*id, m)).collect() } else { HashMap::new() }; + let (mut idle, mut into, mut back, mut plain) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for (id, start) in &self.start { + let Some(o) = self.objects.get(id) else { continue }; + let end = self.end.get(id).unwrap_or(start); + if restored.contains_key(id) { + gpu::moves(&o.res, end, &[COPY_DEST], &mut into); + gpu::moves(&o.res, &[COPY_DEST], start, &mut back); + } else if self.frame.resources[o.index].idle { + gpu::moves(&o.res, end, start, &mut idle); + } else { + gpu::moves(&o.res, end, start, &mut plain); + } + } + let objects = &self.objects; + self.worker.run(|list| { + // SAFETY: an open list; live resources, each copied from one of + // its own description. + unsafe { + barriers(list, &idle); + barriers(list, &[alias()]); + barriers(list, &plain); + barriers(list, &into); + for (id, m) in &restored { + list.CopyResource(&objects[id].res, *m); + } + barriers(list, &back); + } + })?; + self.fresh = true; + Ok(()) + } + + fn pipelines_named(&self, name: &str) -> HashSet { + self.frame.pipelines.iter().filter(|p| p.name == name).map(|p| p.id).collect() + } + + /// The frame's lists, edited: for each submission, its lists' commands. + fn edited(&mut self, o: &Options, report: &mut Report, clamps: &[Vec]) -> Vec>> { + let skip: HashSet = self + .frame + .pipelines + .iter() + .filter(|p| { + let hashes = self.hashes(p); + o.skip_shaders.iter().any(|s| !s.is_empty() && (p.name.contains(s.as_str()) || hashes.iter().any(|h| h.contains(s.as_str())))) + }) + .map(|p| p.id) + .collect(); + if !o.skip_shaders.is_empty() { + report.notes.push(format!("{} pipelines match --skip-shader", skip.len())); + } + let hash = self.pipelines_named(COMPARE); + let (mut skipped, mut hashed, mut uavs, mut merged) = (0, 0, 0, 0); + let mut place = 0; + let mut out = Vec::new(); + for s in &self.frame.submits { + let mut lists = Vec::new(); + for &l in s.lists.iter().filter(|&&l| l != MISSING) { + let mut cmds = self.commands[l as usize].clone(); + let here = place; + place += 1; + if o.only.is_some_and(|(from, to)| here < from || here > to) { + lists.push(edit::barriers_only(cmds)); + continue; + } + if o.skip_clamps && let Some(c) = clamps.get(here as usize) { + cmds = edit::skip_clamps(cmds, c); + } + let mut n; + if !skip.is_empty() { + (cmds, n) = edit::skip_pipelines(cmds, &skip); + skipped += n; + } + if o.skip_hash_passes { + (cmds, n) = edit::skip_pipelines(cmds, &hash); + hashed += n; + } + if o.no_barriers { + (cmds, n) = edit::no_uav_barriers(cmds); + uavs += n; + } + if o.merge_barriers { + (cmds, n) = edit::merge_barriers(cmds); + merged += n; + } + lists.push(cmds); + } + out.push(lists); + } + if !skip.is_empty() { + report.notes.push(format!("--skip-shader left out {skipped} commands")); + } + if o.skip_hash_passes { + report.notes.push(format!("--skip-hash-passes left out {hashed} dispatches")); + } + if o.no_barriers { + report.notes.push(format!("--no-barriers left out {uavs} unordered-access barriers")); + } + if o.merge_barriers { + report.notes.push(format!("--merge-barriers joined {merged} barrier calls to ones before them")); + } + out + } + + /// The clamp passes of each list of the frame, in order, and their + /// results in [`RESULTS`] (by a run that keeps them). + fn clamp_results(&mut self, report: &mut Report) -> Result>> { + let psos = self.pipelines_named(CLAMP); + let mut next = 0; + let mut clamps = Vec::new(); + let mut submits = Vec::new(); + for s in &self.frame.submits { + let mut lists = Vec::new(); + for &l in s.lists.iter().filter(|&&l| l != MISSING) { + let cmds = self.commands[l as usize].clone(); + let found = edit::find_clamps(&cmds, &psos, &mut next); + lists.push(edit::keep_clamped(cmds, &found)); + clamps.push(found); + } + submits.push(lists); + } + let n: usize = clamps.iter().map(Vec::len).sum(); + report.notes.push(format!("--skip-clamps: {n} clamp passes, {} KB of arguments kept from a first run", next >> 10)); + if n == 0 { + return Ok(clamps); + } + self.results = Some(gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, next, D3D12_RESOURCE_FLAG_NONE)?.0); + let built = self.build(&submits, &Options::default())?; + self.restore(true)?; + self.send(&built, false)?; + self.fresh = false; + Ok(clamps) + } + + /// Makes the lists of all submissions, and before each one's the copies + /// of what the CPU wrote. + fn build(&self, submits: &[Vec>], o: &Options) -> Result { + // Room for the timestamps of every command that has one. + let count: usize = submits + .iter() + .flatten() + .map(|c| 2 + if o.detailed { c.iter().filter(|c| c.works() || matches!(c, Cmd::Barriers { .. })).count() } else { 0 }) + .sum::() + + 2 * submits.len(); + let mut heap: Option = None; + let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: count.max(1) as u32, NodeMask: 0 }; + // SAFETY: plain creation. + unsafe { self.device.CreateQueryHeap(&desc, &mut heap)? }; + let heap = heap.context("no timestamps")?; + let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, count.max(1) as u64 * 8, D3D12_RESOURCE_FLAG_NONE)?; + let mut next = 0u32; + let mut steps = Vec::new(); + for (i, lists) in submits.iter().enumerate() { + let parts = self.delta_parts.get(i).filter(|p| !p.is_empty()); + let delta = match (parts, &self.deltas) { + (Some(parts), Some(from)) => { + let open = self.open(&heap, &mut next)?; + // SAFETY: an open list; live buffers. + unsafe { + let mut seen = HashSet::new(); + let mut after = Vec::new(); + for (d, at) in parts { + let Some(ob) = self.objects.get(&d.res) else { continue }; + open.1.CopyBufferRegion(&ob.res, d.at, from, *at, d.len); + if seen.insert(d.res) { + // Back to the common state by itself, for + // lists in the same submission. + after.push(gpu::transition(&ob.res, ALL, COPY_DEST, COMMON)); + } + } + barriers(&open.1, &after); + } + Some(self.close(open, &heap, &mut next, Vec::new())?) + } + _ => None, + }; + let mut built = Vec::new(); + for cmds in lists { + let open = self.open(&heap, &mut next)?; + let stamps = self.translate(&open.1, cmds, i, o.detailed.then_some((&heap, &mut next))); + built.push(self.close(open, &heap, &mut next, stamps)?); + } + steps.push((delta, built)); + } + // Between submissions that are sent as one: everything waits. A list + // each: one cannot stand twice in a submission. + let mut joints = Vec::new(); + if o.one_submit { + for _ in 0..2 * submits.len() { + let open = self.plain_list()?; + // SAFETY: an open list. + unsafe { + self.wait_for_all(&open.1); + open.1.Close()?; + } + joints.push(open); + } + } + let resolve = { + let open = self.plain_list()?; + // SAFETY: an open list; `next` queries were written. + unsafe { + open.1.ResolveQueryData(&heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, next.max(1), &back, 0); + open.1.Close()?; + } + open + }; + Ok(Sends { steps, joints, resolve, _heap: heap, _back: back, data: data as usize, count: next }) + } + + /// Records a wait for everything before, with all caches written out. + /// + /// # Safety + /// An open list. + unsafe fn wait_for_all(&self, list: &ID3D12GraphicsCommandList) { + // SAFETY: the caller's; a feature structure of its size. + unsafe { + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default(); + let size = size_of::() as u32; + let known = self.device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, (&raw mut o).cast(), size).is_ok(); + if known + && o.EnhancedBarriersSupported.as_bool() + && let Ok(list) = list.cast::() + { + let all = [D3D12_GLOBAL_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC_ALL, + SyncAfter: D3D12_BARRIER_SYNC_ALL, + AccessBefore: D3D12_BARRIER_ACCESS_COMMON, + AccessAfter: D3D12_BARRIER_ACCESS_COMMON, + }]; + list.Barrier(&[D3D12_BARRIER_GROUP { + Type: D3D12_BARRIER_TYPE_GLOBAL, + NumBarriers: 1, + Anonymous: D3D12_BARRIER_GROUP_0 { pGlobalBarriers: all.as_ptr() }, + }]); + } else { + list.ResourceBarrier(&[alias(), uav_barrier(None)]); + } + } + } + + fn plain_list(&self) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)> { + // SAFETY: plain creation. + unsafe { + let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list = self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + Ok((allocator, list)) + } + } + + fn open(&self, heap: &ID3D12QueryHeap, next: &mut u32) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList, u32)> { + let (allocator, list) = self.plain_list()?; + // SAFETY: an open list; a query of the heap. + unsafe { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, *next) }; + *next += 1; + Ok((allocator, list, *next - 1)) + } + + fn close( + &self, + (allocator, list, first): (ID3D12CommandAllocator, ID3D12GraphicsCommandList, u32), + heap: &ID3D12QueryHeap, + next: &mut u32, + stamps: Vec, + ) -> Result { + // SAFETY: as above. + unsafe { + list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, *next); + list.Close().context("a list of the frame could not be recorded again")?; + } + *next += 1; + Ok(Built { _allocator: allocator, list, first, last: *next - 1, stamps }) + } + + /// Records commands into a list, in submission `submit`. + fn translate( + &self, + list: &ID3D12GraphicsCommandList, + cmds: &[Cmd], + submit: usize, + mut stamp: Option<(&ID3D12QueryHeap, &mut u32)>, + ) -> Vec { + let version = self.version_of.get(submit).copied().unwrap_or(0); + let clamps = self.pipelines_named(CLAMP); + let compares = self.pipelines_named(COMPARE); + let mesh: HashSet = self + .frame + .pipelines + .iter() + .filter(|p| p.parts.iter().any(|part| matches!(part, wire::Part::Code { kind, .. } if *kind == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0))) + .map(|p| p.id) + .collect(); + let dispatches: HashSet = self + .frame + .signatures + .iter() + .filter(|s| s.args.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)) + .map(|s| s.id) + .collect(); + let mut stamps = Vec::new(); + let mut bound = NONE; + for c in cmds { + if let Cmd::Pipeline { pso } = c { + bound = *pso; + } + // SAFETY: an open list; the objects are the frame's, alive with + // the player; commands the host recorded the same way. + unsafe { self.command(list, c, version) }; + let timed = c.works() || matches!(c, Cmd::Barriers { .. }); + if timed && let Some((heap, next)) = &mut stamp { + // SAFETY: as above. + unsafe { list.EndQuery(*heap, D3D12_QUERY_TYPE_TIMESTAMP, **next) }; + let category = match c { + Cmd::Barriers { .. } => "barriers", + Cmd::Dispatch { .. } if clamps.contains(&bound) => "argument clamps (ours)", + Cmd::Dispatch { .. } if compares.contains(&bound) => "hash and compare passes (ours)", + Cmd::Dispatch { .. } => "dispatches", + Cmd::Indirect { signature, .. } if dispatches.contains(signature) => "indirect dispatches", + Cmd::Indirect { .. } if mesh.contains(&bound) => "indirect mesh draws", + Cmd::Indirect { .. } => "indirect draws", + Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::DispatchMesh { .. } => "draws", + Cmd::ClearDepth { .. } | Cmd::ClearTarget { .. } | Cmd::Discard { .. } => "clears", + Cmd::Resolve { .. } | Cmd::ResolveRegion { .. } => "resolves", + _ => "copies", + }; + let runs = if c.runs_shaders() { bound } else { NONE }; + stamps.push((**next as usize, category, runs)); + **next += 1; + } + } + stamps + } + + unsafe fn command(&self, l: &ID3D12GraphicsCommandList, c: &Cmd, version: usize) { + let res = |id: u32| self.resource(id); + let view = |s: &Slot| self.targets.get(s).copied().unwrap_or_default(); + // SAFETY: the caller's. + unsafe { + match c { + Cmd::Draw { vertices, instances, first, first_instance } => l.DrawInstanced(*vertices, *instances, *first, *first_instance), + Cmd::DrawIndexed { indices, instances, first, base, first_instance } => { + l.DrawIndexedInstanced(*indices, *instances, *first, *base, *first_instance); + } + Cmd::Dispatch { groups } => l.Dispatch(groups[0], groups[1], groups[2]), + Cmd::DispatchMesh { groups } => { + if let Ok(l) = l.cast::() { + l.DispatchMesh(groups[0], groups[1], groups[2]); + } + } + Cmd::CopyBuffer { dst, dst_at, src, src_at, len } => { + if let (Some(dst), Some(src)) = (res(*dst), res(*src)) { + l.CopyBufferRegion(dst, *dst_at, src, *src_at, *len); + } + } + Cmd::CopyTexture { dst, at, src, part } => { + let side = |loc: &Loc| match loc { + Loc::Sub { res: id, sub } => Some(gpu::sub_location(res(*id)?, *sub)), + Loc::Placed { res: id, offset, format, size, pitch } => { + let f = D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(*format), + Width: size[0], + Height: size[1], + Depth: size[2], + RowPitch: *pitch, + }; + Some(gpu::placed_location(res(*id)?, D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: *offset, Footprint: f })) + } + }; + if let (Some(dst), Some(src)) = (side(dst), side(src)) { + let part = part.map(|p| D3D12_BOX { left: p[0], top: p[1], front: p[2], right: p[3], bottom: p[4], back: p[5] }); + l.CopyTextureRegion(&dst, at[0], at[1], at[2], &src, part.as_ref().map(|p| p as *const _)); + } + } + Cmd::CopyResource { dst, src } => { + if let (Some(dst), Some(src)) = (res(*dst), res(*src)) { + l.CopyResource(dst, src); + } + } + Cmd::Resolve { dst, dst_sub, src, src_sub, format } => { + if let (Some(dst), Some(src)) = (res(*dst), res(*src)) { + l.ResolveSubresource(dst, *dst_sub, src, *src_sub, DXGI_FORMAT(*format)); + } + } + Cmd::ResolveRegion { dst, dst_sub, at, src, src_sub, part, format, mode } => { + if let (Some(dst), Some(src), Ok(l)) = (res(*dst), res(*src), l.cast::()) { + let part = part.map(to_rect); + let part = part.as_ref().map(|r| r as *const _); + l.ResolveSubresourceRegion(dst, *dst_sub, at[0], at[1], src, *src_sub, part, DXGI_FORMAT(*format), D3D12_RESOLVE_MODE(*mode)); + } + } + Cmd::Topology { kind } => l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(*kind)), + Cmd::Viewports { all } => { + let all: Vec = all + .iter() + .map(|v| D3D12_VIEWPORT { TopLeftX: v[0], TopLeftY: v[1], Width: v[2], Height: v[3], MinDepth: v[4], MaxDepth: v[5] }) + .collect(); + l.RSSetViewports(&all); + } + Cmd::Scissors { all } => l.RSSetScissorRects(&all.iter().map(|r| to_rect(*r)).collect::>()), + Cmd::BlendFactor { factor } => l.OMSetBlendFactor(factor.as_ref()), + Cmd::StencilRef { value } => l.OMSetStencilRef(*value), + Cmd::DepthBounds { min, max } => { + if let Ok(l) = l.cast::() { + l.OMSetDepthBounds(*min, *max); + } + } + Cmd::Pipeline { pso } => { + if let Some(p) = self.pipelines.get(pso) { + l.SetPipelineState(p); + } + } + Cmd::Barriers { all } => { + let all: Vec = all.iter().filter_map(|b| self.barrier(b)).collect(); + barriers(l, &all); + } + Cmd::Heaps { heaps } => { + let all: Vec> = + heaps.iter().filter_map(|id| Some(Some(self.descriptors.get(id)?.0.get(version)?.heap.clone()))).collect(); + l.SetDescriptorHeaps(&all); + } + Cmd::RootSignature { graphics, root } => { + let root = self.roots.get(root); + if *graphics { l.SetGraphicsRootSignature(root) } else { l.SetComputeRootSignature(root) } + } + Cmd::Table { graphics, param, heap, slot } => { + if let Some((versions, step)) = self.descriptors.get(heap) + && let Some(v) = versions.get(version) + { + let at = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: v.gpu + u64::from(*slot) * step }; + if *graphics { l.SetGraphicsRootDescriptorTable(*param, at) } else { l.SetComputeRootDescriptorTable(*param, at) } + } + } + Cmd::Constants { graphics, param, offset, values } => { + let (n, data) = (values.len() as u32, values.as_ptr().cast()); + if *graphics { + l.SetGraphicsRoot32BitConstants(*param, n, data, *offset); + } else { + l.SetComputeRoot32BitConstants(*param, n, data, *offset); + } + } + Cmd::RootView { graphics, kind, param, va } => { + let va = self.va(va); + match (*kind, *graphics) { + (slot::CBV, true) => l.SetGraphicsRootConstantBufferView(*param, va), + (slot::CBV, false) => l.SetComputeRootConstantBufferView(*param, va), + (slot::SRV, true) => l.SetGraphicsRootShaderResourceView(*param, va), + (slot::SRV, false) => l.SetComputeRootShaderResourceView(*param, va), + (_, true) => l.SetGraphicsRootUnorderedAccessView(*param, va), + (_, false) => l.SetComputeRootUnorderedAccessView(*param, va), + } + } + Cmd::IndexBuffer { view } => { + let v = view.as_ref().map(|(va, size, format)| D3D12_INDEX_BUFFER_VIEW { + BufferLocation: self.va(va), + SizeInBytes: *size, + Format: DXGI_FORMAT(*format), + }); + l.IASetIndexBuffer(v.as_ref().map(|v| v as *const _)); + } + Cmd::VertexBuffers { start, views, count } => match views { + Some(views) => { + let all: Vec = views + .iter() + .map(|(va, size, stride)| D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: self.va(va), + SizeInBytes: *size, + StrideInBytes: *stride, + }) + .collect(); + l.IASetVertexBuffers(*start, Some(&all)); + } + None => l.IASetVertexBuffers(*start, Some(&vec![D3D12_VERTEX_BUFFER_VIEW::default(); *count as usize])), + }, + Cmd::Targets { colors, depth } => { + let colors: Vec = colors.iter().map(view).collect(); + let depth = depth.as_ref().map(view); + l.OMSetRenderTargets( + colors.len() as u32, + (!colors.is_empty()).then_some(colors.as_ptr()), + false, + depth.as_ref().map(|d| d as *const _), + ); + } + Cmd::ClearDepth { view: v, flags, depth, stencil, rects } => { + let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); + let rects = (!rects.is_empty()).then_some(&rects[..]); + if self.objects.contains_key(&v.res) { + l.ClearDepthStencilView(view(v), D3D12_CLEAR_FLAGS(*flags), *depth, *stencil, rects); + } + } + Cmd::ClearTarget { view: v, color, rects } => { + let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); + let rects = (!rects.is_empty()).then_some(&rects[..]); + if self.objects.contains_key(&v.res) { + l.ClearRenderTargetView(view(v), color, rects); + } + } + Cmd::Discard { res: id, rects, subs } => { + if let Some(r) = res(*id) { + let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); + let region = subs.map(|s| D3D12_DISCARD_REGION { + NumRects: rects.len() as u32, + pRects: if rects.is_empty() { std::ptr::null() } else { rects.as_ptr() }, + FirstSubresource: s[0], + NumSubresources: s[1], + }); + l.DiscardResource(r, region.as_ref().map(|r| r as *const _)); + } + } + Cmd::BeginQuery { heap, kind, index } => { + if let Some(h) = self.queries.get(heap) { + l.BeginQuery(h, D3D12_QUERY_TYPE(*kind), *index); + } + } + Cmd::EndQuery { heap, kind, index } => { + if let Some(h) = self.queries.get(heap) { + l.EndQuery(h, D3D12_QUERY_TYPE(*kind), *index); + } + } + Cmd::ResolveQuery { heap, kind, first, count, dst, at } => { + if let (Some(h), Some(dst)) = (self.queries.get(heap), res(*dst)) { + l.ResolveQueryData(h, D3D12_QUERY_TYPE(*kind), *first, *count, dst, *at); + } + } + Cmd::Indirect { signature, most, args, at, count, count_at } => { + if let (Some(s), Some(a)) = (self.signatures.get(signature), res(*args)) { + l.ExecuteIndirect(s, *most, a, *at, res(*count), *count_at); + } + } + Cmd::WriteImmediate { all } => { + if let Ok(l) = l.cast::() { + let all: Vec<&(Va, u32, i32)> = all.iter().filter(|(va, _, _)| self.va(va) != 0).collect(); + let params: Vec = + all.iter().map(|(va, v, _)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: self.va(va), Value: *v }).collect(); + let modes: Vec = all.iter().map(|(_, _, m)| D3D12_WRITEBUFFERIMMEDIATE_MODE(*m)).collect(); + if !params.is_empty() { + l.WriteBufferImmediate(params.len() as u32, params.as_ptr(), Some(modes.as_ptr())); + } + } + } + } + } + } + + fn barrier(&self, b: &Barrier) -> Option { + Some(match b { + Barrier::Transition { flags, res, sub, before, after } => { + let mut t = gpu::transition(self.resource(*res)?, *sub, *before as u32, *after as u32); + t.Flags = D3D12_RESOURCE_BARRIER_FLAGS(*flags); + t + } + Barrier::Uav { flags, res } => { + let mut u = uav_barrier(if *res == NONE { None } else { Some(self.resource(*res)?) }); + u.Flags = D3D12_RESOURCE_BARRIER_FLAGS(*flags); + u + } + Barrier::Alias { flags, before, after } => { + let side = |id: &u32| -> std::mem::ManuallyDrop> { + // SAFETY: a borrowed pointer (or none) never released. + self.resource(*id).map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { std::mem::transmute_copy(r) }) + }; + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAGS(*flags), + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: side(before), + pResourceAfter: side(after), + }), + }, + } + } + }) + } + + /// Sends the frame, waits for it, and reads the timestamps. + fn send(&mut self, s: &Sends, one: bool) -> Result> { + let cast = |l: &ID3D12GraphicsCommandList| l.cast::().map(Some); + let mut submissions: Vec>> = Vec::new(); + for (delta, lists) in &s.steps { + if let Some(d) = delta { + submissions.push(vec![cast(&d.list)?]); + } + let mut all = Vec::new(); + for l in lists { + all.push(cast(&l.list)?); + } + if !all.is_empty() { + submissions.push(all); + } + } + if one { + let mut all = Vec::new(); + for (i, lists) in submissions.into_iter().enumerate() { + if i > 0 + && let Some(joint) = s.joints.get(i) + { + all.push(cast(&joint.1)?); + } + all.extend(lists); + } + submissions = vec![all]; + } + // SAFETY: closed lists whose last run has finished. + unsafe { + for all in &submissions { + self.worker.queue.ExecuteCommandLists(all); + } + self.worker.queue.ExecuteCommandLists(&[cast(&s.resolve.1)?]); + } + self.worker.idle().context("the card was lost running the frame")?; + // SAFETY: the mapping of `count` resolved timestamps. + Ok(unsafe { std::slice::from_raw_parts(s.data as *const u64, s.count as usize) }.to_vec()) + } + + /// Runs the frame as the options say. + pub fn run(&mut self, o: &Options) -> Result { + let mut report = Report { notes: self.notes.clone(), ..Default::default() }; + let clamps = if o.skip_clamps { self.clamp_results(&mut report)? } else { Vec::new() }; + let submits = self.edited(o, &mut report, &clamps); + let built = self.build(&submits, o)?; + let mut stamps = Vec::new(); + for _ in 0..o.loops.max(1) { + self.restore(o.restore)?; + self.fresh = false; + stamps = self.send(&built, o.one_submit)?; + let ms = |a: u32, b: u32| stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency; + let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect(); + let (Some(first), Some(last)) = (lists.first(), lists.last()) else { + bail!("no lists to run"); + }; + let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref()); + report.delta_ms.push(delta.filter(|d| d.first > first.first).map(|d| ms(d.first, d.last)).sum()); + report.frame_ms.push(ms(first.first, last.last)); + let each = |l: &[Built]| match (l.first(), l.last()) { + (Some(a), Some(b)) => ms(a.first, b.last), + _ => 0.0, + }; + report.submits = built.steps.iter().map(|(_, l)| (l.len(), each(l))).collect(); + report.busy_ms.push(report.submits.iter().map(|s| s.1).sum()); + } + if o.detailed { + self.detail(&built, &stamps, o, &mut report); + } + self.picture(o, &mut report)?; + if let Some(q) = &self.info { + let n = debug_messages(q); + report.notes.push(format!("{n} errors from the debug layer")); + } + Ok(report) + } + + /// The last loop's time by command. + fn detail(&self, built: &Sends, stamps: &[u64], o: &Options, report: &mut Report) { + let mut kinds: BTreeMap<&str, (f64, u32)> = BTreeMap::new(); + let mut shaders: HashMap = HashMap::new(); + for l in built.steps.iter().flat_map(|(_, l)| l) { + let mut before = stamps[l.first as usize]; + for &(at, kind, pso) in &l.stamps { + let ms = stamps[at].saturating_sub(before) as f64 * 1e3 / self.frequency; + before = before.max(stamps[at]); + let k = kinds.entry(kind).or_default(); + *k = (k.0 + ms, k.1 + 1); + if pso != NONE { + let s = shaders.entry(pso).or_default(); + *s = (s.0 + ms, s.1 + 1); + } + } + } + report.categories = kinds.into_iter().map(|(k, (ms, n))| (k.to_owned(), ms, n)).collect(); + report.categories.sort_by(|a, b| b.1.total_cmp(&a.1)); + let mut all: Vec<(f64, u32, u32)> = shaders.into_iter().map(|(pso, (ms, n))| (ms, n, pso)).collect(); + all.sort_by(|a, b| b.0.total_cmp(&a.0)); + all.truncate(o.top); + report.shaders = all.into_iter().map(|(ms, n, pso)| (ms, n, self.pipeline_name(pso))).collect(); + } + + /// Saves the presented picture and compares it with the recorded one. + fn picture(&mut self, o: &Options, report: &mut Report) -> Result<()> { + let Some(p) = self.frame.presents.last().cloned() else { + report.notes.push("no picture was presented".into()); + return Ok(()); + }; + let Some(bytes) = self.contents(p.res)? else { + report.notes.push("the presented texture is not there".into()); + return Ok(()); + }; + let Some(rgb) = gpu::rgb(p.width, p.height, p.pitch, p.format, &bytes) else { + report.notes.push("the presented format is not shown".into()); + return Ok(()); + }; + let path = o.image.clone().unwrap_or_else(|| self.folder.join("replay.png")); + std::fs::write(&path, crate::capture::png(p.width, p.height, &rgb))?; + let mut recorded = vec![0; bytes.len()]; + read_at(&File::open(self.folder.join("present.bin"))?, &mut recorded, p.file)?; + let was = gpu::rgb(p.width, p.height, p.pitch, p.format, &recorded).unwrap_or_default(); + report.picture = Some((gpu::psnr(&rgb, &was), rows_equal(&p, &bytes, &recorded))); + report.notes.push(format!( + "picture {} (blake3 {}; recorded {})", + path.display(), + &blake3::hash(&rgb).to_hex()[..16], + &blake3::hash(&was).to_hex()[..16] + )); + Ok(()) + } + + /// What a resource holds now (after a run): a buffer's bytes, or a + /// texture's first subresource in its copyable layout. + pub fn contents(&mut self, id: u32) -> Result>> { + let Some(o) = self.objects.get(&id) else { + return Ok(None); + }; + let (res, r, subs) = (o.res.clone(), &self.frame.resources[o.index], o.subs); + let desc = gpu::to_desc(&r.desc); + let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; + let states = if self.fresh { &self.start } else { &self.end }; + let state = states.get(&id).cloned().unwrap_or(vec![COMMON]); + let (f, total) = if is_buffer { (Vec::new(), r.desc.width) } else { gpu::footprints(&self.device, &desc, 0, 1) }; + let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_FLAG_NONE)?; + self.worker.run(|list| { + if is_buffer { + // SAFETY: an open list; live buffers. + unsafe { list.CopyBufferRegion(&back, 0, &res, 0, total) }; + } else if state.len() == 1 || subs == 1 { + read_sub(list, &res, 0, state[0], &back, f[0]); + } else { + let (mut before, mut after) = (Vec::new(), Vec::new()); + gpu::moves(&res, &state, &[COPY_SOURCE], &mut before); + gpu::moves(&res, &[COPY_SOURCE], &state, &mut after); + // SAFETY: an open list; live resources. + unsafe { barriers(list, &before) }; + read_sub(list, &res, 0, COPY_SOURCE, &back, f[0]); + // SAFETY: as above. + unsafe { barriers(list, &after) }; + } + })?; + // SAFETY: the buffer's mapping; the copy into it has run. + Ok(Some(unsafe { std::slice::from_raw_parts(data, total as usize) }.to_vec())) + } + + /// The id of the resource of a name (tests). + pub fn named(&self, name: &str) -> Option { + self.frame.resources.iter().find(|r| r.name == name).map(|r| r.id) + } +} + +/// Everything to send for a frame. +struct Sends { + /// For each submission: the copies of what the CPU wrote, its lists. + steps: Vec<(Option, Vec)>, + joints: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>, + resolve: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), + _heap: ID3D12QueryHeap, + _back: ID3D12Resource, + data: usize, + count: u32, +} + +fn rows_equal(p: &wire::Present, a: &[u8], b: &[u8]) -> bool { + let texel = match p.format { + 9..=14 => 8, + _ => 4, + }; + (0..p.height as usize).all(|y| { + let from = y * p.pitch as usize; + let to = from + p.width as usize * texel; + a.get(from..to) == b.get(from..to) + }) +} + +fn to_rect(r: [i32; 4]) -> RECT { + RECT { left: r[0], top: r[1], right: r[2], bottom: r[3] } +} + +/// # Safety +/// An open list; barriers of live resources. +unsafe fn barriers(list: &ID3D12GraphicsCommandList, all: &[D3D12_RESOURCE_BARRIER]) { + for some in all.chunks(1000) { + // SAFETY: the caller's. + unsafe { list.ResourceBarrier(some) }; + } +} + +fn uav_barrier(res: Option<&ID3D12Resource>) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + // SAFETY: a borrowed pointer (or none) never released. + pResource: res.map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { std::mem::transmute_copy(r) }), + }), + }, + } +} + +/// Any placed resource to any other: waits for all writes. +fn alias() -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::ManuallyDrop::new(None), + pResourceAfter: std::mem::ManuallyDrop::new(None), + }), + }, + } +} + +fn read_at(file: &File, mut to: &mut [u8], mut at: u64) -> std::io::Result<()> { + while !to.is_empty() { + let n = file.seek_read(to, at)?; + if n == 0 { + return Err(std::io::ErrorKind::UnexpectedEof.into()); + } + to = &mut to[n..]; + at += n as u64; + } + Ok(()) +} + +fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option)> { + // SAFETY: plain creation and queries. + unsafe { + if debug { + let mut layer: Option = None; + match D3D12GetDebugInterface(&mut layer) { + Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()), + Err(e) => tracing::warn!("no debug layer: {e}"), + } + } + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + let mut adapter = None; + for i in 0.. { + let Ok(a) = factory.EnumAdapters1(i) else { break }; + let d = a.GetDesc1()?; + if (d.VendorId, d.DeviceId) == (frame.vendor, frame.device) { + adapter = Some(a); + break; + } + } + if adapter.is_none() { + tracing::warn!("the adapter recorded on ({}) is not here: the default one is used", frame.adapter); + } + let mut device: Option = None; + match &adapter { + Some(a) => D3D12CreateDevice(a, D3D_FEATURE_LEVEL_12_0, &mut device)?, + None => D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?, + } + let device = device.context("no device")?; + let info = device.cast::().ok(); + Ok((device, info)) + } +} + +/// Logs the debug layer's messages; how many errors. +fn debug_messages(q: &ID3D12InfoQueue) -> usize { + let mut errors = 0; + let mut seen: HashMap = HashMap::new(); + // SAFETY: messages read into buffers of the size asked for. + unsafe { + for i in 0..q.GetNumStoredMessages() { + let mut size = 0; + if q.GetMessage(i, None, &mut size).is_err() { + continue; + } + let mut buffer = vec![0u64; size.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::(); + if q.GetMessage(i, Some(message), &mut size).is_err() { + continue; + } + let m = &*message; + if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 { + errors += 1; + let n = seen.entry(m.ID.0).or_default(); + *n += 1; + if *n <= 3 { + let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); + tracing::warn!("D3D12 {}: {}", m.ID.0, String::from_utf8_lossy(text).trim_end_matches('\0')); + } + } + } + q.ClearStoredMessages(); + } + errors +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn captures_are_found() { + let dir = tempfile::tempdir().unwrap(); + assert!(find(dir.path()).is_err()); + for n in [1, 2, 10, 11] { + std::fs::create_dir(dir.path().join(format!("capture-{n}"))).unwrap(); + } + for n in [1, 2, 10] { + std::fs::write(dir.path().join(format!("capture-{n}/frame.bin")), "").unwrap(); + } + // The last complete one; itself when named. + assert_eq!(find(dir.path()).unwrap(), dir.path().join("capture-10")); + assert_eq!(find(&dir.path().join("capture-2")).unwrap(), dir.path().join("capture-2")); + } + + #[test] + fn reports() { + assert_eq!(median(&[]), 0.0); + assert_eq!(median(&[3.0, 1.0, 2.0]), 2.0); + let r = Report { + frame_ms: vec![10.0, 12.0, 11.0], + busy_ms: vec![9.0; 3], + delta_ms: vec![0.5; 3], + submits: vec![(2, 9.0)], + picture: Some((40.0, false)), + ..Default::default() + }; + let t = r.text("a frame"); + assert!(t.contains("a frame: 11.00 ms"), "{t}"); + assert!(t.contains("between submissions 1.50 ms"), "{t}"); + assert!(t.contains("PSNR 40.0 dB"), "{t}"); + let o = Options { skip_clamps: true, buffers: Buffers::Card, ..Default::default() }; + assert!(o.edited() && !o.plain().edited() && o.plain().buffers == Buffers::Card); + } +} diff --git a/crates/victory-gpu/src/replay/pso.rs b/crates/victory-gpu/src/replay/pso.rs new file mode 100644 index 0000000..c1baa0d --- /dev/null +++ b/crates/victory-gpu/src/replay/pso.rs @@ -0,0 +1,317 @@ +//! Pipeline descriptions as parts: every form D3D12 takes them in (graphics, +//! compute, stream) is kept as the subobjects of a stream, and made again +//! from them as a stream. + +use std::ffi::{CString, c_void}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::core::{Interface, PCSTR}; + +use super::wire::{Blob, Part}; + +/// What a subobject holds, by its type: bytes, and whether it starts with a +/// pointer (aligned to 8). +enum Holds { + Root, + Code, + Layout, + /// Pointers the recorder does not follow. + Pointers(usize), + Plain(usize), +} + +fn holds(kind: i32) -> Option { + Some(match kind { + 0 => Holds::Root, + 1..=6 | 24 | 25 => Holds::Code, + 7 => Holds::Pointers(size_of::()), + 8 => Holds::Plain(size_of::()), + 9 | 13 | 14 | 16 | 18 | 20 => Holds::Plain(4), + 10 => Holds::Plain(size_of::()), + 11 => Holds::Plain(size_of::()), + 12 => Holds::Layout, + 15 => Holds::Plain(size_of::()), + 17 => Holds::Plain(size_of::()), + 19 => Holds::Pointers(size_of::()), + 21 => Holds::Plain(size_of::()), + 22 => Holds::Pointers(size_of::()), + 26 => Holds::Plain(size_of::()), + 27 => Holds::Plain(size_of::()), + 28 => Holds::Plain(size_of::()), + _ => return None, + }) +} + +/// What the parts need from the recorder. +pub(super) trait Keep { + fn root(&mut self, root: *mut c_void) -> u32; + fn code(&mut self, code: &[u8]) -> u32; + /// Something in a description that is not kept. + fn lost(&mut self, what: &str); +} + +/// # Safety +/// `at` points at a value of `size` bytes. +unsafe fn plain(kind: i32, at: *const c_void, size: usize) -> Part { + // SAFETY: the caller's. + Part::Plain { kind, data: Blob(unsafe { std::slice::from_raw_parts(at.cast::(), size) }.to_vec()) } +} + +unsafe fn code(kind: i32, c: &D3D12_SHADER_BYTECODE, keep: &mut dyn Keep) -> Option { + if c.pShaderBytecode.is_null() || c.BytecodeLength == 0 { + return None; + } + // SAFETY: the description's own code. + let bytes = unsafe { std::slice::from_raw_parts(c.pShaderBytecode.cast::(), c.BytecodeLength) }; + Some(Part::Code { kind, blob: keep.code(bytes) }) +} + +unsafe fn layout(l: &D3D12_INPUT_LAYOUT_DESC) -> Option { + if l.pInputElementDescs.is_null() || l.NumElements == 0 { + return None; + } + // SAFETY: the description's own elements, with their names. + let elements = unsafe { std::slice::from_raw_parts(l.pInputElementDescs, l.NumElements as usize) } + .iter() + .map(|e| { + // SAFETY: as above. + let name = unsafe { e.SemanticName.to_string() }.unwrap_or_default(); + let rest = [ + e.SemanticIndex, + e.Format.0 as u32, + e.InputSlot, + e.AlignedByteOffset, + e.InputSlotClass.0 as u32, + e.InstanceDataStepRate, + ]; + (name, rest) + }) + .collect(); + Some(Part::Layout { elements }) +} + +/// # Safety +/// A valid description. +pub(super) unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, keep: &mut dyn Keep) -> Vec { + // SAFETY: the caller's description. + unsafe { + let mut parts = vec![Part::Root { root: keep.root(std::mem::transmute_copy(&d.pRootSignature)) }]; + parts.extend(code(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS.0, &d.CS, keep)); + if d.Flags.0 != 0 { + parts.push(plain(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS.0, (&raw const d.Flags).cast(), 4)); + } + parts + } +} + +/// # Safety +/// A valid description. +pub(super) unsafe fn graphics(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, keep: &mut dyn Keep) -> Vec { + // SAFETY: the caller's description. + unsafe { + let mut parts = vec![Part::Root { root: keep.root(std::mem::transmute_copy(&d.pRootSignature)) }]; + for (kind, c) in [(1, &d.VS), (2, &d.PS), (3, &d.DS), (4, &d.HS), (5, &d.GS)] { + parts.extend(code(kind, c, keep)); + } + if d.StreamOutput.NumEntries != 0 { + keep.lost("a pipeline's stream output"); + } + parts.push(plain(8, (&raw const d.BlendState).cast(), size_of::())); + parts.push(plain(9, (&raw const d.SampleMask).cast(), 4)); + parts.push(plain(10, (&raw const d.RasterizerState).cast(), size_of::())); + parts.push(plain(11, (&raw const d.DepthStencilState).cast(), size_of::())); + parts.extend(layout(&d.InputLayout)); + parts.push(plain(13, (&raw const d.IBStripCutValue).cast(), 4)); + parts.push(plain(14, (&raw const d.PrimitiveTopologyType).cast(), 4)); + let targets = D3D12_RT_FORMAT_ARRAY { RTFormats: d.RTVFormats, NumRenderTargets: d.NumRenderTargets }; + parts.push(plain(15, (&raw const targets).cast(), size_of::())); + parts.push(plain(16, (&raw const d.DSVFormat).cast(), 4)); + parts.push(plain(17, (&raw const d.SampleDesc).cast(), size_of::())); + if d.Flags.0 != 0 { + parts.push(plain(20, (&raw const d.Flags).cast(), 4)); + } + parts + } +} + +/// # Safety +/// A valid description. +pub(super) unsafe fn stream(d: &D3D12_PIPELINE_STATE_STREAM_DESC, keep: &mut dyn Keep) -> Vec { + let base = d.pPipelineStateSubobjectStream.cast::().cast_const(); + let mut parts = Vec::new(); + let mut at = 0usize; + while at + 4 <= d.SizeInBytes { + // SAFETY: the caller's stream holds whole subobjects, each at a + // multiple of the size of a pointer. + unsafe { + let kind = base.add(at).cast::().read(); + let Some(h) = holds(kind) else { + keep.lost(&format!("a pipeline stream's subobject of type {kind}, and those after it")); + break; + }; + let (from, size) = match h { + Holds::Root => (8, 8), + Holds::Code | Holds::Layout => (8, 16), + Holds::Pointers(n) => (8, n), + Holds::Plain(n) => (4, n), + }; + let value = base.add(at + from); + match h { + Holds::Root => parts.push(Part::Root { root: keep.root(value.cast::<*mut c_void>().read()) }), + Holds::Code => parts.extend(code(kind, &*value.cast(), keep)), + Holds::Layout => parts.extend(layout(&*value.cast())), + Holds::Pointers(_) => { + // A cached blob is only a shortcut. + let empty = std::slice::from_raw_parts(value, size).iter().all(|&b| b == 0); + if kind != D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO.0 && !empty { + keep.lost(&format!("a pipeline stream's subobject of type {kind}")); + } + } + Holds::Plain(n) => parts.push(plain(kind, value.cast(), n)), + } + at += (from + size).next_multiple_of(8); + } + } + parts +} + +/// A pipeline made again. +pub(super) fn make( + device: &ID3D12Device2, + parts: &[Part], + root: impl Fn(u32) -> Option, + code: impl Fn(u32) -> Option>, +) -> Result { + // Everything the stream points at, kept until the pipeline is made. + let mut codes: Vec> = Vec::new(); + let mut names: Vec = Vec::new(); + let mut elements: Vec> = Vec::new(); + let mut bytes: Vec = Vec::new(); + let mut roots = Vec::new(); + for part in parts { + bytes.resize(bytes.len().next_multiple_of(8), 0); + match part { + Part::Root { root: 0 } => {} + Part::Root { root: id } => { + let r = root(*id).ok_or_else(|| format!("root signature {id} is not in the capture"))?; + bytes.extend([0u8; 8]); + bytes.extend((r.as_raw() as usize).to_le_bytes()); + roots.push(r); + } + Part::Code { kind, blob } => { + let c = code(*blob).ok_or_else(|| format!("shader {blob} is not in the capture"))?; + bytes.extend(kind.to_le_bytes()); + bytes.extend([0u8; 4]); + bytes.extend((c.as_ptr() as usize).to_le_bytes()); + bytes.extend(c.len().to_le_bytes()); + codes.push(c); + } + Part::Plain { kind, data } => { + bytes.extend(kind.to_le_bytes()); + bytes.extend_from_slice(&data.0); + } + Part::Layout { elements: all } => { + let made: Vec = all + .iter() + .map(|(name, r)| { + names.push(CString::new(name.as_str()).unwrap_or_default()); + D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(names.last().map_or(std::ptr::null(), |n| n.as_ptr().cast())), + SemanticIndex: r[0], + Format: DXGI_FORMAT(r[1] as i32), + InputSlot: r[2], + AlignedByteOffset: r[3], + InputSlotClass: D3D12_INPUT_CLASSIFICATION(r[4] as i32), + InstanceDataStepRate: r[5], + } + }) + .collect(); + bytes.extend(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0.to_le_bytes()); + bytes.extend([0u8; 4]); + bytes.extend((made.as_ptr() as usize).to_le_bytes()); + bytes.extend((made.len() as u64).to_le_bytes()); + elements.push(made); + } + } + } + bytes.resize(bytes.len().next_multiple_of(8), 0); + // Aligned for the pointers in it. + let mut words: Vec = bytes.chunks_exact(8).map(|c| u64::from_le_bytes(c.try_into().unwrap_or_default())).collect(); + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: words.len() * 8, + pPipelineStateSubobjectStream: words.as_mut_ptr().cast(), + }; + // SAFETY: a stream of whole subobjects; all it points at is alive. + let made: windows::core::Result = unsafe { device.CreatePipelineState(&desc) }; + made.map_err(|e| e.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Default)] + struct Kept { + codes: Vec>, + lost: Vec, + } + + impl Keep for Kept { + fn root(&mut self, root: *mut c_void) -> u32 { + root as usize as u32 + } + fn code(&mut self, code: &[u8]) -> u32 { + self.codes.push(code.to_vec()); + self.codes.len() as u32 - 1 + } + fn lost(&mut self, what: &str) { + self.lost.push(what.into()); + } + } + + #[test] + fn a_stream_is_taken_apart() { + #[repr(C, align(8))] + struct Sub(i32, T); + #[repr(C)] + struct Stream { + root: Sub, + ms: Sub, + blend: Sub, + mask: Sub, + raster: Sub, + depth: Sub, + targets: Sub, + dsv: Sub, + samples: Sub, + unknown: Sub, + } + let bytes = [1u8, 2, 3]; + let mut s = Stream { + root: Sub(0, 77), + ms: Sub(25, D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: 3 }), + blend: Sub(8, D3D12_BLEND_DESC::default()), + mask: Sub(9, 5), + raster: Sub(10, D3D12_RASTERIZER_DESC { DepthBias: 6, ..Default::default() }), + depth: Sub(11, D3D12_DEPTH_STENCIL_DESC::default()), + targets: Sub(15, D3D12_RT_FORMAT_ARRAY { NumRenderTargets: 3, ..Default::default() }), + dsv: Sub(16, DXGI_FORMAT(40)), + samples: Sub(17, DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }), + unknown: Sub(99, 0), + }; + let d = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: size_of::(), pPipelineStateSubobjectStream: (&raw mut s).cast() }; + let mut kept = Kept::default(); + // SAFETY: the stream above. + let parts = unsafe { stream(&d, &mut kept) }; + assert_eq!(kept.codes, [vec![1, 2, 3]]); + assert_eq!(kept.lost.len(), 1, "the unknown subobject is reported"); + assert_eq!(parts.len(), 9); + assert_eq!(parts[0], Part::Root { root: 77 }); + assert_eq!(parts[1], Part::Code { kind: 25, blob: 0 }); + assert_eq!(parts[3], Part::Plain { kind: 9, data: Blob(5u32.to_le_bytes().to_vec()) }); + let Part::Plain { kind: 10, data } = &parts[4] else { panic!("{:?}", parts[4]) }; + assert_eq!(data.0.len(), size_of::()); + assert_eq!(parts[7], Part::Plain { kind: 16, data: Blob(40u32.to_le_bytes().to_vec()) }); + } +} diff --git a/crates/victory-gpu/src/replay/record.rs b/crates/victory-gpu/src/replay/record.rs new file mode 100644 index 0000000..ea9b6d9 --- /dev/null +++ b/crates/victory-gpu/src/replay/record.rs @@ -0,0 +1,2079 @@ +//! The recorder: what the host layer makes and records with D3D12, seen at +//! the D3D12 boundary (`super::hook`), and one frame of it written down +//! (`super::snap`). On with `VICTORY_RECORD=` only; without it +//! nothing is hooked. +//! +//! From the device's creation on it keeps what objects were made from and +//! what each descriptor slot holds, and follows the states of textures. +//! Lists are recorded only while it is armed: a few frames ahead of the one +//! captured, since the title records lists before they run. + +use std::cell::Cell; +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, RwLock}; + +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; +use windows::core::{BOOL, GUID, HRESULT, IUnknown, Interface, PCWSTR}; + +use super::hook::{self, method, noted_entry, orig}; +use super::states::{self, Change, States}; +use super::wire::{self, ALL, Barrier, Cmd, Loc, NONE, Part, Place, Slot, Va, Wire, slot}; +use super::{gpu, pso, snap}; + +type Ptr = *mut c_void; +type Out = *mut *mut c_void; + +/// What to record. +#[derive(Clone, Debug)] +pub struct Settings { + /// Captures go to `capture-` in it. + pub folder: PathBuf, + pub at: At, + /// Frames to capture. + pub frames: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum At { + /// Seconds after the device was made. + Seconds(f64), + /// A number of presents. + Frame(u64), + /// When a file named `go` appears in the folder (this works in the + /// other cases too). + Trigger, +} + +impl Settings { + /// From `VICTORY_RECORD`, `VICTORY_RECORD_AT` (seconds, or `f`) + /// and `VICTORY_RECORD_FRAMES`. + pub fn from_env() -> Option { + let folder = PathBuf::from(std::env::var_os("VICTORY_RECORD").filter(|v| !v.is_empty())?); + let at = parse_at(&std::env::var("VICTORY_RECORD_AT").unwrap_or_default()); + let frames = std::env::var("VICTORY_RECORD_FRAMES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1); + Some(Settings { folder, at, frames: std::cmp::max(frames, 1) }) + } +} + +fn parse_at(text: &str) -> At { + let text = text.trim(); + if let Some(frame) = text.strip_prefix('f').and_then(|n| n.parse().ok()) { + return At::Frame(frame); + } + match text.parse::() { + Ok(s) => At::Seconds(s), + Err(_) => At::Trigger, + } +} + +pub(super) fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +pub(super) fn read(m: &RwLock) -> std::sync::RwLockReadGuard<'_, T> { + m.read().unwrap_or_else(|e| e.into_inner()) +} + +fn write(m: &RwLock) -> std::sync::RwLockWriteGuard<'_, T> { + m.write().unwrap_or_else(|e| e.into_inner()) +} + +/// A resource that lives. +pub(super) struct Res { + pub(super) id: u32, + pub(super) ptr: usize, + pub(super) place: Place, + pub(super) desc: wire::Desc, + pub(super) made_in: i32, + pub(super) clear: Option<[u32; 5]>, + pub(super) subs: u32, + pub(super) seen: gpu::Seen, + /// Made while a frame was being captured. + pub(super) late: bool, +} + +impl Res { + pub(super) fn is_buffer(&self) -> bool { + self.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 + } + + /// The object, without a reference of its own. + pub(super) fn object(&self) -> ManuallyDrop { + borrow(self.ptr as Ptr) + } +} + +/// A COM object named by its address, without a reference. +pub(super) fn borrow(p: Ptr) -> ManuallyDrop { + // SAFETY: the caller's live object; never released here. + ManuallyDrop::new(unsafe { T::from_raw(p) }) +} + +/// A descriptor heap: where it lies and what its slots hold. +pub(super) struct Heap { + pub(super) id: u32, + pub(super) kind: i32, + pub(super) count: u32, + pub(super) flags: i32, + cpu: usize, + gpu: u64, + step: usize, + slots: *mut Slot, +} + +// SAFETY: slots are written by the thread that writes the descriptor (the +// same rule as the descriptors': one writer at a time) and read as plain +// data. +unsafe impl Send for Heap {} +// SAFETY: as above. +unsafe impl Sync for Heap {} + +impl Heap { + fn new(id: u32, desc: &D3D12_DESCRIPTOR_HEAP_DESC, cpu: usize, gpu: u64, step: usize) -> Heap { + let layout = Self::layout(desc.NumDescriptors); + // SAFETY: a layout of at least one slot; a zeroed slot is an empty + // one. + let slots = unsafe { std::alloc::alloc_zeroed(layout) }.cast::(); + if slots.is_null() { + std::alloc::handle_alloc_error(layout); + } + Heap { id, kind: desc.Type.0, count: desc.NumDescriptors, flags: desc.Flags.0, cpu, gpu, step, slots } + } + + fn layout(count: u32) -> std::alloc::Layout { + std::alloc::Layout::array::(count.max(1) as usize).unwrap_or(std::alloc::Layout::new::()) + } + + pub(super) fn visible(&self) -> bool { + self.flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 != 0 + } + + pub(super) fn get(&self, i: u32) -> Slot { + if i >= self.count { + return Slot::EMPTY; + } + // SAFETY: a slot of ours. + unsafe { self.slots.add(i as usize).read_volatile() } + } + + fn set(&self, i: u32, s: &Slot) { + if i < self.count { + // SAFETY: a slot of ours. + unsafe { self.slots.add(i as usize).write_volatile(*s) }; + } + } + + /// All slots, as they are now. + pub(super) fn all(&self) -> Vec { + let mut out = Vec::with_capacity(self.count as usize); + // SAFETY: `count` slots of ours. + unsafe { + std::ptr::copy_nonoverlapping(self.slots, out.as_mut_ptr(), self.count as usize); + out.set_len(self.count as usize); + } + out + } +} + +impl Drop for Heap { + fn drop(&mut self) { + // SAFETY: as allocated. + unsafe { std::alloc::dealloc(self.slots.cast(), Self::layout(self.count)) }; + } +} + +#[derive(Default)] +pub(super) struct Heaps { + by_cpu: BTreeMap>, + by_gpu: BTreeMap>, +} + +impl Heaps { + fn add(&mut self, heap: Arc) { + let end = heap.cpu + heap.count as usize * heap.step; + let gone: Vec = + self.by_cpu.range(..end).rev().take_while(|(_, h)| h.cpu + h.count as usize * h.step > heap.cpu).map(|(&k, _)| k).collect(); + for k in gone { + self.by_cpu.remove(&k); + } + if heap.visible() { + self.by_gpu.insert(heap.gpu, heap.clone()); + } + self.by_cpu.insert(heap.cpu, heap); + } + + fn remove(&mut self, id: u32) { + self.by_cpu.retain(|_, h| h.id != id); + self.by_gpu.retain(|_, h| h.id != id); + } + + fn cpu(&self, at: usize) -> Option<(&Arc, u32)> { + let (_, h) = self.by_cpu.range(..=at).next_back()?; + let i = (at - h.cpu) / h.step; + (i < h.count as usize).then_some((h, i as u32)) + } + + fn gpu(&self, at: u64) -> Option<(&Arc, u32)> { + let (_, h) = self.by_gpu.range(..=at).next_back()?; + let i = (at - h.gpu) / h.step as u64; + (i < u64::from(h.count)).then_some((h, i as u32)) + } + + pub(super) fn visible(&self) -> impl Iterator> { + self.by_gpu.values() + } +} + +/// A command list's recording. +pub(super) struct ListState { + pub(super) kind: i32, + inner: Mutex, +} + +#[derive(Default)] +struct ListInner { + /// Recorded from its reset on. + whole: bool, + bytes: Vec, + changes: Vec, + closed: Option<(Option>>, Arc>)>, +} + +impl ListState { + fn push(&self, cmd: &Cmd) { + let mut inner = lock(&self.inner); + if inner.whole { + cmd.put(&mut inner.bytes); + } + } + + /// The recording closed last: its commands if it was recorded whole, + /// and the states it changes. None if it was not seen closed since its + /// reset. + pub(super) fn closed(&self) -> Option<(Option>>, Arc>)> { + lock(&self.inner).closed.clone() + } +} + +struct QueueState { + kind: i32, +} + +/// Shader code, written to `shaders.bin` as it is met, once each. +pub(super) struct Codes { + file: Option, + at: u64, + index: HashMap<[u8; 32], u32>, + pub(super) all: Vec, +} + +/// Objects by their address: ids. +#[derive(Default)] +struct Ids([RwLock>; 32]); + +impl Ids { + fn shard(&self, p: usize) -> &RwLock> { + &self.0[(p >> 5 ^ p >> 12) % 32] + } + fn get(&self, p: usize) -> Option { + read(self.shard(p)).get(&p).copied() + } + fn set(&self, p: usize, id: u32) { + write(self.shard(p)).insert(p, id); + } + fn remove(&self, p: usize, id: u32) { + let mut map = write(self.shard(p)); + if map.get(&p) == Some(&id) { + map.remove(&p); + } + } +} + +pub(super) struct Recorder { + pub(super) settings: Settings, + /// Where this process' capture goes. + pub(super) folder: PathBuf, + pub(super) began: std::time::Instant, + next: AtomicU32, + ids: Ids, + pub(super) resources: RwLock>>, + /// Buffers by their GPU address: size and id. + addresses: RwLock>, + pub(super) descriptors: RwLock, + lists: RwLock>>, + pub(super) heaps: Mutex>, + pub(super) roots: Mutex>>>, + pub(super) pipelines: Mutex>>>, + pub(super) signatures: Mutex>, + pub(super) queries: Mutex>, + pub(super) names: Mutex>, + pub(super) codes: Mutex, + pub(super) states: Mutex, + pub(super) queues: Mutex>, + device: Mutex>, + /// Lists are recorded. + armed: AtomicBool, + /// A frame is being captured: descriptor writes are noted, resources + /// made are kept alive. + pub(super) watching: AtomicBool, + pub(super) writes: Mutex>, + pub(super) held: Mutex>, + /// What could not be recorded, with how often. + problems: Mutex>, + /// Submissions and presents, one at a time. + pub(super) submits: Mutex, +} + +static RECORDER: OnceLock = OnceLock::new(); + +/// The recorder, if it is on. +pub(super) fn recorder() -> Option<&'static Recorder> { + RECORDER.get() +} + +/// Whether the recorder is on. +pub fn on() -> bool { + RECORDER.get().is_some() +} + +thread_local! { + static OURS: Cell = const { Cell::new(0) }; +} + +/// While it lives, this thread's D3D12 calls are our own: not recorded. +pub(super) struct Ours; + +impl Ours { + pub(super) fn new() -> Ours { + OURS.with(|o| o.set(o.get() + 1)); + Ours + } +} + +impl Drop for Ours { + fn drop(&mut self) { + OURS.with(|o| o.set(o.get() - 1)); + } +} + +fn ours() -> bool { + OURS.with(|o| o.get() > 0) +} + +impl Recorder { + fn new(settings: Settings) -> std::io::Result { + std::fs::create_dir_all(&settings.folder)?; + let mut n = 1; + let folder = loop { + let folder = settings.folder.join(format!("capture-{n}")); + match std::fs::create_dir(&folder) { + Ok(()) => break folder, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1, + Err(e) => return Err(e), + } + }; + let file = std::fs::File::create(folder.join("shaders.bin"))?; + Ok(Recorder { + settings, + folder, + began: std::time::Instant::now(), + next: AtomicU32::new(1), + ids: Ids::default(), + resources: RwLock::default(), + addresses: RwLock::default(), + descriptors: RwLock::default(), + lists: RwLock::default(), + heaps: Mutex::default(), + roots: Mutex::default(), + pipelines: Mutex::default(), + signatures: Mutex::default(), + queries: Mutex::default(), + names: Mutex::default(), + codes: Mutex::new(Codes { file: Some(file), at: 0, index: HashMap::new(), all: Vec::new() }), + states: Mutex::default(), + queues: Mutex::default(), + device: Mutex::default(), + armed: AtomicBool::new(false), + watching: AtomicBool::new(false), + writes: Mutex::default(), + held: Mutex::default(), + problems: Mutex::default(), + submits: Mutex::new(snap::Phase::default()), + }) + } + + fn id(&self) -> u32 { + self.next.fetch_add(1, Ordering::Relaxed) + } + + /// Notes something that is not in the capture. + pub(super) fn problem(&self, what: &str) { + self.problem_times(what, 1); + } + + pub(super) fn problem_times(&self, what: &str, n: u64) { + let mut problems = lock(&self.problems); + let seen = problems.entry(what.to_owned()).or_insert(0); + if *seen == 0 { + tracing::warn!("frame recorder: {what}"); + } + *seen += n; + } + + /// The problems so far. + pub(super) fn problems(&self) -> Vec { + lock(&self.problems).iter().map(|(what, n)| if *n == 1 { what.clone() } else { format!("{what} ({n} times)") }).collect() + } + + pub(super) fn arm(&self, on: bool) { + self.armed.store(on, Ordering::SeqCst); + } + + pub(super) fn device(&self) -> Option { + lock(&self.device).clone() + } + + /// The state of a list, if its methods are still ours. + pub(super) fn list(&self, p: Ptr) -> Option> { + let state = read(&self.lists).get(&(p as usize)).cloned()?; + // SAFETY: a live list: it is being submitted. + if !unsafe { hook::ours(p) } { + self.problem("a list lost its hooks"); + return None; + } + Some(state) + } + + /// The buffer an address lies in. + pub(super) fn va(&self, address: u64) -> Va { + if address == 0 { + return Va::Null {}; + } + match read(&self.addresses).range(..=address).next_back() { + Some((&start, &(size, res))) if address - start < size => Va::At { res, offset: address - start }, + _ => Va::Unknown { address }, + } + } + + /// The id of an object, [`NONE`] for null; an unknown one is a problem. + fn object(&self, p: Ptr, what: &str) -> u32 { + if p.is_null() { + return NONE; + } + self.ids.get(p as usize).unwrap_or_else(|| { + self.problem(&format!("{what} was used that was not seen made")); + NONE + }) + } + + /// The id of a resource; one not seen made (a swap chain's buffer) is + /// taken in now. + pub(super) fn resource(&self, p: Ptr) -> u32 { + if p.is_null() { + return NONE; + } + if let Some(id) = self.ids.get(p as usize) { + return id; + } + self.add(p, Place::BackBuffer {}, 0, None) + } + + /// Takes a new resource in. + fn add(&self, p: Ptr, place: Place, made_in: i32, clear: Option<[u32; 5]>) -> u32 { + let object = borrow::(p); + // SAFETY: a live resource. + let d = unsafe { object.GetDesc() }; + let desc = gpu::from_desc(&d); + let id = self.id(); + let seen = match &place { + Place::Committed { props, .. } => gpu::seen(props), + Place::Placed { heap, .. } => lock(&self.heaps).get(heap).map_or(gpu::Seen::No, |h| gpu::seen(&h.props)), + Place::BackBuffer {} => gpu::Seen::No, + }; + let subs = gpu::subresources(&desc); + let is_buffer = desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; + // SAFETY: a live buffer. + let va = if is_buffer { unsafe { object.GetGPUVirtualAddress() } } else { 0 }; + let placed = matches!(place, Place::Placed { .. }); + let late = self.watching.load(Ordering::SeqCst); + { + let mut states = lock(&self.states); + if !is_buffer { + let decays = d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0; + states.add(id, subs, made_in as u32, decays); + } + if placed { + states.in_use(id); + } + } + if va != 0 { + write(&self.addresses).insert(va, (desc.width, id)); + } + let res = Arc::new(Res { id, ptr: p as usize, place, desc, made_in, clear, subs, seen, late }); + write(&self.resources).insert(id, res); + self.ids.set(p as usize, id); + if late { + lock(&self.held).push(ID3D12Resource::clone(&object)); + } + self.tell_gone(&*object, Gone::Resource { id, ptr: p as usize, va }); + id + } + + fn gone(&self, what: &Gone) { + match *what { + Gone::Resource { id, ptr, va } => { + self.ids.remove(ptr, id); + write(&self.resources).remove(&id); + if va != 0 { + let mut all = write(&self.addresses); + if all.get(&va).is_some_and(|&(_, i)| i == id) { + all.remove(&va); + } + } + lock(&self.states).remove(id); + lock(&self.names).remove(&id); + } + Gone::List { ptr } => { + write(&self.lists).remove(&ptr); + } + Gone::Heap { id, ptr } => { + self.ids.remove(ptr, id); + write(&self.descriptors).remove(id); + } + } + } + + /// Has us told when an object dies. + fn tell_gone(&self, object: &impl Interface, what: Gone) { + const KEY: GUID = GUID::from_u128(0x3d0d5c1e_7a1b_4a53_9a3e_5f2b1e6b9c41); + let notice = Box::into_raw(Box::new(Notice { methods: &NOTICE, references: AtomicU32::new(1), what })); + // SAFETY: a COM object of ours with one reference, which this drops + // at the end; the object takes its own. + unsafe { + let notice = IUnknown::from_raw(notice.cast()); + let set = object.cast::().and_then(|o| o.SetPrivateDataInterface(&KEY, ¬ice)); + if set.is_err() { + self.problem("an object's end cannot be followed"); + std::mem::forget(notice); + } + } + } + + fn view(&self, at: usize) -> Slot { + match read(&self.descriptors).cpu(at) { + Some((h, i)) => h.get(i), + None => { + self.problem("a descriptor handle in no heap seen made"); + Slot::EMPTY + } + } + } + + fn set_view(&self, at: usize, s: &Slot) { + let all = read(&self.descriptors); + let Some((h, i)) = all.cpu(at) else { + drop(all); + self.problem("a view was made in no descriptor heap seen made"); + return; + }; + h.set(i, s); + self.wrote(h, i, 1); + } + + /// After slots were written: noted if a frame is being captured. + fn wrote(&self, h: &Heap, first: u32, n: u32) { + if h.visible() && self.watching.load(Ordering::SeqCst) { + lock(&self.writes).push((h.id, first, n)); + } + } + + fn copy_views(&self, to: usize, from: usize, n: u32) { + let all = read(&self.descriptors); + let (Some((a, i)), Some((b, j))) = (all.cpu(to), all.cpu(from)) else { + drop(all); + self.problem("descriptors were copied in no heap seen made"); + return; + }; + for k in 0..n { + a.set(i + k, &b.get(j + k)); + } + self.wrote(a, i, n); + } + + fn code(&self, bytes: &[u8]) -> u32 { + use std::io::Write; + let hash = *blake3::hash(bytes).as_bytes(); + let mut codes = lock(&self.codes); + if let Some(&i) = codes.index.get(&hash) { + return i; + } + let i = codes.all.len() as u32; + let at = codes.at; + let wrote = codes.file.as_mut().is_some_and(|f| f.write_all(bytes).is_ok()); + if !wrote { + drop(codes); + self.problem("shader code could not be written"); + return u32::MAX; + } + codes.at += bytes.len() as u64; + codes.all.push(wire::Code { at, len: bytes.len() as u64, hash }); + codes.index.insert(hash, i); + i + } + + fn pipeline(&self, p: Ptr, parts: Vec) { + let id = self.id(); + lock(&self.pipelines).insert(id, Arc::new(parts)); + self.ids.set(p as usize, id); + } + + /// `name` is an object's, for reports. + fn name(&self, p: Ptr, name: &str) { + if let Some(id) = self.ids.get(p as usize) { + lock(&self.names).insert(id, name.to_owned()); + } + } +} + +struct Keeper<'a>(&'a Recorder); + +impl pso::Keep for Keeper<'_> { + fn root(&mut self, root: Ptr) -> u32 { + self.0.object(root, "a root signature") + } + fn code(&mut self, code: &[u8]) -> u32 { + self.0.code(code) + } + fn lost(&mut self, what: &str) { + self.0.problem(what); + } +} + +/// Which object died. +enum Gone { + Resource { id: u32, ptr: usize, va: u64 }, + List { ptr: usize }, + Heap { id: u32, ptr: usize }, +} + +/// A COM object an object of D3D12's holds and lets go of when it dies. +#[repr(C)] +struct Notice { + methods: *const NoticeTable, + references: AtomicU32, + what: Gone, +} + +#[repr(C)] +struct NoticeTable { + query: unsafe extern "system" fn(Ptr, *const GUID, Out) -> HRESULT, + add: unsafe extern "system" fn(Ptr) -> u32, + release: unsafe extern "system" fn(Ptr) -> u32, +} +static NOTICE: NoticeTable = NoticeTable { query: notice_query, add: notice_add, release: notice_release }; + +unsafe extern "system" fn notice_query(this: Ptr, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: COM's rules: a valid id and place for the answer. + unsafe { + if *iid == IUnknown::IID { + notice_add(this); + *out = this; + return HRESULT(0); + } + *out = std::ptr::null_mut(); + } + HRESULT(0x8000_4002_u32 as i32) +} + +unsafe extern "system" fn notice_add(this: Ptr) -> u32 { + // SAFETY: one of ours, alive while a reference is. + unsafe { (*this.cast::()).references.fetch_add(1, Ordering::Relaxed) + 1 } +} + +unsafe extern "system" fn notice_release(this: Ptr) -> u32 { + // SAFETY: as above; the last reference frees the box it was made as. + unsafe { + let left = (*this.cast::()).references.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { + let notice = Box::from_raw(this.cast::()); + if let Some(r) = recorder() { + r.gone(¬ice.what); + } + } + left + } +} + +/// Starts the recorder if the environment asks for it, and hooks `device`. +/// Called right after the device was made. +pub(crate) fn from_env(device: &ID3D12Device) { + let Some(settings) = Settings::from_env() else { + return; + }; + match start(settings, device) { + Ok(folder) => tracing::info!(folder = %folder.display(), "frame recorder on"), + Err(e) => tracing::warn!(error = %e, "frame recorder not started"), + } +} + +/// Starts the recorder (once a process) and hooks `device`, which must have +/// made nothing the frame will use. Where the capture will be. +pub fn start(settings: Settings, device: &ID3D12Device) -> std::io::Result { + let r = Recorder::new(settings)?; + let folder = r.folder.clone(); + if RECORDER.set(r).is_err() { + return Err(std::io::Error::other("the recorder is already on")); + } + let r = recorder().ok_or_else(|| std::io::Error::other("no recorder"))?; + *lock(&r.device) = Some(device.clone()); + // The newer interfaces may be other pointers (they are the same one + // without the debug layer). + let mut all = vec![device.as_raw()]; + let mut more: Vec = Vec::new(); + for iid in [ + ID3D12Device1::IID, + ID3D12Device2::IID, + ID3D12Device3::IID, + ID3D12Device4::IID, + ID3D12Device5::IID, + ID3D12Device8::IID, + ID3D12Device10::IID, + ID3D12Device11::IID, + ID3D12Device13::IID, + ] { + if let Some(p) = query(device.as_raw(), &iid) { + all.push(p.as_raw()); + more.push(p); + } + } + for p in all { + // SAFETY: a live device; the entries below are of their methods' + // types (the compiler checks them). + unsafe { hook::install(p, std::ptr::null(), device_table) }; + } + Ok(folder) +} + +/// Unhooks `device` (tests). +pub fn unhook(device: &ID3D12Device) { + // SAFETY: a live device, used by no other thread (the caller's word). + unsafe { hook::remove(device.as_raw()) }; +} + +/// The object's interface `iid`. +fn query(p: Ptr, iid: &GUID) -> Option { + let object = borrow::(p); + let mut out = std::ptr::null_mut(); + // SAFETY: a live COM object. + unsafe { + object.query(iid, &mut out).ok().ok()?; + (!out.is_null()).then(|| IUnknown::from_raw(out)) + } +} + +/// Names an object for reports. +pub fn name(object: &impl Interface, text: &str) { + if let Some(r) = recorder() { + r.name(object.as_raw(), text); + } +} + +/// At the end of a frame, before the swap chain's present: `texture`, in +/// `state`, is shown. +pub fn present(texture: &ID3D12Resource, state: D3D12_RESOURCE_STATES) { + if let Some(r) = recorder() { + snap::present(r, texture, state.0 as u32); + } +} + +/// Where the capture is, once it is done. +pub fn finished() -> Option { + let r = recorder()?; + lock(&r.submits).done().then(|| r.folder.clone()) +} + +/// Sets a method of a table to a function of its type. +macro_rules! set { + ($t:ident, $vtbl:ident . $name:ident = $f:expr) => {{ + // The compiler checks the function's type here. + let _ = |v: &mut $vtbl| v.$name = $f; + $t[method!($vtbl.$name)] = $f as *const () as usize; + }}; +} + +/// The object's own method. +macro_rules! own { + ($this:ident, $vtbl:ident . $name:ident) => { + orig::<$vtbl>($this).$name + }; +} + +/// Entries for methods that are not recorded: counted, and named in the +/// capture's notes if they were called. +macro_rules! not_recorded { + ($t:ident, $class:ident, $names:ident: $($vtbl:ident . $name:ident),* $(,)?) => { + const $names: &[(usize, &str)] = &[$((method!($vtbl.$name), stringify!($name))),*]; + $($t[method!($vtbl.$name)] = noted_entry::<{ hook::$class * hook::SLOTS + method!($vtbl.$name) }>();)* + }; +} + +fn device_table(t: &mut [usize; hook::SLOTS]) { + set!(t, ID3D12Device_Vtbl.CreateCommandQueue = create_queue); + set!(t, ID3D12Device_Vtbl.CreateGraphicsPipelineState = create_graphics); + set!(t, ID3D12Device_Vtbl.CreateComputePipelineState = create_compute); + set!(t, ID3D12Device_Vtbl.CreateCommandList = create_list); + set!(t, ID3D12Device_Vtbl.CreateDescriptorHeap = create_descriptors); + set!(t, ID3D12Device_Vtbl.CreateRootSignature = create_root); + set!(t, ID3D12Device_Vtbl.CreateConstantBufferView = create_cbv); + set!(t, ID3D12Device_Vtbl.CreateShaderResourceView = create_srv); + set!(t, ID3D12Device_Vtbl.CreateUnorderedAccessView = create_uav); + set!(t, ID3D12Device_Vtbl.CreateRenderTargetView = create_rtv); + set!(t, ID3D12Device_Vtbl.CreateDepthStencilView = create_dsv); + set!(t, ID3D12Device_Vtbl.CreateSampler = create_sampler); + set!(t, ID3D12Device_Vtbl.CopyDescriptors = copy_descriptors); + set!(t, ID3D12Device_Vtbl.CopyDescriptorsSimple = copy_descriptors_simple); + set!(t, ID3D12Device_Vtbl.CreateCommittedResource = create_committed); + set!(t, ID3D12Device_Vtbl.CreateHeap = create_heap); + set!(t, ID3D12Device_Vtbl.CreatePlacedResource = create_placed); + set!(t, ID3D12Device_Vtbl.CreateQueryHeap = create_queries); + set!(t, ID3D12Device_Vtbl.CreateCommandSignature = create_signature); + set!(t, ID3D12Device1_Vtbl.CreatePipelineLibrary = create_library); + set!(t, ID3D12Device2_Vtbl.CreatePipelineState = create_stream); + let _ = device_rest(t); +} + +fn device_rest(t: &mut [usize; hook::SLOTS]) -> &'static [(usize, &'static str)] { + not_recorded!(t, DEVICE, NAMES: + ID3D12Device_Vtbl.CreateReservedResource, + ID3D12Device_Vtbl.OpenSharedHandle, + ID3D12Device4_Vtbl.CreateCommandList1, + ID3D12Device4_Vtbl.CreateCommittedResource1, + ID3D12Device4_Vtbl.CreateHeap1, + ID3D12Device4_Vtbl.CreateReservedResource1, + ID3D12Device5_Vtbl.CreateStateObject, + ID3D12Device8_Vtbl.CreateCommittedResource2, + ID3D12Device8_Vtbl.CreatePlacedResource1, + ID3D12Device8_Vtbl.CreateSamplerFeedbackUnorderedAccessView, + ID3D12Device10_Vtbl.CreateCommittedResource3, + ID3D12Device10_Vtbl.CreatePlacedResource2, + ID3D12Device10_Vtbl.CreateReservedResource2, + ID3D12Device11_Vtbl.CreateSampler2, + ); + NAMES +} + +fn queue_table(t: &mut [usize; hook::SLOTS]) { + set!(t, ID3D12CommandQueue_Vtbl.ExecuteCommandLists = execute); + let _ = queue_rest(t); +} + +fn queue_rest(t: &mut [usize; hook::SLOTS]) -> &'static [(usize, &'static str)] { + not_recorded!(t, QUEUE, NAMES: + ID3D12CommandQueue_Vtbl.UpdateTileMappings, + ID3D12CommandQueue_Vtbl.CopyTileMappings, + ID3D12CommandQueue_Vtbl.Wait, + ); + NAMES +} + +fn library_table(t: &mut [usize; hook::SLOTS]) { + set!(t, ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline = load_graphics); + set!(t, ID3D12PipelineLibrary_Vtbl.LoadComputePipeline = load_compute); + set!(t, ID3D12PipelineLibrary1_Vtbl.LoadPipeline = load_stream); +} + +fn list_table(t: &mut [usize; hook::SLOTS]) { + set!(t, ID3D12GraphicsCommandList_Vtbl.Close = list_close); + set!(t, ID3D12GraphicsCommandList_Vtbl.Reset = list_reset); + set!(t, ID3D12GraphicsCommandList_Vtbl.DrawInstanced = draw); + set!(t, ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced = draw_indexed); + set!(t, ID3D12GraphicsCommandList_Vtbl.Dispatch = dispatch); + set!(t, ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion = copy_buffer); + set!(t, ID3D12GraphicsCommandList_Vtbl.CopyTextureRegion = copy_texture); + set!(t, ID3D12GraphicsCommandList_Vtbl.CopyResource = copy_resource); + set!(t, ID3D12GraphicsCommandList_Vtbl.ResolveSubresource = resolve); + set!(t, ID3D12GraphicsCommandList_Vtbl.IASetPrimitiveTopology = topology); + set!(t, ID3D12GraphicsCommandList_Vtbl.RSSetViewports = viewports); + set!(t, ID3D12GraphicsCommandList_Vtbl.RSSetScissorRects = scissors); + set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor = blend_factor); + set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetStencilRef = stencil_ref); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetPipelineState = set_pipeline); + set!(t, ID3D12GraphicsCommandList_Vtbl.ResourceBarrier = barrier); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps = set_heaps); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature = root_compute); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature = root_graphics); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable = table_compute); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable = table_graphics); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant = constant_compute); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant = constant_graphics); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants = constants_compute); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants = constants_graphics); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootConstantBufferView = cbv_compute); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootConstantBufferView = cbv_graphics); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootShaderResourceView = srv_compute); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootShaderResourceView = srv_graphics); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootUnorderedAccessView = uav_compute); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootUnorderedAccessView = uav_graphics); + set!(t, ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer = index_buffer); + set!(t, ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers = vertex_buffers); + set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets = targets); + set!(t, ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView = clear_depth); + set!(t, ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView = clear_target); + set!(t, ID3D12GraphicsCommandList_Vtbl.DiscardResource = discard); + set!(t, ID3D12GraphicsCommandList_Vtbl.BeginQuery = begin_query); + set!(t, ID3D12GraphicsCommandList_Vtbl.EndQuery = end_query); + set!(t, ID3D12GraphicsCommandList_Vtbl.ResolveQueryData = resolve_query); + set!(t, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect = indirect); + set!(t, ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion = resolve_region); + set!(t, ID3D12GraphicsCommandList1_Vtbl.OMSetDepthBounds = depth_bounds); + set!(t, ID3D12GraphicsCommandList2_Vtbl.WriteBufferImmediate = write_immediate); + set!(t, ID3D12GraphicsCommandList6_Vtbl.DispatchMesh = dispatch_mesh); + let _ = list_rest(t); +} + +fn list_rest(t: &mut [usize; hook::SLOTS]) -> &'static [(usize, &'static str)] { + not_recorded!(t, LIST, NAMES: + ID3D12GraphicsCommandList_Vtbl.ClearState, + ID3D12GraphicsCommandList_Vtbl.CopyTiles, + ID3D12GraphicsCommandList_Vtbl.ExecuteBundle, + ID3D12GraphicsCommandList_Vtbl.SOSetTargets, + ID3D12GraphicsCommandList_Vtbl.ClearUnorderedAccessViewUint, + ID3D12GraphicsCommandList_Vtbl.ClearUnorderedAccessViewFloat, + ID3D12GraphicsCommandList_Vtbl.SetPredication, + ID3D12GraphicsCommandList1_Vtbl.AtomicCopyBufferUINT, + ID3D12GraphicsCommandList1_Vtbl.AtomicCopyBufferUINT64, + ID3D12GraphicsCommandList1_Vtbl.SetSamplePositions, + ID3D12GraphicsCommandList1_Vtbl.SetViewInstanceMask, + ID3D12GraphicsCommandList3_Vtbl.SetProtectedResourceSession, + ID3D12GraphicsCommandList4_Vtbl.BeginRenderPass, + ID3D12GraphicsCommandList4_Vtbl.EndRenderPass, + ID3D12GraphicsCommandList4_Vtbl.InitializeMetaCommand, + ID3D12GraphicsCommandList4_Vtbl.ExecuteMetaCommand, + ID3D12GraphicsCommandList4_Vtbl.BuildRaytracingAccelerationStructure, + ID3D12GraphicsCommandList4_Vtbl.EmitRaytracingAccelerationStructurePostbuildInfo, + ID3D12GraphicsCommandList4_Vtbl.CopyRaytracingAccelerationStructure, + ID3D12GraphicsCommandList4_Vtbl.SetPipelineState1, + ID3D12GraphicsCommandList4_Vtbl.DispatchRays, + ID3D12GraphicsCommandList5_Vtbl.RSSetShadingRate, + ID3D12GraphicsCommandList5_Vtbl.RSSetShadingRateImage, + ID3D12GraphicsCommandList7_Vtbl.Barrier, + ID3D12GraphicsCommandList8_Vtbl.OMSetFrontAndBackStencilRef, + ID3D12GraphicsCommandList9_Vtbl.RSSetDepthBias, + ID3D12GraphicsCommandList9_Vtbl.IASetIndexBufferStripCutValue, + ID3D12GraphicsCommandList10_Vtbl.SetProgram, + ID3D12GraphicsCommandList10_Vtbl.DispatchGraph, + ); + NAMES +} + +/// How often each method that is not recorded was called so far. +pub(super) fn not_recorded_calls() -> Vec<(String, u64)> { + let mut t = [0; hook::SLOTS]; + let mut all = Vec::new(); + for (class, of, names) in [ + (hook::LIST, "command list", list_rest(&mut t)), + (hook::DEVICE, "device", device_rest(&mut t)), + (hook::QUEUE, "queue", queue_rest(&mut t)), + ] { + for &(slot, name) in names { + let what = match (class, name) { + // Submissions are in order anyway: the replay has one queue. + (hook::QUEUE, "Wait") => "waits of the drawing queue (the swap chain makes some) are not replayed".to_owned(), + _ => format!("{of} method {name} is not recorded, and was called"), + }; + all.push((what, hook::count(class, slot))); + } + } + all +} + +/// The recorder, for a call that is the host layer's and not our own, which +/// succeeded. +fn made(hr: HRESULT, out: Out) -> Option<(&'static Recorder, Ptr)> { + if hr.is_err() || out.is_null() || ours() { + return None; + } + // SAFETY: the call's answer. + let p = unsafe { *out }; + (!p.is_null()).then_some(())?; + Some((recorder()?, p)) +} + +unsafe extern "system" fn create_queue(this: Ptr, desc: *const D3D12_COMMAND_QUEUE_DESC, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: the caller's arguments, passed on; then a new queue no other + // thread knows. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateCommandQueue)(this, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + let kind = (*desc).Type.0; + let state = Box::leak(Box::new(QueueState { kind })); + hook::install(p, (&raw const *state).cast(), queue_table); + lock(&r.queues).push((ID3D12CommandQueue::clone(&borrow(p)), kind)); + } + hr + } +} + +unsafe extern "system" fn create_list( + this: Ptr, + nodes: u32, + kind: D3D12_COMMAND_LIST_TYPE, + allocator: Ptr, + pso: Ptr, + iid: *const GUID, + out: Out, +) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateCommandList)(this, nodes, kind, allocator, pso, iid, out); + if let Some((r, p)) = made(hr, out) { + let state = Arc::new(ListState { kind: kind.0, inner: Mutex::default() }); + // Every interface of it we hook, and the one it is submitted as. + static ONE: OnceLock = OnceLock::new(); + let iids = [ + ID3D12CommandList::IID, + ID3D12GraphicsCommandList1::IID, + ID3D12GraphicsCommandList2::IID, + ID3D12GraphicsCommandList4::IID, + ID3D12GraphicsCommandList6::IID, + ]; + let same = *ONE.get_or_init(|| iids.iter().all(|iid| query(p, iid).is_none_or(|q| q.as_raw() == p))); + let mut all = vec![p]; + if !same { + all.extend(iids.iter().filter_map(|iid| query(p, iid)).map(|q| q.as_raw())); + } + { + let mut inner = lock(&state.inner); + inner.whole = r.armed.load(Ordering::SeqCst) && kind == D3D12_COMMAND_LIST_TYPE_DIRECT; + begin(&mut inner, r, pso); + } + for q in all { + // The state's address is kept for good, as the table is. + hook::install(q, Arc::into_raw(state.clone()).cast(), list_table); + write(&r.lists).insert(q as usize, state.clone()); + r.tell_gone(&*borrow::(q), Gone::List { ptr: q as usize }); + } + } + hr + } +} + +/// A list is open again, with pipeline `pso`. +fn begin(inner: &mut ListInner, r: &Recorder, pso: Ptr) { + inner.bytes = Vec::new(); + inner.changes.clear(); + if inner.whole && !pso.is_null() { + Cmd::Pipeline { pso: r.object(pso, "a pipeline") }.put(&mut inner.bytes); + } +} + +unsafe extern "system" fn create_library(this: Ptr, blob: *const c_void, size: usize, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device1_Vtbl.CreatePipelineLibrary)(this, blob, size, iid, out); + if let Some((_, p)) = made(hr, out) { + let mut all = vec![p]; + let newer = query(p, &ID3D12PipelineLibrary1::IID); + all.extend(newer.as_ref().map(|q| q.as_raw())); + for q in all { + hook::install(q, std::ptr::null(), library_table); + } + } + hr + } +} + +unsafe extern "system" fn create_graphics(this: Ptr, desc: *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above; the description is valid, as it was accepted. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateGraphicsPipelineState)(this, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + r.pipeline(p, pso::graphics(&*desc, &mut Keeper(r))); + } + hr + } +} + +unsafe extern "system" fn create_compute(this: Ptr, desc: *const D3D12_COMPUTE_PIPELINE_STATE_DESC, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateComputePipelineState)(this, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + r.pipeline(p, pso::compute(&*desc, &mut Keeper(r))); + } + hr + } +} + +unsafe extern "system" fn create_stream(this: Ptr, desc: *const D3D12_PIPELINE_STATE_STREAM_DESC, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device2_Vtbl.CreatePipelineState)(this, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + r.pipeline(p, pso::stream(&*desc, &mut Keeper(r))); + } + hr + } +} + +unsafe extern "system" fn load_graphics( + this: Ptr, + name: PCWSTR, + desc: *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline)(this, name, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + r.pipeline(p, pso::graphics(&*desc, &mut Keeper(r))); + } + hr + } +} + +unsafe extern "system" fn load_compute( + this: Ptr, + name: PCWSTR, + desc: *const D3D12_COMPUTE_PIPELINE_STATE_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12PipelineLibrary_Vtbl.LoadComputePipeline)(this, name, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + r.pipeline(p, pso::compute(&*desc, &mut Keeper(r))); + } + hr + } +} + +unsafe extern "system" fn load_stream( + this: Ptr, + name: PCWSTR, + desc: *const D3D12_PIPELINE_STATE_STREAM_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12PipelineLibrary1_Vtbl.LoadPipeline)(this, name, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + r.pipeline(p, pso::stream(&*desc, &mut Keeper(r))); + } + hr + } +} + +unsafe extern "system" fn create_root(this: Ptr, nodes: u32, blob: *const c_void, size: usize, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateRootSignature)(this, nodes, blob, size, iid, out); + if let Some((r, p)) = made(hr, out) { + // D3D12 may answer with an object it made before. + let known = r.ids.get(p as usize).filter(|id| lock(&r.roots).contains_key(id)); + let bytes = std::slice::from_raw_parts(blob.cast::(), size).to_vec(); + let id = known.unwrap_or_else(|| r.id()); + lock(&r.roots).insert(id, Arc::new(bytes)); + r.ids.set(p as usize, id); + } + hr + } +} + +unsafe extern "system" fn create_signature( + this: Ptr, + desc: *const D3D12_COMMAND_SIGNATURE_DESC, + root: Ptr, + iid: *const GUID, + out: Out, +) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateCommandSignature)(this, desc, root, iid, out); + if let Some((r, p)) = made(hr, out) { + let id = r.id(); + let d = &*desc; + let args: Vec<[u32; 4]> = + std::slice::from_raw_parts(d.pArgumentDescs.cast::<[u32; 4]>(), d.NumArgumentDescs as usize).to_vec(); + // Arguments that are GPU addresses lie in buffers; they are not + // rewritten for a replay. + let addresses = [ + D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW, + D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW, + D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW, + D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW, + D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW, + ]; + if args.iter().any(|a| addresses.iter().any(|t| t.0 as u32 == a[0])) { + r.problem("a command signature with GPU addresses among its arguments: a replay reads the recorded addresses"); + } + let root = if root.is_null() { NONE } else { r.object(root, "a root signature") }; + lock(&r.signatures).insert(id, wire::Signature { id, stride: d.ByteStride, args, root }); + r.ids.set(p as usize, id); + } + hr + } +} + +unsafe extern "system" fn create_queries(this: Ptr, desc: *const D3D12_QUERY_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateQueryHeap)(this, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + let id = r.id(); + lock(&r.queries).insert(id, wire::QueryHeap { id, kind: (*desc).Type.0, count: (*desc).Count }); + r.ids.set(p as usize, id); + } + hr + } +} + +unsafe extern "system" fn create_descriptors(this: Ptr, desc: *const D3D12_DESCRIPTOR_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateDescriptorHeap)(this, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + let heap = borrow::(p); + let d = &*desc; + let visible = d.Flags.0 & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 != 0; + let cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr; + let gpu = if visible { heap.GetGPUDescriptorHandleForHeapStart().ptr } else { 0 }; + let step = own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, d.Type) as usize; + let id = r.id(); + write(&r.descriptors).add(Arc::new(Heap::new(id, d, cpu, gpu, step.max(1)))); + r.ids.set(p as usize, id); + r.tell_gone(&*heap, Gone::Heap { id, ptr: p as usize }); + } + hr + } +} + +unsafe extern "system" fn create_heap(this: Ptr, desc: *const D3D12_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateHeap)(this, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + let id = r.id(); + lock(&r.heaps).insert(id, heap_of(id, &*desc)); + r.ids.set(p as usize, id); + } + hr + } +} + +fn heap_of(id: u32, d: &D3D12_HEAP_DESC) -> wire::Heap { + wire::Heap { id, size: d.SizeInBytes, props: gpu::from_props(&d.Properties), alignment: d.Alignment, flags: d.Flags.0 } +} + +unsafe fn clear_of(clear: *const D3D12_CLEAR_VALUE) -> Option<[u32; 5]> { + const _: () = assert!(size_of::() == 20); + // SAFETY: null or a clear value, of 20 bytes. + (!clear.is_null()).then(|| unsafe { clear.cast::<[u32; 5]>().read() }) +} + +#[allow(clippy::too_many_arguments)] +unsafe extern "system" fn create_committed( + this: Ptr, + props: *const D3D12_HEAP_PROPERTIES, + flags: D3D12_HEAP_FLAGS, + desc: *const D3D12_RESOURCE_DESC, + state: D3D12_RESOURCE_STATES, + clear: *const D3D12_CLEAR_VALUE, + iid: *const GUID, + out: Out, +) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateCommittedResource)(this, props, flags, desc, state, clear, iid, out); + if let Some((r, p)) = made(hr, out) { + let place = Place::Committed { props: gpu::from_props(&*props), flags: flags.0 }; + r.add(p, place, state.0, clear_of(clear)); + } + hr + } +} + +#[allow(clippy::too_many_arguments)] +unsafe extern "system" fn create_placed( + this: Ptr, + heap: Ptr, + offset: u64, + desc: *const D3D12_RESOURCE_DESC, + state: D3D12_RESOURCE_STATES, + clear: *const D3D12_CLEAR_VALUE, + iid: *const GUID, + out: Out, +) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreatePlacedResource)(this, heap, offset, desc, state, clear, iid, out); + if let Some((r, p)) = made(hr, out) { + // One opened from memory was not seen made. + let heap = r.ids.get(heap as usize).unwrap_or_else(|| { + let id = r.id(); + let d = borrow::(heap).GetDesc(); + r.problem("a heap opened from existing memory: a replay makes one like it"); + lock(&r.heaps).insert(id, heap_of(id, &d)); + r.ids.set(heap as usize, id); + id + }); + r.add(p, Place::Placed { heap, offset }, state.0, clear_of(clear)); + } + hr + } +} + +unsafe extern "system" fn create_cbv(this: Ptr, desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12Device_Vtbl.CreateConstantBufferView)(this, desc, at); + if let Some(r) = recorder().filter(|_| !ours()) { + r.set_view(at.ptr, &Slot::new(slot::CBV, NONE, NONE, desc.cast(), size_of::())); + } + } +} + +unsafe extern "system" fn create_srv(this: Ptr, res: Ptr, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12Device_Vtbl.CreateShaderResourceView)(this, res, desc, at); + if let Some(r) = recorder().filter(|_| !ours()) { + let id = r.resource(res); + r.set_view(at.ptr, &Slot::new(slot::SRV, id, NONE, desc.cast(), size_of::())); + } + } +} + +unsafe extern "system" fn create_uav( + this: Ptr, + res: Ptr, + counter: Ptr, + desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12Device_Vtbl.CreateUnorderedAccessView)(this, res, counter, desc, at); + if let Some(r) = recorder().filter(|_| !ours()) { + let (id, counter) = (r.resource(res), r.resource(counter)); + r.set_view(at.ptr, &Slot::new(slot::UAV, id, counter, desc.cast(), size_of::())); + } + } +} + +unsafe extern "system" fn create_rtv(this: Ptr, res: Ptr, desc: *const D3D12_RENDER_TARGET_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12Device_Vtbl.CreateRenderTargetView)(this, res, desc, at); + if let Some(r) = recorder().filter(|_| !ours()) { + let id = r.resource(res); + r.set_view(at.ptr, &Slot::new(slot::RTV, id, NONE, desc.cast(), size_of::())); + } + } +} + +unsafe extern "system" fn create_dsv(this: Ptr, res: Ptr, desc: *const D3D12_DEPTH_STENCIL_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12Device_Vtbl.CreateDepthStencilView)(this, res, desc, at); + if let Some(r) = recorder().filter(|_| !ours()) { + let id = r.resource(res); + r.set_view(at.ptr, &Slot::new(slot::DSV, id, NONE, desc.cast(), size_of::())); + } + } +} + +unsafe extern "system" fn create_sampler(this: Ptr, desc: *const D3D12_SAMPLER_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + const _: () = assert!(size_of::() == 52); + // SAFETY: as above. + unsafe { + own!(this, ID3D12Device_Vtbl.CreateSampler)(this, desc, at); + if let Some(r) = recorder().filter(|_| !ours()) { + r.set_view(at.ptr, &Slot::new(slot::SAMPLER, NONE, NONE, desc.cast(), 52)); + } + } +} + +unsafe extern "system" fn copy_descriptors_simple( + this: Ptr, + n: u32, + to: D3D12_CPU_DESCRIPTOR_HANDLE, + from: D3D12_CPU_DESCRIPTOR_HANDLE, + kind: D3D12_DESCRIPTOR_HEAP_TYPE, +) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12Device_Vtbl.CopyDescriptorsSimple)(this, n, to, from, kind); + if let Some(r) = recorder().filter(|_| !ours()) { + r.copy_views(to.ptr, from.ptr, n); + } + } +} + +#[allow(clippy::too_many_arguments)] +unsafe extern "system" fn copy_descriptors( + this: Ptr, + n_to: u32, + to: *const D3D12_CPU_DESCRIPTOR_HANDLE, + to_sizes: *const u32, + n_from: u32, + from: *const D3D12_CPU_DESCRIPTOR_HANDLE, + from_sizes: *const u32, + kind: D3D12_DESCRIPTOR_HEAP_TYPE, +) { + // SAFETY: as above; the arrays have as many entries as the counts say, + // and null sizes mean one descriptor each. + unsafe { + own!(this, ID3D12Device_Vtbl.CopyDescriptors)(this, n_to, to, to_sizes, n_from, from, from_sizes, kind); + let Some(r) = recorder().filter(|_| !ours()) else { + return; + }; + let step = own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, kind) as usize; + let size = |sizes: *const u32, i: u32| if sizes.is_null() { 1 } else { *sizes.add(i as usize) }; + let (mut i, mut j, mut done_to, mut done_from) = (0, 0, 0, 0); + while i < n_to && j < n_from { + let n = (size(to_sizes, i) - done_to).min(size(from_sizes, j) - done_from); + if n > 0 { + let a = (*to.add(i as usize)).ptr + done_to as usize * step; + let b = (*from.add(j as usize)).ptr + done_from as usize * step; + r.copy_views(a, b, n); + } + done_to += n; + done_from += n; + if done_to >= size(to_sizes, i) { + (i, done_to) = (i + 1, 0); + } + if done_from >= size(from_sizes, j) { + (j, done_from) = (j + 1, 0); + } + } + } +} + +unsafe extern "system" fn execute(this: Ptr, n: u32, lists: *const Ptr) { + // SAFETY: `n` closed lists, as D3D12 asks; the state is the queue's. + unsafe { + let go = || own!(this, ID3D12CommandQueue_Vtbl.ExecuteCommandLists)(this, n, lists); + let Some(r) = recorder().filter(|_| !ours()) else { + return go(); + }; + let kind = hook::state::(this).kind; + if kind != D3D12_COMMAND_LIST_TYPE_DIRECT.0 { + snap::other_queue(r, n); + return go(); + } + let all = std::slice::from_raw_parts(lists, n as usize); + snap::submit(r, &borrow::(this), all, go); + } +} + +/// A list's recorder and state, for a call of the host layer's. +unsafe fn of(this: Ptr) -> Option<(&'static Recorder, &'static ListState)> { + let r = recorder()?; + if ours() { + return None; + } + // SAFETY: a list with a shim; its state is a list's. + Some((r, unsafe { hook::state::(this) })) +} + +/// Records a command, if lists are recorded now. +unsafe fn note(this: Ptr, cmd: impl FnOnce(&Recorder) -> Cmd) { + // SAFETY: a list with a shim. + if let Some((r, state)) = unsafe { of(this) } + && r.armed.load(Ordering::Relaxed) + { + state.push(&cmd(r)); + } +} + +unsafe extern "system" fn list_close(this: Ptr) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12GraphicsCommandList_Vtbl.Close)(this); + if let Some((_, state)) = of(this) { + let mut inner = lock(&state.inner); + let bytes = std::mem::take(&mut inner.bytes); + let changes = Arc::new(std::mem::take(&mut inner.changes)); + inner.closed = Some((inner.whole.then(|| Arc::new(bytes)), changes)); + } + hr + } +} + +unsafe extern "system" fn list_reset(this: Ptr, allocator: Ptr, pso: Ptr) -> HRESULT { + // SAFETY: as above. + unsafe { + let table = hook::table(this); + let hr = own!(this, ID3D12GraphicsCommandList_Vtbl.Reset)(this, allocator, pso); + // A reset sets the list's table pointer anew. + hook::again(this, table, list_table); + if let Some((r, state)) = of(this) + && hr.is_ok() + { + let mut inner = lock(&state.inner); + inner.closed = None; + inner.whole = r.armed.load(Ordering::SeqCst) && state.kind == D3D12_COMMAND_LIST_TYPE_DIRECT.0; + begin(&mut inner, r, pso); + } + hr + } +} + +unsafe extern "system" fn draw(this: Ptr, vertices: u32, instances: u32, first: u32, first_instance: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.DrawInstanced)(this, vertices, instances, first, first_instance); + note(this, |_| Cmd::Draw { vertices, instances, first, first_instance }); + } +} + +unsafe extern "system" fn draw_indexed(this: Ptr, indices: u32, instances: u32, first: u32, base: i32, first_instance: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced)(this, indices, instances, first, base, first_instance); + note(this, |_| Cmd::DrawIndexed { indices, instances, first, base, first_instance }); + } +} + +unsafe extern "system" fn dispatch(this: Ptr, x: u32, y: u32, z: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.Dispatch)(this, x, y, z); + note(this, |_| Cmd::Dispatch { groups: [x, y, z] }); + } +} + +unsafe extern "system" fn dispatch_mesh(this: Ptr, x: u32, y: u32, z: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList6_Vtbl.DispatchMesh)(this, x, y, z); + note(this, |_| Cmd::DispatchMesh { groups: [x, y, z] }); + } +} + +unsafe extern "system" fn copy_buffer(this: Ptr, dst: Ptr, dst_at: u64, src: Ptr, src_at: u64, len: u64) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion)(this, dst, dst_at, src, src_at, len); + note(this, |r| Cmd::CopyBuffer { dst: r.resource(dst), dst_at, src: r.resource(src), src_at, len }); + } +} + +unsafe fn location(r: &Recorder, l: &D3D12_TEXTURE_COPY_LOCATION) -> Loc { + // SAFETY: a copy's valid location. + unsafe { + let res = r.resource(std::mem::transmute_copy::<_, Ptr>(&l.pResource)); + if l.Type == D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX { + return Loc::Sub { res, sub: l.Anonymous.SubresourceIndex }; + } + let p = l.Anonymous.PlacedFootprint; + let f = p.Footprint; + Loc::Placed { res, offset: p.Offset, format: f.Format.0, size: [f.Width, f.Height, f.Depth], pitch: f.RowPitch } + } +} + +/// A command that changes states whether lists are recorded or not. +unsafe fn note_change(this: Ptr, cmd: impl FnOnce(&Recorder) -> Cmd) { + // SAFETY: a list with a shim. + if let Some((r, state)) = unsafe { of(this) } { + let cmd = cmd(r); + let mut inner = lock(&state.inner); + states::changes(&cmd, &mut inner.changes); + if inner.whole { + cmd.put(&mut inner.bytes); + } + } +} + +unsafe extern "system" fn copy_texture( + this: Ptr, + dst: *const D3D12_TEXTURE_COPY_LOCATION, + x: u32, + y: u32, + z: u32, + src: *const D3D12_TEXTURE_COPY_LOCATION, + part: *const D3D12_BOX, +) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.CopyTextureRegion)(this, dst, x, y, z, src, part); + note_change(this, |r| Cmd::CopyTexture { + dst: location(r, &*dst), + at: [x, y, z], + src: location(r, &*src), + part: part.as_ref().map(|b| [b.left, b.top, b.front, b.right, b.bottom, b.back]), + }); + } +} + +unsafe extern "system" fn copy_resource(this: Ptr, dst: Ptr, src: Ptr) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.CopyResource)(this, dst, src); + note_change(this, |r| Cmd::CopyResource { dst: r.resource(dst), src: r.resource(src) }); + } +} + +unsafe extern "system" fn resolve(this: Ptr, dst: Ptr, dst_sub: u32, src: Ptr, src_sub: u32, format: DXGI_FORMAT) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveSubresource)(this, dst, dst_sub, src, src_sub, format); + note(this, |r| Cmd::Resolve { dst: r.resource(dst), dst_sub, src: r.resource(src), src_sub, format: format.0 }); + } +} + +#[allow(clippy::too_many_arguments)] +unsafe extern "system" fn resolve_region( + this: Ptr, + dst: Ptr, + dst_sub: u32, + x: u32, + y: u32, + src: Ptr, + src_sub: u32, + part: *const RECT, + format: DXGI_FORMAT, + mode: D3D12_RESOLVE_MODE, +) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion)(this, dst, dst_sub, x, y, src, src_sub, part, format, mode); + note(this, |r| Cmd::ResolveRegion { + dst: r.resource(dst), + dst_sub, + at: [x, y], + src: r.resource(src), + src_sub, + part: part.as_ref().map(rect), + format: format.0, + mode: mode.0, + }); + } +} + +fn rect(r: &RECT) -> [i32; 4] { + [r.left, r.top, r.right, r.bottom] +} + +unsafe fn rects(n: u32, all: *const RECT) -> Vec<[i32; 4]> { + if all.is_null() || n == 0 { + return Vec::new(); + } + // SAFETY: `n` rectangles. + unsafe { std::slice::from_raw_parts(all, n as usize) }.iter().map(rect).collect() +} + +unsafe extern "system" fn topology(this: Ptr, kind: D3D_PRIMITIVE_TOPOLOGY) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.IASetPrimitiveTopology)(this, kind); + note(this, |_| Cmd::Topology { kind: kind.0 }); + } +} + +unsafe extern "system" fn viewports(this: Ptr, n: u32, all: *const D3D12_VIEWPORT) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.RSSetViewports)(this, n, all); + note(this, |_| Cmd::Viewports { all: (0..n as usize).map(|i| all.add(i).cast::<[f32; 6]>().read()).collect() }); + } +} + +unsafe extern "system" fn scissors(this: Ptr, n: u32, all: *const RECT) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.RSSetScissorRects)(this, n, all); + note(this, |_| Cmd::Scissors { all: rects(n, all) }); + } +} + +unsafe extern "system" fn blend_factor(this: Ptr, factor: *const f32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor)(this, factor); + note(this, |_| Cmd::BlendFactor { factor: factor.cast::<[f32; 4]>().as_ref().copied() }); + } +} + +unsafe extern "system" fn stencil_ref(this: Ptr, value: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetStencilRef)(this, value); + note(this, |_| Cmd::StencilRef { value }); + } +} + +unsafe extern "system" fn depth_bounds(this: Ptr, min: f32, max: f32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList1_Vtbl.OMSetDepthBounds)(this, min, max); + note(this, |_| Cmd::DepthBounds { min, max }); + } +} + +unsafe extern "system" fn set_pipeline(this: Ptr, pso: Ptr) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetPipelineState)(this, pso); + note(this, |r| Cmd::Pipeline { pso: r.object(pso, "a pipeline") }); + } +} + +unsafe extern "system" fn barrier(this: Ptr, n: u32, all: *const D3D12_RESOURCE_BARRIER) { + // SAFETY: as above; a barrier's type says which of its parts holds. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.ResourceBarrier)(this, n, all); + note_change(this, |r| { + let all = std::slice::from_raw_parts(all, n as usize) + .iter() + .map(|b| match b.Type { + D3D12_RESOURCE_BARRIER_TYPE_ALIASING => { + let a = &b.Anonymous.Aliasing; + Barrier::Alias { + flags: b.Flags.0, + before: r.resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceBefore)), + after: r.resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceAfter)), + } + } + D3D12_RESOURCE_BARRIER_TYPE_UAV => { + Barrier::Uav { flags: b.Flags.0, res: r.resource(std::mem::transmute_copy::<_, Ptr>(&b.Anonymous.UAV.pResource)) } + } + _ => { + let t = &b.Anonymous.Transition; + Barrier::Transition { + flags: b.Flags.0, + res: r.resource(std::mem::transmute_copy::<_, Ptr>(&t.pResource)), + sub: t.Subresource, + before: t.StateBefore.0, + after: t.StateAfter.0, + } + } + }) + .collect(); + Cmd::Barriers { all } + }); + } +} + +unsafe extern "system" fn set_heaps(this: Ptr, n: u32, all: *const Ptr) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps)(this, n, all); + note(this, |r| Cmd::Heaps { heaps: (0..n as usize).map(|i| r.object(*all.add(i), "a descriptor heap")).collect() }); + } +} + +unsafe extern "system" fn root_compute(this: Ptr, root: Ptr) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature)(this, root); + note(this, |r| Cmd::RootSignature { graphics: false, root: r.object(root, "a root signature") }); + } +} + +unsafe extern "system" fn root_graphics(this: Ptr, root: Ptr) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature)(this, root); + note(this, |r| Cmd::RootSignature { graphics: true, root: r.object(root, "a root signature") }); + } +} + +fn table(r: &Recorder, graphics: bool, param: u32, at: u64) -> Cmd { + let (heap, slot) = match read(&r.descriptors).gpu(at) { + Some((h, i)) => (h.id, i), + None => (NONE, 0), + }; + if heap == NONE { + r.problem("a descriptor table in no heap seen made"); + } + Cmd::Table { graphics, param, heap, slot } +} + +unsafe extern "system" fn table_compute(this: Ptr, param: u32, at: D3D12_GPU_DESCRIPTOR_HANDLE) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable)(this, param, at); + note(this, |r| table(r, false, param, at.ptr)); + } +} + +unsafe extern "system" fn table_graphics(this: Ptr, param: u32, at: D3D12_GPU_DESCRIPTOR_HANDLE) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable)(this, param, at); + note(this, |r| table(r, true, param, at.ptr)); + } +} + +unsafe extern "system" fn constant_compute(this: Ptr, param: u32, value: u32, offset: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant)(this, param, value, offset); + note(this, |_| Cmd::Constants { graphics: false, param, offset, values: vec![value] }); + } +} + +unsafe extern "system" fn constant_graphics(this: Ptr, param: u32, value: u32, offset: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant)(this, param, value, offset); + note(this, |_| Cmd::Constants { graphics: true, param, offset, values: vec![value] }); + } +} + +unsafe fn values(n: u32, data: *const c_void) -> Vec { + // SAFETY: `n` values, of any alignment. + (0..n as usize).map(|i| unsafe { data.cast::().add(i).read_unaligned() }).collect() +} + +unsafe extern "system" fn constants_compute(this: Ptr, param: u32, n: u32, data: *const c_void, offset: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants)(this, param, n, data, offset); + note(this, |_| Cmd::Constants { graphics: false, param, offset, values: values(n, data) }); + } +} + +unsafe extern "system" fn constants_graphics(this: Ptr, param: u32, n: u32, data: *const c_void, offset: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants)(this, param, n, data, offset); + note(this, |_| Cmd::Constants { graphics: true, param, offset, values: values(n, data) }); + } +} + +/// A root view's address, reported if it lies in no buffer. +fn address(r: &Recorder, at: u64) -> Va { + let va = r.va(at); + if matches!(va, Va::Unknown { .. }) { + r.problem("a GPU address in no buffer seen made"); + } + va +} + +macro_rules! root_views { + ($($name:ident, $method:ident, $graphics:literal, $kind:ident;)*) => {$( + unsafe extern "system" fn $name(this: Ptr, param: u32, at: u64) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.$method)(this, param, at); + note(this, |r| Cmd::RootView { graphics: $graphics, kind: slot::$kind, param, va: address(r, at) }); + } + } + )*}; +} +root_views! { + cbv_compute, SetComputeRootConstantBufferView, false, CBV; + cbv_graphics, SetGraphicsRootConstantBufferView, true, CBV; + srv_compute, SetComputeRootShaderResourceView, false, SRV; + srv_graphics, SetGraphicsRootShaderResourceView, true, SRV; + uav_compute, SetComputeRootUnorderedAccessView, false, UAV; + uav_graphics, SetGraphicsRootUnorderedAccessView, true, UAV; +} + +unsafe extern "system" fn index_buffer(this: Ptr, view: *const D3D12_INDEX_BUFFER_VIEW) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer)(this, view); + note(this, |r| Cmd::IndexBuffer { view: view.as_ref().map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.Format.0)) }); + } +} + +unsafe extern "system" fn vertex_buffers(this: Ptr, start: u32, n: u32, views: *const D3D12_VERTEX_BUFFER_VIEW) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers)(this, start, n, views); + note(this, |r| Cmd::VertexBuffers { + start, + count: n, + views: (!views.is_null()).then(|| { + let all = std::slice::from_raw_parts(views, n as usize); + all.iter().map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.StrideInBytes)).collect() + }), + }); + } +} + +unsafe extern "system" fn targets( + this: Ptr, + n: u32, + colors: *const D3D12_CPU_DESCRIPTOR_HANDLE, + range: BOOL, + depth: *const D3D12_CPU_DESCRIPTOR_HANDLE, +) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets)(this, n, colors, range, depth); + note(this, |r| { + let colors = (0..n as usize) + .map(|i| { + if !range.as_bool() { + return r.view((*colors.add(i)).ptr); + } + let all = read(&r.descriptors); + all.cpu((*colors).ptr).map_or(Slot::EMPTY, |(h, first)| h.get(first + i as u32)) + }) + .collect(); + Cmd::Targets { colors, depth: depth.as_ref().map(|d| r.view(d.ptr)) } + }); + } +} + +#[allow(clippy::too_many_arguments)] +unsafe extern "system" fn clear_depth( + this: Ptr, + view: D3D12_CPU_DESCRIPTOR_HANDLE, + flags: D3D12_CLEAR_FLAGS, + depth: f32, + stencil: u8, + n: u32, + all: *const RECT, +) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView)(this, view, flags, depth, stencil, n, all); + note(this, |r| Cmd::ClearDepth { view: r.view(view.ptr), flags: flags.0, depth, stencil, rects: rects(n, all) }); + } +} + +unsafe extern "system" fn clear_target(this: Ptr, view: D3D12_CPU_DESCRIPTOR_HANDLE, color: *const f32, n: u32, all: *const RECT) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView)(this, view, color, n, all); + note(this, |r| Cmd::ClearTarget { view: r.view(view.ptr), color: color.cast::<[f32; 4]>().read(), rects: rects(n, all) }); + } +} + +unsafe extern "system" fn discard(this: Ptr, res: Ptr, region: *const D3D12_DISCARD_REGION) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.DiscardResource)(this, res, region); + note(this, |r| Cmd::Discard { + res: r.resource(res), + rects: region.as_ref().map_or(Vec::new(), |d| rects(d.NumRects, d.pRects)), + subs: region.as_ref().map(|d| [d.FirstSubresource, d.NumSubresources]), + }); + } +} + +unsafe extern "system" fn begin_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TYPE, index: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.BeginQuery)(this, heap, kind, index); + note(this, |r| Cmd::BeginQuery { heap: r.object(heap, "a query heap"), kind: kind.0, index }); + } +} + +unsafe extern "system" fn end_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TYPE, index: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.EndQuery)(this, heap, kind, index); + note(this, |r| Cmd::EndQuery { heap: r.object(heap, "a query heap"), kind: kind.0, index }); + } +} + +unsafe extern "system" fn resolve_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TYPE, first: u32, count: u32, dst: Ptr, at: u64) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveQueryData)(this, heap, kind, first, count, dst, at); + note(this, |r| Cmd::ResolveQuery { heap: r.object(heap, "a query heap"), kind: kind.0, first, count, dst: r.resource(dst), at }); + } +} + +unsafe extern "system" fn indirect(this: Ptr, signature: Ptr, most: u32, args: Ptr, at: u64, count: Ptr, count_at: u64) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect)(this, signature, most, args, at, count, count_at); + note(this, |r| Cmd::Indirect { + signature: r.object(signature, "a command signature"), + most, + args: r.resource(args), + at, + count: r.resource(count), + count_at, + }); + } +} + +unsafe extern "system" fn write_immediate( + this: Ptr, + n: u32, + all: *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, + modes: *const D3D12_WRITEBUFFERIMMEDIATE_MODE, +) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList2_Vtbl.WriteBufferImmediate)(this, n, all, modes); + note(this, |r| Cmd::WriteImmediate { + all: (0..n as usize) + .map(|i| { + let p = all.add(i).read(); + let mode = if modes.is_null() { 0 } else { modes.add(i).read().0 }; + (address(r, p.Dest), p.Value, mode) + }) + .collect(), + }); + } +} + +/// The first subresources of all: what [`ALL`] means in a barrier. +const _: () = assert!(ALL == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn when_to_record() { + assert_eq!(parse_at("120"), At::Seconds(120.0)); + assert_eq!(parse_at(" 1.5 "), At::Seconds(1.5)); + assert_eq!(parse_at("f900"), At::Frame(900)); + assert_eq!(parse_at(""), At::Trigger); + assert_eq!(parse_at("later"), At::Trigger); + } + + #[test] + fn descriptor_heaps_are_found_by_address() { + let heap = |id, cpu, gpu, count| { + let d = D3D12_DESCRIPTOR_HEAP_DESC { + NumDescriptors: count, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }; + Arc::new(Heap::new(id, &d, cpu, gpu, 32)) + }; + let mut all = Heaps::default(); + all.add(heap(1, 0x1000, 0x10_0000, 4)); + all.add(heap(2, 0x2000, 0x20_0000, 8)); + let at = |all: &Heaps, p| all.cpu(p).map(|(h, i)| (h.id, i)); + assert_eq!(at(&all, 0x1000), Some((1, 0))); + assert_eq!(at(&all, 0x1060), Some((1, 3))); + assert_eq!(at(&all, 0x1080), None, "past its end"); + assert_eq!(at(&all, 0xfff), None); + assert_eq!(all.gpu(0x20_0040).map(|(h, i)| (h.id, i)), Some((2, 2))); + // A heap made where a dead one was takes its place. + all.add(heap(3, 0x1020, 0x30_0000, 4)); + assert_eq!(at(&all, 0x1000), None); + assert_eq!(at(&all, 0x1020), Some((3, 0))); + all.remove(2); + assert_eq!(at(&all, 0x2000), None); + let h = heap(4, 0, 0, 2); + let s = Slot { kind: slot::SRV, res: 5, ..Slot::EMPTY }; + h.set(1, &s); + h.set(2, &s); + assert_eq!(h.all(), [Slot::EMPTY, s]); + assert_eq!(h.get(9), Slot::EMPTY); + } +} diff --git a/crates/victory-gpu/src/replay/snap.rs b/crates/victory-gpu/src/replay/snap.rs new file mode 100644 index 0000000..b5f7005 --- /dev/null +++ b/crates/victory-gpu/src/replay/snap.rs @@ -0,0 +1,923 @@ +//! One frame written down: what its submissions run, what the card's +//! memory held at its start, and what the CPU put into memory both see +//! before each submission. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::fs::File; +use std::os::windows::fs::FileExt; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::time::Instant; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::Interface; + +use super::gpu::{self, Seen, Worker}; +use super::record::{At, Heap, Ours, Recorder, Res, lock, not_recorded_calls, read}; +use super::states::{COMMON, COPY_SOURCE, Change, States}; +use super::wire::{self, ALL, Cmd, Content, Delta, MISSING, NONE, Place, Slot, Va, ZERO, slot}; + +type Fault = Box; + +/// A read-back buffer contents go through, and how many there are. +const STAGING: u64 = 256 << 20; +const STAGINGS: usize = 4; +/// The most of a buffer in one piece. +const PIECE: u64 = 32 << 20; +/// What the CPU changes is kept in units of. +const PAGE: usize = 4096; +/// What one thread compares at a time. +const CHUNK: usize = 1 << 20; +/// Frames waited, at the most, for one whose lists are all recorded. +const PATIENCE: u64 = 300; + +#[derive(Default)] +enum Stage { + #[default] + Waiting, + /// Lists are recorded, since this many presents. + Armed(u64), + Capturing(Box), + Done, +} + +/// Where the recorder is. +#[derive(Default)] +pub(super) struct Phase { + presents: u64, + stage: Stage, + /// Submissions of this frame so far, and lists among them that were not + /// recorded. + submits: u32, + missing: u32, +} + +impl Phase { + pub(super) fn done(&self) -> bool { + matches!(self.stage, Stage::Done) + } +} + +/// A submission to a queue other than the drawing one: left out. +pub(super) fn other_queue(r: &Recorder, lists: u32) { + if r.watching.load(Ordering::SeqCst) { + r.problem_times("lists sent to a queue other than the drawing one are not in the capture", u64::from(lists)); + } +} + +/// A submission to the drawing queue, made by `go`. +pub(super) fn submit(r: &Recorder, queue: &ID3D12CommandQueue, lists: &[*mut std::ffi::c_void], go: impl FnOnce()) { + let mut phase = lock(&r.submits); + type Closed = (Option>>, Arc>); + let closed: Vec> = lists.iter().map(|&p| r.list(p).and_then(|l| l.closed())).collect(); + phase.submits += 1; + phase.missing += closed.iter().filter(|c| c.as_ref().is_none_or(|c| c.0.is_none())).count() as u32; + if let Stage::Capturing(c) = &mut phase.stage { + let commands: Vec>>> = closed.iter().map(|c| c.as_ref().and_then(|c| c.0.clone())).collect(); + let _ours = Ours::new(); + if let Err(e) = c.submit(r, queue, &commands) { + stop(r, &mut phase, &*e); + } + } + go(); + let mut states = lock(&r.states); + for change in closed.iter().flatten().flat_map(|c| c.1.iter()) { + states.change(change); + } + states.decay(); +} + +/// The capture failed. +fn stop(r: &Recorder, phase: &mut Phase, e: &(dyn std::error::Error + Send + Sync)) { + tracing::error!("frame recorder: the capture failed: {e}"); + let _ = std::fs::write(r.folder.join("failed.txt"), e.to_string()); + phase.stage = Stage::Done; + r.watching.store(false, Ordering::SeqCst); + r.arm(false); + lock(&r.held).clear(); +} + +pub(super) fn present(r: &Recorder, texture: &ID3D12Resource, state: u32) { + let mut phase = lock(&r.submits); + phase.presents += 1; + let presents = phase.presents; + let (submits, missing) = (std::mem::take(&mut phase.submits), std::mem::take(&mut phase.missing)); + let mut finished = None; + match &mut phase.stage { + Stage::Waiting => { + let due = match r.settings.at { + At::Seconds(s) => r.began.elapsed().as_secs_f64() >= s, + At::Frame(f) => presents >= f, + At::Trigger => false, + }; + if due || r.settings.folder.join("go").exists() { + tracing::info!(presents, "frame recorder: lists are recorded from now on"); + r.arm(true); + phase.stage = Stage::Armed(presents); + } + } + Stage::Armed(since) => { + let waited = presents - *since; + let whole = submits > 0 && missing == 0; + if waited >= 2 && (whole || waited > PATIENCE) { + if !whole { + r.problem("no frame was found whose lists were all recorded"); + } + tracing::info!(presents, waited, "frame recorder: the next frame is captured"); + match Capture::new(r) { + Ok(c) => phase.stage = Stage::Capturing(Box::new(c)), + Err(e) => stop(r, &mut phase, &*e), + } + } + } + Stage::Capturing(c) if c.started => { + let _ours = Ours::new(); + let done = c.present(r, texture, state).and_then(|()| { + if c.frame < r.settings.frames { + return Ok(false); + } + c.finish(r)?; + Ok(true) + }); + match done { + Ok(false) => {} + Ok(true) => { + r.watching.store(false, Ordering::SeqCst); + r.arm(false); + if let Stage::Capturing(c) = std::mem::replace(&mut phase.stage, Stage::Done) { + finished = Some((c, std::mem::take(&mut *lock(&r.held)))); + } + } + Err(e) => stop(r, &mut phase, &*e), + } + } + // A frame without a submission: the next one. + Stage::Capturing(_) | Stage::Done => {} + } + drop(phase); + // What was kept alive goes without a lock held. + drop(finished); +} + +/// A buffer the CPU sees. +struct CpuBuffer { + id: u32, + res: ID3D12Resource, + /// Where it is read: its mapping, or the read-back copy of it. + live: *const u8, + /// The read-back buffer and the offset in it, for one that is slow to + /// read. + through: Option<(usize, u64)>, + size: usize, + /// What it held at the submission before (zeros before the first). + kept: Vec, +} + +// SAFETY: the mapping is of a buffer the struct holds. +unsafe impl Send for CpuBuffer {} +// SAFETY: as above; the mapping is only read. +unsafe impl Sync for CpuBuffer {} + +struct Capture { + worker: Worker, + others: Vec, + /// Resources the frame can use, kept alive. + held: Vec, + started: bool, + frame: u32, + states: States, + idle: HashSet, + heaps: Vec<(Arc, Vec<(u32, u32, Slot)>)>, + contents: Vec, + buffers: Vec, + known: HashSet, + /// Read-back buffers for the slow ones: the buffer, its mapping, size, + /// and how much of it is taken. + blocks: Vec<(ID3D12Resource, usize, u64, u64)>, + deltas: File, + delta_at: AtomicU64, + lists: Vec>>, + submits: Vec, + presents: Vec, + present_file: File, + present_at: u64, + calls: Vec<(String, u64)>, + began: Instant, + took: BTreeMap<&'static str, std::time::Duration>, +} + +impl Capture { + fn new(r: &Recorder) -> Result { + let _ours = Ours::new(); + let device = r.device().ok_or("no device")?; + let queues = lock(&r.queues).clone(); + let direct = queues.iter().find(|q| q.1 == D3D12_COMMAND_LIST_TYPE_DIRECT.0).ok_or("no drawing queue")?; + let mut others = Vec::new(); + for (queue, _) in queues.iter().filter(|q| q.0 != direct.0) { + others.push(Worker::new(&device, queue)?); + } + Ok(Capture { + worker: Worker::new(&device, &direct.0)?, + others, + held: Vec::new(), + started: false, + frame: 0, + states: States::default(), + idle: HashSet::new(), + heaps: Vec::new(), + contents: Vec::new(), + buffers: Vec::new(), + known: HashSet::new(), + blocks: Vec::new(), + deltas: File::create(r.folder.join("deltas.bin"))?, + delta_at: AtomicU64::new(0), + lists: Vec::new(), + submits: Vec::new(), + presents: Vec::new(), + present_file: File::create(r.folder.join("present.bin"))?, + present_at: 0, + calls: not_recorded_calls(), + began: Instant::now(), + took: BTreeMap::new(), + }) + } + + fn timed(&mut self, what: &'static str, f: impl FnOnce(&mut Self) -> Result) -> Result { + let began = Instant::now(); + let out = f(self); + *self.took.entry(what).or_default() += began.elapsed(); + out + } + + /// Before the first submission of the frame: what the card holds. + fn start(&mut self, r: &Recorder) -> Result<(), Fault> { + self.began = Instant::now(); + r.watching.store(true, Ordering::SeqCst); + self.started = true; + self.worker.idle()?; + for w in &mut self.others { + w.idle()?; + } + let mut all: Vec> = Vec::new(); + { + let live = read(&r.resources); + for res in live.values() { + let object = res.object(); + // SAFETY: a live resource, or one whose end waits for the + // lock held here (`Recorder::gone`): the count tells which. + let count = unsafe { (Interface::vtable(&*object).base__.base__.base__.base__.AddRef)(object.as_raw()) }; + if count <= 1 { + // Dying: the reference does not bring it back, and + // giving it back would end it a second time. + continue; + } + // SAFETY: the reference just taken. + self.held.push(unsafe { ID3D12Resource::from_raw(object.as_raw()) }); + all.push(res.clone()); + } + } + all.sort_by_key(|res| res.id); + self.states = lock(&r.states).clone(); + self.idle = self.find_idle(&all); + self.timed("contents of the card's memory", |c| c.snapshot(r, &all))?; + Ok(()) + } + + /// Of placed resources that overlap, those that are not the one used + /// last. + fn find_idle(&self, all: &[Arc]) -> HashSet { + let mut heaps: HashMap> = HashMap::new(); + for res in all { + if let Place::Placed { heap, offset } = res.place { + // SAFETY: a plain query. + let info = unsafe { self.worker.device.GetResourceAllocationInfo(0, &[gpu::to_desc(&res.desc)]) }; + let size = if info.SizeInBytes == u64::MAX { res.desc.width } else { info.SizeInBytes }; + let used = self.states.used.get(&res.id).copied().unwrap_or(0); + heaps.entry(heap).or_default().push((used, offset, offset + size, res.id)); + } + } + let mut idle = HashSet::new(); + for (_, mut list) in heaps { + list.sort_by(|a, b| b.cmp(a)); + let mut taken: BTreeMap = BTreeMap::new(); + for (_, from, to, id) in list { + let overlaps = taken.range(..to).next_back().is_some_and(|(_, &end)| end > from); + if overlaps { + idle.insert(id); + } else { + taken.insert(from, to); + } + } + } + idle + } + + fn snapshot(&mut self, r: &Recorder, all: &[Arc]) -> Result<(), Fault> { + let device = self.worker.device.clone(); + let mut pieces: Vec = Vec::new(); + for res in all.iter().filter(|res| res.seen == Seen::No) { + if matches!(res.place, Place::BackBuffer {}) || self.idle.contains(&res.id) { + continue; + } + if res.is_buffer() { + let mut at = 0; + while at < res.desc.width { + let len = PIECE.min(res.desc.width - at); + pieces.push(Piece { res: res.clone(), first: at, count: 1, len, at: 0 }); + at += len; + } + continue; + } + if res.desc.samples[0] > 1 { + r.problem("contents of multisampled textures are not in the capture"); + continue; + } + let desc = gpu::to_desc(&res.desc); + let (_, total) = gpu::footprints(&device, &desc, 0, res.subs); + if total == u64::MAX { + r.problem("contents of a texture without a copyable layout are not in the capture"); + } else if total <= STAGING { + pieces.push(Piece { res: res.clone(), first: 0, count: res.subs, len: total, at: 0 }); + } else { + for sub in 0..res.subs { + let (_, len) = gpu::footprints(&device, &desc, sub, 1); + if len <= STAGING { + pieces.push(Piece { res: res.clone(), first: u64::from(sub), count: 1, len, at: 0 }); + } else { + r.problem("contents of a texture level of over 256 MB are not in the capture"); + } + } + } + } + // Into batches, one read-back buffer each. + let mut batches: Vec> = vec![Vec::new()]; + let mut at = 0u64; + for mut p in pieces { + at = at.next_multiple_of(512); + if at + p.len > STAGING { + batches.push(Vec::new()); + at = 0; + } + p.at = at; + at += p.len; + if let Some(b) = batches.last_mut() { + b.push(p); + } + } + let mut stagings = Vec::new(); + for _ in 0..STAGINGS.min(batches.len()) { + stagings.push(gpu::buffer(&device, D3D12_HEAP_TYPE_READBACK, STAGING, D3D12_RESOURCE_FLAG_NONE)?); + } + let file = File::create(r.folder.join("contents.bin"))?; + let end = AtomicU64::new(0); + let contents: std::sync::Mutex> = std::sync::Mutex::default(); + let failed: std::sync::Mutex> = std::sync::Mutex::default(); + let (todo, work) = std::sync::mpsc::channel::<(usize, Vec)>(); + let work = std::sync::Mutex::new(work); + let (free, freed) = std::sync::mpsc::channel::(); + for i in 0..stagings.len() { + free.send(i)?; + } + let maps: Vec = stagings.iter().map(|s| s.1 as usize).collect(); + std::thread::scope(|scope| -> Result<(), Fault> { + for _ in 0..stagings.len() { + let (work, free, maps, file, end, contents, failed) = (&work, free.clone(), &maps, &file, &end, &contents, &failed); + scope.spawn(move || { + loop { + let next = lock(work).recv(); + let Ok((i, pieces)) = next else { break }; + for p in pieces { + // SAFETY: inside the buffer's mapping; the copy + // into it has run. + let bytes = unsafe { std::slice::from_raw_parts((maps[i] + p.at as usize) as *const u8, p.len as usize) }; + let at = if zero(bytes) { ZERO } else { end.fetch_add(p.len, Ordering::Relaxed) }; + if at != ZERO + && let Err(e) = write_at(file, bytes, at) + { + lock(failed).get_or_insert(e); + } + lock(contents).push(Content { res: p.res.id, first: p.first, count: p.count, len: p.len, file: at }); + } + let _ = free.send(i); + } + }); + } + // Moved in: the writers end when it goes. + let todo = todo; + for pieces in batches { + if pieces.is_empty() { + continue; + } + let i = freed.recv()?; + let value = self.worker.send(|list| copy_out(&device, list, &self.states, &pieces, &stagings[i].0))?; + self.worker.wait(value)?; + todo.send((i, pieces))?; + } + Ok(()) + })?; + if let Some(e) = lock(&failed).take() { + return Err(e.into()); + } + self.contents = contents.into_inner().unwrap_or_else(|e| e.into_inner()); + Ok(()) + } + + /// Buffers the CPU sees that were not known yet. + fn new_buffers(&mut self, r: &Recorder) -> Result<(), Fault> { + let fresh: Vec> = read(&r.resources) + .values() + .filter(|res| matches!(res.seen, Seen::Cached | Seen::Combined) && !self.known.contains(&res.id)) + .cloned() + .collect(); + for res in fresh { + self.known.insert(res.id); + if !res.is_buffer() { + r.problem("contents of textures in memory the CPU sees are not in the capture"); + continue; + } + // Those alive at the start are held, those made since too. + let object = ID3D12Resource::clone(&res.object()); + let size = res.desc.width as usize; + let (live, through) = if res.seen == Seen::Cached { + let mut data = std::ptr::null_mut(); + // SAFETY: a live buffer in memory the CPU sees. + unsafe { object.Map(0, None, Some(&mut data))? }; + (data.cast::().cast_const(), None) + } else { + let room = self.blocks.iter().position(|b| b.3 + size as u64 <= b.2); + let i = match room { + Some(i) => i, + None => { + let len = STAGING.max(size as u64); + let (b, data) = gpu::buffer(&self.worker.device, D3D12_HEAP_TYPE_READBACK, len, D3D12_RESOURCE_FLAG_NONE)?; + self.blocks.push((b, data as usize, len, 0)); + self.blocks.len() - 1 + } + }; + let b = &mut self.blocks[i]; + let at = b.3; + b.3 = (at + size as u64).next_multiple_of(256); + ((b.1 + at as usize) as *const u8, Some((i, at))) + }; + self.buffers.push(CpuBuffer { id: res.id, res: object, live, through, size, kept: vec![0; size] }); + } + Ok(()) + } + + /// What changed in buffers the CPU sees since the submission before. + fn changed(&mut self, r: &Recorder) -> Result, Fault> { + self.new_buffers(r)?; + if self.buffers.iter().any(|b| b.through.is_some()) { + let (buffers, blocks) = (&self.buffers, &self.blocks); + self.worker.run(|list| { + for b in buffers { + if let Some((i, at)) = b.through { + // SAFETY: an open list and live buffers. + unsafe { list.CopyBufferRegion(&blocks[i].0, at, &b.res, 0, b.size as u64) }; + } + } + })?; + } + let chunks: Vec<(usize, usize)> = + self.buffers.iter().enumerate().flat_map(|(i, b)| (0..b.size).step_by(CHUNK).map(move |at| (i, at))).collect(); + // Each chunk is one thread's; threads share what is kept by parts. + struct Kept(*mut u8); + // SAFETY: parts of it are used by one thread each. + unsafe impl Sync for Kept {} + let kept: Vec = self.buffers.iter_mut().map(|b| Kept(b.kept.as_mut_ptr())).collect(); + let next = AtomicUsize::new(0); + let out: std::sync::Mutex> = std::sync::Mutex::default(); + let failed: std::sync::Mutex> = std::sync::Mutex::default(); + let threads = std::thread::available_parallelism().map_or(4, |n| n.get() / 2).clamp(1, 16).min(chunks.len().max(1)); + let (buffers, file, end) = (&self.buffers, &self.deltas, &self.delta_at); + std::thread::scope(|scope| { + for _ in 0..threads { + scope.spawn(|| { + let mut mine = Vec::new(); + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(&(b, at)) = chunks.get(i) else { break }; + let len = CHUNK.min(buffers[b].size - at); + // SAFETY: a chunk of the buffer's memory (it may + // change meanwhile: what is kept is what was read) + // and of what is kept, which no other thread has. + let runs = unsafe { changed_runs(buffers[b].live.add(at), kept[b].0.add(at), len) }; + for (from, to) in runs { + // SAFETY: as above. + let bytes = unsafe { std::slice::from_raw_parts(kept[b].0.add(at + from), to - from) }; + let file_at = end.fetch_add(bytes.len() as u64, Ordering::Relaxed); + if let Err(e) = write_at(file, bytes, file_at) { + lock(&failed).get_or_insert(e); + } + mine.push(Delta { res: buffers[b].id, at: (at + from) as u64, len: bytes.len() as u64, file: file_at }); + } + } + lock(&out).extend(mine); + }); + } + }); + if let Some(e) = lock(&failed).take() { + return Err(e.into()); + } + let mut out = out.into_inner().unwrap_or_else(|e| e.into_inner()); + out.sort_by_key(|d| (d.res, d.at)); + Ok(out) + } + + fn submit(&mut self, r: &Recorder, _queue: &ID3D12CommandQueue, lists: &[Option>>]) -> Result<(), Fault> { + let first = !self.started; + if first { + self.start(r)?; + } else { + self.timed("waiting for the card", |c| Ok(c.worker.idle()?))?; + } + let deltas = self.timed("what the CPU changed", |c| c.changed(r))?; + // Descriptors last: their memory is ready now. + let mut written = std::mem::take(&mut *lock(&r.writes)); + let mut views = Vec::new(); + if first { + let heaps: Vec> = read(&r.descriptors).visible().cloned().collect(); + for h in heaps { + let runs = runs_of(r, &h.all()); + self.heaps.push((h, runs)); + } + } else { + written.sort_unstable(); + let mut seen = HashSet::new(); + for (heap, at, n) in written { + let h = match self.heaps.iter().find(|(h, _)| h.id == heap) { + Some((h, _)) => h.clone(), + None => { + let found = read(&r.descriptors).visible().find(|h| h.id == heap).cloned(); + let Some(h) = found else { continue }; + self.heaps.push((h.clone(), Vec::new())); + h + } + }; + for i in at..at + n { + if seen.insert((heap, i)) { + views.push((heap, i, resolved(r, h.get(i)))); + } + } + } + } + let mut numbers = Vec::new(); + for l in lists { + numbers.push(match l { + None => { + r.problem("a list was submitted that was not recorded whole: its work is missing"); + MISSING + } + Some(commands) => match self.lists.iter().position(|have| Arc::ptr_eq(have, commands)) { + Some(i) => i as u32, + None => { + self.lists.push(commands.clone()); + self.lists.len() as u32 - 1 + } + }, + }); + } + self.submits.push(wire::Submit { frame: self.frame, lists: numbers, deltas, views }); + Ok(()) + } + + fn present(&mut self, r: &Recorder, texture: &ID3D12Resource, state: u32) -> Result<(), Fault> { + self.worker.idle()?; + // SAFETY: a live texture. + let desc = unsafe { texture.GetDesc() }; + let (f, total) = gpu::footprints(&self.worker.device, &desc, 0, 1); + let (back, data) = gpu::buffer(&self.worker.device, D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_FLAG_NONE)?; + self.worker.run(|list| read_sub(list, texture, 0, state, &back, f[0]))?; + // SAFETY: the buffer's mapping; the copy into it has run. + let bytes = unsafe { std::slice::from_raw_parts(data, total as usize) }; + write_at(&self.present_file, bytes, self.present_at)?; + let id = r.resource(texture.as_raw()); + let (width, height, pitch) = (desc.Width as u32, desc.Height, f[0].Footprint.RowPitch); + self.presents.push(wire::Present { + submits: self.submits.len() as u32, + res: id, + width, + height, + format: desc.Format.0, + pitch, + file: self.present_at, + }); + self.present_at += total; + match gpu::rgb(width, height, pitch, desc.Format.0, bytes) { + Some(rgb) => std::fs::write(r.folder.join(format!("frame-{}.png", self.frame)), crate::capture::png(width, height, &rgb))?, + None => r.problem("the presented format is not shown in a PNG"), + } + self.frame += 1; + Ok(()) + } + + /// Writes `frame.bin`. + fn finish(&mut self, r: &Recorder) -> Result<(), Fault> { + let mut resources: Vec = Vec::new(); + { + let names = lock(&r.names); + for res in read(&r.resources).values() { + let state = match (res.is_buffer(), res.late) { + (true, _) => vec![COMMON], + (_, true) => vec![res.made_in as u32], + _ => self.states.get(res.id).unwrap_or(vec![COMMON]), + }; + resources.push(wire::Resource { + id: res.id, + place: res.place.clone(), + desc: res.desc.clone(), + made_in: res.made_in, + clear: res.clear, + state, + idle: self.idle.contains(&res.id), + late: res.late, + name: names.get(&res.id).cloned().unwrap_or_default(), + }); + } + } + resources.sort_by_key(|res| res.id); + let mut heaps: Vec = { + let all = lock(&r.heaps); + let used: HashSet = + resources.iter().filter_map(|res| if let Place::Placed { heap, .. } = res.place { Some(heap) } else { None }).collect(); + used.iter().filter_map(|id| all.get(id).cloned()).collect() + }; + heaps.sort_by_key(|h| h.id); + // What the lists name. + let (mut psos, mut roots, mut signatures, mut queries) = (HashSet::new(), HashSet::new(), HashSet::new(), HashSet::new()); + for l in &self.lists { + for c in Cmd::all(l)? { + match c { + Cmd::Pipeline { pso } => drop(psos.insert(pso)), + Cmd::RootSignature { root, .. } => drop(roots.insert(root)), + Cmd::Indirect { signature, .. } => drop(signatures.insert(signature)), + Cmd::BeginQuery { heap, .. } | Cmd::EndQuery { heap, .. } | Cmd::ResolveQuery { heap, .. } => drop(queries.insert(heap)), + _ => {} + } + } + } + let pipelines: Vec = { + let all = lock(&r.pipelines); + let names = lock(&r.names); + let mut out: Vec = psos + .iter() + .filter_map(|id| { + let parts = all.get(id)?; + Some(wire::Pipeline { id: *id, parts: parts.to_vec(), name: names.get(id).cloned().unwrap_or_default() }) + }) + .collect(); + out.sort_by_key(|p| p.id); + out + }; + roots.extend(pipelines.iter().flat_map(|p| &p.parts).filter_map(|p| if let wire::Part::Root { root } = p { Some(*root) } else { None })); + let signatures: Vec = { + let all = lock(&r.signatures); + signatures.iter().filter_map(|id| all.get(id).cloned()).collect() + }; + roots.extend(signatures.iter().map(|s| s.root)); + roots.remove(&NONE); + let roots: Vec<(u32, wire::Blob)> = { + let all = lock(&r.roots); + roots.iter().filter_map(|id| Some((*id, wire::Blob(all.get(id)?.to_vec())))).collect() + }; + for ((what, before), (_, now)) in self.calls.iter().zip(not_recorded_calls()) { + if now > *before { + r.problem_times(what, now - before); + } + } + let (adapter, vendor, device) = gpu::adapter(&self.worker.device); + let mut notes = r.problems(); + let bytes: u64 = self.contents.iter().filter(|c| c.file != ZERO).map(|c| c.len).sum(); + notes.push(format!( + "{} submissions, {} lists, {} resources, {} pipelines; {} MB of the card's memory, {} MB of changes by the CPU; {:.1} s: {}", + self.submits.len(), + self.lists.len(), + resources.len(), + pipelines.len(), + bytes >> 20, + self.delta_at.load(Ordering::Relaxed) >> 20, + self.began.elapsed().as_secs_f64(), + self.took.iter().map(|(what, d)| format!("{what} {:.1} s", d.as_secs_f64())).collect::>().join(", ") + )); + for n in ¬es { + tracing::info!("frame recorder: {n}"); + } + let frame = wire::Frame { + adapter, + vendor, + device, + notes: notes.clone(), + heaps, + resources, + roots, + codes: lock(&r.codes).all.clone(), + pipelines, + signatures, + descriptor_heaps: self + .heaps + .iter() + .map(|(h, runs)| wire::DescriptorHeap { id: h.id, kind: h.kind, count: h.count, flags: h.flags, runs: runs.clone() }) + .collect(), + query_heaps: { + let all = lock(&r.queries); + queries.iter().filter_map(|id| all.get(id).cloned()).collect() + }, + lists: self + .lists + .iter() + .map(|l| wire::List { kind: D3D12_COMMAND_LIST_TYPE_DIRECT.0, commands: wire::Blob(l.to_vec()) }) + .collect(), + submits: std::mem::take(&mut self.submits), + contents: std::mem::take(&mut self.contents), + presents: std::mem::take(&mut self.presents), + }; + frame.write(&r.folder.join("frame.bin"))?; + std::fs::write(r.folder.join("notes.txt"), notes.join("\n"))?; + tracing::info!(folder = %r.folder.display(), "frame recorder: the frame is captured"); + Ok(()) + } +} + +/// A part of a resource in a read-back buffer, `at` bytes in. +struct Piece { + res: Arc, + first: u64, + count: u32, + len: u64, + at: u64, +} + +/// Records the copies of `pieces` into `to`. Textures are moved to a state +/// they can be copied from and back. +fn copy_out(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, states: &States, pieces: &[Piece], to: &ID3D12Resource) { + let (mut before, mut after) = (Vec::new(), Vec::new()); + let mut seen = HashSet::new(); + for p in pieces.iter().filter(|p| !p.res.is_buffer()) { + if !seen.insert(p.res.id) { + continue; + } + let from = states.get(p.res.id).unwrap_or(vec![COMMON]); + // From the common state a texture is promoted by the copy. + let to: Vec = from.iter().map(|&s| if s == COMMON || s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect(); + gpu::moves(&p.res.object(), &from, &to, &mut before); + gpu::moves(&p.res.object(), &to, &from, &mut after); + } + // SAFETY: an open list; live resources. + unsafe { + if !before.is_empty() { + list.ResourceBarrier(&before); + } + for p in pieces { + let object = p.res.object(); + if p.res.is_buffer() { + list.CopyBufferRegion(to, p.at, &*object, p.first, p.len); + continue; + } + let (all, _) = gpu::footprints(device, &gpu::to_desc(&p.res.desc), p.first as u32, p.count); + for (i, mut f) in all.into_iter().enumerate() { + f.Offset += p.at; + list.CopyTextureRegion(&gpu::placed_location(to, f), 0, 0, 0, &gpu::sub_location(&object, p.first as u32 + i as u32), None); + } + } + if !after.is_empty() { + list.ResourceBarrier(&after); + } + } +} + +/// Records the copy of a texture's subresource, in `state`, into `to`. +pub(super) fn read_sub( + list: &ID3D12GraphicsCommandList, + texture: &ID3D12Resource, + sub: u32, + state: u32, + to: &ID3D12Resource, + f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT, +) { + let there = state == COMMON || state & COPY_SOURCE != 0; + // SAFETY: an open list; live resources. + unsafe { + if !there { + list.ResourceBarrier(&[gpu::transition(texture, ALL, state, COPY_SOURCE)]); + } + list.CopyTextureRegion(&gpu::placed_location(to, f), 0, 0, 0, &gpu::sub_location(texture, sub), None); + if !there { + list.ResourceBarrier(&[gpu::transition(texture, ALL, COPY_SOURCE, state)]); + } + } +} + +/// A slot as it goes into the file: a constant buffer view's address as +/// buffer and offset. +fn resolved(r: &Recorder, mut s: Slot) -> Slot { + if s.kind == slot::CBV && s.described != 0 { + match r.va(s.address()) { + Va::At { res, offset } => { + s.res = res; + s.set_address(offset); + } + Va::Null {} => {} + Va::Unknown { .. } => { + // Its buffer is gone: nothing may read it. + s = Slot { kind: slot::CBV, ..Slot::EMPTY }; + } + } + } + s +} + +/// The slots as runs of equal ones, empty ones left out. +fn runs_of(r: &Recorder, all: &[Slot]) -> Vec<(u32, u32, Slot)> { + let mut runs: Vec<(u32, u32, Slot)> = Vec::new(); + for (i, s) in all.iter().enumerate() { + if s.kind == slot::EMPTY { + continue; + } + match runs.last_mut() { + Some((first, n, same)) if *first + *n == i as u32 && same == s => *n += 1, + _ => runs.push((i as u32, 1, *s)), + } + } + for run in &mut runs { + run.2 = resolved(r, run.2); + } + runs +} + +/// Whether all bytes are zero. +fn zero(bytes: &[u8]) -> bool { + // SAFETY: any bytes are a number. + let (a, b, c) = unsafe { bytes.align_to::() }; + a.iter().chain(c).all(|&x| x == 0) && b.iter().all(|&x| x == 0) +} + +fn write_at(file: &File, mut bytes: &[u8], mut at: u64) -> std::io::Result<()> { + while !bytes.is_empty() { + let n = file.seek_write(bytes, at)?; + if n == 0 { + return Err(std::io::ErrorKind::WriteZero.into()); + } + bytes = &bytes[n..]; + at += n as u64; + } + Ok(()) +} + +/// Compares `len` bytes at `live` with those at `kept`, page by page, brings +/// the changed ones in `kept` up to date, and answers their runs. +/// +/// # Safety +/// Both are `len` bytes; `kept` is the caller's alone. +unsafe fn changed_runs(live: *const u8, kept: *mut u8, len: usize) -> Vec<(usize, usize)> { + let mut runs: Vec<(usize, usize)> = Vec::new(); + let mut at = 0; + while at < len { + let n = PAGE.min(len - at); + // SAFETY: the caller's. + unsafe { + let same = std::slice::from_raw_parts(live.add(at), n) == std::slice::from_raw_parts(kept.add(at), n); + if !same { + std::ptr::copy_nonoverlapping(live.add(at), kept.add(at), n); + match runs.last_mut() { + Some(last) if last.1 == at => last.1 = at + n, + _ => runs.push((at, at + n)), + } + } + } + at += n; + } + runs +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn changes_are_found_by_page() { + let mut live = vec![0u8; 5 * PAGE + 100]; + let mut kept = live.clone(); + let find = |live: &[u8], kept: &mut [u8]| { + // SAFETY: two arrays of one length. + unsafe { changed_runs(live.as_ptr(), kept.as_mut_ptr(), live.len()) } + }; + assert!(find(&live, &mut kept).is_empty()); + live[PAGE + 5] = 1; + live[2 * PAGE] = 2; + live[5 * PAGE + 99] = 3; + assert_eq!(find(&live, &mut kept), [(PAGE, 3 * PAGE), (5 * PAGE, 5 * PAGE + 100)]); + assert_eq!(live, kept); + assert!(find(&live, &mut kept).is_empty()); + } + + #[test] + fn zeros() { + assert!(zero(&[])); + assert!(zero(&[0; 1001])); + for i in [0, 7, 500, 1000] { + let mut b = [0u8; 1001]; + b[i] = 1; + assert!(!zero(&b)); + } + } +} diff --git a/crates/victory-gpu/src/replay/states.rs b/crates/victory-gpu/src/replay/states.rs new file mode 100644 index 0000000..c159423 --- /dev/null +++ b/crates/victory-gpu/src/replay/states.rs @@ -0,0 +1,192 @@ +//! The states textures are in, as lists that ran left them: from the +//! barriers, the copies that promote a texture out of the common state, and +//! the decay at the end of a submission. Buffers are in the common state +//! between submissions, always, and are not kept here. + +use std::collections::HashMap; + +use super::wire::{ALL, Barrier, Cmd, Loc}; + +pub const COMMON: u32 = 0; +pub const RENDER_TARGET: u32 = 0x4; +pub const UNORDERED_ACCESS: u32 = 0x8; +pub const DEPTH_WRITE: u32 = 0x10; +pub const COPY_DEST: u32 = 0x400; +pub const COPY_SOURCE: u32 = 0x800; +pub const RESOLVE_DEST: u32 = 0x1000; + +/// A change of state a list makes, to apply when it runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Change { + pub res: u32, + pub sub: u32, + pub after: u32, + /// A copy into it: it is in the copy-destination state afterwards if it + /// was in the common state, else as it was. + pub promoted: bool, + /// An aliasing barrier made it the one in use. + pub alias: bool, +} + +#[derive(Clone, Debug)] +struct One { + subs: u32, + /// Decays to the common state after each submission. + decays: bool, + all: u32, + each: Vec, +} + +/// The states of textures, by id. +#[derive(Clone, Debug, Default)] +pub struct States { + map: HashMap, + touched: Vec, + /// When a placed resource was last the one in use (made, or named by an + /// aliasing barrier), by id; higher is later. + pub used: HashMap, + clock: u64, +} + +impl States { + /// A texture of `subs` subresources starts in `state`. + pub fn add(&mut self, res: u32, subs: u32, state: u32, decays: bool) { + self.map.insert(res, One { subs: subs.max(1), decays, all: state, each: Vec::new() }); + } + + /// A placed resource is the one in use now. + pub fn in_use(&mut self, res: u32) { + self.clock += 1; + self.used.insert(res, self.clock); + } + + pub fn remove(&mut self, res: u32) { + self.map.remove(&res); + self.used.remove(&res); + } + + /// One state, or one for each subresource. + pub fn get(&self, res: u32) -> Option> { + let one = self.map.get(&res)?; + Some(if one.each.is_empty() { vec![one.all] } else { one.each.clone() }) + } + + pub fn change(&mut self, c: &Change) { + if c.alias { + self.in_use(c.res); + return; + } + let Some(one) = self.map.get_mut(&c.res) else { + return; + }; + let new = |old: u32| match (c.promoted, old) { + (true, COMMON) => COPY_DEST, + (true, old) => old, + (false, _) => c.after, + }; + if c.sub == ALL || one.subs == 1 { + one.all = new(one.all); + if c.promoted { + one.each.iter_mut().for_each(|s| *s = new(*s)); + } else { + one.each.clear(); + } + } else if c.sub < one.subs { + if one.each.is_empty() { + one.each = vec![one.all; one.subs as usize]; + } + let s = &mut one.each[c.sub as usize]; + *s = new(*s); + if one.each.iter().all(|s| *s == one.each[0]) { + one.all = one.each[0]; + one.each.clear(); + } + } + if one.decays { + self.touched.push(c.res); + } + } + + /// The end of a submission (one `ExecuteCommandLists`). + pub fn decay(&mut self) { + for res in std::mem::take(&mut self.touched) { + if let Some(one) = self.map.get_mut(&res) { + one.all = COMMON; + one.each.clear(); + } + } + } +} + +/// The changes a command makes. +pub fn changes(cmd: &Cmd, out: &mut Vec) { + let promoted = |res, sub| Change { res, sub, after: COPY_DEST, promoted: true, alias: false }; + match cmd { + Cmd::Barriers { all } => { + for b in all { + match *b { + // The first half of a split barrier changes nothing yet. + Barrier::Transition { flags, res, sub, after, .. } if flags & 1 == 0 => { + out.push(Change { res, sub, after: after as u32, promoted: false, alias: false }); + } + Barrier::Alias { after, .. } if after != 0 => { + out.push(Change { res: after, sub: ALL, after: 0, promoted: false, alias: true }); + } + _ => {} + } + } + } + Cmd::CopyTexture { dst: Loc::Sub { res, sub }, .. } => out.push(promoted(*res, *sub)), + Cmd::CopyResource { dst, .. } => out.push(promoted(*dst, ALL)), + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn set(res: u32, sub: u32, after: u32) -> Change { + Change { res, sub, after, promoted: false, alias: false } + } + + #[test] + fn states_are_followed() { + let mut s = States::default(); + s.add(1, 4, COPY_DEST, false); + s.add(2, 1, COMMON, false); + s.add(3, 2, COMMON, true); + assert_eq!(s.get(1), Some(vec![COPY_DEST])); + s.change(&set(1, 2, 0x80)); + assert_eq!(s.get(1), Some(vec![COPY_DEST, COPY_DEST, 0x80, COPY_DEST])); + for sub in [0, 1, 3] { + s.change(&set(1, sub, 0x80)); + } + assert_eq!(s.get(1), Some(vec![0x80]), "equal states are one again"); + // A copy into a texture in the common state leaves it a copy + // destination; one into a texture in another state changes nothing. + let copy = |res| Change { res, sub: ALL, after: COPY_DEST, promoted: true, alias: false }; + s.change(©(2)); + s.change(©(1)); + s.decay(); + assert_eq!(s.get(2), Some(vec![COPY_DEST])); + assert_eq!(s.get(1), Some(vec![0x80])); + // Simultaneous access decays. + s.change(&set(3, 1, UNORDERED_ACCESS)); + assert_eq!(s.get(3), Some(vec![COMMON, UNORDERED_ACCESS])); + s.decay(); + assert_eq!(s.get(3), Some(vec![COMMON])); + s.remove(3); + assert_eq!(s.get(3), None); + } + + #[test] + fn commands_change_states() { + let mut out = Vec::new(); + let t = |flags| Barrier::Transition { flags, res: 1, sub: 0, before: 4, after: 8 }; + changes(&Cmd::Barriers { all: vec![t(1), t(2), Barrier::Alias { flags: 0, before: 3, after: 4 }, Barrier::Uav { flags: 0, res: 1 }] }, &mut out); + assert_eq!(out.len(), 2); + assert_eq!(out[0], set(1, 0, 8)); + assert!(out[1].alias && out[1].res == 4); + } +} diff --git a/crates/victory-gpu/src/replay/wire.rs b/crates/victory-gpu/src/replay/wire.rs new file mode 100644 index 0000000..b82667f --- /dev/null +++ b/crates/victory-gpu/src/replay/wire.rs @@ -0,0 +1,741 @@ +//! What a capture holds and how it is written: plain little-endian bytes, +//! fields in order. Read on the machine that wrote it; nothing here is kept +//! compatible between versions beyond the number in [`VERSION`]. + +/// Changes with every change of the layout. +pub const VERSION: u32 = 1; +/// The first bytes of `frame.bin`. +pub const MAGIC: [u8; 8] = *b"VICFRAME"; + +/// Why bytes could not be read back. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Bad(pub &'static str); + +impl std::fmt::Display for Bad { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "the capture cannot be read: {}", self.0) + } +} + +impl std::error::Error for Bad {} + +/// Bytes being read. +pub struct Dec<'a> { + pub bytes: &'a [u8], +} + +impl<'a> Dec<'a> { + pub fn new(bytes: &'a [u8]) -> Self { + Dec { bytes } + } + + pub fn take(&mut self, n: usize) -> Result<&'a [u8], Bad> { + if self.bytes.len() < n { + return Err(Bad("it ends too early")); + } + let (head, tail) = self.bytes.split_at(n); + self.bytes = tail; + Ok(head) + } +} + +/// A value that can be written and read back. +pub trait Wire: Sized { + fn put(&self, out: &mut Vec); + fn get(from: &mut Dec) -> Result; +} + +macro_rules! numbers { + ($($t:ty),*) => {$( + impl Wire for $t { + fn put(&self, out: &mut Vec) { + out.extend_from_slice(&self.to_le_bytes()); + } + fn get(from: &mut Dec) -> Result { + let bytes = from.take(size_of::<$t>())?; + Ok(<$t>::from_le_bytes(bytes.try_into().map_err(|_| Bad("a number"))?)) + } + } + )*}; +} +numbers!(u8, u16, u32, i32, u64, f32); + +impl Wire for bool { + fn put(&self, out: &mut Vec) { + out.push(u8::from(*self)); + } + fn get(from: &mut Dec) -> Result { + Ok(u8::get(from)? != 0) + } +} + +impl Wire for Vec { + fn put(&self, out: &mut Vec) { + (self.len() as u32).put(out); + for x in self { + x.put(out); + } + } + fn get(from: &mut Dec) -> Result { + let n = u32::get(from)? as usize; + // At least a byte each: a wild count is refused, not allocated. + if n > from.bytes.len() { + return Err(Bad("a list longer than the file")); + } + (0..n).map(|_| T::get(from)).collect() + } +} + +impl Wire for Option { + fn put(&self, out: &mut Vec) { + self.is_some().put(out); + if let Some(x) = self { + x.put(out); + } + } + fn get(from: &mut Dec) -> Result { + Ok(if bool::get(from)? { Some(T::get(from)?) } else { None }) + } +} + +impl Wire for [T; N] { + fn put(&self, out: &mut Vec) { + for x in self { + x.put(out); + } + } + fn get(from: &mut Dec) -> Result { + let mut all = [T::default(); N]; + for x in &mut all { + *x = T::get(from)?; + } + Ok(all) + } +} + +impl Wire for String { + fn put(&self, out: &mut Vec) { + (self.len() as u32).put(out); + out.extend_from_slice(self.as_bytes()); + } + fn get(from: &mut Dec) -> Result { + let n = u32::get(from)? as usize; + String::from_utf8(from.take(n)?.to_vec()).map_err(|_| Bad("a name that is not text")) + } +} + +/// Bytes copied whole. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct Blob(pub Vec); + +impl Wire for Blob { + fn put(&self, out: &mut Vec) { + (self.0.len() as u64).put(out); + out.extend_from_slice(&self.0); + } + fn get(from: &mut Dec) -> Result { + let n = u64::get(from)? as usize; + Ok(Blob(from.take(n)?.to_vec())) + } +} + +macro_rules! tuples { + ($($t:ident $i:tt),*) => { + impl<$($t: Wire),*> Wire for ($($t,)*) { + fn put(&self, out: &mut Vec) { + $(self.$i.put(out);)* + } + fn get(from: &mut Dec) -> Result { + Ok(($($t::get(from)?,)*)) + } + } + }; +} +tuples!(A 0, B 1); +tuples!(A 0, B 1, C 2); + +macro_rules! wire_struct { + ($(#[$meta:meta])* $name:ident { $($(#[$fmeta:meta])* $f:ident : $t:ty),* $(,)? }) => { + $(#[$meta])* + #[derive(Clone, Debug, PartialEq)] + pub struct $name { $($(#[$fmeta])* pub $f: $t),* } + impl Wire for $name { + fn put(&self, out: &mut Vec) { + $(self.$f.put(out);)* + } + fn get(from: &mut Dec) -> Result { + Ok($name { $($f: <$t>::get(from)?),* }) + } + } + }; +} + +macro_rules! wire_enum { + ($(#[$meta:meta])* $name:ident { $($(#[$vmeta:meta])* $tag:literal $var:ident { $($f:ident : $t:ty),* $(,)? }),* $(,)? }) => { + $(#[$meta])* + #[derive(Clone, Debug, PartialEq)] + pub enum $name { $($(#[$vmeta])* $var { $($f: $t),* }),* } + impl Wire for $name { + fn put(&self, out: &mut Vec) { + match self { + $($name::$var { $($f),* } => { + out.push($tag); + $($f.put(out);)* + })* + } + } + fn get(from: &mut Dec) -> Result { + Ok(match u8::get(from)? { + $($tag => $name::$var { $($f: <$t>::get(from)?),* },)* + _ => return Err(Bad("a kind that does not exist")), + }) + } + } + }; +} + +/// No object. +pub const NONE: u32 = 0; +/// All subresources. +pub const ALL: u32 = u32::MAX; + +/// What a descriptor slot holds: the view last made in it. `res` and +/// `counter` are object ids; `desc` the view's description as D3D12 lays it +/// out (a sampler's is the longest: 52 bytes). In a capture file a constant +/// buffer view's buffer is in `res` and, in place of the address, the +/// offset in it. +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Slot { + pub kind: u8, + /// Whether a description was given. + pub described: u8, + pub pad: u16, + pub res: u32, + pub counter: u32, + pub desc: [u8; 52], +} + +/// Kinds of [`Slot`]. +pub mod slot { + pub const EMPTY: u8 = 0; + pub const CBV: u8 = 1; + pub const SRV: u8 = 2; + pub const UAV: u8 = 3; + pub const SAMPLER: u8 = 4; + pub const RTV: u8 = 5; + pub const DSV: u8 = 6; +} + +impl Slot { + pub const EMPTY: Slot = Slot { kind: slot::EMPTY, described: 0, pad: 0, res: NONE, counter: NONE, desc: [0; 52] }; + + /// A slot of `kind` with the description at `desc` (`size` bytes), if any. + /// + /// # Safety + /// `desc` is null or points at a description of `size` bytes. + pub unsafe fn new(kind: u8, res: u32, counter: u32, desc: *const u8, size: usize) -> Slot { + let mut s = Slot { kind, res, counter, ..Slot::EMPTY }; + if !desc.is_null() { + s.described = 1; + // SAFETY: the caller's description, at most 52 bytes of it. + unsafe { std::ptr::copy_nonoverlapping(desc, s.desc.as_mut_ptr(), size.min(52)) }; + } + s + } + + /// A constant buffer view's address (or its offset, in a file). + pub fn address(&self) -> u64 { + u64::from_le_bytes([ + self.desc[0], self.desc[1], self.desc[2], self.desc[3], self.desc[4], self.desc[5], self.desc[6], self.desc[7], + ]) + } + + pub fn set_address(&mut self, address: u64) { + self.desc[..8].copy_from_slice(&address.to_le_bytes()); + } +} + +impl Wire for Slot { + fn put(&self, out: &mut Vec) { + out.push(self.kind); + out.push(self.described); + self.res.put(out); + self.counter.put(out); + // Most descriptions are 40 bytes or less. + let n = self.desc.iter().rposition(|&b| b != 0).map_or(0, |i| i + 1); + out.push(n as u8); + out.extend_from_slice(&self.desc[..n]); + } + fn get(from: &mut Dec) -> Result { + let (kind, described) = (u8::get(from)?, u8::get(from)?); + let (res, counter) = (u32::get(from)?, u32::get(from)?); + let n = u8::get(from)? as usize; + if n > 52 { + return Err(Bad("a view's description")); + } + let mut desc = [0; 52]; + desc[..n].copy_from_slice(from.take(n)?); + Ok(Slot { kind, described, pad: 0, res, counter, desc }) + } +} + +wire_enum! { + /// A GPU address. + Va { + 0 Null {}, + 1 At { res: u32, offset: u64 }, + /// In no buffer the recorder knows. + 2 Unknown { address: u64 }, + } +} + +wire_enum! { + /// One side of a texture copy. + Loc { + 0 Sub { res: u32, sub: u32 }, + 1 Placed { res: u32, offset: u64, format: i32, size: [u32; 3], pitch: u32 }, + } +} + +wire_enum! { + /// One barrier of a `ResourceBarrier` call. + Barrier { + 0 Transition { flags: i32, res: u32, sub: u32, before: i32, after: i32 }, + 1 Alias { flags: i32, before: u32, after: u32 }, + 2 Uav { flags: i32, res: u32 }, + } +} + +wire_enum! { + /// A command of a list, objects by id, views by what they hold. + Cmd { + 1 Draw { vertices: u32, instances: u32, first: u32, first_instance: u32 }, + 2 DrawIndexed { indices: u32, instances: u32, first: u32, base: i32, first_instance: u32 }, + 3 Dispatch { groups: [u32; 3] }, + 4 DispatchMesh { groups: [u32; 3] }, + 5 CopyBuffer { dst: u32, dst_at: u64, src: u32, src_at: u64, len: u64 }, + 6 CopyTexture { dst: Loc, at: [u32; 3], src: Loc, part: Option<[u32; 6]> }, + 7 CopyResource { dst: u32, src: u32 }, + 8 Resolve { dst: u32, dst_sub: u32, src: u32, src_sub: u32, format: i32 }, + 9 ResolveRegion { dst: u32, dst_sub: u32, at: [u32; 2], src: u32, src_sub: u32, part: Option<[i32; 4]>, format: i32, mode: i32 }, + 10 Topology { kind: i32 }, + 11 Viewports { all: Vec<[f32; 6]> }, + 12 Scissors { all: Vec<[i32; 4]> }, + 13 BlendFactor { factor: Option<[f32; 4]> }, + 14 StencilRef { value: u32 }, + 15 Pipeline { pso: u32 }, + 16 Barriers { all: Vec }, + 17 Heaps { heaps: Vec }, + 18 RootSignature { graphics: bool, root: u32 }, + 19 Table { graphics: bool, param: u32, heap: u32, slot: u32 }, + 20 Constants { graphics: bool, param: u32, offset: u32, values: Vec }, + 21 RootView { graphics: bool, kind: u8, param: u32, va: Va }, + 22 IndexBuffer { view: Option<(Va, u32, i32)> }, + 23 VertexBuffers { start: u32, count: u32, views: Option> }, + 24 Targets { colors: Vec, depth: Option }, + 25 ClearDepth { view: Slot, flags: i32, depth: f32, stencil: u8, rects: Vec<[i32; 4]> }, + 26 ClearTarget { view: Slot, color: [f32; 4], rects: Vec<[i32; 4]> }, + 27 Discard { res: u32, rects: Vec<[i32; 4]>, subs: Option<[u32; 2]> }, + 28 BeginQuery { heap: u32, kind: i32, index: u32 }, + 29 EndQuery { heap: u32, kind: i32, index: u32 }, + 30 ResolveQuery { heap: u32, kind: i32, first: u32, count: u32, dst: u32, at: u64 }, + 31 Indirect { signature: u32, most: u32, args: u32, at: u64, count: u32, count_at: u64 }, + 32 WriteImmediate { all: Vec<(Va, u32, i32)> }, + 33 DepthBounds { min: f32, max: f32 }, + } +} + +/// The highest kind number of [`Cmd`]. +#[cfg(test)] +const LAST_CMD: u8 = 33; + +impl Cmd { + /// The commands of a list's bytes. + pub fn all(bytes: &[u8]) -> Result, Bad> { + let mut from = Dec::new(bytes); + let mut all = Vec::new(); + while !from.bytes.is_empty() { + all.push(Cmd::get(&mut from)?); + } + Ok(all) + } + + /// Whether it makes the card work (and is timed on its own). + pub fn works(&self) -> bool { + self.runs_shaders() + || matches!( + self, + Cmd::CopyBuffer { .. } + | Cmd::CopyTexture { .. } + | Cmd::CopyResource { .. } + | Cmd::Resolve { .. } + | Cmd::ResolveRegion { .. } + | Cmd::ClearDepth { .. } + | Cmd::ClearTarget { .. } + | Cmd::Discard { .. } + | Cmd::ResolveQuery { .. } + | Cmd::WriteImmediate { .. } + ) + } + + /// Whether it runs the pipeline bound. + pub fn runs_shaders(&self) -> bool { + matches!( + self, + Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::Dispatch { .. } | Cmd::DispatchMesh { .. } | Cmd::Indirect { .. } + ) + } +} + +wire_struct! { + HeapProps { kind: i32, cpu: i32, pool: i32 } +} + +wire_struct! { + /// A resource description (`D3D12_RESOURCE_DESC`). + Desc { + dimension: i32, + alignment: u64, + width: u64, + height: u32, + depth: u16, + mips: u16, + format: i32, + samples: [u32; 2], + layout: i32, + flags: i32, + } +} + +wire_struct! { + Heap { id: u32, size: u64, props: HeapProps, alignment: u64, flags: i32 } +} + +wire_enum! { + /// How a resource got its memory. + Place { + 0 Committed { props: HeapProps, flags: i32 }, + 1 Placed { heap: u32, offset: u64 }, + /// A swap chain's buffer. + 2 BackBuffer {}, + } +} + +wire_struct! { + Resource { + id: u32, + place: Place, + desc: Desc, + /// The state it was made in. + made_in: i32, + clear: Option<[u32; 5]>, + /// Its states at the start of the frame: one, or one for each + /// subresource. Buffers start in the common state. + state: Vec, + /// Not the one in use where placed resources overlap: its contents + /// are not in the capture. + idle: bool, + /// Made after the frame started. + late: bool, + name: String, + } +} + +wire_enum! { + /// A part of a pipeline description. + Part { + 0 Root { root: u32 }, + /// Shader code: the number of its blob ([`Frame::codes`]). + 1 Code { kind: i32, blob: u32 }, + /// Plain data. + 2 Plain { kind: i32, data: Blob }, + 3 Layout { elements: Vec<(String, [u32; 6])> }, + } +} + +wire_struct! { + Pipeline { id: u32, parts: Vec, name: String } +} + +wire_struct! { + /// Bytes in `shaders.bin`. + Code { at: u64, len: u64, hash: [u8; 32] } +} + +wire_struct! { + Signature { id: u32, stride: u32, args: Vec<[u32; 4]>, root: u32 } +} + +wire_struct! { + DescriptorHeap { id: u32, kind: i32, count: u32, flags: i32, runs: Vec<(u32, u32, Slot)> } +} + +wire_struct! { + QueryHeap { id: u32, kind: i32, count: u32 } +} + +wire_struct! { + List { kind: i32, commands: Blob } +} + +wire_struct! { + /// Bytes the CPU (or an earlier submission) put into a buffer the CPU + /// sees, by the time a submission went to the card (in `deltas.bin`). + Delta { res: u32, at: u64, len: u64, file: u64 } +} + +wire_struct! { + Submit { + frame: u32, + /// Lists by number; [`MISSING`] for one that was not recorded. + lists: Vec, + deltas: Vec, + /// Descriptor slots written since the submission before. + views: Vec<(u32, u32, Slot)>, + } +} + +/// In [`Submit::lists`]. +pub const MISSING: u32 = u32::MAX; + +wire_struct! { + /// Contents at the start of the frame, in `contents.bin`: of a buffer, + /// `len` bytes from `first`; of a texture, `count` subresources from + /// `first`, laid out as `GetCopyableFootprints` lays them out. + Content { + res: u32, + first: u64, + count: u32, + len: u64, + /// Where in the file; [`ZERO`] if all bytes are zero. + file: u64, + } +} + +/// In [`Content::file`]. +pub const ZERO: u64 = u64::MAX; + +wire_struct! { + /// A frame's picture: a texture as it was when presented (in + /// `present.bin`). + Present { submits: u32, res: u32, width: u32, height: u32, format: i32, pitch: u32, file: u64 } +} + +wire_struct! { + Frame { + adapter: String, + vendor: u32, + device: u32, + /// What the recorder could not record, and how it went. + notes: Vec, + heaps: Vec, + resources: Vec, + roots: Vec<(u32, Blob)>, + codes: Vec, + pipelines: Vec, + signatures: Vec, + descriptor_heaps: Vec, + query_heaps: Vec, + lists: Vec, + submits: Vec, + contents: Vec, + presents: Vec, + } +} + +impl Frame { + pub fn write(&self, path: &std::path::Path) -> std::io::Result<()> { + let mut out = MAGIC.to_vec(); + VERSION.put(&mut out); + self.put(&mut out); + std::fs::write(path, out) + } + + pub fn read(path: &std::path::Path) -> anyhow::Result { + let bytes = std::fs::read(path)?; + let mut from = Dec::new(&bytes); + if from.take(8)? != MAGIC { + return Err(Bad("it is not a frame").into()); + } + if u32::get(&mut from)? != VERSION { + return Err(Bad("it was made by another version of the recorder").into()); + } + let frame = Frame::get(&mut from)?; + if !from.bytes.is_empty() { + return Err(Bad("bytes after its end").into()); + } + Ok(frame) + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + fn there_and_back(x: &T) { + let mut out = Vec::new(); + x.put(&mut out); + let mut from = Dec::new(&out); + assert_eq!(&T::get(&mut from).unwrap(), x); + assert!(from.bytes.is_empty(), "bytes left over"); + // Cut anywhere, it is refused and does not panic. + for n in 0..out.len() { + assert!(T::get(&mut Dec::new(&out[..n])).is_err()); + } + } + + fn view() -> Slot { + let mut desc = [0; 52]; + desc[3] = 7; + desc[51] = 9; + Slot { kind: slot::SAMPLER, described: 1, pad: 0, res: 4, counter: 5, desc } + } + + fn at() -> Va { + Va::At { res: 3, offset: 1 << 40 } + } + + pub(crate) fn every_command() -> Vec { + let placed = Loc::Placed { res: 5, offset: 512, format: 28, size: [4, 5, 6], pitch: 256 }; + let rects = vec![[1, 2, 3, 4]]; + vec![ + Cmd::Draw { vertices: 1, instances: 2, first: 3, first_instance: 4 }, + Cmd::DrawIndexed { indices: 1, instances: 2, first: 3, base: -4, first_instance: 5 }, + Cmd::Dispatch { groups: [1, 2, 3] }, + Cmd::DispatchMesh { groups: [4, 5, 6] }, + Cmd::CopyBuffer { dst: 1, dst_at: 2, src: 3, src_at: 4, len: 5 }, + Cmd::CopyTexture { dst: Loc::Sub { res: 1, sub: 2 }, at: [3, 4, 5], src: placed, part: Some([1, 2, 3, 4, 5, 6]) }, + Cmd::CopyResource { dst: 1, src: 2 }, + Cmd::Resolve { dst: 1, dst_sub: 2, src: 3, src_sub: 4, format: 28 }, + Cmd::ResolveRegion { dst: 1, dst_sub: 2, at: [3, 4], src: 5, src_sub: 6, part: Some([0, 1, 2, 3]), format: 28, mode: 1 }, + Cmd::Topology { kind: 4 }, + Cmd::Viewports { all: vec![[0.0, 1.0, 2.0, 3.0, 0.5, 1.0]; 2] }, + Cmd::Scissors { all: rects.clone() }, + Cmd::BlendFactor { factor: Some([0.1, 0.2, 0.3, 0.4]) }, + Cmd::BlendFactor { factor: None }, + Cmd::StencilRef { value: 255 }, + Cmd::Pipeline { pso: 9 }, + Cmd::Barriers { + all: vec![ + Barrier::Transition { flags: 1, res: 2, sub: ALL, before: 4, after: 8 }, + Barrier::Alias { flags: 0, before: 1, after: 2 }, + Barrier::Uav { flags: 0, res: 0 }, + ], + }, + Cmd::Heaps { heaps: vec![1, 2] }, + Cmd::RootSignature { graphics: true, root: 3 }, + Cmd::Table { graphics: false, param: 1, heap: 2, slot: 1 << 20 }, + Cmd::Constants { graphics: true, param: 1, offset: 2, values: vec![3, 4, 5] }, + Cmd::RootView { graphics: true, kind: slot::CBV, param: 1, va: at() }, + Cmd::IndexBuffer { view: Some((at(), 5, 42)) }, + Cmd::IndexBuffer { view: None }, + Cmd::VertexBuffers { start: 1, count: 1, views: Some(vec![(Va::Unknown { address: 5 }, 6, 7)]) }, + Cmd::VertexBuffers { start: 1, count: 3, views: None }, + Cmd::Targets { colors: vec![view(); 3], depth: Some(view()) }, + Cmd::ClearDepth { view: view(), flags: 3, depth: 0.5, stencil: 7, rects: rects.clone() }, + Cmd::ClearTarget { view: view(), color: [1.0, 2.0, 3.0, 4.0], rects: Vec::new() }, + Cmd::Discard { res: 1, rects, subs: Some([0, 2]) }, + Cmd::BeginQuery { heap: 1, kind: 0, index: 2 }, + Cmd::EndQuery { heap: 1, kind: 2, index: 3 }, + Cmd::ResolveQuery { heap: 1, kind: 2, first: 3, count: 4, dst: 5, at: 6 }, + Cmd::Indirect { signature: 1, most: 2, args: 3, at: 4, count: 5, count_at: 6 }, + Cmd::WriteImmediate { all: vec![(at(), 1, 2), (Va::Null {}, 3, 4)] }, + Cmd::DepthBounds { min: 0.25, max: 0.75 }, + ] + } + + #[test] + fn every_command_comes_back() { + let all = every_command(); + let mut bytes = Vec::new(); + for c in &all { + there_and_back(c); + c.put(&mut bytes); + } + assert_eq!(Cmd::all(&bytes).unwrap(), all); + assert!(Cmd::all(&[250]).is_err()); + // Every kind there is stands in the list above. + let kinds: std::collections::BTreeSet = all + .iter() + .map(|c| { + let mut out = Vec::new(); + c.put(&mut out); + out[0] + }) + .collect(); + assert_eq!(kinds.into_iter().collect::>(), (1..=LAST_CMD).collect::>()); + assert!(Cmd::all(&[LAST_CMD + 1]).is_err(), "a kind was added: bring LAST_CMD and the list above up to date"); + } + + #[test] + fn a_frame_comes_back() { + let props = HeapProps { kind: 4, cpu: 3, pool: 1 }; + let desc = Desc { + dimension: 3, + alignment: 65536, + width: 1 << 33, + height: 5, + depth: 6, + mips: 7, + format: 28, + samples: [1, 0], + layout: 1, + flags: 4, + }; + let resource = Resource { + id: 2, + place: Place::Placed { heap: 1, offset: 65536 }, + desc, + made_in: 4, + clear: Some([28, 1, 2, 3, 4]), + state: vec![1, 2, 3], + idle: false, + late: true, + name: "a texture".into(), + }; + let frame = Frame { + adapter: "a card".into(), + vendor: 0x1002, + device: 0x744c, + notes: vec!["nothing".into()], + heaps: vec![Heap { id: 1, size: 64 << 20, props: props.clone(), alignment: 65536, flags: 0x84 }], + resources: vec![ + resource.clone(), + Resource { place: Place::Committed { props, flags: 8 }, ..resource.clone() }, + Resource { place: Place::BackBuffer {}, clear: None, ..resource }, + ], + roots: vec![(3, Blob(vec![1, 2, 3]))], + codes: vec![Code { at: 1, len: 2, hash: [7; 32] }], + pipelines: vec![Pipeline { + id: 4, + parts: vec![ + Part::Root { root: 3 }, + Part::Code { kind: 25, blob: 0 }, + Part::Plain { kind: 8, data: Blob(vec![9; 20]) }, + Part::Layout { elements: vec![("POSITION".into(), [1, 2, 3, 4, 5, 6])] }, + ], + name: "a pipeline".into(), + }], + signatures: vec![Signature { id: 5, stride: 12, args: vec![[10, 0, 0, 0]], root: 0 }], + descriptor_heaps: vec![DescriptorHeap { id: 6, kind: 0, count: 10, flags: 1, runs: vec![(0, 9, Slot::EMPTY), (9, 1, view())] }], + query_heaps: vec![QueryHeap { id: 7, kind: 1, count: 8 }], + lists: vec![List { kind: 0, commands: Blob(vec![1, 2]) }], + submits: vec![Submit { + frame: 0, + lists: vec![0, MISSING], + deltas: vec![Delta { res: 2, at: 4096, len: 8192, file: 0 }], + views: vec![(6, 3, view())], + }], + contents: vec![Content { res: 2, first: 0, count: 3, len: 100, file: ZERO }], + presents: vec![Present { submits: 1, res: 2, width: 4, height: 5, format: 28, pitch: 256, file: 0 }], + }; + there_and_back(&frame); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("frame.bin"); + frame.write(&path).unwrap(); + assert_eq!(Frame::read(&path).unwrap(), frame); + std::fs::write(&path, b"VICFRAMEnothing at all").unwrap(); + assert!(Frame::read(&path).is_err()); + } +} diff --git a/crates/victory-gpu/tests/replay.rs b/crates/victory-gpu/tests/replay.rs new file mode 100644 index 0000000..e774e66 --- /dev/null +++ b/crates/victory-gpu/tests/replay.rs @@ -0,0 +1,909 @@ +//! The frame recorder and replayer on the PC's own adapter (skipped without +//! one): a small program with clears, indirect draws of textures picked from +//! a heap, compute, buffers the CPU changes between submissions, descriptors +//! replaced between them, and textures that share memory. It runs without +//! the recorder, then with it, then one frame of it is replayed; every +//! picture and buffer must be the same. +//! +//! `VICTORY_TEST_D3D_DEBUG=1` runs it under the debug layer. +#![cfg(all(windows, feature = "diagnostics"))] + +use std::mem::ManuallyDrop; + +use victory_gpu::replay::play::{self, Buffers, Options, Player}; +use victory_gpu::replay::record::{self, At, Settings}; +use windows::Win32::Foundation::{HANDLE, HWND, RECT}; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ID3DBlob}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::Graphics::Dxgi::*; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::Win32::UI::WindowsAndMessaging::*; +use windows::core::{Interface, PCSTR, s, w}; + +const SIZE: u32 = 128; + +const DRAW: &str = r#" +#define RS "RootConstants(num32BitConstants=2, b0), CBV(b1), DescriptorTable(SRV(t0, numDescriptors=unbounded)), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_POINT)" +cbuffer Pick : register(b0) { uint pick; uint pad; }; +cbuffer Place : register(b1) { float4 place; }; +Texture2D all[] : register(t0); +SamplerState point_sampler : register(s0); +struct V { float4 at : SV_Position; float2 uv : UV; }; +[RootSignature(RS)] +V vs(uint i : SV_VertexID) { + float2 c = float2(i & 1, (i >> 1) & 1); + if (i == 3) c = float2(1, 0); + if (i == 4) c = float2(0, 1); + if (i == 5) c = float2(1, 1); + V v; + v.uv = c; + v.at = float4(place.xy + c * place.zw, 0.5, 1); + return v; +} +float4 ps(V v) : SV_Target { return all[NonUniformResourceIndex(pick)].SampleLevel(point_sampler, v.uv, 0); } +"#; + +/// Writes the arguments of indirect draws (two records: six vertices, and +/// one far too many that the clamp cuts to none). +const ARGS: &str = r#" +#define RS "SRV(t0), UAV(u0)" +ByteAddressBuffer from : register(t0); +RWByteAddressBuffer args : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + args.Store4(0, uint4(from.Load(0), 1, 0, 0)); + args.Store4(16, uint4(4000000000u, 1, 0, 0)); +} +"#; + +/// The argument clamp's parameters, with a simple bound. +const CLAMP: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer C : register(b0) { uint kind; uint stride; uint records; uint args_offset; uint has_count; uint count_offset; }; +ByteAddressBuffer from : register(t0); +ByteAddressBuffer count : register(t1); +RWByteAddressBuffer to : register(u0); +RWByteAddressBuffer budget : register(u1); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= records) return; + uint4 a = from.Load4(args_offset + id.x * stride); + if (a.x > 1000) a.x = 0; + to.Store4(id.x * stride, a); + uint was; + budget.InterlockedAdd(0, a.x, was); +} +"#; + +/// Adds what the CPU gives to what was there, and writes it on. +const ADD: &str = r#" +#define RS "SRV(t0), DescriptorTable(UAV(u0)), UAV(u1)" +ByteAddressBuffer from : register(t0); +RWTexture2D image : register(u0); +RWByteAddressBuffer sum : register(u1); +[RootSignature(RS)] +[numthreads(8, 8, 1)] +void main(uint3 id : SV_DispatchThreadID) { + uint at = (id.y * 16 + id.x) * 4; + uint v = from.Load(at) + sum.Load(at) * 3; + sum.Store(at, v); + image[id.xy] = image[id.xy] + float4((v & 15) / 255.0, 0, 1 / 255.0, 1); +} +"#; + +struct Made { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +fn compile(source: &str, entry: PCSTR, target: PCSTR) -> Vec { + let (mut code, mut errors): (Option, Option) = (None, None); + // SAFETY: the source and names live through the call; the blobs' own + // bytes. + unsafe { + let r = D3DCompile(source.as_ptr().cast(), source.len(), None, None, None, entry, target, 1 << 20, 0, &mut code, Some(&mut errors)); + if r.is_err() { + let e = errors.unwrap(); + let text = std::slice::from_raw_parts(e.GetBufferPointer().cast::(), e.GetBufferSize()); + panic!("{}", String::from_utf8_lossy(text)); + } + let code = code.unwrap(); + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()).to_vec() + } +} + +fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE { + D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() } +} + +fn compute(device: &ID3D12Device, source: &str) -> Made { + let cs = compile(source, s!("main"), s!("cs_5_1")); + // SAFETY: plain creation. + unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, &cs).unwrap(); + let pso = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: code(&cs), + ..Default::default() + }) + .unwrap(); + Made { root, pso } + } +} + +fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + } +} + +fn texture_desc(size: u32, format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(size), + Height: size, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: flags, + ..Default::default() + } +} + +#[derive(Clone, Copy, PartialEq)] +enum In { + Card, + Upload, + Back, + /// The PC's memory, mapped, that shaders write too. + Shared, +} + +fn committed(device: &ID3D12Device, place: In, desc: &D3D12_RESOURCE_DESC, state: D3D12_RESOURCE_STATES) -> (ID3D12Resource, *mut u8) { + let heap = match place { + In::Card => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + In::Upload => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + In::Back => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + In::Shared => D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }, + }; + let mut made: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping. + unsafe { + device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, desc, state, None, &mut made).unwrap(); + let made = made.unwrap(); + if place != In::Card { + made.Map(0, None, Some(&mut data)).unwrap(); + } + (made, data.cast()) + } +} + +fn moved(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: a borrowed pointer never released. + pResource: unsafe { std::mem::transmute_copy(res) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + ..Default::default() + } +} + +fn uav_barrier() -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }), + }, + ..Default::default() + } +} + +fn aliased(before: &ID3D12Resource, after: &ID3D12Resource) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + // SAFETY: borrowed pointers never released. + pResourceBefore: unsafe { std::mem::transmute_copy(before) }, + // SAFETY: as above. + pResourceAfter: unsafe { std::mem::transmute_copy(after) }, + }), + }, + ..Default::default() + } +} + +const COMMON: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COMMON; +const TARGET: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_RENDER_TARGET; +const READ: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; +const UAV: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; +const TO: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_DEST; +const FROM: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_SOURCE; +const ARGUMENTS: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + +/// What the program ends with. +#[derive(PartialEq, Debug)] +struct Outcome { + picture: Vec, + image: Vec, + sum: Vec, + shared: Vec, +} + +struct Scene { + device: ID3D12Device, + queue: ID3D12CommandQueue, + fence: ID3D12Fence, + event: HANDLE, + value: u64, + lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>, + draw: Made, + args: Made, + clamp: Made, + add: Made, + signature: ID3D12CommandSignature, + views: ID3D12DescriptorHeap, + step: usize, + rtvs: ID3D12DescriptorHeap, + dsvs: ID3D12DescriptorHeap, + target: ID3D12Resource, + _depth: ID3D12Resource, + fixed: ID3D12Resource, + one: ID3D12Resource, + other: ID3D12Resource, + _heap: ID3D12Heap, + image: ID3D12Resource, + sum: ID3D12Resource, + arguments: ID3D12Resource, + scratch: ID3D12Resource, + budget: ID3D12Resource, + shared: (ID3D12Resource, *mut u8), + constants: (ID3D12Resource, *mut u8), + texels: (ID3D12Resource, *mut u8), + back: (ID3D12Resource, *mut u8), + swap: Option<(IDXGISwapChain3, HWND)>, +} + +impl Scene { + fn new(device: &ID3D12Device, window: bool) -> Scene { + // SAFETY: plain creation throughout. + unsafe { + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .unwrap(); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let lists = (0..3) + .map(|_| { + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + list.Close().unwrap(); + (allocator, list) + }) + .collect(); + let (vs, ps) = (compile(DRAW, s!("vs"), s!("vs_5_1")), compile(DRAW, s!("ps"), s!("ps_5_1"))); + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = 15; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: code(&vs), + PS: code(&ps), + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + DSVFormat: DXGI_FORMAT_D32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap(); + record::name(&pso, "a drawing pipeline"); + let draw = Made { root, pso }; + let clamp = compute(device, CLAMP); + record::name(&clamp.pso, play::CLAMP); + let argument = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, ..Default::default() }; + let mut signature: Option = None; + let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 16, NumArgumentDescs: 1, pArgumentDescs: &argument, NodeMask: 0 }; + device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature).unwrap(); + let heap = |kind, count, flags| -> ID3D12DescriptorHeap { + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: count, Flags: flags, NodeMask: 0 }).unwrap() + }; + let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5000, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE); + let rtvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); + let dsvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); + let rgba = DXGI_FORMAT_R8G8B8A8_UNORM; + let (target, _) = committed(device, In::Card, &texture_desc(SIZE, rgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), FROM); + let (depth, _) = committed( + device, + In::Card, + &texture_desc(SIZE, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), + D3D12_RESOURCE_STATE_DEPTH_WRITE, + ); + let (fixed, _) = committed(device, In::Card, &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE), TO); + let (image, _) = committed(device, In::Card, &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), UAV); + let mut memory: Option = None; + let desc = D3D12_HEAP_DESC { + SizeInBytes: 4 << 20, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + device.CreateHeap(&desc, &mut memory).unwrap(); + let memory = memory.unwrap(); + let placed = || { + let mut made: Option = None; + let d = texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE); + device.CreatePlacedResource(&memory, 65536, &d, TO, None, &mut made).unwrap(); + made.unwrap() + }; + // Two textures in one place. + let (one, other) = (placed(), placed()); + let uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + let card = |size| committed(device, In::Card, &buffer_desc(size, uav), COMMON).0; + let (sum, arguments, scratch, budget) = (card(1024), card(4096), card(4096), card(256)); + let shared = committed(device, In::Shared, &buffer_desc(70_000, uav), COMMON); + let constants = committed( + device, + In::Upload, + &buffer_desc(8192, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + ); + let texels = committed( + device, + In::Upload, + &buffer_desc(65536, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + ); + let back = committed(device, In::Back, &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE), TO); + for (r, n) in [(&sum, "sum"), (&image, "image"), (&target, "target"), (&shared.0, "shared"), (&one, "one"), (&other, "other")] { + record::name(r, n); + } + device.CreateRenderTargetView(&target, None, rtvs.GetCPUDescriptorHandleForHeapStart()); + device.CreateDepthStencilView(&depth, None, dsvs.GetCPUDescriptorHandleForHeapStart()); + let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let swap = window.then(|| swap_chain(&queue)); + let scene = Scene { + device: device.clone(), + queue, + fence, + event: CreateEventW(None, false, false, None).unwrap(), + value: 0, + lists, + draw, + args: compute(device, ARGS), + clamp, + add: compute(device, ADD), + signature: signature.unwrap(), + views, + step, + rtvs, + dsvs, + target, + _depth: depth, + fixed, + one, + other, + _heap: memory, + image, + sum, + arguments, + scratch, + budget, + shared, + constants, + texels, + back, + swap, + }; + // Null views everywhere, by copies of a slot made elsewhere. + let block = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); + let null = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: rgba, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() } }, + }; + let from = block.GetCPUDescriptorHandleForHeapStart(); + for i in 0..16 { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.ptr + i * step }; + device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&null), at); + } + for i in (0..4992).step_by(16) { + device.CopyDescriptorsSimple(16, scene.cpu(i), from, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + } + // The rest with the other copying method, in unlike pieces. + let to = [scene.cpu(4992), scene.cpu(4994)]; + let sources = [from, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.ptr + 4 * step }]; + device.CopyDescriptors( + 2, + to.as_ptr(), + Some([2u32, 6].as_ptr()), + 2, + sources.as_ptr(), + Some([4u32, 4].as_ptr()), + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + ); + scene.show(4001, &scene.other); + scene.show(4002, &scene.one); + device.CreateUnorderedAccessView(&scene.image, None::<&ID3D12Resource>, None, scene.cpu(7)); + scene + } + } + + fn cpu(&self, i: usize) -> D3D12_CPU_DESCRIPTOR_HANDLE { + // SAFETY: a slot of the heap. + let start = unsafe { self.views.GetCPUDescriptorHandleForHeapStart() }; + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + i * self.step } + } + + /// Slot `i` shows `texture`. + fn show(&self, i: usize, texture: &ID3D12Resource) { + // SAFETY: a slot of the heap and a live texture. + unsafe { self.device.CreateShaderResourceView(texture, None, self.cpu(i)) }; + } + + fn wait(&mut self) { + self.value += 1; + // SAFETY: our queue, fence and event. + unsafe { + self.queue.Signal(&self.fence, self.value).unwrap(); + self.fence.SetEventOnCompletion(self.value, self.event).unwrap(); + WaitForSingleObject(self.event, INFINITE); + self.device.GetDeviceRemovedReason().unwrap(); + } + } + + fn open(&self, i: usize) -> ID3D12GraphicsCommandList { + let (allocator, list) = &self.lists[i]; + // SAFETY: its last run was waited for. + unsafe { + allocator.Reset().unwrap(); + list.Reset(allocator, None).unwrap(); + } + list.clone() + } + + fn send(&self, lists: &[&ID3D12GraphicsCommandList]) { + let all: Vec> = lists.iter().map(|l| Some(l.cast().unwrap())).collect(); + // SAFETY: closed lists. + unsafe { self.queue.ExecuteCommandLists(&all) }; + } + + /// Fills rows of a 16x16 texture in the upload buffer at `at`. + fn fill(&self, at: usize, color: [u8; 4]) { + for y in 0..16 { + for x in 0..16 { + let mut c = color; + c[1] = c[1].wrapping_add((x * 8 + y) as u8); + // SAFETY: inside the mapping (16 rows of 256 bytes). + unsafe { self.texels.1.add(at + y * 256 + x * 4).cast::<[u8; 4]>().write(c) }; + } + } + } + + fn texture_copy(&self, l: &ID3D12GraphicsCommandList, texture: &ID3D12Resource, at: u64) { + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer never released. + pResource: unsafe { std::mem::transmute_copy(&self.texels.0) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(at, 16) }, + }; + let to = 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 { l.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + + /// A quad of the texture in slot `pick`, at the constants at `at`. + fn quad(&self, l: &ID3D12GraphicsCommandList, pick: u32, at: u64, record: u64) { + // SAFETY: an open list; live objects. + unsafe { + l.SetGraphicsRootSignature(&self.draw.root); + l.SetPipelineState(&self.draw.pso); + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + l.SetGraphicsRoot32BitConstant(0, pick, 0); + l.SetGraphicsRootConstantBufferView(1, self.constants.0.GetGPUVirtualAddress() + at); + l.SetGraphicsRootDescriptorTable(2, self.views.GetGPUDescriptorHandleForHeapStart()); + l.ExecuteIndirect(&self.signature, 1, &self.scratch, record * 16, None::<&ID3D12Resource>, 0); + } + } + + /// The arguments made and clamped, as the host layer does it. + fn arguments(&self, l: &ID3D12GraphicsCommandList, before: D3D12_RESOURCE_STATES) { + // SAFETY: an open list; live objects. + unsafe { + l.SetComputeRootSignature(&self.args.root); + l.SetPipelineState(&self.args.pso); + l.SetComputeRootShaderResourceView(0, self.shared.0.GetGPUVirtualAddress() + 65536); + l.SetComputeRootUnorderedAccessView(1, self.arguments.GetGPUVirtualAddress()); + l.Dispatch(1, 1, 1); + l.ResourceBarrier(&[uav_barrier(), moved(&self.arguments, UAV, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]); + l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, before, UAV)]); + l.SetComputeRootSignature(&self.clamp.root); + l.SetPipelineState(&self.clamp.pso); + let constants = [0u32, 16, 2, 0, 0, 0]; + l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + l.SetComputeRootShaderResourceView(1, self.arguments.GetGPUVirtualAddress()); + l.SetComputeRootShaderResourceView(2, self.arguments.GetGPUVirtualAddress()); + l.SetComputeRootUnorderedAccessView(3, self.scratch.GetGPUVirtualAddress()); + l.SetComputeRootUnorderedAccessView(4, self.budget.GetGPUVirtualAddress()); + l.Dispatch(1, 1, 1); + l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, UAV, ARGUMENTS)]); + l.ResourceBarrier(&[moved(&self.arguments, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, UAV)]); + } + } + + fn place(&self, at: usize, place: [f32; 4]) { + // SAFETY: inside the mapping. + unsafe { self.constants.1.add(at).cast::<[f32; 4]>().write(place) }; + } + + fn give(&self, at: usize, value: u32) { + // SAFETY: inside the mapping. + unsafe { self.shared.1.add(at).cast::().write(value) }; + } + + fn targets(&self, l: &ID3D12GraphicsCommandList) { + // SAFETY: an open list; live objects. + unsafe { + let (rtv, dsv) = (self.rtvs.GetCPUDescriptorHandleForHeapStart(), self.dsvs.GetCPUDescriptorHandleForHeapStart()); + l.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv)); + let size = SIZE as f32; + l.RSSetViewports(&[D3D12_VIEWPORT { Width: size, Height: size, MaxDepth: 1.0, ..Default::default() }]); + l.RSSetScissorRects(&[RECT { left: 0, top: 0, right: SIZE as i32, bottom: SIZE as i32 }]); + l.SetDescriptorHeaps(&[Some(self.views.clone())]); + } + } + + fn frame(&mut self, n: u32) { + // SAFETY: open lists of ours, live objects; memory is written while + // the card does not use it. + unsafe { + self.wait(); + if n == 0 { + self.fill(0, [200, 10, 30, 255]); + self.fill(8192, [10, 40, 220, 255]); + let l = self.open(0); + self.texture_copy(&l, &self.fixed, 0); + self.texture_copy(&l, &self.other, 8192); + l.ResourceBarrier(&[moved(&self.fixed, TO, READ), moved(&self.other, TO, READ)]); + l.Close().unwrap(); + self.send(&[&l]); + self.wait(); + } + // The first submission. + self.show(4000, &self.fixed); + self.place(0, [-1.0 + 0.1 * n as f32, -1.0, 0.5, 0.5]); + self.place(256, [0.0, 0.0, 0.5, 0.5]); + self.give(65536, 6); + self.give(40, 7 + n); + let l = self.open(0); + l.ResourceBarrier(&[moved(&self.target, FROM, TARGET)]); + let (rtv, dsv) = (self.rtvs.GetCPUDescriptorHandleForHeapStart(), self.dsvs.GetCPUDescriptorHandleForHeapStart()); + l.ClearRenderTargetView(rtv, &[0.1 * n as f32, 0.2, 0.3, 1.0], None); + l.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None); + self.arguments(&l, COMMON); + self.targets(&l); + self.quad(&l, 4000, 0, 0); + self.quad(&l, 4001, 256, 0); + // Nothing: the clamp cut it to no vertices. + self.quad(&l, 4001, 0, 1); + l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]); + l.Close().unwrap(); + self.send(&[&l]); + self.wait(); + // The second: other constants and another texture in the same + // places, and the second texture in the memory of the first. + self.show(4000, &self.other); + self.place(0, [-0.9, 0.3, 0.6, 0.6]); + self.place(256, [0.3, -0.8, 0.6, 0.5]); + self.give(40, 100 + n); + self.give(65536, 3); + self.fill(16384, [30, 200, 10 + 5 * n as u8, 255]); + let l = self.open(1); + self.targets(&l); + self.arguments(&l, COMMON); + self.quad(&l, 4000, 0, 0); + l.ResourceBarrier(&[moved(&self.other, READ, TO)]); + l.ResourceBarrier(&[aliased(&self.other, &self.one)]); + self.texture_copy(&l, &self.one, 16384); + l.ResourceBarrier(&[moved(&self.one, TO, READ)]); + self.arguments(&l, ARGUMENTS); + self.quad(&l, 4002, 256, 0); + l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]); + // And back, for the next frame. + l.ResourceBarrier(&[moved(&self.one, READ, TO)]); + l.ResourceBarrier(&[aliased(&self.one, &self.other)]); + self.texture_copy(&l, &self.other, 8192); + l.ResourceBarrier(&[moved(&self.other, TO, READ)]); + l.Close().unwrap(); + let second = l; + let l = self.open(2); + l.SetDescriptorHeaps(&[Some(self.views.clone())]); + l.SetComputeRootSignature(&self.add.root); + l.SetPipelineState(&self.add.pso); + l.SetComputeRootShaderResourceView(0, self.shared.0.GetGPUVirtualAddress()); + let table = self.views.GetGPUDescriptorHandleForHeapStart().ptr + 7 * self.step as u64; + l.SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE { ptr: table }); + l.SetComputeRootUnorderedAccessView(2, self.sum.GetGPUVirtualAddress()); + for _ in 0..3 { + l.Dispatch(2, 2, 1); + l.ResourceBarrier(&[uav_barrier()]); + } + // The card writes memory the CPU sees. + l.ResourceBarrier(&[moved(&self.sum, UAV, FROM)]); + l.CopyBufferRegion(&self.shared.0, 30_000, &self.sum, 0, 1024); + l.ResourceBarrier(&[moved(&self.target, TARGET, FROM)]); + l.Close().unwrap(); + self.send(&[&second, &l]); + if let Some((swap, _)) = &self.swap { + swap.Present(0, DXGI_PRESENT(0)).unwrap(); + } + record::present(&self.target, FROM); + } + } + + /// What everything holds now. + fn outcome(&mut self) -> Outcome { + self.wait(); + let l = self.open(0); + // SAFETY: an open list; live objects. + unsafe { + let to = |at: u64, size| D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&self.back.0), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(at, size) }, + }; + let of = |t: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(t), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + l.ResourceBarrier(&[moved(&self.image, UAV, FROM)]); + l.CopyTextureRegion(&to(0, SIZE), 0, 0, 0, &of(&self.target), None); + l.CopyTextureRegion(&to(1 << 18, 16), 0, 0, 0, &of(&self.image), None); + l.ResourceBarrier(&[moved(&self.image, FROM, UAV)]); + l.CopyBufferRegion(&self.back.0, 1 << 19, &self.sum, 0, 1024); + l.Close().unwrap(); + self.send(&[&l]); + self.wait(); + let at = |from: usize, n: usize| std::slice::from_raw_parts(self.back.1.add(from), n).to_vec(); + Outcome { + picture: at(0, (SIZE * 512) as usize), + image: rows(&at(1 << 18, 4096)), + sum: at(1 << 19, 1024), + shared: std::slice::from_raw_parts(self.shared.1, 70_000).to_vec(), + } + } + } +} + +/// The 64 bytes of each row of a 16x16 texture. +fn rows(bytes: &[u8]) -> Vec { + bytes.chunks(256).flat_map(|r| r[..64].to_vec()).collect() +} + +fn footprint(at: u64, size: u32) -> D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: at, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Width: size, + Height: size, + Depth: 1, + RowPitch: (size * 4).next_multiple_of(256), + }, + } +} + +/// A swap chain of a window that is never shown. +fn swap_chain(queue: &ID3D12CommandQueue) -> (IDXGISwapChain3, HWND) { + // SAFETY: plain creation. + unsafe { + let hwnd = + CreateWindowExW(WINDOW_EX_STYLE(0), w!("STATIC"), w!("replay test"), WS_POPUP, 0, 0, 64, 64, None, None, None, None).unwrap(); + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap(); + let desc = DXGI_SWAP_CHAIN_DESC1 { + Width: 64, + Height: 64, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, + BufferCount: 2, + SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, + ..Default::default() + }; + let chain = factory.CreateSwapChainForHwnd(queue, hwnd, &desc, None, None).unwrap().cast().unwrap(); + (chain, hwnd) + } +} + +fn table_of(device: &ID3D12Device) -> usize { + // SAFETY: a live COM object starts with its table's address. + unsafe { *device.as_raw().cast::() } +} + +fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str) -> play::Report { + let report = player.run(options).unwrap(); + println!("{}", report.text(what)); + assert_eq!(report.frame_ms.len(), options.loops as usize); + assert!(report.median_ms() > 0.0); + let (db, same) = report.picture.unwrap(); + assert!(same && db.is_infinite(), "{what}: the picture differs ({db} dB)"); + let mut get = |name: &str| { + let id = player.named(name).unwrap(); + player.contents(id).unwrap().unwrap() + }; + assert_eq!(get("sum"), expected.sum, "{what}: sum"); + assert_eq!(rows(&get("image")), expected.image, "{what}: image"); + assert_eq!(get("target"), expected.picture, "{what}: target"); + assert!(get("shared") == expected.shared, "{what}: memory the CPU sees"); + assert!(!report.notes.iter().any(|n| n.contains("recorder:") && !n.contains("submissions,") && !n.contains("waits of the")), "{what}: {:?}", report.notes); + report +} + +#[test] +fn a_frame_is_recorded_and_replayed() { + let debug = std::env::var_os("VICTORY_TEST_D3D_DEBUG").is_some(); + let mut device: Option = None; + // SAFETY: plain creation. + unsafe { + if debug { + let mut layer: Option = None; + D3D12GetDebugInterface(&mut layer).unwrap(); + layer.unwrap().EnableDebugLayer(); + } + let _ = D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device); + } + let Some(device) = device else { + eprintln!("no adapter: skipped"); + return; + }; + let own = table_of(&device); + // Without the recorder. + let without = { + let mut scene = Scene::new(&device, false); + (0..5).for_each(|n| scene.frame(n)); + scene.outcome() + }; + eprintln!("ran without the recorder"); + // Something is in the picture. + assert!(without.sum.iter().any(|&b| b != 0)); + let colors: std::collections::HashSet<[u8; 4]> = + without.picture.chunks_exact(4).map(|c| [c[0], c[1], c[2], c[3]]).collect(); + assert!(colors.len() > 30, "{}", colors.len()); + + // With it: armed at the first present, the fourth frame is captured (a + // frame whose lists are all recorded comes first). + assert!(!record::on()); + let dir = tempfile::tempdir().unwrap(); + let settings = Settings { folder: dir.path().to_owned(), at: At::Frame(1), frames: 1 }; + let folder = record::start(settings, &device).unwrap(); + assert!(record::on()); + assert_ne!(table_of(&device), own, "the device is hooked"); + assert!( + record::start(Settings { folder: dir.path().to_owned(), at: At::Trigger, frames: 1 }, &device).is_err(), + "one recorder a process" + ); + eprintln!("recorder on"); + let mut scene = Scene::new(&device, true); + eprintln!("scene made"); + (0..4).for_each(|n| scene.frame(n)); + assert_eq!(record::finished(), Some(folder.clone()), "see {}", folder.display()); + let expected = scene.outcome(); + // It goes on as it did without the recorder. + scene.frame(4); + let after = scene.outcome(); + assert!(after == without, "the recorder changed what the program makes"); + drop(scene); + record::unhook(&device); + assert_eq!(table_of(&device), own, "the device is as it was"); + for name in ["frame.bin", "contents.bin", "deltas.bin", "shaders.bin", "present.bin", "notes.txt", "frame-0.png"] { + assert!(folder.join(name).exists(), "{name}"); + } + println!("{}", std::fs::read_to_string(folder.join("notes.txt")).unwrap()); + + let plain = Options { loops: 3, ..Default::default() }; + let mut player = Player::load(dir.path(), &plain).unwrap(); + check(&mut player, &plain, &expected, "unchanged"); + let detailed = Options { detailed: true, ..plain.clone() }; + let report = check(&mut player, &detailed, &expected, "detailed"); + let count = |kind: &str| report.categories.iter().find(|c| c.0 == kind).map_or(0, |c| c.2); + assert_eq!(count("argument clamps (ours)"), 3); + assert_eq!(count("indirect draws"), 5); + assert_eq!(count("dispatches"), 6); + assert_eq!(count("clears"), 2); + assert!(report.shaders.iter().any(|s| s.2.starts_with("a drawing pipeline (DXIL ")), "{:?}", report.shaders); + let merged = Options { merge_barriers: true, ..plain.clone() }; + check(&mut player, &merged, &expected, "merged barriers"); + let clamps = Options { skip_clamps: true, ..plain.clone() }; + let report = check(&mut player, &clamps, &expected, "without clamps"); + assert!(report.notes.iter().any(|n| n.contains("3 clamp passes")), "{:?}", report.notes); + let one = Options { one_submit: true, ..plain.clone() }; + check(&mut player, &one, &expected, "one submission"); + let hash = Options { skip_hash_passes: true, ..plain.clone() }; + check(&mut player, &hash, &expected, "without hash passes (there are none)"); + // These change what is drawn: they run, and then the frame is as before. + let no_barriers = Options { no_barriers: true, ..plain.clone() }; + player.run(&no_barriers).unwrap(); + let some = Options { only: Some((0, 1)), ..plain.clone() }; + player.run(&some).unwrap(); + let skip = Options { skip_shaders: vec!["a drawing".into()], ..plain.clone() }; + let report = player.run(&skip).unwrap(); + assert!(!report.picture.unwrap().1, "without its draws the picture is another"); + assert!(report.notes.iter().any(|n| n.contains("1 pipelines match")) && report.notes.iter().any(|n| n.contains("left out 5 commands"))); + let kept = Options { restore: false, ..plain.clone() }; + player.run(&kept).unwrap(); + check(&mut player, &plain, &expected, "unchanged again"); + drop(player); + for buffers in [Buffers::Card, Buffers::Pc] { + let o = Options { buffers, ..plain.clone() }; + let mut player = Player::load(dir.path(), &o).unwrap(); + check(&mut player, &o, &expected, &format!("buffers {buffers:?}")); + } + let o = Options { compare: true, merge_barriers: true, loops: 2, ..Default::default() }; + let both = play::replay(dir.path(), &o).unwrap(); + assert_eq!(both.len(), 2); + assert!(both.iter().all(|(_, r)| r.picture.unwrap().1)); + assert!(folder.join("replay.png").exists() && folder.join("replay-unchanged.png").exists()); + if debug { + let q = device.cast::().unwrap(); + // SAFETY: plain queries; messages read into buffers of their size. + unsafe { + for i in 0..q.GetNumStoredMessages() { + let mut size = 0; + let _ = q.GetMessage(i, None, &mut size); + let mut buffer = vec![0u64; size.div_ceil(8)]; + let m = buffer.as_mut_ptr().cast::(); + if q.GetMessage(i, Some(m), &mut size).is_ok() && (*m).Severity.0 <= D3D12_MESSAGE_SEVERITY_WARNING.0 { + let text = std::slice::from_raw_parts((*m).pDescription, (*m).DescriptionByteLength); + println!("D3D12 {} {}: {}", (*m).Severity.0, (*m).ID.0, String::from_utf8_lossy(text)); + } + } + } + } +} From d7ecfd2bba2b1b823d7602f80a31d61eaf0e3b57 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 20:09:57 -0600 Subject: [PATCH 156/445] victory replay, larger tests of it Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/main.rs | 8 + apps/victory/src/replay.rs | 131 ++++++++++++ crates/victory-gpu/src/host.rs | 9 +- crates/victory-gpu/src/replay/play.rs | 145 ++++++++++--- crates/victory-gpu/src/replay/record.rs | 11 +- crates/victory-gpu/src/replay/snap.rs | 145 +++++++++++-- crates/victory-gpu/tests/replay.rs | 268 ++++++++++++++++++++++- crates/victory-gpu/tests/replay_big.rs | 271 ++++++++++++++++++++++++ crates/victory-hle/src/lib.rs | 2 + 9 files changed, 938 insertions(+), 52 deletions(-) create mode 100644 apps/victory/src/replay.rs create mode 100644 crates/victory-gpu/tests/replay_big.rs diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index a04655c..99733b9 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -5,6 +5,8 @@ mod census; mod inspect; +#[cfg(all(windows, feature = "diagnostics"))] +mod replay; mod run; mod shader; mod translate; @@ -114,6 +116,10 @@ enum Command { #[arg(last = true)] title_args: Vec, }, + /// Run a captured frame's GPU work again (diagnostics builds; see + /// docs/replay.md). + #[cfg(all(windows, feature = "diagnostics"))] + Replay(replay::Replay), /// Show the resolved configuration and check it. Config, } @@ -181,6 +187,8 @@ fn main() -> Result<()> { console, title_args: _, } => run::run(&exe, unimplemented, strict, execute, console), + #[cfg(all(windows, feature = "diagnostics"))] + Command::Replay(options) => replay::run(options), Command::Config => show_config(), } } diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs new file mode 100644 index 0000000..61de570 --- /dev/null +++ b/apps/victory/src/replay.rs @@ -0,0 +1,131 @@ +//! `victory replay`: a captured frame run again (docs/replay.md). + +use std::path::PathBuf; + +use anyhow::{Context, Result}; +use clap::{Args, ValueEnum}; +use victory_hle::replay::play::{self, Options}; + +#[derive(Clone, Copy, ValueEnum)] +enum Timing { + /// Each list. + Lists, + /// Each command (adds some time of its own). + Detailed, +} + +#[derive(Clone, Copy, ValueEnum)] +enum Buffers { + AsRecorded, + /// All in the card's memory. + Vram, + /// All in the PC's memory. + Sysmem, +} + +#[derive(Args)] +pub(crate) struct Replay { + /// The folder given as VICTORY_RECORD (its last capture) or a capture. + folder: PathBuf, + /// How often the frame is run. + #[arg(long, default_value_t = 5)] + loops: u32, + /// Do not put back, between runs, what a run changed. + #[arg(long)] + no_restore: bool, + #[arg(long, value_enum, default_value_t = Timing::Lists)] + timing: Timing, + /// Pipelines listed with detailed timing. + #[arg(long, default_value_t = 20)] + top: usize, + /// Where the picture goes (default: replay.png in the capture). + #[arg(long)] + image: Option, + /// Run the frame unchanged first, and print both. + #[arg(long)] + compare: bool, + /// Leave out unordered-access barriers. + #[arg(long)] + no_barriers: bool, + /// Join barrier calls with no work between them. + #[arg(long)] + merge_barriers: bool, + /// Leave out the argument clamps: what they bound is kept from a first run. + #[arg(long)] + skip_clamps: bool, + /// Leave out the hash and compare passes over card buffers. + #[arg(long)] + skip_hash_passes: bool, + /// Where buffers lie. + #[arg(long, value_enum, default_value_t = Buffers::AsRecorded)] + buffers: Buffers, + /// One ExecuteCommandLists for the whole frame. + #[arg(long)] + one_submit: bool, + /// Run only these lists, by their place in the frame (`3..7`, or `5`); + /// of the others only barriers. + #[arg(long)] + only: Option, + /// Leave out what runs a pipeline whose name or DXIL hash has this in it + /// (may be given several times). + #[arg(long = "skip-shader")] + skip_shader: Vec, + /// Use the D3D12 debug layer (slow). + #[arg(long)] + debug_layer: bool, +} + +/// `3..7` (both included) or `5`. +fn range(text: &str) -> Option<(u32, u32)> { + match text.split_once("..") { + Some((a, b)) => Some((a.trim().parse().ok()?, b.trim().parse().ok()?)), + None => text.trim().parse().ok().map(|n| (n, n)), + } +} + +pub(crate) fn run(r: Replay) -> Result<()> { + let only = match &r.only { + Some(text) => Some(range(text).with_context(|| format!("--only {text}: not a list or a range of lists (3..7)"))?), + None => None, + }; + let options = Options { + loops: r.loops.max(1), + restore: !r.no_restore, + detailed: matches!(r.timing, Timing::Detailed), + top: r.top, + image: r.image, + buffers: match r.buffers { + Buffers::AsRecorded => play::Buffers::AsRecorded, + Buffers::Vram => play::Buffers::Card, + Buffers::Sysmem => play::Buffers::Pc, + }, + no_barriers: r.no_barriers, + merge_barriers: r.merge_barriers, + skip_clamps: r.skip_clamps, + skip_hash_passes: r.skip_hash_passes, + one_submit: r.one_submit, + only, + skip_shaders: r.skip_shader, + compare: r.compare, + debug: r.debug_layer, + }; + let reports = play::replay(&r.folder, &options)?; + for (what, report) in &reports { + println!("{}", report.text(what)); + } + if let [(_, before), (_, after)] = &reports[..] { + println!("{:+.2} ms", after.median_ms() - before.median_ms()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + #[test] + fn ranges() { + assert_eq!(super::range("3..7"), Some((3, 7))); + assert_eq!(super::range("5"), Some((5, 5))); + assert_eq!(super::range("x"), None); + assert_eq!(super::range("1..x"), None); + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 332ebee..643eab5 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1303,7 +1303,14 @@ fn timing() -> bool { pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) { #[cfg(feature = "diagnostics")] if crate::replay::record::on() { - crate::replay::record::name(object, &text()); + let text = text(); + crate::replay::record::name(object, &text); + if dred_on() + && let Ok(object) = object.cast::() + { + // SAFETY: a plain call on a live object. + let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) }; + } return; } if dred_on() diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index 9f09a0d..c7c7131 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -345,7 +345,7 @@ impl Player { player.make_masters()?; step("copies to restore from", &mut at); let steps: Vec = steps.iter().map(|(w, d)| format!("{w} {:.1} s", d.as_secs_f64())).collect(); - tracing::info!(seconds = began.elapsed().as_secs_f64(), "capture loaded: {}", steps.join(", ")); + player.notes.push(format!("loaded in {:.1} s: {}", began.elapsed().as_secs_f64(), steps.join(", "))); Ok(player) } @@ -635,9 +635,15 @@ impl Player { // version of the heaps of its own: lists are sent without waiting, // so a heap cannot be written between them. let mut now: HashMap<(u32, u32), Slot> = HashMap::new(); + let replaced: HashSet<(u32, u32)> = self.frame.submits.iter().flat_map(|s| s.views.iter().map(|v| (v.0, v.1))).collect(); for h in &self.frame.descriptor_heaps { - for (first, n, s) in &h.runs { - now.extend((*first..first + n).map(|i| ((h.id, i), *s))); + for (id, i) in replaced.iter().filter(|k| k.0 == h.id) { + let k = h.runs.partition_point(|run| run.0 <= *i); + if let Some((first, n, s)) = k.checked_sub(1).and_then(|k| h.runs.get(k)) + && i - first < *n + { + now.insert((*id, *i), *s); + } } } // What each version changes against the one before. @@ -660,6 +666,7 @@ impl Player { self.version_of.push(versions.len() - 1); } let mut made = HashMap::new(); + let mut full = 0; for h in &self.frame.descriptor_heaps { let sampler = h.kind == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0; let kind = D3D12_DESCRIPTOR_HEAP_TYPE(h.kind); @@ -703,7 +710,20 @@ impl Player { all.push(same); continue; } - let heap = make(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)?; + let heap = match make(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) { + Ok(heap) => heap, + // Room for no more of them: the changes go into the + // last one, and lists before see them too. + Err(_) if !all.is_empty() => { + full += 1; + let Some(Version { heap, gpu }) = all.last() else { break }; + let same = Version { heap: ID3D12DescriptorHeap::clone(heap), gpu: *gpu }; + self.device.CopyDescriptorsSimple(h.count, same.heap.GetCPUDescriptorHandleForHeapStart(), start, kind); + all.push(same); + continue; + } + Err(e) => return Err(e.into()), + }; self.device.CopyDescriptorsSimple(h.count, heap.GetCPUDescriptorHandleForHeapStart(), start, kind); let gpu = heap.GetGPUDescriptorHandleForHeapStart().ptr; all.push(Version { heap, gpu }); @@ -712,6 +732,12 @@ impl Player { } } self.descriptors = made; + if versions.len() > 1 { + self.notes.push(format!("{} versions of the descriptor heaps (views replaced during the frame)", versions.len())); + } + if full > 0 { + self.note(format!("{full} versions of descriptor heaps had no room: earlier lists see later views")); + } // Render target and depth views. let mut views: [HashSet; 2] = Default::default(); for c in self.commands.iter().flatten() { @@ -839,11 +865,12 @@ impl Player { fn load_contents(&mut self) -> Result<()> { // Idle aliases first: a change of their state may write memory the // one in use holds. + let known: HashSet = self.frame.contents.iter().map(|c| c.res).collect(); let mut early = Vec::new(); let mut into = Vec::new(); for r in &self.frame.resources { let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { continue }; - let loaded = !r.idle && self.frame.contents.iter().any(|c| c.res == r.id); + let loaded = !r.idle && known.contains(&r.id); gpu::moves(&o.res, &[COMMON], if loaded { &[COPY_DEST] } else { state }, if loaded { &mut into } else { &mut early }); } let textures: Vec<(Content, u64, u64)> = self @@ -890,7 +917,7 @@ impl Player { let mut back = Vec::new(); for r in &self.frame.resources { let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { continue }; - if !r.idle && self.frame.contents.iter().any(|c| c.res == r.id) { + if !r.idle && known.contains(&r.id) { gpu::moves(&o.res, &[COPY_DEST], state, &mut back); } } @@ -906,7 +933,30 @@ impl Player { // What the CPU had put into the memory both see by the first // submission: part of the start of the frame. let file = File::open(self.folder.join("deltas.bin"))?; - let first: Vec<(Delta, u64, u64)> = self.frame.submits[0].deltas.iter().map(|d| (d.clone(), d.len, d.file)).collect(); + let named = self.named_buffers(); + let of = |s: &wire::Submit| s.deltas.iter().filter(|d| named.contains(&d.res)).cloned().collect::>(); + // In memory the card cannot write, bytes looked at first when a + // later submission read them can stand there from the start. + let upload: HashSet = self + .frame + .resources + .iter() + .filter(|r| matches!(&r.place, Place::Committed { props, .. } if props.kind == D3D12_HEAP_TYPE_UPLOAD.0)) + .map(|r| r.id) + .collect(); + let mut first = of(&self.frame.submits[0]); + let mut seen: HashSet<(u32, u64)> = HashSet::new(); + let pages = |d: &Delta| (d.at / 4096..(d.at + d.len).div_ceil(4096)).map(|p| (d.res, p)).collect::>(); + first.iter().for_each(|d| seen.extend(pages(d))); + let mut rest: Vec> = vec![Vec::new()]; + for s in self.frame.submits.iter().skip(1) { + let (early, late): (Vec, Vec) = + of(s).into_iter().partition(|d| upload.contains(&d.res) && pages(d).iter().all(|p| !seen.contains(p))); + early.iter().for_each(|d| seen.extend(pages(d))); + first.extend(early); + rest.push(late); + } + let first: Vec<(Delta, u64, u64)> = first.into_iter().map(|d| (d.clone(), d.len, d.file)).collect(); self.upload(&first, &file, |player, list, parts, staging| { for (d, len, at) in parts { if let Some(o) = player.objects.get(&d.res) { @@ -919,11 +969,11 @@ impl Player { let mut later: Vec<((u64, Delta), u64, u64)> = Vec::new(); let mut total = 0u64; self.delta_parts = vec![Vec::new(); self.frame.submits.len()]; - for (i, s) in self.frame.submits.iter().enumerate().skip(1) { - for d in &s.deltas { + for (i, all) in rest.into_iter().enumerate() { + for d in all { later.push(((total, d.clone()), d.len, d.file)); - self.delta_parts[i].push((d.clone(), total)); total += d.len; + self.delta_parts[i].push((d, total - later.last().map_or(0, |l| l.1))); } } if total > 0 { @@ -939,6 +989,46 @@ impl Player { Ok(()) } + /// The buffers the frame names, in commands or descriptors: what the CPU + /// writes to others (buffers it has results fetched to) is of no use. + fn named_buffers(&self) -> HashSet { + let mut named = HashSet::new(); + let mut va = |va: &Va| { + if let Va::At { res, .. } = va { + named.insert(*res); + } + }; + for c in self.commands.iter().flatten() { + match c { + Cmd::RootView { va: v, .. } => va(v), + Cmd::IndexBuffer { view: Some((v, _, _)) } => va(v), + Cmd::VertexBuffers { views: Some(all), .. } => all.iter().for_each(|(v, _, _)| va(v)), + Cmd::WriteImmediate { all } => all.iter().for_each(|(v, _, _)| va(v)), + _ => {} + } + } + for c in self.commands.iter().flatten() { + match c { + Cmd::CopyBuffer { dst, src, .. } | Cmd::CopyResource { dst, src } => named.extend([*dst, *src]), + Cmd::CopyTexture { dst, src, .. } => { + for Loc::Sub { res, .. } | Loc::Placed { res, .. } in [dst, src] { + named.insert(*res); + } + } + Cmd::Indirect { args, count, .. } => named.extend([*args, *count]), + Cmd::ResolveQuery { dst, .. } => drop(named.insert(*dst)), + _ => {} + } + } + for h in &self.frame.descriptor_heaps { + named.extend(h.runs.iter().flat_map(|(_, _, s)| [s.res, s.counter])); + } + for s in &self.frame.submits { + named.extend(s.views.iter().flat_map(|(_, _, s)| [s.res, s.counter])); + } + named + } + /// Copies of what the frame changes; and the states it leaves. fn make_masters(&mut self) -> Result<()> { let mut states = States::default(); @@ -991,7 +1081,7 @@ impl Player { } states.decay(); if i > 0 { - written.extend(s.deltas.iter().map(|d| d.res)); + written.extend(self.delta_parts[i].iter().map(|(d, _)| d.res)); } } // Buffers any unordered-access view names. @@ -1759,8 +1849,7 @@ impl Player { } self.picture(o, &mut report)?; if let Some(q) = &self.info { - let n = debug_messages(q); - report.notes.push(format!("{n} errors from the debug layer")); + report.notes.extend(debug_messages(q)); } Ok(report) } @@ -1822,6 +1911,11 @@ impl Player { /// What a resource holds now (after a run): a buffer's bytes, or a /// texture's first subresource in its copyable layout. pub fn contents(&mut self, id: u32) -> Result>> { + self.contents_of(id, 0) + } + + /// As [`Player::contents`], of a texture's subresource `sub`. + pub fn contents_of(&mut self, id: u32, sub: u32) -> Result>> { let Some(o) = self.objects.get(&id) else { return Ok(None); }; @@ -1830,21 +1924,21 @@ impl Player { let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; let states = if self.fresh { &self.start } else { &self.end }; let state = states.get(&id).cloned().unwrap_or(vec![COMMON]); - let (f, total) = if is_buffer { (Vec::new(), r.desc.width) } else { gpu::footprints(&self.device, &desc, 0, 1) }; + let (f, total) = if is_buffer { (Vec::new(), r.desc.width) } else { gpu::footprints(&self.device, &desc, sub, 1) }; let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_FLAG_NONE)?; self.worker.run(|list| { if is_buffer { // SAFETY: an open list; live buffers. unsafe { list.CopyBufferRegion(&back, 0, &res, 0, total) }; } else if state.len() == 1 || subs == 1 { - read_sub(list, &res, 0, state[0], &back, f[0]); + read_sub(list, &res, sub, state[0], &back, f[0]); } else { let (mut before, mut after) = (Vec::new(), Vec::new()); gpu::moves(&res, &state, &[COPY_SOURCE], &mut before); gpu::moves(&res, &[COPY_SOURCE], &state, &mut after); // SAFETY: an open list; live resources. unsafe { barriers(list, &before) }; - read_sub(list, &res, 0, COPY_SOURCE, &back, f[0]); + read_sub(list, &res, sub, COPY_SOURCE, &back, f[0]); // SAFETY: as above. unsafe { barriers(list, &after) }; } @@ -1969,10 +2063,9 @@ fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option usize { - let mut errors = 0; - let mut seen: HashMap = HashMap::new(); +/// The debug layer's errors: how many of each kind, and its first text. +fn debug_messages(q: &ID3D12InfoQueue) -> Vec { + let mut seen: BTreeMap = BTreeMap::new(); // SAFETY: messages read into buffers of the size asked for. unsafe { for i in 0..q.GetNumStoredMessages() { @@ -1987,18 +2080,14 @@ fn debug_messages(q: &ID3D12InfoQueue) -> usize { } let m = &*message; if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 { - errors += 1; - let n = seen.entry(m.ID.0).or_default(); - *n += 1; - if *n <= 3 { - let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); - tracing::warn!("D3D12 {}: {}", m.ID.0, String::from_utf8_lossy(text).trim_end_matches('\0')); - } + let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); + let text = || String::from_utf8_lossy(text).trim_end_matches('\0').to_owned(); + seen.entry(m.ID.0).or_insert_with(|| (0, text())).0 += 1; } } q.ClearStoredMessages(); } - errors + seen.into_iter().map(|(id, (n, text))| format!("debug layer: {n} errors {id}, first: {text}")).collect() } #[cfg(test)] diff --git a/crates/victory-gpu/src/replay/record.rs b/crates/victory-gpu/src/replay/record.rs index ea9b6d9..799fe1e 100644 --- a/crates/victory-gpu/src/replay/record.rs +++ b/crates/victory-gpu/src/replay/record.rs @@ -38,6 +38,9 @@ pub struct Settings { pub at: At, /// Frames to capture. pub frames: u32, + /// Record lists from the start on, not only once a capture is near: for + /// a title that submits lists it recorded long before. + pub always: bool, } #[derive(Clone, Copy, Debug, PartialEq)] @@ -52,13 +55,14 @@ pub enum At { } impl Settings { - /// From `VICTORY_RECORD`, `VICTORY_RECORD_AT` (seconds, or `f`) - /// and `VICTORY_RECORD_FRAMES`. + /// From `VICTORY_RECORD`, `VICTORY_RECORD_AT` (seconds, or `f`), + /// `VICTORY_RECORD_FRAMES` and `VICTORY_RECORD_ALWAYS=1`. pub fn from_env() -> Option { let folder = PathBuf::from(std::env::var_os("VICTORY_RECORD").filter(|v| !v.is_empty())?); let at = parse_at(&std::env::var("VICTORY_RECORD_AT").unwrap_or_default()); let frames = std::env::var("VICTORY_RECORD_FRAMES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1); - Some(Settings { folder, at, frames: std::cmp::max(frames, 1) }) + let always = std::env::var_os("VICTORY_RECORD_ALWAYS").is_some_and(|v| v == "1"); + Some(Settings { folder, at, frames: std::cmp::max(frames, 1), always }) } } @@ -733,6 +737,7 @@ pub fn start(settings: Settings, device: &ID3D12Device) -> std::io::Result; @@ -94,7 +94,8 @@ fn stop(r: &Recorder, phase: &mut Phase, e: &(dyn std::error::Error + Send + Syn phase.stage = Stage::Done; r.watching.store(false, Ordering::SeqCst); r.arm(false); - lock(&r.held).clear(); + let held = std::mem::take(&mut *lock(&r.held)); + drop(held); } pub(super) fn present(r: &Recorder, texture: &ID3D12Resource, state: u32) { @@ -159,6 +160,69 @@ pub(super) fn present(r: &Recorder, texture: &ID3D12Resource, state: u32) { drop(finished); } +/// What a submission reads of buffers, by id: parts of them (copied from), +/// or all (read some other way). +#[derive(Default)] +struct Reads { + all: HashSet, + parts: HashMap>, +} + +impl Reads { + fn note(&mut self, cmds: &[Cmd]) { + let (all, parts) = (&mut self.all, &mut self.parts); + let mut whole = |va: &Va| { + if let Va::At { res, .. } = va { + all.insert(*res); + } + }; + for c in cmds { + match c { + Cmd::RootView { va, .. } | Cmd::IndexBuffer { view: Some((va, _, _)) } => whole(va), + Cmd::VertexBuffers { views: Some(views), .. } => views.iter().for_each(|(va, _, _)| whole(va)), + Cmd::Indirect { args, count, .. } => { + for res in [*args, *count] { + whole(&Va::At { res, offset: 0 }); + } + } + Cmd::CopyResource { src, .. } => whole(&Va::At { res: *src, offset: 0 }), + Cmd::CopyBuffer { src, src_at, len, .. } => parts.entry(*src).or_default().push((*src_at, src_at + len)), + Cmd::CopyTexture { src: Loc::Placed { res, offset, size, pitch, .. }, .. } => { + // At the most: compressed formats have fewer rows. + let len = u64::from(*pitch) * u64::from(size[1]) * u64::from(size[2].max(1)); + parts.entry(*res).or_default().push((*offset, offset + len)); + } + _ => {} + } + } + } + + /// The whole pages read of a buffer of `size` bytes; `viewed` by a + /// descriptor, all of it is. + fn pages(&self, id: u32, size: usize, viewed: bool) -> Vec<(usize, usize)> { + if viewed || self.all.contains(&id) { + return vec![(0, size)]; + } + let Some(parts) = self.parts.get(&id) else { + return Vec::new(); + }; + let mut pages: Vec<(usize, usize)> = parts + .iter() + .map(|&(from, to)| (from as usize / PAGE * PAGE, (to as usize).next_multiple_of(PAGE).min(size))) + .filter(|(from, to)| from < to) + .collect(); + pages.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::new(); + for (from, to) in pages { + match out.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => out.push((from, to)), + } + } + out + } +} + /// A buffer the CPU sees. struct CpuBuffer { id: u32, @@ -191,6 +255,8 @@ struct Capture { contents: Vec, buffers: Vec, known: HashSet, + /// Resources descriptors name, or named during the frame. + viewed: HashSet, /// Read-back buffers for the slow ones: the buffer, its mapping, size, /// and how much of it is taken. blocks: Vec<(ID3D12Resource, usize, u64, u64)>, @@ -228,6 +294,7 @@ impl Capture { contents: Vec::new(), buffers: Vec::new(), known: HashSet::new(), + viewed: HashSet::new(), blocks: Vec::new(), deltas: File::create(r.folder.join("deltas.bin"))?, delta_at: AtomicU64::new(0), @@ -464,22 +531,33 @@ impl Capture { Ok(()) } - /// What changed in buffers the CPU sees since the submission before. - fn changed(&mut self, r: &Recorder) -> Result, Fault> { + /// What changed in the buffers the CPU sees, of what a submission reads + /// of them, since they were last looked at (the first time: what is not + /// zero). + fn changed(&mut self, r: &Recorder, reads: &Reads) -> Result, Fault> { self.new_buffers(r)?; - if self.buffers.iter().any(|b| b.through.is_some()) { + let parts: Vec<(usize, usize, usize)> = self + .buffers + .iter() + .enumerate() + .flat_map(|(i, b)| reads.pages(b.id, b.size, self.viewed.contains(&b.id)).into_iter().map(move |(from, to)| (i, from, to))) + .collect(); + if parts.iter().any(|p| self.buffers[p.0].through.is_some()) { let (buffers, blocks) = (&self.buffers, &self.blocks); self.worker.run(|list| { - for b in buffers { - if let Some((i, at)) = b.through { + for &(i, from, to) in &parts { + let b = &buffers[i]; + if let Some((block, at)) = b.through { // SAFETY: an open list and live buffers. - unsafe { list.CopyBufferRegion(&blocks[i].0, at, &b.res, 0, b.size as u64) }; + unsafe { list.CopyBufferRegion(&blocks[block].0, at + from as u64, &b.res, from as u64, (to - from) as u64) }; } } })?; } - let chunks: Vec<(usize, usize)> = - self.buffers.iter().enumerate().flat_map(|(i, b)| (0..b.size).step_by(CHUNK).map(move |at| (i, at))).collect(); + let chunks: Vec<(usize, usize, usize)> = parts + .iter() + .flat_map(|&(i, from, to)| (from..to).step_by(CHUNK).map(move |at| (i, at, CHUNK.min(to - at)))) + .collect(); // Each chunk is one thread's; threads share what is kept by parts. struct Kept(*mut u8); // SAFETY: parts of it are used by one thread each. @@ -496,8 +574,7 @@ impl Capture { let mut mine = Vec::new(); loop { let i = next.fetch_add(1, Ordering::Relaxed); - let Some(&(b, at)) = chunks.get(i) else { break }; - let len = CHUNK.min(buffers[b].size - at); + let Some(&(b, at, len)) = chunks.get(i) else { break }; // SAFETY: a chunk of the buffer's memory (it may // change meanwhile: what is kept is what was read) // and of what is kept, which no other thread has. @@ -531,14 +608,14 @@ impl Capture { } else { self.timed("waiting for the card", |c| Ok(c.worker.idle()?))?; } - let deltas = self.timed("what the CPU changed", |c| c.changed(r))?; - // Descriptors last: their memory is ready now. + // Descriptors first: what they name is looked at below. let mut written = std::mem::take(&mut *lock(&r.writes)); let mut views = Vec::new(); if first { let heaps: Vec> = read(&r.descriptors).visible().cloned().collect(); for h in heaps { let runs = runs_of(r, &h.all()); + self.viewed.extend(runs.iter().flat_map(|(_, _, s)| [s.res, s.counter])); self.heaps.push((h, runs)); } } else { @@ -556,11 +633,18 @@ impl Capture { }; for i in at..at + n { if seen.insert((heap, i)) { - views.push((heap, i, resolved(r, h.get(i)))); + let s = resolved(r, h.get(i)); + self.viewed.extend([s.res, s.counter]); + views.push((heap, i, s)); } } } } + let mut reads = Reads::default(); + for l in lists.iter().flatten() { + reads.note(&Cmd::all(l)?); + } + let deltas = self.timed("what the CPU changed", |c| c.changed(r, &reads))?; let mut numbers = Vec::new(); for l in lists { numbers.push(match l { @@ -810,6 +894,11 @@ pub(super) fn read_sub( /// A slot as it goes into the file: a constant buffer view's address as /// buffer and offset. fn resolved(r: &Recorder, mut s: Slot) -> Slot { + let kind = i32::from_le_bytes([s.desc[4], s.desc[5], s.desc[6], s.desc[7]]); + if s.kind == slot::SRV && s.described != 0 && kind == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE.0 { + r.problem("views of acceleration structures are null in the capture"); + return Slot { kind: slot::SRV, ..Slot::EMPTY }; + } if s.kind == slot::CBV && s.described != 0 { match r.va(s.address()) { Va::At { res, offset } => { @@ -910,6 +999,32 @@ mod tests { assert!(find(&live, &mut kept).is_empty()); } + #[test] + fn what_a_submission_reads() { + let mut reads = Reads::default(); + let part = |from, len| Cmd::CopyBuffer { dst: 9, dst_at: 0, src: 1, src_at: from, len }; + reads.note(&[ + part(100, 50), + part(4000, 200), + part(20_000, 1), + Cmd::CopyTexture { + dst: Loc::Sub { res: 9, sub: 0 }, + at: [0; 3], + src: Loc::Placed { res: 2, offset: 4096, format: 28, size: [16, 16, 1], pitch: 256 }, + part: None, + }, + Cmd::Indirect { signature: 1, most: 1, args: 3, at: 8, count: 0, count_at: 0 }, + Cmd::RootView { graphics: true, kind: slot::CBV, param: 0, va: Va::At { res: 4, offset: 5 } }, + ]); + assert_eq!(reads.pages(1, 1 << 20, false), [(0, 8192), (16384, 20480)]); + assert_eq!(reads.pages(1, 20_100, false), [(0, 8192), (16384, 20_100)], "its end"); + assert_eq!(reads.pages(2, 1 << 20, false), [(4096, 8192)]); + assert_eq!(reads.pages(3, 100, false), [(0, 100)]); + assert_eq!(reads.pages(4, 100, false), [(0, 100)]); + assert_eq!(reads.pages(5, 100, true), [(0, 100)], "a descriptor names it"); + assert!(reads.pages(5, 100, false).is_empty() && reads.pages(9, 100, false).is_empty()); + } + #[test] fn zeros() { assert!(zero(&[])); diff --git a/crates/victory-gpu/tests/replay.rs b/crates/victory-gpu/tests/replay.rs index e774e66..3d5eb5a 100644 --- a/crates/victory-gpu/tests/replay.rs +++ b/crates/victory-gpu/tests/replay.rs @@ -25,7 +25,7 @@ use windows::core::{Interface, PCSTR, s, w}; const SIZE: u32 = 128; const DRAW: &str = r#" -#define RS "RootConstants(num32BitConstants=2, b0), CBV(b1), DescriptorTable(SRV(t0, numDescriptors=unbounded)), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_POINT)" +#define RS "RootConstants(num32BitConstants=2, b0), CBV(b1), DescriptorTable(SRV(t0, numDescriptors=unbounded)), DescriptorTable(Sampler(s0))" cbuffer Pick : register(b0) { uint pick; uint pad; }; cbuffer Place : register(b1) { float4 place; }; Texture2D all[] : register(t0); @@ -45,6 +45,15 @@ V vs(uint i : SV_VertexID) { float4 ps(V v) : SV_Target { return all[NonUniformResourceIndex(pick)].SampleLevel(point_sampler, v.uv, 0); } "#; +/// Triangles of vertices and indices. +const PLAIN: &str = r#" +#define RS "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)" +struct V { float4 at : SV_Position; float3 color : COLOR; }; +[RootSignature(RS)] +V vs(float2 at : POSITION, float3 color : COLOR1) { V v; v.at = float4(at, 0.4, 1); v.color = color; return v; } +float4 ps(V v) : SV_Target { return float4(v.color, 1); } +"#; + /// Writes the arguments of indirect draws (two records: six vertices, and /// one far too many that the clamp cuts to none). const ARGS: &str = r#" @@ -247,9 +256,18 @@ const TO: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_DEST; const FROM: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_SOURCE; const ARGUMENTS: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; +/// A texture the frames do not touch: what each subresource holds, row by +/// row, with the rows' distance in its copyable layout. +#[derive(PartialEq, Debug, Clone)] +struct Still { + name: &'static str, + subs: Vec<(usize, Vec>)>, +} + /// What the program ends with. #[derive(PartialEq, Debug)] struct Outcome { + still: Vec, picture: Vec, image: Vec, sum: Vec, @@ -264,6 +282,11 @@ struct Scene { value: u64, lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>, draw: Made, + plain: Made, + vertices: (ID3D12Resource, *mut u8), + samplers: ID3D12DescriptorHeap, + still: Vec<(&'static str, ID3D12Resource, D3D12_RESOURCE_STATES)>, + copies: (ID3D12CommandQueue, ID3D12CommandAllocator, ID3D12GraphicsCommandList), args: Made, clamp: Made, add: Made, @@ -339,6 +362,26 @@ impl Scene { let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap(); record::name(&pso, "a drawing pipeline"); let draw = Made { root, pso }; + let (vs, ps) = (compile(PLAIN, s!("vs"), s!("vs_5_1")), compile(PLAIN, s!("ps"), s!("ps_5_1"))); + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); + let element = |name, index, format, at| D3D12_INPUT_ELEMENT_DESC { + SemanticName: name, + SemanticIndex: index, + Format: format, + InputSlot: 0, + AlignedByteOffset: at, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + InstanceDataStepRate: 0, + }; + let elements = [ + element(s!("POSITION"), 0, DXGI_FORMAT_R32G32_FLOAT, 0), + element(s!("COLOR"), 1, DXGI_FORMAT_R32G32B32_FLOAT, 8), + ]; + desc.pRootSignature = std::mem::transmute_copy(&root); + (desc.VS, desc.PS) = (code(&vs), code(&ps)); + desc.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elements.as_ptr(), NumElements: 2 }; + let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap(); + let plain = Made { root, pso }; let clamp = compute(device, CLAMP); record::name(&clamp.pso, play::CLAMP); let argument = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, ..Default::default() }; @@ -348,6 +391,18 @@ impl Scene { let heap = |kind, count, flags| -> ID3D12DescriptorHeap { device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: count, Flags: flags, NodeMask: 0 }).unwrap() }; + let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE); + let sampler = D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + MaxLOD: 8.0, + ..Default::default() + }; + let mut at = samplers.GetCPUDescriptorHandleForHeapStart(); + at.ptr += 2 * device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize; + device.CreateSampler(&sampler, at); let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5000, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE); let rtvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); let dsvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); @@ -395,6 +450,41 @@ impl Scene { D3D12_RESOURCE_STATE_GENERIC_READ, ); let back = committed(device, In::Back, &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE), TO); + let vertices = committed( + device, + In::Upload, + &buffer_desc(4096, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + ); + let still = { + let blocks = D3D12_RESOURCE_DESC { + MipLevels: 5, + DepthOrArraySize: 3, + ..texture_desc(64, DXGI_FORMAT_BC7_UNORM, D3D12_RESOURCE_FLAG_NONE) + }; + let volume = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D, + DepthOrArraySize: 8, + MipLevels: 3, + ..texture_desc(16, DXGI_FORMAT_R16_FLOAT, D3D12_RESOURCE_FLAG_NONE) + }; + let stencil = texture_desc(32, DXGI_FORMAT_R32G8X24_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + let (write, read) = (D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + [("blocks", blocks, TO, READ), ("volume", volume, TO, read), ("stencil", stencil, write, write)].map(|(name, d, made_in, ends)| { + let (t, _) = committed(device, In::Card, &d, made_in); + record::name(&t, name); + (name, t, ends) + }) + }; + let copies: (ID3D12CommandQueue, ID3D12CommandAllocator, ID3D12GraphicsCommandList) = { + let queue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COPY, ..Default::default() }) + .unwrap(); + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY).unwrap(); + let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None).unwrap(); + list.Close().unwrap(); + (queue, allocator, list) + }; for (r, n) in [(&sum, "sum"), (&image, "image"), (&target, "target"), (&shared.0, "shared"), (&one, "one"), (&other, "other")] { record::name(r, n); } @@ -410,6 +500,11 @@ impl Scene { value: 0, lists, draw, + plain, + vertices, + samplers, + still: still.to_vec(), + copies, args: compute(device, ARGS), clamp, add: compute(device, ADD), @@ -548,6 +643,9 @@ impl Scene { l.SetGraphicsRoot32BitConstant(0, pick, 0); l.SetGraphicsRootConstantBufferView(1, self.constants.0.GetGPUVirtualAddress() + at); l.SetGraphicsRootDescriptorTable(2, self.views.GetGPUDescriptorHandleForHeapStart()); + let step = self.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + let first = self.samplers.GetGPUDescriptorHandleForHeapStart().ptr; + l.SetGraphicsRootDescriptorTable(3, D3D12_GPU_DESCRIPTOR_HANDLE { ptr: first + 2 * u64::from(step) }); l.ExecuteIndirect(&self.signature, 1, &self.scratch, record * 16, None::<&ID3D12Resource>, 0); } } @@ -595,16 +693,136 @@ impl Scene { let size = SIZE as f32; l.RSSetViewports(&[D3D12_VIEWPORT { Width: size, Height: size, MaxDepth: 1.0, ..Default::default() }]); l.RSSetScissorRects(&[RECT { left: 0, top: 0, right: SIZE as i32, bottom: SIZE as i32 }]); - l.SetDescriptorHeaps(&[Some(self.views.clone())]); + l.SetDescriptorHeaps(&[Some(self.views.clone()), Some(self.samplers.clone())]); } } + /// A triangle with vertices and indices. + fn triangle(&self, l: &ID3D12GraphicsCommandList, n: u32) { + // SAFETY: an open list; live objects; inside the mapping, which the + // card does not use now. + unsafe { + let x = 0.5 + 0.05 * n as f32; + let vertices = [[x, 0.4, 1.0, 0.0, 0.0], [x + 0.3, 0.4, 0.0, 1.0, 0.0], [x, 0.9, 0.0, 0.0, 1.0f32]]; + self.vertices.1.cast::<[[f32; 5]; 3]>().write(vertices); + self.vertices.1.add(1024).cast::<[u16; 4]>().write([9, 2, 0, 1]); + let at = self.vertices.0.GetGPUVirtualAddress(); + l.SetGraphicsRootSignature(&self.plain.root); + l.SetPipelineState(&self.plain.pso); + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + l.IASetVertexBuffers(0, Some(&[D3D12_VERTEX_BUFFER_VIEW { BufferLocation: at, SizeInBytes: 60, StrideInBytes: 20 }])); + let indices = D3D12_INDEX_BUFFER_VIEW { BufferLocation: at + 1024, SizeInBytes: 8, Format: DXGI_FORMAT_R16_UINT }; + l.IASetIndexBuffer(Some(&indices)); + l.DrawIndexedInstanced(3, 1, 1, 0, 0); + } + } + + /// Fills the textures no frame touches. + fn fill_still(&mut self) { + // SAFETY: an open list; live objects; mappings written inside their + // bounds. + unsafe { + let (up, data) = committed( + &self.device, + In::Upload, + &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + ); + for i in 0..1 << 20 { + data.add(i).write((i * 31 + i / 251) as u8 & 0x3b); + } + let l = self.open(0); + let mut at = 0; + for (name, t, ends) in &self.still { + if *name == "stencil" { + let view = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let heap: ID3D12DescriptorHeap = self + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + NumDescriptors: 1, + ..Default::default() + }) + .unwrap(); + let dsv = heap.GetCPUDescriptorHandleForHeapStart(); + self.device.CreateDepthStencilView(t, Some(&view), dsv); + let both = D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL; + l.ClearDepthStencilView(dsv, both, 0.75, 3, None); + let part = RECT { left: 5, top: 6, right: 20, bottom: 17 }; + l.ClearDepthStencilView(dsv, both, 0.25, 200, Some(&[part])); + continue; + } + let desc = t.GetDesc(); + let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize }; + for sub in 0..u32::from(layers * desc.MipLevels) { + let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0; + self.device.GetCopyableFootprints(&desc, sub, 1, at, Some(&mut f), None, None, Some(&mut total)); + at = (at + total).next_multiple_of(512); + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&up), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f }, + }; + l.CopyTextureRegion(&sub_of(t, sub), 0, 0, 0, &from, None); + } + l.ResourceBarrier(&[moved(t, TO, *ends)]); + } + l.Close().unwrap(); + self.send(&[&l]); + self.wait(); + } + } + + /// What they hold. + fn read_still(&mut self) -> Vec { + let mut all = Vec::new(); + for (name, t, state) in self.still.clone() { + // SAFETY: as above. + unsafe { + let desc = t.GetDesc(); + let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize }; + let planes = if name == "stencil" { 2 } else { 1 }; + let mut subs = Vec::new(); + for sub in 0..u32::from(layers * desc.MipLevels) * planes { + let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let (mut rows, mut len) = (0, 0); + self.device.GetCopyableFootprints(&desc, sub, 1, 0, Some(&mut f), Some(&mut rows), Some(&mut len), None); + let l = self.open(0); + l.ResourceBarrier(&[moved(&t, state, FROM)]); + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&self.back.0), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f }, + }; + l.CopyTextureRegion(&to, 0, 0, 0, &sub_of(&t, sub), None); + l.ResourceBarrier(&[moved(&t, FROM, state)]); + l.Close().unwrap(); + self.send(&[&l]); + self.wait(); + let pitch = f.Footprint.RowPitch as usize; + let rows = (0..rows as usize * f.Footprint.Depth as usize) + .map(|r| std::slice::from_raw_parts(self.back.1.add(r * pitch), len as usize).to_vec()) + .collect(); + subs.push((pitch, rows)); + } + all.push(Still { name, subs }); + } + } + all + } + fn frame(&mut self, n: u32) { // SAFETY: open lists of ours, live objects; memory is written while // the card does not use it. unsafe { self.wait(); if n == 0 { + self.fill_still(); self.fill(0, [200, 10, 30, 255]); self.fill(8192, [10, 40, 220, 255]); let l = self.open(0); @@ -630,6 +848,7 @@ impl Scene { self.targets(&l); self.quad(&l, 4000, 0, 0); self.quad(&l, 4001, 256, 0); + self.triangle(&l, n); // Nothing: the clamp cut it to no vertices. self.quad(&l, 4001, 0, 1); l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]); @@ -680,6 +899,18 @@ impl Scene { l.ResourceBarrier(&[moved(&self.target, TARGET, FROM)]); l.Close().unwrap(); self.send(&[&second, &l]); + self.wait(); + // Another queue fetches a result, as the host layer's relay does. + let (queue, allocator, list) = &self.copies; + allocator.Reset().unwrap(); + list.Reset(allocator, None).unwrap(); + list.CopyBufferRegion(&self.back.0, 1 << 18, &self.sum, 0, 1024); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + self.value += 1; + queue.Signal(&self.fence, self.value).unwrap(); + self.fence.SetEventOnCompletion(self.value, self.event).unwrap(); + WaitForSingleObject(self.event, INFINITE); if let Some((swap, _)) = &self.swap { swap.Present(0, DXGI_PRESENT(0)).unwrap(); } @@ -690,6 +921,7 @@ impl Scene { /// What everything holds now. fn outcome(&mut self) -> Outcome { self.wait(); + let still = self.read_still(); let l = self.open(0); // SAFETY: an open list; live objects. unsafe { @@ -713,6 +945,7 @@ impl Scene { self.wait(); let at = |from: usize, n: usize| std::slice::from_raw_parts(self.back.1.add(from), n).to_vec(); Outcome { + still, picture: at(0, (SIZE * 512) as usize), image: rows(&at(1 << 18, 4096)), sum: at(1 << 19, 1024), @@ -722,6 +955,15 @@ impl Scene { } } +fn sub_of(t: &ID3D12Resource, sub: u32) -> D3D12_TEXTURE_COPY_LOCATION { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer never released. + pResource: unsafe { std::mem::transmute_copy(t) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub }, + } +} + /// The 64 bytes of each row of a 16x16 texture. fn rows(bytes: &[u8]) -> Vec { bytes.chunks(256).flat_map(|r| r[..64].to_vec()).collect() @@ -782,7 +1024,19 @@ fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str) assert_eq!(rows(&get("image")), expected.image, "{what}: image"); assert_eq!(get("target"), expected.picture, "{what}: target"); assert!(get("shared") == expected.shared, "{what}: memory the CPU sees"); - assert!(!report.notes.iter().any(|n| n.contains("recorder:") && !n.contains("submissions,") && !n.contains("waits of the")), "{what}: {:?}", report.notes); + for still in &expected.still { + let id = player.named(still.name).unwrap(); + for (sub, (pitch, rows)) in still.subs.iter().enumerate() { + let have = player.contents_of(id, sub as u32).unwrap().unwrap(); + for (r, row) in rows.iter().enumerate() { + assert_eq!(&have[r * pitch..][..row.len()], &row[..], "{what}: {} subresource {sub} row {r}", still.name); + } + } + } + // Nothing was left out but what another queue ran. + let known = ["submissions,", "waits of the drawing queue", "lists sent to a queue other than"]; + assert!(!report.notes.iter().any(|n| n.contains("recorder:") && !known.iter().any(|k| n.contains(k))), "{what}: {:?}", report.notes); + assert!(report.notes.iter().any(|n| n.contains(known[2]))); report } @@ -813,6 +1067,10 @@ fn a_frame_is_recorded_and_replayed() { eprintln!("ran without the recorder"); // Something is in the picture. assert!(without.sum.iter().any(|&b| b != 0)); + for s in &without.still { + assert!(s.subs.iter().all(|(_, rows)| rows.iter().flatten().any(|&b| b != 0)), "{}", s.name); + } + assert_eq!(without.still.iter().map(|s| s.subs.len()).collect::>(), [15, 3, 2]); let colors: std::collections::HashSet<[u8; 4]> = without.picture.chunks_exact(4).map(|c| [c[0], c[1], c[2], c[3]]).collect(); assert!(colors.len() > 30, "{}", colors.len()); @@ -821,12 +1079,12 @@ fn a_frame_is_recorded_and_replayed() { // frame whose lists are all recorded comes first). assert!(!record::on()); let dir = tempfile::tempdir().unwrap(); - let settings = Settings { folder: dir.path().to_owned(), at: At::Frame(1), frames: 1 }; + let settings = Settings { folder: dir.path().to_owned(), at: At::Frame(1), frames: 1, always: false }; let folder = record::start(settings, &device).unwrap(); assert!(record::on()); assert_ne!(table_of(&device), own, "the device is hooked"); assert!( - record::start(Settings { folder: dir.path().to_owned(), at: At::Trigger, frames: 1 }, &device).is_err(), + record::start(Settings { folder: dir.path().to_owned(), at: At::Trigger, frames: 1, always: false }, &device).is_err(), "one recorder a process" ); eprintln!("recorder on"); diff --git a/crates/victory-gpu/tests/replay_big.rs b/crates/victory-gpu/tests/replay_big.rs new file mode 100644 index 0000000..34a9b95 --- /dev/null +++ b/crates/victory-gpu/tests/replay_big.rs @@ -0,0 +1,271 @@ +//! How the frame recorder and replayer do at the size of a title's frame +//! (not run by default: `cargo test --release ... -- --ignored --nocapture`): +//! thousands of textures and buffers, a view heap of 1.5 million slots, 30 +//! submissions of 40,000 calls. +//! +//! `BIG_TEXTURES` (17000) and `BIG_FOLDER` (a temporary one) change it. +#![cfg(all(windows, feature = "diagnostics"))] + +use std::mem::ManuallyDrop; +use std::time::Instant; + +use victory_gpu::replay::play::{self, Options}; +use victory_gpu::replay::record::{self, At, Settings}; +use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::core::Interface; + +const SUBMITS: usize = 30; +const CALLS: usize = 40_000; +const VIEWS: u32 = 1_500_000; + +fn buffer(device: &ID3D12Device, kind: u32, size: u64) -> (ID3D12Resource, *mut u8) { + let (heap, state, flags) = match kind { + 0 => ( + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ), + 1 => ( + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_RESOURCE_STATE_GENERIC_READ, + D3D12_RESOURCE_FLAG_NONE, + ), + _ => ( + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ), + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let mut made: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping. + unsafe { + device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut made).unwrap(); + let made = made.unwrap(); + if kind > 0 { + made.Map(0, None, Some(&mut data)).unwrap(); + // Not all zero, as real data is. + for at in (0..size as usize).step_by(4096) { + data.cast::().add(at).write(at as u8 | 1); + } + } + (made, data.cast()) + } +} + +fn barrier(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: a borrowed pointer never released. + pResource: unsafe { std::mem::transmute_copy(res) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + ..Default::default() + } +} + +struct Big { + device: ID3D12Device, + queue: ID3D12CommandQueue, + fence: ID3D12Fence, + value: u64, + lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>, + _textures: Vec, + card: Vec, + shared: Vec<(ID3D12Resource, *mut u8)>, + upload: Vec<(ID3D12Resource, *mut u8)>, + views: ID3D12DescriptorHeap, + target: ID3D12Resource, +} + +impl Big { + fn new(device: &ID3D12Device, textures: usize) -> Big { + let texture = |size: u32, flags, state| { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(size), + Height: size, + DepthOrArraySize: 1, + MipLevels: if size == 256 { 9 } else { 1 }, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: flags, + ..Default::default() + }; + let mut made: Option = None; + // SAFETY: plain creation. + unsafe { device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut made).unwrap() }; + made.unwrap() + }; + // SAFETY: plain creation; slots of the heap just made. + unsafe { + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .unwrap(); + let lists = (0..SUBMITS) + .map(|_| { + let a: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let l: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a, None).unwrap(); + l.Close().unwrap(); + (a, l) + }) + .collect(); + let views: ID3D12DescriptorHeap = device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: VIEWS, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .unwrap(); + let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let start = views.GetCPUDescriptorHandleForHeapStart().ptr; + let textures: Vec = (0..textures) + .map(|_| texture(256, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE)) + .collect(); + for i in 0..VIEWS as usize { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start + i * step }; + device.CreateShaderResourceView(&textures[i % textures.len()], None, at); + } + let shared: Vec<(ID3D12Resource, *mut u8)> = (0..1000).map(|_| buffer(device, 2, 1 << 20)).collect(); + for (i, (b, _)) in shared.iter().enumerate() { + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { NumElements: 1 << 18, Flags: D3D12_BUFFER_SRV_FLAG_RAW, ..Default::default() }, + }, + }; + device.CreateShaderResourceView(b, Some(&desc), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start + i * step }); + } + Big { + device: device.clone(), + queue, + fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(), + value: 0, + lists, + _textures: textures, + card: (0..600).map(|_| buffer(device, 0, 1 << 20).0).collect(), + shared, + upload: (0..1000).map(|_| buffer(device, 1, 1 << 20)).collect(), + views, + target: texture(1024, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE), + } + } + } + + fn wait(&mut self) { + self.value += 1; + // SAFETY: our queue and fence. + unsafe { + let event = CreateEventW(None, false, false, None).unwrap(); + self.queue.Signal(&self.fence, self.value).unwrap(); + self.fence.SetEventOnCompletion(self.value, event).unwrap(); + WaitForSingleObject(event, INFINITE); + let _ = windows::Win32::Foundation::CloseHandle(event); + self.device.GetDeviceRemovedReason().unwrap(); + } + } + + fn frame(&mut self, n: usize) { + for s in 0..SUBMITS { + // SAFETY: lists whose last run has finished; mappings written + // inside their bounds. + unsafe { + let (a, l) = &self.lists[s]; + a.Reset().unwrap(); + l.Reset(a, None).unwrap(); + l.SetDescriptorHeaps(&[Some(self.views.clone())]); + for i in 0..CALLS / SUBMITS / 4 { + let card = &self.card[(i * 7 + s) % self.card.len()]; + let from = &self.upload[(i + s * 31) % self.upload.len()].0; + l.CopyBufferRegion(card, (i % 1000 * 1000) as u64 & !3, from, 0, 256); + l.ResourceBarrier(&[barrier(card, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + l.ResourceBarrier(&[barrier(card, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST)]); + l.SetMarker(1, None, 0); + } + l.Close().unwrap(); + for i in 0..60 { + let at = (n * 97 + s * 13 + i * 7) % 1000; + self.shared[at].1.add(i * 4096).write((n + s) as u8); + self.upload[at].1.add(i * 8192).write((n + s) as u8); + } + self.queue.ExecuteCommandLists(&[Some(l.cast().unwrap())]); + } + self.wait(); + } + record::present(&self.target, D3D12_RESOURCE_STATE_COPY_SOURCE); + } +} + +#[test] +#[ignore = "takes gigabytes of the card's memory and the disk"] +fn a_frame_of_a_titles_size() { + let mut device: Option = None; + // SAFETY: plain creation. + unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).unwrap() }; + let device = device.unwrap(); + let textures = std::env::var("BIG_TEXTURES").ok().and_then(|v| v.parse().ok()).unwrap_or(17_000); + let timed = |what: &str, began: Instant| println!("{what}: {:.1} ms", began.elapsed().as_secs_f64() * 1e3); + let began = Instant::now(); + { + let mut big = Big::new(&device, textures); + timed("made, without the recorder", began); + for n in 0..4 { + let began = Instant::now(); + big.frame(n); + timed("frame, without the recorder", began); + } + } + let dir = tempfile::tempdir().unwrap(); + let folder = std::env::var_os("BIG_FOLDER").map_or(dir.path().to_owned(), Into::into); + let settings = Settings { folder, at: At::Frame(4), frames: 1, always: false }; + let folder = record::start(settings, &device).unwrap(); + let began = Instant::now(); + let mut big = Big::new(&device, textures); + timed("made, with the recorder", began); + for n in 0..8 { + let began = Instant::now(); + big.frame(n); + timed(["frame", "frame, lists recorded", "frame, captured", "frame, after"][[0, 0, 0, 0, 1, 1, 2, 3][n]], began); + } + assert_eq!(record::finished(), Some(folder.clone())); + drop(big); + record::unhook(&device); + println!("{}", std::fs::read_to_string(folder.join("notes.txt")).unwrap()); + for f in std::fs::read_dir(&folder).unwrap().flatten() { + println!("{:>8} MB {}", f.metadata().unwrap().len() >> 20, f.file_name().to_string_lossy()); + } + let began = Instant::now(); + let reports = play::replay(&folder, &Options { loops: 3, ..Default::default() }).unwrap(); + timed("loaded and replayed", began); + for (what, r) in &reports { + println!("{}", r.text(what)); + } +} diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs index ed5b632..a61e988 100644 --- a/crates/victory-hle/src/lib.rs +++ b/crates/victory-hle/src/lib.rs @@ -19,6 +19,8 @@ pub mod runtime; pub use host::HostPolicy; pub use registry::{HleExport, HleModule, registry}; pub use victory_gpu::console; +#[cfg(all(windows, feature = "diagnostics"))] +pub use victory_gpu::replay; use victory_loader::{ImportResolver, Provenance, Resolution}; use victory_pe::ImportSymbol; From af481877f3cf2af6e5d3dabd11df597c713ce848 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 20:23:46 -0600 Subject: [PATCH 157/445] Frame replay: usage doc, mesh draws and a title's size in its tests Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 5 +- crates/victory-gpu/src/replay/edit.rs | 243 ++++- crates/victory-gpu/src/replay/gpu.rs | 115 ++- crates/victory-gpu/src/replay/hook.rs | 91 +- crates/victory-gpu/src/replay/play.rs | 1235 ++++++++++++++++++----- crates/victory-gpu/src/replay/pso.rs | 203 +++- crates/victory-gpu/src/replay/record.rs | 1035 +++++++++++++++---- crates/victory-gpu/src/replay/snap.rs | 496 +++++++-- crates/victory-gpu/src/replay/states.rs | 93 +- crates/victory-gpu/src/replay/wire.rs | 351 ++++++- crates/victory-gpu/tests/replay.rs | 948 ++++++++++++++--- crates/victory-gpu/tests/replay_big.rs | 185 +++- docs/replay.md | 102 ++ 13 files changed, 4274 insertions(+), 828 deletions(-) create mode 100644 docs/replay.md diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index 61de570..cad167a 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -85,7 +85,10 @@ fn range(text: &str) -> Option<(u32, u32)> { pub(crate) fn run(r: Replay) -> Result<()> { let only = match &r.only { - Some(text) => Some(range(text).with_context(|| format!("--only {text}: not a list or a range of lists (3..7)"))?), + Some(text) => Some( + range(text) + .with_context(|| format!("--only {text}: not a list or a range of lists (3..7)"))?, + ), None => None, }; let options = Options { diff --git a/crates/victory-gpu/src/replay/edit.rs b/crates/victory-gpu/src/replay/edit.rs index a49a343..08184a3 100644 --- a/crates/victory-gpu/src/replay/edit.rs +++ b/crates/victory-gpu/src/replay/edit.rs @@ -52,7 +52,9 @@ pub fn no_uav_barriers(cmds: Vec) -> (Vec, u32) { /// Barriers only: what a list left out still does to the states of /// resources. pub fn barriers_only(cmds: Vec) -> Vec { - cmds.into_iter().filter(|c| matches!(c, Cmd::Barriers { .. })).collect() + cmds.into_iter() + .filter(|c| matches!(c, Cmd::Barriers { .. })) + .collect() } /// Joins the barrier calls with no work between them into one; how many @@ -96,7 +98,9 @@ pub fn merge_barriers(cmds: Vec) -> (Vec, u32) { fn join(have: &mut Vec, b: Barrier) { match b { Barrier::Uav { res, .. } => { - let covered = have.iter().any(|h| matches!(h, Barrier::Uav { res: r, .. } if *r == res || *r == NONE)); + let covered = have + .iter() + .any(|h| matches!(h, Barrier::Uav { res: r, .. } if *r == res || *r == NONE)); if covered { return; } @@ -105,16 +109,36 @@ fn join(have: &mut Vec, b: Barrier) { } have.push(b); } - Barrier::Transition { flags: 0, res, sub, before, after } => { + Barrier::Transition { + flags: 0, + res, + sub, + before, + after, + } => { // The last one of this resource, if it is of the same part of it. - let last = have.iter().rposition(|h| matches!(h, Barrier::Transition { res: r, .. } if *r == res)); + let last = have + .iter() + .rposition(|h| matches!(h, Barrier::Transition { res: r, .. } if *r == res)); if let Some(i) = last - && let Barrier::Transition { flags: 0, sub: s, before: first, after: until, .. } = have[i] + && let Barrier::Transition { + flags: 0, + sub: s, + before: first, + after: until, + .. + } = have[i] && s == sub && until == before { if first != after { - have[i] = Barrier::Transition { flags: 0, res, sub, before: first, after }; + have[i] = Barrier::Transition { + flags: 0, + res, + sub, + before: first, + after, + }; } else { have.remove(i); if after == UNORDERED_ACCESS { @@ -150,7 +174,12 @@ pub fn find_clamps(cmds: &[Cmd], psos: &HashSet, next: &mut u64) -> Vec bound = *pso, - Cmd::Constants { graphics: false, param: 0, offset, values } => { + Cmd::Constants { + graphics: false, + param: 0, + offset, + values, + } => { for (i, v) in values.iter().enumerate() { if let Some(c) = constants.get_mut(*offset as usize + i) { *c = *v; @@ -159,11 +188,21 @@ pub fn find_clamps(cmds: &[Cmd], psos: &HashSet, next: &mut u64) -> Vec to = Some(*res), + Cmd::RootView { + graphics: false, + param: 3, + va: Va::At { res, offset: 0 }, + .. + } => to = Some(*res), Cmd::Dispatch { .. } if psos.contains(&bound) => { if let Some(scratch) = to { let bytes = u64::from(constants[1]) * u64::from(constants[2]); - found.push(Clamp { at, scratch, bytes, result: *next }); + found.push(Clamp { + at, + scratch, + bytes, + result: *next, + }); *next += bytes.next_multiple_of(256); } } @@ -189,10 +228,22 @@ pub fn keep_clamped(cmds: Vec, clamps: &[Clamp]) -> Vec { out.push(c); if done && let Some(clamp) = open.take() { let moved = |before, after| Cmd::Barriers { - all: vec![Barrier::Transition { flags: 0, res: clamp.scratch, sub: ALL, before, after }], + all: vec![Barrier::Transition { + flags: 0, + res: clamp.scratch, + sub: ALL, + before, + after, + }], }; out.push(moved(INDIRECT_ARGUMENT, COPY_SOURCE)); - out.push(Cmd::CopyBuffer { dst: RESULTS, dst_at: clamp.result, src: clamp.scratch, src_at: 0, len: clamp.bytes }); + out.push(Cmd::CopyBuffer { + dst: RESULTS, + dst_at: clamp.result, + src: clamp.scratch, + src_at: 0, + len: clamp.bytes, + }); out.push(moved(COPY_SOURCE, INDIRECT_ARGUMENT)); } } @@ -223,9 +274,23 @@ pub fn skip_clamps(cmds: Vec, clamps: &[Clamp]) -> Vec { out.push(Cmd::Barriers { all }); } } - Cmd::Indirect { signature, most, args, at, count, count_at } if last.contains_key(&args) => { + Cmd::Indirect { + signature, + most, + args, + at, + count, + count_at, + } if last.contains_key(&args) => { let result = last.get(&args).copied().unwrap_or(0); - out.push(Cmd::Indirect { signature, most, args: RESULTS, at: result + at, count, count_at }); + out.push(Cmd::Indirect { + signature, + most, + args: RESULTS, + at: result + at, + count, + count_at, + }); } c => out.push(c), } @@ -247,7 +312,13 @@ mod tests { Barrier::Uav { flags: 0, res } } fn moved(res: u32, before: i32, after: i32) -> Barrier { - Barrier::Transition { flags: 0, res, sub: ALL, before, after } + Barrier::Transition { + flags: 0, + res, + sub: ALL, + before, + after, + } } fn barriers(all: &[Barrier]) -> Cmd { Cmd::Barriers { all: all.to_vec() } @@ -255,18 +326,47 @@ mod tests { #[test] fn pipelines_are_skipped() { - let list = vec![pso(1), go(), pso(2), go(), go(), Cmd::CopyResource { dst: 1, src: 2 }, pso(1), go()]; + let list = vec![ + pso(1), + go(), + pso(2), + go(), + go(), + Cmd::CopyResource { dst: 1, src: 2 }, + pso(1), + go(), + ]; let (out, n) = skip_pipelines(list.clone(), &HashSet::from([2])); assert_eq!(n, 2); - assert_eq!(out, vec![pso(1), go(), pso(2), Cmd::CopyResource { dst: 1, src: 2 }, pso(1), go()]); + assert_eq!( + out, + vec![ + pso(1), + go(), + pso(2), + Cmd::CopyResource { dst: 1, src: 2 }, + pso(1), + go() + ] + ); assert_eq!(skip_pipelines(list.clone(), &HashSet::new()), (list, 0)); } #[test] fn uav_barriers_are_dropped() { - let list = vec![barriers(&[uav(0)]), go(), barriers(&[uav(1), moved(1, 8, 4)])]; - assert_eq!(no_uav_barriers(list.clone()), (vec![go(), barriers(&[moved(1, 8, 4)])], 2)); - assert_eq!(barriers_only(list.clone()), vec![list[0].clone(), list[2].clone()]); + let list = vec![ + barriers(&[uav(0)]), + go(), + barriers(&[uav(1), moved(1, 8, 4)]), + ]; + assert_eq!( + no_uav_barriers(list.clone()), + (vec![go(), barriers(&[moved(1, 8, 4)])], 2) + ); + assert_eq!( + barriers_only(list.clone()), + vec![list[0].clone(), list[2].clone()] + ); } #[test] @@ -286,11 +386,33 @@ mod tests { ]; let (out, saved) = merge_barriers(list); assert_eq!(saved, 4); - assert_eq!(out, vec![barriers(&[moved(1, 0, 64), uav(0)]), pso(1), go(), barriers(&[uav(1)]), go()]); + assert_eq!( + out, + vec![ + barriers(&[moved(1, 0, 64), uav(0)]), + pso(1), + go(), + barriers(&[uav(1)]), + go() + ] + ); // Parts of a resource are not mixed up. - let part = |sub, before, after| Barrier::Transition { flags: 0, res: 1, sub, before, after }; - let list = vec![barriers(&[part(0, 4, 8)]), barriers(&[part(1, 4, 8)]), barriers(&[part(ALL, 8, 64)])]; - assert_eq!(merge_barriers(list).0, vec![barriers(&[part(0, 4, 8), part(1, 4, 8), part(ALL, 8, 64)])]); + let part = |sub, before, after| Barrier::Transition { + flags: 0, + res: 1, + sub, + before, + after, + }; + let list = vec![ + barriers(&[part(0, 4, 8)]), + barriers(&[part(1, 4, 8)]), + barriers(&[part(ALL, 8, 64)]), + ]; + assert_eq!( + merge_barriers(list).0, + vec![barriers(&[part(0, 4, 8), part(1, 4, 8), part(ALL, 8, 64)])] + ); } #[test] @@ -299,29 +421,84 @@ mod tests { vec![ barriers(&[uav(0), moved(scratch, 0, 8)]), pso(9), - Cmd::Constants { graphics: false, param: 0, offset: 0, values: vec![10, stride, records, 0, 0, 0] }, - Cmd::RootView { graphics: false, kind: 3, param: 3, va: Va::At { res: scratch, offset: 0 } }, + Cmd::Constants { + graphics: false, + param: 0, + offset: 0, + values: vec![10, stride, records, 0, 0, 0], + }, + Cmd::RootView { + graphics: false, + kind: 3, + param: 3, + va: Va::At { + res: scratch, + offset: 0, + }, + }, go(), barriers(&[uav(0), moved(scratch, 8, 0x200)]), ] }; - let run = |args, at| Cmd::Indirect { signature: 1, most: 1, args, at, count: 0, count_at: 0 }; + let run = |args, at| Cmd::Indirect { + signature: 1, + most: 1, + args, + at, + count: 0, + count_at: 0, + }; let mut list = clamp(5, 12, 2); list.extend([pso(1), run(5, 12), run(5, 0), run(6, 0)]); list.extend(clamp(5, 12, 100)); list.extend([pso(1), run(5, 24), barriers(&[moved(5, 0x200, 0)])]); let mut next = 0; let found = find_clamps(&list, &HashSet::from([9]), &mut next); - assert_eq!(found.iter().map(|c| (c.scratch, c.bytes, c.result)).collect::>(), [(5, 24, 0), (5, 1200, 256)]); + assert_eq!( + found + .iter() + .map(|c| (c.scratch, c.bytes, c.result)) + .collect::>(), + [(5, 24, 0), (5, 1200, 256)] + ); assert_eq!(next, 256 + 1280); let kept = keep_clamped(list.clone(), &found); assert_eq!(kept.len(), list.len() + 6); - assert_eq!(kept[7], Cmd::CopyBuffer { dst: RESULTS, dst_at: 0, src: 5, src_at: 0, len: 24 }); - assert_eq!(kept.iter().filter(|c| matches!(c, Cmd::CopyBuffer { .. })).count(), 2); + assert_eq!( + kept[7], + Cmd::CopyBuffer { + dst: RESULTS, + dst_at: 0, + src: 5, + src_at: 0, + len: 24 + } + ); + assert_eq!( + kept.iter() + .filter(|c| matches!(c, Cmd::CopyBuffer { .. })) + .count(), + 2 + ); let skipped = skip_clamps(list, &found); - assert!(!skipped.iter().any(|c| matches!(c, Cmd::Dispatch { .. } | Cmd::Barriers { .. }))); - let runs: Vec<(u32, u64)> = - skipped.iter().filter_map(|c| if let Cmd::Indirect { args, at, .. } = c { Some((*args, *at)) } else { None }).collect(); - assert_eq!(runs, [(RESULTS, 12), (RESULTS, 0), (6, 0), (RESULTS, 256 + 24)]); + assert!( + !skipped + .iter() + .any(|c| matches!(c, Cmd::Dispatch { .. } | Cmd::Barriers { .. })) + ); + let runs: Vec<(u32, u64)> = skipped + .iter() + .filter_map(|c| { + if let Cmd::Indirect { args, at, .. } = c { + Some((*args, *at)) + } else { + None + } + }) + .collect(); + assert_eq!( + runs, + [(RESULTS, 12), (RESULTS, 0), (6, 0), (RESULTS, 256 + 24)] + ); } } diff --git a/crates/victory-gpu/src/replay/gpu.rs b/crates/victory-gpu/src/replay/gpu.rs index 61ed472..97ff62e 100644 --- a/crates/victory-gpu/src/replay/gpu.rs +++ b/crates/victory-gpu/src/replay/gpu.rs @@ -46,9 +46,15 @@ impl Worker { let i = match self.lists.iter().position(|l| l.2 <= done) { Some(i) => i, None => { - let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let list: ID3D12GraphicsCommandList = - self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + let allocator: ID3D12CommandAllocator = self + .device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = self.device.CreateCommandList( + 0, + D3D12_COMMAND_LIST_TYPE_DIRECT, + &allocator, + None, + )?; list.Close()?; self.lists.push((allocator, list, 0)); self.lists.len() - 1 @@ -100,7 +106,10 @@ pub(super) fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOU Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() @@ -114,7 +123,10 @@ pub(super) fn buffer( size: u64, flags: D3D12_RESOURCE_FLAGS, ) -> Result<(ID3D12Resource, *mut u8)> { - let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }; + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; let state = match kind { D3D12_HEAP_TYPE_UPLOAD => D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_HEAP_TYPE_READBACK => D3D12_RESOURCE_STATE_COPY_DEST, @@ -124,7 +136,14 @@ pub(super) fn buffer( let mut data = std::ptr::null_mut(); // SAFETY: plain creation and mapping. unsafe { - device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(size, flags), state, None, &mut made)?; + device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &buffer_desc(size, flags), + state, + None, + &mut made, + )?; let made = made.ok_or_else(windows::core::Error::empty)?; if kind == D3D12_HEAP_TYPE_UPLOAD || kind == D3D12_HEAP_TYPE_READBACK { made.Map(0, None, Some(&mut data))?; @@ -146,7 +165,11 @@ pub(super) fn subresources(d: &wire::Desc) -> u32 { if d.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { return 1; } - let layers = if d.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { 1 } else { u32::from(d.depth) }; + let layers = if d.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { + 1 + } else { + u32::from(d.depth) + }; u32::from(d.mips.max(1)) * layers.max(1) * planes(d.format) } @@ -161,7 +184,18 @@ pub(super) fn footprints( let mut all = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize]; let mut total = 0; // SAFETY: outputs for `count` subresources. - unsafe { device.GetCopyableFootprints(desc, first, count, 0, Some(all.as_mut_ptr()), None, None, Some(&mut total)) }; + unsafe { + device.GetCopyableFootprints( + desc, + first, + count, + 0, + Some(all.as_mut_ptr()), + None, + None, + Some(&mut total), + ) + }; (all, total) } @@ -171,12 +205,17 @@ pub(super) fn sub_location(res: &ID3D12Resource, sub: u32) -> D3D12_TEXTURE_COPY // SAFETY: a borrowed pointer the location never releases. pResource: unsafe { std::mem::transmute_copy(res) }, Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: sub, + }, } } /// A location naming bytes of a buffer; no reference is taken. -pub(super) fn placed_location(res: &ID3D12Resource, f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT) -> D3D12_TEXTURE_COPY_LOCATION { +pub(super) fn placed_location( + res: &ID3D12Resource, + f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT, +) -> D3D12_TEXTURE_COPY_LOCATION { D3D12_TEXTURE_COPY_LOCATION { // SAFETY: as above. pResource: unsafe { std::mem::transmute_copy(res) }, @@ -186,7 +225,12 @@ pub(super) fn placed_location(res: &ID3D12Resource, f: D3D12_PLACED_SUBRESOURCE_ } /// A transition; no reference is taken. -pub(super) fn transition(res: &ID3D12Resource, sub: u32, before: u32, after: u32) -> D3D12_RESOURCE_BARRIER { +pub(super) fn transition( + res: &ID3D12Resource, + sub: u32, + before: u32, + after: u32, +) -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -204,7 +248,12 @@ pub(super) fn transition(res: &ID3D12Resource, sub: u32, before: u32, after: u32 /// The barriers that move a texture from `from` (one state, or one for each /// subresource) to `to`. -pub(super) fn moves(res: &ID3D12Resource, from: &[u32], to: &[u32], out: &mut Vec) { +pub(super) fn moves( + res: &ID3D12Resource, + from: &[u32], + to: &[u32], + out: &mut Vec, +) { let n = from.len().max(to.len()); if n == 1 { if from[0] != to[0] { @@ -229,7 +278,10 @@ pub(super) fn to_desc(d: &wire::Desc) -> D3D12_RESOURCE_DESC { DepthOrArraySize: d.depth, MipLevels: d.mips, Format: DXGI_FORMAT(d.format), - SampleDesc: DXGI_SAMPLE_DESC { Count: d.samples[0], Quality: d.samples[1] }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: d.samples[0], + Quality: d.samples[1], + }, Layout: D3D12_TEXTURE_LAYOUT(d.layout), Flags: D3D12_RESOURCE_FLAGS(d.flags), } @@ -260,7 +312,11 @@ pub(super) fn to_props(p: &wire::HeapProps) -> D3D12_HEAP_PROPERTIES { } pub(super) fn from_props(p: &D3D12_HEAP_PROPERTIES) -> wire::HeapProps { - wire::HeapProps { kind: p.Type.0, cpu: p.CPUPageProperty.0, pool: p.MemoryPoolPreference.0 } + wire::HeapProps { + kind: p.Type.0, + cpu: p.CPUPageProperty.0, + pool: p.MemoryPoolPreference.0, + } } /// How the CPU sees memory of a heap. @@ -294,7 +350,13 @@ pub(super) fn seen(p: &wire::HeapProps) -> Seen { /// 8-bit RGB of a presented texture's rows (and the greatest channel value /// of the format, for the signal-to-noise ratio). `None` for formats not /// shown. -pub(super) fn rgb(width: u32, height: u32, pitch: u32, format: i32, rows: &[u8]) -> Option> { +pub(super) fn rgb( + width: u32, + height: u32, + pitch: u32, + format: i32, + rows: &[u8], +) -> Option> { let mut out = Vec::with_capacity((width * height * 3) as usize); let half = |b: &[u8]| { let h = u16::from_le_bytes([b[0], b[1]]); @@ -304,7 +366,11 @@ pub(super) fn rgb(width: u32, height: u32, pitch: u32, format: i32, rows: &[u8]) 31 => 65536.0, e => (1.0 + m / 1024.0) * 2f32.powi(i32::from(e) - 15), }; - if s == 1 { 0 } else { (v.min(1.0) * 255.0) as u8 } + if s == 1 { + 0 + } else { + (v.min(1.0) * 255.0) as u8 + } }; for y in 0..height as usize { let row = rows.get(y * pitch as usize..)?; @@ -334,7 +400,11 @@ pub(super) fn rgb(width: u32, height: u32, pitch: u32, format: i32, rows: &[u8]) /// Peak signal-to-noise ratio of two pictures of 8-bit channels, in dB /// (infinite if equal). pub(super) fn psnr(a: &[u8], b: &[u8]) -> f64 { - let sum: u64 = a.iter().zip(b).map(|(&x, &y)| u64::from(x.abs_diff(y)).pow(2)).sum(); + let sum: u64 = a + .iter() + .zip(b) + .map(|(&x, &y)| u64::from(x.abs_diff(y)).pow(2)) + .sum(); if sum == 0 && a.len() == b.len() { return f64::INFINITY; } @@ -354,7 +424,11 @@ pub(super) fn adapter(device: &ID3D12Device) -> (String, u32, u32) { match desc { Ok(d) => { let name = String::from_utf16_lossy(&d.Description); - (name.trim_end_matches('\0').to_owned(), d.VendorId, d.DeviceId) + ( + name.trim_end_matches('\0').to_owned(), + d.VendorId, + d.DeviceId, + ) } Err(_) => ("unknown".into(), 0, 0), } @@ -371,7 +445,10 @@ mod tests { let v = (1023u32 | 512 << 10).to_le_bytes(); assert_eq!(rgb(1, 1, 4, 24, &v).unwrap(), [255, 128, 0]); // 1.0, 0.5 and -1.0 as halves. - assert_eq!(rgb(1, 1, 8, 10, &[0, 0x3c, 0, 0x38, 0, 0xbc, 0, 0]).unwrap(), [255, 127, 0]); + assert_eq!( + rgb(1, 1, 8, 10, &[0, 0x3c, 0, 0x38, 0, 0xbc, 0, 0]).unwrap(), + [255, 127, 0] + ); assert!(rgb(1, 1, 4, 41, &[0; 4]).is_none()); assert!(rgb(2, 2, 8, 28, &[0; 12]).is_none(), "too few rows"); assert_eq!(psnr(&[1, 2], &[1, 2]), f64::INFINITY); diff --git a/crates/victory-gpu/src/replay/hook.rs b/crates/victory-gpu/src/replay/hook.rs index e4ceca4..e18c3c3 100644 --- a/crates/victory-gpu/src/replay/hook.rs +++ b/crates/victory-gpu/src/replay/hook.rs @@ -9,7 +9,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; /// Methods in a copied table: more than any D3D12 interface has (an /// interface's private methods may follow its public ones). -pub(super) const SLOTS: usize = 192; +pub(super) const SLOTS: usize = 512; /// Entries copied from before the table (type information). const PRE: usize = 4; @@ -64,9 +64,24 @@ fn readable(at: usize, most: usize) -> usize { // SAFETY: a plain query. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; // SAFETY: as above. - let n = unsafe { VirtualQuery(end as *const c_void, &mut info, size_of::()) }; - const READ: u32 = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; - if n == 0 || info.State != MEM_COMMIT || info.Protect & READ == 0 || info.Protect & PAGE_GUARD != 0 { + let n = unsafe { + VirtualQuery( + end as *const c_void, + &mut info, + size_of::(), + ) + }; + const READ: u32 = PAGE_READONLY + | PAGE_READWRITE + | PAGE_WRITECOPY + | PAGE_EXECUTE_READ + | PAGE_EXECUTE_READWRITE + | PAGE_EXECUTE_WRITECOPY; + if n == 0 + || info.State != MEM_COMMIT + || info.Protect & READ == 0 + || info.Protect & PAGE_GUARD != 0 + { break; } end = info.BaseAddress as usize + info.RegionSize; @@ -81,21 +96,32 @@ fn readable(at: usize, most: usize) -> usize { /// # Safety /// `this` is a live COM object no other thread uses yet; what `patch` puts /// into the table are functions of the methods' types. -pub(super) unsafe fn install(this: *mut c_void, state: *const c_void, patch: impl FnOnce(&mut [usize; SLOTS])) -> bool { +pub(super) unsafe fn install( + this: *mut c_void, + state: *const c_void, + patch: impl FnOnce(&mut [usize; SLOTS]), +) -> bool { let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); // SAFETY: a live COM object starts with its table's address. let at = unsafe { *this.cast::() }; if made.contains(&at) { return false; } - let mut new = Box::new(Shim { state, orig: at as *const usize, pre: [0; PRE], table: [0; SLOTS] }); + let mut new = Box::new(Shim { + state, + orig: at as *const usize, + pre: [0; PRE], + table: [0; SLOTS], + }); let have = readable(at, SLOTS * 8) / 8; // SAFETY: `have` entries are readable; the object's table is at least // as long as its interface, and what lies behind it is only copied. unsafe { std::ptr::copy_nonoverlapping(at as *const usize, new.table.as_mut_ptr(), have) }; if readable(at - PRE * 8, PRE * 8) == PRE * 8 { // SAFETY: as above. - unsafe { std::ptr::copy_nonoverlapping((at as *const usize).sub(PRE), new.pre.as_mut_ptr(), PRE) }; + unsafe { + std::ptr::copy_nonoverlapping((at as *const usize).sub(PRE), new.pre.as_mut_ptr(), PRE) + }; } patch(&mut new.table); let new: &'static Shim = Box::leak(new); @@ -130,14 +156,20 @@ pub(super) unsafe fn ours(this: *mut c_void) -> bool { /// /// # Safety /// As [`install`]; `before` is a shim's table. -pub(super) unsafe fn again(this: *mut c_void, before: usize, patch: impl FnOnce(&mut [usize; SLOTS])) { +pub(super) unsafe fn again( + this: *mut c_void, + before: usize, + patch: impl FnOnce(&mut [usize; SLOTS]), +) { // SAFETY: the caller's. unsafe { let now = table(this); if now == before { return; } - let shim = (before as *const u8).sub(std::mem::offset_of!(Shim, table)).cast::(); + let shim = (before as *const u8) + .sub(std::mem::offset_of!(Shim, table)) + .cast::(); if (*shim).orig as usize == now { this.cast::().write(before); } else { @@ -223,14 +255,28 @@ mod tests { value: u64, } - unsafe extern "system" fn add(this: *mut c_void, a: u64, b: u64, c: u64, d: u64, e: f64) -> u64 { + unsafe extern "system" fn add( + this: *mut c_void, + a: u64, + b: u64, + c: u64, + d: u64, + e: f64, + ) -> u64 { // SAFETY: one of the test's objects. unsafe { (*this.cast::()).value + a + b + c + d + e as u64 } } type Add = unsafe extern "system" fn(*mut c_void, u64, u64, u64, u64, f64) -> u64; - unsafe extern "system" fn double(this: *mut c_void, a: u64, b: u64, c: u64, d: u64, e: f64) -> u64 { + unsafe extern "system" fn double( + this: *mut c_void, + a: u64, + b: u64, + c: u64, + d: u64, + e: f64, + ) -> u64 { // SAFETY: an object with a shim whose first method is `add`. unsafe { let first = orig::<[Add; 1]>(this)[0]; @@ -249,9 +295,17 @@ mod tests { #[test] fn one_object_is_changed_and_changed_back() { static STATE: u64 = 1000; - let vtbl = Vtbl { methods: [add as *const () as usize; 8] }; - let mut a = Object { vtbl: &vtbl, value: 100 }; - let mut b = Object { vtbl: &vtbl, value: 200 }; + let vtbl = Vtbl { + methods: [add as *const () as usize; 8], + }; + let mut a = Object { + vtbl: &vtbl, + value: 100, + }; + let mut b = Object { + vtbl: &vtbl, + value: 200, + }; // SAFETY: the test's objects; entries of `Add`'s type. unsafe { let this: *mut c_void = (&raw mut a).cast(); @@ -260,7 +314,10 @@ mod tests { t[2] = noted_entry::<{ QUEUE * SLOTS + 2 }>(); }; assert!(install(this, (&raw const STATE).cast(), patch)); - assert!(!install(this, (&raw const STATE).cast(), patch), "only once"); + assert!( + !install(this, (&raw const STATE).cast(), patch), + "only once" + ); assert_eq!(call(&mut a, 0), 230 + 1000); assert_eq!(call(&mut a, 1), 115); assert_eq!(call(&mut b, 0), 215, "other objects are untouched"); @@ -277,7 +334,9 @@ mod tests { again(this, shim, patch); assert_eq!(table(this), shim); // Or to another table. - let other = Vtbl { methods: [add as *const () as usize; 8] }; + let other = Vtbl { + methods: [add as *const () as usize; 8], + }; a.vtbl = &other; again(this, shim, patch); assert!(ours(this) && table(this) != shim); diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index c7c7131..8543f6a 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -21,8 +21,13 @@ use windows::core::Interface; use super::edit::{self, Clamp, RESULTS}; use super::gpu::{self, Seen, Worker}; use super::snap::read_sub; -use super::states::{self, COMMON, COPY_DEST, COPY_SOURCE, DEPTH_WRITE, RENDER_TARGET, RESOLVE_DEST, States, UNORDERED_ACCESS}; -use super::wire::{self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot}; +use super::states::{ + self, COMMON, COPY_DEST, COPY_SOURCE, DEPTH_WRITE, RENDER_TARGET, RESOLVE_DEST, States, + UNORDERED_ACCESS, +}; +use super::wire::{ + self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot, +}; /// The name of the argument clamp's pipeline, by which its passes are /// recognised. @@ -151,14 +156,32 @@ impl Report { /// The report as text. pub fn text(&self, what: &str) -> String { let mut t = String::new(); - let ms = |v: &[f64]| v.iter().map(|x| format!("{x:.2}")).collect::>().join(" "); - let _ = writeln!(t, "{what}: {:.2} ms on the card (median of {})", self.median_ms(), self.frame_ms.len()); + let ms = |v: &[f64]| { + v.iter() + .map(|x| format!("{x:.2}")) + .collect::>() + .join(" ") + }; + let _ = writeln!( + t, + "{what}: {:.2} ms on the card (median of {})", + self.median_ms(), + self.frame_ms.len() + ); let _ = writeln!(t, " loops, ms: {}", ms(&self.frame_ms)); let (busy, delta) = (median(&self.busy_ms), median(&self.delta_ms)); let idle = (self.median_ms() - busy - delta).max(0.0); - let _ = writeln!(t, " submissions busy {busy:.2} ms, copies standing for CPU writes {delta:.2} ms, between submissions {idle:.2} ms"); + let _ = writeln!( + t, + " submissions busy {busy:.2} ms, copies standing for CPU writes {delta:.2} ms, between submissions {idle:.2} ms" + ); let _ = writeln!(t, " by submission (lists: ms): {}", { - self.submits.iter().enumerate().map(|(i, (n, ms))| format!("{i} ({n}): {ms:.2}")).collect::>().join(", ") + self.submits + .iter() + .enumerate() + .map(|(i, (n, ms))| format!("{i} ({n}): {ms:.2}")) + .collect::>() + .join(", ") }); if !self.categories.is_empty() { let _ = writeln!(t, " by kind of command, ms (commands):"); @@ -173,8 +196,13 @@ impl Report { } } match self.picture { - Some((_, true)) => drop(writeln!(t, " picture: the same bytes as presented")), - Some((db, false)) => drop(writeln!(t, " picture: differs from the presented one, PSNR {db:.1} dB")), + Some((_, true)) => _ = writeln!(t, " picture: the same bytes as presented"), + Some((db, false)) => { + _ = writeln!( + t, + " picture: differs from the presented one, PSNR {db:.1} dB" + ) + } None => {} } for n in &self.notes { @@ -197,14 +225,20 @@ pub fn find(folder: &Path) -> Result { return Ok(folder.to_owned()); } let mut best: Option<(u32, PathBuf)> = None; - for entry in std::fs::read_dir(folder).with_context(|| format!("{}", folder.display()))?.flatten() { + for entry in std::fs::read_dir(folder) + .with_context(|| format!("{}", folder.display()))? + .flatten() + { let name = entry.file_name().to_string_lossy().into_owned(); - let Some(n) = name.strip_prefix("capture-").and_then(|n| n.parse().ok()) else { continue }; + let Some(n) = name.strip_prefix("capture-").and_then(|n| n.parse().ok()) else { + continue; + }; if entry.path().join("frame.bin").exists() && best.as_ref().is_none_or(|b| b.0 < n) { best = Some((n, entry.path())); } } - best.map(|b| b.1).ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display())) + best.map(|b| b.1) + .ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display())) } /// Loads a capture and runs it: the whole of `victory replay`. The reports, @@ -214,9 +248,19 @@ pub fn replay(folder: &Path, options: &Options) -> Result> let mut out = Vec::new(); if options.compare && options.edited() { let image = Some(player.folder.join("replay-unchanged.png")); - out.push(("unchanged".into(), player.run(&Options { image, ..options.plain() })?)); + out.push(( + "unchanged".into(), + player.run(&Options { + image, + ..options.plain() + })?, + )); } - let what = if options.edited() { "with the experiments" } else { "unchanged" }; + let what = if options.edited() { + "with the experiments" + } else { + "unchanged" + }; out.push((what.into(), player.run(options)?)); Ok(out) } @@ -292,14 +336,19 @@ impl Player { let (device, info) = make_device(&frame, options.debug)?; // SAFETY: plain creation and queries. let (queue, frequency) = unsafe { - let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { - Type: D3D12_COMMAND_LIST_TYPE_DIRECT, - ..Default::default() - })?; + let queue: ID3D12CommandQueue = + device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + })?; let frequency = queue.GetTimestampFrequency()? as f64; (queue, frequency) }; - let commands: Vec> = frame.lists.iter().map(|l| Cmd::all(&l.commands.0)).collect::>()?; + let commands: Vec> = frame + .lists + .iter() + .map(|l| Cmd::all(&l.commands.0)) + .collect::>()?; let mut player = Player { folder, worker: Worker::new(&device, &queue)?, @@ -324,7 +373,11 @@ impl Player { results: None, commands, fresh: true, - notes: frame.notes.iter().map(|n| format!("recorder: {n}")).collect(), + notes: frame + .notes + .iter() + .map(|n| format!("recorder: {n}")) + .collect(), frame, }; player.check()?; @@ -344,8 +397,15 @@ impl Player { step("contents", &mut at); player.make_masters()?; step("copies to restore from", &mut at); - let steps: Vec = steps.iter().map(|(w, d)| format!("{w} {:.1} s", d.as_secs_f64())).collect(); - player.notes.push(format!("loaded in {:.1} s: {}", began.elapsed().as_secs_f64(), steps.join(", "))); + let steps: Vec = steps + .iter() + .map(|(w, d)| format!("{w} {:.1} s", d.as_secs_f64())) + .collect(); + player.notes.push(format!( + "loaded in {:.1} s: {}", + began.elapsed().as_secs_f64(), + steps.join(", ") + )); Ok(player) } @@ -356,16 +416,39 @@ impl Player { /// Says what of the frame is not there. fn check(&mut self) -> Result<()> { - let missing = self.frame.submits.iter().flat_map(|s| &s.lists).filter(|&&l| l == MISSING).count(); + let missing = self + .frame + .submits + .iter() + .flat_map(|s| &s.lists) + .filter(|&&l| l == MISSING) + .count(); if missing > 0 { - self.note(format!("{missing} lists of the frame were not recorded: the frame is incomplete")); + self.note(format!( + "{missing} lists of the frame were not recorded: the frame is incomplete" + )); } if self.frame.submits.is_empty() { bail!("the capture has no submission"); } - let unknown = self.commands.iter().flatten().filter(|c| matches!(c, Cmd::RootView { va: Va::Unknown { .. }, .. })).count(); + let unknown = self + .commands + .iter() + .flatten() + .filter(|c| { + matches!( + c, + Cmd::RootView { + va: Va::Unknown { .. }, + .. + } + ) + }) + .count(); if unknown > 0 { - self.note(format!("{unknown} root views name memory in no known buffer: they are null in the replay")); + self.note(format!( + "{unknown} root views name memory in no known buffer: they are null in the replay" + )); } Ok(()) } @@ -394,7 +477,10 @@ impl Player { MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; - let card = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let card = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; match (gpu::seen(p), buffers) { (Seen::ReadBack, _) => gpu::to_props(p), (_, Buffers::Card) if buffer => card, @@ -415,7 +501,12 @@ impl Player { textures.insert(heap); } } - self.frame.heaps.iter().map(|h| h.id).filter(|id| !textures.contains(id)).collect() + self.frame + .heaps + .iter() + .map(|h| h.id) + .filter(|id| !textures.contains(id)) + .collect() }; for h in &self.frame.heaps { let desc = D3D12_HEAP_DESC { @@ -426,7 +517,8 @@ impl Player { }; let mut heap: Option = None; // SAFETY: plain creation. - unsafe { self.device.CreateHeap(&desc, &mut heap) }.with_context(|| format!("heap {}", h.id))?; + unsafe { self.device.CreateHeap(&desc, &mut heap) } + .with_context(|| format!("heap {}", h.id))?; self._heaps.extend(heap.map(|heap| (h.id, heap))); } let mut failed = 0; @@ -443,25 +535,65 @@ impl Player { let result = unsafe { match &r.place { Place::Placed { heap, offset } => match self._heaps.get(heap) { - Some(h) => self.device.CreatePlacedResource(h, *offset, &desc, D3D12_RESOURCE_STATE_COMMON, clear, &mut made), + Some(h) => self.device.CreatePlacedResource( + h, + *offset, + &desc, + D3D12_RESOURCE_STATE_COMMON, + clear, + &mut made, + ), None => Err(windows::core::Error::empty()), }, Place::Committed { props: p, flags } => { let p = props(p, is_buffer); - let state = if p.Type == D3D12_HEAP_TYPE_READBACK { D3D12_RESOURCE_STATE_COPY_DEST } else { D3D12_RESOURCE_STATE_COMMON }; - self.device.CreateCommittedResource(&p, D3D12_HEAP_FLAGS(flags & !DROP), &desc, state, clear, &mut made) + let state = if p.Type == D3D12_HEAP_TYPE_READBACK { + D3D12_RESOURCE_STATE_COPY_DEST + } else { + D3D12_RESOURCE_STATE_COMMON + }; + self.device.CreateCommittedResource( + &p, + D3D12_HEAP_FLAGS(flags & !DROP), + &desc, + state, + clear, + &mut made, + ) } Place::BackBuffer {} => { - let p = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; - self.device.CreateCommittedResource(&p, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut made) + let p = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + self.device.CreateCommittedResource( + &p, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut made, + ) } } }; match (result, made) { (Ok(()), Some(res)) => { // SAFETY: a live resource. - let va = if is_buffer { unsafe { res.GetGPUVirtualAddress() } } else { 0 }; - self.objects.insert(r.id, Object { res, va, index, subs: gpu::subresources(&r.desc) }); + let va = if is_buffer { + unsafe { res.GetGPUVirtualAddress() } + } else { + 0 + }; + self.objects.insert( + r.id, + Object { + res, + va, + index, + subs: gpu::subresources(&r.desc), + }, + ); } (e, _) => { if failed == 0 { @@ -483,7 +615,8 @@ impl Player { fn make_pipelines(&mut self) -> Result<()> { for (id, blob) in &self.frame.roots { // SAFETY: a blob the host took. - let root = unsafe { self.device.CreateRootSignature(0, &blob.0) }.with_context(|| format!("root signature {id}"))?; + let root = unsafe { self.device.CreateRootSignature(0, &blob.0) } + .with_context(|| format!("root signature {id}"))?; self.roots.insert(*id, root); } for s in &self.frame.signatures { @@ -495,11 +628,18 @@ impl Player { }; let mut made: Option = None; // SAFETY: a description the host took. - unsafe { self.device.CreateCommandSignature(&desc, self.roots.get(&s.root), &mut made)? }; + unsafe { + self.device + .CreateCommandSignature(&desc, self.roots.get(&s.root), &mut made)? + }; self.signatures.extend(made.map(|m| (s.id, m))); } for q in &self.frame.query_heaps { - let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE(q.kind), Count: q.count, NodeMask: 0 }; + let desc = D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE(q.kind), + Count: q.count, + NodeMask: 0, + }; let mut made: Option = None; // SAFETY: plain creation. unsafe { self.device.CreateQueryHeap(&desc, &mut made)? }; @@ -510,7 +650,9 @@ impl Player { let next = AtomicUsize::new(0); type Made = std::result::Result; let made: std::sync::Mutex> = std::sync::Mutex::default(); - let threads = std::thread::available_parallelism().map_or(4, |n| n.get() / 2).max(1); + let threads = std::thread::available_parallelism() + .map_or(4, |n| n.get() / 2) + .max(1); let (frame, roots) = (&self.frame, &self.roots); std::thread::scope(|scope| { for _ in 0..threads { @@ -522,8 +664,11 @@ impl Player { read_at(&file, &mut bytes, c.at).ok()?; Some(bytes) }; - let m = super::pso::make(&device, &p.parts, |id| roots.get(&id).cloned(), code); - made.lock().unwrap_or_else(|e| e.into_inner()).push((p.id, m)); + let m = + super::pso::make(&device, &p.parts, |id| roots.get(&id).cloned(), code); + made.lock() + .unwrap_or_else(|e| e.into_inner()) + .push((p.id, m)); } }); } @@ -536,7 +681,11 @@ impl Player { } } if let Some((id, e)) = refused.first() { - let n = format!("{} pipelines could not be made again, first {}: {e}", refused.len(), self.pipeline_name(*id)); + let n = format!( + "{} pipelines could not be made again, first {}: {e}", + refused.len(), + self.pipeline_name(*id) + ); self.note(n); } Ok(()) @@ -549,7 +698,15 @@ impl Player { return format!("pipeline {id}"); }; let code: Vec = self.hashes(p); - format!("{} (DXIL {})", if p.name.is_empty() { "unnamed" } else { &p.name }, code.join(" ")) + format!( + "{} (DXIL {})", + if p.name.is_empty() { + "unnamed" + } else { + &p.name + }, + code.join(" ") + ) } fn hashes(&self, p: &wire::Pipeline) -> Vec { @@ -580,23 +737,45 @@ impl Player { (slot::CBV, described) => { let mut d: D3D12_CONSTANT_BUFFER_VIEW_DESC = Default::default(); if described && let Some(o) = self.objects.get(&s.res) { - d = s.desc.as_ptr().cast::().read_unaligned(); + d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); d.BufferLocation = o.va + s.address(); } self.device.CreateConstantBufferView(Some(&d), at); } (slot::SRV, true) => { - let d = s.desc.as_ptr().cast::().read_unaligned(); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); self.device.CreateShaderResourceView(res, Some(&d), at); } - (slot::SRV, false) if res.is_some() => self.device.CreateShaderResourceView(res, None, at), + (slot::SRV, false) if res.is_some() => { + self.device.CreateShaderResourceView(res, None, at) + } (slot::UAV, true) => { - let d = s.desc.as_ptr().cast::().read_unaligned(); - self.device.CreateUnorderedAccessView(res, counter, Some(&d), at); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); + self.device + .CreateUnorderedAccessView(res, counter, Some(&d), at); + } + (slot::UAV, false) if res.is_some() => { + self.device + .CreateUnorderedAccessView(res, None::<&ID3D12Resource>, None, at) } - (slot::UAV, false) if res.is_some() => self.device.CreateUnorderedAccessView(res, None::<&ID3D12Resource>, None, at), (slot::SAMPLER, true) => { - let d = s.desc.as_ptr().cast::().read_unaligned(); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); self.device.CreateSampler(&d, at); } _ if sampler => { @@ -615,7 +794,12 @@ impl Player { ViewDimension: D3D12_UAV_DIMENSION_BUFFER, ..Default::default() }; - self.device.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&d), at); + self.device.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&d), + at, + ); } _ => { let d = D3D12_SHADER_RESOURCE_VIEW_DESC { @@ -624,7 +808,8 @@ impl Player { Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default() }; - self.device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&d), at); + self.device + .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&d), at); } } } @@ -635,7 +820,12 @@ impl Player { // version of the heaps of its own: lists are sent without waiting, // so a heap cannot be written between them. let mut now: HashMap<(u32, u32), Slot> = HashMap::new(); - let replaced: HashSet<(u32, u32)> = self.frame.submits.iter().flat_map(|s| s.views.iter().map(|v| (v.0, v.1))).collect(); + let replaced: HashSet<(u32, u32)> = self + .frame + .submits + .iter() + .flat_map(|s| s.views.iter().map(|v| (v.0, v.1))) + .collect(); for h in &self.frame.descriptor_heaps { for (id, i) in replaced.iter().filter(|k| k.0 == h.id) { let k = h.runs.partition_point(|run| run.0 <= *i); @@ -650,9 +840,17 @@ impl Player { let mut versions: Vec> = vec![Vec::new()]; let mut touched: HashSet<(u32, u32)> = HashSet::new(); for s in &self.frame.submits { - let live = |old: Option<&Slot>| old.is_some_and(|o| o.kind == slot::SAMPLER || o.res != NONE); - let news: Vec<&(u32, u32, Slot)> = s.views.iter().filter(|(h, i, v)| now.get(&(*h, *i)) != Some(v)).collect(); - if news.iter().any(|(h, i, _)| live(now.get(&(*h, *i))) || touched.contains(&(*h, *i))) { + let live = + |old: Option<&Slot>| old.is_some_and(|o| o.kind == slot::SAMPLER || o.res != NONE); + let news: Vec<&(u32, u32, Slot)> = s + .views + .iter() + .filter(|(h, i, v)| now.get(&(*h, *i)) != Some(v)) + .collect(); + if news + .iter() + .any(|(h, i, _)| live(now.get(&(*h, *i))) || touched.contains(&(*h, *i))) + { versions.push(Vec::new()); touched.clear(); } @@ -671,7 +869,12 @@ impl Player { let sampler = h.kind == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0; let kind = D3D12_DESCRIPTOR_HEAP_TYPE(h.kind); let make = |flags| -> windows::core::Result { - let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: h.count, Flags: flags, NodeMask: 0 }; + let d = D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: h.count, + Flags: flags, + NodeMask: 0, + }; // SAFETY: plain creation. unsafe { self.device.CreateDescriptorHeap(&d) } }; @@ -680,24 +883,29 @@ impl Player { unsafe { let step = self.device.GetDescriptorHandleIncrementSize(kind) as usize; let start = cpu.GetCPUDescriptorHandleForHeapStart(); - let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + i as usize * step }; + let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + i as usize * step, + }; self.view(&Slot::EMPTY, start, sampler); let mut filled = 1; while filled < h.count { let n = filled.min(h.count - filled).min(1 << 16); // Sources and destinations do not overlap. - self.device.CopyDescriptorsSimple(n, at(filled), start, kind); + self.device + .CopyDescriptorsSimple(n, at(filled), start, kind); filled += n; } for (first, n, s) in &h.runs { self.view(s, at(*first), sampler); for i in 1..*n { - self.device.CopyDescriptorsSimple(1, at(first + i), at(*first), kind); + self.device + .CopyDescriptorsSimple(1, at(first + i), at(*first), kind); } } let mut all = Vec::new(); for changes in &versions { - let mine: Vec<&(u32, u32, Slot)> = changes.iter().filter(|(id, _, _)| *id == h.id).collect(); + let mine: Vec<&(u32, u32, Slot)> = + changes.iter().filter(|(id, _, _)| *id == h.id).collect(); for (_, i, s) in &mine { if *i < h.count { self.view(s, at(*i), sampler); @@ -706,7 +914,10 @@ impl Player { if mine.is_empty() && let Some(Version { heap, gpu }) = all.last() { - let same = Version { heap: ID3D12DescriptorHeap::clone(heap), gpu: *gpu }; + let same = Version { + heap: ID3D12DescriptorHeap::clone(heap), + gpu: *gpu, + }; all.push(same); continue; } @@ -716,15 +927,30 @@ impl Player { // last one, and lists before see them too. Err(_) if !all.is_empty() => { full += 1; - let Some(Version { heap, gpu }) = all.last() else { break }; - let same = Version { heap: ID3D12DescriptorHeap::clone(heap), gpu: *gpu }; - self.device.CopyDescriptorsSimple(h.count, same.heap.GetCPUDescriptorHandleForHeapStart(), start, kind); + let Some(Version { heap, gpu }) = all.last() else { + break; + }; + let same = Version { + heap: ID3D12DescriptorHeap::clone(heap), + gpu: *gpu, + }; + self.device.CopyDescriptorsSimple( + h.count, + same.heap.GetCPUDescriptorHandleForHeapStart(), + start, + kind, + ); all.push(same); continue; } Err(e) => return Err(e.into()), }; - self.device.CopyDescriptorsSimple(h.count, heap.GetCPUDescriptorHandleForHeapStart(), start, kind); + self.device.CopyDescriptorsSimple( + h.count, + heap.GetCPUDescriptorHandleForHeapStart(), + start, + kind, + ); let gpu = heap.GetGPUDescriptorHandleForHeapStart().ptr; all.push(Version { heap, gpu }); } @@ -733,10 +959,15 @@ impl Player { } self.descriptors = made; if versions.len() > 1 { - self.notes.push(format!("{} versions of the descriptor heaps (views replaced during the frame)", versions.len())); + self.notes.push(format!( + "{} versions of the descriptor heaps (views replaced during the frame)", + versions.len() + )); } if full > 0 { - self.note(format!("{full} versions of descriptor heaps had no room: earlier lists see later views")); + self.note(format!( + "{full} versions of descriptor heaps had no room: earlier lists see later views" + )); } // Render target and depth views. let mut views: [HashSet; 2] = Default::default(); @@ -746,8 +977,8 @@ impl Player { views[0].extend(colors); views[1].extend(depth); } - Cmd::ClearTarget { view, .. } => drop(views[0].insert(*view)), - Cmd::ClearDepth { view, .. } => drop(views[1].insert(*view)), + Cmd::ClearTarget { view, .. } => _ = views[0].insert(*view), + Cmd::ClearDepth { view, .. } => _ = views[1].insert(*view), _ => {} } } @@ -755,8 +986,15 @@ impl Player { if all.is_empty() { continue; } - let kind = [D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_TYPE_DSV][i]; - let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: all.len() as u32, ..Default::default() }; + let kind = [ + D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + ][i]; + let d = D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: all.len() as u32, + ..Default::default() + }; // SAFETY: plain creation; slots of the heap just made. unsafe { let heap: ID3D12DescriptorHeap = self.device.CreateDescriptorHeap(&d)?; @@ -765,23 +1003,43 @@ impl Player { for s in all { let res = self.objects.get(&s.res).map(|o| &o.res); if i == 0 { - let d = s.desc.as_ptr().cast::().read_unaligned(); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); // Without either there is nothing to make a view of. let null = D3D12_RENDER_TARGET_VIEW_DESC { Format: DXGI_FORMAT(28), ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D, ..Default::default() }; - let d = if s.described != 0 { Some(&d as *const _) } else if res.is_none() { Some(&null as *const _) } else { None }; + let d = if s.described != 0 { + Some(&d as *const _) + } else if res.is_none() { + Some(&null as *const _) + } else { + None + }; self.device.CreateRenderTargetView(res, d, at); } else { - let d = s.desc.as_ptr().cast::().read_unaligned(); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); let null = D3D12_DEPTH_STENCIL_VIEW_DESC { Format: DXGI_FORMAT(40), ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, ..Default::default() }; - let d = if s.described != 0 { Some(&d as *const _) } else if res.is_none() { Some(&null as *const _) } else { None }; + let d = if s.described != 0 { + Some(&d as *const _) + } else if res.is_none() { + Some(&null as *const _) + } else { + None + }; self.device.CreateDepthStencilView(res, d, at); } self.targets.insert(*s, at); @@ -821,7 +1079,12 @@ impl Player { } let mut stagings: Vec<(ID3D12Resource, usize, u64)> = Vec::new(); for _ in 0..batches.len().min(2) { - let (b, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_UPLOAD, most, D3D12_RESOURCE_FLAG_NONE)?; + let (b, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_UPLOAD, + most, + D3D12_RESOURCE_FLAG_NONE, + )?; stagings.push((b, data as usize, 0)); } for (n, batch) in batches.iter().enumerate() { @@ -836,11 +1099,19 @@ impl Player { while let Some(&(i, at)) = batch.get(next.fetch_add(1, Ordering::Relaxed)) { let (_, len, from) = &parts[i]; // SAFETY: this part's own bytes of the mapping. - let to = unsafe { std::slice::from_raw_parts_mut((map + at as usize) as *mut u8, *len as usize) }; + let to = unsafe { + std::slice::from_raw_parts_mut( + (map + at as usize) as *mut u8, + *len as usize, + ) + }; if *from == ZERO { to.fill(0); } else if let Err(e) = read_at(file, to, *from) { - failed.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert(e); + failed + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get_or_insert(e); } } }); @@ -849,7 +1120,10 @@ impl Player { if let Some(e) = failed.into_inner().unwrap_or_else(|e| e.into_inner()) { return Err(e).context("the capture's contents"); } - let list: Vec<(&T, u64, u64)> = batch.iter().map(|&(i, at)| (&parts[i].0, parts[i].1, at)).collect(); + let list: Vec<(&T, u64, u64)> = batch + .iter() + .map(|&(i, at)| (&parts[i].0, parts[i].1, at)) + .collect(); let buffer = stagings[k].0.clone(); // The worker is another part of the player than `copy` uses. let other = Worker::new(&self.device, &self.worker.queue)?; @@ -869,9 +1143,16 @@ impl Player { let mut early = Vec::new(); let mut into = Vec::new(); for r in &self.frame.resources { - let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { continue }; + let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { + continue; + }; let loaded = !r.idle && known.contains(&r.id); - gpu::moves(&o.res, &[COMMON], if loaded { &[COPY_DEST] } else { state }, if loaded { &mut into } else { &mut early }); + gpu::moves( + &o.res, + &[COMMON], + if loaded { &[COPY_DEST] } else { state }, + if loaded { &mut into } else { &mut early }, + ); } let textures: Vec<(Content, u64, u64)> = self .frame @@ -896,7 +1177,9 @@ impl Player { let file = File::open(self.folder.join("contents.bin"))?; self.upload(&textures, &file, |player, list, parts, staging| { for (c, len, at) in parts { - let Some(o) = player.objects.get(&c.res) else { continue }; + let Some(o) = player.objects.get(&c.res) else { + continue; + }; let r = &player.frame.resources[o.index]; // SAFETY: an open list; live resources. unsafe { @@ -904,11 +1187,23 @@ impl Player { list.CopyBufferRegion(&o.res, c.first, staging, *at, *len); continue; } - let (all, _) = gpu::footprints(&player.device, &gpu::to_desc(&r.desc), c.first as u32, c.count); + let (all, _) = gpu::footprints( + &player.device, + &gpu::to_desc(&r.desc), + c.first as u32, + c.count, + ); for (i, mut f) in all.into_iter().enumerate() { f.Offset += at; let to = gpu::sub_location(&o.res, c.first as u32 + i as u32); - list.CopyTextureRegion(&to, 0, 0, 0, &gpu::placed_location(staging, f), None); + list.CopyTextureRegion( + &to, + 0, + 0, + 0, + &gpu::placed_location(staging, f), + None, + ); } } } @@ -916,7 +1211,9 @@ impl Player { // To the states of the frame's start. let mut back = Vec::new(); for r in &self.frame.resources { - let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { continue }; + let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { + continue; + }; if !r.idle && known.contains(&r.id) { gpu::moves(&o.res, &[COPY_DEST], state, &mut back); } @@ -928,13 +1225,21 @@ impl Player { } })?; if missing > 0 { - self.note(format!("contents of {missing} parts of resources that could not be made are left out")); + self.note(format!( + "contents of {missing} parts of resources that could not be made are left out" + )); } // What the CPU had put into the memory both see by the first // submission: part of the start of the frame. let file = File::open(self.folder.join("deltas.bin"))?; let named = self.named_buffers(); - let of = |s: &wire::Submit| s.deltas.iter().filter(|d| named.contains(&d.res)).cloned().collect::>(); + let of = |s: &wire::Submit| { + s.deltas + .iter() + .filter(|d| named.contains(&d.res)) + .cloned() + .collect::>() + }; // In memory the card cannot write, bytes looked at first when a // later submission read them can stand there from the start. let upload: HashSet = self @@ -946,17 +1251,25 @@ impl Player { .collect(); let mut first = of(&self.frame.submits[0]); let mut seen: HashSet<(u32, u64)> = HashSet::new(); - let pages = |d: &Delta| (d.at / 4096..(d.at + d.len).div_ceil(4096)).map(|p| (d.res, p)).collect::>(); + let pages = |d: &Delta| { + (d.at / 4096..(d.at + d.len).div_ceil(4096)) + .map(|p| (d.res, p)) + .collect::>() + }; first.iter().for_each(|d| seen.extend(pages(d))); let mut rest: Vec> = vec![Vec::new()]; for s in self.frame.submits.iter().skip(1) { - let (early, late): (Vec, Vec) = - of(s).into_iter().partition(|d| upload.contains(&d.res) && pages(d).iter().all(|p| !seen.contains(p))); + let (early, late): (Vec, Vec) = of(s).into_iter().partition(|d| { + upload.contains(&d.res) && pages(d).iter().all(|p| !seen.contains(p)) + }); early.iter().for_each(|d| seen.extend(pages(d))); first.extend(early); rest.push(late); } - let first: Vec<(Delta, u64, u64)> = first.into_iter().map(|d| (d.clone(), d.len, d.file)).collect(); + let first: Vec<(Delta, u64, u64)> = first + .into_iter() + .map(|d| (d.clone(), d.len, d.file)) + .collect(); self.upload(&first, &file, |player, list, parts, staging| { for (d, len, at) in parts { if let Some(o) = player.objects.get(&d.res) { @@ -977,7 +1290,12 @@ impl Player { } } if total > 0 { - let (buffer, _) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, total, D3D12_RESOURCE_FLAG_NONE)?; + let (buffer, _) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_DEFAULT, + total, + D3D12_RESOURCE_FLAG_NONE, + )?; self.deltas = Some(buffer.clone()); self.upload(&later, &file, |_, list, parts, staging| { for ((to, _), len, at) in parts { @@ -1001,22 +1319,28 @@ impl Player { for c in self.commands.iter().flatten() { match c { Cmd::RootView { va: v, .. } => va(v), - Cmd::IndexBuffer { view: Some((v, _, _)) } => va(v), - Cmd::VertexBuffers { views: Some(all), .. } => all.iter().for_each(|(v, _, _)| va(v)), + Cmd::IndexBuffer { + view: Some((v, _, _)), + } => va(v), + Cmd::VertexBuffers { + views: Some(all), .. + } => all.iter().for_each(|(v, _, _)| va(v)), Cmd::WriteImmediate { all } => all.iter().for_each(|(v, _, _)| va(v)), _ => {} } } for c in self.commands.iter().flatten() { match c { - Cmd::CopyBuffer { dst, src, .. } | Cmd::CopyResource { dst, src } => named.extend([*dst, *src]), + Cmd::CopyBuffer { dst, src, .. } | Cmd::CopyResource { dst, src } => { + named.extend([*dst, *src]) + } Cmd::CopyTexture { dst, src, .. } => { for Loc::Sub { res, .. } | Loc::Placed { res, .. } in [dst, src] { named.insert(*res); } } Cmd::Indirect { args, count, .. } => named.extend([*args, *count]), - Cmd::ResolveQuery { dst, .. } => drop(named.insert(*dst)), + Cmd::ResolveQuery { dst, .. } => _ = named.insert(*dst), _ => {} } } @@ -1041,15 +1365,27 @@ impl Player { states.add(r.id, subs, r.state[0], decays); if r.state.len() > 1 { for (i, s) in r.state.iter().enumerate() { - states.change(&states::Change { res: r.id, sub: i as u32, after: *s, promoted: false, alias: false }); + states.change(&states::Change { + res: r.id, + sub: i as u32, + after: *s, + promoted: false, + alias: false, + }); } } } // Resources in a state they are written in at some time, or written // some other way. - const WRITE: u32 = RENDER_TARGET | UNORDERED_ACCESS | DEPTH_WRITE | COPY_DEST | RESOLVE_DEST; - let mut written: HashSet = - self.frame.resources.iter().filter(|r| r.state.iter().any(|s| s & WRITE != 0)).map(|r| r.id).collect(); + const WRITE: u32 = + RENDER_TARGET | UNORDERED_ACCESS | DEPTH_WRITE | COPY_DEST | RESOLVE_DEST; + let mut written: HashSet = self + .frame + .resources + .iter() + .filter(|r| r.state.iter().any(|s| s & WRITE != 0)) + .map(|r| r.id) + .collect(); for (i, s) in self.frame.submits.iter().enumerate() { for &l in s.lists.iter().filter(|&&l| l != MISSING) { for c in &self.commands[l as usize] { @@ -1061,19 +1397,38 @@ impl Player { match c { Cmd::Barriers { all } => { for b in all { - if let Barrier::Transition { res, before, after, .. } = b + if let Barrier::Transition { + res, before, after, .. + } = b && (*before | *after) as u32 & WRITE != 0 { written.insert(*res); } } } - Cmd::CopyBuffer { dst, .. } | Cmd::CopyResource { dst, .. } | Cmd::ResolveQuery { dst, .. } => drop(written.insert(*dst)), - Cmd::CopyTexture { dst: Loc::Sub { res, .. } | Loc::Placed { res, .. }, .. } => drop(written.insert(*res)), - Cmd::Resolve { dst, .. } | Cmd::ResolveRegion { dst, .. } => drop(written.insert(*dst)), - Cmd::RootView { kind: slot::UAV, va: Va::At { res, .. }, .. } => drop(written.insert(*res)), + Cmd::CopyBuffer { dst, .. } + | Cmd::CopyResource { dst, .. } + | Cmd::ResolveQuery { dst, .. } => _ = written.insert(*dst), + Cmd::CopyTexture { + dst: Loc::Sub { res, .. } | Loc::Placed { res, .. }, + .. + } => _ = written.insert(*res), + Cmd::Resolve { dst, .. } | Cmd::ResolveRegion { dst, .. } => { + _ = written.insert(*dst) + } + Cmd::RootView { + kind: slot::UAV, + va: Va::At { res, .. }, + .. + } => _ = written.insert(*res), Cmd::WriteImmediate { all } => { - written.extend(all.iter().filter_map(|(va, _, _)| if let Va::At { res, .. } = va { Some(*res) } else { None })); + written.extend(all.iter().filter_map(|(va, _, _)| { + if let Va::At { res, .. } = va { + Some(*res) + } else { + None + } + })); } _ => {} } @@ -1085,15 +1440,28 @@ impl Player { } } // Buffers any unordered-access view names. - let is_buffer = - |id: u32| self.objects.get(&id).is_some_and(|o| self.frame.resources[o.index].desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0); - let simultaneous = |id: u32| { + let is_buffer = |id: u32| { self.objects.get(&id).is_some_and(|o| { - self.frame.resources[o.index].desc.flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0 + self.frame.resources[o.index].desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 }) }; - let views = self.frame.descriptor_heaps.iter().flat_map(|h| h.runs.iter().map(|(_, _, s)| s)); - let late = self.frame.submits.iter().flat_map(|s| s.views.iter().map(|(_, _, s)| s)); + let simultaneous = |id: u32| { + self.objects.get(&id).is_some_and(|o| { + self.frame.resources[o.index].desc.flags + & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 + != 0 + }) + }; + let views = self + .frame + .descriptor_heaps + .iter() + .flat_map(|h| h.runs.iter().map(|(_, _, s)| s)); + let late = self + .frame + .submits + .iter() + .flat_map(|s| s.views.iter().map(|(_, _, s)| s)); for s in views.chain(late).filter(|s| s.kind == slot::UAV) { for id in [s.res, s.counter] { if is_buffer(id) || simultaneous(id) { @@ -1102,7 +1470,8 @@ impl Player { } } for id in self.start.keys() { - self.end.insert(*id, states.get(*id).unwrap_or(vec![COMMON])); + self.end + .insert(*id, states.get(*id).unwrap_or(vec![COMMON])); } let mut ids: Vec = written .into_iter() @@ -1140,12 +1509,22 @@ impl Player { ..Default::default() } } else { - D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() } + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + } }; let mut made: Option = None; // SAFETY: plain creation. let result = unsafe { - self.device.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut made) + self.device.CreateCommittedResource( + &props, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut made, + ) }; match (result, made) { (Ok(()), Some(m)) => { @@ -1153,10 +1532,17 @@ impl Player { in_pc += if pc { size } else { 0 }; self.masters.push((id, m)); } - (e, _) => self.note(format!("no copy of resource {id} to restore it from ({e:?})")), + (e, _) => self.note(format!( + "no copy of resource {id} to restore it from ({e:?})" + )), } } - tracing::info!(resources = self.masters.len(), mb = total >> 20, in_pc_memory_mb = in_pc >> 20, "copies of what the frame changes"); + tracing::info!( + resources = self.masters.len(), + mb = total >> 20, + in_pc_memory_mb = in_pc >> 20, + "copies of what the frame changes" + ); // Filled now: the resources are as at the frame's start. Masters // stay in the copy-source state (buffers decay). let (masters, objects, start) = (&self.masters, &self.objects, &self.start); @@ -1165,7 +1551,10 @@ impl Player { for (id, m) in some { let Some(state) = start.get(id) else { continue }; let o = &objects[id]; - let to: Vec = state.iter().map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect(); + let to: Vec = state + .iter() + .map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }) + .collect(); gpu::moves(&o.res, state, &to, &mut before); gpu::moves(&o.res, &to, state, &mut after); before.push(gpu::transition(m, ALL, COMMON, COPY_DEST)); @@ -1191,8 +1580,12 @@ impl Player { // SAFETY: plain queries. unsafe { let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; - let adapter: IDXGIAdapter3 = factory.EnumAdapterByLuid(self.device.GetAdapterLuid()).ok()?; - adapter.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own).ok()?; + let adapter: IDXGIAdapter3 = factory + .EnumAdapterByLuid(self.device.GetAdapterLuid()) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; } Some(own.Budget.saturating_sub(own.CurrentUsage)) } @@ -1202,10 +1595,17 @@ impl Player { if self.fresh { return Ok(()); } - let restored: HashMap = if contents { self.masters.iter().map(|(id, m)| (*id, m)).collect() } else { HashMap::new() }; - let (mut idle, mut into, mut back, mut plain) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let restored: HashMap = if contents { + self.masters.iter().map(|(id, m)| (*id, m)).collect() + } else { + HashMap::new() + }; + let (mut idle, mut into, mut back, mut plain) = + (Vec::new(), Vec::new(), Vec::new(), Vec::new()); for (id, start) in &self.start { - let Some(o) = self.objects.get(id) else { continue }; + let Some(o) = self.objects.get(id) else { + continue; + }; let end = self.end.get(id).unwrap_or(start); if restored.contains_key(id) { gpu::moves(&o.res, end, &[COPY_DEST], &mut into); @@ -1236,23 +1636,39 @@ impl Player { } fn pipelines_named(&self, name: &str) -> HashSet { - self.frame.pipelines.iter().filter(|p| p.name == name).map(|p| p.id).collect() + self.frame + .pipelines + .iter() + .filter(|p| p.name == name) + .map(|p| p.id) + .collect() } /// The frame's lists, edited: for each submission, its lists' commands. - fn edited(&mut self, o: &Options, report: &mut Report, clamps: &[Vec]) -> Vec>> { + fn edited( + &mut self, + o: &Options, + report: &mut Report, + clamps: &[Vec], + ) -> Vec>> { let skip: HashSet = self .frame .pipelines .iter() .filter(|p| { let hashes = self.hashes(p); - o.skip_shaders.iter().any(|s| !s.is_empty() && (p.name.contains(s.as_str()) || hashes.iter().any(|h| h.contains(s.as_str())))) + o.skip_shaders.iter().any(|s| { + !s.is_empty() + && (p.name.contains(s.as_str()) + || hashes.iter().any(|h| h.contains(s.as_str()))) + }) }) .map(|p| p.id) .collect(); if !o.skip_shaders.is_empty() { - report.notes.push(format!("{} pipelines match --skip-shader", skip.len())); + report + .notes + .push(format!("{} pipelines match --skip-shader", skip.len())); } let hash = self.pipelines_named(COMPARE); let (mut skipped, mut hashed, mut uavs, mut merged) = (0, 0, 0, 0); @@ -1268,7 +1684,9 @@ impl Player { lists.push(edit::barriers_only(cmds)); continue; } - if o.skip_clamps && let Some(c) = clamps.get(here as usize) { + if o.skip_clamps + && let Some(c) = clamps.get(here as usize) + { cmds = edit::skip_clamps(cmds, c); } let mut n; @@ -1293,16 +1711,24 @@ impl Player { out.push(lists); } if !skip.is_empty() { - report.notes.push(format!("--skip-shader left out {skipped} commands")); + report + .notes + .push(format!("--skip-shader left out {skipped} commands")); } if o.skip_hash_passes { - report.notes.push(format!("--skip-hash-passes left out {hashed} dispatches")); + report + .notes + .push(format!("--skip-hash-passes left out {hashed} dispatches")); } if o.no_barriers { - report.notes.push(format!("--no-barriers left out {uavs} unordered-access barriers")); + report.notes.push(format!( + "--no-barriers left out {uavs} unordered-access barriers" + )); } if o.merge_barriers { - report.notes.push(format!("--merge-barriers joined {merged} barrier calls to ones before them")); + report.notes.push(format!( + "--merge-barriers joined {merged} barrier calls to ones before them" + )); } out } @@ -1325,11 +1751,22 @@ impl Player { submits.push(lists); } let n: usize = clamps.iter().map(Vec::len).sum(); - report.notes.push(format!("--skip-clamps: {n} clamp passes, {} KB of arguments kept from a first run", next >> 10)); + report.notes.push(format!( + "--skip-clamps: {n} clamp passes, {} KB of arguments kept from a first run", + next >> 10 + )); if n == 0 { return Ok(clamps); } - self.results = Some(gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, next, D3D12_RESOURCE_FLAG_NONE)?.0); + self.results = Some( + gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_DEFAULT, + next, + D3D12_RESOURCE_FLAG_NONE, + )? + .0, + ); let built = self.build(&submits, &Options::default())?; self.restore(true)?; self.send(&built, false)?; @@ -1344,15 +1781,32 @@ impl Player { let count: usize = submits .iter() .flatten() - .map(|c| 2 + if o.detailed { c.iter().filter(|c| c.works() || matches!(c, Cmd::Barriers { .. })).count() } else { 0 }) + .map(|c| { + 2 + if o.detailed { + c.iter() + .filter(|c| c.works() || matches!(c, Cmd::Barriers { .. })) + .count() + } else { + 0 + } + }) .sum::() + 2 * submits.len(); let mut heap: Option = None; - let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: count.max(1) as u32, NodeMask: 0 }; + let desc = D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: count.max(1) as u32, + NodeMask: 0, + }; // SAFETY: plain creation. unsafe { self.device.CreateQueryHeap(&desc, &mut heap)? }; let heap = heap.context("no timestamps")?; - let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, count.max(1) as u64 * 8, D3D12_RESOURCE_FLAG_NONE)?; + let (back, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_READBACK, + count.max(1) as u64 * 8, + D3D12_RESOURCE_FLAG_NONE, + )?; let mut next = 0u32; let mut steps = Vec::new(); for (i, lists) in submits.iter().enumerate() { @@ -1365,7 +1819,9 @@ impl Player { let mut seen = HashSet::new(); let mut after = Vec::new(); for (d, at) in parts { - let Some(ob) = self.objects.get(&d.res) else { continue }; + let Some(ob) = self.objects.get(&d.res) else { + continue; + }; open.1.CopyBufferRegion(&ob.res, d.at, from, *at, d.len); if seen.insert(d.res) { // Back to the common state by itself, for @@ -1382,7 +1838,8 @@ impl Player { let mut built = Vec::new(); for cmds in lists { let open = self.open(&heap, &mut next)?; - let stamps = self.translate(&open.1, cmds, i, o.detailed.then_some((&heap, &mut next))); + let stamps = + self.translate(&open.1, cmds, i, o.detailed.then_some((&heap, &mut next))); built.push(self.close(open, &heap, &mut next, stamps)?); } steps.push((delta, built)); @@ -1405,12 +1862,27 @@ impl Player { let open = self.plain_list()?; // SAFETY: an open list; `next` queries were written. unsafe { - open.1.ResolveQueryData(&heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, next.max(1), &back, 0); + open.1.ResolveQueryData( + &heap, + D3D12_QUERY_TYPE_TIMESTAMP, + 0, + next.max(1), + &back, + 0, + ); open.1.Close()?; } open }; - Ok(Sends { steps, joints, resolve, _heap: heap, _back: back, data: data as usize, count: next }) + Ok(Sends { + steps, + joints, + resolve, + _heap: heap, + _back: back, + data: data as usize, + count: next, + }) } /// Records a wait for everything before, with all caches written out. @@ -1422,7 +1894,10 @@ impl Player { unsafe { let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default(); let size = size_of::() as u32; - let known = self.device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, (&raw mut o).cast(), size).is_ok(); + let known = self + .device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, (&raw mut o).cast(), size) + .is_ok(); if known && o.EnhancedBarriersSupported.as_bool() && let Ok(list) = list.cast::() @@ -1436,7 +1911,9 @@ impl Player { list.Barrier(&[D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_GLOBAL, NumBarriers: 1, - Anonymous: D3D12_BARRIER_GROUP_0 { pGlobalBarriers: all.as_ptr() }, + Anonymous: D3D12_BARRIER_GROUP_0 { + pGlobalBarriers: all.as_ptr(), + }, }]); } else { list.ResourceBarrier(&[alias(), uav_barrier(None)]); @@ -1447,13 +1924,24 @@ impl Player { fn plain_list(&self) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)> { // SAFETY: plain creation. unsafe { - let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let list = self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + let allocator: ID3D12CommandAllocator = self + .device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list = self.device.CreateCommandList( + 0, + D3D12_COMMAND_LIST_TYPE_DIRECT, + &allocator, + None, + )?; Ok((allocator, list)) } } - fn open(&self, heap: &ID3D12QueryHeap, next: &mut u32) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList, u32)> { + fn open( + &self, + heap: &ID3D12QueryHeap, + next: &mut u32, + ) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList, u32)> { let (allocator, list) = self.plain_list()?; // SAFETY: an open list; a query of the heap. unsafe { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, *next) }; @@ -1471,10 +1959,17 @@ impl Player { // SAFETY: as above. unsafe { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, *next); - list.Close().context("a list of the frame could not be recorded again")?; + list.Close() + .context("a list of the frame could not be recorded again")?; } *next += 1; - Ok(Built { _allocator: allocator, list, first, last: *next - 1, stamps }) + Ok(Built { + _allocator: allocator, + list, + first, + last: *next - 1, + stamps, + }) } /// Records commands into a list, in submission `submit`. @@ -1499,7 +1994,11 @@ impl Player { .frame .signatures .iter() - .filter(|s| s.args.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)) + .filter(|s| { + s.args + .iter() + .any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32) + }) .map(|s| s.id) .collect(); let mut stamps = Vec::new(); @@ -1518,13 +2017,21 @@ impl Player { let category = match c { Cmd::Barriers { .. } => "barriers", Cmd::Dispatch { .. } if clamps.contains(&bound) => "argument clamps (ours)", - Cmd::Dispatch { .. } if compares.contains(&bound) => "hash and compare passes (ours)", + Cmd::Dispatch { .. } if compares.contains(&bound) => { + "hash and compare passes (ours)" + } Cmd::Dispatch { .. } => "dispatches", - Cmd::Indirect { signature, .. } if dispatches.contains(signature) => "indirect dispatches", + Cmd::Indirect { signature, .. } if dispatches.contains(signature) => { + "indirect dispatches" + } Cmd::Indirect { .. } if mesh.contains(&bound) => "indirect mesh draws", Cmd::Indirect { .. } => "indirect draws", - Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::DispatchMesh { .. } => "draws", - Cmd::ClearDepth { .. } | Cmd::ClearTarget { .. } | Cmd::Discard { .. } => "clears", + Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::DispatchMesh { .. } => { + "draws" + } + Cmd::ClearDepth { .. } | Cmd::ClearTarget { .. } | Cmd::Discard { .. } => { + "clears" + } Cmd::Resolve { .. } | Cmd::ResolveRegion { .. } => "resolves", _ => "copies", }; @@ -1542,8 +2049,19 @@ impl Player { // SAFETY: the caller's. unsafe { match c { - Cmd::Draw { vertices, instances, first, first_instance } => l.DrawInstanced(*vertices, *instances, *first, *first_instance), - Cmd::DrawIndexed { indices, instances, first, base, first_instance } => { + Cmd::Draw { + vertices, + instances, + first, + first_instance, + } => l.DrawInstanced(*vertices, *instances, *first, *first_instance), + Cmd::DrawIndexed { + indices, + instances, + first, + base, + first_instance, + } => { l.DrawIndexedInstanced(*indices, *instances, *first, *base, *first_instance); } Cmd::Dispatch { groups } => l.Dispatch(groups[0], groups[1], groups[2]), @@ -1552,7 +2070,13 @@ impl Player { l.DispatchMesh(groups[0], groups[1], groups[2]); } } - Cmd::CopyBuffer { dst, dst_at, src, src_at, len } => { + Cmd::CopyBuffer { + dst, + dst_at, + src, + src_at, + len, + } => { if let (Some(dst), Some(src)) = (res(*dst), res(*src)) { l.CopyBufferRegion(dst, *dst_at, src, *src_at, *len); } @@ -1560,7 +2084,13 @@ impl Player { Cmd::CopyTexture { dst, at, src, part } => { let side = |loc: &Loc| match loc { Loc::Sub { res: id, sub } => Some(gpu::sub_location(res(*id)?, *sub)), - Loc::Placed { res: id, offset, format, size, pitch } => { + Loc::Placed { + res: id, + offset, + format, + size, + pitch, + } => { let f = D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT(*format), Width: size[0], @@ -1568,12 +2098,32 @@ impl Player { Depth: size[2], RowPitch: *pitch, }; - Some(gpu::placed_location(res(*id)?, D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: *offset, Footprint: f })) + Some(gpu::placed_location( + res(*id)?, + D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: *offset, + Footprint: f, + }, + )) } }; if let (Some(dst), Some(src)) = (side(dst), side(src)) { - let part = part.map(|p| D3D12_BOX { left: p[0], top: p[1], front: p[2], right: p[3], bottom: p[4], back: p[5] }); - l.CopyTextureRegion(&dst, at[0], at[1], at[2], &src, part.as_ref().map(|p| p as *const _)); + let part = part.map(|p| D3D12_BOX { + left: p[0], + top: p[1], + front: p[2], + right: p[3], + bottom: p[4], + back: p[5], + }); + l.CopyTextureRegion( + &dst, + at[0], + at[1], + at[2], + &src, + part.as_ref().map(|p| p as *const _), + ); } } Cmd::CopyResource { dst, src } => { @@ -1581,27 +2131,63 @@ impl Player { l.CopyResource(dst, src); } } - Cmd::Resolve { dst, dst_sub, src, src_sub, format } => { + Cmd::Resolve { + dst, + dst_sub, + src, + src_sub, + format, + } => { if let (Some(dst), Some(src)) = (res(*dst), res(*src)) { l.ResolveSubresource(dst, *dst_sub, src, *src_sub, DXGI_FORMAT(*format)); } } - Cmd::ResolveRegion { dst, dst_sub, at, src, src_sub, part, format, mode } => { - if let (Some(dst), Some(src), Ok(l)) = (res(*dst), res(*src), l.cast::()) { + Cmd::ResolveRegion { + dst, + dst_sub, + at, + src, + src_sub, + part, + format, + mode, + } => { + if let (Some(dst), Some(src), Ok(l)) = + (res(*dst), res(*src), l.cast::()) + { let part = part.map(to_rect); let part = part.as_ref().map(|r| r as *const _); - l.ResolveSubresourceRegion(dst, *dst_sub, at[0], at[1], src, *src_sub, part, DXGI_FORMAT(*format), D3D12_RESOLVE_MODE(*mode)); + l.ResolveSubresourceRegion( + dst, + *dst_sub, + at[0], + at[1], + src, + *src_sub, + part, + DXGI_FORMAT(*format), + D3D12_RESOLVE_MODE(*mode), + ); } } Cmd::Topology { kind } => l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(*kind)), Cmd::Viewports { all } => { let all: Vec = all .iter() - .map(|v| D3D12_VIEWPORT { TopLeftX: v[0], TopLeftY: v[1], Width: v[2], Height: v[3], MinDepth: v[4], MaxDepth: v[5] }) + .map(|v| D3D12_VIEWPORT { + TopLeftX: v[0], + TopLeftY: v[1], + Width: v[2], + Height: v[3], + MinDepth: v[4], + MaxDepth: v[5], + }) .collect(); l.RSSetViewports(&all); } - Cmd::Scissors { all } => l.RSSetScissorRects(&all.iter().map(|r| to_rect(*r)).collect::>()), + Cmd::Scissors { all } => { + l.RSSetScissorRects(&all.iter().map(|r| to_rect(*r)).collect::>()) + } Cmd::BlendFactor { factor } => l.OMSetBlendFactor(factor.as_ref()), Cmd::StencilRef { value } => l.OMSetStencilRef(*value), Cmd::DepthBounds { min, max } => { @@ -1615,27 +2201,52 @@ impl Player { } } Cmd::Barriers { all } => { - let all: Vec = all.iter().filter_map(|b| self.barrier(b)).collect(); + let all: Vec = + all.iter().filter_map(|b| self.barrier(b)).collect(); barriers(l, &all); } Cmd::Heaps { heaps } => { - let all: Vec> = - heaps.iter().filter_map(|id| Some(Some(self.descriptors.get(id)?.0.get(version)?.heap.clone()))).collect(); + let all: Vec> = heaps + .iter() + .filter_map(|id| { + Some(Some(self.descriptors.get(id)?.0.get(version)?.heap.clone())) + }) + .collect(); l.SetDescriptorHeaps(&all); } Cmd::RootSignature { graphics, root } => { let root = self.roots.get(root); - if *graphics { l.SetGraphicsRootSignature(root) } else { l.SetComputeRootSignature(root) } + if *graphics { + l.SetGraphicsRootSignature(root) + } else { + l.SetComputeRootSignature(root) + } } - Cmd::Table { graphics, param, heap, slot } => { + Cmd::Table { + graphics, + param, + heap, + slot, + } => { if let Some((versions, step)) = self.descriptors.get(heap) && let Some(v) = versions.get(version) { - let at = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: v.gpu + u64::from(*slot) * step }; - if *graphics { l.SetGraphicsRootDescriptorTable(*param, at) } else { l.SetComputeRootDescriptorTable(*param, at) } + let at = D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: v.gpu + u64::from(*slot) * step, + }; + if *graphics { + l.SetGraphicsRootDescriptorTable(*param, at) + } else { + l.SetComputeRootDescriptorTable(*param, at) + } } } - Cmd::Constants { graphics, param, offset, values } => { + Cmd::Constants { + graphics, + param, + offset, + values, + } => { let (n, data) = (values.len() as u32, values.as_ptr().cast()); if *graphics { l.SetGraphicsRoot32BitConstants(*param, n, data, *offset); @@ -1643,7 +2254,12 @@ impl Player { l.SetComputeRoot32BitConstants(*param, n, data, *offset); } } - Cmd::RootView { graphics, kind, param, va } => { + Cmd::RootView { + graphics, + kind, + param, + va, + } => { let va = self.va(va); match (*kind, *graphics) { (slot::CBV, true) => l.SetGraphicsRootConstantBufferView(*param, va), @@ -1655,14 +2271,20 @@ impl Player { } } Cmd::IndexBuffer { view } => { - let v = view.as_ref().map(|(va, size, format)| D3D12_INDEX_BUFFER_VIEW { - BufferLocation: self.va(va), - SizeInBytes: *size, - Format: DXGI_FORMAT(*format), - }); + let v = view + .as_ref() + .map(|(va, size, format)| D3D12_INDEX_BUFFER_VIEW { + BufferLocation: self.va(va), + SizeInBytes: *size, + Format: DXGI_FORMAT(*format), + }); l.IASetIndexBuffer(v.as_ref().map(|v| v as *const _)); } - Cmd::VertexBuffers { start, views, count } => match views { + Cmd::VertexBuffers { + start, + views, + count, + } => match views { Some(views) => { let all: Vec = views .iter() @@ -1674,10 +2296,14 @@ impl Player { .collect(); l.IASetVertexBuffers(*start, Some(&all)); } - None => l.IASetVertexBuffers(*start, Some(&vec![D3D12_VERTEX_BUFFER_VIEW::default(); *count as usize])), + None => l.IASetVertexBuffers( + *start, + Some(&vec![D3D12_VERTEX_BUFFER_VIEW::default(); *count as usize]), + ), }, Cmd::Targets { colors, depth } => { - let colors: Vec = colors.iter().map(view).collect(); + let colors: Vec = + colors.iter().map(view).collect(); let depth = depth.as_ref().map(view); l.OMSetRenderTargets( colors.len() as u32, @@ -1686,26 +2312,50 @@ impl Player { depth.as_ref().map(|d| d as *const _), ); } - Cmd::ClearDepth { view: v, flags, depth, stencil, rects } => { + Cmd::ClearDepth { + view: v, + flags, + depth, + stencil, + rects, + } => { let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); let rects = (!rects.is_empty()).then_some(&rects[..]); if self.objects.contains_key(&v.res) { - l.ClearDepthStencilView(view(v), D3D12_CLEAR_FLAGS(*flags), *depth, *stencil, rects); + l.ClearDepthStencilView( + view(v), + D3D12_CLEAR_FLAGS(*flags), + *depth, + *stencil, + rects, + ); } } - Cmd::ClearTarget { view: v, color, rects } => { + Cmd::ClearTarget { + view: v, + color, + rects, + } => { let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); let rects = (!rects.is_empty()).then_some(&rects[..]); if self.objects.contains_key(&v.res) { l.ClearRenderTargetView(view(v), color, rects); } } - Cmd::Discard { res: id, rects, subs } => { + Cmd::Discard { + res: id, + rects, + subs, + } => { if let Some(r) = res(*id) { let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); let region = subs.map(|s| D3D12_DISCARD_REGION { NumRects: rects.len() as u32, - pRects: if rects.is_empty() { std::ptr::null() } else { rects.as_ptr() }, + pRects: if rects.is_empty() { + std::ptr::null() + } else { + rects.as_ptr() + }, FirstSubresource: s[0], NumSubresources: s[1], }); @@ -1722,24 +2372,51 @@ impl Player { l.EndQuery(h, D3D12_QUERY_TYPE(*kind), *index); } } - Cmd::ResolveQuery { heap, kind, first, count, dst, at } => { + Cmd::ResolveQuery { + heap, + kind, + first, + count, + dst, + at, + } => { if let (Some(h), Some(dst)) = (self.queries.get(heap), res(*dst)) { l.ResolveQueryData(h, D3D12_QUERY_TYPE(*kind), *first, *count, dst, *at); } } - Cmd::Indirect { signature, most, args, at, count, count_at } => { + Cmd::Indirect { + signature, + most, + args, + at, + count, + count_at, + } => { if let (Some(s), Some(a)) = (self.signatures.get(signature), res(*args)) { l.ExecuteIndirect(s, *most, a, *at, res(*count), *count_at); } } Cmd::WriteImmediate { all } => { if let Ok(l) = l.cast::() { - let all: Vec<&(Va, u32, i32)> = all.iter().filter(|(va, _, _)| self.va(va) != 0).collect(); - let params: Vec = - all.iter().map(|(va, v, _)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: self.va(va), Value: *v }).collect(); - let modes: Vec = all.iter().map(|(_, _, m)| D3D12_WRITEBUFFERIMMEDIATE_MODE(*m)).collect(); + let all: Vec<&(Va, u32, i32)> = + all.iter().filter(|(va, _, _)| self.va(va) != 0).collect(); + let params: Vec = all + .iter() + .map(|(va, v, _)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { + Dest: self.va(va), + Value: *v, + }) + .collect(); + let modes: Vec = all + .iter() + .map(|(_, _, m)| D3D12_WRITEBUFFERIMMEDIATE_MODE(*m)) + .collect(); if !params.is_empty() { - l.WriteBufferImmediate(params.len() as u32, params.as_ptr(), Some(modes.as_ptr())); + l.WriteBufferImmediate( + params.len() as u32, + params.as_ptr(), + Some(modes.as_ptr()), + ); } } } @@ -1749,20 +2426,38 @@ impl Player { fn barrier(&self, b: &Barrier) -> Option { Some(match b { - Barrier::Transition { flags, res, sub, before, after } => { - let mut t = gpu::transition(self.resource(*res)?, *sub, *before as u32, *after as u32); + Barrier::Transition { + flags, + res, + sub, + before, + after, + } => { + let mut t = + gpu::transition(self.resource(*res)?, *sub, *before as u32, *after as u32); t.Flags = D3D12_RESOURCE_BARRIER_FLAGS(*flags); t } Barrier::Uav { flags, res } => { - let mut u = uav_barrier(if *res == NONE { None } else { Some(self.resource(*res)?) }); + let mut u = uav_barrier(if *res == NONE { + None + } else { + Some(self.resource(*res)?) + }); u.Flags = D3D12_RESOURCE_BARRIER_FLAGS(*flags); u } - Barrier::Alias { flags, before, after } => { + Barrier::Alias { + flags, + before, + after, + } => { let side = |id: &u32| -> std::mem::ManuallyDrop> { // SAFETY: a borrowed pointer (or none) never released. - self.resource(*id).map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { std::mem::transmute_copy(r) }) + self.resource(*id) + .map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { + std::mem::transmute_copy(r) + }) }; D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, @@ -1811,17 +2506,28 @@ impl Player { for all in &submissions { self.worker.queue.ExecuteCommandLists(all); } - self.worker.queue.ExecuteCommandLists(&[cast(&s.resolve.1)?]); + self.worker + .queue + .ExecuteCommandLists(&[cast(&s.resolve.1)?]); } - self.worker.idle().context("the card was lost running the frame")?; + self.worker + .idle() + .context("the card was lost running the frame")?; // SAFETY: the mapping of `count` resolved timestamps. Ok(unsafe { std::slice::from_raw_parts(s.data as *const u64, s.count as usize) }.to_vec()) } /// Runs the frame as the options say. pub fn run(&mut self, o: &Options) -> Result { - let mut report = Report { notes: self.notes.clone(), ..Default::default() }; - let clamps = if o.skip_clamps { self.clamp_results(&mut report)? } else { Vec::new() }; + let mut report = Report { + notes: self.notes.clone(), + ..Default::default() + }; + let clamps = if o.skip_clamps { + self.clamp_results(&mut report)? + } else { + Vec::new() + }; let submits = self.edited(o, &mut report, &clamps); let built = self.build(&submits, o)?; let mut stamps = Vec::new(); @@ -1829,20 +2535,33 @@ impl Player { self.restore(o.restore)?; self.fresh = false; stamps = self.send(&built, o.one_submit)?; - let ms = |a: u32, b: u32| stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency; + let ms = |a: u32, b: u32| { + stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency + }; let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect(); let (Some(first), Some(last)) = (lists.first(), lists.last()) else { bail!("no lists to run"); }; let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref()); - report.delta_ms.push(delta.filter(|d| d.first > first.first).map(|d| ms(d.first, d.last)).sum()); + report.delta_ms.push( + delta + .filter(|d| d.first > first.first) + .map(|d| ms(d.first, d.last)) + .sum(), + ); report.frame_ms.push(ms(first.first, last.last)); let each = |l: &[Built]| match (l.first(), l.last()) { (Some(a), Some(b)) => ms(a.first, b.last), _ => 0.0, }; - report.submits = built.steps.iter().map(|(_, l)| (l.len(), each(l))).collect(); - report.busy_ms.push(report.submits.iter().map(|s| s.1).sum()); + report.submits = built + .steps + .iter() + .map(|(_, l)| (l.len(), each(l))) + .collect(); + report + .busy_ms + .push(report.submits.iter().map(|s| s.1).sum()); } if o.detailed { self.detail(&built, &stamps, o, &mut report); @@ -1871,12 +2590,21 @@ impl Player { } } } - report.categories = kinds.into_iter().map(|(k, (ms, n))| (k.to_owned(), ms, n)).collect(); + report.categories = kinds + .into_iter() + .map(|(k, (ms, n))| (k.to_owned(), ms, n)) + .collect(); report.categories.sort_by(|a, b| b.1.total_cmp(&a.1)); - let mut all: Vec<(f64, u32, u32)> = shaders.into_iter().map(|(pso, (ms, n))| (ms, n, pso)).collect(); + let mut all: Vec<(f64, u32, u32)> = shaders + .into_iter() + .map(|(pso, (ms, n))| (ms, n, pso)) + .collect(); all.sort_by(|a, b| b.0.total_cmp(&a.0)); all.truncate(o.top); - report.shaders = all.into_iter().map(|(ms, n, pso)| (ms, n, self.pipeline_name(pso))).collect(); + report.shaders = all + .into_iter() + .map(|(ms, n, pso)| (ms, n, self.pipeline_name(pso))) + .collect(); } /// Saves the presented picture and compares it with the recorded one. @@ -1886,17 +2614,28 @@ impl Player { return Ok(()); }; let Some(bytes) = self.contents(p.res)? else { - report.notes.push("the presented texture is not there".into()); + report + .notes + .push("the presented texture is not there".into()); return Ok(()); }; let Some(rgb) = gpu::rgb(p.width, p.height, p.pitch, p.format, &bytes) else { - report.notes.push("the presented format is not shown".into()); + report + .notes + .push("the presented format is not shown".into()); return Ok(()); }; - let path = o.image.clone().unwrap_or_else(|| self.folder.join("replay.png")); + let path = o + .image + .clone() + .unwrap_or_else(|| self.folder.join("replay.png")); std::fs::write(&path, crate::capture::png(p.width, p.height, &rgb))?; let mut recorded = vec![0; bytes.len()]; - read_at(&File::open(self.folder.join("present.bin"))?, &mut recorded, p.file)?; + read_at( + &File::open(self.folder.join("present.bin"))?, + &mut recorded, + p.file, + )?; let was = gpu::rgb(p.width, p.height, p.pitch, p.format, &recorded).unwrap_or_default(); report.picture = Some((gpu::psnr(&rgb, &was), rows_equal(&p, &bytes, &recorded))); report.notes.push(format!( @@ -1924,8 +2663,17 @@ impl Player { let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; let states = if self.fresh { &self.start } else { &self.end }; let state = states.get(&id).cloned().unwrap_or(vec![COMMON]); - let (f, total) = if is_buffer { (Vec::new(), r.desc.width) } else { gpu::footprints(&self.device, &desc, sub, 1) }; - let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_FLAG_NONE)?; + let (f, total) = if is_buffer { + (Vec::new(), r.desc.width) + } else { + gpu::footprints(&self.device, &desc, sub, 1) + }; + let (back, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_READBACK, + total, + D3D12_RESOURCE_FLAG_NONE, + )?; self.worker.run(|list| { if is_buffer { // SAFETY: an open list; live buffers. @@ -1944,12 +2692,18 @@ impl Player { } })?; // SAFETY: the buffer's mapping; the copy into it has run. - Ok(Some(unsafe { std::slice::from_raw_parts(data, total as usize) }.to_vec())) + Ok(Some( + unsafe { std::slice::from_raw_parts(data, total as usize) }.to_vec(), + )) } /// The id of the resource of a name (tests). pub fn named(&self, name: &str) -> Option { - self.frame.resources.iter().find(|r| r.name == name).map(|r| r.id) + self.frame + .resources + .iter() + .find(|r| r.name == name) + .map(|r| r.id) } } @@ -1978,7 +2732,12 @@ fn rows_equal(p: &wire::Present, a: &[u8], b: &[u8]) -> bool { } fn to_rect(r: [i32; 4]) -> RECT { - RECT { left: r[0], top: r[1], right: r[2], bottom: r[3] } + RECT { + left: r[0], + top: r[1], + right: r[2], + bottom: r[3], + } } /// # Safety @@ -1997,7 +2756,9 @@ fn uav_barrier(res: Option<&ID3D12Resource>) -> D3D12_RESOURCE_BARRIER { Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { // SAFETY: a borrowed pointer (or none) never released. - pResource: res.map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { std::mem::transmute_copy(r) }), + pResource: res.map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { + std::mem::transmute_copy(r) + }), }), }, } @@ -2042,7 +2803,9 @@ fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option Result<(ID3D12Device, Option = None; match &adapter { @@ -2081,13 +2847,19 @@ fn debug_messages(q: &ID3D12InfoQueue) -> Vec { let m = &*message; if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 { let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); - let text = || String::from_utf8_lossy(text).trim_end_matches('\0').to_owned(); + let text = || { + String::from_utf8_lossy(text) + .trim_end_matches('\0') + .to_owned() + }; seen.entry(m.ID.0).or_insert_with(|| (0, text())).0 += 1; } } q.ClearStoredMessages(); } - seen.into_iter().map(|(id, (n, text))| format!("debug layer: {n} errors {id}, first: {text}")).collect() + seen.into_iter() + .map(|(id, (n, text))| format!("debug layer: {n} errors {id}, first: {text}")) + .collect() } #[cfg(test)] @@ -2106,7 +2878,10 @@ mod tests { } // The last complete one; itself when named. assert_eq!(find(dir.path()).unwrap(), dir.path().join("capture-10")); - assert_eq!(find(&dir.path().join("capture-2")).unwrap(), dir.path().join("capture-2")); + assert_eq!( + find(&dir.path().join("capture-2")).unwrap(), + dir.path().join("capture-2") + ); } #[test] @@ -2125,7 +2900,11 @@ mod tests { assert!(t.contains("a frame: 11.00 ms"), "{t}"); assert!(t.contains("between submissions 1.50 ms"), "{t}"); assert!(t.contains("PSNR 40.0 dB"), "{t}"); - let o = Options { skip_clamps: true, buffers: Buffers::Card, ..Default::default() }; + let o = Options { + skip_clamps: true, + buffers: Buffers::Card, + ..Default::default() + }; assert!(o.edited() && !o.plain().edited() && o.plain().buffers == Buffers::Card); } } diff --git a/crates/victory-gpu/src/replay/pso.rs b/crates/victory-gpu/src/replay/pso.rs index c1baa0d..aec3fbc 100644 --- a/crates/victory-gpu/src/replay/pso.rs +++ b/crates/victory-gpu/src/replay/pso.rs @@ -55,7 +55,10 @@ pub(super) trait Keep { /// `at` points at a value of `size` bytes. unsafe fn plain(kind: i32, at: *const c_void, size: usize) -> Part { // SAFETY: the caller's. - Part::Plain { kind, data: Blob(unsafe { std::slice::from_raw_parts(at.cast::(), size) }.to_vec()) } + Part::Plain { + kind, + data: Blob(unsafe { std::slice::from_raw_parts(at.cast::(), size) }.to_vec()), + } } unsafe fn code(kind: i32, c: &D3D12_SHADER_BYTECODE, keep: &mut dyn Keep) -> Option { @@ -63,8 +66,12 @@ unsafe fn code(kind: i32, c: &D3D12_SHADER_BYTECODE, keep: &mut dyn Keep) -> Opt return None; } // SAFETY: the description's own code. - let bytes = unsafe { std::slice::from_raw_parts(c.pShaderBytecode.cast::(), c.BytecodeLength) }; - Some(Part::Code { kind, blob: keep.code(bytes) }) + let bytes = + unsafe { std::slice::from_raw_parts(c.pShaderBytecode.cast::(), c.BytecodeLength) }; + Some(Part::Code { + kind, + blob: keep.code(bytes), + }) } unsafe fn layout(l: &D3D12_INPUT_LAYOUT_DESC) -> Option { @@ -72,34 +79,44 @@ unsafe fn layout(l: &D3D12_INPUT_LAYOUT_DESC) -> Option { return None; } // SAFETY: the description's own elements, with their names. - let elements = unsafe { std::slice::from_raw_parts(l.pInputElementDescs, l.NumElements as usize) } - .iter() - .map(|e| { - // SAFETY: as above. - let name = unsafe { e.SemanticName.to_string() }.unwrap_or_default(); - let rest = [ - e.SemanticIndex, - e.Format.0 as u32, - e.InputSlot, - e.AlignedByteOffset, - e.InputSlotClass.0 as u32, - e.InstanceDataStepRate, - ]; - (name, rest) - }) - .collect(); + let elements = + unsafe { std::slice::from_raw_parts(l.pInputElementDescs, l.NumElements as usize) } + .iter() + .map(|e| { + // SAFETY: as above. + let name = unsafe { e.SemanticName.to_string() }.unwrap_or_default(); + let rest = [ + e.SemanticIndex, + e.Format.0 as u32, + e.InputSlot, + e.AlignedByteOffset, + e.InputSlotClass.0 as u32, + e.InstanceDataStepRate, + ]; + (name, rest) + }) + .collect(); Some(Part::Layout { elements }) } /// # Safety /// A valid description. -pub(super) unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, keep: &mut dyn Keep) -> Vec { +pub(super) unsafe fn compute( + d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, + keep: &mut dyn Keep, +) -> Vec { // SAFETY: the caller's description. unsafe { - let mut parts = vec![Part::Root { root: keep.root(std::mem::transmute_copy(&d.pRootSignature)) }]; + let mut parts = vec![Part::Root { + root: keep.root(std::mem::transmute_copy(&d.pRootSignature)), + }]; parts.extend(code(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS.0, &d.CS, keep)); if d.Flags.0 != 0 { - parts.push(plain(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS.0, (&raw const d.Flags).cast(), 4)); + parts.push(plain( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS.0, + (&raw const d.Flags).cast(), + 4, + )); } parts } @@ -107,27 +124,55 @@ pub(super) unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, keep: &mut d /// # Safety /// A valid description. -pub(super) unsafe fn graphics(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, keep: &mut dyn Keep) -> Vec { +pub(super) unsafe fn graphics( + d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + keep: &mut dyn Keep, +) -> Vec { // SAFETY: the caller's description. unsafe { - let mut parts = vec![Part::Root { root: keep.root(std::mem::transmute_copy(&d.pRootSignature)) }]; + let mut parts = vec![Part::Root { + root: keep.root(std::mem::transmute_copy(&d.pRootSignature)), + }]; for (kind, c) in [(1, &d.VS), (2, &d.PS), (3, &d.DS), (4, &d.HS), (5, &d.GS)] { parts.extend(code(kind, c, keep)); } if d.StreamOutput.NumEntries != 0 { keep.lost("a pipeline's stream output"); } - parts.push(plain(8, (&raw const d.BlendState).cast(), size_of::())); + parts.push(plain( + 8, + (&raw const d.BlendState).cast(), + size_of::(), + )); parts.push(plain(9, (&raw const d.SampleMask).cast(), 4)); - parts.push(plain(10, (&raw const d.RasterizerState).cast(), size_of::())); - parts.push(plain(11, (&raw const d.DepthStencilState).cast(), size_of::())); + parts.push(plain( + 10, + (&raw const d.RasterizerState).cast(), + size_of::(), + )); + parts.push(plain( + 11, + (&raw const d.DepthStencilState).cast(), + size_of::(), + )); parts.extend(layout(&d.InputLayout)); parts.push(plain(13, (&raw const d.IBStripCutValue).cast(), 4)); parts.push(plain(14, (&raw const d.PrimitiveTopologyType).cast(), 4)); - let targets = D3D12_RT_FORMAT_ARRAY { RTFormats: d.RTVFormats, NumRenderTargets: d.NumRenderTargets }; - parts.push(plain(15, (&raw const targets).cast(), size_of::())); + let targets = D3D12_RT_FORMAT_ARRAY { + RTFormats: d.RTVFormats, + NumRenderTargets: d.NumRenderTargets, + }; + parts.push(plain( + 15, + (&raw const targets).cast(), + size_of::(), + )); parts.push(plain(16, (&raw const d.DSVFormat).cast(), 4)); - parts.push(plain(17, (&raw const d.SampleDesc).cast(), size_of::())); + parts.push(plain( + 17, + (&raw const d.SampleDesc).cast(), + size_of::(), + )); if d.Flags.0 != 0 { parts.push(plain(20, (&raw const d.Flags).cast(), 4)); } @@ -137,7 +182,10 @@ pub(super) unsafe fn graphics(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, keep: &mut /// # Safety /// A valid description. -pub(super) unsafe fn stream(d: &D3D12_PIPELINE_STATE_STREAM_DESC, keep: &mut dyn Keep) -> Vec { +pub(super) unsafe fn stream( + d: &D3D12_PIPELINE_STATE_STREAM_DESC, + keep: &mut dyn Keep, +) -> Vec { let base = d.pPipelineStateSubobjectStream.cast::().cast_const(); let mut parts = Vec::new(); let mut at = 0usize; @@ -147,7 +195,9 @@ pub(super) unsafe fn stream(d: &D3D12_PIPELINE_STATE_STREAM_DESC, keep: &mut dyn unsafe { let kind = base.add(at).cast::().read(); let Some(h) = holds(kind) else { - keep.lost(&format!("a pipeline stream's subobject of type {kind}, and those after it")); + keep.lost(&format!( + "a pipeline stream's subobject of type {kind}, and those after it" + )); break; }; let (from, size) = match h { @@ -158,12 +208,16 @@ pub(super) unsafe fn stream(d: &D3D12_PIPELINE_STATE_STREAM_DESC, keep: &mut dyn }; let value = base.add(at + from); match h { - Holds::Root => parts.push(Part::Root { root: keep.root(value.cast::<*mut c_void>().read()) }), + Holds::Root => parts.push(Part::Root { + root: keep.root(value.cast::<*mut c_void>().read()), + }), Holds::Code => parts.extend(code(kind, &*value.cast(), keep)), Holds::Layout => parts.extend(layout(&*value.cast())), Holds::Pointers(_) => { // A cached blob is only a shortcut. - let empty = std::slice::from_raw_parts(value, size).iter().all(|&b| b == 0); + let empty = std::slice::from_raw_parts(value, size) + .iter() + .all(|&b| b == 0); if kind != D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO.0 && !empty { keep.lost(&format!("a pipeline stream's subobject of type {kind}")); } @@ -194,13 +248,15 @@ pub(super) fn make( match part { Part::Root { root: 0 } => {} Part::Root { root: id } => { - let r = root(*id).ok_or_else(|| format!("root signature {id} is not in the capture"))?; + let r = root(*id) + .ok_or_else(|| format!("root signature {id} is not in the capture"))?; bytes.extend([0u8; 8]); bytes.extend((r.as_raw() as usize).to_le_bytes()); roots.push(r); } Part::Code { kind, blob } => { - let c = code(*blob).ok_or_else(|| format!("shader {blob} is not in the capture"))?; + let c = + code(*blob).ok_or_else(|| format!("shader {blob} is not in the capture"))?; bytes.extend(kind.to_le_bytes()); bytes.extend([0u8; 4]); bytes.extend((c.as_ptr() as usize).to_le_bytes()); @@ -217,7 +273,9 @@ pub(super) fn make( .map(|(name, r)| { names.push(CString::new(name.as_str()).unwrap_or_default()); D3D12_INPUT_ELEMENT_DESC { - SemanticName: PCSTR(names.last().map_or(std::ptr::null(), |n| n.as_ptr().cast())), + SemanticName: PCSTR( + names.last().map_or(std::ptr::null(), |n| n.as_ptr().cast()), + ), SemanticIndex: r[0], Format: DXGI_FORMAT(r[1] as i32), InputSlot: r[2], @@ -227,7 +285,11 @@ pub(super) fn make( } }) .collect(); - bytes.extend(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0.to_le_bytes()); + bytes.extend( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT + .0 + .to_le_bytes(), + ); bytes.extend([0u8; 4]); bytes.extend((made.as_ptr() as usize).to_le_bytes()); bytes.extend((made.len() as u64).to_le_bytes()); @@ -237,13 +299,17 @@ pub(super) fn make( } bytes.resize(bytes.len().next_multiple_of(8), 0); // Aligned for the pointers in it. - let mut words: Vec = bytes.chunks_exact(8).map(|c| u64::from_le_bytes(c.try_into().unwrap_or_default())).collect(); + let mut words: Vec = bytes + .chunks_exact(8) + .map(|c| u64::from_le_bytes(c.try_into().unwrap_or_default())) + .collect(); let desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: words.len() * 8, pPipelineStateSubobjectStream: words.as_mut_ptr().cast(), }; // SAFETY: a stream of whole subobjects; all it points at is alive. - let made: windows::core::Result = unsafe { device.CreatePipelineState(&desc) }; + let made: windows::core::Result = + unsafe { device.CreatePipelineState(&desc) }; made.map_err(|e| e.to_string()) } @@ -290,17 +356,44 @@ mod tests { let bytes = [1u8, 2, 3]; let mut s = Stream { root: Sub(0, 77), - ms: Sub(25, D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: 3 }), + ms: Sub( + 25, + D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: 3, + }, + ), blend: Sub(8, D3D12_BLEND_DESC::default()), mask: Sub(9, 5), - raster: Sub(10, D3D12_RASTERIZER_DESC { DepthBias: 6, ..Default::default() }), + raster: Sub( + 10, + D3D12_RASTERIZER_DESC { + DepthBias: 6, + ..Default::default() + }, + ), depth: Sub(11, D3D12_DEPTH_STENCIL_DESC::default()), - targets: Sub(15, D3D12_RT_FORMAT_ARRAY { NumRenderTargets: 3, ..Default::default() }), + targets: Sub( + 15, + D3D12_RT_FORMAT_ARRAY { + NumRenderTargets: 3, + ..Default::default() + }, + ), dsv: Sub(16, DXGI_FORMAT(40)), - samples: Sub(17, DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }), + samples: Sub( + 17, + DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ), unknown: Sub(99, 0), }; - let d = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: size_of::(), pPipelineStateSubobjectStream: (&raw mut s).cast() }; + let d = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::(), + pPipelineStateSubobjectStream: (&raw mut s).cast(), + }; let mut kept = Kept::default(); // SAFETY: the stream above. let parts = unsafe { stream(&d, &mut kept) }; @@ -309,9 +402,23 @@ mod tests { assert_eq!(parts.len(), 9); assert_eq!(parts[0], Part::Root { root: 77 }); assert_eq!(parts[1], Part::Code { kind: 25, blob: 0 }); - assert_eq!(parts[3], Part::Plain { kind: 9, data: Blob(5u32.to_le_bytes().to_vec()) }); - let Part::Plain { kind: 10, data } = &parts[4] else { panic!("{:?}", parts[4]) }; + assert_eq!( + parts[3], + Part::Plain { + kind: 9, + data: Blob(5u32.to_le_bytes().to_vec()) + } + ); + let Part::Plain { kind: 10, data } = &parts[4] else { + panic!("{:?}", parts[4]) + }; assert_eq!(data.0.len(), size_of::()); - assert_eq!(parts[7], Part::Plain { kind: 16, data: Blob(40u32.to_le_bytes().to_vec()) }); + assert_eq!( + parts[7], + Part::Plain { + kind: 16, + data: Blob(40u32.to_le_bytes().to_vec()) + } + ); } } diff --git a/crates/victory-gpu/src/replay/record.rs b/crates/victory-gpu/src/replay/record.rs index 799fe1e..c839d60 100644 --- a/crates/victory-gpu/src/replay/record.rs +++ b/crates/victory-gpu/src/replay/record.rs @@ -60,9 +60,17 @@ impl Settings { pub fn from_env() -> Option { let folder = PathBuf::from(std::env::var_os("VICTORY_RECORD").filter(|v| !v.is_empty())?); let at = parse_at(&std::env::var("VICTORY_RECORD_AT").unwrap_or_default()); - let frames = std::env::var("VICTORY_RECORD_FRAMES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1); + let frames = std::env::var("VICTORY_RECORD_FRAMES") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(1); let always = std::env::var_os("VICTORY_RECORD_ALWAYS").is_some_and(|v| v == "1"); - Some(Settings { folder, at, frames: std::cmp::max(frames, 1), always }) + Some(Settings { + folder, + at, + frames: std::cmp::max(frames, 1), + always, + }) } } @@ -148,11 +156,21 @@ impl Heap { if slots.is_null() { std::alloc::handle_alloc_error(layout); } - Heap { id, kind: desc.Type.0, count: desc.NumDescriptors, flags: desc.Flags.0, cpu, gpu, step, slots } + Heap { + id, + kind: desc.Type.0, + count: desc.NumDescriptors, + flags: desc.Flags.0, + cpu, + gpu, + step, + slots, + } } fn layout(count: u32) -> std::alloc::Layout { - std::alloc::Layout::array::(count.max(1) as usize).unwrap_or(std::alloc::Layout::new::()) + std::alloc::Layout::array::(count.max(1) as usize) + .unwrap_or(std::alloc::Layout::new::()) } pub(super) fn visible(&self) -> bool { @@ -202,8 +220,13 @@ pub(super) struct Heaps { impl Heaps { fn add(&mut self, heap: Arc) { let end = heap.cpu + heap.count as usize * heap.step; - let gone: Vec = - self.by_cpu.range(..end).rev().take_while(|(_, h)| h.cpu + h.count as usize * h.step > heap.cpu).map(|(&k, _)| k).collect(); + let gone: Vec = self + .by_cpu + .range(..end) + .rev() + .take_while(|(_, h)| h.cpu + h.count as usize * h.step > heap.cpu) + .map(|(&k, _)| k) + .collect(); for k in gone { self.by_cpu.remove(&k); } @@ -400,7 +423,12 @@ impl Recorder { signatures: Mutex::default(), queries: Mutex::default(), names: Mutex::default(), - codes: Mutex::new(Codes { file: Some(file), at: 0, index: HashMap::new(), all: Vec::new() }), + codes: Mutex::new(Codes { + file: Some(file), + at: 0, + index: HashMap::new(), + all: Vec::new(), + }), states: Mutex::default(), queues: Mutex::default(), device: Mutex::default(), @@ -433,7 +461,16 @@ impl Recorder { /// The problems so far. pub(super) fn problems(&self) -> Vec { - lock(&self.problems).iter().map(|(what, n)| if *n == 1 { what.clone() } else { format!("{what} ({n} times)") }).collect() + lock(&self.problems) + .iter() + .map(|(what, n)| { + if *n == 1 { + what.clone() + } else { + format!("{what} ({n} times)") + } + }) + .collect() } pub(super) fn arm(&self, on: bool) { @@ -444,6 +481,12 @@ impl Recorder { lock(&self.device).clone() } + /// Whether a list was made through the hooked device (the swap chain may + /// have others). + pub(super) fn knows(&self, p: Ptr) -> bool { + read(&self.lists).contains_key(&(p as usize)) + } + /// The state of a list, if its methods are still ours. pub(super) fn list(&self, p: Ptr) -> Option> { let state = read(&self.lists).get(&(p as usize)).cloned()?; @@ -461,7 +504,10 @@ impl Recorder { return Va::Null {}; } match read(&self.addresses).range(..=address).next_back() { - Some((&start, &(size, res))) if address - start < size => Va::At { res, offset: address - start }, + Some((&start, &(size, res))) if address - start < size => Va::At { + res, + offset: address - start, + }, _ => Va::Unknown { address }, } } @@ -498,13 +544,19 @@ impl Recorder { let id = self.id(); let seen = match &place { Place::Committed { props, .. } => gpu::seen(props), - Place::Placed { heap, .. } => lock(&self.heaps).get(heap).map_or(gpu::Seen::No, |h| gpu::seen(&h.props)), + Place::Placed { heap, .. } => lock(&self.heaps) + .get(heap) + .map_or(gpu::Seen::No, |h| gpu::seen(&h.props)), Place::BackBuffer {} => gpu::Seen::No, }; let subs = gpu::subresources(&desc); let is_buffer = desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; // SAFETY: a live buffer. - let va = if is_buffer { unsafe { object.GetGPUVirtualAddress() } } else { 0 }; + let va = if is_buffer { + unsafe { object.GetGPUVirtualAddress() } + } else { + 0 + }; let placed = matches!(place, Place::Placed { .. }); let late = self.watching.load(Ordering::SeqCst); { @@ -520,13 +572,30 @@ impl Recorder { if va != 0 { write(&self.addresses).insert(va, (desc.width, id)); } - let res = Arc::new(Res { id, ptr: p as usize, place, desc, made_in, clear, subs, seen, late }); + let res = Arc::new(Res { + id, + ptr: p as usize, + place, + desc, + made_in, + clear, + subs, + seen, + late, + }); write(&self.resources).insert(id, res); self.ids.set(p as usize, id); if late { lock(&self.held).push(ID3D12Resource::clone(&object)); } - self.tell_gone(&*object, Gone::Resource { id, ptr: p as usize, va }); + self.tell_gone( + &*object, + Gone::Resource { + id, + ptr: p as usize, + va, + }, + ); id } @@ -557,12 +626,18 @@ impl Recorder { /// Has us told when an object dies. fn tell_gone(&self, object: &impl Interface, what: Gone) { const KEY: GUID = GUID::from_u128(0x3d0d5c1e_7a1b_4a53_9a3e_5f2b1e6b9c41); - let notice = Box::into_raw(Box::new(Notice { methods: &NOTICE, references: AtomicU32::new(1), what })); + let notice = Box::into_raw(Box::new(Notice { + methods: &NOTICE, + references: AtomicU32::new(1), + what, + })); // SAFETY: a COM object of ours with one reference, which this drops // at the end; the object takes its own. unsafe { let notice = IUnknown::from_raw(notice.cast()); - let set = object.cast::().and_then(|o| o.SetPrivateDataInterface(&KEY, ¬ice)); + let set = object + .cast::() + .and_then(|o| o.SetPrivateDataInterface(&KEY, ¬ice)); if set.is_err() { self.problem("an object's end cannot be followed"); std::mem::forget(notice); @@ -620,14 +695,21 @@ impl Recorder { } let i = codes.all.len() as u32; let at = codes.at; - let wrote = codes.file.as_mut().is_some_and(|f| f.write_all(bytes).is_ok()); + let wrote = codes + .file + .as_mut() + .is_some_and(|f| f.write_all(bytes).is_ok()); if !wrote { drop(codes); self.problem("shader code could not be written"); return u32::MAX; } codes.at += bytes.len() as u64; - codes.all.push(wire::Code { at, len: bytes.len() as u64, hash }); + codes.all.push(wire::Code { + at, + len: bytes.len() as u64, + hash, + }); codes.index.insert(hash, i); i } @@ -681,7 +763,11 @@ struct NoticeTable { add: unsafe extern "system" fn(Ptr) -> u32, release: unsafe extern "system" fn(Ptr) -> u32, } -static NOTICE: NoticeTable = NoticeTable { query: notice_query, add: notice_add, release: notice_release }; +static NOTICE: NoticeTable = NoticeTable { + query: notice_query, + add: notice_add, + release: notice_release, +}; unsafe extern "system" fn notice_query(this: Ptr, iid: *const GUID, out: Out) -> HRESULT { // SAFETY: COM's rules: a valid id and place for the answer. @@ -698,13 +784,21 @@ unsafe extern "system" fn notice_query(this: Ptr, iid: *const GUID, out: Out) -> unsafe extern "system" fn notice_add(this: Ptr) -> u32 { // SAFETY: one of ours, alive while a reference is. - unsafe { (*this.cast::()).references.fetch_add(1, Ordering::Relaxed) + 1 } + unsafe { + (*this.cast::()) + .references + .fetch_add(1, Ordering::Relaxed) + + 1 + } } unsafe extern "system" fn notice_release(this: Ptr) -> u32 { // SAFETY: as above; the last reference frees the box it was made as. unsafe { - let left = (*this.cast::()).references.fetch_sub(1, Ordering::AcqRel) - 1; + let left = (*this.cast::()) + .references + .fetch_sub(1, Ordering::AcqRel) + - 1; if left == 0 { let notice = Box::from_raw(this.cast::()); if let Some(r) = recorder() { @@ -831,10 +925,19 @@ macro_rules! not_recorded { fn device_table(t: &mut [usize; hook::SLOTS]) { set!(t, ID3D12Device_Vtbl.CreateCommandQueue = create_queue); - set!(t, ID3D12Device_Vtbl.CreateGraphicsPipelineState = create_graphics); - set!(t, ID3D12Device_Vtbl.CreateComputePipelineState = create_compute); + set!( + t, + ID3D12Device_Vtbl.CreateGraphicsPipelineState = create_graphics + ); + set!( + t, + ID3D12Device_Vtbl.CreateComputePipelineState = create_compute + ); set!(t, ID3D12Device_Vtbl.CreateCommandList = create_list); - set!(t, ID3D12Device_Vtbl.CreateDescriptorHeap = create_descriptors); + set!( + t, + ID3D12Device_Vtbl.CreateDescriptorHeap = create_descriptors + ); set!(t, ID3D12Device_Vtbl.CreateRootSignature = create_root); set!(t, ID3D12Device_Vtbl.CreateConstantBufferView = create_cbv); set!(t, ID3D12Device_Vtbl.CreateShaderResourceView = create_srv); @@ -843,12 +946,21 @@ fn device_table(t: &mut [usize; hook::SLOTS]) { set!(t, ID3D12Device_Vtbl.CreateDepthStencilView = create_dsv); set!(t, ID3D12Device_Vtbl.CreateSampler = create_sampler); set!(t, ID3D12Device_Vtbl.CopyDescriptors = copy_descriptors); - set!(t, ID3D12Device_Vtbl.CopyDescriptorsSimple = copy_descriptors_simple); - set!(t, ID3D12Device_Vtbl.CreateCommittedResource = create_committed); + set!( + t, + ID3D12Device_Vtbl.CopyDescriptorsSimple = copy_descriptors_simple + ); + set!( + t, + ID3D12Device_Vtbl.CreateCommittedResource = create_committed + ); set!(t, ID3D12Device_Vtbl.CreateHeap = create_heap); set!(t, ID3D12Device_Vtbl.CreatePlacedResource = create_placed); set!(t, ID3D12Device_Vtbl.CreateQueryHeap = create_queries); - set!(t, ID3D12Device_Vtbl.CreateCommandSignature = create_signature); + set!( + t, + ID3D12Device_Vtbl.CreateCommandSignature = create_signature + ); set!(t, ID3D12Device1_Vtbl.CreatePipelineLibrary = create_library); set!(t, ID3D12Device2_Vtbl.CreatePipelineState = create_stream); let _ = device_rest(t); @@ -889,8 +1001,14 @@ fn queue_rest(t: &mut [usize; hook::SLOTS]) -> &'static [(usize, &'static str)] } fn library_table(t: &mut [usize; hook::SLOTS]) { - set!(t, ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline = load_graphics); - set!(t, ID3D12PipelineLibrary_Vtbl.LoadComputePipeline = load_compute); + set!( + t, + ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline = load_graphics + ); + set!( + t, + ID3D12PipelineLibrary_Vtbl.LoadComputePipeline = load_compute + ); set!(t, ID3D12PipelineLibrary1_Vtbl.LoadPipeline = load_stream); } @@ -898,48 +1016,153 @@ fn list_table(t: &mut [usize; hook::SLOTS]) { set!(t, ID3D12GraphicsCommandList_Vtbl.Close = list_close); set!(t, ID3D12GraphicsCommandList_Vtbl.Reset = list_reset); set!(t, ID3D12GraphicsCommandList_Vtbl.DrawInstanced = draw); - set!(t, ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced = draw_indexed); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced = draw_indexed + ); set!(t, ID3D12GraphicsCommandList_Vtbl.Dispatch = dispatch); - set!(t, ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion = copy_buffer); - set!(t, ID3D12GraphicsCommandList_Vtbl.CopyTextureRegion = copy_texture); - set!(t, ID3D12GraphicsCommandList_Vtbl.CopyResource = copy_resource); - set!(t, ID3D12GraphicsCommandList_Vtbl.ResolveSubresource = resolve); - set!(t, ID3D12GraphicsCommandList_Vtbl.IASetPrimitiveTopology = topology); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion = copy_buffer + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.CopyTextureRegion = copy_texture + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.CopyResource = copy_resource + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.ResolveSubresource = resolve + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.IASetPrimitiveTopology = topology + ); set!(t, ID3D12GraphicsCommandList_Vtbl.RSSetViewports = viewports); - set!(t, ID3D12GraphicsCommandList_Vtbl.RSSetScissorRects = scissors); - set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor = blend_factor); - set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetStencilRef = stencil_ref); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetPipelineState = set_pipeline); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.RSSetScissorRects = scissors + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor = blend_factor + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.OMSetStencilRef = stencil_ref + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetPipelineState = set_pipeline + ); set!(t, ID3D12GraphicsCommandList_Vtbl.ResourceBarrier = barrier); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps = set_heaps); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature = root_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature = root_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable = table_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable = table_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant = constant_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant = constant_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants = constants_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants = constants_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootConstantBufferView = cbv_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootConstantBufferView = cbv_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootShaderResourceView = srv_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootShaderResourceView = srv_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootUnorderedAccessView = uav_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootUnorderedAccessView = uav_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer = index_buffer); - set!(t, ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers = vertex_buffers); - set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets = targets); - set!(t, ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView = clear_depth); - set!(t, ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView = clear_target); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps = set_heaps + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature = root_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature = root_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable = table_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable = table_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant = constant_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant = constant_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants = constants_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants = constants_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootConstantBufferView = cbv_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootConstantBufferView = cbv_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootShaderResourceView = srv_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootShaderResourceView = srv_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootUnorderedAccessView = uav_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootUnorderedAccessView = uav_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer = index_buffer + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers = vertex_buffers + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets = targets + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView = clear_depth + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView = clear_target + ); set!(t, ID3D12GraphicsCommandList_Vtbl.DiscardResource = discard); set!(t, ID3D12GraphicsCommandList_Vtbl.BeginQuery = begin_query); set!(t, ID3D12GraphicsCommandList_Vtbl.EndQuery = end_query); - set!(t, ID3D12GraphicsCommandList_Vtbl.ResolveQueryData = resolve_query); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.ResolveQueryData = resolve_query + ); set!(t, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect = indirect); - set!(t, ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion = resolve_region); - set!(t, ID3D12GraphicsCommandList1_Vtbl.OMSetDepthBounds = depth_bounds); - set!(t, ID3D12GraphicsCommandList2_Vtbl.WriteBufferImmediate = write_immediate); - set!(t, ID3D12GraphicsCommandList6_Vtbl.DispatchMesh = dispatch_mesh); + set!( + t, + ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion = resolve_region + ); + set!( + t, + ID3D12GraphicsCommandList1_Vtbl.OMSetDepthBounds = depth_bounds + ); + set!( + t, + ID3D12GraphicsCommandList2_Vtbl.WriteBufferImmediate = write_immediate + ); + set!( + t, + ID3D12GraphicsCommandList6_Vtbl.DispatchMesh = dispatch_mesh + ); let _ = list_rest(t); } @@ -990,7 +1213,10 @@ pub(super) fn not_recorded_calls() -> Vec<(String, u64)> { for &(slot, name) in names { let what = match (class, name) { // Submissions are in order anyway: the replay has one queue. - (hook::QUEUE, "Wait") => "waits of the drawing queue (the swap chain makes some) are not replayed".to_owned(), + (hook::QUEUE, "Wait") => { + "waits of the drawing queue (the swap chain makes some) are not replayed" + .to_owned() + } _ => format!("{of} method {name} is not recorded, and was called"), }; all.push((what, hook::count(class, slot))); @@ -1011,7 +1237,12 @@ fn made(hr: HRESULT, out: Out) -> Option<(&'static Recorder, Ptr)> { Some((recorder()?, p)) } -unsafe extern "system" fn create_queue(this: Ptr, desc: *const D3D12_COMMAND_QUEUE_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_queue( + this: Ptr, + desc: *const D3D12_COMMAND_QUEUE_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: the caller's arguments, passed on; then a new queue no other // thread knows. unsafe { @@ -1037,9 +1268,14 @@ unsafe extern "system" fn create_list( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12Device_Vtbl.CreateCommandList)(this, nodes, kind, allocator, pso, iid, out); + let hr = own!(this, ID3D12Device_Vtbl.CreateCommandList)( + this, nodes, kind, allocator, pso, iid, out, + ); if let Some((r, p)) = made(hr, out) { - let state = Arc::new(ListState { kind: kind.0, inner: Mutex::default() }); + let state = Arc::new(ListState { + kind: kind.0, + inner: Mutex::default(), + }); // Every interface of it we hook, and the one it is submitted as. static ONE: OnceLock = OnceLock::new(); let iids = [ @@ -1049,21 +1285,32 @@ unsafe extern "system" fn create_list( ID3D12GraphicsCommandList4::IID, ID3D12GraphicsCommandList6::IID, ]; - let same = *ONE.get_or_init(|| iids.iter().all(|iid| query(p, iid).is_none_or(|q| q.as_raw() == p))); + let same = *ONE.get_or_init(|| { + iids.iter() + .all(|iid| query(p, iid).is_none_or(|q| q.as_raw() == p)) + }); let mut all = vec![p]; if !same { - all.extend(iids.iter().filter_map(|iid| query(p, iid)).map(|q| q.as_raw())); + all.extend( + iids.iter() + .filter_map(|iid| query(p, iid)) + .map(|q| q.as_raw()), + ); } { let mut inner = lock(&state.inner); - inner.whole = r.armed.load(Ordering::SeqCst) && kind == D3D12_COMMAND_LIST_TYPE_DIRECT; + inner.whole = + r.armed.load(Ordering::SeqCst) && kind == D3D12_COMMAND_LIST_TYPE_DIRECT; begin(&mut inner, r, pso); } for q in all { // The state's address is kept for good, as the table is. hook::install(q, Arc::into_raw(state.clone()).cast(), list_table); write(&r.lists).insert(q as usize, state.clone()); - r.tell_gone(&*borrow::(q), Gone::List { ptr: q as usize }); + r.tell_gone( + &*borrow::(q), + Gone::List { ptr: q as usize }, + ); } } hr @@ -1075,11 +1322,20 @@ fn begin(inner: &mut ListInner, r: &Recorder, pso: Ptr) { inner.bytes = Vec::new(); inner.changes.clear(); if inner.whole && !pso.is_null() { - Cmd::Pipeline { pso: r.object(pso, "a pipeline") }.put(&mut inner.bytes); + Cmd::Pipeline { + pso: r.object(pso, "a pipeline"), + } + .put(&mut inner.bytes); } } -unsafe extern "system" fn create_library(this: Ptr, blob: *const c_void, size: usize, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_library( + this: Ptr, + blob: *const c_void, + size: usize, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device1_Vtbl.CreatePipelineLibrary)(this, blob, size, iid, out); @@ -1095,7 +1351,12 @@ unsafe extern "system" fn create_library(this: Ptr, blob: *const c_void, size: u } } -unsafe extern "system" fn create_graphics(this: Ptr, desc: *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_graphics( + this: Ptr, + desc: *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above; the description is valid, as it was accepted. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateGraphicsPipelineState)(this, desc, iid, out); @@ -1106,7 +1367,12 @@ unsafe extern "system" fn create_graphics(this: Ptr, desc: *const D3D12_GRAPHICS } } -unsafe extern "system" fn create_compute(this: Ptr, desc: *const D3D12_COMPUTE_PIPELINE_STATE_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_compute( + this: Ptr, + desc: *const D3D12_COMPUTE_PIPELINE_STATE_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateComputePipelineState)(this, desc, iid, out); @@ -1117,7 +1383,12 @@ unsafe extern "system" fn create_compute(this: Ptr, desc: *const D3D12_COMPUTE_P } } -unsafe extern "system" fn create_stream(this: Ptr, desc: *const D3D12_PIPELINE_STATE_STREAM_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_stream( + this: Ptr, + desc: *const D3D12_PIPELINE_STATE_STREAM_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device2_Vtbl.CreatePipelineState)(this, desc, iid, out); @@ -1137,7 +1408,8 @@ unsafe extern "system" fn load_graphics( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline)(this, name, desc, iid, out); + let hr = + own!(this, ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline)(this, name, desc, iid, out); if let Some((r, p)) = made(hr, out) { r.pipeline(p, pso::graphics(&*desc, &mut Keeper(r))); } @@ -1154,7 +1426,8 @@ unsafe extern "system" fn load_compute( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12PipelineLibrary_Vtbl.LoadComputePipeline)(this, name, desc, iid, out); + let hr = + own!(this, ID3D12PipelineLibrary_Vtbl.LoadComputePipeline)(this, name, desc, iid, out); if let Some((r, p)) = made(hr, out) { r.pipeline(p, pso::compute(&*desc, &mut Keeper(r))); } @@ -1179,13 +1452,24 @@ unsafe extern "system" fn load_stream( } } -unsafe extern "system" fn create_root(this: Ptr, nodes: u32, blob: *const c_void, size: usize, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_root( + this: Ptr, + nodes: u32, + blob: *const c_void, + size: usize, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12Device_Vtbl.CreateRootSignature)(this, nodes, blob, size, iid, out); + let hr = + own!(this, ID3D12Device_Vtbl.CreateRootSignature)(this, nodes, blob, size, iid, out); if let Some((r, p)) = made(hr, out) { // D3D12 may answer with an object it made before. - let known = r.ids.get(p as usize).filter(|id| lock(&r.roots).contains_key(id)); + let known = r + .ids + .get(p as usize) + .filter(|id| lock(&r.roots).contains_key(id)); let bytes = std::slice::from_raw_parts(blob.cast::(), size).to_vec(); let id = known.unwrap_or_else(|| r.id()); lock(&r.roots).insert(id, Arc::new(bytes)); @@ -1208,8 +1492,11 @@ unsafe extern "system" fn create_signature( if let Some((r, p)) = made(hr, out) { let id = r.id(); let d = &*desc; - let args: Vec<[u32; 4]> = - std::slice::from_raw_parts(d.pArgumentDescs.cast::<[u32; 4]>(), d.NumArgumentDescs as usize).to_vec(); + let args: Vec<[u32; 4]> = std::slice::from_raw_parts( + d.pArgumentDescs.cast::<[u32; 4]>(), + d.NumArgumentDescs as usize, + ) + .to_vec(); // Arguments that are GPU addresses lie in buffers; they are not // rewritten for a replay. let addresses = [ @@ -1219,31 +1506,63 @@ unsafe extern "system" fn create_signature( D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW, D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW, ]; - if args.iter().any(|a| addresses.iter().any(|t| t.0 as u32 == a[0])) { + if args + .iter() + .any(|a| addresses.iter().any(|t| t.0 as u32 == a[0])) + { r.problem("a command signature with GPU addresses among its arguments: a replay reads the recorded addresses"); } - let root = if root.is_null() { NONE } else { r.object(root, "a root signature") }; - lock(&r.signatures).insert(id, wire::Signature { id, stride: d.ByteStride, args, root }); + let root = if root.is_null() { + NONE + } else { + r.object(root, "a root signature") + }; + lock(&r.signatures).insert( + id, + wire::Signature { + id, + stride: d.ByteStride, + args, + root, + }, + ); r.ids.set(p as usize, id); } hr } } -unsafe extern "system" fn create_queries(this: Ptr, desc: *const D3D12_QUERY_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_queries( + this: Ptr, + desc: *const D3D12_QUERY_HEAP_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateQueryHeap)(this, desc, iid, out); if let Some((r, p)) = made(hr, out) { let id = r.id(); - lock(&r.queries).insert(id, wire::QueryHeap { id, kind: (*desc).Type.0, count: (*desc).Count }); + lock(&r.queries).insert( + id, + wire::QueryHeap { + id, + kind: (*desc).Type.0, + count: (*desc).Count, + }, + ); r.ids.set(p as usize, id); } hr } } -unsafe extern "system" fn create_descriptors(this: Ptr, desc: *const D3D12_DESCRIPTOR_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_descriptors( + this: Ptr, + desc: *const D3D12_DESCRIPTOR_HEAP_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateDescriptorHeap)(this, desc, iid, out); @@ -1252,18 +1571,34 @@ unsafe extern "system" fn create_descriptors(this: Ptr, desc: *const D3D12_DESCR let d = &*desc; let visible = d.Flags.0 & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 != 0; let cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr; - let gpu = if visible { heap.GetGPUDescriptorHandleForHeapStart().ptr } else { 0 }; - let step = own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, d.Type) as usize; + let gpu = if visible { + heap.GetGPUDescriptorHandleForHeapStart().ptr + } else { + 0 + }; + let step = own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, d.Type) + as usize; let id = r.id(); write(&r.descriptors).add(Arc::new(Heap::new(id, d, cpu, gpu, step.max(1)))); r.ids.set(p as usize, id); - r.tell_gone(&*heap, Gone::Heap { id, ptr: p as usize }); + r.tell_gone( + &*heap, + Gone::Heap { + id, + ptr: p as usize, + }, + ); } hr } } -unsafe extern "system" fn create_heap(this: Ptr, desc: *const D3D12_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_heap( + this: Ptr, + desc: *const D3D12_HEAP_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateHeap)(this, desc, iid, out); @@ -1277,7 +1612,13 @@ unsafe extern "system" fn create_heap(this: Ptr, desc: *const D3D12_HEAP_DESC, i } fn heap_of(id: u32, d: &D3D12_HEAP_DESC) -> wire::Heap { - wire::Heap { id, size: d.SizeInBytes, props: gpu::from_props(&d.Properties), alignment: d.Alignment, flags: d.Flags.0 } + wire::Heap { + id, + size: d.SizeInBytes, + props: gpu::from_props(&d.Properties), + alignment: d.Alignment, + flags: d.Flags.0, + } } unsafe fn clear_of(clear: *const D3D12_CLEAR_VALUE) -> Option<[u32; 5]> { @@ -1299,9 +1640,14 @@ unsafe extern "system" fn create_committed( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12Device_Vtbl.CreateCommittedResource)(this, props, flags, desc, state, clear, iid, out); + let hr = own!(this, ID3D12Device_Vtbl.CreateCommittedResource)( + this, props, flags, desc, state, clear, iid, out, + ); if let Some((r, p)) = made(hr, out) { - let place = Place::Committed { props: gpu::from_props(&*props), flags: flags.0 }; + let place = Place::Committed { + props: gpu::from_props(&*props), + flags: flags.0, + }; r.add(p, place, state.0, clear_of(clear)); } hr @@ -1321,7 +1667,9 @@ unsafe extern "system" fn create_placed( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12Device_Vtbl.CreatePlacedResource)(this, heap, offset, desc, state, clear, iid, out); + let hr = own!(this, ID3D12Device_Vtbl.CreatePlacedResource)( + this, heap, offset, desc, state, clear, iid, out, + ); if let Some((r, p)) = made(hr, out) { // One opened from memory was not seen made. let heap = r.ids.get(heap as usize).unwrap_or_else(|| { @@ -1338,23 +1686,50 @@ unsafe extern "system" fn create_placed( } } -unsafe extern "system" fn create_cbv(this: Ptr, desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_cbv( + this: Ptr, + desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateConstantBufferView)(this, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { - r.set_view(at.ptr, &Slot::new(slot::CBV, NONE, NONE, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::CBV, + NONE, + NONE, + desc.cast(), + size_of::(), + ), + ); } } } -unsafe extern "system" fn create_srv(this: Ptr, res: Ptr, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_srv( + this: Ptr, + res: Ptr, + desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateShaderResourceView)(this, res, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { let id = r.resource(res); - r.set_view(at.ptr, &Slot::new(slot::SRV, id, NONE, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::SRV, + id, + NONE, + desc.cast(), + size_of::(), + ), + ); } } } @@ -1371,40 +1746,84 @@ unsafe extern "system" fn create_uav( own!(this, ID3D12Device_Vtbl.CreateUnorderedAccessView)(this, res, counter, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { let (id, counter) = (r.resource(res), r.resource(counter)); - r.set_view(at.ptr, &Slot::new(slot::UAV, id, counter, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::UAV, + id, + counter, + desc.cast(), + size_of::(), + ), + ); } } } -unsafe extern "system" fn create_rtv(this: Ptr, res: Ptr, desc: *const D3D12_RENDER_TARGET_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_rtv( + this: Ptr, + res: Ptr, + desc: *const D3D12_RENDER_TARGET_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateRenderTargetView)(this, res, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { let id = r.resource(res); - r.set_view(at.ptr, &Slot::new(slot::RTV, id, NONE, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::RTV, + id, + NONE, + desc.cast(), + size_of::(), + ), + ); } } } -unsafe extern "system" fn create_dsv(this: Ptr, res: Ptr, desc: *const D3D12_DEPTH_STENCIL_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_dsv( + this: Ptr, + res: Ptr, + desc: *const D3D12_DEPTH_STENCIL_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateDepthStencilView)(this, res, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { let id = r.resource(res); - r.set_view(at.ptr, &Slot::new(slot::DSV, id, NONE, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::DSV, + id, + NONE, + desc.cast(), + size_of::(), + ), + ); } } } -unsafe extern "system" fn create_sampler(this: Ptr, desc: *const D3D12_SAMPLER_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_sampler( + this: Ptr, + desc: *const D3D12_SAMPLER_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { const _: () = assert!(size_of::() == 52); // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateSampler)(this, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { - r.set_view(at.ptr, &Slot::new(slot::SAMPLER, NONE, NONE, desc.cast(), 52)); + r.set_view( + at.ptr, + &Slot::new(slot::SAMPLER, NONE, NONE, desc.cast(), 52), + ); } } } @@ -1439,12 +1858,21 @@ unsafe extern "system" fn copy_descriptors( // SAFETY: as above; the arrays have as many entries as the counts say, // and null sizes mean one descriptor each. unsafe { - own!(this, ID3D12Device_Vtbl.CopyDescriptors)(this, n_to, to, to_sizes, n_from, from, from_sizes, kind); + own!(this, ID3D12Device_Vtbl.CopyDescriptors)( + this, n_to, to, to_sizes, n_from, from, from_sizes, kind, + ); let Some(r) = recorder().filter(|_| !ours()) else { return; }; - let step = own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, kind) as usize; - let size = |sizes: *const u32, i: u32| if sizes.is_null() { 1 } else { *sizes.add(i as usize) }; + let step = + own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, kind) as usize; + let size = |sizes: *const u32, i: u32| { + if sizes.is_null() { + 1 + } else { + *sizes.add(i as usize) + } + }; let (mut i, mut j, mut done_to, mut done_from) = (0, 0, 0, 0); while i < n_to && j < n_from { let n = (size(to_sizes, i) - done_to).min(size(from_sizes, j) - done_from); @@ -1528,26 +1956,64 @@ unsafe extern "system" fn list_reset(this: Ptr, allocator: Ptr, pso: Ptr) -> HRE { let mut inner = lock(&state.inner); inner.closed = None; - inner.whole = r.armed.load(Ordering::SeqCst) && state.kind == D3D12_COMMAND_LIST_TYPE_DIRECT.0; + inner.whole = + r.armed.load(Ordering::SeqCst) && state.kind == D3D12_COMMAND_LIST_TYPE_DIRECT.0; begin(&mut inner, r, pso); } hr } } -unsafe extern "system" fn draw(this: Ptr, vertices: u32, instances: u32, first: u32, first_instance: u32) { +unsafe extern "system" fn draw( + this: Ptr, + vertices: u32, + instances: u32, + first: u32, + first_instance: u32, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.DrawInstanced)(this, vertices, instances, first, first_instance); - note(this, |_| Cmd::Draw { vertices, instances, first, first_instance }); + own!(this, ID3D12GraphicsCommandList_Vtbl.DrawInstanced)( + this, + vertices, + instances, + first, + first_instance, + ); + note(this, |_| Cmd::Draw { + vertices, + instances, + first, + first_instance, + }); } } -unsafe extern "system" fn draw_indexed(this: Ptr, indices: u32, instances: u32, first: u32, base: i32, first_instance: u32) { +unsafe extern "system" fn draw_indexed( + this: Ptr, + indices: u32, + instances: u32, + first: u32, + base: i32, + first_instance: u32, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced)(this, indices, instances, first, base, first_instance); - note(this, |_| Cmd::DrawIndexed { indices, instances, first, base, first_instance }); + own!(this, ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced)( + this, + indices, + instances, + first, + base, + first_instance, + ); + note(this, |_| Cmd::DrawIndexed { + indices, + instances, + first, + base, + first_instance, + }); } } @@ -1567,11 +2033,26 @@ unsafe extern "system" fn dispatch_mesh(this: Ptr, x: u32, y: u32, z: u32) { } } -unsafe extern "system" fn copy_buffer(this: Ptr, dst: Ptr, dst_at: u64, src: Ptr, src_at: u64, len: u64) { +unsafe extern "system" fn copy_buffer( + this: Ptr, + dst: Ptr, + dst_at: u64, + src: Ptr, + src_at: u64, + len: u64, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion)(this, dst, dst_at, src, src_at, len); - note(this, |r| Cmd::CopyBuffer { dst: r.resource(dst), dst_at, src: r.resource(src), src_at, len }); + own!(this, ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion)( + this, dst, dst_at, src, src_at, len, + ); + note(this, |r| Cmd::CopyBuffer { + dst: r.resource(dst), + dst_at, + src: r.resource(src), + src_at, + len, + }); } } @@ -1580,11 +2061,20 @@ unsafe fn location(r: &Recorder, l: &D3D12_TEXTURE_COPY_LOCATION) -> Loc { unsafe { let res = r.resource(std::mem::transmute_copy::<_, Ptr>(&l.pResource)); if l.Type == D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX { - return Loc::Sub { res, sub: l.Anonymous.SubresourceIndex }; + return Loc::Sub { + res, + sub: l.Anonymous.SubresourceIndex, + }; } let p = l.Anonymous.PlacedFootprint; let f = p.Footprint; - Loc::Placed { res, offset: p.Offset, format: f.Format.0, size: [f.Width, f.Height, f.Depth], pitch: f.RowPitch } + Loc::Placed { + res, + offset: p.Offset, + format: f.Format.0, + size: [f.Width, f.Height, f.Depth], + pitch: f.RowPitch, + } } } @@ -1617,7 +2107,9 @@ unsafe extern "system" fn copy_texture( dst: location(r, &*dst), at: [x, y, z], src: location(r, &*src), - part: part.as_ref().map(|b| [b.left, b.top, b.front, b.right, b.bottom, b.back]), + part: part + .as_ref() + .map(|b| [b.left, b.top, b.front, b.right, b.bottom, b.back]), }); } } @@ -1626,15 +2118,33 @@ unsafe extern "system" fn copy_resource(this: Ptr, dst: Ptr, src: Ptr) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.CopyResource)(this, dst, src); - note_change(this, |r| Cmd::CopyResource { dst: r.resource(dst), src: r.resource(src) }); + note_change(this, |r| Cmd::CopyResource { + dst: r.resource(dst), + src: r.resource(src), + }); } } -unsafe extern "system" fn resolve(this: Ptr, dst: Ptr, dst_sub: u32, src: Ptr, src_sub: u32, format: DXGI_FORMAT) { +unsafe extern "system" fn resolve( + this: Ptr, + dst: Ptr, + dst_sub: u32, + src: Ptr, + src_sub: u32, + format: DXGI_FORMAT, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveSubresource)(this, dst, dst_sub, src, src_sub, format); - note(this, |r| Cmd::Resolve { dst: r.resource(dst), dst_sub, src: r.resource(src), src_sub, format: format.0 }); + own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveSubresource)( + this, dst, dst_sub, src, src_sub, format, + ); + note(this, |r| Cmd::Resolve { + dst: r.resource(dst), + dst_sub, + src: r.resource(src), + src_sub, + format: format.0, + }); } } @@ -1653,7 +2163,10 @@ unsafe extern "system" fn resolve_region( ) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion)(this, dst, dst_sub, x, y, src, src_sub, part, format, mode); + own!( + this, + ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion + )(this, dst, dst_sub, x, y, src, src_sub, part, format, mode); note(this, |r| Cmd::ResolveRegion { dst: r.resource(dst), dst_sub, @@ -1676,7 +2189,10 @@ unsafe fn rects(n: u32, all: *const RECT) -> Vec<[i32; 4]> { return Vec::new(); } // SAFETY: `n` rectangles. - unsafe { std::slice::from_raw_parts(all, n as usize) }.iter().map(rect).collect() + unsafe { std::slice::from_raw_parts(all, n as usize) } + .iter() + .map(rect) + .collect() } unsafe extern "system" fn topology(this: Ptr, kind: D3D_PRIMITIVE_TOPOLOGY) { @@ -1691,7 +2207,11 @@ unsafe extern "system" fn viewports(this: Ptr, n: u32, all: *const D3D12_VIEWPOR // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.RSSetViewports)(this, n, all); - note(this, |_| Cmd::Viewports { all: (0..n as usize).map(|i| all.add(i).cast::<[f32; 6]>().read()).collect() }); + note(this, |_| Cmd::Viewports { + all: (0..n as usize) + .map(|i| all.add(i).cast::<[f32; 6]>().read()) + .collect(), + }); } } @@ -1707,7 +2227,9 @@ unsafe extern "system" fn blend_factor(this: Ptr, factor: *const f32) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor)(this, factor); - note(this, |_| Cmd::BlendFactor { factor: factor.cast::<[f32; 4]>().as_ref().copied() }); + note(this, |_| Cmd::BlendFactor { + factor: factor.cast::<[f32; 4]>().as_ref().copied(), + }); } } @@ -1731,7 +2253,9 @@ unsafe extern "system" fn set_pipeline(this: Ptr, pso: Ptr) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.SetPipelineState)(this, pso); - note(this, |r| Cmd::Pipeline { pso: r.object(pso, "a pipeline") }); + note(this, |r| Cmd::Pipeline { + pso: r.object(pso, "a pipeline"), + }); } } @@ -1747,13 +2271,18 @@ unsafe extern "system" fn barrier(this: Ptr, n: u32, all: *const D3D12_RESOURCE_ let a = &b.Anonymous.Aliasing; Barrier::Alias { flags: b.Flags.0, - before: r.resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceBefore)), - after: r.resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceAfter)), + before: r + .resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceBefore)), + after: r + .resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceAfter)), } } - D3D12_RESOURCE_BARRIER_TYPE_UAV => { - Barrier::Uav { flags: b.Flags.0, res: r.resource(std::mem::transmute_copy::<_, Ptr>(&b.Anonymous.UAV.pResource)) } - } + D3D12_RESOURCE_BARRIER_TYPE_UAV => Barrier::Uav { + flags: b.Flags.0, + res: r.resource(std::mem::transmute_copy::<_, Ptr>( + &b.Anonymous.UAV.pResource, + )), + }, _ => { let t = &b.Anonymous.Transition; Barrier::Transition { @@ -1775,7 +2304,11 @@ unsafe extern "system" fn set_heaps(this: Ptr, n: u32, all: *const Ptr) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps)(this, n, all); - note(this, |r| Cmd::Heaps { heaps: (0..n as usize).map(|i| r.object(*all.add(i), "a descriptor heap")).collect() }); + note(this, |r| Cmd::Heaps { + heaps: (0..n as usize) + .map(|i| r.object(*all.add(i), "a descriptor heap")) + .collect(), + }); } } @@ -1783,15 +2316,24 @@ unsafe extern "system" fn root_compute(this: Ptr, root: Ptr) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature)(this, root); - note(this, |r| Cmd::RootSignature { graphics: false, root: r.object(root, "a root signature") }); + note(this, |r| Cmd::RootSignature { + graphics: false, + root: r.object(root, "a root signature"), + }); } } unsafe extern "system" fn root_graphics(this: Ptr, root: Ptr) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature)(this, root); - note(this, |r| Cmd::RootSignature { graphics: true, root: r.object(root, "a root signature") }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature + )(this, root); + note(this, |r| Cmd::RootSignature { + graphics: true, + root: r.object(root, "a root signature"), + }); } } @@ -1803,13 +2345,21 @@ fn table(r: &Recorder, graphics: bool, param: u32, at: u64) -> Cmd { if heap == NONE { r.problem("a descriptor table in no heap seen made"); } - Cmd::Table { graphics, param, heap, slot } + Cmd::Table { + graphics, + param, + heap, + slot, + } } unsafe extern "system" fn table_compute(this: Ptr, param: u32, at: D3D12_GPU_DESCRIPTOR_HANDLE) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable)(this, param, at); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable + )(this, param, at); note(this, |r| table(r, false, param, at.ptr)); } } @@ -1817,7 +2367,10 @@ unsafe extern "system" fn table_compute(this: Ptr, param: u32, at: D3D12_GPU_DES unsafe extern "system" fn table_graphics(this: Ptr, param: u32, at: D3D12_GPU_DESCRIPTOR_HANDLE) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable)(this, param, at); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable + )(this, param, at); note(this, |r| table(r, true, param, at.ptr)); } } @@ -1825,37 +2378,83 @@ unsafe extern "system" fn table_graphics(this: Ptr, param: u32, at: D3D12_GPU_DE unsafe extern "system" fn constant_compute(this: Ptr, param: u32, value: u32, offset: u32) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant)(this, param, value, offset); - note(this, |_| Cmd::Constants { graphics: false, param, offset, values: vec![value] }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant + )(this, param, value, offset); + note(this, |_| Cmd::Constants { + graphics: false, + param, + offset, + values: vec![value], + }); } } unsafe extern "system" fn constant_graphics(this: Ptr, param: u32, value: u32, offset: u32) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant)(this, param, value, offset); - note(this, |_| Cmd::Constants { graphics: true, param, offset, values: vec![value] }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant + )(this, param, value, offset); + note(this, |_| Cmd::Constants { + graphics: true, + param, + offset, + values: vec![value], + }); } } unsafe fn values(n: u32, data: *const c_void) -> Vec { // SAFETY: `n` values, of any alignment. - (0..n as usize).map(|i| unsafe { data.cast::().add(i).read_unaligned() }).collect() + (0..n as usize) + .map(|i| unsafe { data.cast::().add(i).read_unaligned() }) + .collect() } -unsafe extern "system" fn constants_compute(this: Ptr, param: u32, n: u32, data: *const c_void, offset: u32) { +unsafe extern "system" fn constants_compute( + this: Ptr, + param: u32, + n: u32, + data: *const c_void, + offset: u32, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants)(this, param, n, data, offset); - note(this, |_| Cmd::Constants { graphics: false, param, offset, values: values(n, data) }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants + )(this, param, n, data, offset); + note(this, |_| Cmd::Constants { + graphics: false, + param, + offset, + values: values(n, data), + }); } } -unsafe extern "system" fn constants_graphics(this: Ptr, param: u32, n: u32, data: *const c_void, offset: u32) { +unsafe extern "system" fn constants_graphics( + this: Ptr, + param: u32, + n: u32, + data: *const c_void, + offset: u32, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants)(this, param, n, data, offset); - note(this, |_| Cmd::Constants { graphics: true, param, offset, values: values(n, data) }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants + )(this, param, n, data, offset); + note(this, |_| Cmd::Constants { + graphics: true, + param, + offset, + values: values(n, data), + }); } } @@ -1892,11 +2491,20 @@ unsafe extern "system" fn index_buffer(this: Ptr, view: *const D3D12_INDEX_BUFFE // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer)(this, view); - note(this, |r| Cmd::IndexBuffer { view: view.as_ref().map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.Format.0)) }); + note(this, |r| Cmd::IndexBuffer { + view: view + .as_ref() + .map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.Format.0)), + }); } } -unsafe extern "system" fn vertex_buffers(this: Ptr, start: u32, n: u32, views: *const D3D12_VERTEX_BUFFER_VIEW) { +unsafe extern "system" fn vertex_buffers( + this: Ptr, + start: u32, + n: u32, + views: *const D3D12_VERTEX_BUFFER_VIEW, +) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers)(this, start, n, views); @@ -1905,7 +2513,9 @@ unsafe extern "system" fn vertex_buffers(this: Ptr, start: u32, n: u32, views: * count: n, views: (!views.is_null()).then(|| { let all = std::slice::from_raw_parts(views, n as usize); - all.iter().map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.StrideInBytes)).collect() + all.iter() + .map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.StrideInBytes)) + .collect() }), }); } @@ -1920,7 +2530,9 @@ unsafe extern "system" fn targets( ) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets)(this, n, colors, range, depth); + own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets)( + this, n, colors, range, depth, + ); note(this, |r| { let colors = (0..n as usize) .map(|i| { @@ -1928,10 +2540,14 @@ unsafe extern "system" fn targets( return r.view((*colors.add(i)).ptr); } let all = read(&r.descriptors); - all.cpu((*colors).ptr).map_or(Slot::EMPTY, |(h, first)| h.get(first + i as u32)) + all.cpu((*colors).ptr) + .map_or(Slot::EMPTY, |(h, first)| h.get(first + i as u32)) }) .collect(); - Cmd::Targets { colors, depth: depth.as_ref().map(|d| r.view(d.ptr)) } + Cmd::Targets { + colors, + depth: depth.as_ref().map(|d| r.view(d.ptr)), + } }); } } @@ -1948,16 +2564,34 @@ unsafe extern "system" fn clear_depth( ) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView)(this, view, flags, depth, stencil, n, all); - note(this, |r| Cmd::ClearDepth { view: r.view(view.ptr), flags: flags.0, depth, stencil, rects: rects(n, all) }); + own!(this, ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView)( + this, view, flags, depth, stencil, n, all, + ); + note(this, |r| Cmd::ClearDepth { + view: r.view(view.ptr), + flags: flags.0, + depth, + stencil, + rects: rects(n, all), + }); } } -unsafe extern "system" fn clear_target(this: Ptr, view: D3D12_CPU_DESCRIPTOR_HANDLE, color: *const f32, n: u32, all: *const RECT) { +unsafe extern "system" fn clear_target( + this: Ptr, + view: D3D12_CPU_DESCRIPTOR_HANDLE, + color: *const f32, + n: u32, + all: *const RECT, +) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView)(this, view, color, n, all); - note(this, |r| Cmd::ClearTarget { view: r.view(view.ptr), color: color.cast::<[f32; 4]>().read(), rects: rects(n, all) }); + note(this, |r| Cmd::ClearTarget { + view: r.view(view.ptr), + color: color.cast::<[f32; 4]>().read(), + rects: rects(n, all), + }); } } @@ -1967,8 +2601,12 @@ unsafe extern "system" fn discard(this: Ptr, res: Ptr, region: *const D3D12_DISC own!(this, ID3D12GraphicsCommandList_Vtbl.DiscardResource)(this, res, region); note(this, |r| Cmd::Discard { res: r.resource(res), - rects: region.as_ref().map_or(Vec::new(), |d| rects(d.NumRects, d.pRects)), - subs: region.as_ref().map(|d| [d.FirstSubresource, d.NumSubresources]), + rects: region + .as_ref() + .map_or(Vec::new(), |d| rects(d.NumRects, d.pRects)), + subs: region + .as_ref() + .map(|d| [d.FirstSubresource, d.NumSubresources]), }); } } @@ -1977,7 +2615,11 @@ unsafe extern "system" fn begin_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TY // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.BeginQuery)(this, heap, kind, index); - note(this, |r| Cmd::BeginQuery { heap: r.object(heap, "a query heap"), kind: kind.0, index }); + note(this, |r| Cmd::BeginQuery { + heap: r.object(heap, "a query heap"), + kind: kind.0, + index, + }); } } @@ -1985,22 +2627,53 @@ unsafe extern "system" fn end_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TYPE // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.EndQuery)(this, heap, kind, index); - note(this, |r| Cmd::EndQuery { heap: r.object(heap, "a query heap"), kind: kind.0, index }); + note(this, |r| Cmd::EndQuery { + heap: r.object(heap, "a query heap"), + kind: kind.0, + index, + }); } } -unsafe extern "system" fn resolve_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TYPE, first: u32, count: u32, dst: Ptr, at: u64) { +unsafe extern "system" fn resolve_query( + this: Ptr, + heap: Ptr, + kind: D3D12_QUERY_TYPE, + first: u32, + count: u32, + dst: Ptr, + at: u64, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveQueryData)(this, heap, kind, first, count, dst, at); - note(this, |r| Cmd::ResolveQuery { heap: r.object(heap, "a query heap"), kind: kind.0, first, count, dst: r.resource(dst), at }); + own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveQueryData)( + this, heap, kind, first, count, dst, at, + ); + note(this, |r| Cmd::ResolveQuery { + heap: r.object(heap, "a query heap"), + kind: kind.0, + first, + count, + dst: r.resource(dst), + at, + }); } } -unsafe extern "system" fn indirect(this: Ptr, signature: Ptr, most: u32, args: Ptr, at: u64, count: Ptr, count_at: u64) { +unsafe extern "system" fn indirect( + this: Ptr, + signature: Ptr, + most: u32, + args: Ptr, + at: u64, + count: Ptr, + count_at: u64, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect)(this, signature, most, args, at, count, count_at); + own!(this, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect)( + this, signature, most, args, at, count, count_at, + ); note(this, |r| Cmd::Indirect { signature: r.object(signature, "a command signature"), most, @@ -2025,7 +2698,11 @@ unsafe extern "system" fn write_immediate( all: (0..n as usize) .map(|i| { let p = all.add(i).read(); - let mode = if modes.is_null() { 0 } else { modes.add(i).read().0 }; + let mode = if modes.is_null() { + 0 + } else { + modes.add(i).read().0 + }; (address(r, p.Dest), p.Value, mode) }) .collect(), @@ -2075,7 +2752,11 @@ mod tests { all.remove(2); assert_eq!(at(&all, 0x2000), None); let h = heap(4, 0, 0, 2); - let s = Slot { kind: slot::SRV, res: 5, ..Slot::EMPTY }; + let s = Slot { + kind: slot::SRV, + res: 5, + ..Slot::EMPTY + }; h.set(1, &s); h.set(2, &s); assert_eq!(h.all(), [Slot::EMPTY, s]); diff --git a/crates/victory-gpu/src/replay/snap.rs b/crates/victory-gpu/src/replay/snap.rs index 02b8a4f..d9832d2 100644 --- a/crates/victory-gpu/src/replay/snap.rs +++ b/crates/victory-gpu/src/replay/snap.rs @@ -15,7 +15,9 @@ use windows::core::Interface; use super::gpu::{self, Seen, Worker}; use super::record::{At, Heap, Ours, Recorder, Res, lock, not_recorded_calls, read}; use super::states::{COMMON, COPY_SOURCE, Change, States}; -use super::wire::{self, ALL, Cmd, Content, Delta, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot}; +use super::wire::{ + self, ALL, Cmd, Content, Delta, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot, +}; type Fault = Box; @@ -29,7 +31,7 @@ const PAGE: usize = 4096; /// What one thread compares at a time. const CHUNK: usize = 1 << 20; /// Frames waited, at the most, for one whose lists are all recorded. -const PATIENCE: u64 = 300; +const PATIENCE: u64 = 100; #[derive(Default)] enum Stage { @@ -61,19 +63,38 @@ impl Phase { /// A submission to a queue other than the drawing one: left out. pub(super) fn other_queue(r: &Recorder, lists: u32) { if r.watching.load(Ordering::SeqCst) { - r.problem_times("lists sent to a queue other than the drawing one are not in the capture", u64::from(lists)); + r.problem_times( + "lists sent to a queue other than the drawing one are not in the capture", + u64::from(lists), + ); } } /// A submission to the drawing queue, made by `go`. -pub(super) fn submit(r: &Recorder, queue: &ID3D12CommandQueue, lists: &[*mut std::ffi::c_void], go: impl FnOnce()) { +pub(super) fn submit( + r: &Recorder, + queue: &ID3D12CommandQueue, + lists: &[*mut std::ffi::c_void], + go: impl FnOnce(), +) { let mut phase = lock(&r.submits); type Closed = (Option>>, Arc>); - let closed: Vec> = lists.iter().map(|&p| r.list(p).and_then(|l| l.closed())).collect(); + let closed: Vec> = lists + .iter() + .map(|&p| r.list(p).and_then(|l| l.closed())) + .collect(); phase.submits += 1; - phase.missing += closed.iter().filter(|c| c.as_ref().is_none_or(|c| c.0.is_none())).count() as u32; + let whole = |c: &Option| c.as_ref().is_some_and(|c| c.0.is_some()); + phase.missing += lists + .iter() + .zip(&closed) + .filter(|(p, c)| !whole(c) && r.knows(**p)) + .count() as u32; if let Stage::Capturing(c) = &mut phase.stage { - let commands: Vec>>> = closed.iter().map(|c| c.as_ref().and_then(|c| c.0.clone())).collect(); + let commands: Vec>>> = closed + .iter() + .map(|c| c.as_ref().and_then(|c| c.0.clone())) + .collect(); let _ours = Ours::new(); if let Err(e) = c.submit(r, queue, &commands) { stop(r, &mut phase, &*e); @@ -102,7 +123,10 @@ pub(super) fn present(r: &Recorder, texture: &ID3D12Resource, state: u32) { let mut phase = lock(&r.submits); phase.presents += 1; let presents = phase.presents; - let (submits, missing) = (std::mem::take(&mut phase.submits), std::mem::take(&mut phase.missing)); + let (submits, missing) = ( + std::mem::take(&mut phase.submits), + std::mem::take(&mut phase.missing), + ); let mut finished = None; match &mut phase.stage { Stage::Waiting => { @@ -124,7 +148,11 @@ pub(super) fn present(r: &Recorder, texture: &ID3D12Resource, state: u32) { if !whole { r.problem("no frame was found whose lists were all recorded"); } - tracing::info!(presents, waited, "frame recorder: the next frame is captured"); + tracing::info!( + presents, + waited, + "frame recorder: the next frame is captured" + ); match Capture::new(r) { Ok(c) => phase.stage = Stage::Capturing(Box::new(c)), Err(e) => stop(r, &mut phase, &*e), @@ -178,16 +206,36 @@ impl Reads { }; for c in cmds { match c { - Cmd::RootView { va, .. } | Cmd::IndexBuffer { view: Some((va, _, _)) } => whole(va), - Cmd::VertexBuffers { views: Some(views), .. } => views.iter().for_each(|(va, _, _)| whole(va)), + Cmd::RootView { va, .. } + | Cmd::IndexBuffer { + view: Some((va, _, _)), + } => whole(va), + Cmd::VertexBuffers { + views: Some(views), .. + } => views.iter().for_each(|(va, _, _)| whole(va)), Cmd::Indirect { args, count, .. } => { for res in [*args, *count] { whole(&Va::At { res, offset: 0 }); } } - Cmd::CopyResource { src, .. } => whole(&Va::At { res: *src, offset: 0 }), - Cmd::CopyBuffer { src, src_at, len, .. } => parts.entry(*src).or_default().push((*src_at, src_at + len)), - Cmd::CopyTexture { src: Loc::Placed { res, offset, size, pitch, .. }, .. } => { + Cmd::CopyResource { src, .. } => whole(&Va::At { + res: *src, + offset: 0, + }), + Cmd::CopyBuffer { + src, src_at, len, .. + } => parts.entry(*src).or_default().push((*src_at, src_at + len)), + Cmd::CopyTexture { + src: + Loc::Placed { + res, + offset, + size, + pitch, + .. + }, + .. + } => { // At the most: compressed formats have fewer rows. let len = u64::from(*pitch) * u64::from(size[1]) * u64::from(size[2].max(1)); parts.entry(*res).or_default().push((*offset, offset + len)); @@ -208,7 +256,12 @@ impl Reads { }; let mut pages: Vec<(usize, usize)> = parts .iter() - .map(|&(from, to)| (from as usize / PAGE * PAGE, (to as usize).next_multiple_of(PAGE).min(size))) + .map(|&(from, to)| { + ( + from as usize / PAGE * PAGE, + (to as usize).next_multiple_of(PAGE).min(size), + ) + }) .filter(|(from, to)| from < to) .collect(); pages.sort_unstable(); @@ -277,7 +330,10 @@ impl Capture { let _ours = Ours::new(); let device = r.device().ok_or("no device")?; let queues = lock(&r.queues).clone(); - let direct = queues.iter().find(|q| q.1 == D3D12_COMMAND_LIST_TYPE_DIRECT.0).ok_or("no drawing queue")?; + let direct = queues + .iter() + .find(|q| q.1 == D3D12_COMMAND_LIST_TYPE_DIRECT.0) + .ok_or("no drawing queue")?; let mut others = Vec::new(); for (queue, _) in queues.iter().filter(|q| q.0 != direct.0) { others.push(Worker::new(&device, queue)?); @@ -309,7 +365,11 @@ impl Capture { }) } - fn timed(&mut self, what: &'static str, f: impl FnOnce(&mut Self) -> Result) -> Result { + fn timed( + &mut self, + what: &'static str, + f: impl FnOnce(&mut Self) -> Result, + ) -> Result { let began = Instant::now(); let out = f(self); *self.took.entry(what).or_default() += began.elapsed(); @@ -332,14 +392,22 @@ impl Capture { let object = res.object(); // SAFETY: a live resource, or one whose end waits for the // lock held here (`Recorder::gone`): the count tells which. - let count = unsafe { (Interface::vtable(&*object).base__.base__.base__.base__.AddRef)(object.as_raw()) }; + let count = unsafe { + (Interface::vtable(&*object) + .base__ + .base__ + .base__ + .base__ + .AddRef)(object.as_raw()) + }; if count <= 1 { // Dying: the reference does not bring it back, and // giving it back would end it a second time. continue; } // SAFETY: the reference just taken. - self.held.push(unsafe { ID3D12Resource::from_raw(object.as_raw()) }); + self.held + .push(unsafe { ID3D12Resource::from_raw(object.as_raw()) }); all.push(res.clone()); } } @@ -357,10 +425,21 @@ impl Capture { for res in all { if let Place::Placed { heap, offset } = res.place { // SAFETY: a plain query. - let info = unsafe { self.worker.device.GetResourceAllocationInfo(0, &[gpu::to_desc(&res.desc)]) }; - let size = if info.SizeInBytes == u64::MAX { res.desc.width } else { info.SizeInBytes }; + let info = unsafe { + self.worker + .device + .GetResourceAllocationInfo(0, &[gpu::to_desc(&res.desc)]) + }; + let size = if info.SizeInBytes == u64::MAX { + res.desc.width + } else { + info.SizeInBytes + }; let used = self.states.used.get(&res.id).copied().unwrap_or(0); - heaps.entry(heap).or_default().push((used, offset, offset + size, res.id)); + heaps + .entry(heap) + .or_default() + .push((used, offset, offset + size, res.id)); } } let mut idle = HashSet::new(); @@ -368,7 +447,10 @@ impl Capture { list.sort_by(|a, b| b.cmp(a)); let mut taken: BTreeMap = BTreeMap::new(); for (_, from, to, id) in list { - let overlaps = taken.range(..to).next_back().is_some_and(|(_, &end)| end > from); + let overlaps = taken + .range(..to) + .next_back() + .is_some_and(|(_, &end)| end > from); if overlaps { idle.insert(id); } else { @@ -390,7 +472,13 @@ impl Capture { let mut at = 0; while at < res.desc.width { let len = PIECE.min(res.desc.width - at); - pieces.push(Piece { res: res.clone(), first: at, count: 1, len, at: 0 }); + pieces.push(Piece { + res: res.clone(), + first: at, + count: 1, + len, + at: 0, + }); at += len; } continue; @@ -404,14 +492,28 @@ impl Capture { if total == u64::MAX { r.problem("contents of a texture without a copyable layout are not in the capture"); } else if total <= STAGING { - pieces.push(Piece { res: res.clone(), first: 0, count: res.subs, len: total, at: 0 }); + pieces.push(Piece { + res: res.clone(), + first: 0, + count: res.subs, + len: total, + at: 0, + }); } else { for sub in 0..res.subs { let (_, len) = gpu::footprints(&device, &desc, sub, 1); if len <= STAGING { - pieces.push(Piece { res: res.clone(), first: u64::from(sub), count: 1, len, at: 0 }); + pieces.push(Piece { + res: res.clone(), + first: u64::from(sub), + count: 1, + len, + at: 0, + }); } else { - r.problem("contents of a texture level of over 256 MB are not in the capture"); + r.problem( + "contents of a texture level of over 256 MB are not in the capture", + ); } } } @@ -433,7 +535,12 @@ impl Capture { } let mut stagings = Vec::new(); for _ in 0..STAGINGS.min(batches.len()) { - stagings.push(gpu::buffer(&device, D3D12_HEAP_TYPE_READBACK, STAGING, D3D12_RESOURCE_FLAG_NONE)?); + stagings.push(gpu::buffer( + &device, + D3D12_HEAP_TYPE_READBACK, + STAGING, + D3D12_RESOURCE_FLAG_NONE, + )?); } let file = File::create(r.folder.join("contents.bin"))?; let end = AtomicU64::new(0); @@ -448,7 +555,8 @@ impl Capture { let maps: Vec = stagings.iter().map(|s| s.1 as usize).collect(); std::thread::scope(|scope| -> Result<(), Fault> { for _ in 0..stagings.len() { - let (work, free, maps, file, end, contents, failed) = (&work, free.clone(), &maps, &file, &end, &contents, &failed); + let (work, free, maps, file, end, contents, failed) = + (&work, free.clone(), &maps, &file, &end, &contents, &failed); scope.spawn(move || { loop { let next = lock(work).recv(); @@ -456,14 +564,29 @@ impl Capture { for p in pieces { // SAFETY: inside the buffer's mapping; the copy // into it has run. - let bytes = unsafe { std::slice::from_raw_parts((maps[i] + p.at as usize) as *const u8, p.len as usize) }; - let at = if zero(bytes) { ZERO } else { end.fetch_add(p.len, Ordering::Relaxed) }; + let bytes = unsafe { + std::slice::from_raw_parts( + (maps[i] + p.at as usize) as *const u8, + p.len as usize, + ) + }; + let at = if zero(bytes) { + ZERO + } else { + end.fetch_add(p.len, Ordering::Relaxed) + }; if at != ZERO && let Err(e) = write_at(file, bytes, at) { lock(failed).get_or_insert(e); } - lock(contents).push(Content { res: p.res.id, first: p.first, count: p.count, len: p.len, file: at }); + lock(contents).push(Content { + res: p.res.id, + first: p.first, + count: p.count, + len: p.len, + file: at, + }); } let _ = free.send(i); } @@ -476,7 +599,9 @@ impl Capture { continue; } let i = freed.recv()?; - let value = self.worker.send(|list| copy_out(&device, list, &self.states, &pieces, &stagings[i].0))?; + let value = self + .worker + .send(|list| copy_out(&device, list, &self.states, &pieces, &stagings[i].0))?; self.worker.wait(value)?; todo.send((i, pieces))?; } @@ -493,7 +618,9 @@ impl Capture { fn new_buffers(&mut self, r: &Recorder) -> Result<(), Fault> { let fresh: Vec> = read(&r.resources) .values() - .filter(|res| matches!(res.seen, Seen::Cached | Seen::Combined) && !self.known.contains(&res.id)) + .filter(|res| { + matches!(res.seen, Seen::Cached | Seen::Combined) && !self.known.contains(&res.id) + }) .cloned() .collect(); for res in fresh { @@ -516,7 +643,12 @@ impl Capture { Some(i) => i, None => { let len = STAGING.max(size as u64); - let (b, data) = gpu::buffer(&self.worker.device, D3D12_HEAP_TYPE_READBACK, len, D3D12_RESOURCE_FLAG_NONE)?; + let (b, data) = gpu::buffer( + &self.worker.device, + D3D12_HEAP_TYPE_READBACK, + len, + D3D12_RESOURCE_FLAG_NONE, + )?; self.blocks.push((b, data as usize, len, 0)); self.blocks.len() - 1 } @@ -526,7 +658,14 @@ impl Capture { b.3 = (at + size as u64).next_multiple_of(256); ((b.1 + at as usize) as *const u8, Some((i, at))) }; - self.buffers.push(CpuBuffer { id: res.id, res: object, live, through, size, kept: vec![0; size] }); + self.buffers.push(CpuBuffer { + id: res.id, + res: object, + live, + through, + size, + kept: vec![0; size], + }); } Ok(()) } @@ -540,7 +679,12 @@ impl Capture { .buffers .iter() .enumerate() - .flat_map(|(i, b)| reads.pages(b.id, b.size, self.viewed.contains(&b.id)).into_iter().map(move |(from, to)| (i, from, to))) + .flat_map(|(i, b)| { + reads + .pages(b.id, b.size, self.viewed.contains(&b.id)) + .into_iter() + .map(move |(from, to)| (i, from, to)) + }) .collect(); if parts.iter().any(|p| self.buffers[p.0].through.is_some()) { let (buffers, blocks) = (&self.buffers, &self.blocks); @@ -549,24 +693,43 @@ impl Capture { let b = &buffers[i]; if let Some((block, at)) = b.through { // SAFETY: an open list and live buffers. - unsafe { list.CopyBufferRegion(&blocks[block].0, at + from as u64, &b.res, from as u64, (to - from) as u64) }; + unsafe { + list.CopyBufferRegion( + &blocks[block].0, + at + from as u64, + &b.res, + from as u64, + (to - from) as u64, + ) + }; } } })?; } let chunks: Vec<(usize, usize, usize)> = parts .iter() - .flat_map(|&(i, from, to)| (from..to).step_by(CHUNK).map(move |at| (i, at, CHUNK.min(to - at)))) + .flat_map(|&(i, from, to)| { + (from..to) + .step_by(CHUNK) + .map(move |at| (i, at, CHUNK.min(to - at))) + }) .collect(); // Each chunk is one thread's; threads share what is kept by parts. struct Kept(*mut u8); // SAFETY: parts of it are used by one thread each. unsafe impl Sync for Kept {} - let kept: Vec = self.buffers.iter_mut().map(|b| Kept(b.kept.as_mut_ptr())).collect(); + let kept: Vec = self + .buffers + .iter_mut() + .map(|b| Kept(b.kept.as_mut_ptr())) + .collect(); let next = AtomicUsize::new(0); let out: std::sync::Mutex> = std::sync::Mutex::default(); let failed: std::sync::Mutex> = std::sync::Mutex::default(); - let threads = std::thread::available_parallelism().map_or(4, |n| n.get() / 2).clamp(1, 16).min(chunks.len().max(1)); + let threads = std::thread::available_parallelism() + .map_or(4, |n| n.get() / 2) + .clamp(1, 16) + .min(chunks.len().max(1)); let (buffers, file, end) = (&self.buffers, &self.deltas, &self.delta_at); std::thread::scope(|scope| { for _ in 0..threads { @@ -574,19 +737,30 @@ impl Capture { let mut mine = Vec::new(); loop { let i = next.fetch_add(1, Ordering::Relaxed); - let Some(&(b, at, len)) = chunks.get(i) else { break }; + let Some(&(b, at, len)) = chunks.get(i) else { + break; + }; // SAFETY: a chunk of the buffer's memory (it may // change meanwhile: what is kept is what was read) // and of what is kept, which no other thread has. - let runs = unsafe { changed_runs(buffers[b].live.add(at), kept[b].0.add(at), len) }; + let runs = unsafe { + changed_runs(buffers[b].live.add(at), kept[b].0.add(at), len) + }; for (from, to) in runs { // SAFETY: as above. - let bytes = unsafe { std::slice::from_raw_parts(kept[b].0.add(at + from), to - from) }; + let bytes = unsafe { + std::slice::from_raw_parts(kept[b].0.add(at + from), to - from) + }; let file_at = end.fetch_add(bytes.len() as u64, Ordering::Relaxed); if let Err(e) = write_at(file, bytes, file_at) { lock(&failed).get_or_insert(e); } - mine.push(Delta { res: buffers[b].id, at: (at + from) as u64, len: bytes.len() as u64, file: file_at }); + mine.push(Delta { + res: buffers[b].id, + at: (at + from) as u64, + len: bytes.len() as u64, + file: file_at, + }); } } lock(&out).extend(mine); @@ -601,7 +775,12 @@ impl Capture { Ok(out) } - fn submit(&mut self, r: &Recorder, _queue: &ID3D12CommandQueue, lists: &[Option>>]) -> Result<(), Fault> { + fn submit( + &mut self, + r: &Recorder, + _queue: &ID3D12CommandQueue, + lists: &[Option>>], + ) -> Result<(), Fault> { let first = !self.started; if first { self.start(r)?; @@ -615,7 +794,8 @@ impl Capture { let heaps: Vec> = read(&r.descriptors).visible().cloned().collect(); for h in heaps { let runs = runs_of(r, &h.all()); - self.viewed.extend(runs.iter().flat_map(|(_, _, s)| [s.res, s.counter])); + self.viewed + .extend(runs.iter().flat_map(|(_, _, s)| [s.res, s.counter])); self.heaps.push((h, runs)); } } else { @@ -625,7 +805,10 @@ impl Capture { let h = match self.heaps.iter().find(|(h, _)| h.id == heap) { Some((h, _)) => h.clone(), None => { - let found = read(&r.descriptors).visible().find(|h| h.id == heap).cloned(); + let found = read(&r.descriptors) + .visible() + .find(|h| h.id == heap) + .cloned(); let Some(h) = found else { continue }; self.heaps.push((h.clone(), Vec::new())); h @@ -649,10 +832,16 @@ impl Capture { for l in lists { numbers.push(match l { None => { - r.problem("a list was submitted that was not recorded whole: its work is missing"); + r.problem( + "a list was submitted that was not recorded whole: its work is missing", + ); MISSING } - Some(commands) => match self.lists.iter().position(|have| Arc::ptr_eq(have, commands)) { + Some(commands) => match self + .lists + .iter() + .position(|have| Arc::ptr_eq(have, commands)) + { Some(i) => i as u32, None => { self.lists.push(commands.clone()); @@ -661,7 +850,12 @@ impl Capture { }, }); } - self.submits.push(wire::Submit { frame: self.frame, lists: numbers, deltas, views }); + self.submits.push(wire::Submit { + frame: self.frame, + lists: numbers, + deltas, + views, + }); Ok(()) } @@ -670,8 +864,14 @@ impl Capture { // SAFETY: a live texture. let desc = unsafe { texture.GetDesc() }; let (f, total) = gpu::footprints(&self.worker.device, &desc, 0, 1); - let (back, data) = gpu::buffer(&self.worker.device, D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_FLAG_NONE)?; - self.worker.run(|list| read_sub(list, texture, 0, state, &back, f[0]))?; + let (back, data) = gpu::buffer( + &self.worker.device, + D3D12_HEAP_TYPE_READBACK, + total, + D3D12_RESOURCE_FLAG_NONE, + )?; + self.worker + .run(|list| read_sub(list, texture, 0, state, &back, f[0]))?; // SAFETY: the buffer's mapping; the copy into it has run. let bytes = unsafe { std::slice::from_raw_parts(data, total as usize) }; write_at(&self.present_file, bytes, self.present_at)?; @@ -688,7 +888,10 @@ impl Capture { }); self.present_at += total; match gpu::rgb(width, height, pitch, desc.Format.0, bytes) { - Some(rgb) => std::fs::write(r.folder.join(format!("frame-{}.png", self.frame)), crate::capture::png(width, height, &rgb))?, + Some(rgb) => std::fs::write( + r.folder.join(format!("frame-{}.png", self.frame)), + crate::capture::png(width, height, &rgb), + )?, None => r.problem("the presented format is not shown in a PNG"), } self.frame += 1; @@ -722,20 +925,35 @@ impl Capture { resources.sort_by_key(|res| res.id); let mut heaps: Vec = { let all = lock(&r.heaps); - let used: HashSet = - resources.iter().filter_map(|res| if let Place::Placed { heap, .. } = res.place { Some(heap) } else { None }).collect(); + let used: HashSet = resources + .iter() + .filter_map(|res| { + if let Place::Placed { heap, .. } = res.place { + Some(heap) + } else { + None + } + }) + .collect(); used.iter().filter_map(|id| all.get(id).cloned()).collect() }; heaps.sort_by_key(|h| h.id); // What the lists name. - let (mut psos, mut roots, mut signatures, mut queries) = (HashSet::new(), HashSet::new(), HashSet::new(), HashSet::new()); + let (mut psos, mut roots, mut signatures, mut queries) = ( + HashSet::new(), + HashSet::new(), + HashSet::new(), + HashSet::new(), + ); for l in &self.lists { for c in Cmd::all(l)? { match c { - Cmd::Pipeline { pso } => drop(psos.insert(pso)), - Cmd::RootSignature { root, .. } => drop(roots.insert(root)), - Cmd::Indirect { signature, .. } => drop(signatures.insert(signature)), - Cmd::BeginQuery { heap, .. } | Cmd::EndQuery { heap, .. } | Cmd::ResolveQuery { heap, .. } => drop(queries.insert(heap)), + Cmd::Pipeline { pso } => _ = psos.insert(pso), + Cmd::RootSignature { root, .. } => _ = roots.insert(root), + Cmd::Indirect { signature, .. } => _ = signatures.insert(signature), + Cmd::BeginQuery { heap, .. } + | Cmd::EndQuery { heap, .. } + | Cmd::ResolveQuery { heap, .. } => _ = queries.insert(heap), _ => {} } } @@ -747,22 +965,38 @@ impl Capture { .iter() .filter_map(|id| { let parts = all.get(id)?; - Some(wire::Pipeline { id: *id, parts: parts.to_vec(), name: names.get(id).cloned().unwrap_or_default() }) + Some(wire::Pipeline { + id: *id, + parts: parts.to_vec(), + name: names.get(id).cloned().unwrap_or_default(), + }) }) .collect(); out.sort_by_key(|p| p.id); out }; - roots.extend(pipelines.iter().flat_map(|p| &p.parts).filter_map(|p| if let wire::Part::Root { root } = p { Some(*root) } else { None })); + roots.extend(pipelines.iter().flat_map(|p| &p.parts).filter_map(|p| { + if let wire::Part::Root { root } = p { + Some(*root) + } else { + None + } + })); let signatures: Vec = { let all = lock(&r.signatures); - signatures.iter().filter_map(|id| all.get(id).cloned()).collect() + signatures + .iter() + .filter_map(|id| all.get(id).cloned()) + .collect() }; roots.extend(signatures.iter().map(|s| s.root)); roots.remove(&NONE); let roots: Vec<(u32, wire::Blob)> = { let all = lock(&r.roots); - roots.iter().filter_map(|id| Some((*id, wire::Blob(all.get(id)?.to_vec())))).collect() + roots + .iter() + .filter_map(|id| Some((*id, wire::Blob(all.get(id)?.to_vec())))) + .collect() }; for ((what, before), (_, now)) in self.calls.iter().zip(not_recorded_calls()) { if now > *before { @@ -771,7 +1005,12 @@ impl Capture { } let (adapter, vendor, device) = gpu::adapter(&self.worker.device); let mut notes = r.problems(); - let bytes: u64 = self.contents.iter().filter(|c| c.file != ZERO).map(|c| c.len).sum(); + let bytes: u64 = self + .contents + .iter() + .filter(|c| c.file != ZERO) + .map(|c| c.len) + .sum(); notes.push(format!( "{} submissions, {} lists, {} resources, {} pipelines; {} MB of the card's memory, {} MB of changes by the CPU; {:.1} s: {}", self.submits.len(), @@ -800,16 +1039,28 @@ impl Capture { descriptor_heaps: self .heaps .iter() - .map(|(h, runs)| wire::DescriptorHeap { id: h.id, kind: h.kind, count: h.count, flags: h.flags, runs: runs.clone() }) + .map(|(h, runs)| wire::DescriptorHeap { + id: h.id, + kind: h.kind, + count: h.count, + flags: h.flags, + runs: runs.clone(), + }) .collect(), query_heaps: { let all = lock(&r.queries); - queries.iter().filter_map(|id| all.get(id).cloned()).collect() + queries + .iter() + .filter_map(|id| all.get(id).cloned()) + .collect() }, lists: self .lists .iter() - .map(|l| wire::List { kind: D3D12_COMMAND_LIST_TYPE_DIRECT.0, commands: wire::Blob(l.to_vec()) }) + .map(|l| wire::List { + kind: D3D12_COMMAND_LIST_TYPE_DIRECT.0, + commands: wire::Blob(l.to_vec()), + }) .collect(), submits: std::mem::take(&mut self.submits), contents: std::mem::take(&mut self.contents), @@ -833,7 +1084,13 @@ struct Piece { /// Records the copies of `pieces` into `to`. Textures are moved to a state /// they can be copied from and back. -fn copy_out(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, states: &States, pieces: &[Piece], to: &ID3D12Resource) { +fn copy_out( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + states: &States, + pieces: &[Piece], + to: &ID3D12Resource, +) { let (mut before, mut after) = (Vec::new(), Vec::new()); let mut seen = HashSet::new(); for p in pieces.iter().filter(|p| !p.res.is_buffer()) { @@ -842,7 +1099,16 @@ fn copy_out(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, states: &St } let from = states.get(p.res.id).unwrap_or(vec![COMMON]); // From the common state a texture is promoted by the copy. - let to: Vec = from.iter().map(|&s| if s == COMMON || s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect(); + let to: Vec = from + .iter() + .map(|&s| { + if s == COMMON || s & COPY_SOURCE != 0 { + s + } else { + COPY_SOURCE + } + }) + .collect(); gpu::moves(&p.res.object(), &from, &to, &mut before); gpu::moves(&p.res.object(), &to, &from, &mut after); } @@ -857,10 +1123,18 @@ fn copy_out(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, states: &St list.CopyBufferRegion(to, p.at, &*object, p.first, p.len); continue; } - let (all, _) = gpu::footprints(device, &gpu::to_desc(&p.res.desc), p.first as u32, p.count); + let (all, _) = + gpu::footprints(device, &gpu::to_desc(&p.res.desc), p.first as u32, p.count); for (i, mut f) in all.into_iter().enumerate() { f.Offset += p.at; - list.CopyTextureRegion(&gpu::placed_location(to, f), 0, 0, 0, &gpu::sub_location(&object, p.first as u32 + i as u32), None); + list.CopyTextureRegion( + &gpu::placed_location(to, f), + 0, + 0, + 0, + &gpu::sub_location(&object, p.first as u32 + i as u32), + None, + ); } } if !after.is_empty() { @@ -884,7 +1158,14 @@ pub(super) fn read_sub( if !there { list.ResourceBarrier(&[gpu::transition(texture, ALL, state, COPY_SOURCE)]); } - list.CopyTextureRegion(&gpu::placed_location(to, f), 0, 0, 0, &gpu::sub_location(texture, sub), None); + list.CopyTextureRegion( + &gpu::placed_location(to, f), + 0, + 0, + 0, + &gpu::sub_location(texture, sub), + None, + ); if !there { list.ResourceBarrier(&[gpu::transition(texture, ALL, COPY_SOURCE, state)]); } @@ -895,9 +1176,15 @@ pub(super) fn read_sub( /// buffer and offset. fn resolved(r: &Recorder, mut s: Slot) -> Slot { let kind = i32::from_le_bytes([s.desc[4], s.desc[5], s.desc[6], s.desc[7]]); - if s.kind == slot::SRV && s.described != 0 && kind == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE.0 { + if s.kind == slot::SRV + && s.described != 0 + && kind == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE.0 + { r.problem("views of acceleration structures are null in the capture"); - return Slot { kind: slot::SRV, ..Slot::EMPTY }; + return Slot { + kind: slot::SRV, + ..Slot::EMPTY + }; } if s.kind == slot::CBV && s.described != 0 { match r.va(s.address()) { @@ -908,7 +1195,10 @@ fn resolved(r: &Recorder, mut s: Slot) -> Slot { Va::Null {} => {} Va::Unknown { .. } => { // Its buffer is gone: nothing may read it. - s = Slot { kind: slot::CBV, ..Slot::EMPTY }; + s = Slot { + kind: slot::CBV, + ..Slot::EMPTY + }; } } } @@ -964,7 +1254,8 @@ unsafe fn changed_runs(live: *const u8, kept: *mut u8, len: usize) -> Vec<(usize let n = PAGE.min(len - at); // SAFETY: the caller's. unsafe { - let same = std::slice::from_raw_parts(live.add(at), n) == std::slice::from_raw_parts(kept.add(at), n); + let same = std::slice::from_raw_parts(live.add(at), n) + == std::slice::from_raw_parts(kept.add(at), n); if !same { std::ptr::copy_nonoverlapping(live.add(at), kept.add(at), n); match runs.last_mut() { @@ -994,7 +1285,10 @@ mod tests { live[PAGE + 5] = 1; live[2 * PAGE] = 2; live[5 * PAGE + 99] = 3; - assert_eq!(find(&live, &mut kept), [(PAGE, 3 * PAGE), (5 * PAGE, 5 * PAGE + 100)]); + assert_eq!( + find(&live, &mut kept), + [(PAGE, 3 * PAGE), (5 * PAGE, 5 * PAGE + 100)] + ); assert_eq!(live, kept); assert!(find(&live, &mut kept).is_empty()); } @@ -1002,7 +1296,13 @@ mod tests { #[test] fn what_a_submission_reads() { let mut reads = Reads::default(); - let part = |from, len| Cmd::CopyBuffer { dst: 9, dst_at: 0, src: 1, src_at: from, len }; + let part = |from, len| Cmd::CopyBuffer { + dst: 9, + dst_at: 0, + src: 1, + src_at: from, + len, + }; reads.note(&[ part(100, 50), part(4000, 200), @@ -1010,18 +1310,44 @@ mod tests { Cmd::CopyTexture { dst: Loc::Sub { res: 9, sub: 0 }, at: [0; 3], - src: Loc::Placed { res: 2, offset: 4096, format: 28, size: [16, 16, 1], pitch: 256 }, + src: Loc::Placed { + res: 2, + offset: 4096, + format: 28, + size: [16, 16, 1], + pitch: 256, + }, part: None, }, - Cmd::Indirect { signature: 1, most: 1, args: 3, at: 8, count: 0, count_at: 0 }, - Cmd::RootView { graphics: true, kind: slot::CBV, param: 0, va: Va::At { res: 4, offset: 5 } }, + Cmd::Indirect { + signature: 1, + most: 1, + args: 3, + at: 8, + count: 0, + count_at: 0, + }, + Cmd::RootView { + graphics: true, + kind: slot::CBV, + param: 0, + va: Va::At { res: 4, offset: 5 }, + }, ]); assert_eq!(reads.pages(1, 1 << 20, false), [(0, 8192), (16384, 20480)]); - assert_eq!(reads.pages(1, 20_100, false), [(0, 8192), (16384, 20_100)], "its end"); + assert_eq!( + reads.pages(1, 20_100, false), + [(0, 8192), (16384, 20_100)], + "its end" + ); assert_eq!(reads.pages(2, 1 << 20, false), [(4096, 8192)]); assert_eq!(reads.pages(3, 100, false), [(0, 100)]); assert_eq!(reads.pages(4, 100, false), [(0, 100)]); - assert_eq!(reads.pages(5, 100, true), [(0, 100)], "a descriptor names it"); + assert_eq!( + reads.pages(5, 100, true), + [(0, 100)], + "a descriptor names it" + ); assert!(reads.pages(5, 100, false).is_empty() && reads.pages(9, 100, false).is_empty()); } diff --git a/crates/victory-gpu/src/replay/states.rs b/crates/victory-gpu/src/replay/states.rs index c159423..b7379f4 100644 --- a/crates/victory-gpu/src/replay/states.rs +++ b/crates/victory-gpu/src/replay/states.rs @@ -51,7 +51,15 @@ pub struct States { impl States { /// A texture of `subs` subresources starts in `state`. pub fn add(&mut self, res: u32, subs: u32, state: u32, decays: bool) { - self.map.insert(res, One { subs: subs.max(1), decays, all: state, each: Vec::new() }); + self.map.insert( + res, + One { + subs: subs.max(1), + decays, + all: state, + each: Vec::new(), + }, + ); } /// A placed resource is the one in use now. @@ -68,7 +76,11 @@ impl States { /// One state, or one for each subresource. pub fn get(&self, res: u32) -> Option> { let one = self.map.get(&res)?; - Some(if one.each.is_empty() { vec![one.all] } else { one.each.clone() }) + Some(if one.each.is_empty() { + vec![one.all] + } else { + one.each.clone() + }) } pub fn change(&mut self, c: &Change) { @@ -120,23 +132,50 @@ impl States { /// The changes a command makes. pub fn changes(cmd: &Cmd, out: &mut Vec) { - let promoted = |res, sub| Change { res, sub, after: COPY_DEST, promoted: true, alias: false }; + let promoted = |res, sub| Change { + res, + sub, + after: COPY_DEST, + promoted: true, + alias: false, + }; match cmd { Cmd::Barriers { all } => { for b in all { match *b { // The first half of a split barrier changes nothing yet. - Barrier::Transition { flags, res, sub, after, .. } if flags & 1 == 0 => { - out.push(Change { res, sub, after: after as u32, promoted: false, alias: false }); + Barrier::Transition { + flags, + res, + sub, + after, + .. + } if flags & 1 == 0 => { + out.push(Change { + res, + sub, + after: after as u32, + promoted: false, + alias: false, + }); } Barrier::Alias { after, .. } if after != 0 => { - out.push(Change { res: after, sub: ALL, after: 0, promoted: false, alias: true }); + out.push(Change { + res: after, + sub: ALL, + after: 0, + promoted: false, + alias: true, + }); } _ => {} } } } - Cmd::CopyTexture { dst: Loc::Sub { res, sub }, .. } => out.push(promoted(*res, *sub)), + Cmd::CopyTexture { + dst: Loc::Sub { res, sub }, + .. + } => out.push(promoted(*res, *sub)), Cmd::CopyResource { dst, .. } => out.push(promoted(*dst, ALL)), _ => {} } @@ -147,7 +186,13 @@ mod tests { use super::*; fn set(res: u32, sub: u32, after: u32) -> Change { - Change { res, sub, after, promoted: false, alias: false } + Change { + res, + sub, + after, + promoted: false, + alias: false, + } } #[test] @@ -165,7 +210,13 @@ mod tests { assert_eq!(s.get(1), Some(vec![0x80]), "equal states are one again"); // A copy into a texture in the common state leaves it a copy // destination; one into a texture in another state changes nothing. - let copy = |res| Change { res, sub: ALL, after: COPY_DEST, promoted: true, alias: false }; + let copy = |res| Change { + res, + sub: ALL, + after: COPY_DEST, + promoted: true, + alias: false, + }; s.change(©(2)); s.change(©(1)); s.decay(); @@ -183,8 +234,28 @@ mod tests { #[test] fn commands_change_states() { let mut out = Vec::new(); - let t = |flags| Barrier::Transition { flags, res: 1, sub: 0, before: 4, after: 8 }; - changes(&Cmd::Barriers { all: vec![t(1), t(2), Barrier::Alias { flags: 0, before: 3, after: 4 }, Barrier::Uav { flags: 0, res: 1 }] }, &mut out); + let t = |flags| Barrier::Transition { + flags, + res: 1, + sub: 0, + before: 4, + after: 8, + }; + changes( + &Cmd::Barriers { + all: vec![ + t(1), + t(2), + Barrier::Alias { + flags: 0, + before: 3, + after: 4, + }, + Barrier::Uav { flags: 0, res: 1 }, + ], + }, + &mut out, + ); assert_eq!(out.len(), 2); assert_eq!(out[0], set(1, 0, 8)); assert!(out[1].alias && out[1].res == 4); diff --git a/crates/victory-gpu/src/replay/wire.rs b/crates/victory-gpu/src/replay/wire.rs index b82667f..a5623c2 100644 --- a/crates/victory-gpu/src/replay/wire.rs +++ b/crates/victory-gpu/src/replay/wire.rs @@ -94,7 +94,11 @@ impl Wire for Option { } } fn get(from: &mut Dec) -> Result { - Ok(if bool::get(from)? { Some(T::get(from)?) } else { None }) + Ok(if bool::get(from)? { + Some(T::get(from)?) + } else { + None + }) } } @@ -228,14 +232,26 @@ pub mod slot { } impl Slot { - pub const EMPTY: Slot = Slot { kind: slot::EMPTY, described: 0, pad: 0, res: NONE, counter: NONE, desc: [0; 52] }; + pub const EMPTY: Slot = Slot { + kind: slot::EMPTY, + described: 0, + pad: 0, + res: NONE, + counter: NONE, + desc: [0; 52], + }; /// A slot of `kind` with the description at `desc` (`size` bytes), if any. /// /// # Safety /// `desc` is null or points at a description of `size` bytes. pub unsafe fn new(kind: u8, res: u32, counter: u32, desc: *const u8, size: usize) -> Slot { - let mut s = Slot { kind, res, counter, ..Slot::EMPTY }; + let mut s = Slot { + kind, + res, + counter, + ..Slot::EMPTY + }; if !desc.is_null() { s.described = 1; // SAFETY: the caller's description, at most 52 bytes of it. @@ -247,7 +263,14 @@ impl Slot { /// A constant buffer view's address (or its offset, in a file). pub fn address(&self) -> u64 { u64::from_le_bytes([ - self.desc[0], self.desc[1], self.desc[2], self.desc[3], self.desc[4], self.desc[5], self.desc[6], self.desc[7], + self.desc[0], + self.desc[1], + self.desc[2], + self.desc[3], + self.desc[4], + self.desc[5], + self.desc[6], + self.desc[7], ]) } @@ -276,7 +299,14 @@ impl Wire for Slot { } let mut desc = [0; 52]; desc[..n].copy_from_slice(from.take(n)?); - Ok(Slot { kind, described, pad: 0, res, counter, desc }) + Ok(Slot { + kind, + described, + pad: 0, + res, + counter, + desc, + }) } } @@ -383,7 +413,11 @@ impl Cmd { pub fn runs_shaders(&self) -> bool { matches!( self, - Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::Dispatch { .. } | Cmd::DispatchMesh { .. } | Cmd::Indirect { .. } + Cmd::Draw { .. } + | Cmd::DrawIndexed { .. } + | Cmd::Dispatch { .. } + | Cmd::DispatchMesh { .. } + | Cmd::Indirect { .. } ) } } @@ -589,59 +623,198 @@ pub(crate) mod tests { let mut desc = [0; 52]; desc[3] = 7; desc[51] = 9; - Slot { kind: slot::SAMPLER, described: 1, pad: 0, res: 4, counter: 5, desc } + Slot { + kind: slot::SAMPLER, + described: 1, + pad: 0, + res: 4, + counter: 5, + desc, + } } fn at() -> Va { - Va::At { res: 3, offset: 1 << 40 } + Va::At { + res: 3, + offset: 1 << 40, + } } pub(crate) fn every_command() -> Vec { - let placed = Loc::Placed { res: 5, offset: 512, format: 28, size: [4, 5, 6], pitch: 256 }; + let placed = Loc::Placed { + res: 5, + offset: 512, + format: 28, + size: [4, 5, 6], + pitch: 256, + }; let rects = vec![[1, 2, 3, 4]]; vec![ - Cmd::Draw { vertices: 1, instances: 2, first: 3, first_instance: 4 }, - Cmd::DrawIndexed { indices: 1, instances: 2, first: 3, base: -4, first_instance: 5 }, + Cmd::Draw { + vertices: 1, + instances: 2, + first: 3, + first_instance: 4, + }, + Cmd::DrawIndexed { + indices: 1, + instances: 2, + first: 3, + base: -4, + first_instance: 5, + }, Cmd::Dispatch { groups: [1, 2, 3] }, Cmd::DispatchMesh { groups: [4, 5, 6] }, - Cmd::CopyBuffer { dst: 1, dst_at: 2, src: 3, src_at: 4, len: 5 }, - Cmd::CopyTexture { dst: Loc::Sub { res: 1, sub: 2 }, at: [3, 4, 5], src: placed, part: Some([1, 2, 3, 4, 5, 6]) }, + Cmd::CopyBuffer { + dst: 1, + dst_at: 2, + src: 3, + src_at: 4, + len: 5, + }, + Cmd::CopyTexture { + dst: Loc::Sub { res: 1, sub: 2 }, + at: [3, 4, 5], + src: placed, + part: Some([1, 2, 3, 4, 5, 6]), + }, Cmd::CopyResource { dst: 1, src: 2 }, - Cmd::Resolve { dst: 1, dst_sub: 2, src: 3, src_sub: 4, format: 28 }, - Cmd::ResolveRegion { dst: 1, dst_sub: 2, at: [3, 4], src: 5, src_sub: 6, part: Some([0, 1, 2, 3]), format: 28, mode: 1 }, + Cmd::Resolve { + dst: 1, + dst_sub: 2, + src: 3, + src_sub: 4, + format: 28, + }, + Cmd::ResolveRegion { + dst: 1, + dst_sub: 2, + at: [3, 4], + src: 5, + src_sub: 6, + part: Some([0, 1, 2, 3]), + format: 28, + mode: 1, + }, Cmd::Topology { kind: 4 }, - Cmd::Viewports { all: vec![[0.0, 1.0, 2.0, 3.0, 0.5, 1.0]; 2] }, + Cmd::Viewports { + all: vec![[0.0, 1.0, 2.0, 3.0, 0.5, 1.0]; 2], + }, Cmd::Scissors { all: rects.clone() }, - Cmd::BlendFactor { factor: Some([0.1, 0.2, 0.3, 0.4]) }, + Cmd::BlendFactor { + factor: Some([0.1, 0.2, 0.3, 0.4]), + }, Cmd::BlendFactor { factor: None }, Cmd::StencilRef { value: 255 }, Cmd::Pipeline { pso: 9 }, Cmd::Barriers { all: vec![ - Barrier::Transition { flags: 1, res: 2, sub: ALL, before: 4, after: 8 }, - Barrier::Alias { flags: 0, before: 1, after: 2 }, + Barrier::Transition { + flags: 1, + res: 2, + sub: ALL, + before: 4, + after: 8, + }, + Barrier::Alias { + flags: 0, + before: 1, + after: 2, + }, Barrier::Uav { flags: 0, res: 0 }, ], }, Cmd::Heaps { heaps: vec![1, 2] }, - Cmd::RootSignature { graphics: true, root: 3 }, - Cmd::Table { graphics: false, param: 1, heap: 2, slot: 1 << 20 }, - Cmd::Constants { graphics: true, param: 1, offset: 2, values: vec![3, 4, 5] }, - Cmd::RootView { graphics: true, kind: slot::CBV, param: 1, va: at() }, - Cmd::IndexBuffer { view: Some((at(), 5, 42)) }, + Cmd::RootSignature { + graphics: true, + root: 3, + }, + Cmd::Table { + graphics: false, + param: 1, + heap: 2, + slot: 1 << 20, + }, + Cmd::Constants { + graphics: true, + param: 1, + offset: 2, + values: vec![3, 4, 5], + }, + Cmd::RootView { + graphics: true, + kind: slot::CBV, + param: 1, + va: at(), + }, + Cmd::IndexBuffer { + view: Some((at(), 5, 42)), + }, Cmd::IndexBuffer { view: None }, - Cmd::VertexBuffers { start: 1, count: 1, views: Some(vec![(Va::Unknown { address: 5 }, 6, 7)]) }, - Cmd::VertexBuffers { start: 1, count: 3, views: None }, - Cmd::Targets { colors: vec![view(); 3], depth: Some(view()) }, - Cmd::ClearDepth { view: view(), flags: 3, depth: 0.5, stencil: 7, rects: rects.clone() }, - Cmd::ClearTarget { view: view(), color: [1.0, 2.0, 3.0, 4.0], rects: Vec::new() }, - Cmd::Discard { res: 1, rects, subs: Some([0, 2]) }, - Cmd::BeginQuery { heap: 1, kind: 0, index: 2 }, - Cmd::EndQuery { heap: 1, kind: 2, index: 3 }, - Cmd::ResolveQuery { heap: 1, kind: 2, first: 3, count: 4, dst: 5, at: 6 }, - Cmd::Indirect { signature: 1, most: 2, args: 3, at: 4, count: 5, count_at: 6 }, - Cmd::WriteImmediate { all: vec![(at(), 1, 2), (Va::Null {}, 3, 4)] }, - Cmd::DepthBounds { min: 0.25, max: 0.75 }, + Cmd::VertexBuffers { + start: 1, + count: 1, + views: Some(vec![(Va::Unknown { address: 5 }, 6, 7)]), + }, + Cmd::VertexBuffers { + start: 1, + count: 3, + views: None, + }, + Cmd::Targets { + colors: vec![view(); 3], + depth: Some(view()), + }, + Cmd::ClearDepth { + view: view(), + flags: 3, + depth: 0.5, + stencil: 7, + rects: rects.clone(), + }, + Cmd::ClearTarget { + view: view(), + color: [1.0, 2.0, 3.0, 4.0], + rects: Vec::new(), + }, + Cmd::Discard { + res: 1, + rects, + subs: Some([0, 2]), + }, + Cmd::BeginQuery { + heap: 1, + kind: 0, + index: 2, + }, + Cmd::EndQuery { + heap: 1, + kind: 2, + index: 3, + }, + Cmd::ResolveQuery { + heap: 1, + kind: 2, + first: 3, + count: 4, + dst: 5, + at: 6, + }, + Cmd::Indirect { + signature: 1, + most: 2, + args: 3, + at: 4, + count: 5, + count_at: 6, + }, + Cmd::WriteImmediate { + all: vec![(at(), 1, 2), (Va::Null {}, 3, 4)], + }, + Cmd::DepthBounds { + min: 0.25, + max: 0.75, + }, ] } @@ -664,13 +837,23 @@ pub(crate) mod tests { out[0] }) .collect(); - assert_eq!(kinds.into_iter().collect::>(), (1..=LAST_CMD).collect::>()); - assert!(Cmd::all(&[LAST_CMD + 1]).is_err(), "a kind was added: bring LAST_CMD and the list above up to date"); + assert_eq!( + kinds.into_iter().collect::>(), + (1..=LAST_CMD).collect::>() + ); + assert!( + Cmd::all(&[LAST_CMD + 1]).is_err(), + "a kind was added: bring LAST_CMD and the list above up to date" + ); } #[test] fn a_frame_comes_back() { - let props = HeapProps { kind: 4, cpu: 3, pool: 1 }; + let props = HeapProps { + kind: 4, + cpu: 3, + pool: 1, + }; let desc = Desc { dimension: 3, alignment: 65536, @@ -685,7 +868,10 @@ pub(crate) mod tests { }; let resource = Resource { id: 2, - place: Place::Placed { heap: 1, offset: 65536 }, + place: Place::Placed { + heap: 1, + offset: 65536, + }, desc, made_in: 4, clear: Some([28, 1, 2, 3, 4]), @@ -699,36 +885,95 @@ pub(crate) mod tests { vendor: 0x1002, device: 0x744c, notes: vec!["nothing".into()], - heaps: vec![Heap { id: 1, size: 64 << 20, props: props.clone(), alignment: 65536, flags: 0x84 }], + heaps: vec![Heap { + id: 1, + size: 64 << 20, + props: props.clone(), + alignment: 65536, + flags: 0x84, + }], resources: vec![ resource.clone(), - Resource { place: Place::Committed { props, flags: 8 }, ..resource.clone() }, - Resource { place: Place::BackBuffer {}, clear: None, ..resource }, + Resource { + place: Place::Committed { props, flags: 8 }, + ..resource.clone() + }, + Resource { + place: Place::BackBuffer {}, + clear: None, + ..resource + }, ], roots: vec![(3, Blob(vec![1, 2, 3]))], - codes: vec![Code { at: 1, len: 2, hash: [7; 32] }], + codes: vec![Code { + at: 1, + len: 2, + hash: [7; 32], + }], pipelines: vec![Pipeline { id: 4, parts: vec![ Part::Root { root: 3 }, Part::Code { kind: 25, blob: 0 }, - Part::Plain { kind: 8, data: Blob(vec![9; 20]) }, - Part::Layout { elements: vec![("POSITION".into(), [1, 2, 3, 4, 5, 6])] }, + Part::Plain { + kind: 8, + data: Blob(vec![9; 20]), + }, + Part::Layout { + elements: vec![("POSITION".into(), [1, 2, 3, 4, 5, 6])], + }, ], name: "a pipeline".into(), }], - signatures: vec![Signature { id: 5, stride: 12, args: vec![[10, 0, 0, 0]], root: 0 }], - descriptor_heaps: vec![DescriptorHeap { id: 6, kind: 0, count: 10, flags: 1, runs: vec![(0, 9, Slot::EMPTY), (9, 1, view())] }], - query_heaps: vec![QueryHeap { id: 7, kind: 1, count: 8 }], - lists: vec![List { kind: 0, commands: Blob(vec![1, 2]) }], + signatures: vec![Signature { + id: 5, + stride: 12, + args: vec![[10, 0, 0, 0]], + root: 0, + }], + descriptor_heaps: vec![DescriptorHeap { + id: 6, + kind: 0, + count: 10, + flags: 1, + runs: vec![(0, 9, Slot::EMPTY), (9, 1, view())], + }], + query_heaps: vec![QueryHeap { + id: 7, + kind: 1, + count: 8, + }], + lists: vec![List { + kind: 0, + commands: Blob(vec![1, 2]), + }], submits: vec![Submit { frame: 0, lists: vec![0, MISSING], - deltas: vec![Delta { res: 2, at: 4096, len: 8192, file: 0 }], + deltas: vec![Delta { + res: 2, + at: 4096, + len: 8192, + file: 0, + }], views: vec![(6, 3, view())], }], - contents: vec![Content { res: 2, first: 0, count: 3, len: 100, file: ZERO }], - presents: vec![Present { submits: 1, res: 2, width: 4, height: 5, format: 28, pitch: 256, file: 0 }], + contents: vec![Content { + res: 2, + first: 0, + count: 3, + len: 100, + file: ZERO, + }], + presents: vec![Present { + submits: 1, + res: 2, + width: 4, + height: 5, + format: 28, + pitch: 256, + file: 0, + }], }; there_and_back(&frame); let dir = tempfile::tempdir().unwrap(); diff --git a/crates/victory-gpu/tests/replay.rs b/crates/victory-gpu/tests/replay.rs index 3d5eb5a..9f80bc9 100644 --- a/crates/victory-gpu/tests/replay.rs +++ b/crates/victory-gpu/tests/replay.rs @@ -14,7 +14,9 @@ use victory_gpu::replay::play::{self, Buffers, Options, Player}; use victory_gpu::replay::record::{self, At, Settings}; use windows::Win32::Foundation::{HANDLE, HWND, RECT}; use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; -use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ID3DBlob}; +use windows::Win32::Graphics::Direct3D::{ + D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ID3DBlob, +}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; use windows::Win32::Graphics::Dxgi::*; @@ -54,6 +56,172 @@ V vs(float2 at : POSITION, float3 color : COLOR1) { V v; v.at = float4(at, 0.4, float4 ps(V v) : SV_Target { return float4(v.color, 1); } "#; +/// A quad from a mesh shader, its texture picked from the heap by index. +const MESH: &str = r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), RootConstants(num32BitConstants=5, b0)" +cbuffer C : register(b0) { float4 place; uint pick; }; +struct V { float4 at : SV_Position; float2 uv : UV; }; +[RootSignature(RS)] +[numthreads(1, 1, 1)] +[outputtopology("triangle")] +void ms(out vertices V v[4], out indices uint3 t[2]) { + SetMeshOutputCounts(4, 2); + for (uint i = 0; i < 4; i++) { + float2 c = float2(i & 1, i >> 1); + v[i].at = float4(place.xy + c * place.zw, 0.3, 1); + v[i].uv = c; + } + t[0] = uint3(0, 1, 2); + t[1] = uint3(2, 1, 3); +} +[RootSignature(RS)] +float4 ps(V v) : SV_Target { + Texture2D t = ResourceDescriptorHeap[pick]; + return t.Load(int3(v.uv * 16, 0)) * 0.5 + float4(v.uv, 0, 0) * 0.5; +} +"#; + +/// Compiles with the Windows SDK's dxc, if there is one. +fn dxc(source: &str, entry: &str, target: &str) -> Option> { + let kits = std::fs::read_dir("C:/Program Files (x86)/Windows Kits/10/bin").ok()?; + let exe = kits + .flatten() + .map(|e| e.path().join("x64/dxc.exe")) + .filter(|p| p.exists()) + .max()?; + let dir = tempfile::tempdir().ok()?; + let (from, to) = (dir.path().join("a.hlsl"), dir.path().join("a.dxil")); + std::fs::write(&from, source).ok()?; + let out = std::process::Command::new(exe) + .args(["-T", target, "-E", entry, "-Fo"]) + .arg(&to) + .arg(&from) + .output() + .ok()?; + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + std::fs::read(to).ok() +} + +/// The mesh pipeline, from a stream, by way of a pipeline library; and the +/// signature of its indirect draws. `None` without dxc or mesh shaders. +fn mesh(device: &ID3D12Device, blend: D3D12_BLEND_DESC) -> Option<(Made, ID3D12CommandSignature)> { + #[repr(C, align(8))] + struct Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); + #[repr(C)] + struct Stream { + root: Sub<*mut std::ffi::c_void>, + ms: Sub, + ps: Sub, + blend: Sub, + mask: Sub, + raster: Sub, + depth: Sub, + targets: Sub, + dsv: Sub, + samples: Sub, + topology: Sub, + } + let (ms, ps) = (dxc(MESH, "ms", "ms_6_6")?, dxc(MESH, "ps", "ps_6_6")?); + // SAFETY: plain queries and creation; the stream holds whole subobjects. + unsafe { + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let size = size_of::() as u32; + device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, (&raw mut o).cast(), size) + .ok()?; + if o.MeshShaderTier == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED { + return None; + } + let root: ID3D12RootSignature = device.CreateRootSignature(0, &ms).unwrap(); + let mut formats = D3D12_RT_FORMAT_ARRAY { + NumRenderTargets: 1, + ..Default::default() + }; + formats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let mut stream = Stream { + root: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, + root.as_raw(), + ), + ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, code(&ms)), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, code(&ps)), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, u32::MAX), + raster: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, + D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + ..Default::default() + }, + ), + depth: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, + D3D12_DEPTH_STENCIL_DESC::default(), + ), + targets: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + formats, + ), + dsv: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, + DXGI_FORMAT_D32_FLOAT, + ), + samples: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, + DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ), + topology: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + ), + }; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::(), + pPipelineStateSubobjectStream: (&raw mut stream).cast(), + }; + let library: ID3D12PipelineLibrary1 = device + .cast::() + .unwrap() + .CreatePipelineLibrary::(&[]) + .unwrap() + .cast() + .unwrap(); + { + let made: ID3D12PipelineState = device + .cast::() + .unwrap() + .CreatePipelineState(&desc) + .unwrap(); + library.StorePipeline(w!("mesh"), &made).unwrap(); + } + let pso: ID3D12PipelineState = library.LoadPipeline(w!("mesh"), &desc).unwrap(); + record::name(&pso, "a mesh pipeline"); + let argument = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH, + ..Default::default() + }; + let mut signature: Option = None; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 12, + NumArgumentDescs: 1, + pArgumentDescs: &argument, + NodeMask: 0, + }; + device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature) + .unwrap(); + Some((Made { root, pso }, signature.unwrap())) + } +} + /// Writes the arguments of indirect draws (two records: six vertices, and /// one far too many that the clamp cuts to none). const ARGS: &str = r#" @@ -114,19 +282,36 @@ fn compile(source: &str, entry: PCSTR, target: PCSTR) -> Vec { // SAFETY: the source and names live through the call; the blobs' own // bytes. unsafe { - let r = D3DCompile(source.as_ptr().cast(), source.len(), None, None, None, entry, target, 1 << 20, 0, &mut code, Some(&mut errors)); + let r = D3DCompile( + source.as_ptr().cast(), + source.len(), + None, + None, + None, + entry, + target, + 1 << 20, + 0, + &mut code, + Some(&mut errors), + ); if r.is_err() { let e = errors.unwrap(); - let text = std::slice::from_raw_parts(e.GetBufferPointer().cast::(), e.GetBufferSize()); + let text = + std::slice::from_raw_parts(e.GetBufferPointer().cast::(), e.GetBufferSize()); panic!("{}", String::from_utf8_lossy(text)); } let code = code.unwrap(); - std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()).to_vec() + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) + .to_vec() } } fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE { - D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() } + D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + } } fn compute(device: &ID3D12Device, source: &str) -> Made { @@ -152,14 +337,21 @@ fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() } } -fn texture_desc(size: u32, format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { +fn texture_desc( + size: u32, + format: DXGI_FORMAT, + flags: D3D12_RESOURCE_FLAGS, +) -> D3D12_RESOURCE_DESC { D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: u64::from(size), @@ -167,7 +359,10 @@ fn texture_desc(size: u32, format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS) -> DepthOrArraySize: 1, MipLevels: 1, Format: format, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Flags: flags, ..Default::default() } @@ -182,11 +377,25 @@ enum In { Shared, } -fn committed(device: &ID3D12Device, place: In, desc: &D3D12_RESOURCE_DESC, state: D3D12_RESOURCE_STATES) -> (ID3D12Resource, *mut u8) { +fn committed( + device: &ID3D12Device, + place: In, + desc: &D3D12_RESOURCE_DESC, + state: D3D12_RESOURCE_STATES, +) -> (ID3D12Resource, *mut u8) { let heap = match place { - In::Card => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, - In::Upload => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, - In::Back => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + In::Card => D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + In::Upload => D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_UPLOAD, + ..Default::default() + }, + In::Back => D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }, In::Shared => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, @@ -198,7 +407,9 @@ fn committed(device: &ID3D12Device, place: In, desc: &D3D12_RESOURCE_DESC, state let mut data = std::ptr::null_mut(); // SAFETY: plain creation and mapping. unsafe { - device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, desc, state, None, &mut made).unwrap(); + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, desc, state, None, &mut made) + .unwrap(); let made = made.unwrap(); if place != In::Card { made.Map(0, None, Some(&mut data)).unwrap(); @@ -207,7 +418,11 @@ fn committed(device: &ID3D12Device, place: In, desc: &D3D12_RESOURCE_DESC, state } } -fn moved(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { +fn moved( + res: &ID3D12Resource, + before: D3D12_RESOURCE_STATES, + after: D3D12_RESOURCE_STATES, +) -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Anonymous: D3D12_RESOURCE_BARRIER_0 { @@ -227,7 +442,9 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Anonymous: D3D12_RESOURCE_BARRIER_0 { - UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }), + UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: ManuallyDrop::new(None), + }), }, ..Default::default() } @@ -283,10 +500,15 @@ struct Scene { lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>, draw: Made, plain: Made, + mesh: Option<(Made, ID3D12CommandSignature)>, vertices: (ID3D12Resource, *mut u8), samplers: ID3D12DescriptorHeap, still: Vec<(&'static str, ID3D12Resource, D3D12_RESOURCE_STATES)>, - copies: (ID3D12CommandQueue, ID3D12CommandAllocator, ID3D12GraphicsCommandList), + copies: ( + ID3D12CommandQueue, + ID3D12CommandAllocator, + ID3D12GraphicsCommandList, + ), args: Made, clamp: Made, add: Made, @@ -318,19 +540,28 @@ impl Scene { // SAFETY: plain creation throughout. unsafe { let queue: ID3D12CommandQueue = device - .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) .unwrap(); let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); let lists = (0..3) .map(|_| { - let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); - let list: ID3D12GraphicsCommandList = - device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .unwrap(); + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .unwrap(); list.Close().unwrap(); (allocator, list) }) .collect(); - let (vs, ps) = (compile(DRAW, s!("vs"), s!("vs_5_1")), compile(DRAW, s!("ps"), s!("ps_5_1"))); + let (vs, ps) = ( + compile(DRAW, s!("vs"), s!("vs_5_1")), + compile(DRAW, s!("ps"), s!("ps_5_1")), + ); let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); let mut blend = D3D12_BLEND_DESC::default(); blend.RenderTarget[0].RenderTargetWriteMask = 15; @@ -355,14 +586,20 @@ impl Scene { PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, NumRenderTargets: 1, DSVFormat: DXGI_FORMAT_D32_FLOAT, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, ..Default::default() }; desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap(); record::name(&pso, "a drawing pipeline"); let draw = Made { root, pso }; - let (vs, ps) = (compile(PLAIN, s!("vs"), s!("vs_5_1")), compile(PLAIN, s!("ps"), s!("ps_5_1"))); + let (vs, ps) = ( + compile(PLAIN, s!("vs"), s!("vs_5_1")), + compile(PLAIN, s!("ps"), s!("ps_5_1")), + ); let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); let element = |name, index, format, at| D3D12_INPUT_ELEMENT_DESC { SemanticName: name, @@ -379,19 +616,43 @@ impl Scene { ]; desc.pRootSignature = std::mem::transmute_copy(&root); (desc.VS, desc.PS) = (code(&vs), code(&ps)); - desc.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elements.as_ptr(), NumElements: 2 }; + desc.InputLayout = D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: elements.as_ptr(), + NumElements: 2, + }; let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap(); let plain = Made { root, pso }; let clamp = compute(device, CLAMP); record::name(&clamp.pso, play::CLAMP); - let argument = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, ..Default::default() }; - let mut signature: Option = None; - let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 16, NumArgumentDescs: 1, pArgumentDescs: &argument, NodeMask: 0 }; - device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature).unwrap(); - let heap = |kind, count, flags| -> ID3D12DescriptorHeap { - device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: count, Flags: flags, NodeMask: 0 }).unwrap() + let argument = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, + ..Default::default() }; - let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE); + let mut signature: Option = None; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 16, + NumArgumentDescs: 1, + pArgumentDescs: &argument, + NodeMask: 0, + }; + device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature) + .unwrap(); + let heap = |kind, count, flags| -> ID3D12DescriptorHeap { + device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: flags, + NodeMask: 0, + }) + .unwrap() + }; + let samplers = heap( + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + 4, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ); let sampler = D3D12_SAMPLER_DESC { Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP, @@ -401,25 +662,61 @@ impl Scene { ..Default::default() }; let mut at = samplers.GetCPUDescriptorHandleForHeapStart(); - at.ptr += 2 * device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize; + at.ptr += 2 * device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) + as usize; device.CreateSampler(&sampler, at); - let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5000, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE); - let rtvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); - let dsvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); + let views = heap( + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + 5000, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ); + let rtvs = heap( + D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + 1, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + ); + let dsvs = heap( + D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + 1, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + ); let rgba = DXGI_FORMAT_R8G8B8A8_UNORM; - let (target, _) = committed(device, In::Card, &texture_desc(SIZE, rgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), FROM); + let (target, _) = committed( + device, + In::Card, + &texture_desc(SIZE, rgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), + FROM, + ); let (depth, _) = committed( device, In::Card, - &texture_desc(SIZE, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), + &texture_desc( + SIZE, + DXGI_FORMAT_D32_FLOAT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ), D3D12_RESOURCE_STATE_DEPTH_WRITE, ); - let (fixed, _) = committed(device, In::Card, &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE), TO); - let (image, _) = committed(device, In::Card, &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), UAV); + let (fixed, _) = committed( + device, + In::Card, + &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE), + TO, + ); + let (image, _) = committed( + device, + In::Card, + &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + UAV, + ); let mut memory: Option = None; let desc = D3D12_HEAP_DESC { SizeInBytes: 4 << 20, - Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Properties: D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, }; @@ -428,7 +725,9 @@ impl Scene { let placed = || { let mut made: Option = None; let d = texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE); - device.CreatePlacedResource(&memory, 65536, &d, TO, None, &mut made).unwrap(); + device + .CreatePlacedResource(&memory, 65536, &d, TO, None, &mut made) + .unwrap(); made.unwrap() }; // Two textures in one place. @@ -449,7 +748,12 @@ impl Scene { &buffer_desc(65536, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_GENERIC_READ, ); - let back = committed(device, In::Back, &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE), TO); + let back = committed( + device, + In::Back, + &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE), + TO, + ); let vertices = committed( device, In::Upload, @@ -468,29 +772,61 @@ impl Scene { MipLevels: 3, ..texture_desc(16, DXGI_FORMAT_R16_FLOAT, D3D12_RESOURCE_FLAG_NONE) }; - let stencil = texture_desc(32, DXGI_FORMAT_R32G8X24_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); - let (write, read) = (D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); - [("blocks", blocks, TO, READ), ("volume", volume, TO, read), ("stencil", stencil, write, write)].map(|(name, d, made_in, ends)| { + let stencil = texture_desc( + 32, + DXGI_FORMAT_R32G8X24_TYPELESS, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ); + let (write, read) = ( + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + ); + [ + ("blocks", blocks, TO, READ), + ("volume", volume, TO, read), + ("stencil", stencil, write, write), + ] + .map(|(name, d, made_in, ends)| { let (t, _) = committed(device, In::Card, &d, made_in); record::name(&t, name); (name, t, ends) }) }; - let copies: (ID3D12CommandQueue, ID3D12CommandAllocator, ID3D12GraphicsCommandList) = { + let copies: ( + ID3D12CommandQueue, + ID3D12CommandAllocator, + ID3D12GraphicsCommandList, + ) = { let queue = device - .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COPY, ..Default::default() }) + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COPY, + ..Default::default() + }) + .unwrap(); + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY) + .unwrap(); + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None) .unwrap(); - let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY).unwrap(); - let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None).unwrap(); list.Close().unwrap(); (queue, allocator, list) }; - for (r, n) in [(&sum, "sum"), (&image, "image"), (&target, "target"), (&shared.0, "shared"), (&one, "one"), (&other, "other")] { + for (r, n) in [ + (&sum, "sum"), + (&image, "image"), + (&target, "target"), + (&shared.0, "shared"), + (&one, "one"), + (&other, "other"), + ] { record::name(r, n); } device.CreateRenderTargetView(&target, None, rtvs.GetCPUDescriptorHandleForHeapStart()); device.CreateDepthStencilView(&depth, None, dsvs.GetCPUDescriptorHandleForHeapStart()); - let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let step = device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; let swap = window.then(|| swap_chain(&queue)); let scene = Scene { device: device.clone(), @@ -501,6 +837,7 @@ impl Scene { lists, draw, plain, + mesh: mesh(device, blend), vertices, samplers, still: still.to_vec(), @@ -531,24 +868,45 @@ impl Scene { swap, }; // Null views everywhere, by copies of a slot made elsewhere. - let block = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); + let block = heap( + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + 16, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + ); let null = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: rgba, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, - Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() } }, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MipLevels: 1, + ..Default::default() + }, + }, }; let from = block.GetCPUDescriptorHandleForHeapStart(); for i in 0..16 { - let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.ptr + i * step }; + let at = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: from.ptr + i * step, + }; device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&null), at); } for i in (0..4992).step_by(16) { - device.CopyDescriptorsSimple(16, scene.cpu(i), from, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + device.CopyDescriptorsSimple( + 16, + scene.cpu(i), + from, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + ); } // The rest with the other copying method, in unlike pieces. let to = [scene.cpu(4992), scene.cpu(4994)]; - let sources = [from, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.ptr + 4 * step }]; + let sources = [ + from, + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: from.ptr + 4 * step, + }, + ]; device.CopyDescriptors( 2, to.as_ptr(), @@ -560,7 +918,12 @@ impl Scene { ); scene.show(4001, &scene.other); scene.show(4002, &scene.one); - device.CreateUnorderedAccessView(&scene.image, None::<&ID3D12Resource>, None, scene.cpu(7)); + device.CreateUnorderedAccessView( + &scene.image, + None::<&ID3D12Resource>, + None, + scene.cpu(7), + ); scene } } @@ -568,13 +931,18 @@ impl Scene { fn cpu(&self, i: usize) -> D3D12_CPU_DESCRIPTOR_HANDLE { // SAFETY: a slot of the heap. let start = unsafe { self.views.GetCPUDescriptorHandleForHeapStart() }; - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + i * self.step } + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + i * self.step, + } } /// Slot `i` shows `texture`. fn show(&self, i: usize, texture: &ID3D12Resource) { // SAFETY: a slot of the heap and a live texture. - unsafe { self.device.CreateShaderResourceView(texture, None, self.cpu(i)) }; + unsafe { + self.device + .CreateShaderResourceView(texture, None, self.cpu(i)) + }; } fn wait(&mut self) { @@ -582,7 +950,9 @@ impl Scene { // SAFETY: our queue, fence and event. unsafe { self.queue.Signal(&self.fence, self.value).unwrap(); - self.fence.SetEventOnCompletion(self.value, self.event).unwrap(); + self.fence + .SetEventOnCompletion(self.value, self.event) + .unwrap(); WaitForSingleObject(self.event, INFINITE); self.device.GetDeviceRemovedReason().unwrap(); } @@ -599,7 +969,8 @@ impl Scene { } fn send(&self, lists: &[&ID3D12GraphicsCommandList]) { - let all: Vec> = lists.iter().map(|l| Some(l.cast().unwrap())).collect(); + let all: Vec> = + lists.iter().map(|l| Some(l.cast().unwrap())).collect(); // SAFETY: closed lists. unsafe { self.queue.ExecuteCommandLists(&all) }; } @@ -611,7 +982,13 @@ impl Scene { let mut c = color; c[1] = c[1].wrapping_add((x * 8 + y) as u8); // SAFETY: inside the mapping (16 rows of 256 bytes). - unsafe { self.texels.1.add(at + y * 256 + x * 4).cast::<[u8; 4]>().write(c) }; + unsafe { + self.texels + .1 + .add(at + y * 256 + x * 4) + .cast::<[u8; 4]>() + .write(c) + }; } } } @@ -621,13 +998,17 @@ impl Scene { // SAFETY: a borrowed pointer never released. pResource: unsafe { std::mem::transmute_copy(&self.texels.0) }, Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(at, 16) }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: footprint(at, 16), + }, }; let to = 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 }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, }; // SAFETY: an open list; live resources. unsafe { l.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; @@ -643,10 +1024,24 @@ impl Scene { l.SetGraphicsRoot32BitConstant(0, pick, 0); l.SetGraphicsRootConstantBufferView(1, self.constants.0.GetGPUVirtualAddress() + at); l.SetGraphicsRootDescriptorTable(2, self.views.GetGPUDescriptorHandleForHeapStart()); - let step = self.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + let step = self + .device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); let first = self.samplers.GetGPUDescriptorHandleForHeapStart().ptr; - l.SetGraphicsRootDescriptorTable(3, D3D12_GPU_DESCRIPTOR_HANDLE { ptr: first + 2 * u64::from(step) }); - l.ExecuteIndirect(&self.signature, 1, &self.scratch, record * 16, None::<&ID3D12Resource>, 0); + l.SetGraphicsRootDescriptorTable( + 3, + D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: first + 2 * u64::from(step), + }, + ); + l.ExecuteIndirect( + &self.signature, + 1, + &self.scratch, + record * 16, + None::<&ID3D12Resource>, + 0, + ); } } @@ -659,7 +1054,14 @@ impl Scene { l.SetComputeRootShaderResourceView(0, self.shared.0.GetGPUVirtualAddress() + 65536); l.SetComputeRootUnorderedAccessView(1, self.arguments.GetGPUVirtualAddress()); l.Dispatch(1, 1, 1); - l.ResourceBarrier(&[uav_barrier(), moved(&self.arguments, UAV, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]); + l.ResourceBarrier(&[ + uav_barrier(), + moved( + &self.arguments, + UAV, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + ), + ]); l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, before, UAV)]); l.SetComputeRootSignature(&self.clamp.root); l.SetPipelineState(&self.clamp.pso); @@ -671,7 +1073,11 @@ impl Scene { l.SetComputeRootUnorderedAccessView(4, self.budget.GetGPUVirtualAddress()); l.Dispatch(1, 1, 1); l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, UAV, ARGUMENTS)]); - l.ResourceBarrier(&[moved(&self.arguments, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, UAV)]); + l.ResourceBarrier(&[moved( + &self.arguments, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + UAV, + )]); } } @@ -688,11 +1094,24 @@ impl Scene { fn targets(&self, l: &ID3D12GraphicsCommandList) { // SAFETY: an open list; live objects. unsafe { - let (rtv, dsv) = (self.rtvs.GetCPUDescriptorHandleForHeapStart(), self.dsvs.GetCPUDescriptorHandleForHeapStart()); + let (rtv, dsv) = ( + self.rtvs.GetCPUDescriptorHandleForHeapStart(), + self.dsvs.GetCPUDescriptorHandleForHeapStart(), + ); l.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv)); let size = SIZE as f32; - l.RSSetViewports(&[D3D12_VIEWPORT { Width: size, Height: size, MaxDepth: 1.0, ..Default::default() }]); - l.RSSetScissorRects(&[RECT { left: 0, top: 0, right: SIZE as i32, bottom: SIZE as i32 }]); + l.RSSetViewports(&[D3D12_VIEWPORT { + Width: size, + Height: size, + MaxDepth: 1.0, + ..Default::default() + }]); + l.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: SIZE as i32, + bottom: SIZE as i32, + }]); l.SetDescriptorHeaps(&[Some(self.views.clone()), Some(self.samplers.clone())]); } } @@ -703,15 +1122,34 @@ impl Scene { // card does not use now. unsafe { let x = 0.5 + 0.05 * n as f32; - let vertices = [[x, 0.4, 1.0, 0.0, 0.0], [x + 0.3, 0.4, 0.0, 1.0, 0.0], [x, 0.9, 0.0, 0.0, 1.0f32]]; + let vertices = [ + [x, 0.4, 1.0, 0.0, 0.0], + [x + 0.3, 0.4, 0.0, 1.0, 0.0], + [x, 0.9, 0.0, 0.0, 1.0f32], + ]; self.vertices.1.cast::<[[f32; 5]; 3]>().write(vertices); - self.vertices.1.add(1024).cast::<[u16; 4]>().write([9, 2, 0, 1]); + self.vertices + .1 + .add(1024) + .cast::<[u16; 4]>() + .write([9, 2, 0, 1]); let at = self.vertices.0.GetGPUVirtualAddress(); l.SetGraphicsRootSignature(&self.plain.root); l.SetPipelineState(&self.plain.pso); l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - l.IASetVertexBuffers(0, Some(&[D3D12_VERTEX_BUFFER_VIEW { BufferLocation: at, SizeInBytes: 60, StrideInBytes: 20 }])); - let indices = D3D12_INDEX_BUFFER_VIEW { BufferLocation: at + 1024, SizeInBytes: 8, Format: DXGI_FORMAT_R16_UINT }; + l.IASetVertexBuffers( + 0, + Some(&[D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: at, + SizeInBytes: 60, + StrideInBytes: 20, + }]), + ); + let indices = D3D12_INDEX_BUFFER_VIEW { + BufferLocation: at + 1024, + SizeInBytes: 8, + Format: DXGI_FORMAT_R16_UINT, + }; l.IASetIndexBuffer(Some(&indices)); l.DrawIndexedInstanced(3, 1, 1, 0, 0); } @@ -752,16 +1190,34 @@ impl Scene { self.device.CreateDepthStencilView(t, Some(&view), dsv); let both = D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL; l.ClearDepthStencilView(dsv, both, 0.75, 3, None); - let part = RECT { left: 5, top: 6, right: 20, bottom: 17 }; + let part = RECT { + left: 5, + top: 6, + right: 20, + bottom: 17, + }; l.ClearDepthStencilView(dsv, both, 0.25, 200, Some(&[part])); continue; } let desc = t.GetDesc(); - let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize }; + let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + 1 + } else { + desc.DepthOrArraySize + }; for sub in 0..u32::from(layers * desc.MipLevels) { let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); let mut total = 0; - self.device.GetCopyableFootprints(&desc, sub, 1, at, Some(&mut f), None, None, Some(&mut total)); + self.device.GetCopyableFootprints( + &desc, + sub, + 1, + at, + Some(&mut f), + None, + None, + Some(&mut total), + ); at = (at + total).next_multiple_of(512); let from = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&up), @@ -785,13 +1241,26 @@ impl Scene { // SAFETY: as above. unsafe { let desc = t.GetDesc(); - let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize }; + let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + 1 + } else { + desc.DepthOrArraySize + }; let planes = if name == "stencil" { 2 } else { 1 }; let mut subs = Vec::new(); for sub in 0..u32::from(layers * desc.MipLevels) * planes { let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); let (mut rows, mut len) = (0, 0); - self.device.GetCopyableFootprints(&desc, sub, 1, 0, Some(&mut f), Some(&mut rows), Some(&mut len), None); + self.device.GetCopyableFootprints( + &desc, + sub, + 1, + 0, + Some(&mut f), + Some(&mut rows), + Some(&mut len), + None, + ); let l = self.open(0); l.ResourceBarrier(&[moved(&t, state, FROM)]); let to = D3D12_TEXTURE_COPY_LOCATION { @@ -806,7 +1275,10 @@ impl Scene { self.wait(); let pitch = f.Footprint.RowPitch as usize; let rows = (0..rows as usize * f.Footprint.Depth as usize) - .map(|r| std::slice::from_raw_parts(self.back.1.add(r * pitch), len as usize).to_vec()) + .map(|r| { + std::slice::from_raw_parts(self.back.1.add(r * pitch), len as usize) + .to_vec() + }) .collect(); subs.push((pitch, rows)); } @@ -841,7 +1313,10 @@ impl Scene { self.give(40, 7 + n); let l = self.open(0); l.ResourceBarrier(&[moved(&self.target, FROM, TARGET)]); - let (rtv, dsv) = (self.rtvs.GetCPUDescriptorHandleForHeapStart(), self.dsvs.GetCPUDescriptorHandleForHeapStart()); + let (rtv, dsv) = ( + self.rtvs.GetCPUDescriptorHandleForHeapStart(), + self.dsvs.GetCPUDescriptorHandleForHeapStart(), + ); l.ClearRenderTargetView(rtv, &[0.1 * n as f32, 0.2, 0.3, 1.0], None); l.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None); self.arguments(&l, COMMON); @@ -858,6 +1333,12 @@ impl Scene { // The second: other constants and another texture in the same // places, and the second texture in the memory of the first. self.show(4000, &self.other); + // Arguments of a mesh draw. + self.constants + .1 + .add(1024) + .cast::<[u32; 3]>() + .write([1, 1, 1]); self.place(0, [-0.9, 0.3, 0.6, 0.6]); self.place(256, [0.3, -0.8, 0.6, 0.5]); self.give(40, 100 + n); @@ -873,6 +1354,26 @@ impl Scene { l.ResourceBarrier(&[moved(&self.one, TO, READ)]); self.arguments(&l, ARGUMENTS); self.quad(&l, 4002, 256, 0); + if let Some((made, signature)) = &self.mesh { + l.SetGraphicsRootSignature(&made.root); + l.SetPipelineState(&made.pso); + let constants = [ + (-0.3f32).to_bits(), + (-0.9f32).to_bits(), + 0.5f32.to_bits(), + 0.4f32.to_bits(), + 4002, + ]; + l.SetGraphicsRoot32BitConstants(0, 5, constants.as_ptr().cast(), 0); + l.ExecuteIndirect( + signature, + 1, + &self.constants.0, + 1024, + None::<&ID3D12Resource>, + 0, + ); + } l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]); // And back, for the next frame. l.ResourceBarrier(&[moved(&self.one, READ, TO)]); @@ -909,7 +1410,9 @@ impl Scene { queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); self.value += 1; queue.Signal(&self.fence, self.value).unwrap(); - self.fence.SetEventOnCompletion(self.value, self.event).unwrap(); + self.fence + .SetEventOnCompletion(self.value, self.event) + .unwrap(); WaitForSingleObject(self.event, INFINITE); if let Some((swap, _)) = &self.swap { swap.Present(0, DXGI_PRESENT(0)).unwrap(); @@ -928,12 +1431,16 @@ impl Scene { let to = |at: u64, size| D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&self.back.0), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(at, size) }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: footprint(at, size), + }, }; let of = |t: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(t), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, }; l.ResourceBarrier(&[moved(&self.image, UAV, FROM)]); l.CopyTextureRegion(&to(0, SIZE), 0, 0, 0, &of(&self.target), None); @@ -943,7 +1450,9 @@ impl Scene { l.Close().unwrap(); self.send(&[&l]); self.wait(); - let at = |from: usize, n: usize| std::slice::from_raw_parts(self.back.1.add(from), n).to_vec(); + let at = |from: usize, n: usize| { + std::slice::from_raw_parts(self.back.1.add(from), n).to_vec() + }; Outcome { still, picture: at(0, (SIZE * 512) as usize), @@ -960,7 +1469,9 @@ fn sub_of(t: &ID3D12Resource, sub: u32) -> D3D12_TEXTURE_COPY_LOCATION { // SAFETY: a borrowed pointer never released. pResource: unsafe { std::mem::transmute_copy(t) }, Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: sub, + }, } } @@ -986,20 +1497,40 @@ fn footprint(at: u64, size: u32) -> D3D12_PLACED_SUBRESOURCE_FOOTPRINT { fn swap_chain(queue: &ID3D12CommandQueue) -> (IDXGISwapChain3, HWND) { // SAFETY: plain creation. unsafe { - let hwnd = - CreateWindowExW(WINDOW_EX_STYLE(0), w!("STATIC"), w!("replay test"), WS_POPUP, 0, 0, 64, 64, None, None, None, None).unwrap(); + let hwnd = CreateWindowExW( + WINDOW_EX_STYLE(0), + w!("STATIC"), + w!("replay test"), + WS_POPUP, + 0, + 0, + 64, + 64, + None, + None, + None, + None, + ) + .unwrap(); let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap(); let desc = DXGI_SWAP_CHAIN_DESC1 { Width: 64, Height: 64, Format: DXGI_FORMAT_R8G8B8A8_UNORM, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, BufferCount: 2, SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, ..Default::default() }; - let chain = factory.CreateSwapChainForHwnd(queue, hwnd, &desc, None, None).unwrap().cast().unwrap(); + let chain = factory + .CreateSwapChainForHwnd(queue, hwnd, &desc, None, None) + .unwrap() + .cast() + .unwrap(); (chain, hwnd) } } @@ -1015,7 +1546,10 @@ fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str) assert_eq!(report.frame_ms.len(), options.loops as usize); assert!(report.median_ms() > 0.0); let (db, same) = report.picture.unwrap(); - assert!(same && db.is_infinite(), "{what}: the picture differs ({db} dB)"); + assert!( + same && db.is_infinite(), + "{what}: the picture differs ({db} dB)" + ); let mut get = |name: &str| { let id = player.named(name).unwrap(); player.contents(id).unwrap().unwrap() @@ -1023,19 +1557,38 @@ fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str) assert_eq!(get("sum"), expected.sum, "{what}: sum"); assert_eq!(rows(&get("image")), expected.image, "{what}: image"); assert_eq!(get("target"), expected.picture, "{what}: target"); - assert!(get("shared") == expected.shared, "{what}: memory the CPU sees"); + assert!( + get("shared") == expected.shared, + "{what}: memory the CPU sees" + ); for still in &expected.still { let id = player.named(still.name).unwrap(); for (sub, (pitch, rows)) in still.subs.iter().enumerate() { let have = player.contents_of(id, sub as u32).unwrap().unwrap(); for (r, row) in rows.iter().enumerate() { - assert_eq!(&have[r * pitch..][..row.len()], &row[..], "{what}: {} subresource {sub} row {r}", still.name); + assert_eq!( + &have[r * pitch..][..row.len()], + &row[..], + "{what}: {} subresource {sub} row {r}", + still.name + ); } } } // Nothing was left out but what another queue ran. - let known = ["submissions,", "waits of the drawing queue", "lists sent to a queue other than"]; - assert!(!report.notes.iter().any(|n| n.contains("recorder:") && !known.iter().any(|k| n.contains(k))), "{what}: {:?}", report.notes); + let known = [ + "submissions,", + "waits of the drawing queue", + "lists sent to a queue other than", + ]; + assert!( + !report + .notes + .iter() + .any(|n| n.contains("recorder:") && !known.iter().any(|k| n.contains(k))), + "{what}: {:?}", + report.notes + ); assert!(report.notes.iter().any(|n| n.contains(known[2]))); report } @@ -1068,82 +1621,213 @@ fn a_frame_is_recorded_and_replayed() { // Something is in the picture. assert!(without.sum.iter().any(|&b| b != 0)); for s in &without.still { - assert!(s.subs.iter().all(|(_, rows)| rows.iter().flatten().any(|&b| b != 0)), "{}", s.name); + assert!( + s.subs + .iter() + .all(|(_, rows)| rows.iter().flatten().any(|&b| b != 0)), + "{}", + s.name + ); } - assert_eq!(without.still.iter().map(|s| s.subs.len()).collect::>(), [15, 3, 2]); - let colors: std::collections::HashSet<[u8; 4]> = - without.picture.chunks_exact(4).map(|c| [c[0], c[1], c[2], c[3]]).collect(); + assert_eq!( + without + .still + .iter() + .map(|s| s.subs.len()) + .collect::>(), + [15, 3, 2] + ); + let colors: std::collections::HashSet<[u8; 4]> = without + .picture + .chunks_exact(4) + .map(|c| [c[0], c[1], c[2], c[3]]) + .collect(); assert!(colors.len() > 30, "{}", colors.len()); // With it: armed at the first present, the fourth frame is captured (a // frame whose lists are all recorded comes first). assert!(!record::on()); let dir = tempfile::tempdir().unwrap(); - let settings = Settings { folder: dir.path().to_owned(), at: At::Frame(1), frames: 1, always: false }; + let settings = Settings { + folder: dir.path().to_owned(), + at: At::Frame(1), + frames: 1, + always: false, + }; let folder = record::start(settings, &device).unwrap(); assert!(record::on()); assert_ne!(table_of(&device), own, "the device is hooked"); assert!( - record::start(Settings { folder: dir.path().to_owned(), at: At::Trigger, frames: 1, always: false }, &device).is_err(), + record::start( + Settings { + folder: dir.path().to_owned(), + at: At::Trigger, + frames: 1, + always: false + }, + &device + ) + .is_err(), "one recorder a process" ); eprintln!("recorder on"); let mut scene = Scene::new(&device, true); eprintln!("scene made"); (0..4).for_each(|n| scene.frame(n)); - assert_eq!(record::finished(), Some(folder.clone()), "see {}", folder.display()); + assert_eq!( + record::finished(), + Some(folder.clone()), + "see {}", + folder.display() + ); let expected = scene.outcome(); // It goes on as it did without the recorder. scene.frame(4); let after = scene.outcome(); - assert!(after == without, "the recorder changed what the program makes"); + assert!( + after == without, + "the recorder changed what the program makes" + ); drop(scene); record::unhook(&device); assert_eq!(table_of(&device), own, "the device is as it was"); - for name in ["frame.bin", "contents.bin", "deltas.bin", "shaders.bin", "present.bin", "notes.txt", "frame-0.png"] { + for name in [ + "frame.bin", + "contents.bin", + "deltas.bin", + "shaders.bin", + "present.bin", + "notes.txt", + "frame-0.png", + ] { assert!(folder.join(name).exists(), "{name}"); } - println!("{}", std::fs::read_to_string(folder.join("notes.txt")).unwrap()); + println!( + "{}", + std::fs::read_to_string(folder.join("notes.txt")).unwrap() + ); - let plain = Options { loops: 3, ..Default::default() }; + let plain = Options { + loops: 3, + ..Default::default() + }; let mut player = Player::load(dir.path(), &plain).unwrap(); check(&mut player, &plain, &expected, "unchanged"); - let detailed = Options { detailed: true, ..plain.clone() }; + let detailed = Options { + detailed: true, + ..plain.clone() + }; let report = check(&mut player, &detailed, &expected, "detailed"); - let count = |kind: &str| report.categories.iter().find(|c| c.0 == kind).map_or(0, |c| c.2); + let count = |kind: &str| { + report + .categories + .iter() + .find(|c| c.0 == kind) + .map_or(0, |c| c.2) + }; assert_eq!(count("argument clamps (ours)"), 3); assert_eq!(count("indirect draws"), 5); + assert_eq!(count("draws"), 1); + let meshes = count("indirect mesh draws"); + println!("{meshes} mesh draws"); + if meshes > 0 { + assert!( + report + .shaders + .iter() + .any(|s| s.2.starts_with("a mesh pipeline (DXIL ")), + "{:?}", + report.shaders + ); + } assert_eq!(count("dispatches"), 6); assert_eq!(count("clears"), 2); - assert!(report.shaders.iter().any(|s| s.2.starts_with("a drawing pipeline (DXIL ")), "{:?}", report.shaders); - let merged = Options { merge_barriers: true, ..plain.clone() }; + assert!( + report + .shaders + .iter() + .any(|s| s.2.starts_with("a drawing pipeline (DXIL ")), + "{:?}", + report.shaders + ); + let merged = Options { + merge_barriers: true, + ..plain.clone() + }; check(&mut player, &merged, &expected, "merged barriers"); - let clamps = Options { skip_clamps: true, ..plain.clone() }; + let clamps = Options { + skip_clamps: true, + ..plain.clone() + }; let report = check(&mut player, &clamps, &expected, "without clamps"); - assert!(report.notes.iter().any(|n| n.contains("3 clamp passes")), "{:?}", report.notes); - let one = Options { one_submit: true, ..plain.clone() }; + assert!( + report.notes.iter().any(|n| n.contains("3 clamp passes")), + "{:?}", + report.notes + ); + let one = Options { + one_submit: true, + ..plain.clone() + }; check(&mut player, &one, &expected, "one submission"); - let hash = Options { skip_hash_passes: true, ..plain.clone() }; - check(&mut player, &hash, &expected, "without hash passes (there are none)"); + let hash = Options { + skip_hash_passes: true, + ..plain.clone() + }; + check( + &mut player, + &hash, + &expected, + "without hash passes (there are none)", + ); // These change what is drawn: they run, and then the frame is as before. - let no_barriers = Options { no_barriers: true, ..plain.clone() }; + let no_barriers = Options { + no_barriers: true, + ..plain.clone() + }; player.run(&no_barriers).unwrap(); - let some = Options { only: Some((0, 1)), ..plain.clone() }; + let some = Options { + only: Some((0, 1)), + ..plain.clone() + }; player.run(&some).unwrap(); - let skip = Options { skip_shaders: vec!["a drawing".into()], ..plain.clone() }; + let skip = Options { + skip_shaders: vec!["a drawing".into()], + ..plain.clone() + }; let report = player.run(&skip).unwrap(); - assert!(!report.picture.unwrap().1, "without its draws the picture is another"); - assert!(report.notes.iter().any(|n| n.contains("1 pipelines match")) && report.notes.iter().any(|n| n.contains("left out 5 commands"))); - let kept = Options { restore: false, ..plain.clone() }; + assert!( + !report.picture.unwrap().1, + "without its draws the picture is another" + ); + assert!( + report.notes.iter().any(|n| n.contains("1 pipelines match")) + && report + .notes + .iter() + .any(|n| n.contains("left out 5 commands")) + ); + let kept = Options { + restore: false, + ..plain.clone() + }; player.run(&kept).unwrap(); check(&mut player, &plain, &expected, "unchanged again"); drop(player); for buffers in [Buffers::Card, Buffers::Pc] { - let o = Options { buffers, ..plain.clone() }; + let o = Options { + buffers, + ..plain.clone() + }; let mut player = Player::load(dir.path(), &o).unwrap(); check(&mut player, &o, &expected, &format!("buffers {buffers:?}")); } - let o = Options { compare: true, merge_barriers: true, loops: 2, ..Default::default() }; + let o = Options { + compare: true, + merge_barriers: true, + loops: 2, + ..Default::default() + }; let both = play::replay(dir.path(), &o).unwrap(); assert_eq!(both.len(), 2); assert!(both.iter().all(|(_, r)| r.picture.unwrap().1)); @@ -1157,9 +1841,17 @@ fn a_frame_is_recorded_and_replayed() { let _ = q.GetMessage(i, None, &mut size); let mut buffer = vec![0u64; size.div_ceil(8)]; let m = buffer.as_mut_ptr().cast::(); - if q.GetMessage(i, Some(m), &mut size).is_ok() && (*m).Severity.0 <= D3D12_MESSAGE_SEVERITY_WARNING.0 { - let text = std::slice::from_raw_parts((*m).pDescription, (*m).DescriptionByteLength); - println!("D3D12 {} {}: {}", (*m).Severity.0, (*m).ID.0, String::from_utf8_lossy(text)); + if q.GetMessage(i, Some(m), &mut size).is_ok() + && (*m).Severity.0 <= D3D12_MESSAGE_SEVERITY_WARNING.0 + { + let text = + std::slice::from_raw_parts((*m).pDescription, (*m).DescriptionByteLength); + println!( + "D3D12 {} {}: {}", + (*m).Severity.0, + (*m).ID.0, + String::from_utf8_lossy(text) + ); } } } diff --git a/crates/victory-gpu/tests/replay_big.rs b/crates/victory-gpu/tests/replay_big.rs index 34a9b95..9f60399 100644 --- a/crates/victory-gpu/tests/replay_big.rs +++ b/crates/victory-gpu/tests/replay_big.rs @@ -3,7 +3,8 @@ //! thousands of textures and buffers, a view heap of 1.5 million slots, 30 //! submissions of 40,000 calls. //! -//! `BIG_TEXTURES` (17000) and `BIG_FOLDER` (a temporary one) change it. +//! `BIG_TEXTURES` (17000), `BIG_CARD` (600 buffers of 1 MB in the card's +//! memory) and `BIG_FOLDER` (a temporary one) change it. #![cfg(all(windows, feature = "diagnostics"))] use std::mem::ManuallyDrop; @@ -24,12 +25,18 @@ const VIEWS: u32 = 1_500_000; fn buffer(device: &ID3D12Device, kind: u32, size: u64) -> (ID3D12Resource, *mut u8) { let (heap, state, flags) = match kind { 0 => ( - D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ), 1 => ( - D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_UPLOAD, + ..Default::default() + }, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE, ), @@ -50,7 +57,10 @@ fn buffer(device: &ID3D12Device, kind: u32, size: u64) -> (ID3D12Resource, *mut Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() @@ -59,7 +69,9 @@ fn buffer(device: &ID3D12Device, kind: u32, size: u64) -> (ID3D12Resource, *mut let mut data = std::ptr::null_mut(); // SAFETY: plain creation and mapping. unsafe { - device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut made).unwrap(); + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut made) + .unwrap(); let made = made.unwrap(); if kind > 0 { made.Map(0, None, Some(&mut data)).unwrap(); @@ -72,7 +84,11 @@ fn buffer(device: &ID3D12Device, kind: u32, size: u64) -> (ID3D12Resource, *mut } } -fn barrier(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { +fn barrier( + res: &ID3D12Resource, + before: D3D12_RESOURCE_STATES, + after: D3D12_RESOURCE_STATES, +) -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Anonymous: D3D12_RESOURCE_BARRIER_0 { @@ -88,6 +104,14 @@ fn barrier(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RES } } +/// A number from the environment. +fn number(name: &str, otherwise: usize) -> usize { + std::env::var(name) + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(otherwise) +} + struct Big { device: ID3D12Device, queue: ID3D12CommandQueue, @@ -105,7 +129,10 @@ struct Big { impl Big { fn new(device: &ID3D12Device, textures: usize) -> Big { let texture = |size: u32, flags, state| { - let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: u64::from(size), @@ -113,24 +140,45 @@ impl Big { DepthOrArraySize: 1, MipLevels: if size == 256 { 9 } else { 1 }, Format: DXGI_FORMAT_R8G8B8A8_UNORM, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Flags: flags, ..Default::default() }; let mut made: Option = None; // SAFETY: plain creation. - unsafe { device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut made).unwrap() }; + unsafe { + device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + state, + None, + &mut made, + ) + .unwrap() + }; made.unwrap() }; // SAFETY: plain creation; slots of the heap just made. unsafe { let queue: ID3D12CommandQueue = device - .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) .unwrap(); let lists = (0..SUBMITS) .map(|_| { - let a: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); - let l: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a, None).unwrap(); + let a: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .unwrap(); + let l: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a, None) + .unwrap(); l.Close().unwrap(); (a, l) }) @@ -143,26 +191,47 @@ impl Big { NodeMask: 0, }) .unwrap(); - let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let step = device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; let start = views.GetCPUDescriptorHandleForHeapStart().ptr; let textures: Vec = (0..textures) - .map(|_| texture(256, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE)) + .map(|_| { + texture( + 256, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE, + ) + }) .collect(); for i in 0..VIEWS as usize { - let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start + i * step }; + let at = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start + i * step, + }; device.CreateShaderResourceView(&textures[i % textures.len()], None, at); } - let shared: Vec<(ID3D12Resource, *mut u8)> = (0..1000).map(|_| buffer(device, 2, 1 << 20)).collect(); + let shared: Vec<(ID3D12Resource, *mut u8)> = + (0..1000).map(|_| buffer(device, 2, 1 << 20)).collect(); for (i, (b, _)) in shared.iter().enumerate() { let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, ViewDimension: D3D12_SRV_DIMENSION_BUFFER, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { - Buffer: D3D12_BUFFER_SRV { NumElements: 1 << 18, Flags: D3D12_BUFFER_SRV_FLAG_RAW, ..Default::default() }, + Buffer: D3D12_BUFFER_SRV { + NumElements: 1 << 18, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + ..Default::default() + }, }, }; - device.CreateShaderResourceView(b, Some(&desc), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start + i * step }); + device.CreateShaderResourceView( + b, + Some(&desc), + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start + i * step, + }, + ); } Big { device: device.clone(), @@ -171,11 +240,17 @@ impl Big { value: 0, lists, _textures: textures, - card: (0..600).map(|_| buffer(device, 0, 1 << 20).0).collect(), + card: (0..number("BIG_CARD", 600)) + .map(|_| buffer(device, 0, 1 << 20).0) + .collect(), shared, upload: (0..1000).map(|_| buffer(device, 1, 1 << 20)).collect(), views, - target: texture(1024, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE), + target: texture( + 1024, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + ), } } } @@ -194,6 +269,21 @@ impl Big { } fn frame(&mut self, n: usize) { + if n == 0 { + // Nothing in the card's buffers is all zero, as in a title's. + // SAFETY: a list whose last run has finished; live buffers. + unsafe { + let (a, l) = &self.lists[0]; + a.Reset().unwrap(); + l.Reset(a, None).unwrap(); + for (i, card) in self.card.iter().enumerate() { + l.CopyBufferRegion(card, 0, &self.upload[i % self.upload.len()].0, 0, 1 << 20); + } + l.Close().unwrap(); + self.queue.ExecuteCommandLists(&[Some(l.cast().unwrap())]); + } + self.wait(); + } for s in 0..SUBMITS { // SAFETY: lists whose last run has finished; mappings written // inside their bounds. @@ -206,8 +296,16 @@ impl Big { let card = &self.card[(i * 7 + s) % self.card.len()]; let from = &self.upload[(i + s * 31) % self.upload.len()].0; l.CopyBufferRegion(card, (i % 1000 * 1000) as u64 & !3, from, 0, 256); - l.ResourceBarrier(&[barrier(card, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); - l.ResourceBarrier(&[barrier(card, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST)]); + l.ResourceBarrier(&[barrier( + card, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + l.ResourceBarrier(&[barrier( + card, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); l.SetMarker(1, None, 0); } l.Close().unwrap(); @@ -231,8 +329,10 @@ fn a_frame_of_a_titles_size() { // SAFETY: plain creation. unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).unwrap() }; let device = device.unwrap(); - let textures = std::env::var("BIG_TEXTURES").ok().and_then(|v| v.parse().ok()).unwrap_or(17_000); - let timed = |what: &str, began: Instant| println!("{what}: {:.1} ms", began.elapsed().as_secs_f64() * 1e3); + let textures = number("BIG_TEXTURES", 17_000); + let timed = |what: &str, began: Instant| { + println!("{what}: {:.1} ms", began.elapsed().as_secs_f64() * 1e3) + }; let began = Instant::now(); { let mut big = Big::new(&device, textures); @@ -245,7 +345,12 @@ fn a_frame_of_a_titles_size() { } let dir = tempfile::tempdir().unwrap(); let folder = std::env::var_os("BIG_FOLDER").map_or(dir.path().to_owned(), Into::into); - let settings = Settings { folder, at: At::Frame(4), frames: 1, always: false }; + let settings = Settings { + folder, + at: At::Frame(4), + frames: 1, + always: false, + }; let folder = record::start(settings, &device).unwrap(); let began = Instant::now(); let mut big = Big::new(&device, textures); @@ -253,17 +358,39 @@ fn a_frame_of_a_titles_size() { for n in 0..8 { let began = Instant::now(); big.frame(n); - timed(["frame", "frame, lists recorded", "frame, captured", "frame, after"][[0, 0, 0, 0, 1, 1, 2, 3][n]], began); + timed( + [ + "frame", + "frame, lists recorded", + "frame, captured", + "frame, after", + ][[0, 0, 0, 0, 1, 1, 2, 3][n]], + began, + ); } assert_eq!(record::finished(), Some(folder.clone())); drop(big); record::unhook(&device); - println!("{}", std::fs::read_to_string(folder.join("notes.txt")).unwrap()); + println!( + "{}", + std::fs::read_to_string(folder.join("notes.txt")).unwrap() + ); for f in std::fs::read_dir(&folder).unwrap().flatten() { - println!("{:>8} MB {}", f.metadata().unwrap().len() >> 20, f.file_name().to_string_lossy()); + println!( + "{:>8} MB {}", + f.metadata().unwrap().len() >> 20, + f.file_name().to_string_lossy() + ); } let began = Instant::now(); - let reports = play::replay(&folder, &Options { loops: 3, ..Default::default() }).unwrap(); + let reports = play::replay( + &folder, + &Options { + loops: 3, + ..Default::default() + }, + ) + .unwrap(); timed("loaded and replayed", began); for (what, r) in &reports { println!("{}", r.text(what)); diff --git a/docs/replay.md b/docs/replay.md new file mode 100644 index 0000000..7333348 --- /dev/null +++ b/docs/replay.md @@ -0,0 +1,102 @@ +# Recording a frame and running it again + +A diagnostics build can write down one frame's D3D12 work (what the host +layer sends to the card, and the memory it reads) and run it again without +the title, to see where the card's time goes and to try changes in seconds. +Code: `crates/victory-gpu/src/replay`. + +## Recording + +Off unless `VICTORY_RECORD` is set. Build with +`cargo build --locked --profile diag -p victory --features diagnostics`. + +| variable | meaning | +|---|---| +| `VICTORY_RECORD=` | on; the capture goes to `\capture-` (outside the repository) | +| `VICTORY_RECORD_AT=` or `f` | when: seconds after the device was made, or a number of presents. Unset: only the trigger file | +| file `\go` | when it appears, the capture starts (always watched) | +| `VICTORY_RECORD_FRAMES=` | frames to capture (1) | +| `VICTORY_RECORD_ALWAYS=1` | record lists from the start: needed only if notes say lists were not recorded (a title that submits old lists again) | + +At the time given, lists are recorded for a few frames, until a frame's lists +were all recorded; the next frame is captured: everything sent to the drawing +queue between two presents (the first may be the swap chain's own work for +the frame before). One capture per process. At the frame's first submission +the card is drained and its memory copied out; before each later one the card +is drained again and what the CPU changed is written. The title stands still +meanwhile. `frame recorder: the frame is captured` in the log and `frame.bin` +in the folder mean it is done; `failed.txt` that it failed. + +**Read `notes.txt`**: everything that could not be recorded is listed there +(and in every replay's report). Only the line with the totals, waits of the +drawing queue and lists of another queue (the relay's copies) are expected. + +Measured on a made-up frame of a title's size (12,000 resources, 1.5 million +views, 30 submissions, 40,000 calls): a frame takes 3-10 ms more with the +recorder on, the capture stands still for 5.4 s and is 9 GB (8 GB of the card's +memory at 2.3 GB/s, 1 GB the CPU wrote). The recorder holds a copy of the +memory both sides see that the frame reads, and 1 GB or more of read-back +buffers, until it is done. + +## Running it + + victory replay [--loops 5] [--timing detailed] [experiments] + +`` is the one given as `VICTORY_RECORD` (its last capture) or a +capture. Each loop puts back what the one before changed and sends the frame +without waiting between submissions. Reported, from timestamps on the card: +the frame (first list's start to last list's end), each submission, copies +that stand for what the CPU wrote between submissions (not the title's cost), +and gaps. With `--timing detailed`, each command: sums by kind and the +costliest pipelines with the names the runtime logs and their DXIL hashes +(blake3). A command's time is from the end of the one before to its own end: +draws overlap, so it is a share of the list, not a cost alone; the extra +timestamps cost a little too. The picture goes to `replay.png` and is compared +with the presented one. + +| switch | does | +|---|---| +| `--compare` | runs the frame unchanged first and prints the difference | +| `--skip-clamps` | no argument clamps and no barriers of their scratch buffers; draws read arguments kept from a first run | +| `--skip-hash-passes` | no compare/rehash passes over card buffers | +| `--no-barriers` | no unordered-access barriers | +| `--merge-barriers` | joins barrier calls with no work between them | +| `--buffers vram` / `sysmem` | all buffers in the card's / the PC's memory | +| `--one-submit` | one `ExecuteCommandLists`, with a full wait between the former ones | +| `--only 3..7` | runs these lists; of the others only barriers | +| `--skip-shader ` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) | +| `--no-restore` | leaves what a loop changed | +| `--debug-layer` | D3D12's debug layer; its errors in the report | + +Use the median of several loops; the first is slower. An experiment that +leaves out waits or work can draw another picture and, with wild data, lose +the device: save work in other programs first. Do not run the title at the +same time. + +## Limits + +- Not recorded, but reported when used: reserved (tiled) resources, bundles, + ray tracing, render passes, enhanced barriers, predication, stream output, + `ClearUnorderedAccessView`, shading rate, newer creation methods + (`CreateCommittedResource1` and on). +- Not kept: contents of multisampled textures, of textures in memory the CPU + sees, and of texture levels over 256 MB; resources of other queues' work. +- Texture states come from the barriers seen. A resource that overlaps the + one last used (aliasing) is taken as without contents. +- Addresses in memory are not rewritten: indirect arguments with addresses + (vertex buffers, root views) are reported, and would be wrong. Descriptors + and root arguments are. +- Views replaced during the frame get a heap of their own per submission in + the replay (64 MB for two million views). +- Upload heaps become custom write-combined ones in the replay, as the card + writes what the CPU wrote. +- What the CPU changes in memory both see is taken before each submission, by + pages of 4 KiB, of what that submission reads of it (all of a buffer that a + descriptor names). Pages the card wrote there are part of it: they count as + copies, and set the card's own results to the recorded ones. +- The card's clocks are the system's: other programs on the card change the + times. + +Tests: `cargo test -p victory-gpu --features diagnostics` (`tests/replay.rs` +runs a small program and compares every byte; `VICTORY_TEST_D3D_DEBUG=1` adds +the debug layer) and `tests/replay_big.rs` (`--ignored`). From 66afb2b4cbe8aa09d90e3999e91d2f0c4b043e7e Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 20:28:42 -0600 Subject: [PATCH 158/445] Only changed dwords go back into title memory; cheap safe copies; title's own arguments; more shader forms Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/main.rs | 7 +- apps/victory/src/shader.rs | 2 +- apps/victory/src/translate.rs | 2 +- crates/victory-gpu/src/host.rs | 18 ++ crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/pipeline.rs | 2 +- crates/victory-gpu/src/safecopy.rs | 359 +++++++++++++++++++++++ crates/victory-gpu/src/shadow.rs | 127 +++++++- crates/victory-gpu/src/watch.rs | 23 +- crates/victory-hle/src/modules/kernel.rs | 78 ++++- crates/victory-hle/src/runtime.rs | 12 + crates/victory-shader/src/dxbc.rs | 2 + crates/victory-shader/src/emit/lower.rs | 96 +++++- crates/victory-shader/src/emit/mod.rs | 1 + crates/victory-shader/src/native.rs | 141 ++++++++- crates/victory-shader/src/resource.rs | 130 +++++++- 16 files changed, 973 insertions(+), 29 deletions(-) create mode 100644 crates/victory-gpu/src/safecopy.rs diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index a04655c..2aafa3a 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -179,8 +179,11 @@ fn main() -> Result<()> { strict, execute, console, - title_args: _, - } => run::run(&exe, unimplemented, strict, execute, console), + title_args, + } => { + victory_hle::runtime::set_title_args(title_args); + run::run(&exe, unimplemented, strict, execute, console) + } Command::Config => show_config(), } } diff --git a/apps/victory/src/shader.rs b/apps/victory/src/shader.rs index 49180ea..1c6e002 100644 --- a/apps/victory/src/shader.rs +++ b/apps/victory/src/shader.rs @@ -101,7 +101,7 @@ pub fn run(paths: Vec, verbose: bool, disasm: bool) -> Result<()> { }; found_here += 1; t.containers += 1; - let dxil = container.part(FourCC::DXIL); + let dxil = container.part(FourCC::DXIL).or(container.part(FourCC::ACCC)); t.with_dxil_part += usize::from(dxil.is_some()); let program = dxil.and_then(|p| DxilProgram::parse(p.data).ok()); let mut listing = Vec::new(); diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index ddc2bd3..c817360 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -400,7 +400,7 @@ fn translate( let Ok(container) = Container::parse(&bytes) else { return t.fail("no DXIL part (SM5 or older)".into(), example); }; - let Some(dxil) = container.part(FourCC::DXIL).map(|p| p.data) else { + let Some(dxil) = container.part(FourCC::DXIL).or(container.part(FourCC::ACCC)).map(|p| p.data) else { return t.fail("no DXIL part (SM5 or older)".into(), example); }; // `~`: the hash of the code alone; containers that differ only around diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 27853d6..182d250 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -5824,6 +5824,11 @@ pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool { fn read(src: *const u8, dst: *mut u8, len: usize) -> bool { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; + if crate::safecopy::on() { + // SAFETY: the destination is mapped writable memory of `len` bytes; + // a source page that is not there fails the copy. + return unsafe { crate::safecopy::copy(dst, src, len) }; + } let mut done = 0; // SAFETY: the destination is mapped writable memory of `len` bytes; the // kernel checks the source. @@ -5863,6 +5868,11 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { let direct = direct_writes(); let write = |at: usize, n: usize| { let from = src.wrapping_add(at - dst as usize); + if crate::safecopy::on() { + // SAFETY: the source is ours; a destination page that is not + // there, or not writable, fails the copy. + return unsafe { crate::safecopy::copy(at as *mut u8, from, n) }; + } let mut done = 0; if direct { // SAFETY: as below; the kernel checks the destination and @@ -6227,6 +6237,14 @@ impl Meter { #[cfg(feature = "diagnostics")] { log_blame(frames); + let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames); + tracing::info!( + "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps", + put[0], + put[1], + put[2] / 1e6, + put[3] + ); 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/lib.rs b/crates/victory-gpu/src/lib.rs index 911e8fb..99c467b 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -45,6 +45,8 @@ pub mod queue; pub mod resource; pub mod root; #[cfg(windows)] +mod safecopy; +#[cfg(windows)] mod sampler; #[cfg(windows)] pub mod shader_cache; diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 60ed05c..1efa54c 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -178,7 +178,7 @@ fn translate(container: &[u8]) -> Result { // The translation depends on it (a view index past a capped heap). crate::descriptor::host::probe_view_limit(); let c = Container::parse(container).map_err(|e| e.to_string())?; - let programs = match c.part(FourCC::DXIL) { + let programs = match c.part(FourCC::DXIL).or(c.part(FourCC::ACCC)) { Some(part) => victory_shader::native_programs(part.data).map_err(|e| e.to_string())?, None => Vec::new(), }; diff --git a/crates/victory-gpu/src/safecopy.rs b/crates/victory-gpu/src/safecopy.rs new file mode 100644 index 0000000..24eb646 --- /dev/null +++ b/crates/victory-gpu/src/safecopy.rs @@ -0,0 +1,359 @@ +//! Copies between our memory and the title's that fail instead of faulting. +//! +//! Title memory may be unmapped, remapped or made read-only by the title's +//! other threads while we copy it, so copies went through the kernel +//! (`ReadProcessMemory`, `NtWriteVirtualMemory`), which reports a missing +//! page instead of faulting: some 35,000 calls a frame, each of which locks +//! the pages it copies, 39 ms of kernel time on the submitting thread alone. +//! +//! [`copy`] is one `rep movsb`. A fault in it is taken by the handler of +//! [`crate::watch`] (`on_write`, the first in the process), which opens a +//! block we guard ourselves and lets the copy go on, and otherwise sends it +//! to its failing exit. `VICTORY_SAFE_COPY=0`: through the kernel, as before. + +use std::sync::OnceLock; + +std::arch::global_asm!( + ".globl victory_safe_copy", + ".globl victory_safe_copy_at", + ".globl victory_safe_copy_after", + ".globl victory_safe_copy_failed", + // rcx destination, rdx source, r8 bytes; eax: whether all were copied. + // A leaf that leaves the stack alone (the two registers it must give + // back are kept in volatile ones), so a stack walk through it works. + "victory_safe_copy:", + "mov r10, rsi", + "mov r11, rdi", + "mov rdi, rcx", + "mov rsi, rdx", + "mov rcx, r8", + "victory_safe_copy_at:", + "rep movsb", + "victory_safe_copy_after:", + "mov eax, 1", + "mov rsi, r10", + "mov rdi, r11", + "ret", + "victory_safe_copy_failed:", + "xor eax, eax", + "mov rsi, r10", + "mov rdi, r11", + "ret", + ".globl victory_safe_put", + ".globl victory_safe_put_at", + ".globl victory_safe_put_after", + ".globl victory_safe_put_failed", + // rcx destination, rdx what was there, r8 what is to be there, r9 blocks + // of eight dwords: stores the dwords in which the two differ, and no + // other byte. eax: whether all could be stored. + "victory_safe_put:", + "test r9, r9", + "jz 4f", + "vpcmpeqd ymm3, ymm3, ymm3", + "2:", + "vmovdqu ymm1, ymmword ptr [r8]", + "vpcmpeqd ymm2, ymm1, ymmword ptr [rdx]", + "vmovmskps eax, ymm2", + "cmp eax, 255", + "je 3f", + "vpxor ymm2, ymm2, ymm3", + "victory_safe_put_at:", + "vpmaskmovd ymmword ptr [rcx], ymm2, ymm1", + "victory_safe_put_after:", + "nop", + "3:", + "add rcx, 32", + "add rdx, 32", + "add r8, 32", + "dec r9", + "jnz 2b", + "vzeroupper", + "4:", + "mov eax, 1", + "ret", + "victory_safe_put_failed:", + "vzeroupper", + "xor eax, eax", + "ret", +); + +unsafe extern "system" { + fn victory_safe_copy(dst: *mut u8, src: *const u8, len: usize) -> u32; + fn victory_safe_copy_at(); + fn victory_safe_copy_after(); + fn victory_safe_copy_failed(); + fn victory_safe_put(dst: *mut u8, was: *const u8, now: *const u8, blocks: usize) -> u32; + fn victory_safe_put_at(); + fn victory_safe_put_after(); + fn victory_safe_put_failed(); +} + +/// Puts `now` at `dst` where it differs from `was`, whole dwords (as `dst` +/// is aligned) and not a byte beside them: other threads may be writing +/// those. At the ends, single bytes of a dword only partly in the stretch. +/// False if a page could not be written; then some may have been. +/// +/// # Safety +/// As [`copy`]'s. +pub(crate) unsafe fn put_changed(dst: *mut u8, was: &[u8], now: &[u8]) -> bool { + assert_eq!(was.len(), now.len()); + let n = now.len(); + let head = dst.addr().wrapping_neg() & 3; + let head = head.min(n); + let blocks = (n - head) / 32; + let tail = head + blocks * 32; + let mut all = true; + if blocks > 0 { + // SAFETY: the two slices hold the blocks; the destination's faults + // leave through the failing exit. + all &= unsafe { victory_safe_put(dst.add(head), was[head..].as_ptr(), now[head..].as_ptr(), blocks) != 0 }; + } + let single = |from: usize, to: usize| { + let mut all = true; + let mut i = from; + while i < to { + // A whole aligned dword, or the bytes there are of one. + let len = (4 - (dst.addr() + i) % 4).min(to - i); + if was[i..i + len] != now[i..i + len] { + // SAFETY: inside the stretch. + all &= unsafe { copy(dst.add(i), now[i..].as_ptr(), len) }; + } + i += len; + } + all + }; + all &= single(0, head); + all &= single(tail, n); + all +} + +/// Whether copies are made here and not by the kernel. +pub(crate) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var_os("VICTORY_SAFE_COPY").is_none_or(|v| v != "0"); + if on { + crate::watch::install(); + } + on + }) +} + +/// Copies `len` bytes. False if a page of the source cannot be read or one +/// of the destination cannot be written; then some of the bytes may have +/// been copied. +/// +/// # Safety +/// Of the two ranges, what is not title memory must be valid, and no Rust +/// reference may cover the destination. [`on`] must have been asked. +pub(crate) unsafe fn copy(dst: *mut u8, src: *const u8, len: usize) -> bool { + // SAFETY: a fault on either side leaves through the failing exit + // ([`failing_exit`]); the rest is the caller's. + unsafe { victory_safe_copy(dst, src, len) != 0 } +} + +/// For the fault handler: where a fault at instruction `at` is to go on, if +/// it is [`copy`]'s. +pub(crate) fn failing_exit(at: usize) -> Option { + let (from, to) = (victory_safe_copy_at as *const () as usize, victory_safe_copy_after as *const () as usize); + if (from..to).contains(&at) { + return Some(victory_safe_copy_failed as *const () as usize); + } + let (from, to) = (victory_safe_put_at as *const () as usize, victory_safe_put_after as *const () as usize); + (from..to).contains(&at).then_some(victory_safe_put_failed as *const () as usize) +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE, VirtualAlloc, + VirtualFree, VirtualProtect, + }; + + struct Pages(*mut u8, usize); + + impl Pages { + fn new(len: usize) -> Pages { + // SAFETY: plain allocation. + let at = unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; + assert!(!at.is_null()); + Pages(at.cast(), len) + } + fn fill(&self) { + for i in 0..self.1 { + // SAFETY: inside the allocation. + unsafe { self.0.add(i).write((i * 31 + 7) as u8) }; + } + } + } + + impl Drop for Pages { + fn drop(&mut self) { + // SAFETY: our allocation. + unsafe { VirtualFree(self.0.cast(), 0, MEM_RELEASE) }; + } + } + + #[test] + fn copies_every_length_and_alignment() { + assert!(on()); + let (a, b) = (Pages::new(1 << 16), Pages::new(1 << 16)); + a.fill(); + for len in [0usize, 1, 3, 4, 8, 31, 64, 255, 4095, 4096, 4097, 60_000] { + for (da, sa) in [(0usize, 0usize), (1, 0), (0, 3), (5, 2)] { + // SAFETY: inside the two allocations. + unsafe { + std::ptr::write_bytes(b.0, 0xEE, b.1); + assert!(copy(b.0.add(da), a.0.add(sa), len)); + let (to, from) = (std::slice::from_raw_parts(b.0, b.1), std::slice::from_raw_parts(a.0, a.1)); + assert_eq!(to[da..da + len], from[sa..sa + len]); + assert!(to[..da].iter().chain(&to[da + len..]).all(|&x| x == 0xEE)); + } + } + } + } + + /// The dwords that changed are stored, and no byte of any other, at + /// every alignment and length; a page that is not there fails. + #[test] + fn only_changed_dwords_are_put() { + assert!(on()); + let pages = Pages::new(3 << 12); + for at in [0usize, 1, 2, 3, 4, 13, 4090] { + for len in [0usize, 1, 3, 4, 5, 31, 32, 33, 64, 100, 1000, 4096] { + let was: Vec = (0..len).map(|i| (i * 13 + 1) as u8).collect(); + for step in [1usize, 5, 17, 64, 10_000] { + let mut now = was.clone(); + for i in (0..len).step_by(step) { + now[i] ^= 0x5A; + } + // Other threads changed everything meanwhile. + // SAFETY: inside the allocation. + unsafe { + std::ptr::write_bytes(pages.0, 0xC3, pages.1); + assert!(put_changed(pages.0.add(at), &was, &now)); + let there = std::slice::from_raw_parts(pages.0, pages.1); + let base = pages.0.addr(); + for (k, &byte) in there.iter().enumerate() { + let expect = if (at..at + len).contains(&k) { + let dword = (base + k) / 4; + let changed = (0..len).any(|i| now[i] != was[i] && (base + at + i) / 4 == dword); + if changed { now[k - at] } else { 0xC3 } + } else { + 0xC3 + }; + if byte != expect { + panic!("at {at} len {len} step {step} byte {k}: {byte:#x}, not {expect:#x}"); + } + if k > at + len + 64 { + break; + } + } + } + } + } + } + // SAFETY: pages of our allocation. + unsafe { + VirtualFree(pages.0.add(4096).cast(), 4096, MEM_DECOMMIT); + let (was, now) = (vec![0u8; 8192], vec![1u8; 8192]); + assert!(!put_changed(pages.0, &was, &now)); + // Nothing differs on the page that is not there: nothing fails. + let mut now = was.clone(); + now[0] = 1; + assert!(put_changed(pages.0, &was, &now)); + } + } + + /// What the copies cost (ignored: a measurement): 64 KiB pieces of + /// scattered memory into a buffer the card reads, by the kernel and here. + #[test] + #[ignore] + fn copy_costs() { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + assert!(on()); + let Some(host) = crate::host::host() else { return }; + const N: usize = 128 << 20; + let from = Pages::new(N); + from.fill(); + let (_buffer, shared) = host.shared_buffer(N as u64).expect("a shared buffer"); + let plain = Pages::new(N); + plain.fill(); + for (what, to) in [("a buffer the card reads", shared), ("plain memory", plain.0)] { + for piece in [256usize, 4 << 10, 64 << 10] { + let count = (N / piece).min(4096); + // A different, scattered piece each time. + let at = |i: usize| (i * 7919 % (N / piece)) * piece; + let time = |f: &dyn Fn(usize) -> bool| { + let mut best = f64::MAX; + for _ in 0..5 { + let t = std::time::Instant::now(); + for i in 0..count { + assert!(f(at(i))); + } + best = best.min(t.elapsed().as_secs_f64()); + } + (best * 1e6 / count as f64, count as f64 * piece as f64 / best / 1e9) + }; + // SAFETY: inside the buffers. + let kernel = time(&|o| unsafe { + let mut done = 0; + ReadProcessMemory(GetCurrentProcess(), from.0.add(o).cast(), to.add(o).cast(), piece, &mut done) != 0 + }); + // SAFETY: as above. + let here = time(&|o| unsafe { copy(to.add(o), from.0.add(o), piece) }); + // SAFETY: as above. + let std_copy = time(&|o| unsafe { + std::ptr::copy_nonoverlapping(from.0.add(o), to.add(o), piece); + true + }); + println!( + "{piece:>6} bytes into {what}: kernel {:.2} us ({:.1} GB/s), rep movsb {:.2} us ({:.1} GB/s), memcpy {:.2} us ({:.1} GB/s)", + kernel.0, kernel.1, here.0, here.1, std_copy.0, std_copy.1 + ); + } + } + } + + /// Missing, forbidden and read-only pages: the copy fails, at any byte, + /// and the process goes on. + #[test] + fn faults_are_failures() { + assert!(on()); + let (a, b) = (Pages::new(3 << 12), Pages::new(3 << 12)); + a.fill(); + let mut old = 0; + // SAFETY: pages of our allocations. + unsafe { + assert!(copy(b.0, a.0, b.1)); + VirtualProtect(a.0.add(4096).cast(), 4096, PAGE_NOACCESS, &mut old); + assert!(!copy(b.0, a.0, b.1)); + assert!(copy(b.0, a.0, 4096)); + assert!(!copy(b.0, a.0.add(8191), 1)); + assert!(copy(b.0, a.0.add(8192), 4096)); + VirtualProtect(a.0.add(4096).cast(), 4096, PAGE_READWRITE, &mut old); + VirtualFree(a.0.add(8192).cast(), 4096, MEM_DECOMMIT); + assert!(!copy(b.0, a.0, b.1)); + VirtualProtect(b.0.add(4096).cast(), 4096, PAGE_READONLY, &mut old); + assert!(!copy(b.0, a.0, 8192)); + assert!(!copy(std::ptr::without_provenance_mut(0x10), a.0, 4)); + assert!(!copy(b.0, std::ptr::without_provenance(usize::MAX - 7), 4)); + VirtualProtect(b.0.add(4096).cast(), 4096, PAGE_READWRITE, &mut old); + } + // Many faults, on several threads at once. + let at = a.0 as usize; + std::thread::scope(|s| { + for _ in 0..4 { + s.spawn(move || { + let mut to = [0u8; 64]; + for _ in 0..500 { + // SAFETY: a decommitted page and our own buffer. + assert!(!unsafe { copy(to.as_mut_ptr(), (at + 8192) as *const u8, 64) }); + } + }); + } + }); + } +} diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 997765e..68817e0 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1409,9 +1409,114 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { runs } +/// Whether what shaders wrote goes into title memory run by run +/// ([`put_changed`]; on by default, `VICTORY_EXACT_BACK=0` writes the whole +/// stretch from the first changed byte to the last, as before). +fn exact_back() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_EXACT_BACK").is_none_or(|v| v != "0")) +} + +/// Since the last frame-rate line: pieces put back by [`put_changed`], the +/// writes they took, the bytes written, and the pieces whose runs were +/// joined over bytes that had not changed. +pub(crate) static PUT: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +/// The dwords (of title memory from `at` on) where `merged` differs from +/// `title`, as (offset, bytes) in order, joined where at most `gap` bytes +/// lie between. +fn dword_runs(at: usize, title: &[u8], merged: &[u8], gap: usize) -> Vec<(usize, usize)> { + let mut runs: Vec<(usize, usize)> = Vec::new(); + for (from, n) in changed_runs(merged, title) { + // Shaders write dwords: the whole of each. + let lo = ((at + from) & !3).max(at) - at; + let hi = ((at + from + n + 3) & !3).min(at + title.len()) - at; + match runs.last_mut() { + Some((a, len)) if lo <= *a + *len + gap => *len = (*len).max(hi - *a), + _ => runs.push((lo, hi - lo)), + } + } + runs +} + +/// 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 +/// byte to the last was: between the read and the write the title's own +/// threads, or data streamed in, may have written the bytes between (a heap +/// holds what shaders write beside what the CPU does), and those writes were +/// undone. Beside running title threads (the relay) that is a piece of +/// memory going back in time now and then: runs pool1, blame1 and seriess2 +/// ended in the title decoding garbage. +/// +/// shortcut: a piece with very many runs has them joined over small gaps, +/// where the old race is left. +fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { + crate::watch::landing(at, title.len()); + if !exact_back() { + crate::host::write_mapped(at as *mut u8, merged.as_ptr(), merged.len()); + return merged.len(); + } + if crate::safecopy::on() { + PUT[0].fetch_add(1, Ordering::Relaxed); + PUT[2].fetch_add(merged.len() as u64, Ordering::Relaxed); + // SAFETY: title memory; a page of it that is not there fails the + // put, and the rest is put page by page. + if unsafe { crate::safecopy::put_changed(at as *mut u8, title, merged) } { + return merged.len(); + } + let mut from = 0; + while from < merged.len() { + let n = (4096 - (at + from) % 4096).min(merged.len() - from); + // SAFETY: as above. + unsafe { crate::safecopy::put_changed((at + from) as *mut u8, &title[from..from + n], &merged[from..from + n]) }; + from += n; + } + return merged.len(); + } + let mut runs = dword_runs(at, title, merged, 0); + if runs.len() > 64 { + runs = dword_runs(at, title, merged, 32); + PUT[3].fetch_add(1, Ordering::Relaxed); + } + let mut written = 0; + for &(from, n) in &runs { + crate::host::write_mapped((at + from) as *mut u8, merged[from..].as_ptr(), n); + written += n; + } + PUT[0].fetch_add(1, Ordering::Relaxed); + PUT[1].fetch_add(runs.len() as u64, Ordering::Relaxed); + PUT[2].fetch_add(written as u64, Ordering::Relaxed); + written +} + #[cfg(test)] mod merge_tests { - use super::changed_runs; + use super::{changed_runs, dword_runs}; + + /// Whole dwords around every changed byte and no other, whatever the + /// alignment; small gaps joined only when asked. + #[test] + fn dword_runs_hold_the_dwords_that_changed() { + let title: Vec = (0..200u32).map(|i| (i * 7 + 3) as u8).collect(); + for at in [0x1000usize, 0x1001, 0x1002, 0x1003] { + for changes in [vec![0], vec![199], vec![5, 6], vec![8, 12, 40, 41, 43, 120]] { + let mut merged = title.clone(); + for &c in &changes { + merged[c] ^= 0x55; + } + let runs = dword_runs(at, &title, &merged, 0); + let held: Vec = runs.iter().flat_map(|&(a, n)| a..a + n).collect(); + let mut expect: Vec = (0..200).filter(|i| changes.iter().any(|c| (at + c) / 4 == (at + i) / 4)).collect(); + expect.dedup(); + assert_eq!(held, expect, "{at:#x} {changes:?}"); + let joined = dword_runs(at, &title, &merged, 32); + assert!(joined.len() <= runs.len()); + assert!(runs.iter().all(|r| joined.iter().any(|j| j.0 <= r.0 && r.0 + r.1 <= j.0 + j.1))); + } + } + assert!(dword_runs(0, &title, &title, 0).is_empty()); + } /// The runs hold exactly the bytes that differ: putting them into the /// old bytes gives the new ones, and no run holds an equal byte. @@ -2002,6 +2107,7 @@ impl Shadow { // before the submission, else the title's. (With the two // searches above this was 44 ms a frame for 970 pieces.) let mut differs = 0u8; + let was = title.to_vec(); for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) { let gpu = if *h != *o { 0xffu8 } else { 0 }; let merged = (*t & !gpu) | (*h & gpu); @@ -2010,9 +2116,7 @@ impl Shadow { *h = merged; } if differs != 0 { - crate::watch::landing(start + at, n); - crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); - written += n; + written += put_changed(start + at, &was, title); } } // Our write shows as a title write at the copy's next refresh, @@ -2096,12 +2200,11 @@ impl Shadow { if !crate::host::read_into((start + at) as *const u8, title) { return 0; } + let was = title.clone(); if !merge_piece(now, held, title) { return 0; } - crate::watch::landing(start + at, n); - crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); - n + put_changed(start + at, &was, title) } /// The 64 KiB pieces (cut at multiples of 64 KiB of title memory) of @@ -2619,6 +2722,7 @@ impl Shadow { // As in `copy_back`: the card's byte where it is not what it // was before the submission, else the title's. let mut differs = 0u8; + let was = title.clone(); for ((t, g), o) in title.iter_mut().zip(gpu).zip(old.iter_mut()) { let wrote = if *g != *o { 0xffu8 } else { 0 }; let merged = (*t & !wrote) | (*g & wrote); @@ -2627,9 +2731,7 @@ impl Shadow { *o = merged; } if differs != 0 { - crate::watch::landing(start + at, n); - crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); - written = n; + written = put_changed(start + at, &was, title); } } else { // Title memory is not mapped there: the copy keeps what the @@ -2692,6 +2794,7 @@ impl Shadow { title.clear(); title.resize(n, 0); let mapped = crate::host::read_into((start + at) as *const u8, title); + let was = title.clone(); let mut changed = false; for (a, b) in outside(at, at + n, skip) { let (a, b) = (a - at, b - at); @@ -2702,9 +2805,7 @@ impl Shadow { if !mapped || !changed { return 0; } - crate::watch::landing(start + at, n); - crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); - n + put_changed(start + at, &was, title) } } diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 46ade96..27774d6 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -758,7 +758,7 @@ pub fn title_memory_remapped(at: usize, len: usize) { /// Registers the handler that takes writes to guarded blocks, once, ahead /// of the crash reporter's. -fn install() { +pub(crate) fn install() { use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; use windows_sys::Win32::System::Diagnostics::Debug::{ AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH, @@ -768,11 +768,22 @@ fn install() { // SAFETY: the system passes the exception being dispatched. let r = unsafe { &*(*info).ExceptionRecord }; const WRITE: usize = 1; + // 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: the context the system passes, to go on from. + unsafe { (*(*info).ContextRecord).Rip = exit as u64 }; + EXCEPTION_CONTINUE_EXECUTION + }; if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 || r.ExceptionInformation[0] != WRITE { - return EXCEPTION_CONTINUE_SEARCH; + return match ours { + Some(exit) => fail(exit), + None => EXCEPTION_CONTINUE_SEARCH, + }; } let at = r.ExceptionInformation[1]; // Held across both checks: another thread may have opened the block @@ -785,9 +796,11 @@ fn install() { return EXCEPTION_CONTINUE_EXECUTION; } if writable(at) { - EXCEPTION_CONTINUE_EXECUTION - } else { - EXCEPTION_CONTINUE_SEARCH + return EXCEPTION_CONTINUE_EXECUTION; + } + match ours { + Some(exit) => fail(exit), + None => EXCEPTION_CONTINUE_SEARCH, } } static ONCE: std::sync::Once = std::sync::Once::new(); diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index 3ab3067..d1604cc 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -7,7 +7,7 @@ // API would trust. #![allow(clippy::not_unsafe_ptr_arg_deref)] -use std::ffi::{CStr, c_void}; +use std::ffi::{CStr, c_char, c_void}; use crate::{HleModule, HostPolicy, hle_export, registry, runtime}; @@ -350,6 +350,57 @@ fn refuse(file: &str) { const ERROR_MOD_NOT_FOUND: u32 = 126; +/// The title's argument list: the program, then what was given after `--`. +/// The host's own would be ours (`victory run ...`), and the title +/// looks at fixed places in it (`-skipToIIS` only as the first argument). +struct TitleArgv { + count: std::cell::UnsafeCell, + list: std::cell::UnsafeCell<*mut *mut c_char>, +} + +// SAFETY: never written here after it was made; the title's C runtime start +// reads it once, on one thread. +unsafe impl Send for TitleArgv {} +// SAFETY: as above. +unsafe impl Sync for TitleArgv {} + +/// Kept for the whole run: the title holds on to the pointers. +fn title_argv(program: &str, args: &[String]) -> TitleArgv { + let list: Vec<*mut c_char> = std::iter::once(program) + .chain(args.iter().map(String::as_str)) + .filter_map(|a| std::ffi::CString::new(a).ok()) + .map(std::ffi::CString::into_raw) + .collect(); + let count = list.len() as i32; + // `argv[argc]` is null. + let list: Box<[*mut c_char]> = list.into_iter().chain(Some(std::ptr::null_mut())).collect(); + TitleArgv { + count: count.into(), + list: Box::leak(list).as_mut_ptr().into(), + } +} + +fn argv() -> &'static TitleArgv { + static ARGV: std::sync::OnceLock = std::sync::OnceLock::new(); + ARGV.get_or_init(|| { + // The program's name stays what the host says (as it was before). + let program = std::env::args_os().next().unwrap_or_default(); + let args = runtime::title_args(); + tracing::info!(?args, "the title's arguments"); + title_argv(&program.to_string_lossy(), args) + }) +} + +/// See [`TitleArgv`]. +pub extern "C" fn __p___argc() -> *mut i32 { + argv().count.get() +} + +/// See [`TitleArgv`]. +pub extern "C" fn __p___argv() -> *mut *mut *mut c_char { + argv().list.get() +} + pub(crate) fn module() -> HleModule { HleModule { name: "kernel", @@ -363,6 +414,8 @@ pub(crate) fn module() -> HleModule { "api-ms-win-crt-runtime-*", ], exports: vec![ + hle_export!(__p___argc), + hle_export!(__p___argv), hle_export!(GetModuleHandleW), hle_export!(GetModuleHandleA), hle_export!(GetModuleFileNameW), @@ -615,6 +668,29 @@ mod tests { assert_eq!(&small, &[b'C', b':', b'\\', 0]); } + /// The title's arguments come right after the program, and the list ends + /// in a null pointer; without any there is only the program. + #[test] + fn the_title_gets_its_own_arguments() { + let read = |made: &TitleArgv| { + // SAFETY: made above, kept for the whole run. + unsafe { + let (count, list) = (*made.count.get() as usize, *made.list.get()); + assert!((*list.add(count)).is_null()); + (0..count) + .map(|i| CStr::from_ptr(*list.add(i)).to_str().unwrap().to_owned()) + .collect::>() + } + }; + let some = title_argv("victory.exe", &["-skipToIIS".into(), "-x=1".into()]); + assert_eq!(read(&some), ["victory.exe", "-skipToIIS", "-x=1"]); + assert_eq!(read(&title_argv("victory.exe", &[])), ["victory.exe"]); + // What the title is given: the same list every time. + assert_eq!(__p___argc(), __p___argc()); + // SAFETY: as above. + unsafe { assert_eq!((*__p___argc(), (**__p___argv()).is_null()), (1, false)) }; + } + fn w(text: &str) -> Vec { text.encode_utf16().chain(Some(0)).collect() } diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index cc13821..aed5c19 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -55,6 +55,18 @@ pub fn image_named(file: &str) -> Option { .map(|(b, _)| *b) } +static TITLE_ARGS: std::sync::OnceLock> = std::sync::OnceLock::new(); + +/// The arguments the title's `main` gets (those after `--`). Set once, before +/// the title starts; later calls are ignored. +pub fn set_title_args(args: Vec) { + let _ = TITLE_ARGS.set(args); +} + +pub fn title_args() -> &'static [String] { + TITLE_ARGS.get().map_or(&[], Vec::as_slice) +} + /// Maps a title DLL the title loads itself (`LoadLibrary`) and returns its /// base; `Ok(None)` if `file` is not one of the title's DLLs. pub type TitleDllLoader = Box Result, String> + Send + Sync>; diff --git a/crates/victory-shader/src/dxbc.rs b/crates/victory-shader/src/dxbc.rs index 7a20963..8d5bd73 100644 --- a/crates/victory-shader/src/dxbc.rs +++ b/crates/victory-shader/src/dxbc.rs @@ -17,6 +17,8 @@ pub struct FourCC(pub [u8; 4]); impl FourCC { pub const DXIL: FourCC = FourCC(*b"DXIL"); + /// Native code another compiler made, in place of `DXIL` (VIctory upstream 0b35b7f). + pub const ACCC: FourCC = FourCC(*b"ACCC"); pub const STAT: FourCC = FourCC(*b"STAT"); pub const RTS0: FourCC = FourCC(*b"RTS0"); pub const PSV0: FourCC = FourCC(*b"PSV0"); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 82e370f..c2a9d35 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -3110,6 +3110,12 @@ impl<'a> Lower<'a> { let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?; self.i32_of(v) } + // src_scc: SCC as 0 or 1 (VIctory upstream 0b35b7f, as the dot + // products and packed multiply-adds below). + Operand::Const(253) => { + let bit = self.scc_in(inst)?; + Ok(self.s.m.cast(self.cur, Cast::ZExt, bit, self.s.t.i32)) + } Operand::Const(c) => crate::resource::inline(c) .map(|x| self.s.m.i32(x)) .ok_or("a special operand (vccz, execz, scc, lds_direct)"), @@ -6955,6 +6961,61 @@ impl<'a> Lower<'a> { .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]); int(self, r) } + "v_dot4c_i32_i8" => { + // D += the dot product of four signed bytes, wrapping: DXIL's + // Dot4AddI8Packed. + let (a, bb) = (s(self, 0)?, s(self, 1)?); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("an accumulator"); + }; + let acc = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?; + let i32_ty = self.s.t.i32; + let r = self.s.op( + c, + "dot4AddPacked.i32", + Attr::ReadNone, + i32_ty, + 163, + &[acc, a, bb], + ); + int(self, r) + } + "v_dot4_i32_i8" => { + // VOP3P: op_sel picks the half each multiplicand's low half + // reads, op_sel_hi its high half's; the accumulator is read + // whole (as AMD's compilers fold constants into it). + if v.clamp || v.neg_hi != 0 { + return Err("a saturating or negated dot product"); + } + let mut xs = Vec::new(); + for k in 0..2 { + let x = s(self, k)?; + let (lo, hi) = (v.opsel >> k & 1 != 0, v.opsel_hi >> k & 1 != 0); + if (lo, hi) == (false, true) { + xs.push(x); + continue; + } + let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF)); + let top = self.s.m.bin(c, Bin::LShr, x, k16); + let bottom = self.s.m.bin(c, Bin::And, x, low); + let hi = self + .s + .m + .bin(c, Bin::Shl, if hi { top } else { bottom }, k16); + xs.push(self.s.m.bin(c, Bin::Or, if lo { top } else { bottom }, hi)); + } + let acc = s(self, 2)?; + let i32_ty = self.s.t.i32; + let r = self.s.op( + c, + "dot4AddPacked.i32", + Attr::ReadNone, + i32_ty, + 163, + &[acc, xs[0], xs[1]], + ); + int(self, r) + } "v_mov_b32" => { if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 { let a = f(self, 0)?; @@ -8411,6 +8472,30 @@ impl<'a> Lower<'a> { Ok(self.s.m.bin(c, Bin::And, x, m)) } + /// Half `high` of source `k` of `v_pk_fmac_f16`, in the low 16 bits: a + /// VOP2 operation (no op_sel) whose third source is its destination. + fn fmac_half(&mut self, inst: &Inst, k: usize, high: bool) -> Result { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let op = if k == 2 { v.dst } else { v.src.get(k).copied() }; + let op = op.ok_or("a missing operand")?; + if matches!(op, Operand::Const(_) | Operand::Literal(_)) { + // shortcut: no constant operand seen; its high half is not known. + return Err("a constant operand of v_pk_fmac_f16"); + } + let x = self.operand(inst, &op)?; + let c = self.cur; + let x = if high { + let k16 = self.s.m.i32(16); + self.s.m.bin(c, Bin::LShr, x, k16) + } else { + x + }; + let m = self.s.m.i32(0xFFFF); + Ok(self.s.m.bin(c, Bin::And, x, m)) + } + /// Packed 16-bit operations (`v_pk_*`): each half computed as the /// 16-bit operation does, f16 through f32 as in [`Self::valu16`]. fn packed16(&mut self, inst: &Inst, op: &str, guard: Option) -> Result<(), Why> { @@ -8419,7 +8504,7 @@ impl<'a> Lower<'a> { }; let float = op.ends_with("_f16"); let n = match op { - "fma_f16" | "mad_u16" | "mad_i16" => 3, + "fma_f16" | "fmac_f16" | "mad_u16" | "mad_i16" => 3, "add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16" | "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2, @@ -8434,7 +8519,11 @@ impl<'a> Lower<'a> { for high in [false, true] { let mut xs = Vec::new(); for k in 0..n { - let h = self.packed_src(inst, k, high, float)?; + let h = if op == "fmac_f16" { + self.fmac_half(inst, k, high)? + } else { + self.packed_src(inst, k, high, float)? + }; if float { let mut f = self .s @@ -9480,7 +9569,8 @@ impl<'a> Lower<'a> { let Fields::Image { cache, .. } = &inst.fields else { unreachable!() }; - if *d16 || *a16 { + // 16-bit coordinates (a16) are read as `addr_val` reads them. + if *d16 { return Err("a 16-bit image atomic"); } // Compare-exchange consumes a replacement followed by a comparand. diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 65e73d5..9ca8313 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -284,6 +284,7 @@ pub fn translate(container: &[u8]) -> Result { let c = Container::parse(container)?; let dxil = c .part(FourCC::DXIL) + .or(c.part(FourCC::ACCC)) .ok_or(ShaderError::Malformed("no DXIL part"))?; let native = crate::native_programs(dxil.data)? .into_iter() diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index 4c267e1..192f355 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -120,6 +120,18 @@ const CS_THREADS: usize = 0x28; const RECORD_LDS: usize = 0x4c; const MS_CLIP_CNTL: usize = 0x194; const MS_INFO: usize = 0x448; +const FSPX_VERSION: u32 = 1; +const FSPX_HEADER: usize = 0x10; +const FSPX_PACKET: u32 = 0; +const FSPX_CODE: u32 = 6; +const FSPX_METADATA: u32 = 7; +const PACKET_THREADS: usize = 0x0c; +const PACKET_FLAGS: usize = 0x12; +const PACKET_WAVE32: u16 = 1 << 4; +const PACKET_RSRC1: usize = 0x14; +const PACKET_RSRC2: usize = 0x18; +const FSPX_RECORDS: usize = 0x18; +const FSPX_RECORD: usize = 32; /// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes. const MAX_UNPACKED: u64 = 16 << 20; @@ -409,8 +421,12 @@ pub struct UsedResource { pub slot: u8, } -/// The native programs in a `DXIL` part's data; empty for the PC layout. +/// The native programs in a `DXIL` part's data, or in an `ACCC` part's +/// ([`fspx_program`]); empty for the PC layout. pub fn native_programs(part: &[u8]) -> Result, ShaderError> { + if part.starts_with(b"FSPX") { + return Ok(vec![fspx_program(part)?]); + } if part.get(XDAT_OFFSET..XDAT_OFFSET + 4) != Some(b"XDAT") { return Ok(Vec::new()); } @@ -432,6 +448,129 @@ pub fn native_programs(part: &[u8]) -> Result, ShaderError> { Ok(out) } +/// The compute program of an `ACCC` part, which a container carries in place +/// of `DXIL` when another compiler made the native code (the AMD +/// FidelityFX upscaler's shaders). Layout as observed (offsets from "FSPX"): +/// +/// ```text +/// +0x00 "FSPX" u32 version (1), u32 entry count, u32 size; entries of 16 B +/// from +0x10: u32 kind, u32 offset, u32 size, u32 0 +/// kind 0 pipeline registers, 0x1c B: +0x0c u16 x3 thread-group size, +/// +0x12 u16 flags (bit 4 wave32), +0x14 COMPUTE_PGM_RSRC1, +/// +0x18 COMPUTE_PGM_RSRC2 +/// kind 1 pipeline metadata (a hash); kind 6 the GFX10 code +/// kind 7 program metadata: u32 0x403, u32 size - 0x14, u32 code dwords, +/// u64 0, u8 0x40, u8 first user-data dword, u8 count of 0x41 +/// records, u8 0; then 32-byte records from +0x18, each a u32 tag: +/// 0x41 a resource the code reads: u8 resource type (as FSSM's used +/// entries), u8 root type, u16 0, u32 table offset (dwords), u32 +/// register, u32 view dimension (1 buffer, 4 2D, 0 root view), +/// u8 descriptor dwords, u8 user-data dword, u8 root slot, u8 0, +/// u32 -1, u32 0 +/// 0x42 a view declaration: u32 0, u8 1, u8 class (0 SRV, 1 UAV), +/// u8 resource kind (DXIL's), u8 0, u32 register +/// 0x43 the shader hash (16 B); the last record +/// ``` +pub fn fspx_program(part: &[u8]) -> Result { + if u32_at(part, 4)? != FSPX_VERSION { + return Err(Malformed("unknown FSPX version")); + } + let count = u32_at(part, 8)? as usize; + if count > MAX_XDAT_ENTRIES { + return Err(Malformed("implausible FSPX entry count")); + } + let entry = |kind: u32| -> Result<&[u8], ShaderError> { + for i in 0..count { + let at = FSPX_HEADER + 16 * i; + if u32_at(part, at)? == kind { + let (offset, size) = (u32_at(part, at + 4)?, u32_at(part, at + 8)?); + return bytes(part, offset.into(), size.into()) + .ok_or(Malformed("FSPX entry out of bounds")); + } + } + Err(Malformed("FSPX entry missing")) + }; + let packet = entry(FSPX_PACKET)?; + let code = entry(FSPX_CODE)?; + let meta = entry(FSPX_METADATA)?; + if u32_at(meta, 8)? as usize * 4 != code.len() { + return Err(Malformed("FSPX code size disagrees")); + } + let wave64 = u16_at(packet, PACKET_FLAGS)? & PACKET_WAVE32 == 0; + // VGPRs in granules of 4 (wave64) or 8 (wave32). + let granules = (u32_at(packet, PACKET_RSRC1)? & 0x3F) + 1; + let vgprs = (granules * if wave64 { 4 } else { 8 }).min(256) as u16; + let threads = |i: usize| u16_at(packet, PACKET_THREADS + 2 * i).map(u32::from); + let mut layout: Vec = Vec::new(); + let mut used = Vec::new(); + for e in meta + .get(FSPX_RECORDS..) + .unwrap_or(&[]) + .as_chunks::() + .0 + { + match e[0] { + 0x41 => {} + 0x42 => continue, + 0x43 => break, + _ => return Err(Malformed("unknown FSPX metadata record")), + } + let root = RootType::from_raw(e[5].into()); + let u = UsedResource { + kind: match e[4] { + 0 => ResourceType::Srv, + 1 => ResourceType::Sampler, + 2 => ResourceType::Cbv, + 3 => ResourceType::Uav, + n => ResourceType::Other(n), + }, + root, + table_offset_dwords: le32(e, 8), + lower_bound: le32(e, 12), + stride: 0, + dwords: e[20], + user_data: e[21], + slot: e[22], + }; + let sgprs = match root { + RootType::Table => 1, + RootType::Descriptor => 2, + // The code holds its words; no user data. + RootType::ImmediateSampler => 0, + _ => return Err(Malformed("an FSPX resource of an unknown root type")), + }; + if sgprs > 0 && !layout.iter().any(|p| p.slot == u.slot) { + layout.push(RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: u.lower_bound, + user_data: u.user_data, + slot: u.slot, + }); + } + used.push(u); + } + Ok(NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs, + layout, + used, + io: StageIo::Cs(ComputeIo { + rsrc2: u32_at(packet, PACKET_RSRC2)?, + threads: [threads(0)?, threads(1)?, threads(2)?], + }), + code: code.to_vec(), + }) +} + +fn u16_at(data: &[u8], at: usize) -> Result { + data.get(at..at + 2) + .map(|b| u16::from_le_bytes([b[0], b[1]])) + .ok_or(Malformed("FSPX data out of bounds")) +} + fn unpack(blob: &[u8]) -> Result, ShaderError> { if blob.get(0..4) != Some(b"XBCH") { return Err(Malformed("native blob lacks XBCH magic")); diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 2b6edd4..d63d2b3 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -1118,10 +1118,17 @@ impl<'a> Tracer<'a> { let Operand::Scalar { code, dwords } = *op else { return Err("a descriptor not in SGPRs"); }; - let words = (0..dwords) + let mut words = (0..dwords) .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v))) .collect::>>() .ok_or("a descriptor not in SGPRs")?; + // A byte access through a buffer descriptor made raw reads what the + // descriptor's view does with a raw host view (VIctory upstream 0b35b7f). + if !inst.name().contains("format") + && let Some(raw) = self.made_raw(&words) + { + words = raw.to_vec(); + } // Only the lanes that reach the access read the descriptor. let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true))); self.classify(&words, &mut Vec::new(), &mut known) @@ -1462,6 +1469,46 @@ impl<'a> Tracer<'a> { } } + /// The words of a buffer descriptor that `words` makes raw, as the + /// FidelityFX upscaler's compiler does before byte accesses: the stride + /// (dword 1 bits 16-29) cleared, the record count times max(stride, 1), + /// out-of-bounds checking by bytes (dword 3 bits 28-29 set). The bounds + /// are then the view's size in bytes either way. + fn made_raw(&self, words: &[Term]) -> Option<[Term; 4]> { + let [w0, Term::Value(w1), Term::Value(w2), Term::Value(w3)] = *words else { + return None; + }; + // `x op c` with `c` either side. + let with = |v: Value, name: &str, c: u32| match self.sop2(v, &[name])?.1 { + [x, Term::Const(k)] | [Term::Const(k), x] if k == c => Some(x), + _ => None, + }; + let d1 = with(w1, "s_and_b32", 0xC000_FFFF)?; + let Term::Value(m3) = with(w3, "s_or_b32", 0x3000_0000)? else { + return None; + }; + let d3 = with(m3, "s_and_b32", 0xCFFF_FFFF)?; + let [a, b] = self.sop2(w2, &["s_mul_i32"])?.1; + let max = |t: Term| match t { + Term::Value(s) => with(s, "s_max_u32", 1), + Term::Const(_) => None, + }; + let (d2, field) = match (max(a), max(b)) { + (_, Some(f)) => (a, f), + (Some(f), None) => (b, f), + (None, None) => return None, + }; + let Term::Value(field) = field else { + return None; + }; + // s_bfe_u32: offset 16, width 14. + let (_, [x, Term::Const(0x000E_0010)]) = self.sop2(field, &["s_bfe_u32"])? else { + return None; + }; + (x == d1).then_some([w0, d1, d2, d3]) + } + + /// For a `v_readfirstlane_b32` result: the VGPR value it reads. fn first_lane_source(&self, v: Value) -> Option { let inst = self.def(v)?; @@ -2331,6 +2378,12 @@ fn copy_source(inst: &Inst, k: usize) -> Option { if inst.name() == "s_movk_i32" { return Some(Moved::Const(i32::from((*imm)? as i16) as u32)); } + // A mask of S0 bits from bit S1, as the upscaler's compiler makes an + // immediate sampler's word. + if let ("s_bfm_b32", 0, [Operand::Const(w), Operand::Const(at)]) = (inst.name(), k, &src[..]) { + let (w, at) = (inline(*w)? & 31, inline(*at)? & 31); + return Some(Moved::Const(((1u32 << w) - 1) << at)); + } let src = src.first()?; match (inst.name(), *src) { ("s_mov_b32" | "s_mov_b64", Operand::Scalar { code, .. }) if code != NULL => { @@ -2343,6 +2396,11 @@ fn copy_source(inst: &Inst, k: usize) -> Option { // that has no inline form; fold more if descriptors need it. ("s_brev_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(x.reverse_bits())), ("s_not_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(!x)), + // shortcut: a literal below 2^31, whose high dword is 0 whether the + // hardware extends it with zeros or with its sign. + ("s_mov_b64", Operand::Literal(x)) if x >> 31 == 0 => { + Some(Moved::Const(if k == 0 { x } else { 0 })) + } // 64-bit inline integers are sign-extended. ("s_mov_b64", Operand::Const(c @ 128..=208)) => { let low = inline(c)?; @@ -2763,6 +2821,76 @@ pub(crate) mod tests { assert_eq!(r.scalar, [((0, 2), at(0, 0)), ((0, 3), at(0, 0x10))]); } + /// The FidelityFX upscaler's byte accesses make a loaded buffer + /// descriptor raw first (stride cleared, records times stride, bounds + /// in bytes): the access reads the loaded descriptor. Any other change + /// still fails. + #[test] + fn a_descriptor_made_raw_is_the_loaded_one() { + let words = |mask: u32| -> Vec { + [ + 0xBE88_0304, // s_mov_b32 s8, s4 + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xF408_0204, + 0xFA00_0160, // s_load_dwordx4 s[8:11], s[8:9], 0x160 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x938C_FF09, + 0x000E_0010, // s_bfe_u32 s12, s9, 0x000e0010 + 0x848C_810C, // s_max_u32 s12, s12, 1 + 0x8709_FF09, + mask, // s_and_b32 s9, s9, mask + 0x870B_FF0B, + 0xCFFF_FFFF, // s_and_b32 s11, s11, 0xcfffffff + 0x930A_0C0A, // s_mul_i32 s10, s10, s12 + 0x880B_FF0B, + 0x3000_0000, // s_or_b32 s11, s11, 0x30000000 + 0xE078_1000, + 0x8002_0007, // buffer_store_dwordx4 v[0:3], v7, s[8:11], 0 offen + S_ENDPGM, + ] + .iter() + .flat_map(|w: &u32| w.to_le_bytes()) + .collect() + }; + let run = |mask| { + let p = crate::ir::build(&words(mask), false, 256).unwrap(); + track(&p, &[param(Table, 4, 1)], HwStage::Cs, lanes(&p).as_ref()) + }; + assert!(run(0xC000_FFFF).is_ok()); + assert_eq!( + run(0xC000_FFFE).unwrap_err(), + ShaderError::Unsupported { + offset: 0x3c, + what: "a descriptor changed after loading" + } + ); + } + + /// Immediate sampler words the upscaler's compiler makes with a bit + /// mask and a 64-bit move of a literal. + #[test] + fn sampler_words_from_bit_masks_and_wide_literals_are_constants() { + let code: Vec = [ + 0xB010_3092, // s_movk_i32 s16, 0x3092 + 0x9211_8C8C, // s_bfm_b32 s17, 12, 12 + 0xBE92_04FF, + 0x1850_0000, // s_mov_b64 s[18:19], 0x18500000 + S_ENDPGM, + ] + .iter() + .flat_map(|w: &u32| w.to_le_bytes()) + .collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let layout = [param(Table, 4, 1)]; + let t = Tracer::new(&p, &layout, HwStage::Cs, None).unwrap(); + let block = &p.blocks[0]; + let value = |n: usize, k: usize| t.origin(block.insts[n].writes[k].1); + assert_eq!(value(1, 0), Term::Const(0x00FF_F000)); + assert_eq!(value(2, 0), Term::Const(0x1850_0000)); + assert_eq!(value(2, 1), Term::Const(0)); + } + + #[test] fn a_selection_that_mixes_two_descriptors_fails() { // The high half picked from the first load whatever SCC is: when From 310c6eb6c16822ab95076aad61fce19bba86bb98 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:19:10 -0500 Subject: [PATCH 159/445] Packed textures stay in the upload queue; a texture on the card is refreshed when the card is full Two fixes for textures that shaders pick by index, both proven with a slot listing before they were made: - The title keeps only a texture's small levels and places the next texture in the address range of the absent large ones. Described at full size every neighbour overlapped, and each view written took the textures beside it out of the upload queue and made their host slots null (tens of thousands of slots a run). A newer view now makes an older one stale only when it starts within that one's first 4 KiB. VICTORY_STALE_TEXTURES=overlap: the old rule; =0: never. Unit tests on the span table alone. The first room is lit with its walls and the characters' textures in the first launch with it. - With the card at its limit, a texture that already has its host copy is uploaded again when the title changed its memory (it took no new card memory, and was refused all the same). VICTORY_REUPLOAD_WHEN_FULL=0: as before. Logging only, off unless asked for: both video memory groups and budget moves; card accounting (VICTORY_CARD_ACCOUNTING=1); the slots a listed draw's shaders read, with their state (VICTORY_LIST_SLOTS=); a trace for the missing first-room walls (VICTORY_WALLS_TRACE=1 or 2). A card test of what a bare command costs (ignored by default): cargo test -p victory-gpu --release -- --ignored bare_command_cost --nocapture Known: about 3 to 5 frames a second; more than half of the texture memory on the card is held for levels the title has not loaded yet (next). Co-Authored-By: Claude Fable 5.2 --- crates/victory-gpu/src/copystat.rs | 5 + crates/victory-gpu/src/descriptor/host.rs | 286 +++++++++- crates/victory-gpu/src/draw.rs | 463 +++++++++++++++- crates/victory-gpu/src/host.rs | 114 +++- crates/victory-gpu/src/indirect.rs | 601 +++++++++++++++++++++ crates/victory-gpu/src/resource.rs | 217 ++++++++ crates/victory-gpu/src/shadow.rs | 94 ++++ crates/victory-gpu/src/texture.rs | 10 + crates/victory-hle/src/modules/dstorage.rs | 49 ++ 9 files changed, 1807 insertions(+), 32 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 4a2b785..204b6c4 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -690,6 +690,11 @@ fn log_memory() { let card = crate::host::host() .and_then(|h| h.video_memory()) .unwrap_or_default(); + // Everything the system says of the two memory groups, beside the + // budget and use the lines below print. + if let Some(h) = crate::host::host() { + h.log_video_memory("with the memory line"); + } // What else holds memory: the map, on a thread of its own, with every // sixth line; and what the shader table and the pipeline library keep. static LINES: AtomicU64 = AtomicU64::new(0); diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index b2c27c5..7b18b45 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -89,16 +89,25 @@ pub(crate) struct HostHeap { } /// Title memory by the placed texture views that describe it: per span of -/// memory (its start, its end) the title slots holding a view of a -/// texture that takes exactly that span. Spans never overlap: a console -/// title need not clear a descriptor when it streams a texture out, so a -/// view written over memory that older views describe otherwise (another -/// start or another length: another texture) is all that says the older -/// ones are stale. Views of one span with different descriptions (the -/// formats of one family, say) are one texture's. +/// memory (its start, its end at full size) the title slots holding a +/// view of a texture that takes exactly that span. A console title need +/// not clear a descriptor when it streams a texture out, so a newer view +/// that cannot be there together with an older one is all that says the +/// older one is stale ([`Rule`] says when that is). Views of one span with +/// different descriptions (the formats of one family, say) are one +/// texture's. +/// +/// Spans may overlap: a texture's smallest levels lie at the start of its +/// memory, and a title that holds only those puts the next texture where +/// the larger ones would be (the title: three 512x256 textures +/// of 0x2c000 bytes each whose starts are 0x2000 and 0x4000 apart, all +/// three read by the same frame's draws, run 188). What is there of a +/// texture ends where the next one starts. /// No host heap is needed, so it is tested without one. #[derive(Default)] pub(crate) struct Spans { + /// When a newer view makes an older one stale. + rule: Rule, by_start: std::collections::BTreeMap)>, by_slot: std::collections::HashMap, /// The bytes a placed texture takes, by resource description: worked @@ -107,6 +116,32 @@ pub(crate) struct Spans { sizes: std::collections::HashMap<[u32; 14], Option>, } +/// When a view the title writes makes an older view of other memory stale. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Rule { + /// When it starts where the older one starts: at the same address + /// with another length, or within the older one's first [`HEAD`] + /// bytes (or the older within its own). No two textures share the + /// block of their smallest levels. A view that only reaches into the + /// address range of an older texture's larger levels says nothing. + #[default] + Start, + /// Whenever their spans at full size overlap (the rule until run + /// 188, where it made null the slots of textures packed as above: + /// each view written took its neighbours out of the queue and off the + /// card, for good). `VICTORY_STALE_TEXTURES=overlap`. + Overlap, + /// Never; a view that would be stale under [`Rule::Overlap`] is left + /// out of the spans instead. `VICTORY_STALE_TEXTURES=0`, as before. + Never, +} + +/// The first bytes of a placed texture that are its own under +/// [`Rule::Start`]: the 4 KiB block its smallest levels share. (Of 129 +/// pairs of overlapping neighbours in the listings of runs 188 and 189, +/// none starts closer than 0x2000 to the one before it.) +const HEAD: u64 = 4096; + impl Spans { /// The bytes of title memory a placed texture with the resource /// description `desc` takes (`crate::resource::placed_bytes`). @@ -119,7 +154,10 @@ impl Spans { bytes } - /// The starts of the spans that overlap `[start, end)`. + /// The starts of the spans that overlap `[start, end)`, each taken to + /// end where the next one starts: the last span that starts before + /// `start`, if it reaches past it at full size, and every span that + /// starts inside. fn overlapping(&self, start: u64, end: u64) -> Vec { let before = self .by_start @@ -131,10 +169,10 @@ impl Spans { } /// Slot `index` holds a view of a texture in `[start, end)`. `newer`: - /// the title wrote it now, so the slots whose views describe that - /// memory otherwise are stale: they are returned, and forgotten. - /// Otherwise (a draw made the slot from what it held) a view that - /// overlaps other spans is left out. + /// the title wrote it now, so the slots whose views cannot be there + /// with it ([`Rule`]) are stale: they are returned, and forgotten. + /// Otherwise (a draw made the slot from what it held), and under + /// [`Rule::Never`], a view that clashes with other spans is left out. fn note(&mut self, index: u32, start: u64, end: u64, newer: bool) -> Vec { let same = |span: Option<&(u64, std::collections::BTreeSet)>| span.is_some_and(|s| s.0 == end); if self.by_slot.get(&index) == Some(&start) && same(self.by_start.get(&start)) { @@ -144,15 +182,40 @@ impl Spans { if end <= start { return Vec::new(); } + let rule = self.rule; + // The spans the view cannot be there with. + let clashing: Vec = match rule { + Rule::Start => self + .by_start + .range(start.saturating_sub(HEAD - 1)..start.saturating_add(HEAD)) + .map(|(at, _)| *at) + .collect(), + Rule::Overlap | Rule::Never => self.overlapping(start, end), + }; let mut stale = Vec::new(); - for at in self.overlapping(start, end) { + for at in clashing { if at == start && same(self.by_start.get(&at)) { continue; } - if !newer { + if !newer || rule == Rule::Never { return stale; } - if let Some((_, slots)) = self.by_start.remove(&at) { + if let Some((old_end, slots)) = self.by_start.remove(&at) { + // The first of them are said with both spans, to tell a + // replacement from a neighbour in one launch's log. + static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 48 { + tracing::info!( + slot = index, + start = format_args!("{start:#x}"), + end = format_args!("{end:#x}"), + stale_start = format_args!("{at:#x}"), + stale_end = format_args!("{old_end:#x}"), + stale_slots = slots.len(), + rule = ?rule, + "a placed texture view makes older views of other memory stale" + ); + } for slot in slots { self.by_slot.remove(&slot); stale.push(slot); @@ -206,11 +269,18 @@ static SPANNED: [std::sync::atomic::AtomicU64; 2] = [ pub(crate) static STALE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; -/// Whether a view written over memory that older views describe otherwise -/// makes those stale; `VICTORY_STALE_TEXTURES=0` leaves them as they are. -fn stale_out() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_STALE_TEXTURES").is_none_or(|v| v != "0")) +/// When a view the title writes makes older views of other memory stale +/// ([`Rule`]): where it starts in the block of their smallest levels, by +/// default; `VICTORY_STALE_TEXTURES=0`: never, as before; +/// `VICTORY_STALE_TEXTURES=overlap`: wherever their spans overlap, the rule +/// until run 188. +fn stale_rule() -> Rule { + static RULE: std::sync::OnceLock = std::sync::OnceLock::new(); + *RULE.get_or_init(|| match std::env::var("VICTORY_STALE_TEXTURES").as_deref() { + Ok("0") => Rule::Never, + Ok("overlap") => Rule::Overlap, + _ => Rule::Start, + }) } /// The runtime mapped or unmapped title memory `[at, at + len)`, or is @@ -856,6 +926,20 @@ impl HostHeap { (if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame)) } + /// Every title slot of the queue that is due at `frame`, and whether + /// it was uploaded before (in part, or whole and waiting for another + /// look): for the card accounting line + /// (`crate::resource::card_accounting`). + pub(crate) fn texture_slots_all_due(&self, frame: u64) -> Vec<(u32, bool)> { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + textures + .slots + .iter() + .filter(|(_, w)| w.due <= frame) + .map(|(&index, w)| (index, w.mapped > 0 || w.checked.2 != 0)) + .collect() + } + /// The texture view of title slot `index` (as handed out with `write`) /// was brought up to date: due again from frame `again` (uploaded with /// that many bytes of its memory there, not all), or not until the @@ -934,6 +1018,36 @@ impl HostHeap { slots.len() } + /// Whether host slot `index` is made from the very record the title + /// has at `handle` now. Its host texture then exists (a slot keeps what + /// it views), so bringing that texture up to date takes no memory of + /// the card. + pub(crate) fn texture_slot_made_from(&self, index: u32, handle: u64) -> bool { + if index >= self.count { + return false; + } + // SAFETY: the handle is a descriptor slot in title memory. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + let key = u64::from(generation) << 32 | u64::from(i); + if tag != VIEW_TAG { + return false; + } + // And the slot holds a host resource: a slot is also noted as made + // 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 + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(index as usize) + .is_some_and(Option::is_some) + } + /// The memory of the texture title slot `index` views is not mapped /// (any more): a host slot made from it becomes null again, so that /// the host copy can be let go (`crate::resource::let_go_idle`; a slot @@ -1103,7 +1217,8 @@ impl HostHeap { Some((start, end)) => { SPANNED[0].fetch_min(start, Relaxed); SPANNED[1].fetch_max(end, Relaxed); - placed.note(index, start, end, !seen && stale_out()) + placed.rule = stale_rule(); + placed.note(index, start, end, !seen) } None => { placed.forget(index); @@ -1412,6 +1527,24 @@ impl HostHeap { Some(windows::core::Interface::as_raw(shown) == windows::core::Interface::as_raw(buffer)) } + /// What the queue of textures picked by index knows of title slot + /// `index` at `frame`, in a few words (diagnostics). + #[cfg(feature = "diagnostics")] + pub(crate) fn texture_slot_state(&self, index: u32, frame: u64) -> String { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + match textures.slots.get(&index) { + None => "not queued".into(), + Some(w) => format!( + "queued due={} written@{} looks={} part_mapped={} recheck={}", + if w.due <= frame { "now".to_string() } else { format!("@{}", w.due) }, + w.written, + w.looks, + w.mapped, + w.checked.2 != 0 + ), + } + } + /// The view host slot `index` was made from, in a few words, with the /// title and host addresses of a buffer view (diagnostics). "null" for /// a slot never made or left null. @@ -2433,11 +2566,116 @@ mod tests { assert!(q.due(16, 100).iter().any(|d| d.0 == 98)); } - /// A view written over memory that older views describe otherwise - /// makes those stale; views of the same span are one texture's. + /// Textures of which only the smallest levels are held, packed into + /// one another's address range (the three of run 188: 0x2c000 bytes + /// each at full size, their starts 0x2000 and 0x4000 apart): writing + /// any of them, in any order and again, leaves the others. + #[test] + fn packed_neighbours_stay() { + let mut spans = Spans::default(); + assert_eq!(spans.rule, Rule::Start); + let at = 0xb_86bf_8000u64; + let (a, b, c) = (at, at + 0x2000, at + 0x6000); + assert!(spans.note(105_998, a, a + 0x2c000, true).is_empty()); + assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty()); + assert!(spans.note(108_521, c, c + 0x2c000, true).is_empty()); + // The first written again (as a title does when levels arrive), + // from another slot too: its span reaches over the other two. + assert!(spans.note(7, a, a + 0x2c000, true).is_empty()); + assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty()); + let mut all = spans.slots_in(0, u64::MAX); + all.sort_unstable(); + assert_eq!(all, [7, 105_998, 106_004, 108_521]); + // A draw makes a slot of the second texture: it is one of them. + assert!(spans.note(9, b, b + 0x2c000, false).is_empty()); + assert_eq!(spans.by_slot.get(&9), Some(&b)); + } + + /// A texture written where another starts replaces it: at the same + /// address with another length, or inside the block of its smallest + /// levels. The packed neighbours of the one replaced stay. + #[test] + fn a_texture_written_at_the_start_of_another_replaces_it() { + let mut spans = Spans::default(); + let at = 0x7_0000_0000u64; + assert!(spans.note(1, at, at + 0x2c000, true).is_empty()); + assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty()); + // Another length from the same start: slot 1 is stale, slot 2 not. + assert_eq!(spans.note(3, at, at + 0xb000, true), [1]); + // A start inside the first 4 KiB of slot 3's texture: stale too. + assert_eq!(spans.note(4, at + 0x800, at + 0x1800, true), [3]); + // And the other way: a texture that starts just before one. + assert_eq!(spans.note(5, at + 0x1800, at + 0x4800, true), [2]); + let mut left = spans.slots_in(0, u64::MAX); + left.sort_unstable(); + assert_eq!(left, [4, 5]); + // Exactly 4 KiB apart: both there. + assert!(spans.note(6, at + 0x2800, at + 0x3800, true).is_empty()); + // A draw's view that clashes is left out, and nothing is stale. + assert!(spans.note(8, at + 0x900, at + 0x2900, false).is_empty()); + assert_eq!(spans.by_slot.get(&8), None); + assert_eq!(spans.by_slot.len(), 3); + } + + /// A slot written with another texture leaves its old span; the same + /// view written again changes nothing. + #[test] + fn a_slot_rewritten_moves_to_its_new_span() { + let mut spans = Spans::default(); + assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty()); + assert!(spans.note(2, 0x12000, 0x3e000, true).is_empty()); + assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty()); + assert_eq!(spans.slots_in(0x10000, 0x10001), [1]); + // Slot 1 now views a texture far away. + assert!(spans.note(1, 0x90000, 0x91000, true).is_empty()); + assert_eq!(spans.slots_in(0x10000, 0x10001), [] as [u32; 0]); + assert_eq!(spans.slots_in(0x12000, 0x12001), [2]); + assert_eq!(spans.slots_in(0x90000, 0x90001), [1]); + spans.forget(1); + spans.forget(2); + assert!(spans.by_start.is_empty() && spans.by_slot.is_empty()); + } + + /// Memory the runtime maps, unmaps or writes names the textures that + /// are there: among packed neighbours the one whose held levels the + /// range lies in (it ends where the next one starts), and the ones + /// that start inside the range. + #[test] + fn memory_changed_under_packed_neighbours_names_the_ones_there() { + let mut spans = Spans::default(); + let at = 0x7_0000_0000u64; + assert!(spans.note(1, at, at + 0x2c000, true).is_empty()); + assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty()); + assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty()); + // Inside the first one's held levels. + assert_eq!(spans.slots_in(at + 0x1000, at + 0x2000), [1]); + // Inside the second's: not the first, which ends where it starts. + assert_eq!(spans.slots_in(at + 0x3000, at + 0x4000), [2]); + // Past the last start: the last one. + assert_eq!(spans.slots_in(at + 0x20000, at + 0x21000), [3]); + // A range over all of them. + assert_eq!(spans.slots_in(at, at + 0x8000), [1, 2, 3]); + // Past the end of all: none. + assert_eq!(spans.slots_in(at + 0x32000, at + 0x33000), [] as [u32; 0]); + } + + /// `VICTORY_STALE_TEXTURES=0`: nothing is ever stale, and a view that + /// overlaps others is left out of the spans, as before. + #[test] + fn never_stale_leaves_overlapping_views_out() { + let mut spans = Spans { rule: Rule::Never, ..Default::default() }; + assert!(spans.note(1, 0x1000, 0x3000, true).is_empty()); + assert!(spans.note(2, 0x2000, 0x4000, true).is_empty()); + assert!(spans.note(3, 0x1000, 0x2000, true).is_empty()); + assert_eq!(spans.slots_in(0, u64::MAX), [1]); + } + + /// The rule until run 188 (`VICTORY_STALE_TEXTURES=overlap`): a view + /// written over memory that older views describe otherwise makes + /// those stale; views of the same span are one texture's. #[test] fn a_newer_view_of_other_memory_makes_the_older_stale() { - let mut spans = Spans::default(); + let mut spans = Spans { rule: Rule::Overlap, ..Default::default() }; // Three textures side by side, the first in two slots. assert!(spans.note(1, 0x1000, 0x3000, true).is_empty()); assert!(spans.note(2, 0x1000, 0x3000, true).is_empty()); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index c018811..29f34cf 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -381,6 +381,18 @@ const RECHECK_FRAMES: [u64; 5] = [4, 12, 40, 120, 400]; /// was, and that found it changed (uploaded again), since the start. pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; +/// Uploads of textures already on the card made while it had no room for +/// new ones, since the start. +pub(crate) static HEAP_TEXTURES_REUPLOADED_FULL: AtomicU64 = AtomicU64::new(0); + +/// Whether a texture that has its host copy is still brought up to date +/// while the card has no room for new ones (`VICTORY_REUPLOAD_WHEN_FULL=0`: +/// no). +fn reupload_when_full() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_REUPLOAD_WHEN_FULL").is_none_or(|v| v != "0")) +} + /// Whether textures picked by index are looked at again after their upload /// (`VICTORY_HEAP_RECHECK=0`: no). fn heap_recheck() -> bool { @@ -913,6 +925,9 @@ impl State { let l = &list.list; // Textures picked by index, before anything asks for them. self.early_textures(list, p, compute); + if crate::host::walls_trace() { + self.walls_census(p, compute); + } // Heaps first: a root signature with directly indexed heaps must be // set after them. if self.host_heaps != self.heaps { @@ -1550,6 +1565,77 @@ impl State { } } + /// The queue's side of the card accounting line + /// (`crate::resource::card_accounting`, which says what the line + /// holds): the slots that are due, by what their texture has on the + /// card. Off unless `VICTORY_CARD_ACCOUNTING=1`; then at the first pass + /// that finds the card without room, and every five seconds after it. + /// Nothing is made, uploaded or counted as used here. For 18,000 due + /// slots: 18,000 looks at a title slot and at the texture it views, a + /// lock each, some milliseconds of the thread that records the frame. + fn card_accounting( + heap: &crate::descriptor::Heap, + host: &crate::descriptor::host::HostHeap, + frame: u64, + room: bool, + ) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ACCOUNTING").is_some_and(|v| v == "1")) { + return; + } + // When the next line is due (0: none yet, the card has had room). + static NEXT: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms().max(1); + let next = NEXT.load(Ordering::Relaxed); + let due_now = if next == 0 { !room } else { now >= next }; + if !due_now || NEXT.compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + // Due slots; of them uploaded before; of them viewing nothing the + // title fills; and the textures (each once) whose host copy is + // alive, with their bytes on the card. + let mut due = [0u64; 5]; + // Textures (each once) that never had a host copy, and ones whose + // host copy was let go: where their memory is, and its bytes. + let (mut never, mut gone) = (Vec::new(), Vec::new()); + let mut seen = std::collections::BTreeSet::new(); + for (index, uploaded) in host.texture_slots_all_due(frame) { + due[0] += 1; + due[1] += u64::from(uploaded); + let state = match heap.handle(index).and_then(crate::descriptor::view) { + Some(View::Placed(false, resource, desc)) if resource[0] != 1 => { + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + match crate::resource::placed_known(address, &resource) { + Some(texture) => crate::resource::copy_state(texture), + // No title texture was made for it: the pass never + // got as far as making one. + None => Some((0, crate::resource::placed_bytes(&resource).unwrap_or(0), address)), + } + } + Some(View::Shader(object, _)) if crate::resource::title_fills(object as This) => { + crate::resource::copy_state(object as This) + } + _ => None, + }; + let Some((state, bytes, memory)) = state else { + due[2] += 1; + continue; + }; + if !seen.insert(memory) { + continue; + } + match state { + 2 => { + due[3] += 1; + due[4] += bytes; + } + 1 => gone.push((memory, bytes)), + _ => never.push((memory, bytes)), + } + } + crate::resource::card_accounting(room, due, never, gone); + } + /// The texture side of [`State::heap_buffers`]: textures the title fills /// itself (streamed pages, layout-library copies) whose views sit in the /// view heap are created (placed textures have no host texture until @@ -1609,6 +1695,10 @@ impl State { for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) { count.store(now, Ordering::Relaxed); } + // Where the card's memory is, and what the due slots would need + // (`VICTORY_CARD_ACCOUNTING=1`; a line when the card first has no + // room, and every five seconds after it). + Self::card_accounting(heap, host, frame, room); // The frames in about four seconds, between 16 and 256: how long a // slot with nothing to upload waits at most for its next look. In // frames alone it was 120: four minutes at the opening cutscene's @@ -1738,12 +1828,35 @@ impl State { } // From here on a host texture is made: not without room. The // slot stays due. + // Not so a slot already made from this very view: its host + // texture exists, and uploading it again takes none of the + // card's memory. It was refused all the same, so a texture the + // title filled after its first upload kept its empty host copy + // from the moment the card reached the line, which is the first + // world frame in eight launches of nine: the same slots were + // found changed again at every pass and never uploaded (run + // 179: 33,000 such findings), and the main character's face + // had its colour only in the launches that entered the world + // under the line. `VICTORY_REUPLOAD_WHEN_FULL=0`: refused, as + // before. if !room { - refused += 1; - if refused > 256 { - break; + let has_its_texture = reupload_when_full() + && heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle)); + if !has_its_texture { + refused += 1; + if refused > 256 { + break; + } + continue; + } + let n = HEAP_TEXTURES_REUPLOADED_FULL.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n.is_multiple_of(500) { + tracing::info!( + so_far = n, + slot = index, + "a texture already on the card is brought up to date although the card has no room for new ones" + ); } - continue; } let view = heap.handle(index).and_then(|handle| host.mirror(index, handle, true)); let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); @@ -1976,9 +2089,180 @@ impl State { } } let _ = write!(text, " tables {:?}", self.reads(compute)); + if !compute && !list_slots().is_empty() { + text.push_str(&self.slots_text()); + } text } + /// For the frame listing, after a draw whose shader `VICTORY_LIST_SLOTS` + /// names: the heap slots it will pick textures from by index, and what + /// the title and the host hold there (one `~slot` line each), with the + /// words they were read from (`~raw` lines, to decode offline what is + /// not decoded here). + /// + /// Where the slots are, for the title's character shaders + /// (`PS_DeferredPedTexturedNC`, from their native code): in the small + /// buffers and constants of the draw's own table (every word of those + /// that names a texture view gets a line); in the material record, at + /// the byte offset the draw's constants (table 1, dword 56) hold at + /// 0x1c, of the buffer at table 0, dword 160; and in the record at the + /// byte offset the second root constant holds of the buffer at table 0, + /// dword 688. A word that is a small number by chance and names a + /// texture gets a line too. + #[cfg(feature = "diagnostics")] + fn slots_text(&self) -> String { + use std::fmt::Write; + const MATERIALS: u32 = 160; + const GLOBAL: u32 = 688; + const DRAW_CONSTANTS: u32 = 56; + let wanted = list_slots(); + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return String::new(); + }; + let Some(stage) = p.stages.iter().find(|s| wanted.iter().any(|w| s.shader.hash.starts_with(w.as_str()))) + else { + return String::new(); + }; + let Some(heap) = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers()) + else { + return String::new(); + }; + let t = stage.translated(); + let mut text = String::new(); + let entry = |slot: u8, dwords: u32| -> Option { + let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(slot)) else { + return None; + }; + crate::descriptor::view(table + u64::from(dwords) * 4) + }; + let mut material = None; + for u in t.used.iter().filter(|u| u.root == RootType::Table && u.kind != ResourceType::Sampler) { + let label = format!("s{}+{}", u.slot, u.table_offset_dwords); + let Some(view) = entry(u.slot, u.table_offset_dwords) else { + let _ = write!(text, "\n ~table {label} no view"); + continue; + }; + let range = match &view { + View::Constant(address, size) => Some((*address, u64::from(*size))), + other => crate::descriptor::host::buffer_range(other), + }; + match range { + // A small buffer or constants: its words. + Some((address, len)) if len <= 2048 => { + Self::slot_words(&mut text, heap, &label, address, len as usize); + if u.slot == 1 && u.table_offset_dwords == DRAW_CONSTANTS && len >= 0x20 { + let mut word = [0u8; 4]; + if crate::host::read_into((address + 0x1c) as *const u8, &mut word) { + material = Some(u32::from_le_bytes(word)); + } + } + } + Some(_) => {} + // A texture read through the table: the title slot it sits in. + None => { + let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(u.slot)) else { + continue; + }; + match heap.index(table + u64::from(u.table_offset_dwords) * 4) { + Some(index) => text.push_str(&Self::slot_line(heap, &format!("table:{label}"), 0, index)), + None => { + let _ = write!(text, "\n ~table {label} title=[{}]", view_state(Some(&view))); + } + } + } + } + } + let uses = |slot: u8, dwords: u32| { + t.used.iter().any(|u| u.root == RootType::Table && u.slot == slot && u.table_offset_dwords == dwords) + }; + if let Some(at) = material + && uses(0, MATERIALS) + && let Some((base, len)) = entry(0, MATERIALS).as_ref().and_then(crate::descriptor::host::buffer_range) + { + let at = u64::from(at); + let _ = write!(text, "\n ~material record at {at:#x} of the buffer at {base:#x} bytes {len}"); + if at + 64 <= len { + Self::slot_words(&mut text, heap, "M", base + at, 64); + } + if at + 1936 + 512 <= len { + Self::slot_words(&mut text, heap, "M+1936", base + at + 1936, 512); + } + } + if uses(0, GLOBAL) + && let Some(slot) = t.used.iter().find(|u| u.root == RootType::Constants).map(|u| u.slot) + && let Some(Root::Constants(words)) = self.roots_ref(false).get(usize::from(slot)) + && let Some(&at) = words.get(1) + && let Some((base, len)) = entry(0, GLOBAL).as_ref().and_then(crate::descriptor::host::buffer_range) + { + let at = u64::from(at); + let _ = write!(text, "\n ~root constants {words:08x?}: record at {at:#x} of the buffer at {base:#x} bytes {len}"); + if at + 64 <= len { + Self::slot_words(&mut text, heap, "G", base + at, 64); + } + } + text + } + + /// Up to 512 bytes of title memory at `address` as hex words (a `~raw` + /// line), and a `~slot` line for every word of them that names a + /// texture view in `heap`. + #[cfg(feature = "diagnostics")] + fn slot_words(text: &mut String, heap: &crate::descriptor::Heap, label: &str, address: u64, len: usize) { + use std::fmt::Write; + let mut bytes = vec![0u8; len.min(512) & !3]; + if bytes.is_empty() || !crate::host::read_into(address as *const u8, &mut bytes) { + let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}: unreadable"); + return; + } + let words: Vec = + bytes.chunks_exact(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect(); + let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}:"); + for w in &words { + let _ = write!(text, " {w:08x}"); + } + for (i, &index) in words.iter().enumerate() { + let names = index != 0 + && heap + .handle(index) + .and_then(crate::descriptor::view) + .as_ref() + .is_some_and(crate::descriptor::host::is_texture_view); + if names { + text.push_str(&Self::slot_line(heap, label, i * 4, index)); + } + } + } + + /// One `~slot` line: where the slot number was read (`from`, byte + /// `at`), what the title's heap holds in slot `index` with the state + /// of that texture ([`view_state`]), what the host slot was made from, + /// and what the queue of textures picked by index knows of it. + #[cfg(feature = "diagnostics")] + fn slot_line(heap: &crate::descriptor::Heap, from: &str, at: usize, index: u32) -> String { + let title = heap.handle(index).and_then(crate::descriptor::view); + let host: String = heap + .host() + .and_then(|h| h.describe_slot(index)) + .unwrap_or_else(|| "none".into()) + .chars() + .take(90) + .collect(); + let queue = match heap.host() { + Some(h) => h.texture_slot_state(index, crate::frame::current()), + None => "no host heap".into(), + }; + format!( + "\n ~slot from={from}+{at:#x} slot={index} title=[{}] host=[{host}] queue=[{queue}]", + view_state(title.as_ref()) + ) + } + /// A mesh draw under `VICTORY_MESH_TEST=scissor` rasterises one pixel: /// the scissors before it (`on`), the title's after it. fn mesh_scissor(&self, list: &HostList, on: bool) { @@ -2022,6 +2306,74 @@ impl State { } } + /// The walls trace (`crate::host::walls_trace`): one log line per + /// frame with the draws of its main pass (four or more colour targets) + /// by scissor rectangle, and how often each of the title's culling + /// programs was dispatched. The title clips what it draws + /// through a window or door to that opening's rectangle while it holds + /// the camera to be in a room (run 182, frame 1529: 1,386 draws under + /// `531 0 1789 1337`); in a launch without the room's walls the same + /// shot has no such rectangle (run 187, frame 1414). The line shows + /// the frame in which that changes. + fn walls_census(&self, p: &HostPipeline, compute: bool) { + const CULL: [(&str, &str); 9] = [ + ("55679a0547649d0b", "tree"), + ("89d08e561897d4e5", "tree_imposter"), + ("9209777e8face9dd", "grass"), + ("17af15c4015cb4b6", "prop"), + ("fdd56d97a806bcca", "prop_nocull"), + ("42f717f1b4d18e94", "simple"), + ("1c4b3c0547e3e6fa", "slod"), + ("9146291b38ea9ce1", "meshlet_args"), + ("42683eebec081520", "depth_pyramid_cpu_occlusion"), + ]; + type Census = (u64, std::collections::BTreeMap<[i32; 4], u32>, [u32; 9]); + static CENSUS: std::sync::Mutex = + std::sync::Mutex::new((u64::MAX, std::collections::BTreeMap::new(), [0; 9])); + let frame = crate::frame::current(); + let mut census = CENSUS.lock().unwrap_or_else(|e| e.into_inner()); + if census.0 != frame { + let draws: u32 = census.1.values().sum(); + if draws > 0 { + let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect(); + rects.sort_unstable_by(|a, b| b.1.cmp(&a.1)); + let scissors: Vec = rects + .iter() + .take(5) + .map(|(r, n)| format!("{} {} {} {} x{n}", r[0], r[1], r[2], r[3])) + .collect(); + let counts = census.2; + let culling: Vec = CULL + .iter() + .zip(counts) + .filter(|(_, n)| *n > 0) + .map(|(c, n)| format!("{}={n}", c.1)) + .collect(); + tracing::info!( + frame = census.0, + main_pass_draws = draws, + rectangles = rects.len(), + scissors = ?scissors, + culling = ?culling, + "walls trace: the frame's main pass by scissor rectangle, and its culling dispatches" + ); + } + census.0 = frame; + census.1.clear(); + census.2 = [0; 9]; + } + if compute { + for (i, c) in CULL.iter().enumerate() { + if p.stages.iter().any(|s| s.shader.hash.as_str() == c.0) { + census.2[i] += 1; + } + } + } else if self.targets.iter().filter(|&&t| t != 0).count() >= 4 { + let r = self.scissors.first().map_or([0; 4], |r| [r.left, r.top, r.right, r.bottom]); + *census.1.entry(r).or_insert(0) += 1; + } + } + fn roots_ref(&self, compute: bool) -> &Vec { if compute { &self.compute @@ -2816,6 +3168,109 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) { } } +/// The pixel shaders whose draws get their slots listed +/// ([`State::slots_text`]): `VICTORY_LIST_SLOTS`, hash prefixes separated +/// by commas. None by default. +#[cfg(feature = "diagnostics")] +fn list_slots() -> &'static [String] { + static LIST: std::sync::OnceLock> = std::sync::OnceLock::new(); + LIST.get_or_init(|| { + std::env::var("VICTORY_LIST_SLOTS") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_ascii_lowercase()) + .filter(|s| !s.is_empty()) + .collect() + }) +} + +/// A fingerprint of the 4 KiB of title memory at `at` (FNV-1a, 64 bits; of +/// 4 KiB of zeros it is always the same value, which `slots.py` knows), or +/// "unreadable". +#[cfg(feature = "diagnostics")] +fn print_4k(at: u64) -> String { + let mut bytes = [0u8; 4096]; + if at == 0 || !crate::host::read_into(at as *const u8, &mut bytes) { + return "unreadable".into(); + } + let mut hash = 0xcbf2_9ce4_8422_2325_u64; + for b in bytes { + hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3); + } + format!("{hash:016x}") +} + +/// The `bytes` of title memory at `at`: how many are mapped, and the +/// fingerprints of the first and the last 4 KiB (a texture's smallest +/// levels lie first, its largest last). +#[cfg(feature = "diagnostics")] +fn memory_state(at: u64, bytes: u64) -> String { + let mapped = crate::texture::mapped_bytes(at as *const u8, bytes as usize); + let last = at + bytes.saturating_sub(4096); + format!("memory={at:#x} mapped={mapped}/{bytes} first4k={} last4k={}", print_4k(at), print_4k(last)) +} + +/// Title texture `this` for the frame listing: its size, whether it has a +/// host copy (not made here), its staging buffer's state, whether the host +/// copied into it, and its memory ([`memory_state`]). +#[cfg(feature = "diagnostics")] +fn texture_state(this: This) -> String { + let Some((at, desc)) = crate::resource::texture_memory(this) else { + return "not a texture".into(); + }; + // SAFETY: 56 bytes in the description's layout. + let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() }; + let bytes = crate::resource::placed_bytes(&words).unwrap_or(0); + let staged = match crate::texture::staged_state(this) { + Some((uploaded, dirty)) => format!("staged=yes uploaded={uploaded} dirty={dirty}"), + None => "staged=no".into(), + }; + format!( + "{}x{} f{} levels={} host_copy={} {staged} host_written={} title_fills={} {}", + u64::from(words[4]) | u64::from(words[5]) << 32, + words[6], + words[8], + words[7] >> 16, + crate::resource::host_made(this).is_some(), + crate::texture::host_wrote(this as usize), + crate::resource::title_fills(this), + memory_state(at as u64, bytes) + ) +} + +/// A view of the title's heap for the frame listing: a texture with its +/// state ([`texture_state`]; a placed one that has no resource yet with +/// its memory alone), anything else in a few words. +#[cfg(feature = "diagnostics")] +fn view_state(view: Option<&View>) -> String { + match view { + None => "no view".into(), + Some(View::Placed(false, r, d)) if r[0] != 1 => { + let address = u64::from(d[10]) | u64::from(d[11]) << 32; + let state = match crate::resource::texture_at_made(address, r) { + Some(this) => texture_state(this), + None => format!( + "{}x{} f{} levels={} resource=none {}", + u64::from(r[4]) | u64::from(r[5]) << 32, + r[6], + r[8], + r[7] >> 16, + memory_state(address, crate::resource::placed_bytes(r).unwrap_or(0)) + ), + }; + format!("placed texture view_format={} {state}", d[0]) + } + Some(View::Shader(r, d)) if crate::resource::texture_memory(*r as This).is_some() => { + format!( + "texture object {r:#x} view_format={} {}", + d.as_ref().map_or(0, |d| d[0]), + texture_state(*r as This) + ) + } + Some(v) => format!("{v:?}").chars().take(80).collect(), + } +} + /// A view in a few words (diagnostics builds). #[cfg(feature = "diagnostics")] fn describe(view: Option<&View>) -> String { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b384328..492ae72 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2692,6 +2692,19 @@ fn declared_writes(runs: &[&HostList]) -> Vec { back } +/// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log +/// lines that say what the title's CPU was given while it decided whether +/// the camera is in a room. The values of the small read-backs +/// ([`read_backs`]), the frame's main pass by scissor rectangle with its +/// culling dispatches (`draw.rs`, `walls_census`), the shader-written +/// buffers merged into title memory (`shadow.rs`, `walls_merged`), host +/// copies found stale after their refresh (`shadow.rs`), and, in the +/// runtime, the read requests that fail (with 2: every request). +pub(crate) fn walls_trace() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2")) +} + /// After `list` has run: the texels its read-backs copied into host /// buffers of ours go to the title's memory (`HostList::defer_read_back`). /// @@ -2711,6 +2724,19 @@ fn read_backs(list: &HostList) { for line in 0..*rows { std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row); } + // The walls trace: what the title is handed (one row of at + // most 24 values: its 5x1 and 1x1 float targets). + if walls_trace() && *rows == 1 && *row <= 96 { + let mut values = [0f32; 24]; + std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::(), *row & !3); + tracing::info!( + frame = crate::frame::current(), + to = format_args!("{:#x}", *at), + bytes = *row, + values = ?&values[..*row / 4], + "walls trace: a read-back lands in title memory" + ); + } buffer.Unmap(0, None); } } @@ -3424,7 +3450,9 @@ impl Host { // SAFETY: the mapping of the fetched bytes, `total` of them; // the copy into it has run. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) }; - written += shadow.card_merge_relay(*lo, gpu, after, &mut title); + let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title); + shadow.walls_merged(gpu.len(), merged); + written += merged; } COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); // Sends up to `after` are of no use to any later merge. @@ -3653,7 +3681,9 @@ impl Host { // the copy into it has run, and the caller // waits for this job. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) }; - counts[i].fetch_add(shadow.card_merge(lo, gpu, &mut title), Ordering::Relaxed); + let merged = shadow.card_merge(lo, gpu, &mut title); + shadow.walls_merged(gpu.len(), merged); + counts[i].fetch_add(merged, Ordering::Relaxed); } }) as Box }) @@ -3668,7 +3698,9 @@ impl Host { // SAFETY: the mapping of the fetched bytes, `total` of // them; the copy into it has run. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) }; - written[i] += plan.ranges[i].shadow.card_merge(lo, gpu, &mut title); + let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title); + plan.ranges[i].shadow.walls_merged(gpu.len(), merged); + written[i] += merged; } } } @@ -5978,7 +6010,17 @@ impl Host { .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0)) }; match resized { - Ok(()) => (p.width, p.height, p.format) = (width, height, format), + Ok(()) => { + (p.width, p.height, p.format) = (width, height, format); + tracing::info!( + width, + height, + format = format.0, + frame, + "the swap chain's buffers were made again for another size or format" + ); + self.log_video_memory("right after the swap chain's buffers were made again"); + } Err(e) => { tracing::warn!(error = %e, width, height, "swap chain not resized"); return None; @@ -6072,6 +6114,7 @@ impl Host { Some(hwnd) => hwnd, None => window(width, height)?, }; + self.log_video_memory("right before the swap chain is made"); // SAFETY: plain object creation for our window. unsafe { let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; @@ -6094,6 +6137,7 @@ impl Host { let copy = self.new_list()?; copy.close(); tracing::info!(width, height, format = format.0, "presenting to a window"); + self.log_video_memory("right after the swap chain is made"); Ok(Presenter { swap_chain, width, @@ -6173,9 +6217,71 @@ impl Host { .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) .ok()?; } + // The card's budget moved by 256 MB or more since the last look: + // said at once, with what was in use at the last look, so the log + // has the moment. (It fell from 11,242 MB to some 10,300 MB with + // the first world frame in runs 179 to 185, and the memory line, + // seconds later, was the first to show it. We reserve nothing + // and make the swap chain once, at the start.) + static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage]; + let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed)); + if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) { + tracing::info!( + "the system changed the budget of the card's memory from {} MB to {} MB (frame {}); at the last look {} MB of the card's and {} MB of the PC's shared memory were in use", + last[0] >> 20, + own.Budget >> 20, + crate::frame::current(), + last[1] >> 20, + last[2] >> 20 + ); + self.log_video_memory("right after that change"); + } Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage]) } + /// Both of the system's memory groups for this process, in bytes: for + /// the card's own memory and then for the PC's memory shared with the + /// card, the budget, the use, what could still be reserved and what + /// is reserved (the layer reserves none). + pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> { + let adapter = self.adapter.as_ref()?; + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: plain queries that fill our structures. + unsafe { + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) + .ok()?; + } + let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| { + [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation] + }; + Some([all(&own), all(&shared)]) + } + + /// Logs [`Self::video_memory_groups`], with `when` it is said. + pub(crate) fn log_video_memory(&self, when: &str) { + let Some([own, shared]) = self.video_memory_groups() else { + return; + }; + tracing::info!( + "video memory as the system counts it, {}: the card's own: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved; the PC's shared with the card: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved (the layer reserves none)", + when, + own[0] >> 20, + own[1] >> 20, + own[2] >> 20, + own[3] >> 20, + shared[0] >> 20, + shared[1] >> 20, + shared[2] >> 20, + shared[3] >> 20 + ); + } + /// A buffer in system memory that the CPU maps (write-back, so reading /// it is fast too) and shaders read and write: for host copies of title /// memory that shaders write, which upload memory cannot be. Starts in diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index bff1577..321cc63 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -1214,3 +1214,604 @@ void main() { list.reset(); } } + +/// What one small draw costs this card, bare and with one thing changed +/// between every two draws: a measurement, not a check (it asserts only +/// that the card answered). The timing run of the lit scene (run 187) has +/// some 11,000 small commands a frame at 5 to 16 microseconds each, and no +/// log says whether that is what we put around a command or what the card +/// takes for one. Each variant here is 10,000 one-triangle draws into a +/// 2560x1440 target, timed on the card by one pair of timestamps around +/// the whole batch (not one per command, which would time the stamps). +/// +/// Run by name, no game needed: +/// `cargo test -p victory-gpu --release -- --ignored bare_command_cost --nocapture` +#[cfg(test)] +mod bare_cost { + use windows::Win32::Foundation::{HANDLE, RECT}; + use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY}; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + use windows::core::{Interface, s}; + + use crate::host::{compile, transition}; + + /// Draws in a batch. + const DRAWS: u32 = 10_000; + const WIDTH: u32 = 2560; + const HEIGHT: u32 = 1440; + + /// One small triangle in the middle of the target (about 180 pixels), + /// and two pixel programs that read one texel of a texture through a + /// table, so that the view heap set is in use. + const DRAW: &str = r#" +#define RS "DescriptorTable(SRV(t0))" +Texture2D image : register(t0); +[RootSignature(RS)] +float4 corner(uint i : SV_VertexID) : SV_Position { + float2 p = float2((i << 1) & 2, i & 2); + return float4(p * 0.02 - 0.01, 0.5, 1.0); +} +[RootSignature(RS)] +float4 first(float4 at : SV_Position) : SV_Target { + return image.Load(int3(0, 0, 0)); +} +[RootSignature(RS)] +float4 second(float4 at : SV_Position) : SV_Target { + return 1.0 - image.Load(int3(0, 0, 0)); +} +"#; + + /// A compute pass of next to nothing, as our clamp of an indirect + /// record is: one group of one thread that writes one word. + const WORK: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer words : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void work() { + words.Store(0, words.Load(0) + 1); +} +"#; + + /// What changes between every two draws of a batch. + #[derive(Clone, Copy, PartialEq)] + enum Between { + /// Nothing. + Nothing, + /// The pipeline: two alternate. + Pipeline, + /// A second texture goes from target to shader read and back. + BarrierPair, + /// The depth texture bound for testing goes from write to read or + /// back. + DepthMove, + /// The pair of descriptor heaps: two pairs alternate. + Heaps, + /// The colour target: two alternate. + Targets, + /// A compute pass of ours of one group, and the pipeline back. + Compute, + /// The same between two waits for every earlier shader write, as + /// the clamp records them. + ComputeWithWaits, + } + + struct Rig { + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + submitted: u64, + event: HANDLE, + root: ID3D12RootSignature, + pipelines: [ID3D12PipelineState; 2], + work_root: ID3D12RootSignature, + work: ID3D12PipelineState, + words: ID3D12Resource, + other: ID3D12Resource, + depth: ID3D12Resource, + /// Kept alive: the views below name them. + _kept: Vec, + _target_heaps: [ID3D12DescriptorHeap; 2], + heap_pairs: [[Option; 2]; 2], + tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2], + targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2], + depth_written: D3D12_CPU_DESCRIPTOR_HANDLE, + depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE, + stamps: ID3D12QueryHeap, + back: ID3D12Resource, + card: String, + } + + fn texture( + device: &ID3D12Device, + (width, height): (u32, u32), + format: DXGI_FORMAT, + flags: D3D12_RESOURCE_FLAGS, + state: D3D12_RESOURCE_STATES, + ) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(width), + Height: height, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: flags, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: plain texture creation. + unsafe { + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + fn buffer( + device: &ID3D12Device, + size: u64, + kind: D3D12_HEAP_TYPE, + flags: D3D12_RESOURCE_FLAGS, + state: D3D12_RESOURCE_STATES, + ) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: plain buffer creation. + unsafe { + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + fn heap(device: &ID3D12Device, kind: D3D12_DESCRIPTOR_HEAP_TYPE, count: u32, visible: bool) -> ID3D12DescriptorHeap { + let flags = if visible { + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE + } else { + D3D12_DESCRIPTOR_HEAP_FLAG_NONE + }; + // SAFETY: plain heap creation. + unsafe { + device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: flags, + NodeMask: 0, + }) + .unwrap() + } + } + + fn pipeline(device: &ID3D12Device, root: &ID3D12RootSignature, vs: &[u8], ps: &[u8]) -> ID3D12PipelineState { + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = 0xf; + let mut formats = [DXGI_FORMAT(0); 8]; + formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + // SAFETY: the description points at live data and never releases + // its pointer to the root signature. + unsafe { + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(root), + VS: code(vs), + PS: code(ps), + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // Depth is tested and never written, so the texture may be + // in the write state or in the read state under one view. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: formats, + DSVFormat: DXGI_FORMAT_D32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + device.CreateGraphicsPipelineState(&desc).unwrap() + } + } + + impl Rig { + /// The default adapter, as the layer takes it; `None` without one + /// or on a software adapter. + fn new() -> Option { + let vs = compile(DRAW, s!("corner"), s!("vs_5_1")).ok()?; + let ps = [ + compile(DRAW, s!("first"), s!("ps_5_1")).ok()?, + compile(DRAW, s!("second"), s!("ps_5_1")).ok()?, + ]; + let cs = compile(WORK, s!("work"), s!("cs_5_1")).ok()?; + // SAFETY: plain object creation on a device of our own; the + // views are made in heaps that live as long as the rig. + unsafe { + let mut device: Option = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let desc = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|factory| factory.EnumAdapterByLuid::(device.GetAdapterLuid())) + .ok()? + .cast::() + .ok()? + .GetDesc1() + .ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { + return None; + } + let card = String::from_utf16_lossy(&desc.Description) + .trim_end_matches('\0') + .to_owned(); + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let allocator: ID3D12CommandAllocator = + device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs[..]).ok()?; + let pipelines = [ + pipeline(&device, &root, &vs, &ps[0]), + pipeline(&device, &root, &vs, &ps[1]), + ]; + let work_root: ID3D12RootSignature = device.CreateRootSignature(0, &cs[..]).ok()?; + let work: ID3D12PipelineState = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&work_root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }) + .ok()?; + + let size = (WIDTH, HEIGHT); + let colour = |state| texture(&device, size, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, state); + let target = [ + colour(D3D12_RESOURCE_STATE_RENDER_TARGET), + colour(D3D12_RESOURCE_STATE_RENDER_TARGET), + ]; + let other = colour(D3D12_RESOURCE_STATE_RENDER_TARGET); + let depth = texture( + &device, + size, + DXGI_FORMAT_D32_FLOAT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + ); + let image = texture( + &device, + (4, 4), + DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + ); + let words = buffer( + &device, + 64 << 10, + D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ); + let back = buffer( + &device, + 16, + D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let mut stamps: Option = None; + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2, + NodeMask: 0, + }, + &mut stamps, + ) + .ok()?; + let stamps = stamps?; + + // Target and depth views. + let rtvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, false); + let rtv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + let mut targets = [rtvs.GetCPUDescriptorHandleForHeapStart(); 2]; + targets[1].ptr += rtv_step; + device.CreateRenderTargetView(&target[0], None, targets[0]); + device.CreateRenderTargetView(&target[1], None, targets[1]); + let dsvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, false); + let dsv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + let depth_written = dsvs.GetCPUDescriptorHandleForHeapStart(); + let mut depth_tested = depth_written; + depth_tested.ptr += dsv_step; + device.CreateDepthStencilView(&depth, None, depth_written); + let tested = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D32_FLOAT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + Flags: D3D12_DSV_FLAG_READ_ONLY_DEPTH, + ..Default::default() + }; + device.CreateDepthStencilView(&depth, Some(&tested), depth_tested); + + // Two pairs of shader-visible heaps: views (one view of the + // small texture each) and samplers (none used). + let view_heaps = [ + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true), + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true), + ]; + let sampler_heaps = [ + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), + ]; + for views in &view_heaps { + device.CreateShaderResourceView(&image, None, views.GetCPUDescriptorHandleForHeapStart()); + } + let tables = [ + view_heaps[0].GetGPUDescriptorHandleForHeapStart(), + view_heaps[1].GetGPUDescriptorHandleForHeapStart(), + ]; + let heap_pairs = [ + [Some(view_heaps[0].clone()), Some(sampler_heaps[0].clone())], + [Some(view_heaps[1].clone()), Some(sampler_heaps[1].clone())], + ]; + + // The first list: both targets and the depth texture cleared. + list.ClearRenderTargetView(targets[0], &[0.0; 4], None); + list.ClearRenderTargetView(targets[1], &[0.0; 4], None); + list.ClearDepthStencilView(depth_written, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None); + let [first_target, second_target] = target; + let mut rig = Rig { + queue, + allocator, + list, + fence, + submitted: 0, + event, + root, + pipelines, + work_root, + work, + words, + other, + depth, + _kept: vec![first_target, second_target, image], + _target_heaps: [rtvs, dsvs], + heap_pairs, + tables, + targets, + depth_written, + depth_tested, + stamps, + back, + card, + }; + rig.finish(); + Some(rig) + } + } + + /// Closes the open list, runs it, waits for the card and opens the + /// list again. + fn finish(&mut self) { + self.submitted += 1; + // SAFETY: our list, queue and fence; the allocator is reset + // only after the card finished everything recorded from it. + unsafe { + self.list.Close().unwrap(); + let run: ID3D12CommandList = self.list.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + self.queue.Signal(&self.fence, self.submitted).unwrap(); + self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap(); + WaitForSingleObject(self.event, INFINITE); + self.allocator.Reset().unwrap(); + self.list.Reset(&self.allocator, None).unwrap(); + } + } + + /// What every list starts with: a new list has nothing set. + fn begin(&self) { + let l = &self.list; + // SAFETY: an open list and live objects and views. + unsafe { + l.SetDescriptorHeaps(&self.heap_pairs[0]); + l.SetGraphicsRootSignature(&self.root); + l.SetPipelineState(&self.pipelines[0]); + l.SetGraphicsRootDescriptorTable(0, self.tables[0]); + l.OMSetRenderTargets(1, Some(&self.targets[0]), false, Some(&self.depth_tested)); + l.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: WIDTH as f32, + Height: HEIGHT as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + l.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: WIDTH as i32, + bottom: HEIGHT as i32, + }]); + // A triangle list. + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4)); + } + } + + /// One batch of [`DRAWS`] draws in `lists` lists run one by one, + /// with `between` recorded before every draw: the microseconds a + /// draw took on the card, and the milliseconds recording took. + fn batch(&mut self, between: Between, lists: u32) -> (f64, f64) { + let (target, read, written, tested) = ( + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_DEPTH_READ, + ); + let started = std::time::Instant::now(); + let mut drawn = 0u32; + for part in 0..lists { + let l = &self.list; + // SAFETY: an open list; our query heap; live objects. + unsafe { + if part == 0 { + l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + } + } + self.begin(); + // SAFETY: an open list with everything set; live objects. + // Every state moved is moved back within the batch (the + // draws of a list are an even number). + unsafe { + for _ in 0..DRAWS / lists { + let odd = (drawn % 2) as usize; + match between { + Between::Nothing => {} + Between::Pipeline => l.SetPipelineState(&self.pipelines[odd]), + Between::BarrierPair => { + l.ResourceBarrier(&[transition(&self.other, target, read)]); + l.ResourceBarrier(&[transition(&self.other, read, target)]); + } + Between::DepthMove => { + let (from, to) = if odd == 0 { (written, tested) } else { (tested, written) }; + l.ResourceBarrier(&[transition(&self.depth, from, to)]); + } + Between::Heaps => { + l.SetDescriptorHeaps(&self.heap_pairs[odd]); + l.SetGraphicsRootDescriptorTable(0, self.tables[odd]); + } + Between::Targets => { + l.OMSetRenderTargets(1, Some(&self.targets[odd]), false, Some(&self.depth_tested)); + } + Between::Compute | Between::ComputeWithWaits => { + let waits = between == Between::ComputeWithWaits; + if waits { + l.ResourceBarrier(&[super::uav_barrier()]); + } + l.SetComputeRootSignature(&self.work_root); + l.SetPipelineState(&self.work); + l.SetComputeRootUnorderedAccessView(0, self.words.GetGPUVirtualAddress()); + l.Dispatch(1, 1, 1); + if waits { + l.ResourceBarrier(&[super::uav_barrier()]); + } + l.SetPipelineState(&self.pipelines[0]); + } + } + l.DrawInstanced(3, 1, 0, 0); + drawn += 1; + } + if part + 1 < lists { + // The next list of the batch: this one is sent on + // its own and the list is opened again at once + // (the allocator is not reset before the card is + // done with all of them). + l.Close().unwrap(); + let run: ID3D12CommandList = l.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + l.Reset(&self.allocator, None).unwrap(); + } else { + l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); + l.ResolveQueryData(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &self.back, 0); + } + } + } + let recording = started.elapsed().as_secs_f64() * 1e3; + self.finish(); + let mut data = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: 0, End: 16 }; + // SAFETY: a read-back buffer the finished list resolved two + // timestamps into. + let ticks = unsafe { + self.back.Map(0, Some(&range), Some(&mut data)).unwrap(); + let stamps = std::slice::from_raw_parts(data.cast::(), 2).to_vec(); + self.back.Unmap(0, None); + stamps[1].saturating_sub(stamps[0]) + }; + // SAFETY: a plain query of our queue. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1).max(1); + (ticks as f64 * 1e6 / frequency as f64 / f64::from(drawn.max(1)), recording) + } + } + + #[test] + #[ignore = "a measurement on the card: run it by name with --ignored --nocapture"] + fn bare_command_cost() { + let Some(mut rig) = Rig::new() else { + eprintln!("no hardware adapter, or our shaders did not compile; skipped"); + return; + }; + eprintln!("bare command cost on {}: {DRAWS} one-triangle draws into {WIDTH}x{HEIGHT}, three batches each", rig.card); + // The first batch pays for whatever the driver does at first use. + rig.batch(Between::Nothing, 1); + let variants = [ + ("(a) nothing changes between draws", Between::Nothing, 1), + ("(b) another pipeline every draw", Between::Pipeline, 1), + ("(c) a barrier pair on a second texture every draw", Between::BarrierPair, 1), + ("(d) the tested depth texture moved between write and read every draw", Between::DepthMove, 1), + ("(e) another pair of descriptor heaps every draw", Between::Heaps, 1), + ("(f) another colour target every draw", Between::Targets, 1), + ("(g) nothing changes, in 100 lists run one by one", Between::Nothing, 100), + ("(h) a compute pass of ours of one group before every draw", Between::Compute, 1), + ("(i) the same pass between two waits for earlier shader writes", Between::ComputeWithWaits, 1), + ]; + let mut least = Vec::new(); + for (name, between, lists) in variants { + let mut runs: Vec<(f64, f64)> = (0..3).map(|_| rig.batch(between, lists)).collect(); + runs.sort_by(|a, b| a.0.total_cmp(&b.0)); + eprintln!( + "{name}: {:.2} microseconds a draw on the card (the three: {:.2}, {:.2}, {:.2}); recording took {:.1} ms", + runs[0].0, runs[0].0, runs[1].0, runs[2].0, runs[0].1 + ); + least.push(runs[0].0); + } + assert!(least.iter().all(|us| us.is_finite() && *us > 0.0), "the card gave no time for a batch"); + } +} diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index bb6a00a..e4fee24 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1402,6 +1402,210 @@ fn room_percent() -> u64 { }) } +/// For the card accounting line ([`card_accounting`]): the title texture +/// made for a view of memory at `address` with the resource description +/// `desc`, if there is one ([`texture_at`] makes it; this does not). +#[cfg(windows)] +pub(crate) fn placed_known(address: u64, desc: &[u32; 14]) -> Option { + // Without the filler words and with them: whichever `texture_at` keeps. + let mut key = *desc; + key[1] = 0; + key[13] = 0; + let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + map.get(&(address, key)).or_else(|| map.get(&(address, *desc))).map(|&r| r as This) +} + +/// For the card accounting line: whether title texture `this` has a host +/// copy now (2), had one that was let go and not made again (1), or never +/// had one (0); the bytes (its host copy's on the card, or without one +/// what its console layout takes in title memory); and where its title +/// memory is. `None` for buffers. Not a use of the texture. +#[cfg(windows)] +pub(crate) fn copy_state(this: This) -> Option<(u8, u64, u64)> { + use std::sync::atomic::Ordering::Relaxed; + if this.is_null() { + return None; + } + let r = resource(this); + if r.desc.dimension == BUFFER { + return None; + } + let memory = r.data() as u64; + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + Some(match made.as_ref() { + Some((host, _)) => (2, host.bytes, memory), + None => (u8::from(r.host.gone.load(Relaxed)), footprint(&r.desc).map_or(0, |f| f.size), memory), + }) +} + +/// One line of where the card's memory is and what the queue of textures +/// picked by index would need (`VICTORY_CARD_ACCOUNTING=1`; `draw.rs` +/// `card_accounting` says when, and hands over the queue's side: `room` +/// as the pass found it, `due` its counts, `never` and `gone` the memory +/// of the due textures without a host copy). The line holds +/// - the host copies of textures the title fills that are alive: how +/// many, their bytes, and the bytes of the levels whose title memory is +/// not mapped (a host copy is made with every level of the description; +/// a texture streaming in has its small levels only). A copy's bytes +/// are shared out to its levels by their texels, so that part is an +/// estimate; +/// - the due slots: how many, and their textures by what they have on +/// the card (a host copy alive: no card memory needed; never one; one +/// that was let go), with the bytes the last two would need and how +/// much of their memory is mapped now; +/// - the host copies let go, made again and made since the line before. +/// +/// The textures are noted under the table's lock (their memory, their +/// description, their copy's bytes: about a millisecond for 18,000) and +/// the kernel is asked about their memory on a thread of its own, after +/// the lock is given back: one question for a texture that is all there +/// (up to 256 pages each; 18,000 textures of 5.5 GB are 1.4 million +/// pages, some 20,000 questions), one per level and array slice more for +/// one that is not. Not measured: a tenth to half a second is expected, +/// and the line says what it took. No line is begun while one is walking. +#[cfg(windows)] +pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, gone: Vec<(u64, u64)>) { + use std::sync::atomic::Ordering::Relaxed; + static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + // Host copies let go and their bytes, made again and their bytes, and + // made in all, at the line before. + static BEFORE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + if WALKING.swap(true, Relaxed) { + return; + } + let began = std::time::Instant::now(); + let mut copies: Vec<(usize, ResourceDesc, u64)> = Vec::new(); + // Textures the title fills without a host copy: never one, one let go. + let mut without = [0u64; 2]; + { + let all = textures(); + for &at in all.iter() { + // SAFETY: as in `let_go_idle`. + let r = unsafe { &*(at as *const Resource) }; + if !fills(&r.desc) { + continue; + } + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + match made.as_ref() { + Some((host, _)) => copies.push((r.data() as usize, r.desc, host.bytes)), + None => without[usize::from(r.host.gone.load(Relaxed))] += 1, + } + } + } + let kinds = KINDS.each_ref().map(|k| k.load(Relaxed)); + let mut since = [0u64; 5]; + for ((slot, now), before) in since.iter_mut().zip([kinds[2], kinds[3], kinds[4], kinds[5], kinds[6]]).zip(&BEFORE) { + *slot = now.saturating_sub(before.swap(now, Relaxed)); + } + let video = crate::host::host().and_then(|h| h.video_memory()); + let noted_us = began.elapsed().as_micros() as u64; + let walk = move || { + fn texels(m: &texture::Mip) -> u64 { + u64::from(m.width) * u64::from(m.height) * u64::from(m.depth) + } + let began = std::time::Instant::now(); + // Copies; their bytes; the bytes of levels not mapped; copies with + // a level not mapped; with the largest level not mapped; with no + // level mapped; copies without a console layout (not asked). + let mut c = [0u64; 7]; + for &(memory, desc, bytes) in &copies { + c[0] += 1; + c[1] += bytes; + let Some(layout) = texture_layout(&desc).map(|t| t.planes[0].layout.clone()) else { + c[6] += 1; + continue; + }; + if layout.size == 0 || crate::texture::committed(memory as *const u8, layout.size as usize) { + continue; + } + c[3] += 1; + // Every slice holds the whole chain: the levels of the tail in + // its first block, the others after it from the smallest up + // (`victory_formats::texture::Layout`). + let mips = &layout.mips; + let tail = (layout.first_tail_mip as usize).min(mips.len()); + let there = |from: u64, to: u64| { + (0..u64::from(layout.slices)).all(|slice| { + let at = memory as u64 + slice * layout.slice_size + from; + crate::texture::committed(at as *const u8, (to - from) as usize) + }) + }; + let all: u64 = mips.iter().map(texels).sum::().max(1); + let (mut missing, mut any) = (0u64, false); + for (level, m) in mips.iter().enumerate().take(tail) { + let end = if level == 0 { layout.slice_size } else { mips[level - 1].offset }; + if end <= m.offset { + continue; + } + if there(m.offset, end) { + any = true; + } else { + missing += texels(m); + c[4] += u64::from(level == 0); + } + } + if tail < mips.len() { + if there(0, layout.alignment.min(layout.slice_size).max(1)) { + any = true; + } else { + missing += mips[tail..].iter().map(texels).sum::(); + } + } + c[2] += (u128::from(bytes) * u128::from(missing) / u128::from(all)) as u64; + c[5] += u64::from(!any); + } + // Of the due textures without a host copy: how many; the bytes of + // their memory; with all of it mapped, and those bytes; with part + // of it mapped, and the bytes that are; with none of it mapped. + let mapped = |list: &[(u64, u64)]| { + let mut n = [0u64; 7]; + for &(at, len) in list { + n[0] += 1; + n[1] += len; + let there = crate::texture::mapped_bytes(at as *const u8, len as usize); + if len > 0 && there >= len { + n[2] += 1; + n[3] += len; + } else if there > 0 { + n[4] += 1; + n[5] += there; + } else { + n[6] += 1; + } + } + n + }; + let (never, gone) = (mapped(&never), mapped(&gone)); + let [budget_mb, used_mb] = video.map_or([0, 0], |v| [v[0] >> 20, v[1] >> 20]); + let [copies_n, copies_mb, unmapped_mb, partly, largest, nothing, unknown] = + [c[0], c[1] >> 20, c[2] >> 20, c[3], c[4], c[5], c[6]]; + let [without_never, without_gone] = without; + let [due_slots, due_uploaded, due_other, alive_n, alive_mb] = [due[0], due[1], due[2], due[3], due[4] >> 20]; + let [never_n, never_mb, never_whole, never_whole_mb, never_part, never_part_mb, never_none] = + [never[0], never[1] >> 20, never[2], never[3] >> 20, never[4], never[5] >> 20, never[6]]; + let [gone_n, gone_mb, gone_whole, gone_whole_mb, gone_part, gone_part_mb, gone_none] = + [gone[0], gone[1] >> 20, gone[2], gone[3] >> 20, gone[4], gone[5] >> 20, gone[6]]; + let [let_go, let_go_mb, again, again_mb, made] = [since[0], since[1] >> 20, since[2], since[3] >> 20, since[4]]; + let walk_ms = began.elapsed().as_millis() as u64; + tracing::info!( + "card accounting: room {room}, the card {used_mb} MB in use of a budget of {budget_mb} MB; host copies of textures the title \ + fills: {copies_n} alive {copies_mb} MB, of which {unmapped_mb} MB are levels whose title memory is not mapped ({partly} copies \ + with such a level, {largest} of them the largest level, {nothing} with no level mapped; {unknown} without a console layout, not \ + asked); title textures without a host copy: {without_never} never had one, {without_gone} had one let go; due slots: \ + {due_slots} ({due_uploaded} uploaded before, {due_other} of nothing the title fills), their textures: {alive_n} with a host \ + copy alive ({alive_mb} MB, no card memory needed); {never_n} that never had one ({never_mb} MB of title memory: {never_whole} \ + all mapped {never_whole_mb} MB, {never_part} in part {never_part_mb} MB mapped, {never_none} not mapped); {gone_n} whose host \ + copy was let go ({gone_mb} MB: {gone_whole} all mapped {gone_whole_mb} MB, {gone_part} in part {gone_part_mb} MB mapped, \ + {gone_none} not mapped); since the line before: {let_go} host copies let go {let_go_mb} MB, {again} made again {again_mb} MB, \ + {made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own" + ); + WALKING.store(false, Relaxed); + }; + if std::thread::Builder::new().name("card accounting".into()).spawn(walk).is_err() { + WALKING.store(false, Relaxed); + } +} + /// Lets go of the host copies of textures the title fills that nothing /// names any more: placed textures were never released (one host texture /// per address and description ever viewed: 18,639 of them, 2.5 GB, after @@ -2067,6 +2271,19 @@ pub(crate) fn placed_bytes(desc: &[u32; 14]) -> Option { footprint(&d).map(|f| f.size) } +/// The resource [`texture_at`] made for a texture placed at `address` with +/// the description `desc`, if it has made one: never made here (for the +/// frame listing, which must not count as a use). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option { + let mut key = *desc; + key[1] = 0; + key[13] = 0; + let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + let found = map.get(&(address, key)).or_else(|| map.get(&(address, *desc)))?; + Some(*found as This) +} + /// 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/shadow.rs b/crates/victory-gpu/src/shadow.rs index da412f8..133e871 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2403,6 +2403,7 @@ impl Shadow { if let Some((now, written)) = crate::watch::writes(from, to, true) { self.watched.store(1, Ordering::Relaxed); let copied = self.copy_stale(from, to, now, &written); + self.refresh_check(from, to); #[cfg(feature = "diagnostics")] { use crate::copystat::{C, add}; @@ -2423,6 +2424,63 @@ impl Shadow { to - from } + /// Diagnostic (`VICTORY_REFRESH_CHECK=1`; off by default): after a + /// refresh of `[from, to)` that trusted the write watch or the guards, + /// the first 256 bytes of every 64 KiB block of it are read from title + /// memory and compared with the copy. A block that differs on three + /// refreshes in a row was changed with nothing to tell of it (a write + /// through another view of its pages, as DirectStorage's page + /// destinations make) and the card reads old bytes there: said with + /// the copy and the address. One that differs once is a write of the + /// title's that arrived between the refresh and the look. + fn refresh_check(&self, from: usize, to: usize) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1") || crate::host::walls_trace()) { + return; + } + const SAMPLE: usize = 256; + // Blocks found differing: how many refreshes in a row. + static DIFFERING: Mutex>> = Mutex::new(None); + static SAID: AtomicU64 = AtomicU64::new(0); + let start = self.start as usize; + let mut title = [0u8; SAMPLE]; + let mut at = from; + while at < to { + let n = SAMPLE.min(to - at); + if crate::host::read_into(at as *const u8, &mut title[..n]) { + // SAFETY: `[from, to)` lies inside the buffer (`update`), + // so these bytes are inside the copy's mapping. + let copy = unsafe { std::slice::from_raw_parts(self.data.add(at - start).cast_const(), n) }; + let mut map = DIFFERING.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_with(Default::default); + if copy == &title[..n] { + map.remove(&at); + } else { + let times = map.entry(at).or_insert(0); + *times += 1; + if *times == 3 { + let said = SAID.fetch_add(1, Ordering::Relaxed) + 1; + if said <= 64 || said.is_power_of_two() { + tracing::warn!( + said, + copy = self.id, + copy_start = format_args!("{start:#x}"), + copy_bytes = self.len, + address = format_args!("{at:#x}"), + refreshed = format_args!("{from:#x}..{to:#x}"), + on_the_card = self.card.is_some(), + window = self.window, + "a host copy of title memory is stale after its refresh, three times in a row: the memory changed with nothing to tell of it (VICTORY_REFRESH_CHECK=1)" + ); + } + } + } + } + // The first bytes of the next 64 KiB block. + at = (at / PAGE + 1) * PAGE; + } + } + /// Copies the pages of `[from, to)` written after their last copy /// (`written`: last writes by page, in page order; `now`: this /// asking), whole pages within the buffer. @@ -2542,6 +2600,42 @@ impl Shadow { card_piece_of(self.start as usize, self.len as usize, span, i) } + /// The walls trace (`crate::host::walls_trace`): a piece of `fetched` + /// bytes of this copy came back from the card and `written` of them + /// went into title memory. Summed per buffer and logged once a frame: + /// which shader-written buffers the title's CPU could see fresh in + /// that frame, and how much of each changed. + pub(crate) fn walls_merged(&self, fetched: usize, written: usize) { + if !crate::host::walls_trace() { + return; + } + static SEEN: Mutex<(u64, BTreeMap)> = Mutex::new((0, BTreeMap::new())); + let frame = crate::frame::current(); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if seen.0 != frame { + let buffers: Vec = seen + .1 + .iter() + .map(|(at, v)| format!("{at:#x}+{:#x}: {} pieces, {} fetched, {} written", v.0, v.1, v.2, v.3)) + .take(32) + .collect(); + if !buffers.is_empty() { + tracing::info!( + frame = seen.0, + count = seen.1.len(), + buffers = ?buffers, + "walls trace: shader-written card buffers merged into title memory in this frame" + ); + } + seen.1.clear(); + seen.0 = frame; + } + let entry = seen.1.entry(self.start).or_insert((self.len, 0, 0, 0)); + entry.1 += 1; + entry.2 += fetched as u64; + entry.3 += written as u64; + } + /// After a submission, for a copy in the card's memory: `gpu` is what /// the card's side holds at offset `at` on, in a piece the compare /// found differing. The bytes shaders wrote (those that differ from the diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 41d6f1e..34e7d51 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -915,6 +915,16 @@ pub(crate) fn fingerprint(at: u64, len: u64) -> u64 { /// Whether a title texture has a staging buffer: a list recorded its /// upload, and the lists that sample it check it at submission. +/// For the frame listing: whether a list has uploaded `resource`'s staging +/// buffer, and whether it was detiled since. None: it has none. +#[cfg(feature = "diagnostics")] +pub(crate) fn staged_state(resource: This) -> Option<(bool, bool)> { + use std::sync::atomic::Ordering::Relaxed; + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let staging = map.as_ref()?.get(&(resource as usize))?; + Some((staging.uploaded.load(Relaxed), staging.dirty.load(Relaxed))) +} + pub(crate) fn is_staged(resource: This) -> bool { let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); map.as_ref().is_some_and(|map| map.contains_key(&(resource as usize))) diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index c066419..4c17b8e 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -141,10 +141,12 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out tracing::warn!(path = name, %error, "dstorage: opening a file failed"); return from_win32(&error); } + let kept = name.clone(); tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened"); // SAFETY: a handle we just opened and nobody else owns. let file = unsafe { std::fs::File::from_raw_handle(handle) }; let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file }); + WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept)); put(out, file) } @@ -440,6 +442,52 @@ impl Scheduler { } } +/// The walls trace (`VICTORY_WALLS_TRACE`): 0 or unset: off; 1: a line for +/// every read request that fails, with its file; 2: for every request (the +/// list of a launch's reads, by file and offset, is what a launch with the +/// first room's walls and one without are compared by). +fn walls_trace() -> u8 { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + std::env::var("VICTORY_WALLS_TRACE").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0) + }) +} + +/// The files opened, by the address of our file object, with their paths +/// (for the walls trace: a request names its file by that address). +static WALLS_FILES: Mutex> = Mutex::new(Vec::new()); + +/// The walls trace's line for a request that is done. +fn walls_request(request: &Request, result: &Result<(), HRESULT>, started: std::time::Instant) { + let level = walls_trace(); + if level == 0 || (level == 1 && result.is_ok()) { + return; + } + let file = if request.options & MEMORY_SOURCE != 0 { + "memory".to_string() + } else { + let files = WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()); + let source = request.source as usize; + files.iter().find(|f| f.0 == source).map_or_else(|| "?".to_string(), |f| f.1.clone()) + }; + let hr = match result { + Ok(()) => 0, + Err(hr) => *hr as u32, + }; + tracing::info!( + file, + offset = request.offset, + source_size = request.source_size, + destination_size = request.destination_size, + to_pages = request.options & PAGE_DESTINATION != 0, + options = format_args!("{:#x}", request.options), + ms = started.elapsed().as_millis() as u64, + ok = result.is_ok(), + hr = format_args!("{hr:#010x}"), + "walls trace: a read request is done" + ); +} + /// A worker: runs the next read of the most deserving queue. fn work(scheduler: &'static Scheduler) { let mut lanes = scheduler.lock(); @@ -451,6 +499,7 @@ fn work(scheduler: &'static Scheduler) { drop(lanes); let started = std::time::Instant::now(); let result = execute(&job.request); + walls_request(&job.request, &result, started); lanes = scheduler.lock(); lanes.finish(&job, result); lanes.count(&job, started); From bdae3b372bba85e76ac197b5b73e512e5ea8cf26 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 21:29:09 -0600 Subject: [PATCH 160/445] Frame replay: where identical runs diverge; resources dying as a capture starts Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 101 ++ crates/victory-gpu/src/replay/play.rs | 140 ++- crates/victory-gpu/src/replay/play/diverge.rs | 1046 +++++++++++++++++ crates/victory-gpu/src/replay/record.rs | 13 +- crates/victory-gpu/src/replay/snap.rs | 37 +- 5 files changed, 1315 insertions(+), 22 deletions(-) create mode 100644 crates/victory-gpu/src/replay/play/diverge.rs diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index cad167a..714009f 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -62,6 +62,12 @@ pub(crate) struct Replay { /// One ExecuteCommandLists for the whole frame. #[arg(long)] one_submit: bool, + /// A full wait after every draw, dispatch, copy and clear. + #[arg(long)] + wait_all: bool, + /// Each list sent on its own, and waited for. + #[arg(long)] + wait_lists: bool, /// Run only these lists, by their place in the frame (`3..7`, or `5`); /// of the others only barriers. #[arg(long)] @@ -70,6 +76,45 @@ pub(crate) struct Replay { /// (may be given several times). #[arg(long = "skip-shader")] skip_shader: Vec, + /// Find the commands that make identical runs differ: each list is run + /// this often from the same memory. + #[arg(long, num_args = 0..=1, default_missing_value = "3")] + diverge: Option, + /// Find where the picture's variants are decided: from each list on, the + /// rest of the frame is run this often from the same memory. + #[arg(long, num_args = 0..=1, default_missing_value = "5")] + diverge_picture: Option, + /// Run each draw of one list (--lists) whose pipeline's name has this in + /// it alone, --diverge times: how many outcomes it has. + #[arg(long)] + draws: Option, + /// Say which lists (with --lists: commands) change words of buffers: + /// `::` (hexadecimal; repeatable). + #[arg(long)] + watch: Vec, + /// With --diverge-picture and one list in --lists: its commands (`0..900`) + /// and how many are stepped over at a time. + #[arg(long)] + commands: Option, + #[arg(long, default_value_t = 1)] + step: usize, + /// With --diverge and --diverge-picture: only these lists (`3..7`). + #[arg(long)] + lists: Option, + /// With --diverge: the most commands named of one list. + #[arg(long, default_value_t = 4)] + roots: u32, + /// Name resources the frame changes that the replay does not put back. + #[arg(long)] + check_written: bool, + /// Name what the heap slots hold that a command's constants name: + /// `:`. + #[arg(long)] + slots: Option, + /// Only write the DXIL of pipelines with this in their name to the + /// capture's `shaders` folder. + #[arg(long)] + dump: Option, /// Use the D3D12 debug layer (slow). #[arg(long)] debug_layer: bool, @@ -84,6 +129,12 @@ fn range(text: &str) -> Option<(u32, u32)> { } pub(crate) fn run(r: Replay) -> Result<()> { + if let Some(text) = &r.dump { + for line in play::dump(&r.folder, text)? { + println!("{line}"); + } + return Ok(()); + } let only = match &r.only { Some(text) => Some( range(text) @@ -107,11 +158,61 @@ pub(crate) fn run(r: Replay) -> Result<()> { skip_clamps: r.skip_clamps, skip_hash_passes: r.skip_hash_passes, one_submit: r.one_submit, + wait_all: r.wait_all, + wait_lists: r.wait_lists, only, skip_shaders: r.skip_shader, compare: r.compare, debug: r.debug_layer, }; + if let Some(text) = &r.slots { + let (list, command) = text + .split_once(':') + .and_then(|(l, c)| Some((l.parse().ok()?, c.parse().ok()?))) + .with_context(|| format!("--slots {text}: not :"))?; + let player = play::Player::load(&r.folder, &options)?; + return player.slots(list, command, &mut |line| println!("{line}")); + } + if r.check_written { + let mut player = play::Player::load(&r.folder, &options)?; + return player.check_written(&mut |line| println!("{line}")); + } + let mut watched = Vec::new(); + for text in &r.watch { + let mut n = text.split(':').map(|p| u64::from_str_radix(p.trim_start_matches("0x"), 16)); + let mut next = || n.next().and_then(Result::ok).with_context(|| format!("--watch {text}")); + let id = text.split(':').next().and_then(|p| p.parse().ok()).with_context(|| format!("--watch {text}"))?; + let _ = next(); + watched.push((id, next()?, next()?)); + } + if let Some(runs) = r.diverge.or(r.diverge_picture).or((!watched.is_empty()).then_some(2)) { + let lists = match &r.lists { + Some(text) => Some(range(text).with_context(|| format!("--lists {text}"))?), + None => None, + }; + let search = play::diverge::Search { + runs: runs.max(2), + lists, + roots: r.roots, + wait_all: options.wait_all, + options: options.clone(), + }; + let mut player = play::Player::load(&r.folder, &options)?; + if !watched.is_empty() { + return player.watch(&search, &watched, &mut |line| println!("{line}")); + } + if let Some(text) = &r.draws { + return player.diverge_draws(&search, text, &mut |line| println!("{line}")); + } + if r.diverge_picture.is_some() { + let commands = match &r.commands { + Some(text) => Some(range(text).with_context(|| format!("--commands {text}"))?), + None => None, + }; + return player.diverge_picture(&search, commands, r.step, &mut |line| println!("{line}")); + } + return player.diverge(&search, &mut |line| println!("{line}")); + } let reports = play::replay(&r.folder, &options)?; for (what, report) in &reports { println!("{}", report.text(what)); diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index 8543f6a..ba1543a 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -29,6 +29,8 @@ use super::wire::{ self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot, }; +pub mod diverge; + /// The name of the argument clamp's pipeline, by which its passes are /// recognised. pub const CLAMP: &str = "victory: argument clamp"; @@ -67,6 +69,10 @@ pub struct Options { pub skip_clamps: bool, pub skip_hash_passes: bool, pub one_submit: bool, + /// A full wait after every command that works. + pub wait_all: bool, + /// Each list sent on its own, and waited for. + pub wait_lists: bool, /// Run only these lists (by their place in the frame). pub only: Option<(u32, u32)>, /// Skip what runs a pipeline whose name or shader hash has one of @@ -92,6 +98,8 @@ impl Default for Options { skip_clamps: false, skip_hash_passes: false, one_submit: false, + wait_all: false, + wait_lists: false, only: None, skip_shaders: Vec::new(), compare: false, @@ -107,6 +115,8 @@ impl Options { || self.skip_clamps || self.skip_hash_passes || self.one_submit + || self.wait_all + || self.wait_lists || self.only.is_some() || !self.skip_shaders.is_empty() } @@ -119,6 +129,8 @@ impl Options { skip_clamps: false, skip_hash_passes: false, one_submit: false, + wait_all: false, + wait_lists: false, only: None, skip_shaders: Vec::new(), ..self.clone() @@ -144,6 +156,8 @@ pub struct Report { /// Against the presented picture: dB (infinite: the same), and whether /// its bytes are the same. pub picture: Option<(f64, bool)>, + /// Of each loop's picture: dB against the presented one, and its hash. + pub pictures: Vec<(f64, String)>, /// Things to know: from the capture and the replay. pub notes: Vec, } @@ -205,6 +219,20 @@ impl Report { } None => {} } + if self.pictures.len() > 1 { + let all: Vec = self + .pictures + .iter() + .map(|(db, hash)| format!("{db:.1} dB {}", &hash[..8])) + .collect(); + let kinds: HashSet<&String> = self.pictures.iter().map(|p| &p.1).collect(); + let _ = writeln!( + t, + " pictures of the loops: {} different: {}", + kinds.len(), + all.join(", ") + ); + } for n in &self.notes { let _ = writeln!(t, " note: {n}"); } @@ -241,6 +269,43 @@ pub fn find(folder: &Path) -> Result { .ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display())) } +/// Writes the DXIL of the pipelines whose name has `text` in it to `shaders` +/// in the capture, and the pipelines' descriptions; what was written. +pub fn dump(folder: &Path, text: &str) -> Result> { + let folder = find(folder)?; + let frame = Frame::read(&folder.join("frame.bin"))?; + let file = File::open(folder.join("shaders.bin"))?; + let to = folder.join("shaders"); + std::fs::create_dir_all(&to)?; + let mut out = Vec::new(); + for p in frame.pipelines.iter().filter(|p| p.name.contains(text)) { + let mut line = format!("pipeline {} {}:", p.id, p.name); + for part in &p.parts { + match part { + wire::Part::Code { kind, blob } => { + let c = &frame.codes[*blob as usize]; + let mut bytes = vec![0; c.len as usize]; + read_at(&file, &mut bytes, c.at)?; + let name: String = c.hash[..8].iter().map(|b| format!("{b:02x}")).collect(); + std::fs::write(to.join(format!("{name}.dxil")), bytes)?; + let _ = write!(line, " {kind}={name}.dxil"); + } + wire::Part::Root { root } => { + if let Some((_, blob)) = frame.roots.iter().find(|r| r.0 == *root) { + std::fs::write(to.join(format!("root-{root}.bin")), &blob.0)?; + } + let _ = write!(line, " root-{root}.bin"); + } + other => { + let _ = write!(line, " {other:?}"); + } + } + } + out.push(line); + } + Ok(out) +} + /// Loads a capture and runs it: the whole of `victory replay`. The reports, /// with what each is of. pub fn replay(folder: &Path, options: &Options) -> Result> { @@ -312,6 +377,8 @@ pub struct Player { commands: Vec>, /// Resources in the states of the start (not those of the end). fresh: bool, + /// States as the last run left them (`diverge`). + at: States, notes: Vec, } @@ -373,6 +440,7 @@ impl Player { results: None, commands, fresh: true, + at: States::default(), notes: frame .notes .iter() @@ -1769,7 +1837,7 @@ impl Player { ); let built = self.build(&submits, &Options::default())?; self.restore(true)?; - self.send(&built, false)?; + self.send(&built, &Options::default())?; self.fresh = false; Ok(clamps) } @@ -1838,8 +1906,13 @@ impl Player { let mut built = Vec::new(); for cmds in lists { let open = self.open(&heap, &mut next)?; - let stamps = - self.translate(&open.1, cmds, i, o.detailed.then_some((&heap, &mut next))); + let stamps = self.translate( + &open.1, + cmds, + i, + o.detailed.then_some((&heap, &mut next)), + o.wait_all, + ); built.push(self.close(open, &heap, &mut next, stamps)?); } steps.push((delta, built)); @@ -1979,6 +2052,7 @@ impl Player { cmds: &[Cmd], submit: usize, mut stamp: Option<(&ID3D12QueryHeap, &mut u32)>, + wait: bool, ) -> Vec { let version = self.version_of.get(submit).copied().unwrap_or(0); let clamps = self.pipelines_named(CLAMP); @@ -2010,6 +2084,10 @@ impl Player { // SAFETY: an open list; the objects are the frame's, alive with // the player; commands the host recorded the same way. unsafe { self.command(list, c, version) }; + if wait && c.works() { + // SAFETY: an open list. + unsafe { self.wait_for_all(list) }; + } let timed = c.works() || matches!(c, Cmd::Barriers { .. }); if timed && let Some((heap, next)) = &mut stamp { // SAFETY: as above. @@ -2474,7 +2552,7 @@ impl Player { } /// Sends the frame, waits for it, and reads the timestamps. - fn send(&mut self, s: &Sends, one: bool) -> Result> { + fn send(&mut self, s: &Sends, o: &Options) -> Result> { let cast = |l: &ID3D12GraphicsCommandList| l.cast::().map(Some); let mut submissions: Vec>> = Vec::new(); for (delta, lists) in &s.steps { @@ -2489,7 +2567,7 @@ impl Player { submissions.push(all); } } - if one { + if o.one_submit { let mut all = Vec::new(); for (i, lists) in submissions.into_iter().enumerate() { if i > 0 @@ -2504,7 +2582,14 @@ impl Player { // SAFETY: closed lists whose last run has finished. unsafe { for all in &submissions { - self.worker.queue.ExecuteCommandLists(all); + if !o.wait_lists { + self.worker.queue.ExecuteCommandLists(all); + continue; + } + for l in all { + self.worker.queue.ExecuteCommandLists(&[l.clone()]); + self.worker.idle()?; + } } self.worker .queue @@ -2534,7 +2619,10 @@ impl Player { for _ in 0..o.loops.max(1) { self.restore(o.restore)?; self.fresh = false; - stamps = self.send(&built, o.one_submit)?; + stamps = self.send(&built, o)?; + if let Some((db, _, hash, _)) = self.picture_now()? { + report.pictures.push((db, hash)); + } let ms = |a: u32, b: u32| { stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency }; @@ -2607,6 +2695,34 @@ impl Player { .collect(); } + /// The presented picture as it is now: dB against the recorded one, + /// whether its bytes are the same, its hash, and its pixels. + fn picture_now(&mut self) -> Result)>> { + let Some(p) = self.frame.presents.last().cloned() else { + return Ok(None); + }; + let Some(bytes) = self.contents(p.res)? else { + return Ok(None); + }; + let Some(rgb) = gpu::rgb(p.width, p.height, p.pitch, p.format, &bytes) else { + return Ok(None); + }; + let mut recorded = vec![0; bytes.len()]; + read_at( + &File::open(self.folder.join("present.bin"))?, + &mut recorded, + p.file, + )?; + let was = gpu::rgb(p.width, p.height, p.pitch, p.format, &recorded).unwrap_or_default(); + let hash = blake3::hash(&rgb).to_hex().to_string(); + Ok(Some(( + gpu::psnr(&rgb, &was), + rows_equal(&p, &bytes, &recorded), + hash, + rgb, + ))) + } + /// Saves the presented picture and compares it with the recorded one. fn picture(&mut self, o: &Options, report: &mut Report) -> Result<()> { let Some(p) = self.frame.presents.last().cloned() else { @@ -2796,7 +2912,15 @@ fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option = None; match D3D12GetDebugInterface(&mut layer) { - Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()), + Ok(()) => layer.iter().for_each(|l| { + l.EnableDebugLayer(); + // Every shader access checked on the card: very slow. + if std::env::var_os("VICTORY_REPLAY_GBV").is_some() + && let Ok(l) = l.cast::() + { + l.SetEnableGPUBasedValidation(true); + } + }), Err(e) => tracing::warn!("no debug layer: {e}"), } } diff --git a/crates/victory-gpu/src/replay/play/diverge.rs b/crates/victory-gpu/src/replay/play/diverge.rs new file mode 100644 index 0000000..7a6ace0 --- /dev/null +++ b/crates/victory-gpu/src/replay/play/diverge.rs @@ -0,0 +1,1046 @@ +//! Where identical runs of a frame part: every list is run several times +//! from the very same memory (what the frame writes is put back before each, +//! and everything before it was run once), so what differs after it was made +//! different by it; then the first command of the list that does so, by +//! halving the list. The state after the last run is what the rest goes on +//! from, so each finding is a root, not a consequence. + +use super::*; + +/// A part of memory compared as one. +const PIECE: usize = 64 << 10; + +/// Where a run's contents come down: for each resource (and subresource) the +/// frame writes, its place in read-back memory. +struct Reader { + blocks: Vec<(ID3D12Resource, usize)>, + parts: Vec, +} + +#[derive(Clone)] +struct Part { + id: u32, + /// `None` for a buffer. + sub: Option<(u32, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)>, + block: usize, + at: u64, + len: u64, +} + +/// One way to run commands `from..to` of a list. +struct Unit<'a> { + submit: usize, + cmds: &'a [Cmd], + from: usize, + to: usize, + /// With the copies of what the CPU wrote before the submission. + delta: bool, +} + +/// What differed between runs: part and piece. +type Pieces = Vec<(usize, usize)>; + +/// What to look at. +#[derive(Clone, Debug)] +pub struct Search { + /// Runs of each list. + pub runs: u32, + /// Only these lists (the others are run once). + pub lists: Option<(u32, u32)>, + /// Roots looked for in one list. + pub roots: u32, + /// A full wait after each command. + pub wait_all: bool, + /// Experiments on the frame. + pub options: Options, +} + +impl Player { + /// Looks for what makes identical runs differ; `say` gets the findings + /// as they are made. + pub fn diverge(&mut self, s: &Search, say: &mut dyn FnMut(String)) -> Result<()> { + let mut report = Report::default(); + let clamps = if s.options.skip_clamps { + self.clamp_results(&mut report)? + } else { + Vec::new() + }; + let submits = self.edited(&s.options, &mut report, &clamps); + self.restore(true)?; + self.fresh = false; + let ids: Vec = self.masters.iter().map(|m| m.0).collect(); + let reader = self.reader(&ids)?; + let mb: u64 = reader.parts.iter().map(|p| p.len).sum::() >> 20; + say(format!( + "{} resources the frame writes ({mb} MB in {} parts) compared after each list, {} runs of each", + self.masters.len(), + reader.parts.len(), + s.runs + )); + let mut states = self.start_states(); + let mut global = 0u32; + for (i, lists) in submits.iter().enumerate() { + for (j, cmds) in lists.iter().enumerate() { + let here = global; + global += 1; + let delta = j == 0; + let wanted = s.lists.is_none_or(|(a, b)| (a..=b).contains(&here)); + let mut from = 0; + let mut roots = 0; + loop { + let unit = Unit { + submit: i, + cmds, + from, + to: cmds.len(), + delta: delta && from == 0, + }; + let looks = wanted && cmds[from..].iter().any(Cmd::works); + let runs = if looks { s.runs } else { 1 }; + let pieces = self.trials(&reader, &unit, &states, runs, s.wait_all)?; + if pieces.is_empty() || roots >= s.roots { + self.commit(&unit, &mut states)?; + break; + } + roots += 1; + // The shortest start of the rest that differs. + let works: Vec = (from..cmds.len()).filter(|&c| cmds[c].works()).collect(); + let (mut lo, mut hi) = (0, works.len() - 1); + while lo < hi { + let mid = (lo + hi) / 2; + let cut = Unit { to: works[mid] + 1, ..unit }; + self.put_back(&states)?; + if self.trials(&reader, &cut, &states, s.runs, s.wait_all)?.is_empty() { + lo = mid + 1; + } else { + hi = mid; + } + } + let at = works[lo]; + let cut = Unit { to: at + 1, ..unit }; + self.put_back(&states)?; + let pieces = self.trials(&reader, &cut, &states, s.runs.max(6), s.wait_all)?; + say(format!( + "list {here} (submission {i}, its list {j}), command {at} of {}: {}", + cmds.len(), + self.describe(cmds, at) + )); + self.put_back(&states)?; + for line in self.compare(&reader, &cut, &states, &pieces, s.wait_all)? { + say(format!(" {line}")); + } + self.commit(&cut, &mut states)?; + from = at + 1; + if from >= cmds.len() { + break; + } + } + } + states.decay(); + if s.lists.is_some_and(|(_, b)| global > b) { + break; + } + if i % 5 == 4 { + say(format!("submission {i} done")); + } + } + self.restore_all()?; + Ok(()) + } + + /// Looks for where the picture's variants are decided: at each list (or, + /// of one list, each `step` commands in `commands`) the rest of the frame + /// is run several times from the same memory. Where the runs' pictures + /// agree from a point on but not from the one before, what lies between + /// decides. + pub fn diverge_picture( + &mut self, + s: &Search, + commands: Option<(u32, u32)>, + step: usize, + say: &mut dyn FnMut(String), + ) -> Result<()> { + let mut report = Report::default(); + let submits = self.edited(&s.options, &mut report, &[]); + let flat: Vec<(usize, usize, &Vec)> = submits + .iter() + .enumerate() + .flat_map(|(i, lists)| lists.iter().enumerate().map(move |(j, c)| (i, j, c))) + .collect(); + self.restore(true)?; + self.fresh = false; + let mut states = self.start_states(); + for (here, &(i, j, cmds)) in flat.iter().enumerate() { + let inside = s.lists.is_some_and(|(a, b)| a == b && a as usize == here); + let looks = s.lists.is_none_or(|(a, b)| (a as usize..=b as usize).contains(&here)); + let works: Vec = (0..cmds.len()).filter(|&c| cmds[c].works()).collect(); + // Where the list is cut. + let mut cuts: Vec = vec![0]; + if inside { + let (a, b) = commands.unwrap_or((0, u32::MAX)); + let some = works.iter().map(|&c| c + 1).filter(|c| (a as usize..=b as usize).contains(c)); + cuts.extend(some.step_by(step.max(1))); + } + for (k, &from) in cuts.iter().enumerate() { + if looks && !works.is_empty() { + let mut pictures: Vec<(f64, String, Vec)> = Vec::new(); + for run in 0..s.runs { + if run > 0 { + self.put_back(&states)?; + } + let mut now = states.clone(); + let first = Unit { submit: i, cmds, from, to: cmds.len(), delta: j == 0 && from == 0 }; + self.go(&first, s.wait_all)?; + now = self.after(&first, &now); + for (n, &(i, j, cmds)) in flat.iter().enumerate().skip(here + 1) { + if flat[n - 1].0 != i { + now.decay(); + } + let unit = Unit { submit: i, cmds, from: 0, to: cmds.len(), delta: j == 0 }; + self.go(&unit, s.wait_all)?; + now = self.after(&unit, &now); + } + self.at = now; + if let Some((db, _, hash, rgb)) = self.picture_now()? { + pictures.push((db, hash, rgb)); + } + } + self.put_back(&states)?; + let least = pictures + .iter() + .enumerate() + .flat_map(|(a, x)| pictures[a + 1..].iter().map(|y| gpu::psnr(&x.2, &y.2))) + .fold(f64::INFINITY, f64::min); + let kinds: HashSet<&String> = pictures.iter().map(|p| &p.1).collect(); + let db: Vec = pictures.iter().map(|p| format!("{:.1}", p.0)).collect(); + say(format!( + "from list {here} (submission {i}, its list {j}), command {from}: {} pictures of {}, the least alike {least:.1} dB; against the recorded: {}", + kinds.len(), + pictures.len(), + db.join(" ") + )); + } + // On to the next cut. + let to = cuts.get(k + 1).copied().unwrap_or(cmds.len()); + let unit = Unit { submit: i, cmds, from, to, delta: j == 0 && from == 0 }; + self.go(&unit, s.wait_all)?; + self.commit(&unit, &mut states)?; + self.at = states.clone(); + if inside && looks { + let last = (from..to).rev().find(|&c| cmds[c].works()); + if let Some(c) = last { + say(format!(" command {c}: {}", self.describe(cmds, c))); + } + } + } + if flat.get(here + 1).is_none_or(|n| n.0 != i) { + states.decay(); + self.at = states.clone(); + } + if s.lists.is_some_and(|(_, b)| here >= b as usize) { + break; + } + } + Ok(()) + } + + /// The states of textures at the frame's start. + fn start_states(&self) -> States { + let mut states = States::default(); + for (id, all) in &self.start { + let Some(o) = self.objects.get(id) else { continue }; + let flags = self.frame.resources[o.index].desc.flags; + let decays = flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0; + states.add(*id, o.subs, all[0], decays); + for (i, s) in all.iter().enumerate().filter(|_| all.len() > 1) { + states.change(&states::Change { + res: *id, + sub: i as u32, + after: *s, + promoted: false, + alias: false, + }); + } + } + states + } + + fn after(&self, unit: &Unit, states: &States) -> States { + let mut after = states.clone(); + let mut all = Vec::new(); + for c in &unit.cmds[unit.from..unit.to] { + states::changes(c, &mut all); + } + all.iter().for_each(|c| after.change(c)); + after + } + + /// Says which resources that are not put back before a run are changed + /// by one all the same. + pub fn check_written(&mut self, say: &mut dyn FnMut(String)) -> Result<()> { + // What is put back, is as it was. + { + let ids: Vec = self.masters.iter().map(|m| m.0).collect(); + let reader = self.reader(&ids)?; + let start = self.start_states(); + let before = self.hashes_now(&reader, &start)?; + let mut again = self.hashes_now(&reader, &start)?; + say(format!("read twice, {} parts differ", before.iter().zip(&again).filter(|(a, b)| a != b).count())); + for i in 0..3 { + self.run(&Options { loops: 1, ..Options::default() })?; + let ran = { + let end: Vec<(u32, Vec)> = self.end.iter().map(|(k, v)| (*k, v.clone())).collect(); + let mut s = start.clone(); + for (id, v) in end { + for (sub, st) in v.iter().enumerate() { + let sub = if v.len() == 1 { ALL } else { sub as u32 }; + s.change(&states::Change { res: id, sub, after: *st, promoted: false, alias: false }); + } + } + self.hashes_now(&reader, &s)? + }; + self.restore(true)?; + again = self.hashes_now(&reader, &start)?; + let differ: Vec = (0..before.len()).filter(|&i| before[i] != again[i]).collect(); + let changed = (0..before.len()).filter(|&i| before[i] != ran[i]).count(); + say(format!("run {i}: {changed} parts changed by the frame, {} not put back as they were", differ.len())); + for &d in differ.iter().take(20) { + let pieces = before[d].iter().zip(&again[d]).filter(|(a, b)| a != b).count(); + say(format!(" {} {:?}: {pieces} of {} pieces", self.called(reader.parts[d].id), reader.parts[d].sub.map(|s| s.0), before[d].len())); + } + } + } + let put_back: HashSet = self.masters.iter().map(|m| m.0).collect(); + let others: Vec = self.objects.keys().copied().filter(|id| !put_back.contains(id)).collect(); + let reader = self.reader(&others)?; + self.restore(true)?; + let start = self.start_states(); + let before = self.hashes_now(&reader, &start)?; + let o = Options { loops: 1, ..Options::default() }; + self.run(&o)?; + self.restore(true)?; + let after = self.hashes_now(&reader, &start)?; + let mut n = 0; + for (i, (a, b)) in before.iter().zip(&after).enumerate() { + let pieces = a.iter().zip(b).filter(|(a, b)| a != b).count(); + if pieces > 0 { + n += 1; + let p = &reader.parts[i]; + let r = &self.frame.resources[self.objects[&p.id].index]; + say(format!( + "not put back, but changed: {} {:?} idle {} late {}: {pieces} pieces of {}", + self.called(p.id), + r.place, + r.idle, + r.late, + a.len() + )); + } + } + say(format!("{} parts of {} resources looked at, {n} changed", reader.parts.len(), others.len())); + Ok(()) + } + + fn reader(&self, ids: &[u32]) -> Result { + const BLOCK: u64 = 512 << 20; + let mut parts = Vec::new(); + let mut sizes: Vec = vec![0]; + for id in ids { + let o = &self.objects[id]; + let r = &self.frame.resources[o.index]; + let back = matches!(&r.place, Place::Committed { props, .. } if gpu::seen(props) == Seen::ReadBack); + if r.desc.samples[0] > 1 || back { + continue; + } + let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; + let desc = gpu::to_desc(&r.desc); + for sub in 0..o.subs { + let (sub, len) = if is_buffer { + (None, r.desc.width) + } else { + let (f, total) = gpu::footprints(&self.device, &desc, sub, 1); + (Some((sub, f[0])), total) + }; + let last = sizes.len() - 1; + let at = sizes[last].next_multiple_of(512); + let (block, at) = if at + len > BLOCK && at > 0 { + sizes.push(0); + (last + 1, 0) + } else { + (last, at) + }; + sizes[block] = at + len; + parts.push(Part { + id: *id, + sub, + block, + at, + len, + }); + } + } + let mut blocks = Vec::new(); + for size in sizes { + let (b, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, size, D3D12_RESOURCE_FLAG_NONE)?; + blocks.push((b, data as usize)); + } + Ok(Reader { blocks, parts }) + } + + /// Runs the unit once; resources are as at its start. + fn go(&mut self, unit: &Unit, wait: bool) -> Result<()> { + let mut lists = Vec::new(); + if unit.delta + && let Some(parts) = self.delta_parts.get(unit.submit).filter(|p| !p.is_empty()) + && let Some(from) = &self.deltas + { + let l = self.plain_list()?; + for (d, at) in parts { + if let Some(o) = self.objects.get(&d.res) { + // SAFETY: an open list; live buffers. + unsafe { l.1.CopyBufferRegion(&o.res, d.at, from, *at, d.len) }; + } + } + // SAFETY: as above. + unsafe { l.1.Close()? }; + lists.push(l); + } + let l = self.plain_list()?; + // What the commands before have set, without what they do. + let before: Vec = unit.cmds[..unit.from] + .iter() + .filter(|c| { + !c.works() && !matches!(c, Cmd::Barriers { .. } | Cmd::BeginQuery { .. } | Cmd::EndQuery { .. }) + }) + .cloned() + .collect(); + self.translate(&l.1, &before, unit.submit, None, false); + self.translate(&l.1, &unit.cmds[unit.from..unit.to], unit.submit, None, wait); + // SAFETY: an open list. + unsafe { l.1.Close()? }; + lists.push(l); + for l in &lists { + // SAFETY: a closed list; waited for before it goes. + unsafe { self.worker.queue.ExecuteCommandLists(&[Some(l.1.cast()?)]) }; + self.worker.idle().context("the card was lost")?; + } + Ok(()) + } + + /// Hashes of all parts' pieces, as memory is now (in `states`). + fn hashes_now(&mut self, reader: &Reader, states: &States) -> Result>> { + let objects = &self.objects; + for block in 0..reader.blocks.len() { + let parts: Vec<&Part> = reader.parts.iter().filter(|p| p.block == block).collect(); + let (mut before, mut after) = (Vec::new(), Vec::new()); + let mut seen = HashSet::new(); + for p in parts.iter().filter(|p| p.sub.is_some()) { + if seen.insert(p.id) { + let state = states.get(p.id).unwrap_or(vec![COMMON]); + let to: Vec = state.iter().map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect(); + gpu::moves(&objects[&p.id].res, &state, &to, &mut before); + gpu::moves(&objects[&p.id].res, &to, &state, &mut after); + } + } + let to = &reader.blocks[block].0; + self.worker.run(|list| { + // SAFETY: an open list; live resources. + unsafe { + barriers(list, &before); + for p in &parts { + let res = &objects[&p.id].res; + match p.sub { + None => list.CopyBufferRegion(to, p.at, res, 0, p.len), + Some((sub, mut f)) => { + f.Offset = p.at; + list.CopyTextureRegion(&gpu::placed_location(to, f), 0, 0, 0, &gpu::sub_location(res, sub), None); + } + } + } + barriers(list, &after); + } + })?; + } + let next = AtomicUsize::new(0); + let out: std::sync::Mutex>> = std::sync::Mutex::new(vec![Vec::new(); reader.parts.len()]); + std::thread::scope(|scope| { + for _ in 0..16 { + scope.spawn(|| { + while let Some((i, p)) = { + let i = next.fetch_add(1, Ordering::Relaxed); + reader.parts.get(i).map(|p| (i, p)) + } { + let all: Vec = reader + .bytes(p) + .chunks(PIECE) + .map(|c| { + let h = blake3::hash(c); + u64::from_le_bytes(h.as_bytes()[..8].try_into().unwrap_or_default()) + }) + .collect(); + out.lock().unwrap_or_else(|e| e.into_inner())[i] = all; + } + }); + } + }); + Ok(out.into_inner().unwrap_or_else(|e| e.into_inner())) + } + + /// Runs the unit `runs` times (memory is as at its start, and is put + /// back between runs) and compares. Memory is as the last run left it. + fn trials(&mut self, reader: &Reader, unit: &Unit, states: &States, runs: u32, wait: bool) -> Result { + let after = self.after(unit, states); + let mut first: Option>> = None; + let mut pieces = std::collections::BTreeSet::new(); + for run in 0..runs { + if run > 0 { + self.put_back_from(&after, states)?; + } + self.go(unit, wait)?; + if runs == 1 { + break; + } + let now = self.hashes_now(reader, &after)?; + match &first { + None => first = Some(now), + Some(first) => { + for (p, (a, b)) in first.iter().zip(&now).enumerate() { + pieces.extend(a.iter().zip(b).enumerate().filter(|(_, (a, b))| a != b).map(|(i, _)| (p, i))); + } + } + } + } + self.at = after; + Ok(pieces.into_iter().collect()) + } + + /// Puts memory back to the start of a unit in `states`, from where the + /// last run left it. + fn put_back(&mut self, states: &States) -> Result<()> { + let from = self.at.clone(); + self.put_back_from(&from, states) + } + + fn put_back_from(&mut self, from: &States, to: &States) -> Result<()> { + self.copy_masters(from, to, false)?; + self.at = to.clone(); + Ok(()) + } + + /// What memory holds after the last run is the start of what follows. + fn commit(&mut self, unit: &Unit, states: &mut States) -> Result<()> { + *states = self.after(unit, states); + self.copy_masters(&states.clone(), states, true)?; + Ok(()) + } + + /// Copies the masters over the resources (which are in `from` and go to + /// `to`), or the resources into the masters. + fn copy_masters(&mut self, from: &States, to: &States, save: bool) -> Result<()> { + let known: HashMap = self.masters.iter().map(|(id, m)| (*id, m)).collect(); + let (mut before, mut after, mut plain) = (Vec::new(), Vec::new(), Vec::new()); + let here = if save { COPY_SOURCE } else { COPY_DEST }; + for id in self.start.keys() { + let Some(o) = self.objects.get(id) else { continue }; + let (a, b) = (from.get(*id).unwrap_or(vec![COMMON]), to.get(*id).unwrap_or(vec![COMMON])); + let Some(m) = known.get(id) else { + gpu::moves(&o.res, &a, &b, &mut plain); + continue; + }; + gpu::moves(&o.res, &a, &[here], &mut before); + gpu::moves(&o.res, &[here], &b, &mut after); + if save { + before.push(gpu::transition(m, ALL, COPY_SOURCE, COPY_DEST)); + after.push(gpu::transition(m, ALL, COPY_DEST, COPY_SOURCE)); + } + } + let objects = &self.objects; + self.worker.run(|list| { + // SAFETY: an open list; live resources of one description. + unsafe { + barriers(list, &plain); + barriers(list, &before); + for (id, m) in &known { + if save { + list.CopyResource(*m, &objects[id].res); + } else { + list.CopyResource(&objects[id].res, *m); + } + } + barriers(list, &after); + } + })?; + Ok(()) + } + + /// The masters hold another state than the frame's start now. + fn restore_all(&mut self) -> Result<()> { + self.note("the player's copies are no longer of the frame's start: load it again".into()); + Ok(()) + } + + /// A command in words: its pipeline, what its list bound for it, and the + /// barriers since the last command that worked. + fn describe(&self, cmds: &[Cmd], at: usize) -> String { + let mut pso = NONE; + let mut binds: BTreeMap<(bool, u32), String> = BTreeMap::new(); + let mut since: Vec = Vec::new(); + let mut targets = String::new(); + for c in &cmds[..at] { + match c { + Cmd::Pipeline { pso: p } => pso = *p, + Cmd::RootSignature { graphics, .. } => binds.retain(|k, _| k.0 != *graphics), + Cmd::RootView { graphics, kind, param, va } => { + let kind = ["", "cbv", "srv", "uav"].get(*kind as usize).copied().unwrap_or(""); + let text = match va { + Va::At { res, offset } => format!("{kind} {} +{offset:#x}", self.called(*res)), + _ => format!("{kind} null"), + }; + binds.insert((*graphics, *param), text); + } + Cmd::Table { graphics, param, heap, slot } => { + binds.insert((*graphics, *param), format!("table heap {heap} slot {slot}")); + } + Cmd::Constants { graphics, param, offset, values } => { + let text = format!("constants +{offset} {values:x?}"); + binds.entry((*graphics, *param)).and_modify(|t| *t = format!("{t}, {text}")).or_insert(text); + } + Cmd::Targets { colors, depth } => { + let all: Vec = colors.iter().chain(depth).map(|s| self.called(s.res)).collect(); + targets = all.join(", "); + } + Cmd::Barriers { all } => since.extend(all.iter().map(|b| match b { + Barrier::Transition { res, before, after, .. } => format!("{} {before:#x}->{after:#x}", self.called(*res)), + Barrier::Uav { res: 0, .. } => "all uav".into(), + Barrier::Uav { res, .. } => format!("uav {}", self.called(*res)), + Barrier::Alias { .. } => "alias".into(), + })), + _ => {} + } + if c.works() { + since.clear(); + } + } + let graphics = !matches!(cmds[at], Cmd::Dispatch { .. }); + let binds: Vec = binds.iter().filter(|(k, _)| k.0 == graphics).map(|(k, t)| format!("[{}] {t}", k.1)).collect(); + let mut text = format!("{:?}", cmds[at]); + if cmds[at].runs_shaders() { + text += &format!(" of {}", self.pipeline_name(pso)); + text += &format!("\n bound: {}", binds.join("; ")); + if graphics && !targets.is_empty() { + text += &format!("\n targets: {targets}"); + } + } + text + &format!("\n barriers since the command before: {}", since.join("; ")) + } + + /// Says which lists (of the list in `s.lists`: which commands) change + /// words of a buffer, and to what. + pub fn watch(&mut self, s: &Search, parts: &[(u32, u64, u64)], say: &mut dyn FnMut(String)) -> Result<()> { + let mut report = Report::default(); + let submits = self.edited(&s.options, &mut report, &[]); + self.restore(true)?; + self.fresh = false; + let words = |p: &mut Player| -> Result>> { + parts + .iter() + .map(|&(id, at, len)| { + let bytes = p.slice(id, at, len)?; + Ok(bytes.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect()) + }) + .collect() + }; + let mut was = words(self)?; + say(format!("at the start: {was:x?}")); + let mut global = 0u32; + for (i, lists) in submits.iter().enumerate() { + for (j, cmds) in lists.iter().enumerate() { + let here = global; + global += 1; + let inside = s.lists.is_some_and(|(a, b)| (a..=b).contains(&here)); + let mut cuts: Vec = vec![0]; + if inside { + cuts.extend((0..cmds.len()).filter(|&c| cmds[c].works()).map(|c| c + 1)); + } + if *cuts.last().unwrap_or(&0) != cmds.len() { + cuts.push(cmds.len()); + } + for k in 0..cuts.len() - 1 { + let unit = Unit { submit: i, cmds, from: cuts[k], to: cuts[k + 1], delta: j == 0 && k == 0 }; + self.go(&unit, s.wait_all)?; + let now = words(self)?; + if now != was { + if inside { + let last = (unit.from..unit.to).rev().find(|&c| cmds[c].works()).unwrap_or(unit.to - 1); + say(format!("list {here} (submission {i}, its list {j}) command {last}: {}", self.describe(cmds, last))); + } else { + say(format!("list {here} (submission {i}, its list {j})")); + } + for (n, (a, b)) in was.iter().zip(&now).enumerate() { + let changed: Vec = a + .iter() + .zip(b) + .enumerate() + .filter(|(_, (a, b))| a != b) + .take(40) + .map(|(w, (a, b))| format!("+{:#x}: {a:x} -> {b:x}", w * 4)) + .collect(); + if !changed.is_empty() { + say(format!(" part {n}: {}", changed.join(", "))); + } + } + was = now; + } + } + if s.options.only.is_some_and(|(_, b)| here >= b) { + return Ok(()); + } + } + } + Ok(()) + } + + /// Each draw of one list whose pipeline's name has `text` in it, run + /// alone (with what prepares its arguments) from the memory at the list's + /// start, `runs` times: how many different contents its targets get. + pub fn diverge_draws(&mut self, s: &Search, text: &str, say: &mut dyn FnMut(String)) -> Result<()> { + let mut report = Report::default(); + let submits = self.edited(&s.options, &mut report, &[]); + let flat: Vec<(usize, usize, &Vec)> = submits + .iter() + .enumerate() + .flat_map(|(i, lists)| lists.iter().enumerate().map(move |(j, c)| (i, j, c))) + .collect(); + let wanted = s.lists.map_or(0, |l| l.0 as usize); + self.restore(true)?; + self.fresh = false; + let mut states = self.start_states(); + for (here, &(i, j, cmds)) in flat.iter().enumerate() { + if here < wanted { + let unit = Unit { submit: i, cmds, from: 0, to: cmds.len(), delta: j == 0 }; + self.go(&unit, s.wait_all)?; + self.commit(&unit, &mut states)?; + if flat.get(here + 1).is_none_or(|n| n.0 != i) { + states.decay(); + } + self.at = states.clone(); + continue; + } + let mut last = 0; + let mut pso = NONE; + let mut targets: Vec = Vec::new(); + for (c, cmd) in cmds.iter().enumerate() { + match cmd { + Cmd::Pipeline { pso: p } => pso = *p, + Cmd::Targets { colors, depth } => targets = colors.iter().chain(depth).map(|s| s.res).filter(|r| *r != NONE).collect(), + _ => {} + } + if !matches!(cmd, Cmd::Indirect { .. } | Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::DispatchMesh { .. }) { + continue; + } + let from = std::mem::replace(&mut last, c + 1); + if !self.pipeline_name(pso).contains(text) { + continue; + } + targets.sort_unstable(); + targets.dedup(); + let reader = self.reader(&targets)?; + let unit = Unit { submit: i, cmds, from, to: c + 1, delta: false }; + // Barriers before it in the list are made up for: textures + // are in the states the list has them in here. + let mut before = states.clone(); + let mut all = Vec::new(); + cmds[..from].iter().for_each(|c| states::changes(c, &mut all)); + all.iter().for_each(|c| before.change(c)); + let after = self.after(&unit, &before); + let mut kinds: HashMap>, u32> = HashMap::new(); + for _ in 0..s.runs { + let at = self.at.clone(); + self.copy_masters(&at, &before, false)?; + self.at = before.clone(); + self.go(&unit, s.wait_all)?; + self.at = after.clone(); + *kinds.entry(self.hashes_now(&reader, &after)?).or_default() += 1; + } + let at = self.at.clone(); + self.copy_masters(&at, &before, false)?; + self.at = before.clone(); + if kinds.len() > 1 || std::env::var_os("VICTORY_REPLAY_PEEK").is_some() { + self.peek(cmds, c, i, say)?; + } + let mut counts: Vec = kinds.values().copied().collect(); + counts.sort_unstable(); + say(format!("command {c} (from {from}) {:?} of {}: {} outcomes {counts:?}", cmd, self.pipeline_name(pso), counts.len())); + } + break; + } + Ok(()) + } + + /// `len` bytes of a buffer from `at`. + fn slice(&mut self, id: u32, at: u64, len: u64) -> Result> { + let Some(o) = self.objects.get(&id) else { return Ok(Vec::new()) }; + let len = len.min(self.frame.resources[o.index].desc.width.saturating_sub(at)); + if len == 0 { + return Ok(Vec::new()); + } + let res = o.res.clone(); + let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, len, D3D12_RESOURCE_FLAG_NONE)?; + self.worker.run(|list| { + // SAFETY: an open list; live buffers. + unsafe { list.CopyBufferRegion(&back, 0, &res, at, len) }; + })?; + // SAFETY: the mapping; the copy into it has run. + Ok(unsafe { std::slice::from_raw_parts(data, len as usize) }.to_vec()) + } + + /// The words of a buffer view (raw or typed, of words). + fn view_words(&mut self, s: &Slot, first: u64, n: u64) -> Result> { + let at = u64::from_le_bytes([s.desc[16], s.desc[17], s.desc[18], s.desc[19], s.desc[20], s.desc[21], s.desc[22], s.desc[23]]); + let count = u64::from(u32::from_le_bytes([s.desc[24], s.desc[25], s.desc[26], s.desc[27]])); + let n = n.min(count.saturating_sub(first)); + let bytes = self.slice(s.res, (at + first) * 4, n * 4)?; + Ok(bytes.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect()) + } + + /// What a mesh draw of the title's (with its usual constants) reads. + fn peek(&mut self, cmds: &[Cmd], at: usize, submit: usize, say: &mut dyn FnMut(String)) -> Result<()> { + let mut v = [0u32; 16]; + let mut heap = NONE; + for c in &cmds[..at] { + match c { + Cmd::Constants { graphics: true, param: 0, offset, values } => { + for (k, x) in values.iter().enumerate() { + if let Some(at) = v.get_mut(*offset as usize + k) { + *at = *x; + } + } + } + Cmd::Heaps { heaps } => heap = heaps.first().copied().unwrap_or(NONE), + _ => {} + } + } + say(format!(" constants {v:x?}")); + let slot = |p: &Player, byte: u32| p.slot_at(heap, byte >> 5, submit); + for (name, byte, n) in [ + ("y+0", v[9], 64u64), + ("y+32 (matrices)", v[9] + 32, 64), + ("y+64", v[9] + 64, 32), + ("y+96 (instances)", v[9] + 96, 64), + ("y+128 (meshlets)", v[9] + 128, 64), + ("y+192 (visible)", v[9] + 192, 64), + ("x+1600", v[8] + 1600, 0), + ("x+2752", v[8] + 2752, 0), + ("x+2848", v[8] + 2848, 0), + ] { + let s = slot(self, byte); + let words = if s.kind == slot::SRV { self.view_words(&s, 0, n)? } else { Vec::new() }; + say(format!(" {name}: slot {} {}: {words:x?}", byte >> 5, self.slot_text(&s))); + } + // The list of visible meshlets, as the mesh shader finds it. + let lists = slot(self, v[8] + 2752); + let word = self.view_words(&lists, u64::from((v[13] & 0x07ff_ffff) & 0x07ff_ffff), 4)?; + let typed = slot(self, v[8] + 1600); + let index = self.view_words(&typed, 510, 1)?; + say(format!(" list words {word:x?} (count {}, first {}), typed view slot {index:x?}", word.first().map_or(0, |w| w >> 15), word.first().map_or(0, |w| w & 0x7fff))); + if let (Some(w), Some(i)) = (word.first(), index.first()) { + let s = self.slot_at(heap, i & 0x07ff_ffff, submit); + say(format!(" typed view: {}", self.slot_text(&s))); + if s.kind == slot::SRV && s.res != NONE { + let list = self.view_words(&s, u64::from(w & 0x7fff) * 16, u64::from(w >> 15) + 16)?; + say(format!(" visible meshlets: {list:x?}")); + } + } + Ok(()) + } + + /// What the heap slots hold that a draw's constants name, as the title's + /// shaders find them: byte offsets in the view heap among its first + /// constants, a descriptor of 32 bytes each. + pub fn slots(&self, list: u32, command: usize, say: &mut dyn FnMut(String)) -> Result<()> { + let mut here = 0; + for (i, s) in self.frame.submits.iter().enumerate() { + for &l in s.lists.iter().filter(|&&l| l != MISSING) { + if here == list { + let cmds = &self.commands[l as usize]; + say(self.describe(cmds, command)); + let mut values = [[0u32; 16]; 3]; + let mut heap = NONE; + for c in &cmds[..command] { + match c { + Cmd::Constants { param, offset, values: v, .. } => { + for (k, x) in v.iter().enumerate() { + if let Some(all) = values.get_mut(*param as usize) + && let Some(at) = all.get_mut(*offset as usize + k) + { + *at = *x; + } + } + } + Cmd::Heaps { heaps } => heap = heaps.first().copied().unwrap_or(NONE), + _ => {} + } + } + say(format!("heap {heap}, constants {values:x?}")); + let mut bases: Vec = values.iter().flatten().map(|v| v >> 5).filter(|v| *v > 64).collect(); + bases.dedup(); + for base in bases { + for k in 0..12 { + let s = self.slot_at(heap, base + k, i); + if s.kind != slot::EMPTY { + say(format!(" slot {base}+{k}: {}", self.slot_text(&s))); + } else { + say(format!(" slot {base}+{k}: never written")); + } + } + } + } + here += 1; + } + } + Ok(()) + } + + /// A heap slot as it was for a submission. + fn slot_at(&self, heap: u32, at: u32, submit: usize) -> Slot { + let late = self.frame.submits[..=submit].iter().rev().find_map(|s| { + s.views.iter().rev().find(|(h, i, _)| *h == heap && *i == at).map(|v| v.2) + }); + late.unwrap_or_else(|| { + let runs = self.frame.descriptor_heaps.iter().find(|h| h.id == heap).map(|h| &h.runs); + runs.and_then(|runs| { + let k = runs.partition_point(|r| r.0 <= at).checked_sub(1)?; + let (first, n, s) = &runs[k]; + (at - first < *n).then_some(*s) + }) + .unwrap_or(Slot::EMPTY) + }) + } + + fn slot_text(&self, s: &Slot) -> String { + let word = |i: usize| u32::from_le_bytes([s.desc[i * 4], s.desc[i * 4 + 1], s.desc[i * 4 + 2], s.desc[i * 4 + 3]]); + let kind = ["empty", "cbv", "srv", "uav", "sampler", "rtv", "dsv"].get(s.kind as usize).copied().unwrap_or("?"); + let res = if s.res == NONE { "null".into() } else { self.called(s.res) }; + match s.kind { + slot::CBV => format!("cbv {res} +{:#x} size {:#x}", s.address(), word(2)), + _ => format!( + "{kind} format {} dimension {} first {} count {} stride {} flags {}: {res}", + word(0), + word(1), + word(if s.kind == slot::SRV { 4 } else { 2 }), + word(if s.kind == slot::SRV { 6 } else { 4 }), + word(if s.kind == slot::SRV { 7 } else { 5 }), + word(if s.kind == slot::SRV { 8 } else { 8 }), + ), + } + } + + fn called(&self, id: u32) -> String { + let Some(o) = self.objects.get(&id) else { + return format!("resource {id} (not there)"); + }; + let r = &self.frame.resources[o.index]; + let d = &r.desc; + if d.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { + let kind = match &r.place { + Place::Committed { props, .. } => format!("{:?}", gpu::seen(props)), + _ => "placed".into(), + }; + format!("#{id} '{}' buffer {:#x} {kind}", r.name, d.width) + } else { + format!("#{id} '{}' {}x{}x{} m{} f{}", r.name, d.width, d.height, d.depth, d.mips, d.format) + } + } + + /// Runs the unit until two runs differ, and says how. + fn compare(&mut self, reader: &Reader, unit: &Unit, states: &States, pieces: &Pieces, wait: bool) -> Result> { + let after = self.after(unit, states); + let parts: std::collections::BTreeSet = pieces.iter().map(|p| p.0).collect(); + let mut seen: Vec<(Vec>, Vec>)> = Vec::new(); + for run in 0..8 { + if run > 0 { + self.put_back_from(&after, states)?; + } + self.go(unit, wait)?; + let hashes = self.hashes_now(reader, &after)?; + if seen.iter().any(|(h, _)| *h == hashes) { + continue; + } + let data = parts.iter().map(|&p| reader.bytes(&reader.parts[p]).to_vec()).collect(); + seen.push((hashes, data)); + if seen.len() == 2 { + break; + } + } + let mut out = Vec::new(); + // The arguments it ran with. + if let Some(Cmd::Indirect { args, at, .. }) = unit.cmds.get(unit.to - 1) + && let Some((p, part)) = reader.parts.iter().enumerate().find(|(_, p)| p.id == *args) + { + let bytes = &reader.bytes(part)[*at as usize..]; + let words: Vec = bytes.chunks_exact(4).take(8).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect(); + let each: HashSet<&Vec> = seen.iter().map(|s| &s.0[p]).collect(); + out.push(format!("arguments {words:x?} (the same in all runs: {})", each.len() == 1)); + } + self.at = after; + let [(_, a), (_, b)] = &seen[..] else { + out.push("it did not differ when looked at again".into()); + return Ok(out); + }; + // And without the command. + let before = Unit { to: unit.to - 1, ..*unit }; + self.put_back(states)?; + self.go(&before, wait)?; + self.at = self.after(&before, states); + let now = self.at.clone(); + self.hashes_now(reader, &now)?; + let without: Vec> = parts.iter().map(|&p| reader.bytes(&reader.parts[p]).to_vec()).collect(); + let to = self.folder.join("diverge"); + let _ = std::fs::create_dir_all(&to); + for (k, &p) in parts.iter().enumerate().take(12) { + let part = &reader.parts[p]; + // Both contents, to look at. + let sub = part.sub.map_or(0, |s| s.0); + let _ = std::fs::write(to.join(format!("{}-{sub}-0.bin", part.id)), &without[k]); + let changed = |v: &[u8]| v.chunks_exact(4).zip(without[k].chunks_exact(4)).filter(|(x, y)| x != y).count(); + out.push(format!("it changes {} dwords in one run, {} in another", changed(&a[k]), changed(&b[k]))); + let _ = std::fs::write(to.join(format!("{}-{sub}-a.bin", part.id)), &a[k]); + let _ = std::fs::write(to.join(format!("{}-{sub}-b.bin", part.id)), &b[k]); + let words = |v: &[u8]| -> Vec { v.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect() }; + let (x, y) = (words(&a[k]), words(&b[k])); + let differ: Vec = (0..x.len().min(y.len())).filter(|&i| x[i] != y[i]).collect(); + if differ.is_empty() { + continue; + } + // The same words in another order: an order, not a value. + let sorted = |v: &[u32]| { + let mut s: Vec = differ.iter().map(|&i| v[i]).collect(); + s.sort_unstable(); + s + }; + let order = if sorted(&x) == sorted(&y) { " (the same values in another order)" } else { "" }; + let sub = part.sub.map_or(String::new(), |(s, f)| format!(" subresource {s} pitch {}", f.Footprint.RowPitch)); + let sample: Vec = differ.iter().take(8).map(|&i| format!("+{:#x}: {:08x} {:08x}", i * 4, x[i], y[i])).collect(); + out.push(format!( + "writes {}{sub}: {} of {} dwords differ, {:#x}..{:#x}{order}: {}", + self.called(part.id), + differ.len(), + x.len(), + differ[0] * 4, + differ[differ.len() - 1] * 4 + 4, + sample.join(", ") + )); + } + if parts.len() > 12 { + out.push(format!("and {} more parts", parts.len() - 12)); + } + Ok(out) + } +} + +impl Reader { + fn bytes(&self, p: &Part) -> &[u8] { + // SAFETY: a part of a mapped block; copies into it have run. + unsafe { std::slice::from_raw_parts((self.blocks[p.block].1 + p.at as usize) as *const u8, p.len as usize) } + } +} diff --git a/crates/victory-gpu/src/replay/record.rs b/crates/victory-gpu/src/replay/record.rs index c839d60..67a77e3 100644 --- a/crates/victory-gpu/src/replay/record.rs +++ b/crates/victory-gpu/src/replay/record.rs @@ -351,7 +351,10 @@ pub(super) struct Recorder { /// made are kept alive. pub(super) watching: AtomicBool, pub(super) writes: Mutex>, - pub(super) held: Mutex>, + /// Resources kept alive for a capture, by id. One that dies all the same + /// (its last reference was going when ours was taken) is taken out: see + /// `Recorder::gone`. + pub(super) held: Mutex>, /// What could not be recorded, with how often. problems: Mutex>, /// Submissions and presents, one at a time. @@ -586,7 +589,7 @@ impl Recorder { write(&self.resources).insert(id, res); self.ids.set(p as usize, id); if late { - lock(&self.held).push(ID3D12Resource::clone(&object)); + lock(&self.held).insert(id, ID3D12Resource::clone(&object)); } self.tell_gone( &*object, @@ -602,6 +605,12 @@ impl Recorder { fn gone(&self, what: &Gone) { match *what { Gone::Resource { id, ptr, va } => { + // The memory goes whatever we hold: letting go of it later + // would be a call into what is there then. + if let Some(dead) = lock(&self.held).remove(&id) { + std::mem::forget(dead); + self.problem("a resource died as the frame started: its contents may be missing"); + } self.ids.remove(ptr, id); write(&self.resources).remove(&id); if va != 0 { diff --git a/crates/victory-gpu/src/replay/snap.rs b/crates/victory-gpu/src/replay/snap.rs index d9832d2..07acb47 100644 --- a/crates/victory-gpu/src/replay/snap.rs +++ b/crates/victory-gpu/src/replay/snap.rs @@ -279,7 +279,8 @@ impl Reads { /// A buffer the CPU sees. struct CpuBuffer { id: u32, - res: ID3D12Resource, + /// Held by the recorder, not by this. + res: std::mem::ManuallyDrop, /// Where it is read: its mapping, or the read-back copy of it. live: *const u8, /// The read-back buffer and the offset in it, for one that is slow to @@ -298,8 +299,6 @@ unsafe impl Sync for CpuBuffer {} struct Capture { worker: Worker, others: Vec, - /// Resources the frame can use, kept alive. - held: Vec, started: bool, frame: u32, states: States, @@ -341,7 +340,6 @@ impl Capture { Ok(Capture { worker: Worker::new(&device, &direct.0)?, others, - held: Vec::new(), started: false, frame: 0, states: States::default(), @@ -388,7 +386,8 @@ impl Capture { let mut all: Vec> = Vec::new(); { let live = read(&r.resources); - for res in live.values() { + let mut held = lock(&r.held); + for res in live.values().filter(|res| !res.late) { let object = res.object(); // SAFETY: a live resource, or one whose end waits for the // lock held here (`Recorder::gone`): the count tells which. @@ -405,9 +404,11 @@ impl Capture { // giving it back would end it a second time. continue; } - // SAFETY: the reference just taken. - self.held - .push(unsafe { ID3D12Resource::from_raw(object.as_raw()) }); + // SAFETY: the reference just taken. (The count does not tell + // all that are dying: `Recorder::gone` takes those out.) + held.insert(res.id, unsafe { + ID3D12Resource::from_raw(object.as_raw()) + }); all.push(res.clone()); } } @@ -594,7 +595,11 @@ impl Capture { } // Moved in: the writers end when it goes. let todo = todo; - for pieces in batches { + for mut pieces in batches { + { + let held = lock(&r.held); + pieces.retain(|p| held.contains_key(&p.res.id)); + } if pieces.is_empty() { continue; } @@ -629,8 +634,12 @@ impl Capture { r.problem("contents of textures in memory the CPU sees are not in the capture"); continue; } - // Those alive at the start are held, those made since too. - let object = ID3D12Resource::clone(&res.object()); + // Those alive at the start are held, those made since too; what + // is not is dying. + if !lock(&r.held).contains_key(&res.id) { + continue; + } + let object = res.object(); let size = res.desc.width as usize; let (live, through) = if res.seen == Seen::Cached { let mut data = std::ptr::null_mut(); @@ -675,6 +684,10 @@ impl Capture { /// zero). fn changed(&mut self, r: &Recorder, reads: &Reads) -> Result, Fault> { self.new_buffers(r)?; + { + let held = lock(&r.held); + self.buffers.retain(|b| held.contains_key(&b.id)); + } let parts: Vec<(usize, usize, usize)> = self .buffers .iter() @@ -697,7 +710,7 @@ impl Capture { list.CopyBufferRegion( &blocks[block].0, at + from as u64, - &b.res, + &*b.res, from as u64, (to - from) as u64, ) From 475409218e6338701a9d1591e89d7eff5e34fe35 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 21:37:32 -0600 Subject: [PATCH 161/445] Frame replay: the CPU's copies leave what the card wrote; buffers in the card's memory fit Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 30 +- crates/victory-gpu/src/replay/play.rs | 128 ++++- crates/victory-gpu/src/replay/play/diverge.rs | 516 +++++++++++++++--- crates/victory-gpu/src/replay/play/merge.rs | 291 ++++++++++ crates/victory-gpu/src/replay/record.rs | 4 +- crates/victory-gpu/src/replay/snap.rs | 4 +- docs/replay.md | 24 + 7 files changed, 893 insertions(+), 104 deletions(-) create mode 100644 crates/victory-gpu/src/replay/play/merge.rs diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index 714009f..f73ea08 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -62,6 +62,10 @@ pub(crate) struct Replay { /// One ExecuteCommandLists for the whole frame. #[arg(long)] one_submit: bool, + /// Let copies of what the CPU wrote also overwrite what the card wrote in + /// the replay (as the recorded commands say). + #[arg(long)] + no_merge: bool, /// A full wait after every draw, dispatch, copy and clear. #[arg(long)] wait_all: bool, @@ -158,6 +162,7 @@ pub(crate) fn run(r: Replay) -> Result<()> { skip_clamps: r.skip_clamps, skip_hash_passes: r.skip_hash_passes, one_submit: r.one_submit, + merge: !r.no_merge, wait_all: r.wait_all, wait_lists: r.wait_lists, only, @@ -179,13 +184,27 @@ pub(crate) fn run(r: Replay) -> Result<()> { } let mut watched = Vec::new(); for text in &r.watch { - let mut n = text.split(':').map(|p| u64::from_str_radix(p.trim_start_matches("0x"), 16)); - let mut next = || n.next().and_then(Result::ok).with_context(|| format!("--watch {text}")); - let id = text.split(':').next().and_then(|p| p.parse().ok()).with_context(|| format!("--watch {text}"))?; + let mut n = text + .split(':') + .map(|p| u64::from_str_radix(p.trim_start_matches("0x"), 16)); + let mut next = || { + n.next() + .and_then(Result::ok) + .with_context(|| format!("--watch {text}")) + }; + let id = text + .split(':') + .next() + .and_then(|p| p.parse().ok()) + .with_context(|| format!("--watch {text}"))?; let _ = next(); watched.push((id, next()?, next()?)); } - if let Some(runs) = r.diverge.or(r.diverge_picture).or((!watched.is_empty()).then_some(2)) { + if let Some(runs) = r + .diverge + .or(r.diverge_picture) + .or((!watched.is_empty()).then_some(2)) + { let lists = match &r.lists { Some(text) => Some(range(text).with_context(|| format!("--lists {text}"))?), None => None, @@ -209,7 +228,8 @@ pub(crate) fn run(r: Replay) -> Result<()> { Some(text) => Some(range(text).with_context(|| format!("--commands {text}"))?), None => None, }; - return player.diverge_picture(&search, commands, r.step, &mut |line| println!("{line}")); + return player + .diverge_picture(&search, commands, r.step, &mut |line| println!("{line}")); } return player.diverge(&search, &mut |line| println!("{line}")); } diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index ba1543a..5ad96c5 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -30,6 +30,7 @@ use super::wire::{ }; pub mod diverge; +mod merge; /// The name of the argument clamp's pipeline, by which its passes are /// recognised. @@ -69,6 +70,9 @@ pub struct Options { pub skip_clamps: bool, pub skip_hash_passes: bool, pub one_submit: bool, + /// Copies of what the CPU wrote leave alone what the card wrote in this + /// run (`merge`). + pub merge: bool, /// A full wait after every command that works. pub wait_all: bool, /// Each list sent on its own, and waited for. @@ -98,6 +102,7 @@ impl Default for Options { skip_clamps: false, skip_hash_passes: false, one_submit: false, + merge: true, wait_all: false, wait_lists: false, only: None, @@ -372,6 +377,11 @@ pub struct Player { /// States at the start of the frame and after it. start: HashMap>, end: HashMap>, + /// For `Options::merge`. + merger: Option, + merging: bool, + /// Resources the card may write in the frame. + card_writes: HashSet, /// The results of clamp passes ([`RESULTS`]). results: Option, commands: Vec>, @@ -437,6 +447,9 @@ impl Player { delta_parts: Vec::new(), start: HashMap::new(), end: HashMap::new(), + merger: None, + merging: false, + card_writes: HashSet::new(), results: None, commands, fresh: true, @@ -463,12 +476,22 @@ impl Player { step("descriptors", &mut at); player.load_contents()?; step("contents", &mut at); - player.make_masters()?; + player.make_masters(options.buffers)?; step("copies to restore from", &mut at); let steps: Vec = steps .iter() .map(|(w, d)| format!("{w} {:.1} s", d.as_secs_f64())) .collect(); + if let Some([budget, used, pc]) = player.memory() { + let over = if used + 256 > budget { + ": over the budget, so the system moves memory to the PC's and the times are not the card's" + } else { + "" + }; + player.notes.push(format!( + "{used} MB of the card's memory used, budget {budget} MB; {pc} MB of the PC's{over}" + )); + } player.notes.push(format!( "loaded in {:.1} s: {}", began.elapsed().as_secs_f64(), @@ -1422,7 +1445,7 @@ impl Player { } /// Copies of what the frame changes; and the states it leaves. - fn make_masters(&mut self) -> Result<()> { + fn make_masters(&mut self, buffers: Buffers) -> Result<()> { let mut states = States::default(); for r in &self.frame.resources { if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { @@ -1454,6 +1477,7 @@ impl Player { .filter(|r| r.state.iter().any(|s| s & WRITE != 0)) .map(|r| r.id) .collect(); + let mut by_cpu: HashSet = HashSet::new(); for (i, s) in self.frame.submits.iter().enumerate() { for &l in s.lists.iter().filter(|&&l| l != MISSING) { for c in &self.commands[l as usize] { @@ -1504,7 +1528,7 @@ impl Player { } states.decay(); if i > 0 { - written.extend(self.delta_parts[i].iter().map(|(d, _)| d.res)); + by_cpu.extend(self.delta_parts[i].iter().map(|(d, _)| d.res)); } } // Buffers any unordered-access view names. @@ -1537,6 +1561,8 @@ impl Player { } } } + self.card_writes = written.clone(); + written.extend(by_cpu); for id in self.start.keys() { self.end .insert(*id, states.get(*id).unwrap_or(vec![COMMON])); @@ -1568,7 +1594,10 @@ impl Player { let size = unsafe { self.device.GetResourceAllocationInfo(0, &[desc]) }.SizeInBytes; let room = self.room(); let buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; - let pc = buffer && room.is_some_and(|room| room < size + (1 << 30)); + // With all buffers in the card's memory there is no room for + // their copies as well. + let pc = buffer + && (buffers == Buffers::Card || room.is_some_and(|room| room < size + (1 << 30))); let props = if pc { D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, @@ -1642,6 +1671,31 @@ impl Player { Ok(()) } + /// The card's memory budget and use, and the use of the PC's memory, in + /// MB. + fn memory(&self) -> Option<[u64; 3]> { + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut pc = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: plain queries. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter3 = factory + .EnumAdapterByLuid(self.device.GetAdapterLuid()) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut pc) + .ok()?; + } + Some([ + own.Budget >> 20, + own.CurrentUsage >> 20, + pc.CurrentUsage >> 20, + ]) + } + /// What is free of the card's memory budget. fn room(&self) -> Option { let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); @@ -1696,6 +1750,13 @@ impl Player { for (id, m) in &restored { list.CopyResource(&objects[id].res, *m); } + if let Some(merger) = &self.merger { + for (id, base) in &merger.bases { + if let Some((_, m)) = self.masters.iter().find(|m| m.0 == *id) { + list.CopyResource(base, m); + } + } + } barriers(list, &back); } })?; @@ -1886,10 +1947,15 @@ impl Player { unsafe { let mut seen = HashSet::new(); let mut after = Vec::new(); + let mut merges = Vec::new(); for (d, at) in parts { let Some(ob) = self.objects.get(&d.res) else { continue; }; + if self.merging && self.card_writes.contains(&d.res) { + merges.push((d.res, d.at, *at, d.len)); + continue; + } open.1.CopyBufferRegion(&ob.res, d.at, from, *at, d.len); if seen.insert(d.res) { // Back to the common state by itself, for @@ -1898,6 +1964,11 @@ impl Player { } } barriers(&open.1, &after); + if !merges.is_empty() { + self.wait_for_all(&open.1); + self.merge_all(&open.1, from.GetGPUVirtualAddress(), &merges); + self.wait_for_all(&open.1); + } } Some(self.close(open, &heap, &mut next, Vec::new())?) } @@ -2077,13 +2148,51 @@ impl Player { .collect(); let mut stamps = Vec::new(); let mut bound = NONE; + // What the compute side has bound. + let mut compute: Vec = Vec::new(); for c in cmds { if let Cmd::Pipeline { pso } = c { bound = *pso; } - // SAFETY: an open list; the objects are the frame's, alive with - // the player; commands the host recorded the same way. - unsafe { self.command(list, c, version) }; + let merged = self.merged_copy(c); + if let Some((from, what)) = merged { + // SAFETY: an open list; live buffers; what the compute side + // of it had bound is bound again. + unsafe { + self.wait_for_all(list); + self.merge_all(list, from, &[what]); + self.wait_for_all(list); + for c in &compute { + self.command(list, c, version); + } + } + } else { + // SAFETY: an open list; the objects are the frame's, alive + // with the player; commands the host recorded the same way. + unsafe { self.command(list, c, version) }; + } + match c { + Cmd::RootSignature { + graphics: false, .. + } => { + compute.retain(|c| matches!(c, Cmd::Pipeline { .. })); + compute.push(c.clone()); + } + Cmd::Pipeline { .. } => { + compute.retain(|c| !matches!(c, Cmd::Pipeline { .. })); + compute.push(c.clone()); + } + Cmd::Table { + graphics: false, .. + } + | Cmd::Constants { + graphics: false, .. + } + | Cmd::RootView { + graphics: false, .. + } => compute.push(c.clone()), + _ => {} + } if wait && c.works() { // SAFETY: an open list. unsafe { self.wait_for_all(list) }; @@ -2608,6 +2717,7 @@ impl Player { notes: self.notes.clone(), ..Default::default() }; + self.set_merging(o.merge)?; let clamps = if o.skip_clamps { self.clamp_results(&mut report)? } else { @@ -2654,6 +2764,10 @@ impl Player { if o.detailed { self.detail(&built, &stamps, o, &mut report); } + if self.merging { + let notes = self.merge_notes(o.loops)?; + report.notes.extend(notes); + } self.picture(o, &mut report)?; if let Some(q) = &self.info { report.notes.extend(debug_messages(q)); diff --git a/crates/victory-gpu/src/replay/play/diverge.rs b/crates/victory-gpu/src/replay/play/diverge.rs index 7a6ace0..a297040 100644 --- a/crates/victory-gpu/src/replay/play/diverge.rs +++ b/crates/victory-gpu/src/replay/play/diverge.rs @@ -104,13 +104,20 @@ impl Player { } roots += 1; // The shortest start of the rest that differs. - let works: Vec = (from..cmds.len()).filter(|&c| cmds[c].works()).collect(); + let works: Vec = + (from..cmds.len()).filter(|&c| cmds[c].works()).collect(); let (mut lo, mut hi) = (0, works.len() - 1); while lo < hi { let mid = (lo + hi) / 2; - let cut = Unit { to: works[mid] + 1, ..unit }; + let cut = Unit { + to: works[mid] + 1, + ..unit + }; self.put_back(&states)?; - if self.trials(&reader, &cut, &states, s.runs, s.wait_all)?.is_empty() { + if self + .trials(&reader, &cut, &states, s.runs, s.wait_all)? + .is_empty() + { lo = mid + 1; } else { hi = mid; @@ -172,13 +179,18 @@ impl Player { let mut states = self.start_states(); for (here, &(i, j, cmds)) in flat.iter().enumerate() { let inside = s.lists.is_some_and(|(a, b)| a == b && a as usize == here); - let looks = s.lists.is_none_or(|(a, b)| (a as usize..=b as usize).contains(&here)); + let looks = s + .lists + .is_none_or(|(a, b)| (a as usize..=b as usize).contains(&here)); let works: Vec = (0..cmds.len()).filter(|&c| cmds[c].works()).collect(); // Where the list is cut. let mut cuts: Vec = vec![0]; if inside { let (a, b) = commands.unwrap_or((0, u32::MAX)); - let some = works.iter().map(|&c| c + 1).filter(|c| (a as usize..=b as usize).contains(c)); + let some = works + .iter() + .map(|&c| c + 1) + .filter(|c| (a as usize..=b as usize).contains(c)); cuts.extend(some.step_by(step.max(1))); } for (k, &from) in cuts.iter().enumerate() { @@ -189,14 +201,26 @@ impl Player { self.put_back(&states)?; } let mut now = states.clone(); - let first = Unit { submit: i, cmds, from, to: cmds.len(), delta: j == 0 && from == 0 }; + let first = Unit { + submit: i, + cmds, + from, + to: cmds.len(), + delta: j == 0 && from == 0, + }; self.go(&first, s.wait_all)?; now = self.after(&first, &now); for (n, &(i, j, cmds)) in flat.iter().enumerate().skip(here + 1) { if flat[n - 1].0 != i { now.decay(); } - let unit = Unit { submit: i, cmds, from: 0, to: cmds.len(), delta: j == 0 }; + let unit = Unit { + submit: i, + cmds, + from: 0, + to: cmds.len(), + delta: j == 0, + }; self.go(&unit, s.wait_all)?; now = self.after(&unit, &now); } @@ -222,7 +246,13 @@ impl Player { } // On to the next cut. let to = cuts.get(k + 1).copied().unwrap_or(cmds.len()); - let unit = Unit { submit: i, cmds, from, to, delta: j == 0 && from == 0 }; + let unit = Unit { + submit: i, + cmds, + from, + to, + delta: j == 0 && from == 0, + }; self.go(&unit, s.wait_all)?; self.commit(&unit, &mut states)?; self.at = states.clone(); @@ -248,7 +278,9 @@ impl Player { fn start_states(&self) -> States { let mut states = States::default(); for (id, all) in &self.start { - let Some(o) = self.objects.get(id) else { continue }; + let Some(o) = self.objects.get(id) else { + continue; + }; let flags = self.frame.resources[o.index].desc.flags; let decays = flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0; states.add(*id, o.subs, all[0], decays); @@ -285,38 +317,73 @@ impl Player { let start = self.start_states(); let before = self.hashes_now(&reader, &start)?; let mut again = self.hashes_now(&reader, &start)?; - say(format!("read twice, {} parts differ", before.iter().zip(&again).filter(|(a, b)| a != b).count())); + say(format!( + "read twice, {} parts differ", + before.iter().zip(&again).filter(|(a, b)| a != b).count() + )); for i in 0..3 { - self.run(&Options { loops: 1, ..Options::default() })?; + self.run(&Options { + loops: 1, + ..Options::default() + })?; let ran = { - let end: Vec<(u32, Vec)> = self.end.iter().map(|(k, v)| (*k, v.clone())).collect(); + let end: Vec<(u32, Vec)> = + self.end.iter().map(|(k, v)| (*k, v.clone())).collect(); let mut s = start.clone(); for (id, v) in end { for (sub, st) in v.iter().enumerate() { let sub = if v.len() == 1 { ALL } else { sub as u32 }; - s.change(&states::Change { res: id, sub, after: *st, promoted: false, alias: false }); + s.change(&states::Change { + res: id, + sub, + after: *st, + promoted: false, + alias: false, + }); } } self.hashes_now(&reader, &s)? }; self.restore(true)?; again = self.hashes_now(&reader, &start)?; - let differ: Vec = (0..before.len()).filter(|&i| before[i] != again[i]).collect(); + let differ: Vec = (0..before.len()) + .filter(|&i| before[i] != again[i]) + .collect(); let changed = (0..before.len()).filter(|&i| before[i] != ran[i]).count(); - say(format!("run {i}: {changed} parts changed by the frame, {} not put back as they were", differ.len())); + say(format!( + "run {i}: {changed} parts changed by the frame, {} not put back as they were", + differ.len() + )); for &d in differ.iter().take(20) { - let pieces = before[d].iter().zip(&again[d]).filter(|(a, b)| a != b).count(); - say(format!(" {} {:?}: {pieces} of {} pieces", self.called(reader.parts[d].id), reader.parts[d].sub.map(|s| s.0), before[d].len())); + let pieces = before[d] + .iter() + .zip(&again[d]) + .filter(|(a, b)| a != b) + .count(); + say(format!( + " {} {:?}: {pieces} of {} pieces", + self.called(reader.parts[d].id), + reader.parts[d].sub.map(|s| s.0), + before[d].len() + )); } } } let put_back: HashSet = self.masters.iter().map(|m| m.0).collect(); - let others: Vec = self.objects.keys().copied().filter(|id| !put_back.contains(id)).collect(); + let others: Vec = self + .objects + .keys() + .copied() + .filter(|id| !put_back.contains(id)) + .collect(); let reader = self.reader(&others)?; self.restore(true)?; let start = self.start_states(); let before = self.hashes_now(&reader, &start)?; - let o = Options { loops: 1, ..Options::default() }; + let o = Options { + loops: 1, + ..Options::default() + }; self.run(&o)?; self.restore(true)?; let after = self.hashes_now(&reader, &start)?; @@ -337,7 +404,11 @@ impl Player { )); } } - say(format!("{} parts of {} resources looked at, {n} changed", reader.parts.len(), others.len())); + say(format!( + "{} parts of {} resources looked at, {n} changed", + reader.parts.len(), + others.len() + )); Ok(()) } @@ -381,7 +452,12 @@ impl Player { } let mut blocks = Vec::new(); for size in sizes { - let (b, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, size, D3D12_RESOURCE_FLAG_NONE)?; + let (b, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_READBACK, + size, + D3D12_RESOURCE_FLAG_NONE, + )?; blocks.push((b, data as usize)); } Ok(Reader { blocks, parts }) @@ -410,12 +486,22 @@ impl Player { let before: Vec = unit.cmds[..unit.from] .iter() .filter(|c| { - !c.works() && !matches!(c, Cmd::Barriers { .. } | Cmd::BeginQuery { .. } | Cmd::EndQuery { .. }) + !c.works() + && !matches!( + c, + Cmd::Barriers { .. } | Cmd::BeginQuery { .. } | Cmd::EndQuery { .. } + ) }) .cloned() .collect(); self.translate(&l.1, &before, unit.submit, None, false); - self.translate(&l.1, &unit.cmds[unit.from..unit.to], unit.submit, None, wait); + self.translate( + &l.1, + &unit.cmds[unit.from..unit.to], + unit.submit, + None, + wait, + ); // SAFETY: an open list. unsafe { l.1.Close()? }; lists.push(l); @@ -437,7 +523,10 @@ impl Player { for p in parts.iter().filter(|p| p.sub.is_some()) { if seen.insert(p.id) { let state = states.get(p.id).unwrap_or(vec![COMMON]); - let to: Vec = state.iter().map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect(); + let to: Vec = state + .iter() + .map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }) + .collect(); gpu::moves(&objects[&p.id].res, &state, &to, &mut before); gpu::moves(&objects[&p.id].res, &to, &state, &mut after); } @@ -453,7 +542,14 @@ impl Player { None => list.CopyBufferRegion(to, p.at, res, 0, p.len), Some((sub, mut f)) => { f.Offset = p.at; - list.CopyTextureRegion(&gpu::placed_location(to, f), 0, 0, 0, &gpu::sub_location(res, sub), None); + list.CopyTextureRegion( + &gpu::placed_location(to, f), + 0, + 0, + 0, + &gpu::sub_location(res, sub), + None, + ); } } } @@ -462,7 +558,8 @@ impl Player { })?; } let next = AtomicUsize::new(0); - let out: std::sync::Mutex>> = std::sync::Mutex::new(vec![Vec::new(); reader.parts.len()]); + let out: std::sync::Mutex>> = + std::sync::Mutex::new(vec![Vec::new(); reader.parts.len()]); std::thread::scope(|scope| { for _ in 0..16 { scope.spawn(|| { @@ -488,7 +585,14 @@ impl Player { /// Runs the unit `runs` times (memory is as at its start, and is put /// back between runs) and compares. Memory is as the last run left it. - fn trials(&mut self, reader: &Reader, unit: &Unit, states: &States, runs: u32, wait: bool) -> Result { + fn trials( + &mut self, + reader: &Reader, + unit: &Unit, + states: &States, + runs: u32, + wait: bool, + ) -> Result { let after = self.after(unit, states); let mut first: Option>> = None; let mut pieces = std::collections::BTreeSet::new(); @@ -505,7 +609,13 @@ impl Player { None => first = Some(now), Some(first) => { for (p, (a, b)) in first.iter().zip(&now).enumerate() { - pieces.extend(a.iter().zip(b).enumerate().filter(|(_, (a, b))| a != b).map(|(i, _)| (p, i))); + pieces.extend( + a.iter() + .zip(b) + .enumerate() + .filter(|(_, (a, b))| a != b) + .map(|(i, _)| (p, i)), + ); } } } @@ -537,12 +647,18 @@ impl Player { /// Copies the masters over the resources (which are in `from` and go to /// `to`), or the resources into the masters. fn copy_masters(&mut self, from: &States, to: &States, save: bool) -> Result<()> { - let known: HashMap = self.masters.iter().map(|(id, m)| (*id, m)).collect(); + let known: HashMap = + self.masters.iter().map(|(id, m)| (*id, m)).collect(); let (mut before, mut after, mut plain) = (Vec::new(), Vec::new(), Vec::new()); let here = if save { COPY_SOURCE } else { COPY_DEST }; for id in self.start.keys() { - let Some(o) = self.objects.get(id) else { continue }; - let (a, b) = (from.get(*id).unwrap_or(vec![COMMON]), to.get(*id).unwrap_or(vec![COMMON])); + let Some(o) = self.objects.get(id) else { + continue; + }; + let (a, b) = ( + from.get(*id).unwrap_or(vec![COMMON]), + to.get(*id).unwrap_or(vec![COMMON]), + ); let Some(m) = known.get(id) else { gpu::moves(&o.res, &a, &b, &mut plain); continue; @@ -590,27 +706,59 @@ impl Player { match c { Cmd::Pipeline { pso: p } => pso = *p, Cmd::RootSignature { graphics, .. } => binds.retain(|k, _| k.0 != *graphics), - Cmd::RootView { graphics, kind, param, va } => { - let kind = ["", "cbv", "srv", "uav"].get(*kind as usize).copied().unwrap_or(""); + Cmd::RootView { + graphics, + kind, + param, + va, + } => { + let kind = ["", "cbv", "srv", "uav"] + .get(*kind as usize) + .copied() + .unwrap_or(""); let text = match va { - Va::At { res, offset } => format!("{kind} {} +{offset:#x}", self.called(*res)), + Va::At { res, offset } => { + format!("{kind} {} +{offset:#x}", self.called(*res)) + } _ => format!("{kind} null"), }; binds.insert((*graphics, *param), text); } - Cmd::Table { graphics, param, heap, slot } => { - binds.insert((*graphics, *param), format!("table heap {heap} slot {slot}")); + Cmd::Table { + graphics, + param, + heap, + slot, + } => { + binds.insert( + (*graphics, *param), + format!("table heap {heap} slot {slot}"), + ); } - Cmd::Constants { graphics, param, offset, values } => { + Cmd::Constants { + graphics, + param, + offset, + values, + } => { let text = format!("constants +{offset} {values:x?}"); - binds.entry((*graphics, *param)).and_modify(|t| *t = format!("{t}, {text}")).or_insert(text); + binds + .entry((*graphics, *param)) + .and_modify(|t| *t = format!("{t}, {text}")) + .or_insert(text); } Cmd::Targets { colors, depth } => { - let all: Vec = colors.iter().chain(depth).map(|s| self.called(s.res)).collect(); + let all: Vec = colors + .iter() + .chain(depth) + .map(|s| self.called(s.res)) + .collect(); targets = all.join(", "); } Cmd::Barriers { all } => since.extend(all.iter().map(|b| match b { - Barrier::Transition { res, before, after, .. } => format!("{} {before:#x}->{after:#x}", self.called(*res)), + Barrier::Transition { + res, before, after, .. + } => format!("{} {before:#x}->{after:#x}", self.called(*res)), Barrier::Uav { res: 0, .. } => "all uav".into(), Barrier::Uav { res, .. } => format!("uav {}", self.called(*res)), Barrier::Alias { .. } => "alias".into(), @@ -622,7 +770,11 @@ impl Player { } } let graphics = !matches!(cmds[at], Cmd::Dispatch { .. }); - let binds: Vec = binds.iter().filter(|(k, _)| k.0 == graphics).map(|(k, t)| format!("[{}] {t}", k.1)).collect(); + let binds: Vec = binds + .iter() + .filter(|(k, _)| k.0 == graphics) + .map(|(k, t)| format!("[{}] {t}", k.1)) + .collect(); let mut text = format!("{:?}", cmds[at]); if cmds[at].runs_shaders() { text += &format!(" of {}", self.pipeline_name(pso)); @@ -631,12 +783,20 @@ impl Player { text += &format!("\n targets: {targets}"); } } - text + &format!("\n barriers since the command before: {}", since.join("; ")) + text + &format!( + "\n barriers since the command before: {}", + since.join("; ") + ) } /// Says which lists (of the list in `s.lists`: which commands) change /// words of a buffer, and to what. - pub fn watch(&mut self, s: &Search, parts: &[(u32, u64, u64)], say: &mut dyn FnMut(String)) -> Result<()> { + pub fn watch( + &mut self, + s: &Search, + parts: &[(u32, u64, u64)], + say: &mut dyn FnMut(String), + ) -> Result<()> { let mut report = Report::default(); let submits = self.edited(&s.options, &mut report, &[]); self.restore(true)?; @@ -646,7 +806,10 @@ impl Player { .iter() .map(|&(id, at, len)| { let bytes = p.slice(id, at, len)?; - Ok(bytes.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect()) + Ok(bytes + .chunks_exact(4) + .map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())) + .collect()) }) .collect() }; @@ -666,13 +829,25 @@ impl Player { cuts.push(cmds.len()); } for k in 0..cuts.len() - 1 { - let unit = Unit { submit: i, cmds, from: cuts[k], to: cuts[k + 1], delta: j == 0 && k == 0 }; + let unit = Unit { + submit: i, + cmds, + from: cuts[k], + to: cuts[k + 1], + delta: j == 0 && k == 0, + }; self.go(&unit, s.wait_all)?; let now = words(self)?; if now != was { if inside { - let last = (unit.from..unit.to).rev().find(|&c| cmds[c].works()).unwrap_or(unit.to - 1); - say(format!("list {here} (submission {i}, its list {j}) command {last}: {}", self.describe(cmds, last))); + let last = (unit.from..unit.to) + .rev() + .find(|&c| cmds[c].works()) + .unwrap_or(unit.to - 1); + say(format!( + "list {here} (submission {i}, its list {j}) command {last}: {}", + self.describe(cmds, last) + )); } else { say(format!("list {here} (submission {i}, its list {j})")); } @@ -703,7 +878,12 @@ impl Player { /// Each draw of one list whose pipeline's name has `text` in it, run /// alone (with what prepares its arguments) from the memory at the list's /// start, `runs` times: how many different contents its targets get. - pub fn diverge_draws(&mut self, s: &Search, text: &str, say: &mut dyn FnMut(String)) -> Result<()> { + pub fn diverge_draws( + &mut self, + s: &Search, + text: &str, + say: &mut dyn FnMut(String), + ) -> Result<()> { let mut report = Report::default(); let submits = self.edited(&s.options, &mut report, &[]); let flat: Vec<(usize, usize, &Vec)> = submits @@ -717,7 +897,13 @@ impl Player { let mut states = self.start_states(); for (here, &(i, j, cmds)) in flat.iter().enumerate() { if here < wanted { - let unit = Unit { submit: i, cmds, from: 0, to: cmds.len(), delta: j == 0 }; + let unit = Unit { + submit: i, + cmds, + from: 0, + to: cmds.len(), + delta: j == 0, + }; self.go(&unit, s.wait_all)?; self.commit(&unit, &mut states)?; if flat.get(here + 1).is_none_or(|n| n.0 != i) { @@ -732,10 +918,23 @@ impl Player { for (c, cmd) in cmds.iter().enumerate() { match cmd { Cmd::Pipeline { pso: p } => pso = *p, - Cmd::Targets { colors, depth } => targets = colors.iter().chain(depth).map(|s| s.res).filter(|r| *r != NONE).collect(), + Cmd::Targets { colors, depth } => { + targets = colors + .iter() + .chain(depth) + .map(|s| s.res) + .filter(|r| *r != NONE) + .collect() + } _ => {} } - if !matches!(cmd, Cmd::Indirect { .. } | Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::DispatchMesh { .. }) { + if !matches!( + cmd, + Cmd::Indirect { .. } + | Cmd::Draw { .. } + | Cmd::DrawIndexed { .. } + | Cmd::DispatchMesh { .. } + ) { continue; } let from = std::mem::replace(&mut last, c + 1); @@ -745,12 +944,20 @@ impl Player { targets.sort_unstable(); targets.dedup(); let reader = self.reader(&targets)?; - let unit = Unit { submit: i, cmds, from, to: c + 1, delta: false }; + let unit = Unit { + submit: i, + cmds, + from, + to: c + 1, + delta: false, + }; // Barriers before it in the list are made up for: textures // are in the states the list has them in here. let mut before = states.clone(); let mut all = Vec::new(); - cmds[..from].iter().for_each(|c| states::changes(c, &mut all)); + cmds[..from] + .iter() + .for_each(|c| states::changes(c, &mut all)); all.iter().for_each(|c| before.change(c)); let after = self.after(&unit, &before); let mut kinds: HashMap>, u32> = HashMap::new(); @@ -770,7 +977,12 @@ impl Player { } let mut counts: Vec = kinds.values().copied().collect(); counts.sort_unstable(); - say(format!("command {c} (from {from}) {:?} of {}: {} outcomes {counts:?}", cmd, self.pipeline_name(pso), counts.len())); + say(format!( + "command {c} (from {from}) {:?} of {}: {} outcomes {counts:?}", + cmd, + self.pipeline_name(pso), + counts.len() + )); } break; } @@ -779,13 +991,20 @@ impl Player { /// `len` bytes of a buffer from `at`. fn slice(&mut self, id: u32, at: u64, len: u64) -> Result> { - let Some(o) = self.objects.get(&id) else { return Ok(Vec::new()) }; + let Some(o) = self.objects.get(&id) else { + return Ok(Vec::new()); + }; let len = len.min(self.frame.resources[o.index].desc.width.saturating_sub(at)); if len == 0 { return Ok(Vec::new()); } let res = o.res.clone(); - let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, len, D3D12_RESOURCE_FLAG_NONE)?; + let (back, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_READBACK, + len, + D3D12_RESOURCE_FLAG_NONE, + )?; self.worker.run(|list| { // SAFETY: an open list; live buffers. unsafe { list.CopyBufferRegion(&back, 0, &res, at, len) }; @@ -796,20 +1015,39 @@ impl Player { /// The words of a buffer view (raw or typed, of words). fn view_words(&mut self, s: &Slot, first: u64, n: u64) -> Result> { - let at = u64::from_le_bytes([s.desc[16], s.desc[17], s.desc[18], s.desc[19], s.desc[20], s.desc[21], s.desc[22], s.desc[23]]); - let count = u64::from(u32::from_le_bytes([s.desc[24], s.desc[25], s.desc[26], s.desc[27]])); + let at = u64::from_le_bytes([ + s.desc[16], s.desc[17], s.desc[18], s.desc[19], s.desc[20], s.desc[21], s.desc[22], + s.desc[23], + ]); + let count = u64::from(u32::from_le_bytes([ + s.desc[24], s.desc[25], s.desc[26], s.desc[27], + ])); let n = n.min(count.saturating_sub(first)); let bytes = self.slice(s.res, (at + first) * 4, n * 4)?; - Ok(bytes.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect()) + Ok(bytes + .chunks_exact(4) + .map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())) + .collect()) } /// What a mesh draw of the title's (with its usual constants) reads. - fn peek(&mut self, cmds: &[Cmd], at: usize, submit: usize, say: &mut dyn FnMut(String)) -> Result<()> { + fn peek( + &mut self, + cmds: &[Cmd], + at: usize, + submit: usize, + say: &mut dyn FnMut(String), + ) -> Result<()> { let mut v = [0u32; 16]; let mut heap = NONE; for c in &cmds[..at] { match c { - Cmd::Constants { graphics: true, param: 0, offset, values } => { + Cmd::Constants { + graphics: true, + param: 0, + offset, + values, + } => { for (k, x) in values.iter().enumerate() { if let Some(at) = v.get_mut(*offset as usize + k) { *at = *x; @@ -834,20 +1072,33 @@ impl Player { ("x+2848", v[8] + 2848, 0), ] { let s = slot(self, byte); - let words = if s.kind == slot::SRV { self.view_words(&s, 0, n)? } else { Vec::new() }; - say(format!(" {name}: slot {} {}: {words:x?}", byte >> 5, self.slot_text(&s))); + let words = if s.kind == slot::SRV { + self.view_words(&s, 0, n)? + } else { + Vec::new() + }; + say(format!( + " {name}: slot {} {}: {words:x?}", + byte >> 5, + self.slot_text(&s) + )); } // The list of visible meshlets, as the mesh shader finds it. let lists = slot(self, v[8] + 2752); let word = self.view_words(&lists, u64::from((v[13] & 0x07ff_ffff) & 0x07ff_ffff), 4)?; let typed = slot(self, v[8] + 1600); let index = self.view_words(&typed, 510, 1)?; - say(format!(" list words {word:x?} (count {}, first {}), typed view slot {index:x?}", word.first().map_or(0, |w| w >> 15), word.first().map_or(0, |w| w & 0x7fff))); + say(format!( + " list words {word:x?} (count {}, first {}), typed view slot {index:x?}", + word.first().map_or(0, |w| w >> 15), + word.first().map_or(0, |w| w & 0x7fff) + )); if let (Some(w), Some(i)) = (word.first(), index.first()) { let s = self.slot_at(heap, i & 0x07ff_ffff, submit); say(format!(" typed view: {}", self.slot_text(&s))); if s.kind == slot::SRV && s.res != NONE { - let list = self.view_words(&s, u64::from(w & 0x7fff) * 16, u64::from(w >> 15) + 16)?; + let list = + self.view_words(&s, u64::from(w & 0x7fff) * 16, u64::from(w >> 15) + 16)?; say(format!(" visible meshlets: {list:x?}")); } } @@ -868,7 +1119,12 @@ impl Player { let mut heap = NONE; for c in &cmds[..command] { match c { - Cmd::Constants { param, offset, values: v, .. } => { + Cmd::Constants { + param, + offset, + values: v, + .. + } => { for (k, x) in v.iter().enumerate() { if let Some(all) = values.get_mut(*param as usize) && let Some(at) = all.get_mut(*offset as usize + k) @@ -882,7 +1138,12 @@ impl Player { } } say(format!("heap {heap}, constants {values:x?}")); - let mut bases: Vec = values.iter().flatten().map(|v| v >> 5).filter(|v| *v > 64).collect(); + let mut bases: Vec = values + .iter() + .flatten() + .map(|v| v >> 5) + .filter(|v| *v > 64) + .collect(); bases.dedup(); for base in bases { for k in 0..12 { @@ -904,10 +1165,19 @@ impl Player { /// A heap slot as it was for a submission. fn slot_at(&self, heap: u32, at: u32, submit: usize) -> Slot { let late = self.frame.submits[..=submit].iter().rev().find_map(|s| { - s.views.iter().rev().find(|(h, i, _)| *h == heap && *i == at).map(|v| v.2) + s.views + .iter() + .rev() + .find(|(h, i, _)| *h == heap && *i == at) + .map(|v| v.2) }); late.unwrap_or_else(|| { - let runs = self.frame.descriptor_heaps.iter().find(|h| h.id == heap).map(|h| &h.runs); + let runs = self + .frame + .descriptor_heaps + .iter() + .find(|h| h.id == heap) + .map(|h| &h.runs); runs.and_then(|runs| { let k = runs.partition_point(|r| r.0 <= at).checked_sub(1)?; let (first, n, s) = &runs[k]; @@ -918,9 +1188,23 @@ impl Player { } fn slot_text(&self, s: &Slot) -> String { - let word = |i: usize| u32::from_le_bytes([s.desc[i * 4], s.desc[i * 4 + 1], s.desc[i * 4 + 2], s.desc[i * 4 + 3]]); - let kind = ["empty", "cbv", "srv", "uav", "sampler", "rtv", "dsv"].get(s.kind as usize).copied().unwrap_or("?"); - let res = if s.res == NONE { "null".into() } else { self.called(s.res) }; + let word = |i: usize| { + u32::from_le_bytes([ + s.desc[i * 4], + s.desc[i * 4 + 1], + s.desc[i * 4 + 2], + s.desc[i * 4 + 3], + ]) + }; + let kind = ["empty", "cbv", "srv", "uav", "sampler", "rtv", "dsv"] + .get(s.kind as usize) + .copied() + .unwrap_or("?"); + let res = if s.res == NONE { + "null".into() + } else { + self.called(s.res) + }; match s.kind { slot::CBV => format!("cbv {res} +{:#x} size {:#x}", s.address(), word(2)), _ => format!( @@ -935,7 +1219,7 @@ impl Player { } } - fn called(&self, id: u32) -> String { + pub(super) fn called(&self, id: u32) -> String { let Some(o) = self.objects.get(&id) else { return format!("resource {id} (not there)"); }; @@ -948,12 +1232,22 @@ impl Player { }; format!("#{id} '{}' buffer {:#x} {kind}", r.name, d.width) } else { - format!("#{id} '{}' {}x{}x{} m{} f{}", r.name, d.width, d.height, d.depth, d.mips, d.format) + format!( + "#{id} '{}' {}x{}x{} m{} f{}", + r.name, d.width, d.height, d.depth, d.mips, d.format + ) } } /// Runs the unit until two runs differ, and says how. - fn compare(&mut self, reader: &Reader, unit: &Unit, states: &States, pieces: &Pieces, wait: bool) -> Result> { + fn compare( + &mut self, + reader: &Reader, + unit: &Unit, + states: &States, + pieces: &Pieces, + wait: bool, + ) -> Result> { let after = self.after(unit, states); let parts: std::collections::BTreeSet = pieces.iter().map(|p| p.0).collect(); let mut seen: Vec<(Vec>, Vec>)> = Vec::new(); @@ -966,7 +1260,10 @@ impl Player { if seen.iter().any(|(h, _)| *h == hashes) { continue; } - let data = parts.iter().map(|&p| reader.bytes(&reader.parts[p]).to_vec()).collect(); + let data = parts + .iter() + .map(|&p| reader.bytes(&reader.parts[p]).to_vec()) + .collect(); seen.push((hashes, data)); if seen.len() == 2 { break; @@ -978,9 +1275,16 @@ impl Player { && let Some((p, part)) = reader.parts.iter().enumerate().find(|(_, p)| p.id == *args) { let bytes = &reader.bytes(part)[*at as usize..]; - let words: Vec = bytes.chunks_exact(4).take(8).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect(); + let words: Vec = bytes + .chunks_exact(4) + .take(8) + .map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())) + .collect(); let each: HashSet<&Vec> = seen.iter().map(|s| &s.0[p]).collect(); - out.push(format!("arguments {words:x?} (the same in all runs: {})", each.len() == 1)); + out.push(format!( + "arguments {words:x?} (the same in all runs: {})", + each.len() == 1 + )); } self.at = after; let [(_, a), (_, b)] = &seen[..] else { @@ -988,13 +1292,19 @@ impl Player { return Ok(out); }; // And without the command. - let before = Unit { to: unit.to - 1, ..*unit }; + let before = Unit { + to: unit.to - 1, + ..*unit + }; self.put_back(states)?; self.go(&before, wait)?; self.at = self.after(&before, states); let now = self.at.clone(); self.hashes_now(reader, &now)?; - let without: Vec> = parts.iter().map(|&p| reader.bytes(&reader.parts[p]).to_vec()).collect(); + let without: Vec> = parts + .iter() + .map(|&p| reader.bytes(&reader.parts[p]).to_vec()) + .collect(); let to = self.folder.join("diverge"); let _ = std::fs::create_dir_all(&to); for (k, &p) in parts.iter().enumerate().take(12) { @@ -1002,13 +1312,28 @@ impl Player { // Both contents, to look at. let sub = part.sub.map_or(0, |s| s.0); let _ = std::fs::write(to.join(format!("{}-{sub}-0.bin", part.id)), &without[k]); - let changed = |v: &[u8]| v.chunks_exact(4).zip(without[k].chunks_exact(4)).filter(|(x, y)| x != y).count(); - out.push(format!("it changes {} dwords in one run, {} in another", changed(&a[k]), changed(&b[k]))); + let changed = |v: &[u8]| { + v.chunks_exact(4) + .zip(without[k].chunks_exact(4)) + .filter(|(x, y)| x != y) + .count() + }; + out.push(format!( + "it changes {} dwords in one run, {} in another", + changed(&a[k]), + changed(&b[k]) + )); let _ = std::fs::write(to.join(format!("{}-{sub}-a.bin", part.id)), &a[k]); let _ = std::fs::write(to.join(format!("{}-{sub}-b.bin", part.id)), &b[k]); - let words = |v: &[u8]| -> Vec { v.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect() }; + let words = |v: &[u8]| -> Vec { + v.chunks_exact(4) + .map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())) + .collect() + }; let (x, y) = (words(&a[k]), words(&b[k])); - let differ: Vec = (0..x.len().min(y.len())).filter(|&i| x[i] != y[i]).collect(); + let differ: Vec = (0..x.len().min(y.len())) + .filter(|&i| x[i] != y[i]) + .collect(); if differ.is_empty() { continue; } @@ -1018,9 +1343,19 @@ impl Player { s.sort_unstable(); s }; - let order = if sorted(&x) == sorted(&y) { " (the same values in another order)" } else { "" }; - let sub = part.sub.map_or(String::new(), |(s, f)| format!(" subresource {s} pitch {}", f.Footprint.RowPitch)); - let sample: Vec = differ.iter().take(8).map(|&i| format!("+{:#x}: {:08x} {:08x}", i * 4, x[i], y[i])).collect(); + let order = if sorted(&x) == sorted(&y) { + " (the same values in another order)" + } else { + "" + }; + let sub = part.sub.map_or(String::new(), |(s, f)| { + format!(" subresource {s} pitch {}", f.Footprint.RowPitch) + }); + let sample: Vec = differ + .iter() + .take(8) + .map(|&i| format!("+{:#x}: {:08x} {:08x}", i * 4, x[i], y[i])) + .collect(); out.push(format!( "writes {}{sub}: {} of {} dwords differ, {:#x}..{:#x}{order}: {}", self.called(part.id), @@ -1041,6 +1376,11 @@ impl Player { impl Reader { fn bytes(&self, p: &Part) -> &[u8] { // SAFETY: a part of a mapped block; copies into it have run. - unsafe { std::slice::from_raw_parts((self.blocks[p.block].1 + p.at as usize) as *const u8, p.len as usize) } + unsafe { + std::slice::from_raw_parts( + (self.blocks[p.block].1 + p.at as usize) as *const u8, + p.len as usize, + ) + } } } diff --git a/crates/victory-gpu/src/replay/play/merge.rs b/crates/victory-gpu/src/replay/play/merge.rs new file mode 100644 index 0000000..daddcd0 --- /dev/null +++ b/crates/victory-gpu/src/replay/play/merge.rs @@ -0,0 +1,291 @@ +//! What the CPU wrote, put in without what the card wrote. +//! +//! The host layer brings results of shaders back to title memory, and sends +//! pieces of title memory up again (64 KiB at a time) when the title changed +//! some of them. What goes up therefore holds results of the recorded frame. +//! Shaders that give out places with atomics give other places in every run: +//! the recorded results put over a replay's own leave lists and what points +//! into them of two different frames. So where a copy brings memory of the +//! CPU to a buffer the card writes, words the card has written since the +//! start of the frame (which are not what was last put there) stay. + +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; + +use super::*; + +const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0), UAV(u1), UAV(u2)" +cbuffer C : register(b0) { uint words; uint call; }; +ByteAddressBuffer from : register(t0); +RWByteAddressBuffer to : register(u0); +RWByteAddressBuffer base : register(u1); +// For each call: words put, words of the card's left that were to get +// another value, and of those the ones that were to get back what stood +// there before the card wrote. +RWByteAddressBuffer counts : register(u2); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= words) return; + uint at = id.x * 4; + uint v = from.Load(at), now = to.Load(at), was = base.Load(at), n; + if (now != was) { + if (v == now) return; + counts.InterlockedAdd(call * 12 + 4, 1, n); + if (v == was) counts.InterlockedAdd(call * 12 + 8, 1, n); + return; + } + if (v == now) return; + counts.InterlockedAdd(call * 12, 1, n); + to.Store(at, v); + base.Store(at, v); +} +"#; + +pub(super) struct Merger { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// For each buffer: what was last put there (at first, what it held at + /// the frame's start). + pub(super) bases: HashMap, + pub(super) counts: ID3D12Resource, + /// The merges recorded: buffer, offset, length (in `CALLS` at the most). + pub(super) calls: std::cell::RefCell>, +} + +const CALLS: u64 = 1 << 16; + +impl Player { + /// The copy of a piece of a card buffer's CPU side to it: its source's + /// address, then the buffer, offset, 0 and length. + pub(super) fn merged_copy(&self, c: &Cmd) -> Option<(u64, (u32, u64, u64, u64))> { + let Cmd::CopyBuffer { + dst, + dst_at, + src, + src_at, + len, + } = c + else { + return None; + }; + if !self.merging + || !self.pairs(*src, *dst) + || dst_at != src_at + || dst_at % 4 != 0 + || len % 4 != 0 + { + return None; + } + self.merger.as_ref()?.bases.get(dst)?; + let from = self.objects.get(src)?.va + src_at; + Some((from, (*dst, *dst_at, 0, *len))) + } + + /// Whether `src` is the CPU's side of card buffer `dst`. + fn pairs(&self, src: u32, dst: u32) -> bool { + let (Some(a), Some(b)) = (self.objects.get(&src), self.objects.get(&dst)) else { + return false; + }; + let (a, b) = ( + &self.frame.resources[a.index], + &self.frame.resources[b.index], + ); + let cpu = + matches!(&a.place, Place::Committed { props, .. } if gpu::seen(props) == Seen::Cached); + cpu && b.name.ends_with("on the card") + && a.desc.width == b.desc.width + && self.card_writes.contains(&dst) + } + + /// Records merges: (buffer, offset in it, offset from `from`, length). + /// + /// # Safety + /// An open list; `from` is the address of memory that holds the bytes. + pub(super) unsafe fn merge_all( + &self, + list: &ID3D12GraphicsCommandList, + from: u64, + all: &[(u32, u64, u64, u64)], + ) { + let Some(m) = &self.merger else { return }; + // SAFETY: the caller's; live buffers. + unsafe { + list.SetComputeRootSignature(&m.root); + list.SetPipelineState(&m.pso); + for (id, at, source, len) in all { + let (Some(o), Some(base)) = (self.objects.get(id), m.bases.get(id)) else { + continue; + }; + let base = base.GetGPUVirtualAddress(); + // At most 65,535 groups in a dispatch. + const MOST: u64 = 8 << 20; + let mut done = 0; + while done < *len { + let n = MOST.min(len - done); + let words = (n / 4) as u32; + let mut calls = m.calls.borrow_mut(); + let call = (calls.len() as u64).min(CALLS - 1) as u32; + if calls.len() < CALLS as usize { + calls.push((*id, at + done, n)); + } + drop(calls); + list.SetComputeRoot32BitConstants(0, 2, [words, call].as_ptr().cast(), 0); + list.SetComputeRootUnorderedAccessView(4, m.counts.GetGPUVirtualAddress()); + list.SetComputeRootShaderResourceView(1, from + source + done); + list.SetComputeRootUnorderedAccessView(2, o.va + at + done); + list.SetComputeRootUnorderedAccessView(3, base + at + done); + list.Dispatch(words.div_ceil(64), 1, 1); + done += n; + } + } + } + } + + /// Switches merging on or off; makes what it needs at first. + pub(super) fn set_merging(&mut self, on: bool) -> Result<()> { + self.merging = on; + if let Some(m) = &self.merger { + m.calls.borrow_mut().clear(); + } + if !on || self.merger.is_some() { + return Ok(()); + } + let mut code: Option = None; + // SAFETY: the source and names live through the call; the blob's own + // bytes. + let (root, pso) = unsafe { + D3DCompile( + SOURCE.as_ptr().cast(), + SOURCE.len(), + None, + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + let code = code.context("no merge shader")?; + let bytes = std::slice::from_raw_parts( + code.GetBufferPointer().cast::(), + code.GetBufferSize(), + ); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso = + self.device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + (root, pso) + }; + let mut ids: HashSet = HashSet::new(); + for c in self.commands.iter().flatten() { + if let Cmd::CopyBuffer { dst, src, .. } = c + && self.pairs(*src, *dst) + { + ids.insert(*dst); + } + } + ids.extend( + self.delta_parts + .iter() + .flatten() + .map(|(d, _)| d.res) + .filter(|id| self.card_writes.contains(id)), + ); + let mut bases = HashMap::new(); + let mut total = 0; + for id in ids { + if !self.masters.iter().any(|m| m.0 == id) { + continue; + } + let size = self.frame.resources[self.objects[&id].index].desc.width; + let flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + bases.insert( + id, + gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, size, flags)?.0, + ); + total += size; + } + let masters: HashMap = self.masters.iter().cloned().collect(); + self.worker.run(|list| { + for (id, base) in &bases { + // SAFETY: an open list; live buffers of one size. + unsafe { list.CopyResource(base, &masters[id]) }; + } + })?; + tracing::info!( + buffers = bases.len(), + mb = total >> 20, + "bases of merged copies" + ); + let flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + let counts = gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, CALLS * 12, flags)?.0; + self.merger = Some(Merger { + root, + pso, + bases, + counts, + calls: Default::default(), + }); + Ok(()) + } + + /// What the merges of the last run (of `loops`, which add up) found. + pub(super) fn merge_notes(&mut self, loops: u32) -> Result> { + let Some(m) = &self.merger else { + return Ok(Vec::new()); + }; + let (counts, calls) = (m.counts.clone(), m.calls.borrow().clone()); + let (back, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_READBACK, + CALLS * 12, + D3D12_RESOURCE_FLAG_NONE, + )?; + self.worker.run(|list| { + // SAFETY: an open list; live buffers. + unsafe { list.CopyBufferRegion(&back, 0, &counts, 0, CALLS * 12) }; + })?; + // SAFETY: the mapping; the copy into it has run. + let all = unsafe { std::slice::from_raw_parts(data.cast::(), CALLS as usize * 3) }; + let each = |k: usize| { + all.iter() + .skip(k) + .step_by(3) + .map(|&n| u64::from(n)) + .sum::() + / u64::from(loops.max(1)) + }; + let mut out = vec![format!( + "{} copies of what the CPU wrote to memory the card writes: {} words put; {} left as the card wrote them in this run, where other values were to go ({} of them the values from before the card wrote)", + calls.len(), + each(0), + each(1), + each(2) + )]; + let mut worst: Vec<(u32, usize)> = (0..calls.len()) + .map(|i| (all[i * 3 + 2], i)) + .filter(|w| w.0 > 0) + .collect(); + worst.sort_by(|a, b| b.0.cmp(&a.0)); + for (n, i) in worst.into_iter().take(8) { + let (id, at, len) = calls[i]; + out.push(format!( + " values from before the card wrote: {} words, {} +{at:#x} {len:#x} bytes", + n / loops.max(1), + self.called(id) + )); + } + Ok(out) + } +} diff --git a/crates/victory-gpu/src/replay/record.rs b/crates/victory-gpu/src/replay/record.rs index 67a77e3..232f7b7 100644 --- a/crates/victory-gpu/src/replay/record.rs +++ b/crates/victory-gpu/src/replay/record.rs @@ -609,7 +609,9 @@ impl Recorder { // would be a call into what is there then. if let Some(dead) = lock(&self.held).remove(&id) { std::mem::forget(dead); - self.problem("a resource died as the frame started: its contents may be missing"); + self.problem( + "a resource died as the frame started: its contents may be missing", + ); } self.ids.remove(ptr, id); write(&self.resources).remove(&id); diff --git a/crates/victory-gpu/src/replay/snap.rs b/crates/victory-gpu/src/replay/snap.rs index 07acb47..6c69042 100644 --- a/crates/victory-gpu/src/replay/snap.rs +++ b/crates/victory-gpu/src/replay/snap.rs @@ -406,9 +406,7 @@ impl Capture { } // SAFETY: the reference just taken. (The count does not tell // all that are dying: `Recorder::gone` takes those out.) - held.insert(res.id, unsafe { - ID3D12Resource::from_raw(object.as_raw()) - }); + held.insert(res.id, unsafe { ID3D12Resource::from_raw(object.as_raw()) }); all.push(res.clone()); } } diff --git a/docs/replay.md b/docs/replay.md index 7333348..352f976 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -64,6 +64,7 @@ with the presented one. | `--buffers vram` / `sysmem` | all buffers in the card's / the PC's memory | | `--one-submit` | one `ExecuteCommandLists`, with a full wait between the former ones | | `--only 3..7` | runs these lists; of the others only barriers | +| `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) | | `--skip-shader ` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) | | `--no-restore` | leaves what a loop changed | | `--debug-layer` | D3D12's debug layer; its errors in the report | @@ -73,6 +74,29 @@ leaves out waits or work can draw another picture and, with wild data, lose the device: save work in other programs first. Do not run the title at the same time. +## Runs that differ + +Shaders that give out places with atomics (the title's culling) give other +ones in every run. The host layer brings such results to title memory and +sends 64 KiB pieces of it up again, so the recorded copies hold the recorded +run's results. Put over a replay's own, lists and what points into them are of +two runs, and things are drawn from other things' lists. So copies of what the +CPU wrote leave alone words the card has written in this run (`merge.rs`; the +report counts them). `--no-merge` runs the copies as recorded. + +| switch | does | +|---|---| +| `--wait-all` / `--wait-lists` | a full wait after every command / each list sent alone and waited for: if pictures still differ, waits are not what is missing | +| `--diverge [runs]` | runs each list this often from the very same memory, finds the first commands that make different memory of it, and says what differs (same values in another order: places given out); contents go to `diverge` in the capture | +| `--diverge-picture [runs]` | from each list on, runs the rest this often from the same memory: where the pictures start to agree, what lies before decides. `--lists 76 --commands 0..900 --step 8` goes into one list | +| `--diverge 10 --lists 76 --draws ` | each draw of the pipelines named, alone, this often: how many outcomes, and what it reads | +| `--watch ::` | which lists (with `--lists`: commands) change those words | +| `--slots :` | the heap slots its constants name | +| `--check-written` | that everything the frame changes is put back | +| `--dump ` | the DXIL of the pipelines named, in `shaders` | + +The `--diverge` family runs the recorded copies without the merge. + ## Limits - Not recorded, but reported when used: reserved (tiled) resources, bundles, From f669746e67c5b79e6cceb3bd9ee084e349e05b77 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 21:37:54 -0600 Subject: [PATCH 162/445] The hash passes over copies in the card's memory walk a piece with 64 threads Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 94 +++++++++++++++++++++--------- crates/victory-gpu/src/indirect.rs | 72 +++++++++++++++++++++-- 2 files changed, 135 insertions(+), 31 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4ae7669..ba0c44f 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1527,11 +1527,17 @@ unsafe impl Send for CardWork {} static CARD_WORK: Mutex> = Mutex::new(None); /// The compare of a declared range of a copy in the card's memory with -/// its bytes from before, one thread per 64 KiB piece (cut at multiples of +/// its bytes from before, one group per 64 KiB piece (cut at multiples of /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs` /// gets a dword per piece, 1 where a byte differs. The offsets are widened /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a /// byte just outside the range costs a fetch that finds nothing. +/// +/// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and +/// one of them hashes their 64 hashes: 64 steps after one another. One thread +/// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's +/// 82 on the card (capture replay1, 405 of them), most of it waiting for +/// those steps. pub(crate) const CARD_COMPARE: &str = r#" #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)" cbuffer Span : register(b0) { @@ -1547,22 +1553,31 @@ ByteAddressBuffer now : register(t0); // last sent up (or hashed whole, the first time). RWByteAddressBuffer hashes : register(u0); RWByteAddressBuffer differs : register(u1); +groupshared uint4 parts[64]; [RootSignature(RS)] [numthreads(64, 1, 1)] -void main(uint3 id : SV_DispatchThreadID) { - if (id.x >= pieces) return; +void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) { uint piece = first + id.x; uint lo = piece * 65536u; lo = lo > skew ? lo - skew : 0u; uint hi = min((piece + 1u) * 65536u - skew, size); lo = lo & ~15u; hi = (hi + 15u) & ~15u; - uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu); + uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread; [loop] - for (uint at = lo; at < hi; at += 16u) { + for (uint at = lo + thread * 16u; at < hi; at += 1024u) { h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); h = h.yzwx ^ (h >> 15); } + parts[thread] = h; + GroupMemoryBarrierWithGroupSync(); + if (thread != 0u) return; + h = parts[0]; + [loop] + for (uint i = 1u; i < 64u; ++i) { + h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + } if (compare != 0u) { differs.Store(out_at + id.x * 4u, any(h != hashes.Load4(piece * 16u)) ? 1u : 0u); // With the copy-back on its own thread: the next compare of the @@ -1574,16 +1589,36 @@ void main(uint3 id : SV_DispatchThreadID) { } "#; +/// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from +/// dword `at` on (`mode` as the shader's `compare`): a group per piece, in +/// parts a dispatch can hold. +/// +/// # Safety +/// The list is open with the compare's root signature, pipeline and buffers +/// set, and the pieces lie in the buffer. +unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) { + const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; + let mut done = 0; + while done < span.pieces { + let n = (span.pieces - done).min(MOST); + let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode]; + // SAFETY: the caller's. + unsafe { + list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + list.Dispatch(n, 1, 1); + } + done += n; + } +} + /// Whether the pieces hashed again after ranges were sent up to a copy in /// the card's memory are hashed in runs of pieces that touch, each piece /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass /// per range sent up. /// /// These passes are ours, they run on the card before every submission's -/// lists, and no timing so far names them: each walks its 64 KiB pieces -/// 16 bytes at a time, 4,096 steps one after the other, so a pass takes -/// the time of one piece however few its pieces are. Run 102 sent up 514 -/// ranges a frame: 514 such passes. The same pieces are hashed either way; +/// lists: a pass takes the time of one piece however few its pieces are. +/// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way; /// a piece hashed when it need not be, or not hashed when it should, costs /// a fetch that finds nothing and loses no shader write. fn rehash_runs() -> bool { @@ -3263,8 +3298,12 @@ impl Host { (|| -> windows::core::Result<()> { allocator.Reset()?; list.Reset(allocator, None)?; + // Every copy first, then one barrier call, then every + // pass: a wait between each copy and its pass had the + // card do them one after the other. + let mut sent = Vec::new(); for (shadow, ranges) in &dirty { - let Some((staging, before, size)) = shadow.card_sides() else { + let Some((staging, before, _)) = shadow.card_sides() else { continue; }; for &(a, b) in ranges { @@ -3272,7 +3311,22 @@ 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); - let Some(before) = before else { + if before.is_some() && !ranges.is_empty() { + sent.push(transition( + &shadow.buffer, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )); + } + } + if !sent.is_empty() { + list.ResourceBarrier(&sent); + } + list.SetComputeRootSignature(&work.root); + list.SetPipelineState(&work.pso); + list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); + for (shadow, ranges) in &dirty { + let Some((_, Some(before), size)) = shadow.card_sides() else { continue; }; // No twin (it cost the card the copy's size again, @@ -3281,18 +3335,8 @@ impl Host { // hashed again, all of them the first time; the // compare after the lists hashes the declared // pieces and flags those whose hash is another. - if !ranges.is_empty() { - list.ResourceBarrier(&[transition( - &shadow.buffer, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - )]); - } - list.SetComputeRootSignature(&work.root); - list.SetPipelineState(&work.pso); list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); - list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); let runs: Vec = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) { vec![shadow.card_run(0, usize::MAX)] } else { @@ -3303,9 +3347,7 @@ impl Host { CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed); CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::(), Ordering::Relaxed); for run in runs { - let constants = [run.first, run.skew, size as u32, run.pieces, 0, 0]; - list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); - list.Dispatch(run.pieces.div_ceil(64), 1, 1); + card_pass(list, &run, size as u32, 0, 0); } } list.Close()?; @@ -3387,11 +3429,9 @@ impl Host { let Some((_, Some(before), size)) = r.shadow.card_sides() else { continue; }; - let constants = [r.span.first, r.span.skew, size as u32, r.span.pieces, r.at * 4, if flown { 2 } else { 1 }]; - list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); - list.Dispatch(r.span.pieces.div_ceil(64), 1, 1); + card_pass(list, &r.span, size as u32, r.at, if flown { 2 } else { 1 }); CARD_PASSES[2].fetch_add(1, Ordering::Relaxed); } list.Close()?; diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index af7f010..95b33a4 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -525,13 +525,22 @@ void main() { impl WarpHarness { fn new() -> Option { - // SAFETY: plain DXGI WARP query and D3D12 test harness setup. + Self::on(true) + } + + /// On the software adapter, or the first one (for measurements). + fn on(software: bool) -> Option { + // SAFETY: plain DXGI query and D3D12 test harness setup. unsafe { let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; - let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let adapter: IDXGIAdapter = if software { + factory.EnumWarpAdapter().ok()? + } else { + factory.EnumAdapters(0).ok()? + }; let desc = adapter.cast::().ok()?.GetDesc1().ok()?; - if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + if software != (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { return None; } let mut device: Option = None; @@ -760,7 +769,7 @@ void main() { warp.list.SetComputeRootShaderResourceView(1, now_gpu); warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu); warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu); - warp.list.Dispatch(PIECES.div_ceil(64), 1, 1); + warp.list.Dispatch(PIECES, 1, 1); } warp.submit_and_wait(); // SAFETY: as above. @@ -790,6 +799,61 @@ void main() { assert_eq!(run(&mut warp, 2), [0, 0, 0]); } + /// What the passes over copies in the card's memory cost on the card + /// (ignored: a measurement): rounds of a few passes of some pieces and a + /// wait, as a frame has them. `VICTORY_BENCH_CS=` times another + /// source of the shader. + #[test] + #[ignore] + fn card_compare_costs() { + let Some(mut gpu) = WarpHarness::on(false) else { + return; + }; + let other = std::env::var("VICTORY_BENCH_CS").ok().map(|f| std::fs::read_to_string(f).unwrap()); + let source: &'static str = other.map_or(crate::host::CARD_COMPARE, |s| Box::leak(s.into_boxed_str())); + let walked_alone = source.contains("SV_DispatchThreadID"); + let compare = compile_cs(&gpu.device, source).expect("the compare must compile"); + let now = gpu.default_uav(256 << 20); + let hashes = gpu.default_uav(64 << 10); + let differs = gpu.default_uav(64 << 10); + for (rounds, passes, pieces) in [(80u32, 5u32, 1u32), (80, 5, 5), (80, 5, 64), (80, 5, 500), (1, 1, 4000)] { + let mut best = f64::MAX; + for _ in 0..6 { + // SAFETY: our open list, live buffers, the compare's own + // root signature; the pieces lie in the buffers. + unsafe { + gpu.list.SetComputeRootSignature(&compare.root); + gpu.list.SetPipelineState(&compare.pso); + gpu.list.SetComputeRootShaderResourceView(1, now.GetGPUVirtualAddress()); + gpu.list.SetComputeRootUnorderedAccessView(2, hashes.GetGPUVirtualAddress()); + gpu.list.SetComputeRootUnorderedAccessView(3, differs.GetGPUVirtualAddress()); + for _ in 0..rounds { + for pass in 0..passes { + let first = if pieces * passes < 4096 { pass * pieces } else { 0 }; + let constants = [first, 0u32, 256 << 20, pieces, 0, 1]; + gpu.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + gpu.list.Dispatch(if walked_alone { pieces.div_ceil(64) } else { pieces }, 1, 1); + } + gpu.list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + ..Default::default() + }]); + } + } + let t = std::time::Instant::now(); + gpu.submit_and_wait(); + best = best.min(t.elapsed().as_secs_f64() * 1e3); + } + let mb = f64::from(rounds * passes * pieces) / 16.0; + println!("{rounds} rounds of {passes} passes of {pieces} pieces: {best:.2} ms ({mb:.0} MB, {:.0} GB/s)", mb / best / 1.024); + } + } + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { From cc03ecbc82c46679167b8b1dcbddde9a9a7a16bc Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 21:39:04 -0600 Subject: [PATCH 163/445] Reads of title memory under flights done on the card (VICTORY_CARD_STEPS) The submitting thread stood 25-30 ms a frame for one 480-byte constant buffer and one 20 KiB buffer copy a frame whose source lies in the title's 174 MB heap, which a pass of nearly every flight is declared to write whole (a root view has no size). With VICTORY_CARD_STEPS=1 such a constant buffer, with =2 such a copy too, is made on the card by a list of ours in front of the submission's lists, behind the flights; anything the argument does not hold for waits as before. Off by default. Diagnostics: the five waits for flights that cost most, every second, by what waited, why it was not done on the card, the declared write and the shaders that declare it. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 14 + crates/victory-gpu/src/draw.rs | 9 +- crates/victory-gpu/src/host.rs | 234 ++++-- crates/victory-gpu/src/host/card_steps.rs | 868 ++++++++++++++++++++++ crates/victory-gpu/src/memory.rs | 2 + crates/victory-gpu/src/shadow.rs | 5 + 6 files changed, 1084 insertions(+), 48 deletions(-) create mode 100644 crates/victory-gpu/src/host/card_steps.rs diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 8485014..f50a96f 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -168,6 +168,20 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { } } +/// Makes dynamic slot `index` of the host heap behind the title heap at +/// `heap`, if that heap still exists, the constant buffer view of `size` +/// bytes at `gpu`. +#[cfg(windows)] +pub(crate) fn constant_slot(heap: usize, index: u32, gpu: u64, size: u32) { + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + if heaps.iter().any(|&(_, _, h)| h == heap) + // SAFETY: registered heaps are live (removed when dropped). + && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get() + { + host.constant_at(index, gpu, size); + } +} + #[cfg(windows)] impl Drop for Heap { fn drop(&mut self) { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 7d290a3..6530abd 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1164,6 +1164,8 @@ impl State { let len = s.left(a).min(limit); s.refresh(list, a, len); if writes { + #[cfg(feature = "diagnostics")] + crate::host::wide_write(a, len, self.pipeline); s.gpu_writes(list, a, len); } }; @@ -2213,7 +2215,8 @@ impl State { host.make_null(index); continue; }; - list.defer_fill(to, address as *const u8, size as usize); + let slot = (std::ptr::from_ref(heap) as usize, index); + list.defer_constants(to, address as *const u8, size as usize, slot); host.constant_at(index, gpu, size); } Some(view) => { @@ -2395,7 +2398,7 @@ impl State { }; let (from, to, stride) = (from as usize, to as usize, stride as usize); let n = rects as usize; - list.defer_host(move || { + list.defer_host_read(from, n * 3 * stride, move || { // The vertices are read in place, at submission: no change // of mapping under the read (see // `crate::watch::title_memory_reading`). @@ -2763,6 +2766,8 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) { // A shader that cannot store to buffers leaves the range as // the title has it: nothing to find afterwards. if STORES.get() || !write_skip() { + #[cfg(feature = "diagnostics")] + crate::host::wide_write(address, len, 0); shadow.gpu_writes(list, address, len); } else { #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4ae7669..b2cbc74 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1642,16 +1642,19 @@ enum Step { /// A copy into title memory (destination, source, bytes): the title's /// buffer copies, which later refreshes must see. Copy(usize, usize, usize), - /// A copy of title memory into the list's own upload memory. - Fill(usize, usize, usize), + /// A copy of title memory into the list's own upload memory; if a + /// descriptor slot shows that memory and nothing else does (a constant + /// buffer of a table made for the draw), the title heap and the slot. + Fill(usize, usize, usize, Option<(usize, u32)>), /// Brings a range (address, bytes) of a buffer's host copy up to date: /// once per submission, whichever lists ask, until a `Copy` or `Run` /// intervenes. Refresh(std::sync::Arc, usize, usize), /// Work that may write title memory. Run(Box), - /// Work that writes host memory only. - Host(Box), + /// Work that writes host memory only, and the title memory it reads + /// (from, to; empty for none). + Host(Box, (usize, usize)), /// Shaders write a range (address, bytes) of a buffer's host copy. GpuWrite(std::sync::Arc, usize, usize), /// Brings a texture's staging buffer up to date: once per submission, @@ -2019,6 +2022,8 @@ struct Sent { number: u64, card: Option, back: Vec, + /// What was taken off it to be done on the card. + own: Option, /// Its bottom-of-pipe writes. writes: Vec<(usize, crate::queue::Written, usize)>, } @@ -2034,6 +2039,8 @@ struct Flight { order: Vec, card: Option, back: Vec, + /// The list of ours that ran ahead of them ([`card_steps`]). + own: Option, } /// One thing in the line of what waits for the card, in order. @@ -2067,6 +2074,8 @@ struct Line { /// With [`relay`]: the bottom-of-pipe writes of the flights being /// landed (taken out of `line`, not done yet), for [`late_met`]. in_hand: Vec<(usize, crate::queue::Written, usize)>, + /// With [`card_steps`]: what the flights being landed write. + landing: Vec, } // SAFETY: D3D12 objects (free-threaded) and host lists nothing records @@ -2082,6 +2091,7 @@ static LINE: Mutex = Mutex::new(Line { poke: false, landed: Vec::new(), in_hand: Vec::new(), + landing: Vec::new(), }); /// Told when a flight joins [`LINE`] or it is poked. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new(); @@ -2152,14 +2162,14 @@ fn flying() -> bool { /// runs steps of ours that may read or write it anywhere; what the /// flights' shaders write is not there yet. fn late_blocked(runs: &[&HostList]) -> Option { - let written = { + let (written, copies) = { let line = line(); if line.written.is_empty() { return None; } - line.written.clone() + (line.written.clone(), card_steps::copies(&line)) }; - blocked_by(&written, runs, true) + blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ)) } /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for @@ -2188,48 +2198,131 @@ fn fill_is_titles(src: usize, len: usize) -> bool { on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600)) } -/// Diagnostics: the reads that made a submission wait for flights: what -/// kind, where, how much, and the declared write it lies in; how often and -/// how long the wait was. +/// Diagnostics: the waits for flights, by what waited, why it was not done +/// on the card ([`card_steps`]), its bytes, and the declared write it lies +/// in (start, bytes). #[cfg(feature = "diagnostics")] -type Blame = std::collections::HashMap<(&'static str, usize, usize, usize, usize), (u64, u64)>; +type Blamed = (&'static str, &'static str, usize, usize, usize); +/// How often and how long, and the address the last one read. #[cfg(feature = "diagnostics")] -static BLAME: Mutex> = Mutex::new(None); +static BLAME: Mutex>> = Mutex::new(None); +/// What the wait that comes next is for, and why not on the card. #[cfg(feature = "diagnostics")] -static BLAMED: Mutex> = Mutex::new(None); +static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, "")); + +/// Diagnostics: shader writes declared over a megabyte or more: the range +/// (from, to) and what declares it ([`wide_write`]): how often, and its +/// shaders. +#[cfg(feature = "diagnostics")] +static WIDE_WRITES: Mutex>> = Mutex::new(None); + +/// Diagnostics: a draw or dispatch declares that it writes `len` bytes at +/// `address`, through a root view of `pipeline`, a view in a table (0) or a +/// raw address (1). +#[cfg(feature = "diagnostics")] +pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) { + if len < 1 << 20 { + return; + } + let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()); + let e = all + .get_or_insert_with(Default::default) + .entry((address as usize, (address + len) as usize, pipeline)) + .or_insert_with(|| { + let shaders = match pipeline { + 0 => "a view in a table".into(), + 1 => "a raw address".into(), + p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| { + p.stages.iter().map(|s| s.shader.hash.to_string()).collect::>().join("+") + }), + }; + (0, shaders) + }); + e.0 += 1; +} #[cfg(feature = "diagnostics")] fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) { let i = written.partition_point(|r| r.1 <= at); let (from, to) = written.get(i).copied().unwrap_or((0, 0)); - *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = Some((kind, at, len, from, to - from)); + let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner()); + let why = blamed.1; + blamed.0 = Some(((kind, why, len, from, to - from), at)); } -/// The wait for what [`blame`] last named took `us`. +/// Why [`card_steps`] left the submission to the wait that comes next. #[cfg(feature = "diagnostics")] -fn blamed(us: u64) { - if let Some(key) = BLAMED.lock().unwrap_or_else(|e| e.into_inner()).take() { - let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner()); - let e = all.get_or_insert_with(Default::default).entry(key).or_insert((0, 0)); - e.0 += 1; - e.1 += us; - } +fn refused(why: &'static str) { + *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why); } +/// The wait for what [`blame`] last named, or a wait of another reason than +/// title memory read, took `us`. +#[cfg(feature = "diagnostics")] +fn blamed(why: usize, us: u64) { + let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, "")); + let (key, at) = match (why, named) { + (WHY_READ, Some(named)) => named, + (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0), + _ => { + let kind = match why { + WHY_SYNC => "a synchronous submission, a present or the sweep", + WHY_VALUE => "a memory value", + WHY_STALE => "title memory changed under shader writes", + WHY_RUN => "a step of ours", + WHY_MOST => "lists in the air", + WHY_FENCE => "a blocking fence wait", + _ => "another reason", + }; + ((kind, "", 0, 0, 0), 0) + } + }; + let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner()); + let e = all.get_or_insert_with(Default::default).entry(key).or_default(); + *e = (e.0 + 1, e.1 + us, at); +} + +/// For the frame-rate line: the five that waited longest. #[cfg(feature = "diagnostics")] fn log_blame(frames: f64) { let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default(); + let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default(); let mut all: Vec<_> = all.into_iter().collect(); - all.sort_unstable_by_key(|(_, (_, us))| std::cmp::Reverse(*us)); - for ((kind, at, len, from, size), (n, us)) in all.into_iter().take(8) { + all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us)); + for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) { + // The passes that declare it written, the ones that do so most. + let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new(); + for ((a, b, _), (n, shaders)) in &wide { + if *a < at + len && at < *b { + *passes.entry(shaders).or_default() += n; + } + } + let mut passes: Vec<(&str, u64)> = passes.into_iter().collect(); + passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1)); + let passes: Vec = + passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect(); tracing::info!( - "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} {at:#x}+{len:#x}, in shader writes declared over {from:#x}+{size:#x}", + "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \ + over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}", us as f64 / 1e3 / frames, - n as f64 / frames + n as f64 / frames, + passes.join(", "), + if why.is_empty() { "" } else { "; not done on the card: " }, ); } } +/// Whether flights that write `written` stop a read of `len` bytes at `src`. +fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool { + touches(written, src, src + len) && !fill_is_titles(src, len) +} + +/// Whether they stop a title buffer copy, and if so whether by its source. +fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option { + let read = read_blocked(written, src, len); + (read || touches(written, dst, dst + len)).then_some(read) +} + /// [`late_blocked`] against `written`, the title memory flights' shaders /// may write (in order, joined); `count` whether the kind of read is /// counted for the frame line. @@ -2241,12 +2334,11 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op for step in &list.deferred().copies { match step { &Step::Copy(dst, src, len) => { - let read = touches(written, src, src + len) && !fill_is_titles(src, len); - if read || touches(written, dst, dst + len) { + if let Some(_read) = copy_blocked(written, dst, src, len) { if count { LATE_STATS[15].fetch_add(1, Ordering::Relaxed); #[cfg(feature = "diagnostics")] - if read { + if _read { blame("a buffer copy's source", written, src, len); } else { blame("a buffer copy's destination", written, dst, len); @@ -2255,8 +2347,8 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op return Some(WHY_READ); } } - &Step::Fill(_, src, len) => { - if touches(written, src, src + len) && !fill_is_titles(src, len) { + &Step::Fill(_, src, len, _) => { + if read_blocked(written, src, len) { if count { LATE_STATS[16].fetch_add(1, Ordering::Relaxed); #[cfg(feature = "diagnostics")] @@ -2277,7 +2369,7 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op } } Step::Run(_) => return Some(WHY_RUN), - Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(_) => {} + Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {} } } } @@ -2517,7 +2609,7 @@ fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) { LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed); SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed); #[cfg(feature = "diagnostics")] - blamed(us); + blamed(why, us); } /// What the thread that lands flights fetches card copies' pieces with @@ -2582,6 +2674,9 @@ fn relay_worker() { _ => None, }) .collect(); + if card_steps::stage() > 0 { + line.landing = card_steps::writers(&items); + } break Ok(items); } }; @@ -2711,6 +2806,9 @@ fn late_line(frames: f64) { r[4] / 1000.0, ); } + card_steps::log(frames); + #[cfg(feature = "diagnostics")] + log_blame(frames); if late_exact() { let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames); tracing::info!( @@ -2721,6 +2819,8 @@ fn late_line(frames: f64) { } } +mod card_steps; + #[cfg(test)] mod late_tests { use super::{continues, join_ranges, touches}; @@ -3691,6 +3791,9 @@ impl Host { if let Some(card) = flight.card { self.card_done(card); } + if let Some(own) = flight.own { + own.landed(); + } landed.push((flight.lists, flight.order)); } Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), @@ -3713,10 +3816,12 @@ impl Host { poke, landed: kept, in_hand, + landing, .. } = &mut *line; kept.extend(landed); in_hand.clear(); + landing.clear(); // What is still in the air, from the flights that are. written.clear(); *lists = 0; @@ -3909,6 +4014,7 @@ impl Host { order, card: sent.card, back: sent.back, + own: sent.own, })); items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); *flying >= late_most() @@ -3953,6 +4059,7 @@ impl Host { order: Vec::new(), card: sent.card, back: sent.back, + own: sent.own, })); items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); } @@ -4133,17 +4240,32 @@ impl Host { // Flights in the air ([`late`]): a submission that is waited for // settles them first, one sent ahead only if preparing it reads // what they write. + // Or the reads are done on the card, behind the flights. + let own = if late { self.card_steps(runs) } else { None }; if !late { self.settle(&mut submitted, WHY_SYNC); - } else if let Some(why) = late_blocked(runs) { + } else if own.is_none() + && let Some(why) = late_blocked(runs) + { if relay_exact() && why == WHY_READ { // Only until the flights that may write what is read have // landed: their copy-back's end, not the card's other work. - relay_wait(why, |line| blocked_by(&line.written, runs, false).is_none()); + relay_wait(why, |line| { + blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs) + }); } else { self.settle(&mut submitted, why); } } + // That list runs first, and is one of the submission's from here on. + let with: Vec<&HostList>; + let runs = match &own { + Some(own) => { + with = std::iter::once(own.list()).chain(runs.iter().copied()).collect(); + &with[..] + } + None => runs, + }; let behind = late && flying(); // Before this submission counts as started: what the sweep lets go // of is named by no list, and nothing runs now (behind flights the @@ -4214,7 +4336,7 @@ impl Host { settled += settling.elapsed(); } for list in runs { - list.run_deferred(&mut batch); + list.run_deferred(&mut batch, |i| own.as_ref().is_some_and(|own| own.takes(list, i))); firsts.push(lists.len()); if let Some(prelude) = list.prelude() { lists.push(Some(prelude)); @@ -4268,6 +4390,7 @@ impl Host { number: this_submission, card, back, + own, writes, }; working(was_working); @@ -5152,7 +5275,15 @@ impl HostList { pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) { self.deferred() .copies - .push(Step::Fill(dst as usize, src as usize, len)); + .push(Step::Fill(dst as usize, src as usize, len, None)); + } + + /// As [`HostList::defer_fill`], for upload memory that only `slot` (a + /// title heap's address, and the slot) shows. + pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) { + self.deferred() + .copies + .push(Step::Fill(dst as usize, src as usize, len, Some(slot))); } /// Brings `[address, address + len)` of a buffer's host copy up to date @@ -5272,7 +5403,7 @@ impl HostList { // list's last run (mesh dispatches: the largest group count // asked for, the groups asked in all; with the card's copy, as // the list's end copied them here): taken, then zeroed. - deferred.copies.push(Step::Host(Box::new(move || unsafe { + let notes = Box::new(move || unsafe { let words = at as *mut u32; let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile()); MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed); @@ -5280,7 +5411,8 @@ impl HostList { for k in 0..3 { words.add(k).write_volatile(0); } - }))); + }); + deferred.copies.push(Step::Host(notes, (0, 0))); drop(deferred); if let Some(card) = card { self.zero_card_budget(card); @@ -5456,7 +5588,13 @@ impl HostList { /// As [`HostList::defer`], for work that writes only host memory. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) { - self.deferred().copies.push(Step::Host(Box::new(work))); + self.deferred().copies.push(Step::Host(Box::new(work), (0, 0))); + } + + /// As [`HostList::defer_host`], for work that reads `len` bytes of title + /// memory at `from`. + pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) { + self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len))); } /// Brings a texture's staging buffer up to date when the list is @@ -5467,11 +5605,16 @@ impl HostList { /// Runs the list's submission-time steps; refreshes go into `batch` /// (the title's big buffers, a 174 MB one among them, are read by most - /// lists of a submission, through many ranges). - fn run_deferred(&self, batch: &mut Batch) { + /// lists of a submission, through many ranges). Copies and fills that + /// `taken` names (by their place) are left out: they are done on the + /// card ([`card_steps`]). + fn run_deferred(&self, batch: &mut Batch, taken: impl Fn(usize) -> bool) { #[cfg(feature = "diagnostics")] use crate::copystat::{C, add}; - for step in &self.deferred().copies { + for (i, step) in self.deferred().copies.iter().enumerate() { + if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) { + continue; + } let started = std::time::Instant::now(); let copied = match step { &Step::Copy(dst, src, len) => { @@ -5486,7 +5629,7 @@ impl HostList { crate::watch::wrote(dst, len); len } - &Step::Fill(dst, src, len) => { + &Step::Fill(dst, src, len, _) => { #[cfg(feature = "diagnostics")] { add(C::Copies, 1); @@ -5504,7 +5647,7 @@ impl HostList { batch.add(shadow, *address, *len); continue; } - Step::Run(work) | Step::Host(work) => { + Step::Run(work) | Step::Host(work, _) => { if matches!(step, Step::Run(_)) { batch.title_written(); } @@ -6254,7 +6397,6 @@ impl Meter { ); #[cfg(feature = "diagnostics")] { - log_blame(frames); let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames); tracing::info!( "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps", diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs new file mode 100644 index 0000000..6c1f622 --- /dev/null +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -0,0 +1,868 @@ +//! Steps of a submission that read title memory flights in the air may +//! still write, done on the card in the flights' order instead of on the +//! CPU after a wait for them (`VICTORY_CARD_STEPS`, see [`stage`]). + +use std::sync::Arc; + +use super::*; +use crate::shadow::Shadow; + +/// The stage (`VICTORY_CARD_STEPS`; off by default): `1` constant buffers +/// of descriptor tables (`Step::Fill` with a slot of its own), `2` the +/// title's buffer copies (`Step::Copy`) too. Only with the relay's second +/// stage (`relay_exact`). +/// +/// Why: a root view has no size, so a pass that writes through one into the +/// title's 174 MB heap is declared to write all that is left of it, and +/// some pass of every flight does. The title's ring of constants lies in +/// the same heap. One constant buffer of 480 bytes and one copy of 20 KiB a +/// frame, at a new place of the ring each time, waited for nearly +/// everything in the air: 25-30 ms of a 105 ms frame, the submitting thread +/// standing (run record-1; with `VICTORY_FILL_TITLE=1` in run relaycopy-1 +/// the copy alone took over the wait). +/// +/// What is done: a list of ours goes to the card in front of the +/// submission's lists, in the same call. It copies the bytes read from the +/// host copy that the flights write into a buffer of ours, and from there +/// to the destination's host copy (a copy), or the fill's descriptor slot +/// is pointed at that buffer (a fill; the slot is the fill's alone, the +/// root signatures say such descriptors are volatile, and the list that +/// names it has not gone to the card). +/// +/// Why that is the value the CPU would have read after the wait. After the +/// wait title memory holds, for every byte read, what the title wrote, or +/// what the last of the flights that wrote it wrote (the landings put it +/// there, in order). The host copy on the card holds the same when our list +/// runs: every flight that may write one of these bytes writes this same +/// host copy ([`holder`]: a write through another host copy, a read-back +/// or a value written behind a flight there, and the old wait is taken), +/// they are all ahead of our list on the queue, and the title's own bytes +/// are brought up to date by a refresh step of our list, which is prepared +/// like any other list's (also under flights' declared writes: +/// `stale_under_flights`, which settles if it cannot). Nothing of this +/// submission writes these bytes earlier than our list: the steps are done +/// in front of all its lists in either case, and [`plan`] refuses when +/// another step of the submission writes what is read. Every draw that +/// reads a buffer view of the heap relies on the same refresh and the same +/// order; what is new is only that a constant buffer and a copy do too. +/// Where a page is not mapped the host copy may hold other bytes than the +/// CPU's copy would have left: refused. +/// +/// For a copy's destination our list declares a shader write, exactly the +/// bytes copied, after a refresh of them: from there on it is what any +/// shader's write is. The relay compares, and puts what changed into title +/// memory before the title is told anything of this flight (its +/// bottom-of-pipe writes and fences come after, in order); CPU steps of +/// later submissions that read it find it declared and wait, or are done +/// here. Refused: another step of the submission reads or writes the +/// destination on the CPU, or a refresh brings another host copy of it up +/// to date ([`plan`], [`elsewhere`]). While such a copy is in the air a +/// submission that refreshes another host copy of its destination, or +/// reads it in a step that is not checked otherwise, waits for it +/// ([`copied_read`]); with the copy done on the CPU it was there at once. +/// +/// What stage 2 does not see: code of ours that reads title memory away +/// from a submission's steps (the pass over textures picked by index, while +/// a list is recorded). With the CPU's copy such a read of the destination +/// found the bytes at once; now it finds them when the flight has landed. +/// The landing tells the guards (`crate::watch::landing`), so a texture +/// made from older bytes is made again. This is why stage 2 is its own. +pub(super) fn stage() -> u32 { + static STAGE: OnceLock = OnceLock::new(); + *STAGE.get_or_init(|| match std::env::var("VICTORY_CARD_STEPS").ok().as_deref() { + Some("1") => 1, + Some("2") => 2, + _ => 0, + }) +} + +/// The bytes of our buffer between reading and writing: what one submission +/// may do this way. +const BETWEEN: u64 = 1 << 20; + +/// Title memory something in the air writes: the host copy it goes through +/// (`None`: none, the bytes reach title memory when the flight lands), from, +/// to, and whether it is the destination of a copy done here. +pub(super) struct Writer { + shadow: Option>, + from: usize, + to: usize, + copy: bool, +} + +/// What `items` of the line write. +pub(super) fn writers(items: &[Late]) -> Vec { + let mut out = Vec::new(); + for item in items { + match item { + Late::Run(flight) => { + for (shadow, ranges) in &flight.back { + out.extend(ranges.iter().map(|&(from, to)| Writer { + shadow: Some(shadow.clone()), + from, + to, + copy: false, + })); + } + for &i in &flight.order { + for &(_, at, [row, rows, pitch]) in &flight.lists[i].host().deferred().backs { + out.push(Writer { + shadow: None, + from: at, + to: at + rows.saturating_sub(1) * pitch + row, + copy: false, + }); + } + } + out.extend(flight.own.iter().flat_map(Taken::copied)); + } + Late::Write(at, _, bytes) => out.push(Writer { + shadow: None, + from: *at, + to: *at + *bytes, + copy: false, + }), + Late::Signal(..) => {} + } + } + out +} + +/// The destinations of copies done here that have not landed. +pub(super) fn copies(line: &Line) -> Vec { + if stage() < 2 { + return Vec::new(); + } + let flying = line.line.iter().filter_map(|l| match l { + Late::Run(flight) => flight.own.as_ref(), + _ => None, + }); + let landing = line.landing.iter().filter(|w| w.copy).map(|w| Writer { + shadow: w.shadow.clone(), + ..*w + }); + flying.flat_map(Taken::copied).chain(landing).collect() +} + +/// Whether `runs` refresh another host copy of a destination in `copies`, +/// or read it in a step that flights are not waited for otherwise +/// (`Step::Host`): that reads title memory, where the copy is not yet. +pub(super) fn copied_read(copies: &[Writer], runs: &[&HostList]) -> bool { + if copies.is_empty() { + return false; + } + runs.iter().any(|list| { + list.deferred().copies.iter().any(|step| match step { + Step::Refresh(shadow, at, len) => copies + .iter() + .any(|w| w.from < *at + *len && *at < w.to && w.shadow.as_ref().is_none_or(|s| !Arc::ptr_eq(s, shadow))), + Step::Host(_, (from, to)) => copies.iter().any(|w| w.from < *to && *from < w.to), + _ => false, + }) + }) +} + +/// What a step of a submission does to title memory, as the plan sees it. +/// `asked`: flights in the air stop it from being done on the CPU now. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Does { + Copy { dst: usize, src: usize, len: usize, asked: bool }, + Fill { src: usize, len: usize, asked: bool, slot: Option<(usize, u32)> }, + /// Another read on the CPU (a texture, vertices expanded). + Read { from: usize, to: usize, asked: bool }, + /// A refresh of a host copy (named by its address). + Refresh { shadow: usize, from: usize, to: usize }, + /// Anything, anywhere. + Run, +} + +fn meet(a: (usize, usize), b: (usize, usize)) -> bool { + a.0 < b.1 && b.0 < a.1 +} + +/// The steps of `does` (by place) to be done on the card: all that are +/// asked for, or why not. Our list does them all in front of the +/// submission's, every read before every write, so that is right only if no +/// step, asked for or not, writes what one of them reads or writes, and no +/// CPU step reads what one of them writes. +fn plan(does: &[Does], stage: u32) -> Result, &'static str> { + let mut asked = Vec::new(); + for (i, d) in does.iter().enumerate() { + match *d { + Does::Run => return Err("a step of ours runs"), + Does::Read { asked: true, .. } => return Err("a texture reads it"), + Does::Fill { asked: true, slot: None, .. } => return Err("a fill without a descriptor slot of its own"), + Does::Copy { asked: true, .. } if stage < 2 => return Err("a buffer copy (VICTORY_CARD_STEPS=2 does it on the card)"), + Does::Copy { asked: true, .. } | Does::Fill { asked: true, .. } => asked.push(i), + _ => {} + } + } + for &i in &asked { + let (src, dst) = match does[i] { + Does::Copy { dst, src, len, .. } => ((src, src + len), Some((dst, dst + len))), + Does::Fill { src, len, .. } => ((src, src + len), None), + _ => continue, + }; + for (k, d) in does.iter().enumerate() { + let (read, written) = match *d { + Does::Copy { dst, src, len, .. } => (Some((src, src + len)), Some((dst, dst + len))), + Does::Fill { src, len, .. } => (Some((src, src + len)), None), + Does::Read { from, to, .. } => (Some((from, to)), None), + Does::Refresh { .. } | Does::Run => (None, None), + }; + if written.is_some_and(|w| meet(w, src)) { + return Err("a copy of the submission writes what it reads"); + } + let Some(dst) = dst else { + continue; + }; + if k != i && written.is_some_and(|w| meet(w, dst)) { + return Err("another copy of the submission writes what it writes"); + } + if read.is_some_and(|r| meet(r, dst)) { + return Err("a step of the submission reads what it writes"); + } + } + } + Ok(asked) +} + +/// Whether a refresh of `does` brings a host copy other than `shadow` up to +/// date in `[from, to)`. +fn elsewhere(does: &[Does], shadow: usize, from: usize, to: usize) -> bool { + does.iter().any(|d| match *d { + Does::Refresh { shadow: s, from: a, to: b } => s != shadow && meet((a, b), (from, to)), + _ => false, + }) +} + +/// The host copy that holds `[from, to)` on the card once what `writers` +/// write is there: the one they all write it through, or without any the +/// one shaders would be given. +fn holder(writers: &[Writer], from: usize, to: usize) -> Result, &'static str> { + let mut found: Option<&Arc> = None; + for w in writers.iter().filter(|w| meet((w.from, w.to), (from, to))) { + match (&w.shadow, found) { + (None, _) => return Err("a read-back or a value behind a flight is written there"), + (Some(s), Some(f)) if !Arc::ptr_eq(s, f) => return Err("flights write it through two host copies"), + (Some(s), _) => found = Some(s), + } + } + let shadow = match found { + Some(s) => s.clone(), + None => crate::shadow::find(from as u64, (to - from) as u64).ok_or("no host copy of it")?, + }; + let (start, len) = shadow.span(); + if shadow.in_place() || (from as u64) < start || to as u64 > start + len { + return Err("no host copy holds all of it"); + } + Ok(shadow) +} + +/// Whether every page of `[from, to)` can be read (through the kernel: +/// asking Windows walks the page tables, milliseconds in the title's heap). +fn mapped(from: usize, to: usize) -> bool { + let mut bytes = vec![0u8; to - from]; + read_into(from as *const u8, &mut bytes) +} + +/// A step done on the card. +struct Op { + from: (Arc, usize), + len: usize, + /// Its place in the buffer between. + at: u64, + to: To, +} + +enum To { + /// A host copy, and the title address. + Copy(Arc, usize), + /// A descriptor slot (title heap, slot). + Slot(usize, u32), +} + +/// Records what [`stage`] describes into `list` (open): `reads` are copied +/// into `between` (source, offset in it, offset in `between`, bytes), then +/// `writes` out of it (destination, offset in it, offset in `between`, +/// bytes). `between` is left readable as constants, the others in the +/// common state, as the submission's lists expect them. +fn record( + list: &ID3D12GraphicsCommandList, + between: &ID3D12Resource, + reads: &[(&ID3D12Resource, u64, u64, u64)], + writes: &[(&ID3D12Resource, u64, u64, u64)], +) { + let common = D3D12_RESOURCE_STATE_COMMON; + let (source, dest) = (D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST); + let mut sources: Vec<&ID3D12Resource> = Vec::new(); + let mut dests: Vec<&ID3D12Resource> = Vec::new(); + for (all, list) in [(reads, &mut sources), (writes, &mut dests)] { + for &(buffer, ..) in all { + if !list.iter().any(|b| b.as_raw() == buffer.as_raw()) { + list.push(buffer); + } + } + } + let both = |b: &ID3D12Resource| dests.iter().any(|d| d.as_raw() == b.as_raw()); + let mut barriers = vec![transition(between, dest, source | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER)]; + barriers.extend(sources.iter().map(|b| transition(b, source, if both(b) { dest } else { common }))); + let done: Vec = dests.iter().map(|b| transition(b, dest, common)).collect(); + // SAFETY: an open list; live buffers, and the callers' ranges lie in + // them. The buffers start in the common state (the list is the first of + // its call) and are promoted by their first use. + unsafe { + // What earlier lists' shaders wrote, first. + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + for &(buffer, offset, at, len) in reads { + list.CopyBufferRegion(between, at, buffer, offset, len); + } + list.ResourceBarrier(&barriers); + for &(buffer, offset, at, len) in writes { + list.CopyBufferRegion(buffer, offset, between, at, len); + } + if !done.is_empty() { + list.ResourceBarrier(&done); + } + } +} + +/// The list in front of a submission's, and its buffer ([`BETWEEN`] bytes). +struct Own { + list: HostList, + between: ID3D12Resource, +} + +// SAFETY: D3D12 objects are free-threaded, and the list is touched by one +// thread at a time (the submitting one until it is sent, then the one that +// lands it, then nobody until it is taken out of `POOL`). +unsafe impl Send for Own {} + +/// Those that have landed: closed, their steps dropped. +static POOL: Mutex> = Mutex::new(Vec::new()); + +/// Since the last frame-rate line: fills and copies done on the card, their +/// bytes, and submissions that waited instead, refused by a check. +static DONE: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// What [`Host::card_steps`] took off a submission: the list that does it, +/// for the submission to run first, and the steps the CPU leaves out (their +/// list by address, their place in it). +pub(super) struct Taken { + own: Own, + steps: std::collections::HashSet<(usize, usize)>, + copied: Vec<(Arc, usize, usize)>, +} + +impl Taken { + pub(super) fn list(&self) -> &HostList { + &self.own.list + } + + /// Whether step `i` of `list` is done by this. + pub(super) fn takes(&self, list: &HostList, i: usize) -> bool { + self.steps.contains(&(std::ptr::from_ref(list) as usize, i)) + } + + fn copied(&self) -> impl Iterator { + self.copied.iter().map(|(shadow, from, to)| Writer { + shadow: Some(shadow.clone()), + from: *from, + to: *to, + copy: true, + }) + } + + /// The submission has run and landed: the list and its buffer are free. + pub(super) fn landed(self) { + // The host copies its steps held go; its commands stay until the + // next use resets it. + drop(std::mem::take(&mut *self.own.list.deferred())); + POOL.lock().unwrap_or_else(|e| e.into_inner()).push(self.own); + } +} + +impl Host { + /// With flights in the air: if what keeps `runs` from being prepared + /// now is reads of title memory that can all be done on the card + /// ([`stage`]), the list that does them. `None` if nothing is in the + /// way or the old wait is due. Under the submission lock. + pub(super) fn card_steps(&self, runs: &[&HostList]) -> Option { + if stage() == 0 || !relay_exact() { + return None; + } + let (written, copies) = { + let line = line(); + if line.written.is_empty() { + return None; + } + (line.written.clone(), copies(&line)) + }; + blocked_by(&written, runs, false)?; + let taken = if copied_read(&copies, runs) { + Err("a copy done on the card is read through another host copy") + } else { + self.take_steps(&written, runs) + }; + match taken { + Ok(taken) => taken, + Err(why) => { + DONE[3].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + refused(why); + let _ = why; + None + } + } + } + + 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, slot) => Does::Fill { + src, + len, + asked: read_blocked(written, src, len), + slot, + }, + 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::GpuWrite(..) | Step::Host(..) => continue, + }); + steps.push((std::ptr::from_ref::(list) as usize, i)); + } + } + let chosen = plan(&does, stage())?; + if chosen.is_empty() { + return Ok(None); + } + let writers = { + let line = line(); + let mut all = writers(&line.line); + all.extend(line.landing.iter().map(|w| Writer { + shadow: w.shadow.clone(), + ..*w + })); + all + }; + let mut ops: Vec = Vec::with_capacity(chosen.len()); + let mut at = 0u64; + for &i in &chosen { + let (src, len) = match does[i] { + Does::Copy { src, len, .. } | Does::Fill { src, len, .. } => (src, len), + _ => continue, + }; + if len == 0 { + return Err("nothing to read"); + } + if at + len as u64 > BETWEEN { + return Err("too much at once"); + } + let from = holder(&writers, src, src + len)?; + if !mapped(src, src + len) { + return Err("not all of what it reads is mapped"); + } + let to = match does[i] { + Does::Copy { dst, .. } => { + let to = holder(&writers, dst, dst + len)?; + if elsewhere(&does, Arc::as_ptr(&to) as usize, dst, dst + len) { + return Err("another host copy of what it writes is read"); + } + if !mapped(dst, dst + len) { + return Err("not all of what it writes is mapped"); + } + To::Copy(to, dst) + } + Does::Fill { slot: Some((heap, index)), .. } => To::Slot(heap, index), + _ => continue, + }; + ops.push(Op { + from: (from, src), + len, + at, + to, + }); + at = (at + len as u64).next_multiple_of(256); + } + let Some(own) = self.own_list() else { + return Err("no host list or buffer for it"); + }; + let mut reads = Vec::new(); + let mut writes = Vec::new(); + let mut copied = Vec::new(); + // First every refresh, then the write: the bytes compared with are + // the title's. + for op in &ops { + op.from.0.refresh(&own.list, op.from.1 as u64, op.len as u64); + reads.push((&op.from.0.buffer, op.from.0.offset(op.from.1 as u64), op.at, op.len as u64)); + if let To::Copy(to, dst) = &op.to { + to.refresh(&own.list, *dst as u64, op.len as u64); + writes.push((&to.buffer, to.offset(*dst as u64), op.at, op.len as u64)); + } + } + for op in &ops { + if let To::Copy(to, dst) = &op.to { + to.gpu_writes(&own.list, *dst as u64, op.len as u64); + copied.push((to.clone(), *dst, *dst + op.len)); + } + } + #[cfg(feature = "diagnostics")] + own.list.note_op(|| format!("{} copies of title memory done on the card, {at} bytes (VICTORY_CARD_STEPS)", ops.len())); + record(&own.list.list, &own.between, &reads, &writes); + own.list.close(); + // SAFETY: a live buffer. + let gpu = unsafe { own.between.GetGPUVirtualAddress() }; + for op in &ops { + DONE[2].fetch_add(op.len as u64, Ordering::Relaxed); + match &op.to { + To::Slot(heap, index) => { + DONE[0].fetch_add(1, Ordering::Relaxed); + // (A heap that is gone: nothing can read the slot.) + crate::descriptor::constant_slot(*heap, *index, gpu + op.at, op.len as u32); + } + To::Copy(..) => { + DONE[1].fetch_add(1, Ordering::Relaxed); + } + } + #[cfg(feature = "diagnostics")] + noted(op); + } + Ok(Some(Taken { + own, + steps: chosen.iter().map(|&i| steps[i]).collect(), + copied, + })) + } + + /// A list of ours open for recording, and its buffer. + fn own_list(&self) -> Option { + let pooled = POOL.lock().unwrap_or_else(|e| e.into_inner()).pop(); + if let Some(own) = pooled { + own.list.reset(); + return Some(own); + } + let between = self.uav_buffer(BETWEEN)?; + name(&between, || "copies of title memory on the card".into()); + let list = self.new_list().ok()?; + Some(Own { list, between }) + } +} + +/// Diagnostics: the copies and fills done on the card since the last +/// frame-rate line, by bytes, host copy read and host copy written (start +/// and length; zeros for a fill): how many, and the last title addresses. +#[cfg(feature = "diagnostics")] +type Noted = std::collections::HashMap<(usize, (u64, u64), (u64, u64)), (u64, usize, usize)>; +#[cfg(feature = "diagnostics")] +static NOTED: Mutex> = Mutex::new(None); + +#[cfg(feature = "diagnostics")] +fn noted(op: &Op) { + let (to, dst) = match &op.to { + To::Copy(to, dst) => (to.span(), *dst), + To::Slot(..) => ((0, 0), 0), + }; + let mut noted = NOTED.lock().unwrap_or_else(|e| e.into_inner()); + let e = noted.get_or_insert_with(Default::default).entry((op.len, op.from.0.span(), to)).or_default(); + *e = (e.0 + 1, op.from.1, dst); +} + +/// For the frame-rate line. +pub(super) fn log(frames: f64) { + if stage() == 0 { + return; + } + let d: Vec = DONE.iter().map(|d| d.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "steps done on the card instead of waiting for flights, per frame (VICTORY_CARD_STEPS={}): {:.2} fills, {:.2} buffer \ + copies, {:.1} KB; {:.2} submissions refused and waited", + stage(), + d[0], + d[1], + d[2] / 1024.0, + d[3], + ); + #[cfg(feature = "diagnostics")] + { + let noted = NOTED.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default(); + let mut noted: Vec<_> = noted.into_iter().collect(); + noted.sort_unstable_by_key(|(_, e)| std::cmp::Reverse(e.0)); + for ((len, from, to), (n, src, dst)) in noted.into_iter().take(5) { + let n = n as f64 / frames; + if to.1 == 0 { + tracing::info!("done on the card, per frame: {n:.2} fills of {len:#x} bytes from the host copy of {:#x}+{:#x} (last {src:#x})", from.0, from.1); + } else { + tracing::info!( + "done on the card, per frame: {n:.2} copies of {len:#x} bytes from the host copy of {:#x}+{:#x} (last {src:#x}) \ + to that of {:#x}+{:#x} (last {dst:#x})", + from.0, + from.1, + to.0, + to.1 + ); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn copy(dst: usize, src: usize, len: usize, asked: bool) -> Does { + Does::Copy { dst, src, len, asked } + } + + fn fill(src: usize, len: usize, asked: bool) -> Does { + Does::Fill { src, len, asked, slot: Some((1, 2)) } + } + + /// Only what is asked for is taken, all of it, and a step that stands + /// in none of their ways changes nothing. + #[test] + fn steps_apart_from_one_another_are_taken() { + let does = [ + copy(1000, 5000, 100, false), + fill(2000, 64, true), + Does::Refresh { shadow: 1, from: 0, to: 9000 }, + copy(3000, 6000, 100, true), + fill(1000, 64, false), + Does::Read { from: 3100, to: 4000, asked: false }, + ]; + assert_eq!(plan(&does, 2), Ok(vec![1, 3])); + // Two fills of the same bytes. + assert_eq!(plan(&[fill(0, 64, true), fill(32, 64, true)], 1), Ok(vec![0, 1])); + assert_eq!(plan(&[fill(0, 64, false)], 1), Ok(vec![])); + } + + /// Everything that could make the card's order another than the CPU's + /// refuses the lot, wherever in the submission it stands. + #[test] + fn steps_in_one_anothers_way_are_refused() { + let taken = copy(1000, 5000, 100, true); + let refused = |other: Does| { + assert!(plan(&[taken, other], 2).is_err(), "{other:?} after"); + assert!(plan(&[other, taken], 2).is_err(), "{other:?} before"); + }; + for asked in [false, true] { + // Writes what it reads. + refused(copy(5099, 9000, 1, asked)); + // Writes what it writes. + refused(copy(999, 9000, 2, asked)); + // Reads what it writes. + refused(copy(7000, 1050, 10, asked)); + refused(fill(1099, 64, asked)); + refused(Does::Read { from: 900, to: 1001, asked }); + } + refused(Does::Run); + // A texture that itself waits for flights; a fill with no slot. + refused(Does::Read { from: 1, to: 2, asked: true }); + refused(Does::Fill { src: 1, len: 1, asked: true, slot: None }); + // Into itself, and the same list twice. + assert!(plan(&[copy(1000, 1050, 100, true)], 2).is_err()); + assert!(plan(&[taken, taken], 2).is_err()); + // A fill of what a copy writes, and copies without stage 2. + assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 2).is_err()); + assert!(plan(&[taken], 1).is_err()); + // Ends that touch are apart. + assert!(plan(&[taken, copy(900, 9000, 100, false), copy(1100, 9000, 5, false), copy(4900, 9000, 100, false)], 2).is_ok()); + } + + #[test] + fn a_refresh_of_another_host_copy_is_seen() { + let does = [Does::Refresh { shadow: 7, from: 100, to: 200 }]; + assert!(!elsewhere(&does, 7, 100, 200)); + assert!(elsewhere(&does, 8, 199, 300)); + assert!(!elsewhere(&does, 8, 200, 300)); + } + + /// A value written behind a flight, or a read-back, is in no host copy + /// before it lands. + #[test] + fn what_no_host_copy_holds_is_refused() { + let writers = [Writer { shadow: None, from: 100, to: 108, copy: false }]; + assert!(holder(&writers, 104, 120).is_err()); + } + + /// Reads are all before writes, between two buffers and within one, and + /// the buffers are usable in the lists that follow in the same call. + #[test] + fn the_card_copies_what_is_recorded() { + let Some(host) = host() else { + return; // no host GPU + }; + let (a, a_data) = host.shared_buffer(1 << 16).unwrap(); + let (b, b_data) = host.shared_buffer(1 << 16).unwrap(); + // SAFETY: mappings of 64 KiB. + let (a_bytes, b_bytes) = + unsafe { (std::slice::from_raw_parts_mut(a_data, 1 << 16), std::slice::from_raw_parts_mut(b_data, 1 << 16)) }; + for (i, (x, y)) in a_bytes.iter_mut().zip(b_bytes.iter_mut()).enumerate() { + (*x, *y) = (i as u8 ^ (i >> 8) as u8, 0xee); + } + let was = a_bytes.to_vec(); + let own = host.own_list().unwrap(); + // Within `a` (there and back), from `a` to `b`, and a read alone. + record( + &own.list.list, + &own.between, + &[(&a, 33, 0, 100), (&a, 2000, 256, 100), (&a, 5001, 512, 7), (&a, 9, 1024, 4)], + &[(&a, 2000, 0, 100), (&a, 33, 256, 100), (&b, 77, 512, 7)], + ); + own.list.close(); + // A list behind it that uses the buffers in other ways. + let next = host.new_list().unwrap(); + let (out, out_data) = host.shared_buffer(1 << 16).unwrap(); + // SAFETY: an open list; live buffers. + unsafe { + next.list.CopyBufferRegion(&out, 0, &own.between, 1024, 4); + next.list.CopyBufferRegion(&b, 4096, &a, 33, 100); + } + next.close(); + host.execute(&[&own.list, &next]); + // With the debug layer (`VICTORY_D3D12_DEBUG=1`, diagnostics). + assert_eq!(host.log_messages(), None); + assert_eq!(a_bytes[2000..2100], was[33..133]); + assert_eq!(a_bytes[33..133], was[2000..2100]); + assert_eq!(b_bytes[77..84], was[5001..5008]); + assert_eq!(b_bytes[4096..4196], was[2000..2100]); + // SAFETY: a mapping of 64 KiB. + assert_eq!(unsafe { std::slice::from_raw_parts(out_data, 4) }, &was[9..13]); + assert!(b_bytes[..77].iter().all(|&x| x == 0xee)); + a_bytes[2000..2100].copy_from_slice(&was[2000..2100]); + a_bytes[33..133].copy_from_slice(&was[33..133]); + assert_eq!(a_bytes, &was[..]); + // As the landing does: its next use records anew. + POOL.lock().unwrap().push(own); + let own = host.own_list().unwrap(); + own.list.close(); + } + + /// The whole way, in a process of its own with the relay on: + /// `VICTORY_RELAY=2 VICTORY_CARD_STEPS=2 cargo test -p victory-gpu --lib + /// card_steps -- --ignored --test-threads=1`. A flight's list writes + /// part of what the next submission's copy reads, the title wrote the + /// rest; the copy is done on the card behind the flight, and a second + /// one reads what the first wrote. Title memory ends as on the CPU. + #[test] + #[ignore = "wants VICTORY_RELAY=2 VICTORY_CARD_STEPS=2 and a process of its own"] + fn a_copy_behind_a_flight_reads_what_the_flight_wrote() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const LEN: usize = 4 << 20; + const WRITE_WATCH: u32 = 0x20_0000; + let Some(host) = host() else { + return; + }; + assert!(relay_exact() && stage() == 2, "set VICTORY_RELAY=2 VICTORY_CARD_STEPS=2"); + // Two title buffers: in the first a copy within it, from it into the + // second, and back. + let (title, start) = { + // SAFETY: memory of our own, never freed. + let base = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, PAGE_READWRITE) }.cast::(); + assert!(!base.is_null()); + // SAFETY: `LEN` bytes just committed. + (unsafe { std::slice::from_raw_parts_mut(base, LEN) }, base as usize) + }; + const HALF: usize = LEN / 2; + crate::shadow::register(0x1111, start as u64, HALF as u64); + crate::shadow::register(0x2222, (start + HALF) as u64, HALF as u64); + let first = crate::shadow::find(start as u64, 64).unwrap(); + let (slow_from, slow_to) = (host.uav_buffer(64 << 20).unwrap(), host.uav_buffer(64 << 20).unwrap()); + let before = DONE[1].load(Ordering::Relaxed); + let mut lists = Vec::new(); + for round in 0..8usize { + // The title writes; then a "shader" of a flight writes 300 bytes + // of what the copy reads, behind some work. + let seed = |i: usize| (i * 7 + round * 13 + i / 251) as u8; + for (i, b) in title[4000..6000].iter_mut().enumerate() { + *b = seed(i); + } + let (upload, data) = host.upload_buffer(4096).unwrap(); + for i in 0..300 { + // SAFETY: inside the mapping. + unsafe { data.add(i).write(0x80 | (round * 31 + i) as u8) }; + } + let a = host.new_list().unwrap(); + first.refresh(&a, start as u64, HALF as u64); + first.gpu_writes(&a, start as u64, HALF as u64); + // SAFETY: an open list; live buffers. + unsafe { + for _ in 0..24 { + a.list.CopyBufferRegion(&slow_to, 0, &slow_from, 0, 64 << 20); + } + a.list.CopyBufferRegion(&first.buffer, 4500, &upload, 0, 300); + a.list + .ResourceBarrier(&[transition(&first.buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]); + } + a.close(); + host.execute_own(&a); + // With the flight in the air, beside what it writes. + for (i, b) in title[5300..5400].iter_mut().enumerate() { + *b = seed(1300 + i) ^ 0x5c; + } + // Into the second buffer, and within the first. + let b = host.new_list().unwrap(); + b.defer_copy((start + HALF + 100) as *mut u8, (start + 4001) as *const u8, 1500); + b.defer_copy((start + 900_001) as *mut u8, (start + 4400) as *const u8, 777); + b.close(); + host.execute_own(&b); + // What the first wrote, read by the next submission. + let c = host.new_list().unwrap(); + c.defer_copy((start + 1_200_000) as *mut u8, (start + HALF + 100) as *const u8, 1500); + c.close(); + let number = host.execute_own(&c); + settle_now(WHY_SYNC); + assert!(FINISHED.load(Ordering::Acquire) >= number); + let wanted: Vec = (0..2000) + .map(|i| match i { + 500..800 => 0x80 | (round * 31 + i - 500) as u8, + 1300..1400 => seed(i) ^ 0x5c, + _ => seed(i), + }) + .collect(); + assert!(title[4000..6000] == wanted[..], "what the flight wrote, round {round}"); + assert!(title[HALF + 100..HALF + 1600] == wanted[1..1501], "the copy to the other buffer, round {round}"); + assert!(title[900_001..900_778] == wanted[400..1177], "the copy within the buffer, round {round}"); + assert!(title[1_200_000..1_201_500] == wanted[1..1501], "the copy of the copy, round {round}"); + assert!(title[HALF..HALF + 100].iter().all(|&x| x == 0)); + assert!(title[HALF + 1600..].iter().all(|&x| x == 0)); + a.keep(&upload); + lists.extend([a, b, c]); + } + assert_eq!(host.log_messages(), None); + let done = DONE[1].load(Ordering::Relaxed) - before; + eprintln!("{done} of 24 copies were done on the card, {} submissions waited", DONE[3].load(Ordering::Relaxed)); + assert!(done >= 12, "only {done} copies were done on the card"); + } +} diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index c256367..67ebe7a 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -304,6 +304,8 @@ pub(crate) fn ready( shadow.refresh(list, start, len); } if writes && (first_write || n >= numbered) { + #[cfg(feature = "diagnostics")] + crate::host::wide_write(start, len, 1); shadow.gpu_writes(list, start, len); } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 68817e0..2d2c6c5 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1831,6 +1831,11 @@ impl Shadow { self.id } + /// Whether it is no copy but title memory in place (`crate::inplace`). + pub(crate) fn in_place(&self) -> bool { + self.place.is_some() + } + /// Offset of a title address from the buffer's start. pub(crate) fn offset(&self, address: u64) -> u64 { address - self.start + self.place.as_ref().map_or(0, |place| place.1) From 389db9efb25be4d7727c920730194527ec87a916 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 22:02:52 -0600 Subject: [PATCH 164/445] Shader forms: sizes of views nothing reads, ordered sections, wave sums off the beaten path, counters - An image or structured buffer whose descriptor is read for its size alone (the puddle passes, a water simulation step). - The record count of a structured buffer is asked of the raw view the host makes of it: as a structured view's it was in bytes on AMD. - Primitive-ordered pixel shading becomes rasterizer ordered views (the hair cards' layers). - A 16-bit wave sum where not every lane runs, on 64-lane waves, bit for bit as the console's tree. - "Some lane is left" of a mask operation as a number; scalars parked in a VGPR used before; a one-channel store into a counter texture (the upscaler). - translate --list prints a hash of every emitted module. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/translate.rs | 6 + crates/victory-shader/src/emit/bitcode/opt.rs | 6 +- crates/victory-shader/src/emit/lower.rs | 329 ++++++++++++++++-- crates/victory-shader/src/emit/mod.rs | 130 +++++++ crates/victory-shader/src/emit/shader.rs | 5 + crates/victory-shader/src/emit/size_tests.rs | 268 ++++++++++++++ .../src/emit/waterfall_tests.rs | 2 +- .../victory-shader/src/emit/wave64_tests.rs | 156 +++++++++ crates/victory-shader/src/ir.rs | 34 +- crates/victory-shader/src/resource.rs | 36 ++ 10 files changed, 941 insertions(+), 31 deletions(-) create mode 100644 crates/victory-shader/src/emit/size_tests.rs diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index c817360..f334d20 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -598,6 +598,12 @@ fn check( if let Some(keep) = &checks.keep { lock(keep).push((label(), shader.clone())); } + // With `--list`: a hash of the module and of what the host binds for it, + // to show which shaders a change to the translator touches. + if t.list { + let hash = blake3::hash(format!("{shader:?}").as_bytes()).to_hex(); + t.lines.push(format!("{} emitted {}", label(), &hash[..16])); + } // `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file. if t.list && let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP") diff --git a/crates/victory-shader/src/emit/bitcode/opt.rs b/crates/victory-shader/src/emit/bitcode/opt.rs index 13551c3..89dc8b7 100644 --- a/crates/victory-shader/src/emit/bitcode/opt.rs +++ b/crates/victory-shader/src/emit/bitcode/opt.rs @@ -63,6 +63,8 @@ pub const ALL: u32 = MODULE | FIRST; pub(crate) struct Usage { /// A wave or quad operation. pub wave_ops: bool, + /// A rasterizer ordered view. + pub rovs: bool, /// A 64-bit integer, as a result or an operand. pub int64: bool, /// A typed load of several components from a UAV. @@ -388,7 +390,7 @@ impl Module { } /// An integer constant's width and value (the bits of that width). - fn int_k(&self, v: V) -> Option<(u32, u64)> { + pub(crate) fn int_k(&self, v: V) -> Option<(u32, u64)> { let V::Const(i) = v else { return None }; let (ty, Const::Int(x)) = &self.consts[i as usize] else { return None; @@ -1009,6 +1011,8 @@ impl Module { Some((_, 0)) => u.heap_views = true, _ => u.heap_samplers = true, } + } else if name == "annotateHandle" { + u.rovs |= annotation(V::Inst(i)).is_some_and(|(kind, _)| kind & 0x2000 != 0); } else if name.starts_with("atomic") && name.ends_with(".i64") { u.atomic64 = true; } else if name.starts_with("textureLoad") || name.starts_with("bufferLoad") { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c2a9d35..f5a547e 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -107,6 +107,64 @@ pub(crate) fn lower(parts: &Parts) -> Result { const TWO_PI: f32 = std::f32::consts::TAU; /// `s_sendmsg` id of a mesh or NGG stage's output allocation request. const GS_ALLOC_REQ: u16 = 9; +/// `s_sendmsg` id that ends a pixel wave's ordered section. +const ORDERED_PS_DONE: u16 = 7; +/// Hardware register (of `s_setreg_b32`) a pixel wave names its packer in +/// before it waits for the waves it overlaps. +const POPS_PACKER: u16 = 25; +/// The operand `src_pops_exiting_wave_id`. +const POPS_EXITING: u8 = 239; + +/// The instructions inside a pixel program's ordered section +/// (primitive-ordered pixel shading, which the console compiler makes of +/// rasterizer ordered views): from the write of `POPS_PACKER`, along every +/// path, to the message that ends the section or the program's end. The +/// console waits there until the waves holding earlier primitives' samples +/// of the same pixels have left their sections; a host's rasterizer ordered +/// views wait by themselves, at their first access. Empty for a program +/// without such a section. +fn ordered_section(p: &Program) -> HashSet { + let starts = |i: &Inst| { + i.name() == "s_setreg_b32" + && matches!(i.fields, Fields::Sop { imm: Some(imm), .. } if imm & 0x3F == POPS_PACKER) + }; + let ends = |i: &Inst| { + i.name() == "s_sendmsg" + && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == ORDERED_PS_DONE) + }; + let mut section = HashSet::new(); + let mut entered = vec![false; p.blocks.len()]; + let mut work: Vec = p + .blocks + .iter() + .enumerate() + .flat_map(|(b, block)| { + (0..block.insts.len()) + .filter(|&i| starts(&block.insts[i])) + .map(move |i| (b, i)) + }) + .collect(); + while let Some((b, from)) = work.pop() { + let block = &p.blocks[b]; + let mut done = false; + for i in from..block.insts.len() { + if ends(&block.insts[i]) { + done = true; + break; + } + section.insert((b, i)); + } + if done { + continue; + } + for (t, next) in p.blocks.iter().enumerate() { + if next.preds.contains(&b) && !std::mem::replace(&mut entered[t], true) { + work.push((t, 0)); + } + } + } + section +} /// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0, /// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)). @@ -194,6 +252,8 @@ struct Lower<'a> { /// Descriptor dwords with no host value (addresses, formats, all of a constant /// buffer's): no program reads them as numbers ([`Self::dead`]). stale: HashSet, + /// See [`ordered_section`] (pixel programs). + ordered: HashSet, mask_phis: HashMap, pending_masks: Vec<(V, usize, usize)>, data_phis: Vec<(V, usize, usize)>, @@ -1486,6 +1546,11 @@ impl<'a> Lower<'a> { data_phis: Vec::new(), read_phis: HashSet::new(), stale: HashSet::new(), + ordered: if x.native.stage == HwStage::Ps { + ordered_section(p) + } else { + HashSet::new() + }, params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(), user_data: None, user_reads: BTreeMap::new(), @@ -2064,9 +2129,12 @@ impl<'a> Lower<'a> { /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange /// their halves' sums for the last addition. The high half of the result is lane 0's, /// which no `v_add_f16` writes. - /// That needs every lane of a full wave there to be read: refused where not every lane - /// runs, in a thread group that does not fill its waves, and for each half-wave on its - /// own (half a sum is no sum). + /// On a host wave of 64 lanes where not every lane runs, the lanes that are elsewhere + /// count as the console's do (it masks them to +0): a partner's partial sum is read from + /// the first lane there is of the partner's run of lanes, and is +0 without one. Two host + /// waves of 32 can only exchange where every lane runs: refused elsewhere, in a thread + /// group that does not fill its waves, and for each half-wave on its own (half a sum is + /// no sum). fn half_sum(&mut self, x: V) -> Result { const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs"; let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?; @@ -2087,24 +2155,54 @@ impl<'a> Lower<'a> { } else { all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false)) }; - if !every { - if halves { - need(self.cur_ir); - } + if !every && halves { + need(self.cur_ir); return Err(WHERE); } let c = self.cur; let i32t = self.s.t.i32; let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0)); + // the lanes that are here, when not all are + let here = (!every).then(|| { + self.s.flags |= flags::WAVE_OPS; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let yes = self.s.m.bool(true); + let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[yes]); + (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1)) + }); + // `v` of the first lane here of the `n` (a power of two) lanes from `base`: +0 of none + let first_of = |l: &mut Self, v: V, base: V, n: u32| { + let Some((lo, hi)) = here else { + return l.read_lane(v, base); + }; + let (k31, k32) = (l.s.m.i32(31), l.s.m.i32(32)); + let lower = l.s.m.cmp(c, pred::IULT, base, k32); + let word = l.s.m.select(c, lower, lo, hi); + let shift = l.s.m.bin(c, Bin::And, base, k31); + let word = l.s.m.bin(c, Bin::LShr, word, shift); + let run = l.s.m.i32(u32::MAX >> (32 - n)); + let word = l.s.m.bin(c, Bin::And, word, run); + let any = l.s.m.cmp(c, pred::NE, word, zero); + let nth = l.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[word]); + let from = l.s.m.bin(c, Bin::Add, base, nth); + // (no lane there: this one, which is here; the read is not used) + let from = l.s.m.select(c, any, from, lane); + let got = l.read_lane(v, from); + l.s.m.select(c, any, got, zero) + }; let mut sum = x; for step in 0..if halves { 5 } else { 6 } { let bit = self.s.m.i32(1 << step); - let partner = self.s.m.bin(c, Bin::Xor, lane, bit); - let theirs = self.read_lane(sum, partner); + let mut partner = self.s.m.bin(c, Bin::Xor, lane, bit); + if !every { + let run = self.s.m.i32(!((1 << step) - 1)); + partner = self.s.m.bin(c, Bin::And, partner, run); + } + let theirs = first_of(self, sum, partner, 1 << step); sum = self.add_halves(sum, theirs); } - let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0)); - let first = self.read_lane(x, zero); + let first = first_of(self, x, zero, 1); let first = self.s.m.bin(c, Bin::And, first, high); let sum = self.s.m.bin(c, Bin::And, sum, low); let mine = self.s.m.bin(c, Bin::Or, first, sum); @@ -2258,6 +2356,8 @@ impl<'a> Lower<'a> { // paths only seem to allow it before any save: the lane of a VGPR // nobody wrote, and VGPRs nobody set read as zero. None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)), + // No wave overlaps this one (see `ordered_section`). + None if self.pops_collision(v) => Val::I32(self.s.m.i32(0)), None => Val::Missing("a hardware SGPR input"), }, Reg::Scc => Val::Missing("SCC on entry"), @@ -2273,6 +2373,36 @@ impl<'a> Lower<'a> { Ok(()) } + /// Whether the input SGPR `v` is the POPS collision wave id: a program + /// with an ordered section only takes its fields apart (bit 31 says + /// that the wave overlaps another, the others which packer and waves). + fn pops_collision(&self, v: Value) -> bool { + if self.ordered.is_empty() { + return false; + } + let mut packer = false; + for block in &self.x.p.blocks { + if block.phis.iter().any(|p| p.args.contains(&v)) { + return false; + } + for i in &block.insts { + if !i.reads.iter().any(|r| r.1 == v) { + continue; + } + let Fields::Sop { src, .. } = &i.fields else { + return false; + }; + match (i.name(), src.get(1)) { + // bits 28 and 29: the packer + ("s_bfe_u32", Some(Operand::Literal(0x0002_001C))) => packer = true, + ("s_bfe_u32" | "s_lshr_b32", _) => {} + _ => return false, + } + } + } + packer + } + fn input(&mut self, input: Input) -> Val { let (kind, col) = match input { Input::VertexId => (1, 0), @@ -2665,6 +2795,93 @@ impl<'a> Lower<'a> { }) } + /// Whether the image `src` names is one of 32-bit integers (one channel): + /// the program has an integer atomic on the same table entry, which + /// takes no other view. + fn is_counter(&self, src: &Source) -> bool { + let entry = |s: &Source| match s { + Source::Loaded { load, first } => self + .scalar + .get(load) + .filter(|a| a.dynamic.is_none()) + .map(|a| (a.param, a.offset + 4 * u32::from(*first))), + _ => None, + }; + let Some(this) = entry(src) else { + return false; + }; + self.x.res.descriptors.iter().any(|d| { + let i = &self.x.p.blocks[d.site.0].insts[d.site.1]; + d.role == Role::Resource + && matches!(i.fields, Fields::Image { dmask: 1, .. }) + && matches!( + i.name(), + "image_atomic_add" + | "image_atomic_sub" + | "image_atomic_and" + | "image_atomic_or" + | "image_atomic_xor" + | "image_atomic_smin" + | "image_atomic_smax" + | "image_atomic_umin" + | "image_atomic_umax" + ) + && entry(&d.source) == Some(this) + }) + } + + /// The kind of a view no instruction uses (in this program, or through + /// another load of its address), by what the code reads of the + /// descriptor the load `inst` at `site` writes to the SGPRs from `code`: + /// `Some(true)` for a 2D image, read only for its size, `Some(false)` + /// for a structured buffer, read only for its record count. + /// + /// - Eight dwords are an image's. `GetDimensions` of a 2D one reads the + /// width (dwords 1 and 2), the height (dword 2, bits 14-29, with one + /// `s_bfe_u32`) and the base level or the last (dword 3); of an array, + /// a cube or a volume also dword 4. + /// - Four dwords at a table entry the used resources list as an SRV or + /// UAV are a buffer's. A stride above 4 bytes there is an element's + /// (a typed or raw view has at most 4): a test for a null view reads + /// the record count, nothing else. + fn sized_view(&self, inst: &Inst, site: Site, code: u8, count: u32) -> Option { + let dword = |k: u8| inst.write(Reg::S(code + k)); + let read = |v: Value| { + self.x.p.blocks.iter().any(|b| { + b.insts.iter().any(|i| i.reads.iter().any(|r| r.1 == v)) + || b.phis.iter().any(|p| p.args.contains(&v)) + }) + }; + let only = |allowed: &[u8]| { + (0..count as u8).all(|k| allowed.contains(&k) || !dword(k).is_some_and(read)) + }; + match count { + 8 => { + const HEIGHT: u32 = 16 << 16 | 14; + let v = dword(2)?; + let height = self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| { + i.name() == "s_bfe_u32" + && i.reads.iter().any(|r| r.1 == v) + && matches!(&i.fields, Fields::Sop { src, .. } + if matches!(src.get(1), Some(Operand::Literal(HEIGHT)))) + }); + (height && only(&[1, 2, 3])).then_some(true) + } + 4 => { + let used = self.used_kind(&Source::Loaded { load: site, first: 0 })?; + let a = self.scalar.get(&site)?; + let buffer = used.dwords == 4 + && a.dynamic.is_none() + && used.table_offset_dwords == a.offset / 4 + && matches!(used.kind, ResourceType::Srv | ResourceType::Uav) + && used.stride > 4 + && used.stride.is_multiple_of(4); + (buffer && only(&[2])).then_some(false) + } + _ => None, + } + } + /// The title address (low dword, bits from 32 up) of the buffer view /// whose descriptor the scalar load at `site` reads from the start of /// a table entry, as the host tells it when it binds (`shader.rs` @@ -3052,6 +3269,11 @@ impl<'a> Lower<'a> { if self.exchange.is_some() && !self.local { need(made.unwrap_or(0)); } + if std::env::var_os("VICTORY_DESC_WHY").is_some() { + let by = made.map(|b| &self.x.p.blocks[b]); + let def = by.and_then(|b| b.insts.iter().find(|i| i.writes.iter().any(|w| w.1 == lo))); + eprintln!("MASK-WHY {v:?} made in {made:?} by {:?} at {:x?}; read in block at {:#x}; phi {}", def.map(|i| i.name()), def.map(|i| i.machine.offset), self.x.p.blocks[self.cur_ir].offset, self.phi_at.contains_key(&lo)); + } return Err(MASK_ELSEWHERE); } let (x, y) = match self.ballots.get(&lo) { @@ -3116,6 +3338,8 @@ impl<'a> Lower<'a> { let bit = self.scc_in(inst)?; Ok(self.s.m.cast(self.cur, Cast::ZExt, bit, self.s.t.i32)) } + // Nothing to wait for (see `ordered_section`). + Operand::Const(POPS_EXITING) if !self.ordered.is_empty() => Ok(self.s.m.i32(0)), Operand::Const(c) => crate::resource::inline(c) .map(|x| self.s.m.i32(x)) .ok_or("a special operand (vccz, execz, scc, lds_direct)"), @@ -5400,12 +5624,30 @@ impl<'a> Lower<'a> { fn scc_in(&mut self, inst: &Inst) -> Result { let v = inst.read(Reg::Scc).ok_or("an unread SCC")?; - match self.get(v)? { - Val::Bit(x) => Ok(x), - _ => Err("SCC without a value"), + match self.get(v) { + Ok(Val::Bit(x)) => Ok(x), + Ok(_) => Err("SCC without a value"), + // Of a mask operation whose result lies within EXEC: whether + // some lane is left. + Err(LANE_MASK) if self.within_exec(v) => self.scc_some(v), + Err(why) => Err(why), } } + /// Whether the mask operation that sets the SCC value `scc` gives no + /// lane outside EXEC a bit. + fn within_exec(&self, scc: Value) -> bool { + let Some(&b) = self.def_block.get(&scc) else { + return false; + }; + let by = self.x.p.blocks[b].insts.iter().find(|i| i.write(Reg::Scc) == Some(scc)); + by.is_some_and(|i| { + i.write(Reg::S(EXEC)).is_some() + || matches!(&i.fields, Fields::Sop { dst: Some(Operand::Scalar { code, .. }), .. } + if i.write(Reg::S(*code)).is_some_and(|lo| self.x.st.active.contains(&lo))) + }) + } + fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { let Fields::Smem { data, @@ -5653,7 +5895,12 @@ impl<'a> Lower<'a> { .find_map(|(s, _)| use_of(*s)) }; let use_at = use_of(site).or_else(twin); - let Some((at, first)) = use_at else { + // A view whose kind no use tells, but what is read of it does. + let sized = match use_at { + Some(_) => None, + None => self.sized_view(inst, site, code, count), + }; + let Some((at, first)) = use_at.or(sized.map(|_| (site, 0))) else { // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only // copies its dwords and compares them, lane against first lane, and every load // that reaches those lanes reads one address. Each dword stands in as its place @@ -5721,6 +5968,8 @@ impl<'a> Lower<'a> { || used.is_some_and(|u| u.kind == ResourceType::Uav); let u = if uav { 0x1000 } else { 0 }; let (props, image) = match &ui.fields { + _ if sized.is_some_and(|image| image) => ((2 | u, 0x409), Some(2)), + _ if sized.is_some() => ((11 | u, 0), None), // A ray-tracing structure in a buffer of the host: read raw. Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None), Fields::Image { dim, .. } => { @@ -5734,15 +5983,15 @@ impl<'a> Lower<'a> { }; ((kind | u, 0x409), Some(kind)) } - Fields::Buffer { idxen, format, .. } => { - let stride = used.map_or(0, |u| u.stride); + Fields::Buffer { .. } => { let props = if un.starts_with("buffer_load_format") || un.starts_with("buffer_store_format") { (10 | u, 0x409) - } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) { - (12 | u, stride) } else { + // Structured ones too: the host's views of them are raw + // (see `buffer`), which count bytes, and a size asked + // for as a structured view's is that count on AMD. (11 | u, 0) }; if used.is_some_and(|u| u.kind == ResourceType::Cbv) { @@ -9549,7 +9798,13 @@ impl<'a> Lower<'a> { || self .used_kind(src) .is_some_and(|u| u.kind == ResourceType::Uav); - let props = (kind | if uav { 0x1000 } else { 0 }, 0x409); + // A UAV inside an ordered section is a rasterizer ordered view. + let ordered = uav && self.ordered.contains(&site); + if ordered { + self.s.flags |= flags::ROVS; + } + let rov = if ordered { 0x2000 } else { 0 }; + let props = (kind | if uav { 0x1000 } else { 0 } | rov, 0x409); if let Some(op) = name.strip_prefix("image_atomic_") { // GLC returns the old value. DXIL implements subtraction by adding // the two's complement of the operand at the same width. @@ -9607,7 +9862,7 @@ impl<'a> Lower<'a> { } else { original }; - let h = self.handle(site, src, false, (kind | 0x1000, component))?; + let h = self.handle(site, src, false, (kind | 0x1000 | rov, component))?; let mut args = vec![h]; let (intrinsic, opcode) = if compare { let comparand = if wide { @@ -9660,7 +9915,9 @@ impl<'a> Lower<'a> { } // shortcut: stores are taken to write all four channels of a // float format (the console converts by the view's format). - if *dmask != 0xF { + // One channel goes into a view the program also counts in. + let counter = *dmask == 1 && self.is_counter(src); + if *dmask != 0xF && !counter { return Err("an image store of some channels"); } let iu = self.s.m.undef(self.s.t.i32); @@ -9671,6 +9928,34 @@ impl<'a> Lower<'a> { let Operand::Vector { reg, .. } = *data else { return Err("image store data"); }; + if counter { + let v = inst.read(Reg::V(reg)).ok_or("image store data")?; + let x = self.i32_of(v)?; + // A 16-bit integer, extended by the view's sign: the same + // number either way only if it is known to be small. + if *d16 && !self.s.m.int_k(x).is_some_and(|(_, k)| k < 0x8000) { + return Err("a 16-bit image store of one channel"); + } + let h = self.handle(site, src, false, (kind | 0x1000 | rov, 0x105))?; + let at = self.begin_guarded(guard); + // All four channels are written (the validator wants them + // all): the view has the first alone. + let mut args = vec![h]; + args.extend(cs); + args.extend([x; 4]); + args.push(self.s.m.i8(0xF)); + let void = self.s.t.void; + self.s.op( + self.cur, + "textureStore.i32", + Attr::NoUnwind, + void, + 67, + &args, + ); + self.end_guarded(at, &[]); + return Ok(()); + } let mut vals = Vec::new(); for k in 0..4u8 { // d16: two f16 channels per VGPR, low half first. diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 9ca8313..d919660 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -99,6 +99,8 @@ mod threading; #[cfg(windows)] pub mod validator; #[cfg(all(test, windows))] +mod size_tests; +#[cfg(all(test, windows))] mod valu_tests; #[cfg(all(test, windows))] mod waterfall_tests; @@ -859,6 +861,134 @@ mod tests { assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef"); } + /// A pixel program with an ordered section, as the console compiler + /// makes one of rasterizer ordered views (the title's hair cards keep + /// their nearest layers that way): the wait for overlapped waves is + /// skipped, the views inside the section are the host's ordered ones, + /// the one after it is not. + #[test] + fn an_ordered_section_uses_rasterizer_ordered_views() { + let section = [ + 0xBE82_0300u32, // s_mov_b32 s2, s0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0201, // s_load_dwordx8 s[8:15], s[2:3], 0 + 0xFA00_0000, + 0x9390_FF01, // s_bfe_u32 s16, s1, 0x2001c + 0x0002_001C, + 0x9391_FF01, // s_bfe_u32 s17, s1, 0xa0000 + 0x000A_0000, + 0x8F10_8110, // s_lshl_b32 s16, s16, 1 + 0x9392_FF01, // s_bfe_u32 s18, s1, 0xa0010 + 0x000A_0010, + 0xBE91_0711, // s_not_b32 s17, s17 + 0x9013_9F01, // s_lshr_b32 s19, s1, 31 + 0x8810_8110, // s_or_b32 s16, s16, 1 + 0x8112_1112, // s_add_i32 s18, s18, s17 + 0xBF06_8013, // s_cmp_eq_u32 s19, 0 + 0xB990_1019, // s_setreg_b32 hwreg(HW_REG_POPS_PACKER, 0, 3), s16 + 0x8514_807E, // s_cselect_b32 s20, exec_lo, 0 + 0x8115_11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17 + 0xBF08_1215, // s_cmp_gt_u32 s21, s18 + 0x8516_807E, // s_cselect_b32 s22, exec_lo, 0 + 0x8814_1614, // s_or_b32 s20, s20, s22 + 0x876A_147E, // s_and_b32 vcc_lo, exec_lo, s20 + 0xBF87_0004, // s_cbranch_vccnz past the wait + 0xBF8E_FFFF, // s_sleep 0xffff + 0x8115_11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17 + 0xBF0A_1512, // s_cmp_lt_u32 s18, s21 + 0xBF84_FFFC, // s_cbranch_scc0 back to the sleep + 0x7E00_0280, // v_mov_b32 v0, 0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0xF000_3F88, // image_load v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc dlc + 0x0002_0200, + 0x0604_04F2, // v_add_f32 v2, 1.0, v2 + 0xF020_3F08, // image_store v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc + 0x0002_0200, + 0xBEFC_0380, // s_mov_b32 m0, 0 + 0xBF90_0007, // s_sendmsg sendmsg(MSG_ORDERED_PS_DONE) + ]; + let end = [ + 0xF800_180Fu32, // exp mrt0 v2, v2, v2, v2 done vm + 0x0202_0202, + 0xBF81_0000, // s_endpgm + ]; + // A store after the section, through an ordinary view. + let after = [0xF020_3F08u32, 0x0002_0200]; + let lower = |words: Vec| { + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 8, + layout: vec![crate::native::RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![crate::native::UsedResource { + kind: crate::native::ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 8, + user_data: 0, + slot: 0, + }], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let target = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }; + let osg1 = container::signature(&[target], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let st = structure::structure(&p)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native)?; + let out = emit(&c, &native, &p, &st, &io, &res)?; + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut out.dxil.clone()).unwrap(); + } + let host = Container::parse(&out.dxil).unwrap(); + let sfi0 = host.part(FourCC::SFI0).unwrap().data; + Ok::(u64::from_le_bytes(sfi0.try_into().unwrap())) + }; + // D3D_SHADER_REQUIRES_ROVS + let features = lower([§ion[..], &end].concat()).unwrap(); + assert_ne!(features & 0x1000, 0, "SFI0 {features:#x}: no ROVs"); + lower([§ion[..], &after, &end].concat()).unwrap(); + // The same accesses outside a section: ordinary views, no feature. + let plain = [§ion[..4], §ion[28..35], &end].concat(); + let features = lower(plain).unwrap(); + assert_eq!(features & 0x1000, 0, "SFI0 {features:#x}: ROVs"); + // Without the section's start the wait stays unknown. + let mut unmarked = [§ion[..], &end].concat(); + unmarked.remove(16); + assert!(lower(unmarked).is_err()); + } + /// A wave64 compute program that writes only EXEC's high dword /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was /// opaque and keyed by the unchanged low dword, so building its lane bit diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 28a36f1..eb6d589 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -76,6 +76,7 @@ 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; + pub const ROVS: u64 = 1 << 18; pub const WAVE_OPS: u64 = 1 << 19; pub const BARYCENTRICS: u64 = 1 << 22; pub const INT64: u64 = 1 << 20; @@ -455,6 +456,7 @@ impl Shader { self.m.optimise(passes); let used = self.m.usage(); for (flag, used) in [ + (flags::ROVS, used.rovs), (flags::WAVE_OPS, used.wave_ops), (flags::INT64, used.int64), (flags::TYPED_UAV_LOADS, used.typed_uav_loads), @@ -787,6 +789,9 @@ impl Shader { if self.flags & flags::TYPED_UAV_LOADS != 0 { features |= 0x800; } + if self.flags & flags::ROVS != 0 { + features |= 0x1000; + } if self.flags & flags::WAVE_OPS != 0 { features |= 0x4000; } diff --git a/crates/victory-shader/src/emit/size_tests.rs b/crates/victory-shader/src/emit/size_tests.rs new file mode 100644 index 0000000..5c6c40e --- /dev/null +++ b/crates/victory-shader/src/emit/size_tests.rs @@ -0,0 +1,268 @@ +//! End-to-end tests of what a program tells about a view by how it uses it: +//! descriptors read for sizes (the dwords of a view no instruction uses) and +//! counters, lowered to DXIL, validated by `dxil.dll` when present, and run +//! on the host GPU and WARP. + +use super::host::{Stride, View}; +use super::waterfall_tests::run; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{ShaderError, io, ir, resource, structure}; + +/// Lowers a wave32 compute program of one thread with the table of views at +/// s0 and the view heap at s1; `srv`: the dwords and the stride of the used +/// resource at the table's first entry (the third is a raw UAV). +fn build(words: &[u32], srv: (u8, u32)) -> Result { + let param = |root, user_data| RootParam { + root, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data, + slot: 0, + }; + let range = |kind, table_offset_dwords, dwords, stride| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: 0, + stride, + dwords, + user_data: 0, + slot: 0, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 32, + layout: vec![param(RootType::Table, 0), param(RootType::ResourceHeap, 1)], + used: vec![ + range(ResourceType::Srv, 0, srv.0, srv.1), + range(ResourceType::Uav, 16, 4, 0), + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs)?; + let st = structure::structure(&p)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native)?; + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + })?; + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: Vec::new(), + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } else { + eprintln!("no dxil.dll; validation skipped"); + } + Ok(shader) +} + +/// The table at s[2:3], its raw UAV's descriptor in s[20:23]. +const TABLE: &[u32] = &[ + 0xBE82_0300, // s_mov_b32 s2, s0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF408_0501, // s_load_dwordx4 s[20:23], s[2:3], 64 + 0xFA00_0040, +]; + +/// Stores s4 and s5 at bytes 0 and 4 of the UAV. +const STORE: &[u32] = &[ + 0x7E08_0204, // v_mov_b32 v4, s4 + 0x7E0A_0205, // v_mov_b32 v5, s5 + 0xE070_0000, // buffer_store_dword v4, off, s[20:23], 0 + 0x8005_0400, + 0xE070_0004, // buffer_store_dword v5, off, s[20:23], 0 offset:4 + 0x8005_0500, + 0xBF81_0000, // s_endpgm +]; + +/// `GetDimensions` of a texture as the console compiler expands it, from +/// the descriptor in s[8:15]: width in s4, height in s5, base level in s6. +const SIZES: &[u32] = &[ + 0x9004_9E09, // s_lshr_b32 s4, s9, 30 + 0x8F05_820A, // s_lshl_b32 s5, s10, 2 + 0x8804_0504, // s_or_b32 s4, s4, s5 + 0x8704_FF04, // s_and_b32 s4, s4, 0xffff + 0x0000_FFFF, + 0x9385_FF0A, // s_bfe_u32 s5, s10, 0x10000e + 0x0010_000E, + 0x9386_FF0B, // s_bfe_u32 s6, s11, 0x4000c + 0x0004_000C, + 0x8104_8104, // s_add_i32 s4, s4, 1 + 0x8105_8105, // s_add_i32 s5, s5, 1 + 0x9004_0604, // s_lshr_b32 s4, s4, s6 + 0x9005_0605, // s_lshr_b32 s5, s5, s6 +]; + +/// s_load_dwordx8 s[8:15], s[6:7], s12: entry 1 of the view heap. +const FROM_HEAP: &[u32] = &[ + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xBE8C_03A0, // s_mov_b32 s12, 32 + 0xF40C_0203, + 0x1800_0000, +]; + +/// `s_load_dwordx4 s[8:11], s[2:3], 0`, then the record count in s4 and 0 +/// in s5. +const COUNT: &[u32] = &[ + 0xF408_0201, + 0xFA00_0000, + 0xBE84_030A, // s_mov_b32 s4, s10 + 0xBE85_0380, // s_mov_b32 s5, 0 +]; + +/// A puddle pass of the title picks three textures from the view heap, +/// reads the first one's size and samples the other two. +#[test] +fn the_size_of_a_heap_texture_nothing_reads() { + let words = [TABLE, FROM_HEAP, SIZES, STORE].concat(); + let shader = build(&words, (8, 0)).expect("translates"); + let (one, texels) = ([[0.0; 4]; 1], [[0.0; 4]; 15]); + let views = [ + View::Texture(1, 1, &one), + View::Texture(5, 3, &texels), + View::RawUav(2), + ]; + for (label, got) in run(&shader, &views) { + assert_eq!(got[..2], [5, 3], "{label}"); + } +} + +/// Without the height nothing tells a 2D texture from the others, and a +/// volume's depth or an array's layers are no 2D texture's. +#[test] +fn sizes_of_unknown_dimensions_stay_untranslated() { + let width = [ + 0x9004_9E09, // s_lshr_b32 s4, s9, 30 + 0x8F05_820A, // s_lshl_b32 s5, s10, 2 + 0x8804_0504, // s_or_b32 s4, s4, s5 + ]; + let words = [TABLE, FROM_HEAP, &width, STORE].concat(); + assert!(build(&words, (8, 0)).is_err()); + let depth = [ + 0x8805_0C05, // s_or_b32 s5, s5, s12 + ]; + let words = [TABLE, FROM_HEAP, SIZES, &depth, STORE].concat(); + assert!(build(&words, (8, 0)).is_err()); +} + +/// A water simulation step runs only while a structured buffer is bound: +/// it tests the record count of a view it never reads. +#[test] +fn the_record_count_of_a_structured_buffer_nothing_reads() { + let words = [TABLE, COUNT, STORE].concat(); + let shader = build(&words, (4, 16)).expect("translates"); + let (data, texel) = ([0u32; 12], [[0.0; 4]; 1]); + // The runtime makes structured views raw. + let views = [ + View::Buffer { + data: &data, + stride: Stride::Raw, + }, + View::Texture(1, 1, &texel), + View::RawUav(2), + ]; + for (label, got) in run(&shader, &views) { + assert_eq!(got[..2], [3, 0], "{label}"); + } + // A stride of 4 or less may be a typed view's component count. + assert!(build(&words, (4, 4)).is_err()); + assert!(build(&words, (4, 0)).is_err()); +} + +/// As [`the_record_count_of_a_structured_buffer_nothing_reads`], of one the +/// program also reads by index. +#[test] +fn the_record_count_of_a_structured_buffer_read_by_index() { + let load = [ + 0x7E06_0280, // v_mov_b32 v3, 0 + 0xE030_2000, // buffer_load_dword v5, v3, s[8:11], 0 idxen + 0x8002_0503, + 0x7E0A_0505, // v_readfirstlane_b32 s5, v5 + ]; + let words = [TABLE, COUNT, &load, STORE].concat(); + let shader = build(&words, (4, 16)).expect("translates"); + let (mut data, texel) = ([0u32; 12], [[0.0; 4]; 1]); + data[0] = 77; + let views = [ + View::Buffer { + data: &data, + stride: Stride::Raw, + }, + View::Texture(1, 1, &texel), + View::RawUav(2), + ]; + for (label, got) in run(&shader, &views) { + assert_eq!(got[..2], [3, 77], "{label}"); + } +} + +/// An upscaler counts its groups in a texture with atomics and sets the +/// counter back with a store of one channel, 16 bits wide. +#[test] +fn a_counter_texture_is_set_by_a_store_of_one_channel() { + let program = |store: [u32; 2], value: u32| { + let words = [ + 0xF40C_0201u32, // s_load_dwordx8 s[8:15], s[2:3], 0 + 0xFA00_0000, + 0x7E00_0280, // v_mov_b32 v0, 0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x7E04_0283, // v_mov_b32 v2, 3 + 0xF044_3108, // image_atomic_add v2, v[0:1], s[8:15] dmask:0x1 2D glc + 0x0002_0200, + value, // v_mov_b32 v3, .. + store[0], + store[1], + 0x7E08_0281, // v_mov_b32 v4, 1 + 0xF044_3108, // image_atomic_add v4, v[0:1], s[8:15] dmask:0x1 2D glc + 0x0002_0400, + 0xBE84_0380, // s_mov_b32 s4, 0 + 0xBE85_0380, // s_mov_b32 s5, 0 + ]; + build(&[TABLE, &words, STORE].concat(), (8, 0)) + }; + // image_store v3, v[0:1], s[8:15] dmask:0x1 2D, with and without d16 + for store in [[0xF020_1108, 0x0002_0300], [0xF020_1108, 0x8002_0300]] { + let shader = program(store, 0x7E06_0289).expect("translates"); // v3 = 9 + let texel = [[0.0; 4]; 1]; + let views = [ + View::UintTextureUav(1, 1), + View::Texture(1, 1, &texel), + View::RawUav(2), + ]; + for (label, got) in run(&shader, &views) { + assert_eq!(got[0], 10, "{label}"); + } + } + // Sixteen bits of a number only the card knows may be signed. + assert!(program([0xF020_1108, 0x8002_0300], 0x7E06_0302).is_err()); // v3 = v2 + // A store of two channels says nothing about the view. + assert!(program([0xF020_1308, 0x0002_0300], 0x7E06_0289).is_err()); +} diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 365883a..31dadd6 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -97,7 +97,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader { /// Runs `shader` with `views` at heap indices 0.. (the UAV last) on the /// hardware GPU and on WARP (each skipped without a device) and returns, /// per one that ran, the UAV's 32 dwords. -fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { +pub(super) fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { let samplers = [D3D12_SAMPLER_DESC { Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index db82f33..1bdd117 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -199,6 +199,162 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]); } +/// "Some lane is left" of a mask operation as a number: an upscaler's programs wait for +/// other groups in a loop that ends when every lane saw its flag, or after enough rounds: +/// both tests become -1 or 0 and SCC of `timeout | ~waiting` ends it. +#[test] +fn some_lane_of_a_mask_is_a_number_the_whole_wave_agrees_on() { + let native = native(&[ + 0xD765_0001, + 0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0xD766_0001, + 0x0002_02C1, // v_mbcnt_hi_u32_b32 v1, -1, v1 + 0x7D84_0200, // v_cmp_eq_u32 vcc, s0, v1 + 0x8792_7E6A, // s_and_b64 s[18:19], vcc, exec + 0x8592_80C1, // s_cselect_b64 s[18:19], -1, 0 + 0xBF09_8501, // s_cmp_ge_u32 s1, 5 + 0x8594_80C1, // s_cselect_b64 s[20:21], -1, 0 + 0x8B92_1214, // s_orn2_b64 s[18:19], s[20:21], s[18:19] + 0x8506_8081, // s_cselect_b32 s6, 1, 0 + 0x7E04_0206, // v_mov_b32 v2, s6 + 0xE070_0000, + 0x8002_0200, // buffer_store_dword v2, off, s[8:11], 0 + ]); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = on_64_lanes(&native, &p); + // (lane s0 waits, if there is one; s1 rounds) + for (wait, rounds, done) in [(0, 0, 0), (37, 4, 0), (63, 4, 0), (64, 0, 1), (37, 5, 1), (64, 9, 1)] { + let Some(out) = dispatched(&shader, &[wait, rounds]) else { + return; + }; + assert_eq!(out, done, "lane {wait} after {rounds} rounds"); + } +} + +/// `native` for a host of 64-lane waves. +fn on_64_lanes(native: &NativeProgram, p: &ir::Program) -> HostShader { + let st = structure::structure(p).expect("structure"); + let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(p, native).expect("io::raise"); + let was = lower::TEST_HOST_WAVE.replace(Some(64)); + let lowered = lower::lower(&lower::Parts { + native, + p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + lower::TEST_HOST_WAVE.set(was); + let lowered = lowered.expect("lower"); + assert_eq!(lowered.wave_size, Some(64)); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + shader +} + +/// Dword 0 of the UAV after `shader` ran with root constants `constants`; none without a +/// device that takes it. +fn dispatched(shader: &HostShader, constants: &[u32]) -> Option { + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return None; + }; + let (root, pso) = match host.compute_pipeline(shader) { + Ok(x) => x, + Err(e) => { + eprintln!("the hardware device does not take this program (waves of 64?): {e}; not run"); + return None; + } + }; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if u.root == RootType::Constants { + ud[u.index as usize] = constants.get(u.dword as usize).copied().unwrap_or(0); + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + Some(out[0][0]) +} + +/// The same sum inside `if (t >= s0) { ... }` on a host of 64-lane waves: the lanes below s0 +/// are elsewhere, and count as +0 in the console's tree. +#[test] +fn a_sum_of_halves_where_not_every_lane_runs_on_a_wave_of_64() { + let mut words = vec![ + 0x340C_0085, // v_lshlrev_b32 v6, 5, v0 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 + 0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7 + 0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7 + 0x4A0E_0EFF, + 0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7 + 0x7D86_0000, // v_cmp_le_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF88_0000 | 23, // s_cbranch_execz to the restore of EXEC + ]; + words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w })); + words.extend_from_slice(&[ + 0x7E00_0207, // v_mov_b32 v0, s7 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + ]); + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = on_64_lanes(&native, &p); + let wide = |h: u16| match h { + 0 => 0.0, + h => f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13), + }; + let narrow = |f: f32| { + if f == 0.0 { + return 0; + } + let b = f.to_bits(); + let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF); + let rest = b & 0x1FFF; + (h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16 + }; + for from in [0u32, 1, 5, 31, 32, 37, 63] { + let mut tree: Vec = (0..64u16).map(|t| if u32::from(t) < from { 0 } else { 0x3C00 + 37 * t }).collect(); + while tree.len() > 1 { + tree = tree.chunks(2).map(|c| narrow(wide(c[0]) + wide(c[1]))).collect(); + } + let Some(out) = dispatched(&shader, &[from]) else { + return; + }; + assert_eq!(out, u32::from(tree[0]), "lanes from {from}"); + } +} + /// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2 /// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The /// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 0b8fd9c..5b659e3 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -242,6 +242,9 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result; 256] = [None; 256]; // the last such use let mut used = [false; 128]; let mut parks: Vec> = Vec::with_capacity(list.len()); let mut written: Vec> = Vec::with_capacity(list.len()); @@ -314,7 +317,7 @@ fn unspill( match reg { Reg::S(c) => used[usize::from(c)] = true, Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true, - Reg::V(r) => other[usize::from(r)] = true, + Reg::V(r) => other[usize::from(r)] = Some(parks.len()), Reg::Scc => {} } } @@ -323,16 +326,33 @@ fn unspill( written.push(codes); read.push(from); } - for (i, park) in parks.iter_mut().enumerate() { - if park.is_some_and(|p| other[usize::from(p.1)]) { - *park = None; + let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok(); + for reg in 0..256 { + let Some(last) = other[reg] else { continue }; + let of = |p: &Option<(bool, u8, u8, u32)>| p.filter(|p| usize::from(p.1) == reg); + let first = parks.iter().position(|p| of(p).is_some_and(|p| p.0)); + let late = first.is_some_and(|first| { + let end = parks.iter().rposition(|p| of(p).is_some()).unwrap_or(first); + let mut saved = Vec::new(); + last < first + && !(first + 1..=end).any(leader) + && parks[first..=end].iter().filter_map(of).all(|(save, _, _, lane)| { + if save { + saved.push(lane); + } + saved.contains(&lane) + }) + }); + let from = if late { first.unwrap_or(0) } else { parks.len() }; + for park in &mut parks[..from] { + if of(park).is_some() { + *park = None; + } } - let _ = i; } if parks.iter().all(Option::is_none) { return Vec::new(); } - let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok(); // Lane pairs (register, lower lane) that always move together: each // save of the lower lane is followed, in the same block and before its // register changes, by the save of the next register into the next diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index d63d2b3..6ef558c 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -2611,6 +2611,42 @@ pub(crate) mod tests { assert_eq!(r.scalar, [((0, 3), at(0, 0x20))]); } + /// A VGPR a wave reduction used is free again after it: from the first + /// save on it holds parked scalars alone (an upscaler program parks a + /// constant buffer's descriptor that way). + #[test] + fn a_vgpr_used_before_holds_spilled_sgprs_from_its_first_save() { + let before = [ + 0x7E00_0281, // v_mov_b32 v0, 1 + 0x7E02_0300, // v_mov_b32 v1, v0 + ]; + let park = [ + 0xD761_0000, + 0x0001_0609, // v_writelane_b32 v0, s9, 3 + 0xD760_0002, + 0x0001_0700, // v_readlane_b32 s2, v0, 3 + 0xBE83_0380, // s_mov_b32 s3, 0 + ]; + let load = [ + 0xF40C_0001, + 0xFA00_0020, // s_load_dwordx8 s[0:7], s[2:3], 0x20 + S_ENDPGM, + ]; + let words = [&before[..], &park, &load].concat(); + let r = track_words(&words, &[param(Table, 9, 1)], HwStage::Ps); + assert_eq!(r.scalar, [((0, 5), at(0, 0x20))]); + // Still lane reads: a lane restored before it is saved, and a + // register with an ordinary use after the first save. + let restored_first = [&before[..], &park[2..4], &park[..2], &load].concat(); + let used_after = [&before[..], &park, &before[1..], &load].concat(); + for words in [restored_first, used_after] { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, true, 8).unwrap(); + let insts = p.blocks.iter().flat_map(|b| &b.insts); + assert_eq!(insts.filter(|i| i.name() == "v_readlane_b32").count(), 1); + } + } + #[test] fn descriptors_joined_by_control_flow_are_traced_per_edge() { let r = track_words( From 2aa8134b59161ab0f23b24d4b2aaea3b311d6181 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 22:03:45 -0600 Subject: [PATCH 165/445] Lighter refreshes of host copies; landing past the guards; the heap pass spread VICTORY_LIGHT_REFRESH (on): view memory nothing wrote since the last asking is known by a bit a block, copies nothing of which changed wake no thread, the ends of a range are not copied at every refresh, long copies are split. VICTORY_LAND_WINDOW=1: what shaders wrote goes into guarded title memory through a view of ours of the section, the guard stays. VICTORY_SEND_CHANGED=1: pages taken again go up to the card where they differ. VICTORY_HEAP_SPREAD (on): a sixteenth of the heap's slots at every pass. Three log lines split the preparing, the askings and the heap pass. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 7 + crates/victory-gpu/src/draw.rs | 155 +++++- crates/victory-gpu/src/host.rs | 545 +++++++++++++++++++++- crates/victory-gpu/src/inplace.rs | 30 ++ crates/victory-gpu/src/lib.rs | 2 +- crates/victory-gpu/src/safecopy.rs | 143 +++++- crates/victory-gpu/src/shadow.rs | 305 +++++++++++- crates/victory-gpu/src/watch.rs | 420 ++++++++++++++++- crates/victory-hle/src/modules/xmem.rs | 1 + 9 files changed, 1549 insertions(+), 59 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 2b065a2..a067acc 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1047,6 +1047,13 @@ impl HostHeap { buffers.iter().copied().collect() } + /// 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() + } + /// The title slots whose buffer view was written, or went, since the /// last call. pub(crate) fn buffer_changes(&self) -> Vec { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 7d290a3..712298b 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -365,6 +365,126 @@ pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0); /// index ([`State::heap_buffers`]), and the microseconds they took. pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0); pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0); +/// Of the passes, nanoseconds since the last frame line: looking at slots, +/// the spans and refreshes of their copies, the texture side. +#[cfg(feature = "diagnostics")] +pub(crate) static HEAP_SPLIT: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +/// Passes after which every buffer slot of the heap was looked at again. +const HEAP_ROUND: u64 = 16; + +/// Whether the slots looked at again for no write are a part of them at +/// every pass, each slot at every sixteenth (`VICTORY_HEAP_SPREAD=0`: all of +/// them at every sixteenth pass, as before). +/// +/// All at once was some 115 ms on a thread that records the frame, every +/// sixteenth frame (72,000 slots; run record-1: 11 ms a pass in the lines +/// without such a pass, 22 in those of ten frames with one). A slot is +/// looked at as often as before. +fn heap_spread() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SPREAD").is_none_or(|v| v != "0")) +} + +/// The host copy and range the buffer view of each of a heap's slots reads +/// ([`State::heap_buffers`]), by slot. +#[derive(Default)] +struct HeapRanges(Vec>); + +impl HeapRanges { + fn set(&mut self, slot: u32, range: Option<(T, u64, u64)>) { + let slot = slot as usize; + if range.is_none() && slot >= self.0.len() { + return; + } + if slot >= self.0.len() { + self.0.resize_with(slot + 1, || None); + } + self.0[slot] = range; + } + + /// Forgets the slots of one of `parts` parts + /// (`HostHeap::buffer_slots_of`). + fn forget_part(&mut self, part: u32, parts: u32) { + self.0.iter_mut().skip(part as usize).step_by(parts as usize).for_each(|r| *r = None); + } + + fn ranges(&self) -> impl Iterator { + self.0.iter().flatten() + } +} + +#[cfg(test)] +mod heap_range_tests { + use super::{HEAP_ROUND, HeapRanges}; + + /// Round by round every slot is looked at again once, whatever was + /// written between, and what a slot holds is what was found last. + #[test] + fn every_slot_is_looked_at_again_in_a_round() { + const SLOTS: u32 = 1000; + let mut ranges = HeapRanges(Vec::new()); + ranges.set(7, None); + assert_eq!(ranges.ranges().count(), 0); + for slot in (0..SLOTS).step_by(3) { + ranges.set(slot, Some(((), 0, 1))); + } + let parts = HEAP_ROUND as u32; + for pass in 1..=HEAP_ROUND { + let part = (pass % HEAP_ROUND) as u32; + ranges.forget_part(part, parts); + for slot in (0..SLOTS).step_by(3).filter(|slot| slot % parts == part) { + assert!(ranges.0[slot as usize].is_none(), "slot {slot} not forgotten"); + ranges.set(slot, Some(((), pass, pass))); + } + assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize); + } + assert!(ranges.ranges().all(|r| r.1 != 0), "a slot not looked at in a round"); + ranges.set(3, None); + assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize - 1); + } + + /// The spans of 4,400 copies from the ranges of 72,000 slots, as a pass + /// makes them, by slot and from the table they were in. Run with + /// `--ignored --nocapture`. + #[test] + #[ignore] + fn spans_of_a_pass() { + use std::collections::HashMap; + use std::sync::Arc; + let copies: Vec> = (0..4400).map(Arc::new).collect(); + let (mut table, mut slots) = (HashMap::new(), HeapRanges(Vec::new())); + for slot in 0..72_000u32 { + let copy = &copies[slot as usize * 7919 % 4400]; + table.insert(slot, (copy.clone(), u64::from(slot), u64::from(slot) + 64)); + slots.set(slot, Some((copy.clone(), u64::from(slot), u64::from(slot) + 64))); + } + fn join(ranges: &mut dyn Iterator, u64, u64)>) -> usize { + let mut spans: HashMap, u64, u64), S> = HashMap::default(); + for (copy, from, to) in ranges { + let span = spans.entry(Arc::as_ptr(copy) as usize).or_insert_with(|| (copy.clone(), *from, *to)); + span.1 = span.1.min(*from); + span.2 = span.2.max(*to); + } + spans.len() + } + let best = |f: &mut dyn FnMut() -> usize| { + (0..30) + .map(|_| { + let t = std::time::Instant::now(); + assert_eq!(f(), 4400); + t.elapsed().as_secs_f64() * 1e3 + }) + .fold(f64::MAX, f64::min) + }; + println!( + "{:.2} ms from the table, {:.2} ms by slot", + best(&mut || join::(&mut table.values())), + best(&mut || join::>(&mut slots.ranges())), + ); + } +} + /// Textures brought up to date for shaders that pick them by index /// ([`State::heap_textures`]), the bytes of their memory, and the slots /// still waiting. @@ -1368,18 +1488,25 @@ impl State { // at best); all of them every 16 passes, because a view of a // released resource goes stale without a write, and a slot written // before its memory had a host copy is only made then. - type Ranges = std::collections::HashMap, u64, u64)>; + type Ranges = HeapRanges>; static RANGES: std::sync::Mutex>> = std::sync::Mutex::new(None); let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); let (passes, ranges) = kept .get_or_insert_with(Default::default) .entry(std::ptr::from_ref(host) as usize) - .or_insert_with(|| (0, Ranges::new())); + .or_insert_with(|| (0, HeapRanges(Vec::new()))); let changed = host.buffer_changes(); - let slots = if *passes % 16 == 0 { - ranges.clear(); + let slots = if *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread()) { + ranges.0.clear(); host.buffer_slots() + } else if heap_spread() { + // The written ones, and this pass's part of the others. + let (part, parts) = ((*passes % HEAP_ROUND) as u32, HEAP_ROUND as u32); + ranges.forget_part(part, parts); + let mut slots = host.buffer_slots_of(part, parts); + slots.extend(changed); + slots } else { changed }; @@ -1389,7 +1516,7 @@ impl State { 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(); for (n, &index) in slots.iter().enumerate() { - ranges.remove(&index); + ranges.set(index, None); let Some(handle) = heap.handle(index) else { continue; }; @@ -1420,13 +1547,15 @@ impl State { if host.shows(index, &shadow.buffer) == Some(false) { HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed); } - ranges.insert(index, (shadow, address, address + len)); + ranges.set(index, Some((shadow, address, address + len))); } - let views = ranges.len() as u32; + #[cfg(feature = "diagnostics")] + let looked = std::time::Instant::now(); // Per host copy, the span its picked views cover. - let mut spans: std::collections::HashMap, u64, u64)> = - std::collections::HashMap::new(); - for (shadow, from, to) in ranges.values() { + let mut spans: crate::host::ByCopy<(std::sync::Arc, u64, u64)> = Default::default(); + let mut views = 0u32; + for (shadow, from, to) in ranges.ranges() { + views += 1; let key = std::sync::Arc::as_ptr(shadow) as usize; let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to)); span.1 = span.1.min(*from); @@ -1466,7 +1595,13 @@ impl State { } shadow.refresh(list, *from, to - from); } + #[cfg(feature = "diagnostics")] + let refreshed = std::time::Instant::now(); self.heap_textures(list, heap, host); + #[cfg(feature = "diagnostics")] + for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked, refreshed.elapsed()]) { + sum.fetch_add(time.as_nanos() as u64, Ordering::Relaxed); + } HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); static LOGGED: AtomicU64 = AtomicU64::new(0); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4ae7669..a580438 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4176,6 +4176,8 @@ impl Host { // Where each run's lists start in `lists`. let mut firsts = Vec::with_capacity(runs.len()); let mut batch = Batch::default(); + #[cfg(feature = "diagnostics")] + let split = Split::begin(); // The time a settle of flights takes inside this preparing: the // wait for the card and the copy-back have their own places on the // frame line (run 92 showed them twice, "preparing" 250 ms for 135). @@ -4183,7 +4185,7 @@ impl Host { // One write-watch asking for everything the submission refreshes // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges. if crate::watch::once() { - let mut spans: std::collections::HashMap = std::collections::HashMap::new(); + let mut spans: ByCopy<(usize, usize)> = ByCopy::default(); for list in runs { for step in &list.deferred().copies { if let Step::Refresh(shadow, address, len) = step @@ -4198,6 +4200,8 @@ impl Host { } let ranges: Vec<(usize, usize)> = spans.into_values().collect(); crate::watch::ask_once(&ranges); + #[cfg(feature = "diagnostics")] + split.part(0); // Behind flights: the title wrote memory that a flight's shaders // may write too, and this submission refreshes it. The flights // are settled, and the asking made again: the copy-back wrote @@ -4213,6 +4217,8 @@ impl Host { self.settle(&mut submitted, WHY_STALE); settled += settling.elapsed(); } + #[cfg(feature = "diagnostics")] + split.part(1); for list in runs { list.run_deferred(&mut batch); firsts.push(lists.len()); @@ -4223,6 +4229,8 @@ impl Host { } batch.flush(); crate::watch::ask_once_end(); + #[cfg(feature = "diagnostics")] + split.part(2); // The snapshots of the ranges shaders may write, if they were left // for now (`crate::shadow::wide_back`): the refreshes are done, the // lists have not gone to the card. @@ -4233,6 +4241,8 @@ impl Host { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64); } + #[cfg(feature = "diagnostics")] + split.part(3); // Copies in the card's memory: what changed on their CPU side goes // up ahead of the lists, and a compare of what the shaders may // write follows them in the same submission. @@ -4246,6 +4256,8 @@ impl Host { if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) { lists.push(Some(check)); } + #[cfg(feature = "diagnostics")] + split.part(4); let prepared = std::time::Instant::now(); if late { *submitted += 1; @@ -4258,6 +4270,8 @@ impl Host { if let Err(e) = signalled { fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); } + #[cfg(feature = "diagnostics")] + split.part(5); let back = declared_writes(runs); 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); @@ -5471,40 +5485,46 @@ impl HostList { fn run_deferred(&self, batch: &mut Batch) { #[cfg(feature = "diagnostics")] use crate::copystat::{C, add}; + // The time and the bytes of the copies and fills, some 13,000 a + // frame between 20,000 refreshes: summed here and added once. + let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64); + #[cfg(feature = "diagnostics")] + let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64); for step in &self.deferred().copies { - let started = std::time::Instant::now(); - let copied = match step { + let (started, copied) = match step { &Step::Copy(dst, src, len) => { + let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] { - add(C::Copies, 1); - add(C::CopyBytes, len as u64); + copies += 1; } batch.title_written(); copy_mapped(dst as *mut u8, src as *const u8, len, true); // With the submission's one asking: the journal learns it. crate::watch::wrote(dst, len); - len + (started, len) } &Step::Fill(dst, src, len) => { + let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] { - add(C::Copies, 1); - add(C::CopyBytes, len as u64); + copies += 1; } copy_mapped(dst as *mut u8, src as *const u8, len, false); - len + (started, len) } Step::Refresh(shadow, address, len) => { #[cfg(feature = "diagnostics")] { - add(C::Refreshes, 1); - add(C::RefreshBytes, *len as u64); + refreshes += 1; + refreshed += *len as u64; } batch.add(shadow, *address, *len); continue; } Step::Run(work) | Step::Host(work) => { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); if matches!(step, Step::Run(_)) { batch.title_written(); } @@ -5545,12 +5565,132 @@ impl HostList { continue; } }; - PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); - PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + us += started.elapsed(); + bytes += copied as u64; + } + PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed); + PREPARING[1].fetch_add(bytes, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + { + add(C::Copies, copies); + add(C::CopyBytes, bytes); + add(C::Refreshes, refreshes); + add(C::RefreshBytes, refreshed); + SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed); } } } +/// A table by a copy's address. +pub(crate) type ByCopy = std::collections::HashMap>; + +/// A hash for addresses of ours: the bits that tell them apart, spread. The +/// tables it serves are asked 40,000 times a frame, and hold no one's keys +/// but our own. +#[derive(Default)] +pub(crate) struct AddressHash(u64); + +impl std::hash::Hasher for AddressHash { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.write_usize(usize::from(b)); + } + } + fn write_usize(&mut self, n: usize) { + let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15); + self.0 = h ^ (h >> 32); + } +} + +/// Since the last frame-rate line, nanoseconds of the submitting thread's +/// preparing: the write-watch asking for a submission; the title's bytes put +/// in under flights' writes; the lists' steps, the refreshes among them; the +/// snapshots; what goes to copies in the card's memory; the lists sent; and +/// of the steps: the refreshes, and the copies and fills (those with the +/// refreshes a copy of title memory flushes). +#[cfg(feature = "diagnostics")] +static SPLIT: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8]; + +/// Since the last frame-rate line: flushes of refreshes, their refreshes, +/// those known to copy nothing, and those done on several threads. +#[cfg(feature = "diagnostics")] +static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Counts into [`SPLIT`]. +#[cfg(feature = "diagnostics")] +struct Split(std::cell::Cell); + +#[cfg(feature = "diagnostics")] +impl Split { + fn begin() -> Split { + Split(std::cell::Cell::new(std::time::Instant::now())) + } + + /// What came since the last part was part `i`. + fn part(&self, i: usize) { + let now = std::time::Instant::now(); + SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed); + } +} + +/// The split of the preparing, per frame, for the frame-rate line. +#[cfg(feature = "diagnostics")] +fn split_line(frames: f64) { + let ms: Vec = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); + let f: Vec = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let a: Vec = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect(); + let h: Vec = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); + let s: Vec = crate::shadow::send_stats().iter().map(|&n| n as f64 / (1 << 20) as f64 / frames).collect(); + tracing::info!( + "preparing per frame, the submitting thread: {:.1} ms asking the write watch, {:.1} putting the title's bytes under flights' \ + writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \ + several threads; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \ + card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})", + ms[0], + ms[1], + ms[2], + ms[6], + f[0], + f[1], + f[2], + f[3], + ms[7], + ms[3], + ms[4], + ms[5], + if crate::watch::light() { "on" } else { "off" }, + ); + tracing::info!( + "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB; view ranges: {:.0} answered by their \ + bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves ({:.0} pieces \ + put past the guards, VICTORY_LAND_WINDOW); {:.1} ms \ + waiting for the guards, {:.1} ms changing protections; pages taken again for the card: {:.1} MB compared, {:.1} MB of them \ + as they were, {:.1} MB to go up (VICTORY_SEND_CHANGED)", + a[0], + a[1] / 1024.0, + a[2], + a[3], + a[4], + a[5], + a[6], + a[9], + a[7] / 1e6, + a[8] / 1e6, + s[0], + s[1], + s[2], + ); + tracing::info!( + "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures", + h[0], + h[1], + h[2], + ); +} + /// Whether a submission's refreshes of host copies run on several threads, /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it). /// @@ -5612,7 +5752,7 @@ struct Batch { /// the heap's buffers ready adds some 4,100 copies, and searching them /// for every refresh of a submission was tens of millions of /// comparisons a frame. - index: std::collections::HashMap, + index: ByCopy, /// Staging buffers (by address) refreshed since the last title write. textures: std::collections::HashSet, } @@ -5644,7 +5784,13 @@ impl Batch { if let Some(moved) = self.refreshes.get(at) { self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at); } - Self::update(&shadow, from, to); + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + if !(crate::watch::light() && shadow.nothing_new(from, to - from)) { + Self::update(&shadow, from, to); + } + #[cfg(feature = "diagnostics")] + SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); } /// Brings `[from, to)` of a copy up to date, timed. @@ -5673,6 +5819,36 @@ impl Batch { fn flush(&mut self) { self.index.clear(); + if self.refreshes.is_empty() { + return; + } + #[cfg(feature = "diagnostics")] + let (began, all) = (std::time::Instant::now(), self.refreshes.len()); + self.flush_all(); + #[cfg(feature = "diagnostics")] + { + SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed); + FLUSHES[0].fetch_add(1, Ordering::Relaxed); + FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed); + } + } + + fn flush_all(&mut self) { + // Most of a flush's copies are as they were: they are told so here, + // from what the submission's asking found, before anything is asked + // and any thread woken. (Thousands of them, the heap's buffer views + // once a frame: on the threads, below.) + const FEW: usize = 256; + let light = crate::watch::light(); + if light && self.refreshes.len() <= FEW { + let started = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + let all = self.refreshes.len(); + self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed); + } // One write-watch asking for the copies that lie close together, // not one per copy. let ahead = self.refreshes.len() > 1; @@ -5693,12 +5869,28 @@ impl Batch { // The time counted is the time it took, not the threads' sum. let started = std::time::Instant::now(); let before = PREPARING[0].load(Ordering::Relaxed); - let jobs: Vec> = self - .refreshes - .drain(..) - .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box) - .collect(); - crate::shadow::wide_run(jobs); + #[cfg(feature = "diagnostics")] + FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed); + if light { + // A number to a free thread, not a job to each copy. + let refreshes = std::mem::take(&mut self.refreshes); + crate::shadow::wide_each(refreshes.len(), move |i| { + let (shadow, from, to) = &refreshes[i]; + if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) { + #[cfg(feature = "diagnostics")] + FLUSHES[2].fetch_add(1, Ordering::Relaxed); + return; + } + Self::update(shadow, *from, *to); + }); + } else { + let jobs: Vec> = self + .refreshes + .drain(..) + .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box) + .collect(); + crate::shadow::wide_run(jobs); + } let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before); PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed); } else { @@ -6116,6 +6308,8 @@ impl Meter { late_line(frames); card_clock_line(frames, ms); crate::shadow::back_line(frames); + #[cfg(feature = "diagnostics")] + split_line(frames); { let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); if passes + compares > 0.0 { @@ -6853,6 +7047,315 @@ mod spare { } } +#[cfg(test)] +mod refresh_tests { + use super::Batch; + use crate::shadow::Shadow; + use std::sync::Arc; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE, + VirtualAlloc, + }; + + const PAGE: usize = 64 << 10; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + /// Title memory for the tests (never given back: copies of it stay in + /// the guards): write-watched, or a view of a section. + fn title(len: usize, view: bool) -> usize { + // SAFETY: plain allocations. + let at = unsafe { + if view { + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null()); + let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize; + // As the runtime tells of it. + crate::title_memory_section(section as usize, len as u64, true); + crate::title_memory_remapped(at, len); + crate::title_memory_view(at, len, section as usize, 0); + at + } else { + VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize + } + }; + assert_ne!(at, 0); + at + } + + fn memory(len: usize) -> *mut u8 { + // SAFETY: a plain allocation. + unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() } + } + + struct Random(u64); + + impl Random { + fn below(&mut self, n: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 >> 11) as usize % n + } + } + + /// Prepares as a submission does: one asking for all the ranges, the + /// refreshes in several flushes, the asking's end. + fn submission(ranges: &[(Arc, usize, usize)], flushes: usize) { + // One at a time, as submissions are. + static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); + let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect(); + crate::watch::ask_once(&asked); + let mut batch = Batch::default(); + for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) { + for (shadow, at, len) in part { + batch.add(shadow, *at, *len); + } + batch.flush(); + } + crate::watch::ask_once_end(); + } + + /// Whatever is written where, by the title or by us, and whichever + /// copies (of both kinds of memory, over one another, none on a page + /// line) are refreshed in which ranges: a refreshed range holds what + /// title memory holds. + #[test] + fn refreshed_ranges_hold_title_memory() { + // SAFETY (all blocks): title memory and copies of the test's own, + // written by this thread and, in `Batch::flush`, by the threads that + // refresh, which are done when it returns. + let mut random = Random(0x1234_5678_9ABC_DEF1); + const LEN: usize = 24 * PAGE; + let regions = [title(LEN, false), title(LEN, true)]; + let mut copies = Vec::new(); + for ®ion in ®ions { + for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] { + let data = memory(to - from); + copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data)); + } + } + let byte = |at: usize| unsafe { (at as *const u8).read_volatile() }; + for round in 0..600 { + for _ in 0..random.below(4) { + let at = regions[random.below(2)] + random.below(LEN - 64); + let n = 1 + random.below(60); + if random.below(3) == 0 { + // What shaders wrote. + let was: Vec = (0..n).map(|i| byte(at + i)).collect(); + let now: Vec = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect(); + Shadow::put(at, &was, &now); + assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put"); + continue; + } + for i in 0..n { + unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) }; + } + } + let mut ranges = Vec::new(); + for (shadow, _) in &copies { + if random.below(3) == 0 { + continue; + } + let (start, len) = shadow.span(); + let (start, len) = (start as usize, len as usize); + // Often the range of the time before, as a list's is. + let from = if random.below(2) == 0 { 0 } else { random.below(len) }; + let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) }; + ranges.push((shadow.clone(), start + from, n)); + } + if ranges.is_empty() { + continue; + } + let flushes = 1 + random.below(3); + submission(&ranges, flushes); + for (shadow, at, n) in &ranges { + let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1; + let start = shadow.span().0 as usize; + let same = unsafe { + std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n) + }; + assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at)); + } + } + } + + /// A range nothing wrote is known to be as it was, at its ends too, and + /// is so no more once something wrote it. + #[test] + fn unchanged_ranges_are_known() { + for view in [false, true] { + let region = title(8 * PAGE, view); + // (A page read for the first time counts as written.) + // SAFETY: the test's own memory. + unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) }; + let data = memory(8 * PAGE); + let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false); + // Ends in the middle of pages. + let (at, len) = (region + 500, 5 * PAGE); + let look = |expected: bool, what: &str| { + // The submission's one asking, which takes two ranges. (Again + // if a submission of another test ended it.) + let mut known = false; + for _ in 0..100 { + crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]); + known = copy.nothing_new(at, len); + if known || !expected { + break; + } + } + assert_eq!(known, expected, "view {view}: {what}"); + let copied = copy.update(at, len); + crate::watch::ask_once_end(); + copied + }; + assert_eq!(look(false, "never taken"), len); + assert_eq!(look(true, "taken"), 0); + assert_eq!(look(true, "taken"), 0); + // SAFETY: the test's own memory. + unsafe { ((region + 600) as *mut u8).write_volatile(1) }; + assert_eq!(look(false, "written at its end"), PAGE - 500); + assert_eq!(look(true, "taken again"), 0); + // Outside the range, on its last page. + // SAFETY: as above. + unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) }; + assert_eq!(look(false, "written on its last page"), 500); + // A longer range was never taken whole. + assert!(!copy.nothing_new(region, 6 * PAGE)); + } + } + + /// A part of a copy in the card's memory taken again goes up only if it + /// differs (with `VICTORY_SEND_CHANGED=1`), whole when never taken. + #[test] + fn only_what_differs_goes_up() { + let region = title(4 * PAGE, true); + let data = memory(4 * PAGE); + let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true); + copy.update(region, 4 * PAGE); + assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change"); + // What the relay does: shader writes into title memory, and into the + // CPU's side. + crate::watch::landing(region + PAGE + 640, 64); + // SAFETY: the test's own memory. + unsafe { + std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64); + std::ptr::write_bytes(data.add(PAGE + 640), 7, 64); + } + copy.update(region, 4 * PAGE); + let again = copy.take_dirty(); + // SAFETY: as above. + unsafe { ((region + 2 * PAGE + 128) as *mut u8).write_volatile(9) }; + copy.update(region, 4 * PAGE); + let written = copy.take_dirty(); + if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") { + assert_eq!(again, []); + assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 192)]); + } else { + assert_eq!(again, [(PAGE, 2 * PAGE)]); + assert_eq!(written, [(2 * PAGE, 3 * PAGE)]); + } + // SAFETY: as above. + assert_eq!(unsafe { data.add(2 * PAGE + 128).read() }, 9); + } + + /// The refreshes of a frame as run record-1 had them: 30 submissions, the + /// first with a copy for each of 4,400 ranges, the others with 60 and a + /// big copy that 55 landed pieces and 9 title writes opened, while a + /// thread lands what shaders wrote. Run with `--ignored --nocapture`, + /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was. + #[test] + #[ignore] + fn frame_of_refreshes() { + let mut random = Random(0x9876_5432_1234_5671); + const EACH: usize = 224 << 10; + const BIG: usize = 174 << 20; + let watched = title(3000 * EACH, false); + let views = title(1400 * EACH, true); + let big = title(BIG, true); + // SAFETY: the test's own memory. + unsafe { + std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH); + std::ptr::write_bytes(views as *mut u8, 1, 1400 * EACH); + std::ptr::write_bytes(big as *mut u8, 1, BIG); + } + let mut small = Vec::new(); + for i in 0..4400 { + let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) }; + let data = memory(EACH); + // The range views read, not all of the copy. + small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000)); + } + let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG); + let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]); + let (mut sum, mut landing) = (0.0, 0.0); + const FRAMES: usize = 12; + for frame in 0..FRAMES { + let mut took = [0f64; 2]; + for i in 0..30 { + // The title's writes, and the relay's beside the submission. + for _ in 0..9 { + let at = views + random.below(1400 * EACH / 8) * 8; + // SAFETY: the test's own memory. + unsafe { (at as *mut u64).write_volatile(frame as u64) }; + } + for _ in 0..60 { + let at = watched + random.below(3000 * EACH / 8) * 8; + // SAFETY: the test's own memory. + unsafe { (at as *mut u64).write_volatile(frame as u64) }; + } + let first = random.below(BIG / PAGE - 60); + let land = std::thread::spawn(move || { + let mut took = 0.0; + for piece in first..first + 55 { + let mut was = vec![0; PAGE]; + assert!(super::read_into((big + piece * PAGE) as *const u8, &mut was)); + let mut now = was.clone(); + now[8..PAGE - 8].fill(frame as u8 ^ i as u8); + let started = std::time::Instant::now(); + Shadow::put(big + piece * PAGE, &was, &now); + took += started.elapsed().as_secs_f64() * 1e3; + } + took + }); + let ranges: Vec<(Arc, usize, usize)> = if i == 0 { + small.iter().cloned().chain([heap.clone()]).collect() + } else { + (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect() + }; + let started = std::time::Instant::now(); + submission(&ranges, 3); + took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3; + let put = land.join().unwrap(); + if frame >= 2 { + landing += put; + } + heap.0.take_dirty(); + } + if frame >= 2 { + sum += took[0] + took[1]; + for k in 0..2 { + best[k] = best[k].min(took[k]); + asking[k] += took[k]; + } + } + } + println!( + "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \ + others {:.2} (best {:.2}); the landing thread's puts {:.2}", + crate::watch::light(), + sum / (FRAMES - 2) as f64, + asking[0] / (FRAMES - 2) as f64, + best[0], + asking[1] / (FRAMES - 2) as f64, + best[1], + landing / (FRAMES - 2) as f64, + ); + #[cfg(feature = "diagnostics")] + println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64)); + } +} + #[cfg(test)] mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file use super::Batch; diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 25461df..2d3e27e 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -280,11 +280,41 @@ fn views() -> std::sync::MutexGuard<'static, Views> { /// 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) { + title_memory_section_gone(section); let mut v = views(); v.sections.retain(|s| s.0 != section); v.sections.push((section, bytes, committed)); } +/// Views of ours of whole sections, by the section's handle: where. +static WINDOWS: Mutex> = Mutex::new(BTreeMap::new()); + +/// The runtime lets go of a section, and of its handle: no view of it is +/// mapped any more. +pub fn title_memory_section_gone(section: usize) { + let window = WINDOWS.lock().unwrap_or_else(|e| e.into_inner()).remove(§ion); + if let Some(base) = window.filter(|&base| base != 0) { + // SAFETY: a view of ours. Who writes through it holds off the + // runtime's unmapping of the view it found the section by + // (`crate::watch::land_through`), which came before this. + unsafe { mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: base as *mut c_void }) }; + } +} + +/// Where a view of ours of all of `section` is, made when first asked for; +/// `None` if the host gives none. The caller holds off remapping +/// (`crate::title_memory_reading`) and found the section in a view the +/// runtime told us of, so the section lives. +pub(crate) fn window(section: usize) -> Option { + let bytes = views().sections.iter().find(|s| s.0 == section)?.1; + let mut windows = WINDOWS.lock().unwrap_or_else(|e| e.into_inner()); + let base = *windows.entry(section).or_insert_with(|| { + // SAFETY: a live section of that many bytes. + unsafe { mem::MapViewOfFile(section as *mut c_void, mem::FILE_MAP_WRITE, 0, 0, bytes as usize) }.Value as usize + }); + (base != 0).then_some(base) +} + /// The runtime mapped `[at, at + len)` as a view of `section` from /// `offset` on. Call after [`crate::title_memory_remapped`] of the range. pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 2ecf3ab..f09fac1 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -65,7 +65,7 @@ mod watch; #[cfg(windows)] pub use host::on_failure; #[cfg(windows)] -pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; +pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view}; #[cfg(windows)] pub use watch::{ title_memory_reading, title_memory_remapped, title_memory_remapping, writing as kernel_will_write, diff --git a/crates/victory-gpu/src/safecopy.rs b/crates/victory-gpu/src/safecopy.rs index 24eb646..3dd7bc2 100644 --- a/crates/victory-gpu/src/safecopy.rs +++ b/crates/victory-gpu/src/safecopy.rs @@ -75,6 +75,46 @@ std::arch::global_asm!( "vzeroupper", "xor eax, eax", "ret", + ".globl victory_safe_update", + ".globl victory_safe_update_at", + ".globl victory_safe_update_after", + ".globl victory_safe_update_failed", + // rcx destination, rdx source, r8 bytes (whole 64s, not none), r9 where + // the offset of the first 64 bytes that differed goes (-1: none did) and + // behind it the offset of the end of the last: stores the 64s that + // differ. eax: whether all could be read. + "victory_safe_update:", + "xor r10d, r10d", + "mov r11, -1", + "xor eax, eax", + "2:", + "victory_safe_update_at:", + "vmovdqu ymm0, ymmword ptr [rdx + r10]", + "vmovdqu ymm1, ymmword ptr [rdx + r10 + 32]", + "victory_safe_update_after:", + "vpxor ymm2, ymm0, ymmword ptr [rcx + r10]", + "vpxor ymm3, ymm1, ymmword ptr [rcx + r10 + 32]", + "vpor ymm2, ymm2, ymm3", + "vptest ymm2, ymm2", + "jz 3f", + "vmovdqu ymmword ptr [rcx + r10], ymm0", + "vmovdqu ymmword ptr [rcx + r10 + 32], ymm1", + "cmp r11, -1", + "cmove r11, r10", + "lea rax, [r10 + 64]", + "3:", + "add r10, 64", + "cmp r10, r8", + "jb 2b", + "mov qword ptr [r9], r11", + "mov qword ptr [r9 + 8], rax", + "vzeroupper", + "mov eax, 1", + "ret", + "victory_safe_update_failed:", + "vzeroupper", + "xor eax, eax", + "ret", ); unsafe extern "system" { @@ -86,6 +126,57 @@ unsafe extern "system" { fn victory_safe_put_at(); fn victory_safe_put_after(); fn victory_safe_put_failed(); + fn victory_safe_update(dst: *mut u8, src: *const u8, len: usize, changed: *mut [usize; 2]) -> u32; + fn victory_safe_update_at(); + fn victory_safe_update_after(); + fn victory_safe_update_failed(); +} + +/// What [`update`] found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Updated { + /// Every byte was the same already; nothing was stored. + Same, + /// The bytes that changed lie in these offsets. + Changed(usize, usize), + /// Not all of the source could be read; some may have been copied. + Failed, +} + +/// Makes `dst` hold what `src` holds, storing only what differs. The source +/// may change meanwhile: what is compared is what is stored, read once. +/// +/// # Safety +/// As [`copy`]'s, and the destination is memory of ours that nothing else +/// writes. +pub(crate) unsafe fn update(dst: *mut u8, src: *const u8, len: usize) -> Updated { + let whole = len / 64 * 64; + let (mut from, mut to) = (usize::MAX, 0); + if whole > 0 { + let mut changed = [usize::MAX, 0]; + // SAFETY: the source's faults leave through the failing exit; the + // rest is the caller's. + if unsafe { victory_safe_update(dst, src, whole, &mut changed) } == 0 { + return Updated::Failed; + } + [from, to] = changed; + } + if whole < len { + let mut rest = [0u8; 64]; + let rest = &mut rest[..len - whole]; + // SAFETY: as above; `rest` is ours. + unsafe { + if !copy(rest.as_mut_ptr(), src.add(whole), rest.len()) { + return Updated::Failed; + } + let held = std::slice::from_raw_parts_mut(dst.add(whole), rest.len()); + if held != rest { + held.copy_from_slice(rest); + (from, to) = (from.min(whole), len); + } + } + } + if from >= to { Updated::Same } else { Updated::Changed(from, to) } } /// Puts `now` at `dst` where it differs from `was`, whole dwords (as `dst` @@ -160,7 +251,11 @@ pub(crate) fn failing_exit(at: usize) -> Option { return Some(victory_safe_copy_failed as *const () as usize); } let (from, to) = (victory_safe_put_at as *const () as usize, victory_safe_put_after as *const () as usize); - (from..to).contains(&at).then_some(victory_safe_put_failed as *const () as usize) + if (from..to).contains(&at) { + return Some(victory_safe_put_failed as *const () as usize); + } + let (from, to) = (victory_safe_update_at as *const () as usize, victory_safe_update_after as *const () as usize); + (from..to).contains(&at).then_some(victory_safe_update_failed as *const () as usize) } #[cfg(test)] @@ -214,6 +309,52 @@ mod tests { } } + /// An update makes the two the same, says where they differed (to 64 + /// bytes), stores nothing where they did not, and fails at a page that + /// is not there. + #[test] + fn updates_store_what_differs() { + assert!(on()); + let (src, dst) = (Pages::new(1 << 14), Pages::new(1 << 14)); + for len in [0usize, 1, 63, 64, 65, 200, 4096, 5000] { + for (da, sa) in [(0usize, 0usize), (3, 0), (0, 5)] { + for changed in [vec![], vec![0usize], vec![len / 2], vec![len.saturating_sub(1)], vec![1, len / 3, len / 2]] { + src.fill(); + // SAFETY: inside the two allocations. + unsafe { + std::ptr::write_bytes(dst.0, 0xEE, dst.1); + std::ptr::copy_nonoverlapping(src.0.add(sa), dst.0.add(da), len); + let at: std::collections::BTreeSet = changed.iter().copied().filter(|&i| i < len).collect(); + for &i in &at { + *src.0.add(sa + i) ^= 0x40; + } + let found = update(dst.0.add(da), src.0.add(sa), len); + match (at.iter().min(), at.iter().max()) { + (Some(&first), Some(&last)) => { + let Updated::Changed(from, to) = found else { + panic!("{len} {at:?}: {found:?}") + }; + assert_eq!(from, first / 64 * 64); + assert_eq!(to, ((last / 64 + 1) * 64).min(len)); + } + _ => assert_eq!(found, Updated::Same), + } + let (to, from) = (std::slice::from_raw_parts(dst.0, dst.1), std::slice::from_raw_parts(src.0, src.1)); + assert_eq!(to[da..da + len], from[sa..sa + len]); + assert!(to[..da].iter().chain(&to[da + len..]).all(|&x| x == 0xEE)); + } + } + } + } + // SAFETY: our allocation. + unsafe { + VirtualFree(src.0.add(4096).cast(), 4096, MEM_DECOMMIT); + assert_eq!(update(dst.0, src.0, 8192), Updated::Failed); + assert_eq!(update(dst.0, src.0.add(4096), 10), Updated::Failed); + assert_ne!(update(dst.0, src.0, 4096), Updated::Failed); + } + } + /// The dwords that changed are stored, and no byte of any other, at /// every alignment and length; a page that is not there fails. #[test] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 68817e0..37363bd 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -35,6 +35,11 @@ pub(crate) struct Shadow { /// Per page of title memory from `start`'s on: the write-watch asking /// after which it was last copied (0: never). copied: Mutex>, + /// Two ranges of title memory taken whole, the last one and the longest, + /// and the asking after which each was ([`Shadow::copy_stale`]). A page + /// a range holds in part cannot say so in `copied`. Locked inside + /// `copied`'s lock. + ranged: Mutex<[(usize, usize, u64); 2]>, /// Whether the memory is write-watched: unknown, yes, no. watched: AtomicU8, /// Ranges shaders of a submission not yet copied back may be writing: @@ -1028,6 +1033,11 @@ struct Workers { more: std::sync::Condvar, } +/// How many threads are kept for [`wide`]. +fn wide_threads() -> usize { + std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6) +} + fn workers() -> &'static Workers { static WORKERS: std::sync::OnceLock = std::sync::OnceLock::new(); static STARTED: std::sync::Once = std::sync::Once::new(); @@ -1036,8 +1046,7 @@ fn workers() -> &'static Workers { more: std::sync::Condvar::new(), }); STARTED.call_once(|| { - let n = std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6); - for i in 0..n { + for i in 0..wide_threads() { let _ = std::thread::Builder::new().name(format!("victory-wide-{i}")).spawn(move || { let workers = WORKERS.get().expect("made above"); loop { @@ -1103,6 +1112,30 @@ pub(crate) fn wide_run(jobs: Vec>) { wide(jobs); } +/// Calls `work` with every number under `n`, on the kept threads and on +/// this one, the next number to whichever is free: for thousands of small +/// pieces of work, where a job each ([`wide`]) is mostly the jobs' queue. +pub(crate) fn wide_each(n: usize, work: impl Fn(usize) + Send + Sync + 'static) { + let next = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let work = Arc::new(work); + let threads = (wide_threads() + 1).min(n); + let jobs = (0..threads) + .map(|_| { + let (next, work) = (next.clone(), work.clone()); + Box::new(move || { + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= n { + break; + } + work(i); + } + }) as Job + }) + .collect(); + wide(jobs); +} + /// About this many bytes to a piece of work for [`wide`]. const WIDE_JOB: usize = 1 << 20; @@ -1390,7 +1423,11 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { let mut runs = Vec::new(); let mut i = 0; while i < n { - // Equal bytes, eight at a time while they last. + // Equal bytes, many at a time while they last (a page looked at + // under a flight's writes hardly ever differs at all). + while i + 512 <= n && now[i..i + 512] == was[i..i + 512] { + i += 512; + } while i + 8 <= n && now[i..i + 8] == was[i..i + 8] { i += 8; } @@ -1409,6 +1446,52 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { runs } +/// Whether pages of a copy in the card's memory that a refresh takes again +/// go up to the card only where they are not what the CPU's side holds +/// already (`VICTORY_SEND_CHANGED=1`; off by default). +/// +/// A refresh copies the 64 KiB pages that were written since it last took +/// them, and all of each went up and was hashed there again. Most of them +/// the title did not write: the relay put what shaders wrote into title +/// memory, and the card and the CPU's side hold those bytes already +/// ([`Shadow::card_merge_relay`]). Run record-1: 1,500 pieces (98 MB) a +/// frame fetched from the card, 103 MB in 328 ranges sent up, 322 hash +/// passes, while the title's own writes took some 260 guards off. +/// +/// What it rests on: the card's side holds what the CPU's side holds, but +/// for ranges shaders may be writing (no refresh touches them) and what is +/// still to go up. A page's first taking always goes up whole, so does one +/// that could not be read; after that every byte that changes on the CPU's +/// side goes up (the bytes compared are the bytes stored). +/// +/// Why it is not on by default: a shader that writes a copy through a view +/// nobody declared (`crate::draw`, buffers picked by index) breaks that +/// rule. Taken again, its page went up over what it wrote; with the switch +/// its bytes stay, as they would on the console, until the title changes the +/// same 64 bytes: clearing them to the zeros they held before is then no +/// change. +fn send_changed() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + #[cfg(feature = "diagnostics")] + if crate::copystat::mode() != 0 { + return false; + } + std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") && crate::safecopy::on() + }) +} + +/// Since the last frame-rate line, of pages taken again into copies in the +/// card's memory ([`send_changed`]): bytes compared, those of pages that +/// held the same, and bytes to go up. +static SEND: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +/// [`SEND`], taken. +#[cfg(feature = "diagnostics")] +pub(crate) fn send_stats() -> [u64; 3] { + [0, 1, 2].map(|i| SEND[i].swap(0, Ordering::Relaxed)) +} + /// Whether what shaders wrote goes into title memory run by run /// ([`put_changed`]; on by default, `VICTORY_EXACT_BACK=0` writes the whole /// stretch from the first changed byte to the last, as before). @@ -1452,6 +1535,16 @@ fn dword_runs(at: usize, title: &[u8], merged: &[u8], gap: usize) -> Vec<(usize, /// shortcut: a piece with very many runs has them joined over small gaps, /// where the old race is left. fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { + // Past the guard, if it is one (`VICTORY_LAND_WINDOW`). + if exact_back() + && crate::safecopy::on() + // SAFETY: the same title memory through a view of ours. + && crate::watch::land_through(at, title.len(), |to| unsafe { crate::safecopy::put_changed(to, title, merged) }) + { + PUT[0].fetch_add(1, Ordering::Relaxed); + PUT[2].fetch_add(merged.len() as u64, Ordering::Relaxed); + return merged.len(); + } crate::watch::landing(at, title.len()); if !exact_back() { crate::host::write_mapped(at as *mut u8, merged.as_ptr(), merged.len()); @@ -1520,6 +1613,34 @@ mod merge_tests { /// The runs hold exactly the bytes that differ: putting them into the /// old bytes gives the new ones, and no run holds an equal byte. + /// What looking at a page that did not change costs, against the look + /// eight bytes at a time that it was (a frame has some 250 of them, on + /// the submitting thread). Run with `--ignored --nocapture`. + #[test] + #[ignore] + fn runs_of_equal_pages() { + let (a, b) = (vec![7u8; 64 << 10], vec![7u8; 64 << 10]); + let eights = || { + let (now, was) = (std::hint::black_box(&a), std::hint::black_box(&b)); + let mut i = 0; + while i + 8 <= now.len() && now[i..i + 8] == was[i..i + 8] { + i += 8; + } + std::hint::black_box(i); + }; + let best = |f: &dyn Fn()| { + (0..500) + .map(|_| { + let t = std::time::Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1e6 + }) + .fold(f64::MAX, f64::min) + }; + let runs = || drop(std::hint::black_box(changed_runs(std::hint::black_box(&a), std::hint::black_box(&b)))); + println!("64 KiB that are the same: {:.1} us by eights, {:.1} us now", best(&eights), best(&runs)); + } + #[test] fn changed_runs_are_exactly_the_bytes_that_differ() { let was: Vec = (0..300u32).map(|i| (i * 13 + 5) as u8).collect(); @@ -1871,6 +1992,7 @@ impl Shadow { start, len, copied: Mutex::new(vec![0; pages as usize]), + ranged: Mutex::default(), watched: AtomicU8::new(0), pending: Mutex::default(), flights: Mutex::default(), @@ -2547,6 +2669,43 @@ impl Shadow { self.update_free(from, to) } + /// Whether [`Shadow::update`] of `[address, address + len)` would copy + /// nothing, and knows it without asking anything + /// (`crate::watch::nothing_new`). `false` if it would have to ask. + pub(crate) fn nothing_new(&self, address: usize, len: usize) -> bool { + if self.place.is_some() { + return true; + } + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), (address + len).min(end)); + if from >= to { + return true; + } + if self.watched.load(Ordering::Relaxed) != 1 { + return false; + } + // Around ranges shaders are writing the refresh asks gap by gap. + if self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) { + return false; + } + let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + let same = crate::watch::nothing_new(from, to, start / PAGE, &copied, self.ranged(from, to)); + #[cfg(feature = "diagnostics")] + if same { + use crate::copystat::{C, add}; + add(C::Checked, (to - from) as u64); + add(C::Unchanged, (to - from) as u64); + } + same + } + + /// The latest asking after which a range that holds `[from, to)` was + /// taken whole (0: none is known). The caller holds `copied`'s lock. + fn ranged(&self, from: usize, to: usize) -> u64 { + let ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner()); + ranged.iter().filter(|r| r.0 <= from && to <= r.1).map(|r| r.2).max().unwrap_or(0) + } + /// [`Shadow::update`] of `[from, to)` (inside the buffer) where no /// shader writes. fn update_free(&self, from: usize, to: usize) -> usize { @@ -2581,7 +2740,13 @@ impl Shadow { let base = self.start as usize / PAGE; let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); let mut writes = written.iter().peekable(); - let (mut bytes, mut run) = (0, None); + // Pages the range holds in part are never noted in `copied`, and + // were copied again at every refresh of the range, written or not: + // of the heap's buffer views alone two ends for each of 4,400 + // copies, every frame. A range that was taken whole, and not written + // since, is as it was. + let ranged = if crate::watch::light() { self.ranged(from, to) } else { 0 }; + let (mut runs, mut run) = (Vec::new(), None::<(usize, bool)>); let last = (to - 1) / PAGE; for page in from / PAGE..=last { let write = match writes.peek() { @@ -2592,25 +2757,111 @@ impl Shadow { _ => 0, }; let at = &mut copied[page - base]; - if *at == 0 || write > *at { + let taken = (*at).max(ranged); + if taken == 0 || write > taken { // A page only partly in the range is copied in part: it // stays stale for the rest. let (start, end) = (self.start as usize, (self.start + self.len) as usize); if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to { *at = now; } - run.get_or_insert(page); - } else if let Some(first) = run.take() { - bytes += self.copy((first * PAGE).max(from), (page * PAGE).min(to)); + // Cut where pages taken before meet pages never taken. + let again = taken != 0; + if let Some((first, known)) = run + && known != again + { + runs.push(((first * PAGE).max(from), (page * PAGE).min(to), known)); + run = None; + } + run.get_or_insert((page, again)); + } else if let Some((first, known)) = run.take() { + runs.push(((first * PAGE).max(from), (page * PAGE).min(to), known)); } } // Cut to the range: next to it shaders may be writing the copy. - if let Some(first) = run { - bytes += self.copy((first * PAGE).max(from), ((last + 1) * PAGE).min(to)); + if let Some((first, known)) = run { + runs.push(((first * PAGE).max(from), ((last + 1) * PAGE).min(to), known)); + } + let bytes = self.take_all(runs); + if crate::watch::light() { + // All of the range is in the copy as of this asking. + let mut ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner()); + ranged[0] = (from, to, now); + if to - from >= ranged[1].1 - ranged[1].0 { + ranged[1] = (from, to, now); + } } bytes } + /// [`Shadow::take`] of `runs` (from, to, known), on several threads if + /// they are long: the big heap's copy has some 4 MB of them in each of + /// 14 refreshes a frame, on one thread while the others had nothing. + fn take_all(&self, runs: Vec<(usize, usize, bool)>) -> usize { + const LONG: usize = 1 << 20; + const PART: usize = 256 << 10; + let bytes = runs.iter().map(|r| r.1 - r.0).sum(); + if bytes < LONG || !crate::watch::light() { + for (from, to, known) in runs { + self.take(from, to, known); + } + return bytes; + } + let mut parts = Vec::with_capacity(bytes / PART + runs.len()); + for (from, to, known) in runs { + let mut at = from; + while at < to { + // Whole pages to a part. + let next = ((at / PAGE) * PAGE + PART).min(to); + parts.push((at, next, known)); + at = next; + } + } + let this = std::ptr::from_ref(self) as usize; + wide_each(parts.len(), move |i| { + // SAFETY: `wide_each` returns when every part is done, before + // the borrow of `self` ends. The parts lie apart. + let this = unsafe { &*(this as *const Shadow) }; + let (from, to, known) = parts[i]; + this.take(from, to, known); + }); + bytes + } + + /// 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 { + if !known || self.card.is_none() || !send_changed() { + return self.copy(from, to); + } + let start = self.start as usize; + let mut at = from; + while at < to { + let n = (PAGE - at % PAGE).min(to - at); + // SAFETY: inside the mapping of the copy's CPU side, which + // nothing else writes there: no shader's range holds it. + let found = unsafe { crate::safecopy::update(self.data.add(at - start), at as *const u8, n) }; + SEND[0].fetch_add(n as u64, Ordering::Relaxed); + match found { + crate::safecopy::Updated::Same => { + SEND[1].fetch_add(n as u64, Ordering::Relaxed); + } + crate::safecopy::Updated::Changed(a, b) => { + SEND[2].fetch_add((b - a) as u64, Ordering::Relaxed); + self.changed(at - start + a, at - start + b); + self.card_changed(at - start + a, at - start + b); + } + // A page is not there: as before, around it, and all of it + // goes up. + crate::safecopy::Updated::Failed => { + self.copy(at, at + n); + } + } + at += n; + } + to - from + } + /// Copies title memory `[from, to)`, cut to the buffer, into the copy. fn copy(&self, from: usize, to: usize) -> usize { let (start, end) = (self.start as usize, (self.start + self.len) as usize); @@ -2809,6 +3060,40 @@ impl Shadow { } } +/// For tests: copies with no host buffer behind them. +#[cfg(test)] +impl Shadow { + /// A copy at `data` of title memory `[start, start + len)`, with a card + /// side if `card`. It is never let go: there is no buffer to release. + pub(crate) fn unbacked(start: u64, data: *mut u8, len: u64, card: bool) -> Arc { + // SAFETY: an interface pointer nothing calls. + let none = || unsafe { std::mem::transmute::(8) }; + let mut shadow = Shadow::new(none(), data, 0, start, len); + if card { + shadow.card = Some(Card { + staging: none(), + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + size: len.next_multiple_of(PIECE as u64), + }); + } + let shadow = Arc::new(shadow); + std::mem::forget(shadow.clone()); + shadow + } + + /// What shaders wrote goes into title memory ([`put_changed`]). + pub(crate) fn put(at: usize, title: &[u8], merged: &[u8]) { + put_changed(at, title, merged); + } + + /// What is to go up to the card, taken. + pub(crate) fn take_dirty(&self) -> Vec<(usize, usize)> { + std::mem::take(&mut *self.card.as_ref().unwrap().dirty.lock().unwrap()) + } +} + struct Entry { end: u64, shadow: Option>, diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 27774d6..0b19382 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -149,6 +149,8 @@ fn kernel_written(first: usize, last: usize) -> Option> { add(C::Watches, 1); add(C::WatchUs, started.elapsed().as_micros() as u64); slow(started.elapsed().as_micros() as u64); + tally(0, 1); + tally(1, ((last - first) * (PAGE >> 10)) as u64); } let mut pages: Vec = found[..count].iter().map(|&at| at / PAGE).collect(); pages.dedup(); @@ -173,7 +175,9 @@ const AHEAD_MAX: usize = (1 << 30) / PAGE; pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { let mut pieces: Vec<(usize, usize)> = ranges .iter() - .filter(|r| r.0 < r.1) + // Not view memory known by its bits: the kernel would refuse the + // asking (and, asked together with others, theirs). + .filter(|r| r.0 < r.1 && !published(r.0, r.1)) .map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE))) .collect(); if pieces.len() < 2 { @@ -291,7 +295,7 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) { // here, once; what is not write-watched stays with `writes`. let mut written = Vec::new(); for &(start, end) in ranges { - if start >= end { + if start >= end || published(start, end) { continue; } let (first, last) = (start / PAGE, end.div_ceil(PAGE)); @@ -384,15 +388,24 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve if let Some(known) = ahead(&journal()) { return Some(known); } + // Read-only since an asking noted it: the bits first, then the journal. + if guarded && published(start, end) { + #[cfg(feature = "diagnostics")] + tally(2, 1); + let j = journal(); + return Some((next_asking(), of(&j))); + } // Asked, and the answer noted, with the range held: nothing else asks // about any of it in between. let _range = Asking::hold(first, last); if let Some(known) = ahead(&journal()) { return Some(known); } + let mut guards_asked = false; let pages = match kernel_written(first, last) { Some(pages) => pages, None => { + guards_asked = true; if !guarded { return None; } @@ -418,15 +431,190 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve let j = journal(); return Some((next_asking(), of(&j))); } - let mut j = journal_mut(); - let now = next_asking(); - j.written.extend(pages.into_iter().map(|page| (page, now))); - Some((now, of(&j))) + let answer = { + let mut j = journal_mut(); + let now = next_asking(); + j.written.extend(pages.iter().map(|&page| (page, now))); + (now, of(&j)) + }; + // Noted: what the guards made clean of it is known by its bits from + // now on. (The range is still held: no other asking of any of it came + // between.) + if guards_asked && light() { + publish(&pages); + } + Some(answer) +} + +/// Whether nothing of `[start, end)` was written that a copy with the notes +/// `copied` (the asking after which each page from page `base` on was taken) +/// and `ranged` (the asking after which a range that holds this one was +/// taken whole, or 0) does not hold, as [`writes`] would answer with nothing +/// asked: the submission's asking covers the range, or its blocks are known +/// by their bits. `false` if something would have to be asked. +pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], ranged: u64) -> bool { + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + // The bits first, then the journal, as in `writes`. + let known = published(start, end); + let j = journal(); + if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { + return false; + } + let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else { + return false; + }; + (ranged != 0 || taken.iter().all(|&at| at != 0)) + && j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].max(ranged)) } /// Guarded blocks of view memory. const BLOCK: usize = PAGE; +/// Whether the refreshes of host copies go the light way +/// (`VICTORY_LIGHT_REFRESH=0`: as before): view memory nothing wrote since +/// it was last asked about is known by its bits ([`PUBLISHED`]), a copy +/// nothing of whose range changed is told so before any thread is woken +/// for it (`crate::host`, `Shadow::nothing_new`), and the ends of a range, +/// pages the range holds in part, are not copied again at every refresh +/// (`Shadow::copy_stale`). +/// +/// A frame asked about view memory some 1,500 times, for nearly all of it +/// to hear that nothing was written, on up to seven threads at once, each +/// asking under the guards' one lock and behind [`ASKING`]'s: 94 ms a frame +/// of all threads' time (run record-1), most of it waiting. +pub(crate) fn light() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LIGHT_REFRESH").is_none_or(|v| v != "0")) +} + +/// A bit per block of the address space, in pieces made when first needed +/// and never let go. +struct Bits([std::sync::atomic::AtomicPtr; Bits::PIECES]); + +/// The bits of 4 GiB. +type BitsPiece = [std::sync::atomic::AtomicU64; Bits::WORDS]; + +impl Bits { + const WORDS: usize = 1 << 10; + /// 128 TiB, what a process has. + const PIECES: usize = 1 << 15; + + const fn new() -> Bits { + Bits([const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; Bits::PIECES]) + } + + fn piece(&self, word: usize) -> Option<&BitsPiece> { + let piece = self.0.get(word / Bits::WORDS)?.load(std::sync::atomic::Ordering::Acquire); + // SAFETY: null, or a piece made by `set`, which is never freed. + 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}; + let word = block / 64; + let Some(place) = self.0.get(word / Bits::WORDS) else { + return; + }; + if place.load(Relaxed).is_null() { + let piece: Box = Box::new([const { std::sync::atomic::AtomicU64::new(0) }; Bits::WORDS]); + place.store(Box::into_raw(piece), Release); + } + if let Some(piece) = self.piece(word) { + piece[word % Bits::WORDS].fetch_or(1 << (block % 64), Release); + } + } + + fn clear(&self, block: usize) { + let word = block / 64; + if let Some(piece) = self.piece(word) { + // Ahead of the protection's change, and seen by whoever the + // writer tells of its write. + piece[word % Bits::WORDS].fetch_and(!(1 << (block % 64)), std::sync::atomic::Ordering::SeqCst); + } + } + + /// Whether the bits of all of `[first, last)` are set (not so of none). + fn all(&self, first: usize, last: usize) -> bool { + let mut block = first; + while block < last { + let word = block / 64; + let until = ((word + 1) * 64).min(last); + let mask = (u64::MAX >> (64 - (until - block))) << (block % 64); + let Some(piece) = self.piece(word) else { + return false; + }; + if piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::Acquire) & mask != mask { + return false; + } + block = until; + } + first < last + } +} + +/// The blocks that are read-only by our hand, not written since, and of +/// which the journal holds every write from before that: for those, what +/// [`writes`] answers is in the journal, and neither the kernel, nor the +/// guards' lock, nor [`ASKING`] need be asked. +/// +/// Why that is so: a block's bit is set under the guards' lock while the +/// block is clean, by the asking that made it clean, after that asking noted +/// in the journal what it found ([`publish`]). It is cleared under the same +/// lock, before the block becomes writable again ([`open`]) or is forgotten +/// ([`title_memory_remapped`]). So while the bit is set nothing can have +/// written the block through this address, and who sees the bit and looks +/// at the journal after that finds every earlier write in it. A write that +/// comes while the bit is looked at is no different from one that comes just +/// after an asking: the next asking finds the block open. +static PUBLISHED: Bits = Bits::new(); + +/// 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) { + PUBLISHED.set(*page); + } + } +} + +/// Whether nothing of `[start, end)` can have been written since an asking +/// noted it in the journal ([`PUBLISHED`]). +fn published(start: usize, end: usize) -> bool { + light() && PUBLISHED.all(start / BLOCK, end.div_ceil(BLOCK)) +} + +/// Since the last frame line: what asking about title memory was. Kernel +/// askings and the KiB they walked; view ranges answered by their bits, by +/// the guards whole clean, and block by block; blocks made read-only; blocks +/// opened by ourselves; nanoseconds waiting for the guards' lock and +/// nanoseconds of changing protections (all threads); pieces put into title +/// memory past the guards ([`land_through`]). +#[cfg(feature = "diagnostics")] +static ASKS: [std::sync::atomic::AtomicU64; 10] = [const { std::sync::atomic::AtomicU64::new(0) }; 10]; + +#[cfg(feature = "diagnostics")] +fn tally(what: usize, n: u64) { + ASKS[what].fetch_add(n, std::sync::atomic::Ordering::Relaxed); +} + +/// [`ASKS`], taken. +#[cfg(feature = "diagnostics")] +pub(crate) fn asks() -> [u64; 10] { + std::array::from_fn(|i| ASKS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// The guards' lock, the wait for it counted. +fn guards_timed() -> std::sync::MutexGuard<'static, Guards> { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + let g = guards(); + #[cfg(feature = "diagnostics")] + tally(7, started.elapsed().as_nanos() as u64); + g +} + struct Guards { /// Blocks we made read-only. protected: BTreeSet, @@ -453,15 +641,78 @@ static LANDED: Mutex>> = Mutex::new /// What shaders wrote is about to go into title memory at `[at, at + len)`. pub(crate) fn landing(at: usize, len: usize) { + note_landed(at, len); + writing(at, len); +} + +fn note_landed(at: usize, len: usize) { + let frame = crate::frame::current(); + let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); + let landed = landed.get_or_insert_with(Default::default); + for page in at / 4096..=(at + len.max(1) - 1) / 4096 { + landed.insert(page, frame); + } +} + +/// Whether what shaders wrote goes into guarded title memory past the guard +/// (`VICTORY_LAND_WINDOW=1`; off by default, not yet run in the game). +/// +/// Each piece put into title memory took the guard off its block, and the +/// next refresh of a copy of it put it on again, two changes of protection +/// under the guards' one lock, 10 microseconds each with the title's threads +/// running: some 1,600 pieces a frame, in the relay's landing and in the +/// submitting thread's refreshes. The title's own writes take some 260. +fn land_window() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAND_WINDOW").is_some_and(|v| v == "1") && light()) +} + +/// With [`land_window`], if `[at, at + len)` is guarded view memory: `put` +/// writes what shaders wrote there, at the address it is given, through a +/// view of ours of the same section. Whether it did (`put` says whether it +/// could); if not the caller goes the other way ([`landing`]), `put` begun +/// or not. +/// +/// Why it is the same: the runtime tells of every view it maps, and forgets +/// those it unmaps, under the lock held here for reading, so while it is +/// held the pages the title sees at `at` are the pages written. The block +/// stays read-only for the title, whose own writes are seen as before. Ours +/// is noted in the journal, after the bytes are in: an asking before that +/// may or may not copy them, and has a number under the note's, so the next +/// one copies the page (again). +pub(crate) fn land_through(at: usize, len: usize, put: impl FnOnce(*mut u8) -> bool) -> bool { + land_window() && land_past(at, len, put) +} + +fn land_past(at: usize, len: usize, put: impl FnOnce(*mut u8) -> bool) -> bool { + if len == 0 || !published(at, at + len) { + return false; + } + let Some(_mapped) = title_memory_reading_now() else { + return false; + }; + let crate::inplace::Cover::Run(section, offset) = crate::inplace::cover(at, len) else { + return false; + }; + let Some(base) = crate::inplace::window(section) else { + return false; + }; + if !put((base + offset as usize) as *mut u8) { + return false; + } + note_landed(at, len); { - let frame = crate::frame::current(); - let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); - let landed = landed.get_or_insert_with(Default::default); - for page in at / 4096..=(at + len.max(1) - 1) / 4096 { - landed.insert(page, frame); + let mut j = journal_mut(); + let now = next_asking(); + for page in at / PAGE..(at + len).div_ceil(PAGE) { + j.written.insert(page, now); } } - writing(at, len); + #[cfg(feature = "diagnostics")] + tally(9, 1); + // As `writing` says. + crate::descriptor::host::remapped(at, len); + true } /// Whether shaders' writes went into a page of `[at, at + len)` in the last @@ -501,7 +752,7 @@ fn guard(start: usize, end: usize) -> Option> { // `VICTORY_GUARD_ASK=1` asks every time, as before. static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && { - let g = guards(); + let g = guards_timed(); let first = start / BLOCK; g.protected.contains(&first) || g.absent.contains(&first) }; @@ -509,7 +760,7 @@ fn guard(start: usize, end: usize) -> Option> { return None; } install(); - let mut g = guards(); + let mut g = guards_timed(); let mut written = Vec::new(); let mut run: Option = None; let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); @@ -521,8 +772,12 @@ fn guard(start: usize, end: usize) -> Option> { let clean: Vec = g.clean.range(first..last).copied().collect(); if clean.len() == last - first { // Nothing written, mapped or new since the range was last taken. + #[cfg(feature = "diagnostics")] + tally(3, 1); return Some(written); } + #[cfg(feature = "diagnostics")] + tally(4, 1); let mut next_clean = 0; let mut uncommitted_until = first; for block in first..=last { @@ -610,15 +865,23 @@ fn protect(g: &mut Guards, from: usize, to: usize) { use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; let set = |from: usize, to: usize| { let mut old = 0; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); // SAFETY: title view memory; only its protection changes. - unsafe { + let done = unsafe { VirtualProtect( (from * BLOCK) as *const _, (to - from) * BLOCK, PAGE_READONLY, &mut old, ) != 0 + }; + #[cfg(feature = "diagnostics")] + { + tally(5, (to - from) as u64); + tally(8, started.elapsed().as_nanos() as u64); } + done }; let note = |g: &mut Guards, from: usize, to: usize| { g.protected.extend(from..to); @@ -662,13 +925,21 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { .range(start / BLOCK..end.div_ceil(BLOCK)) .copied() .collect(); + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); for &block in &blocks { g.protected.remove(&block); g.clean.remove(&block); + // Before the block can be written. + PUBLISHED.clear(block); let mut old = 0; // SAFETY: a block we made read-only. unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; } + #[cfg(feature = "diagnostics")] + if !blocks.is_empty() { + tally(8, started.elapsed().as_nanos() as u64); + } !blocks.is_empty() } @@ -678,7 +949,14 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { /// reads into its own memory. pub fn writing(at: usize, len: usize) { // The length is the title's (`fread`'s size times count, saturated). - open(&mut guards(), at, at.saturating_add(len)); + { + let mut g = guards_timed(); + #[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); + } // A placed texture there changes with no descriptor written. crate::descriptor::host::remapped(at, len); } @@ -753,6 +1031,7 @@ pub fn title_memory_remapped(at: usize, len: usize) { for block in blocks { g.protected.remove(&block); g.clean.remove(&block); + PUBLISHED.clear(block); } } @@ -1264,4 +1543,113 @@ mod many_askers_tests { // SAFETY: the reservation made above. unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) }; } + + /// The same of view memory, which is guarded: what its bits answer + /// misses no write either, however often blocks are opened and guarded + /// again between. + #[test] + fn no_write_to_views_is_lost_between_askers() { + const PAGES: usize = 12; + const THREADS: usize = 8; + // SAFETY: a view of a section of our own. + let at = unsafe { + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (PAGES * PAGE) as u32, + std::ptr::null(), + ); + let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, PAGES * PAGE).Value as usize; + crate::title_memory_section(section as usize, (PAGES * PAGE) as u64, true); + super::title_memory_remapped(at, PAGES * PAGE); + crate::title_memory_view(at, PAGES * PAGE, section as usize, 0); + at + }; + assert!(at != 0 && at.is_multiple_of(PAGE)); + let by_bits = std::sync::atomic::AtomicUsize::new(0); + let past = std::sync::atomic::AtomicUsize::new(0); + std::thread::scope(|s| { + for t in 0..THREADS { + let (by_bits, past) = (&by_bits, &past); + s.spawn(move || { + let mut last = [0u64; PAGES]; + let mut seed = t as u64 * 7919 + 1; + let mut next = |n: usize| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as usize % n + }; + for _ in 0..500 { + let page = next(PAGES); + let from = page - next(page.min(3) + 1); + let to = page + 1 + next((PAGES - page).min(3)); + if next(4) != 0 { + // As in the test above, or after a word of ours, + // or past the guard. + let word = at + page * PAGE + t * 8; + // SAFETY (both): as above. + let put = next(3) == 0 + && super::land_past(word, 8, |to| { + unsafe { to.cast::().write_volatile(2) }; + true + }); + if put { + past.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + assert_eq!(unsafe { (word as *const u64).read_volatile() }, 2, "put elsewhere"); + } else { + if next(4) == 0 { + super::writing(word, 8); + } + unsafe { (word as *mut u64).write_volatile(1) }; + } + } else { + // Nothing written: what is asked counts as before. + by_bits.fetch_add( + usize::from(super::published(at + from * PAGE, at + to * PAGE)), + std::sync::atomic::Ordering::Relaxed, + ); + let (now, _) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view"); + for l in &mut last[from..to] { + *l = now; + } + continue; + } + 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}: {number} is not after {}", last[page]); + for l in &mut last[from..to] { + *l = now; + } + } + }); + } + }); + assert!(by_bits.into_inner() > 0, "the bits answered none"); + assert!(past.into_inner() > 0, "nothing was put past the guards"); + super::title_memory_remapped(at, PAGES * PAGE); + // SAFETY: the view mapped above. + unsafe { UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: at as *mut _ }) }; + } + + /// A range's bits are all of its blocks', whatever lies beside them. + #[test] + fn bits_of_ranges() { + static BITS: super::Bits = super::Bits::new(); + let blocks = [0usize, 1, 63, 64, 65, 127, 128, 200, 65535, 65536, 65537, 1 << 20, (1 << 31) - 1]; + for &b in &blocks { + assert!(!BITS.all(b, b + 1)); + BITS.set(b); + assert!(BITS.all(b, b + 1)); + } + assert!(BITS.all(0, 2) && BITS.all(63, 66) && BITS.all(127, 129) && BITS.all(65535, 65538)); + assert!(!BITS.all(0, 3) && !BITS.all(62, 64) && !BITS.all(65534, 65536) && !BITS.all(5, 5)); + for b in 300..700 { + BITS.set(b); + } + assert!(BITS.all(300, 700) && !BITS.all(299, 700) && !BITS.all(300, 701)); + BITS.clear(511); + assert!(!BITS.all(300, 700) && BITS.all(300, 511) && BITS.all(512, 700)); + assert!(!BITS.all(1 << 40, (1 << 40) + 1), "outside the address space"); + } } diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index fe5b4c5..95fd0df 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -419,6 +419,7 @@ impl Drop for Section { }) }; } + victory_gpu::title_memory_section_gone(self.handle as usize); // SAFETY: our handle; views keep the section alive on their own. unsafe { CloseHandle(self.handle) }; } From 160d22222ca78e41989f9a56a779e0f04796e3c0 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 22:09:38 -0600 Subject: [PATCH 166/445] Views guarded while they are mapped stay writable; tests take turns on WARP The runtime maps a view and then tells the write watch. A refresh on another thread could guard the new blocks in between, and the telling then forgot them and left them read-only: the title's next write to one was an access violation nobody takes. Told of a new view, the watch now gives the write access back; before an unmapping it only forgets, as before. The test binary's random crashes were d3d10warp.dll's own, with two tests on the software adapter at once: they take turns now. The watch's tests forget their guards before their memory is freed (another test's memory could get the address and inherit them), and three more are no longer tied to other tests' memory, the adapter's other work or a busy PC's timing. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/frame.rs | 33 +++++--- crates/victory-gpu/src/indirect.rs | 17 +++- crates/victory-gpu/src/inplace.rs | 13 ++- crates/victory-gpu/src/lib.rs | 3 +- crates/victory-gpu/src/watch.rs | 108 +++++++++++++++++++++---- crates/victory-hle/src/modules/xmem.rs | 2 +- 6 files changed, 144 insertions(+), 32 deletions(-) diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 798b760..84b74ba 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -226,18 +226,29 @@ mod tests { // origin poll that times out (and starts the frame), then a // blocking flip wait. Each flip takes its own tick. const FLIP: u32 = 2; - assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK); + // (The ticks are far apart, and it may take a few tries: a busy PC + // wakes a wait tens of milliseconds late at times.) + assert_eq!(set_interval(null, null, 60_000, 3, 0), S_OK); let mut token = 0; - let flips: Vec = (0..4) - .map(|_| { - let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); - assert_eq!( - wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), - S_OK - ); - LAST[2].load(Ordering::Relaxed) - }) - .collect(); + let mut four = || -> Vec { + (0..4) + .map(|_| { + let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); + assert_eq!( + wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), + S_OK + ); + LAST[2].load(Ordering::Relaxed) + }) + .collect() + }; + let mut flips = four(); + for _ in 0..10 { + if flips.windows(2).all(|w| w[1] == w[0] + 1) { + break; + } + flips = four(); + } assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}"); // Even when a flip wait begins on the tick another just ended on. let (tick, _) = next_tick(FLIP); diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index af7f010..b8128ea 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -491,7 +491,7 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; @@ -521,10 +521,24 @@ void main() { event: HANDLE, clamp: Clamp, worker: Clamp, + /// Last, so given up last. + _turn: std::sync::MutexGuard<'static, ()>, + } + + /// The software adapter is one test's at a time. Two tests that compile + /// and run shaders on it at once (it is one device for the process) make + /// `d3d10warp.dll` (10.0.26100) crash now and then: access violations in + /// its own shader compiler, on its own worker threads, in 12% of runs of + /// all tests and 3% of runs of these alone on two threads; none in 100 + /// runs one after the other. + pub(crate) fn warp_turn() -> std::sync::MutexGuard<'static, ()> { + static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + TURN.lock().unwrap_or_else(|e| e.into_inner()) } impl WarpHarness { fn new() -> Option { + let turn = warp_turn(); // SAFETY: plain DXGI WARP query and D3D12 test harness setup. unsafe { let factory: IDXGIFactory4 = @@ -563,6 +577,7 @@ void main() { event, clamp, worker, + _turn: turn, }) } } diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 25461df..bcafed8 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -1099,6 +1099,7 @@ mod tests { /// driver is what a run with `VICTORY_INPLACE_PROBE=1` adds. #[test] fn warp_probe_opens_title_like_memory_and_the_gpu_sees_its_bytes() { + let _turn = crate::indirect::tests::warp_turn(); let Some(device) = warp() else { return }; if device.cast::().is_err() { eprintln!("no ID3D12Device13 here: parts of an allocation cannot be opened"); @@ -1122,6 +1123,7 @@ mod tests { /// whole is turned down without asking the host. #[test] fn warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset() { + let _turn = crate::indirect::tests::warp_turn(); let Some(device) = warp() else { return }; if device.cast::().is_err() { return; @@ -1142,7 +1144,16 @@ mod tests { assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address"); drop(placed); // Half of it decommitted: turned down, the host not asked. - assert_ne!(mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT), 0); + // The heap lets go of the pages a moment after its last + // reference, if the adapter is busy with other tests' work. + let gone = (0..500).any(|_| { + let done = mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(gone, "the heap keeps the pages"); assert!(matches!(place_part(&device, start, len), Err(None))); mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); } diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 2ecf3ab..ab6102e 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -68,5 +68,6 @@ pub use host::on_failure; pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; #[cfg(windows)] pub use watch::{ - title_memory_reading, title_memory_remapped, title_memory_remapping, writing as kernel_will_write, + title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping, + writing as kernel_will_write, }; diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 27774d6..74b0d80 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -732,10 +732,38 @@ pub fn title_memory_reading_now() -> Option { } } -/// The runtime mapped or unmapped title memory `[at, at + len)`: what it -/// shows is new and read-write, so it is no longer guarded (nor known -/// unmapped). +/// The runtime mapped title memory `[at, at + len)`: what it shows is new, +/// so it is no longer guarded (nor known unmapped), and read-write. +/// +/// The view is there before we are told of it, and a copy's refresh on +/// another thread may have guarded its blocks in between (it finds blocks +/// it knew absent committed, and holds [`GUARDS`], which we wait for). +/// Forgetting such a block and leaving it read-only would make the title's +/// next write to it an access violation nobody takes (`on_write` finds it +/// neither guarded nor writable) and a kernel read into it fail, so the +/// write access is given back. pub fn title_memory_remapped(at: usize, len: usize) { + open(&mut title_memory_changed(at, len), at, at.saturating_add(len)); +} + +/// The runtime is about to unmap title memory `[at, at + len)`: it is +/// nothing of ours any more. Its protection goes with it. +pub fn title_memory_unmapping(at: usize, len: usize) { + let mut g = title_memory_changed(at, len); + let blocks: Vec = g + .protected + .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) + .copied() + .collect(); + for block in blocks { + g.protected.remove(&block); + g.clean.remove(&block); + } +} + +/// Tells what keeps track of what title memory shows; the guards, with no +/// block of the range known unmapped. +fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, Guards> { // A placed texture there arrives, goes or changes with no descriptor // written. crate::descriptor::host::remapped(at, len); @@ -745,15 +773,11 @@ pub fn title_memory_remapped(at: usize, len: usize) { 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).copied().collect(); for block in absent { g.absent.remove(&block); } - let blocks: Vec = g.protected.range(range).copied().collect(); - for block in blocks { - g.protected.remove(&block); - g.clean.remove(&block); - } + g } /// Registers the handler that takes writes to guarded blocks, once, ahead @@ -843,16 +867,18 @@ mod tests { } as usize; assert_ne!(p, 0); let (start, end) = (p, p + 4 * PAGE); - let (_, before) = writes(start, end, false).expect("watched"); - assert!(before.is_empty()); + // The journal may hold pages of another test's memory that was here. + let (none, before) = writes(start, end, false).expect("watched"); + assert!(before.iter().all(|&(_, w)| w < none), "{before:?}"); // SAFETY: committed pages of ours. unsafe { ((p + PAGE + 8) as *mut u8).write(1) }; let (now, after) = writes(start, end, false).expect("watched"); - assert_eq!(after, [(p / PAGE + 1, now)]); + let new = |w: Vec<(usize, u64)>| w.into_iter().filter(|w| w.1 > none).collect::>(); + assert_eq!(new(after), [(p / PAGE + 1, now)]); // Another asker after the kernel's bit was cleared still sees it. let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched"); assert!(later > now); - assert_eq!(again, [(p / PAGE + 1, now)]); + assert_eq!(new(again), [(p / PAGE + 1, now)]); let mut plain = vec![0u8; PAGE]; assert!( writes( @@ -911,6 +937,9 @@ mod tests { guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect()) ); + // Before the view goes, as the runtime does: the address may be + // another test's the moment it is free. + title_memory_unmapping(view, 2 * BLOCK); // SAFETY: our view. unsafe { UnmapViewOfFile( @@ -919,7 +948,52 @@ mod tests { }, ) }; - title_memory_remapped(view, 2 * BLOCK); + } + + /// The runtime maps a view and then tells us; a copy's refresh on another + /// thread can guard it in between. Told, it is the title's to write: a + /// block left read-only and forgotten would be an access violation in + /// title code. + #[test] + fn a_block_guarded_before_we_were_told_of_its_view_can_be_written() { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile, + }; + // SAFETY: a pagefile section of two blocks, mapped read-write; the + // view holds it. + let view = unsafe { + let section = CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK); + CloseHandle(section); + view + }; + let at = view.Value as usize; + assert_ne!(at, 0); + // The refresh, then the runtime's word. + assert!(guard(at, at + 2 * BLOCK).is_some()); + assert!(!writable(at) && !writable(at + BLOCK)); + title_memory_remapped(at, 2 * BLOCK); + assert!(writable(at) && writable(at + BLOCK)); + // SAFETY: inside the view; a fault would end the process. + unsafe { ((at + 8) as *mut u8).write_volatile(1) }; + // Looked at again as new, and guarded again. + assert_eq!( + guard(at, at + 2 * BLOCK), + Some((at / PAGE..at / PAGE + 2).collect()) + ); + assert!(!writable(at)); + title_memory_unmapping(at, 2 * BLOCK); + // SAFETY: our view. + unsafe { UnmapViewOfFile(view) }; } #[test] @@ -934,7 +1008,7 @@ mod tests { struct View(MEMORY_MAPPED_VIEW_ADDRESS); impl Drop for View { fn drop(&mut self) { - title_memory_remapped(self.0.Value as usize, SIZE); + title_memory_unmapping(self.0.Value as usize, SIZE); // SAFETY: our view is still mapped. unsafe { UnmapViewOfFile(self.0) }; } @@ -1060,6 +1134,7 @@ mod tests { let mut local = [0u8; 16]; let at = local.as_mut_ptr() as usize; assert!(!is_view(at, at + local.len())); + title_memory_unmapping(p, 3 * BLOCK); // SAFETY: our views and placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); @@ -1069,7 +1144,6 @@ mod tests { } windows_sys::Win32::Foundation::CloseHandle(section); } - title_memory_remapped(p, 3 * BLOCK); } /// Blocks of a placeholder between views are reported once, then not @@ -1144,6 +1218,7 @@ mod tests { title_memory_remapped(p + BLOCK, BLOCK); assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + title_memory_unmapping(p, 3 * BLOCK); // SAFETY: our views and placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); @@ -1153,7 +1228,6 @@ mod tests { } windows_sys::Win32::Foundation::CloseHandle(section); } - title_memory_remapped(p, 3 * BLOCK); } /// A write or mapping that runs past the end of the address space (a diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index fe5b4c5..56d56ca 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -1028,7 +1028,7 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { continue; }; physical.forget_view(at, size, &slice); - victory_gpu::title_memory_remapped(at, size); + victory_gpu::title_memory_unmapping(at, size); // SAFETY: a view we mapped; it becomes a placeholder again. unsafe { UnmapViewOfFile2( From 037596241a0328d9343dcc676ea7d3a67acaf2fd Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 22:10:47 -0600 Subject: [PATCH 167/445] Argument clamps in batches (VICTORY_INDIRECT_BATCH) One pass clamps the arguments of all indirect executions between two points where they may change; its jobs are in upload memory that is filled while the list is recorded. The replayed frame: 2,355 clamps become 980 passes, 86.1 -> 77.7 ms; with VICTORY_INDIRECT_BATCH=2 133 passes, 84.6 -> 75.3 ms. Replay: --batch-clamps, --only-buffers, --listing; --compare runs turn by turn. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 18 ++ crates/victory-gpu/src/draw.rs | 144 ++++++++- crates/victory-gpu/src/host.rs | 46 +++ crates/victory-gpu/src/indirect.rs | 382 +++++++++++++++++++++++ crates/victory-gpu/src/indirect/batch.rs | 276 ++++++++++++++++ crates/victory-gpu/src/list.rs | 13 +- crates/victory-gpu/src/replay/edit.rs | 379 +++++++++++++++++++++- crates/victory-gpu/src/replay/play.rs | 282 ++++++++++++++--- docs/replay.md | 5 +- 9 files changed, 1492 insertions(+), 53 deletions(-) create mode 100644 crates/victory-gpu/src/indirect/batch.rs diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index f73ea08..147106a 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -53,12 +53,21 @@ pub(crate) struct Replay { /// Leave out the argument clamps: what they bound is kept from a first run. #[arg(long)] skip_clamps: bool, + /// The argument clamps in batches, as VICTORY_INDIRECT_BATCH does (2: + /// a wait before every indirect dispatch). + #[arg(long, num_args = 0..=1, default_missing_value = "1", default_value_t = 0)] + batch_clamps: u32, /// Leave out the hash and compare passes over card buffers. #[arg(long)] skip_hash_passes: bool, /// Where buffers lie. #[arg(long, value_enum, default_value_t = Buffers::AsRecorded)] buffers: Buffers, + /// With --buffers, only the buffers all of these match: `name=`, + /// `min=`, `max=`, `seen=`, + /// `id=..`, or `!` and one of those (may be given several times). + #[arg(long)] + only_buffers: Vec, /// One ExecuteCommandLists for the whole frame. #[arg(long)] one_submit: bool, @@ -119,6 +128,9 @@ pub(crate) struct Replay { /// capture's `shaders` folder. #[arg(long)] dump: Option, + /// Only write the frame's buffers and the commands of these lists (`3..7`). + #[arg(long)] + listing: Option, /// Use the D3D12 debug layer (slow). #[arg(long)] debug_layer: bool, @@ -139,6 +151,10 @@ pub(crate) fn run(r: Replay) -> Result<()> { } return Ok(()); } + if let Some(text) = &r.listing { + let lists = range(text).with_context(|| format!("--listing {text}"))?; + return play::listing(&r.folder, lists, &mut |line| println!("{line}")); + } let only = match &r.only { Some(text) => Some( range(text) @@ -157,9 +173,11 @@ pub(crate) fn run(r: Replay) -> Result<()> { Buffers::Vram => play::Buffers::Card, Buffers::Sysmem => play::Buffers::Pc, }, + only_buffers: r.only_buffers, no_barriers: r.no_barriers, merge_barriers: r.merge_barriers, skip_clamps: r.skip_clamps, + batch_clamps: r.batch_clamps, skip_hash_passes: r.skip_hash_passes, one_submit: r.one_submit, merge: !r.no_merge, diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 633088a..c2f61ce 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -186,6 +186,67 @@ fn windows() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1")) } +/// Whether indirect executions of one record are clamped in batches +/// (`crate::indirect::batch`; `VICTORY_INDIRECT_BATCH=0`: each on its own, +/// or in windows ([`windows`])). +/// +/// A frame of gameplay has 4,809 indirect executions (a capture: 3,523 mesh +/// draws, 948 dispatches, 338 draws), and with the windows still 2,355 +/// clamps: each a dispatch between two full waits, with the scratch buffer +/// moved twice. The replayed frame's 84.6 ms are 75.3 ms with the clamps in +/// 133 passes, and 77.7 ms in the 980 of this. +/// +/// A batch is opened by the first execution after a point where arguments +/// may have changed, and all executions up to the next such point read +/// theirs from it, each exactly the record it asks for (windows guess which +/// are next, and clamp what they do not know). Arguments in buffers change +/// by dispatches and by draws whose shaders store to buffers; those end the +/// batch, so the record an execution reads is clamped after all that was +/// recorded before it, and the pass waits for all of it, exactly as the +/// clamp of its own did. Between two executions of a batch is no wait of +/// ours: there is nothing between them to wait for but draws that store to +/// no buffer. +/// +/// `VICTORY_INDIRECT_BATCH=2`: a dispatch does not end the batch before the +/// title waits for it (a barrier, or a pipeline sync) or draws: what a +/// dispatch writes is not there for a later command without a wait, and +/// dispatches the title runs side by side (its tile classes, up to 92 at a +/// time) are not held up by waits of ours. Off: whether the title has ways +/// to wait that do not pass through its lists' methods is not known. +fn batches() -> u8 { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var("VICTORY_INDIRECT_BATCH").as_deref() { + Ok("0") => 0, + Ok("2") => 2, + _ => 1, + }) +} + +/// The records clamped by the pass opened last ([`batches`]). +struct Batch { + table: crate::indirect::batch::Table, + scratch: ID3D12Resource, + /// Dispatches since, which may have written arguments + /// (`VICTORY_INDIRECT_BATCH=2`). + wrote: bool, +} + +/// The host copies arguments were read from last: what a batch opens with, +/// as the executions after the first may read theirs from another one. +static ARGUMENT_COPIES: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); + +/// [`ARGUMENT_COPIES`] that live, and `first` put in front of them. +fn argument_copies(first: &std::sync::Arc) -> Vec<(u64, ID3D12Resource)> { + let mut copies = ARGUMENT_COPIES.lock().unwrap_or_else(|e| e.into_inner()); + let live: Vec<_> = copies.iter().filter_map(std::sync::Weak::upgrade).filter(|s| s.id() != first.id()).collect(); + *copies = std::iter::once(first) + .chain(&live) + .take(crate::indirect::batch::SOURCES) + .map(std::sync::Arc::downgrade) + .collect(); + live.iter().map(|s| (s.id(), s.buffer.clone())).collect() +} + /// What one title list has set, and what its host list was last given. #[derive(Default)] pub(crate) struct State { @@ -219,6 +280,9 @@ pub(crate) struct State { /// The indirect records clamped last, if later draws may still read /// them ([`windows`]). window: Option, + /// The records clamped in a batch, if later executions may still read + /// them ([`batches`]). + batch: Option, /// What the host list has: pipeline, root signature, heaps. host_pipeline: usize, /// Graphics, compute. @@ -2031,6 +2095,7 @@ impl State { list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); // SAFETY: an open list with everything set. unsafe { list.list.Dispatch(x, y, z) }; + self.buffers_written(); DISPATCHED.fetch_add(1, Ordering::Relaxed); } @@ -2301,6 +2366,7 @@ impl State { self.mesh_scissor(list, true); // SAFETY: an open list with everything set. unsafe { l6.DispatchMesh(x, 1, 1) }; + self.drew(crate::pipeline::host_pipeline(self.pipeline as This)); self.mesh_scissor(list, false); DRAWN.fetch_add(1, Ordering::Relaxed); true @@ -2702,6 +2768,7 @@ impl State { list.list .DrawInstanced(count, instances, from, first_instance) }; + self.drew(crate::pipeline::host_pipeline(self.pipeline as This)); DRAWN.fetch_add(1, Ordering::Relaxed); } if !ran { @@ -2803,6 +2870,7 @@ impl State { list.list .DrawIndexedInstanced(indices, instances, first, base, first_instance) }; + self.drew(crate::pipeline::host_pipeline(self.pipeline as This)); DRAWN.fetch_add(1, Ordering::Relaxed); } if !ran { @@ -2814,6 +2882,65 @@ impl State { } impl State { + /// Shaders that can write buffers were recorded: arguments may be others + /// from here on. + fn buffers_written(&mut self) { + match &mut self.batch { + Some(batch) if batches() == 2 => batch.wrote = true, + batch => *batch = None, + } + } + + /// A draw with the pipeline `p` was recorded (as [`State::buffers_written`] + /// if its shaders can store to buffers). + fn drew(&mut self, p: Option<&HostPipeline>) { + if p.is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) { + self.batch = None; + } + } + + /// The title waits for earlier work (a barrier or a pipeline sync). + pub(crate) fn synced(&mut self) { + if self.batch.as_ref().is_some_and(|b| b.wrote) { + self.batch = None; + } + } + + /// Where the clamped record of `kind` at `arguments` of the copy `args` + /// is, from the open batch or a new one ([`batches`]). `None` if it + /// cannot be clamped in one. + fn batched( + &mut self, + list: &HostList, + args: &std::sync::Arc, + arguments: u64, + kind: u32, + ) -> Option<(ID3D12Resource, u64)> { + const BATCH_USE: usize = usize::MAX - 0x78; + const DISPATCH: u32 = 2; + // Another host list, or this one after its reset ([`windows`]). + if list.first_use(BATCH_USE) { + self.batch = None; + } + // A draw after dispatches waits for them. + if kind != DISPATCH { + self.synced(); + } + let (id, offset) = (args.id(), args.offset(arguments)); + if let Some(b) = &mut self.batch + && let Some(at) = b.table.place(id, offset, kind) + { + return Some((b.scratch.clone(), at)); + } + self.batch = None; + let (mut table, scratch) = crate::indirect::open_batch(list, (id, &args.buffer), &argument_copies(args))?; + self.host_pipeline = 0; + self.host_roots[1] = 0; + let at = table.place(id, offset, kind)?; + self.batch = Some(Batch { table, scratch: scratch.clone(), wrote: false }); + Some((scratch, at)) + } + /// Indirect execution of a one-argument signature of `kind` (PC /// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with /// records `stride` bytes apart at title address `arguments`, and the @@ -2905,6 +3032,16 @@ impl State { why("mesh draws are switched off (VICTORY_MESH_TEST=skip)"); return false; } + // One record without a count: clamped in a batch (`batches`). + let batch = if batches() > 0 && max == 1 && count.is_none() { + args.refresh(list, arguments, len); + self.batched(list, &args, arguments, kind) + } else { + None + }; + if batch.is_some() { + self.window = None; + } // A window of records clamped in one pass (`windows`): for single // records without a count buffer, drawn by shaders that store to no // buffer. Anything else ends the window: it uses the scratch buffer @@ -2928,7 +3065,7 @@ impl State { .filter(|w| same(w) && offset >= w.base) .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records)) .map(|w| (w.scratch.clone(), offset - w.base)); - let (bounded, at) = match hit { + let (bounded, at) = match batch.or(hit) { Some(hit) => hit, None => { // A record a short step after the last window's last one @@ -3018,6 +3155,11 @@ impl State { if kind == MESH { self.mesh_scissor(list, false); } + if kind == DISPATCH { + self.buffers_written(); + } else { + self.drew(Some(p)); + } // The scratch buffer stays readable as arguments: the next draw of // the window reads it with no barrier, and the next clamp moves it // back (`crate::indirect`). diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 8e3572a..67622d7 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -767,6 +767,10 @@ mod tests { } } +/// The batches of clamped records in one scratch buffer +/// ([`HostList::batch_place`]). +const BATCHES: u32 = 8; + /// A host command list and its allocator, always used together. pub(crate) struct HostList { allocator: ID3D12CommandAllocator, @@ -802,6 +806,9 @@ pub(crate) struct HostList { /// Device-local scratch buffer for clamped indirect arguments (`indirect`), /// grown to the largest indirect execution recorded on the list. indirect_args: Mutex>, + /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and + /// how many batches of this recording have a place in them. + batch_args: Mutex<(Vec, u32)>, /// Counts the list in [`ALIVE`] while it lives. _alive: Counted, /// The texts of the markers `note_op` set, in order (for device-removed @@ -3221,6 +3228,7 @@ impl Host { budget: OnceLock::new(), card_budget: OnceLock::new(), indirect_args: Mutex::default(), + batch_args: Mutex::default(), _alive: Counted::new(), #[cfg(feature = "diagnostics")] notes: Mutex::default(), @@ -4873,6 +4881,7 @@ impl HostList { if let Some((scratch, _)) = scratch { self.indirect_common(&scratch); } + self.batches_common(); self.card_budget_out(); #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { @@ -5594,6 +5603,43 @@ impl HostList { Some(buffer) } + /// Where the next batch of clamped records goes: a device-local buffer + /// the list keeps from recording to recording, the batch's place in it + /// and the state the buffer is in. Every batch of a recording has a place + /// of its own: the executions before it may still read theirs. + pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> { + use crate::indirect::batch::{JOBS, SLOT}; + let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner()); + let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES); + if buffer == args.0.len() { + let size = u64::from(BATCHES * JOBS * SLOT); + let made = host()?.uav_buffer(size)?; + name(&made, || format!("indirect batches {size:#x}")); + args.0.push(made); + } + args.1 += 1; + // (Its first batch finds it as the recording before left it: + // `batches_common`.) + let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT }; + Some((args.0[buffer].clone(), i * JOBS * SLOT, state)) + } + + /// Before the list closes: the scratch buffers of the batched clamps go + /// back to the common state, where the next recording expects them. + fn batches_common(&self) { + let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner()); + let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize; + let barriers: Vec = args.0[..used] + .iter() + .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON)) + .collect(); + if !barriers.is_empty() { + // SAFETY: an open list and live buffers this recording left in + // `INDIRECT_ARGUMENT`. + unsafe { self.list.ResourceBarrier(&barriers) }; + } + } + /// Moves `scratch` back to the common state if a clamp left it readable /// as indirect arguments ([`HostList::indirect_readable`]): where the /// list's first clamp expects it. Done before the list closes and before diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index f8f961b..275a5fd 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -17,6 +17,10 @@ //! execution was followed by a move of the scratch buffer back to the //! common state, which drivers may treat as a full wait. //! +//! The executions of one record without a count buffer (all the title's) +//! are clamped in batches ([`batch`], `VICTORY_INDIRECT_BATCH`): the rest of +//! this is for the others. +//! //! When a count buffer is given, threads at or past `min(max, count)` return //! immediately without charging the list's budget or reading uninitialized //! tail slots. Each list has a budget (2^27 vertex instances or threads, @@ -36,6 +40,8 @@ use windows::core::s; use crate::host::{HostList, host, transition}; +pub(crate) mod batch; + const SOURCE: &str = r#" #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" cbuffer Record : register(b0) { @@ -478,6 +484,70 @@ fn record_clamp_as( true } +/// The batched clamp's pipeline ([`batch`]). +fn batch_clamp() -> Option<&'static Clamp> { + static CLAMP: std::sync::OnceLock> = std::sync::OnceLock::new(); + CLAMP + .get_or_init(|| { + let made = host().ok_or_else(windows::core::Error::empty).and_then(|h| make_from(&h.device, batch::SOURCE)); + match made { + Ok(c) => Some(c), + Err(e) => { + tracing::warn!(error = %e, "no batched argument clamp: records are clamped one at a time"); + None + } + } + }) + .as_ref() +} + +/// Opens a batch in `list` ([`batch`]): a pass that clamps the records of +/// the executions recorded after it, of `source` (a host copy's number and +/// buffer) and of the `recent` ones after it. The table to add them to, +/// and the scratch buffer its places are in. Replaces the list's compute +/// root signature and pipeline (callers bind theirs after). `None` if the +/// clamp is not available. +pub(crate) fn open_batch( + list: &HostList, + source: (u64, &ID3D12Resource), + recent: &[(u64, ID3D12Resource)], +) -> Option<(batch::Table, ID3D12Resource)> { + let c = batch_clamp()?; + let budget = list.budget()?; + let (jobs, at) = list.scratch(batch::TABLE)?; + let (dst, base, before) = list.batch_place()?; + let gpu = |b: &ID3D12Resource| { + // SAFETY: a live buffer. + Some(unsafe { b.GetGPUVirtualAddress() }).filter(|at| at.is_multiple_of(4)) + }; + // A source there is none of is the first again, which no job names. + let mut ids = [0u64; batch::SOURCES]; + let mut sources = [gpu(source.1)?; batch::SOURCES]; + ids[0] = source.0; + let others = recent.iter().filter(|r| r.0 != source.0).take(batch::SOURCES - 1); + for (i, (id, buffer)) in others.enumerate() { + if let Some(at) = gpu(buffer) { + // Bound, and read only if a job names it: kept alive like the + // copies draws read (`Shadow::refresh`). + list.keep(buffer); + (ids[i + 1], sources[i + 1]) = (*id, at); + } + } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::IndirectBounded, 1); + batch::record(c, &list.list, (&dst, before), budget, sources, jobs); + // SAFETY: the list's own upload memory of that many bytes, 256-byte + // aligned, until it is reset. + Some((unsafe { batch::Table::new(at, base, ids) }, dst)) +} + +/// The batched clamp's root signature and pipeline on `device`, for the +/// replayer. +#[cfg(feature = "diagnostics")] +pub(crate) fn batch_for(device: &ID3D12Device) -> windows::core::Result<(ID3D12RootSignature, ID3D12PipelineState)> { + make_from(device, batch::SOURCE).map(|c| (c.root, c.pso)) +} + fn uav_barrier() -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, @@ -1716,6 +1786,318 @@ void main() { assert_eq!(hits, expected, "every record of both windows runs once"); } } + + /// A command signature of one argument of `kind` on `device`. + fn one_argument(device: &ID3D12Device, kind: u32, stride: u32) -> ID3D12CommandSignature { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: stride, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + // SAFETY: a valid single-argument command signature description. + unsafe { + device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig).unwrap(); + } + sig.unwrap() + } + + /// What a batch's table says of records added to it: one job per + /// record, charged for every execution that reads it, and none for what + /// the pass cannot read. + #[test] + fn batch_tables() { + use batch::{JOBS, SLOT, TABLE, TIMES, Table, job}; + let mut memory = vec![0xffff_ffffu32; TABLE as usize / 4 + 1]; + // SAFETY: the vector holds the table and outlives its use. + let mut t = unsafe { Table::new(memory.as_mut_ptr().cast(), 4096, [7, 9, 0, 0]) }; + assert_eq!(t.place(7, 64, 10), Some(4096)); + assert_eq!(t.place(9, 64, 10), Some(4096 + u64::from(SLOT))); + assert_eq!(t.place(7, 64, 2), Some(4096 + 2 * u64::from(SLOT)), "another kind is another record"); + // The same record again: the same place, charged twice. + assert_eq!(t.place(9, 64, 10), Some(4096 + u64::from(SLOT))); + assert_eq!(&memory[..4], [3, 0xffff_ffff, 0xffff_ffff, 0xffff_ffff]); + assert_eq!(memory[4..8], [job(0, 10, 1), 64, 4096, 0]); + assert_eq!(memory[8..12], [job(1, 10, 2), 64, 4096 + SLOT, 0]); + assert_eq!(job(1, 10, 2), 1 | 10 << 4 | 3 << 8 | 2 << 16); + // Not a copy of the pass, not on 4 bytes, past 32 bits, not a kind. + for (id, offset, kind) in [(8, 64, 10), (7, 66, 10), (7, 1 << 32, 10), (7, u64::from(u32::MAX) & !3, 10), (7, 64, 3)] { + assert_eq!(t.place(id, offset, kind), None); + } + // Read more often than one job may be charged for: another job. + for _ in 1..TIMES { + assert_eq!(t.place(7, 64, 10), Some(4096)); + } + assert_eq!(t.place(7, 64, 10), Some(4096 + 3 * u64::from(SLOT))); + assert_eq!(t.place(7, 64, 10), Some(4096 + 3 * u64::from(SLOT))); + for i in 4..u64::from(JOBS) { + assert_eq!(t.place(7, 1024 + 16 * i, 0), Some(4096 + i * u64::from(SLOT))); + } + assert_eq!(t.place(7, 1024, 1), None, "full"); + assert_eq!(t.place(7, 1024 + 16 * 5, 0), Some(4096 + 5 * u64::from(SLOT))); + assert_eq!((memory[0], memory[TABLE as usize / 4]), (JOBS, 0xffff_ffff)); + } + + /// A batch clamps records exactly as the clamp of one execution does, of + /// any kind, sensible or not; they are added to its table after the pass + /// was recorded; it charges each as often as it is read. + #[test] + fn warp_batch_clamps_as_the_clamp_of_one_does() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP"); + let kinds = [0u32, 1, 2, 10]; + let values = [0u32, 1, 3, 100, 65_535, 65_536, 1 << 20, 1 << 24, (1 << 26) + 1, u32::MAX]; + // Every kind with many records, in two sources. + let mut records: Vec<(u32, [u32; 5])> = Vec::new(); + for kind in kinds { + for (i, a) in values.into_iter().enumerate() { + for (k, b) in values.into_iter().enumerate() { + records.push((kind, [a, b, values[(i * 3 + k) % 4], 77, 0xABCD])); + } + } + } + // In passes of so few that the budget holds whatever one asks for, + // and one pass of them all, which it does not. + let (src, src_ptr, src_gpu) = warp.shared_buffer(64 << 10); + let (_other, other_ptr, other_gpu) = warp.shared_buffer(64 << 10); + for (i, (_, words)) in records.iter().enumerate() { + for (w, word) in words.iter().enumerate() { + // SAFETY: 400 records of 32 bytes in 64 KiB. + unsafe { + src_ptr.cast::().add(i * 8 + w).write_volatile(*word); + other_ptr.cast::().add(i * 8 + w).write_volatile(*word); + } + } + } + let (_budget, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (back, back_ptr, _) = warp.shared_buffer(64 << 10); + let dst = warp.default_uav(64 << 10); + let (_table, table_ptr, table_gpu) = warp.shared_buffer(batch::TABLE); + for (i, (kind, _)) in records.iter().enumerate().step_by(3) { + let offset = i as u64 * 32; + let words = batch::words(*kind).unwrap(); + let stride = words * 4; + let read = |p: *mut u8| -> Vec { + // SAFETY: the mapping holds more. + (0..words as usize).map(|w| unsafe { p.cast::().add(w).read_volatile() }).collect() + }; + let mut seen = Vec::new(); + for batched in [false, true] { + // SAFETY: mapped buffers; nothing runs. + unsafe { std::ptr::write_bytes(budget_ptr, 0, 256) }; + if batched { + batch::record(&pass, &warp.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu, other_gpu, src_gpu, src_gpu], table_gpu); + // SAFETY: the mapped table; the list has not run. + let mut table = unsafe { batch::Table::new(table_ptr, 0, [1, 2, 0, 0]) }; + assert_eq!(table.place(1 + i as u64 % 2, offset, *kind), Some(0)); + } else { + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + (&src, offset), + None, + (*kind, stride, 1), + false, + )); + } + // SAFETY: an open list; the records are readable as arguments. + unsafe { + warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + warp.list.CopyBufferRegion(&back, 0, &dst, 0, u64::from(stride)); + warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); + } + warp.submit_and_wait(); + // SAFETY: the list has run; mapped words. + let budget: Vec = (0..3).map(|k| unsafe { budget_ptr.cast::().add(k).read_volatile() }).collect(); + seen.push((read(back_ptr), budget)); + } + // (A mesh record that asks for nothing notes nothing.) + assert_eq!(seen[0], seen[1], "record {i} of kind {kind}: {:?}", records[i].1); + } + } + + /// Records past the list's budget come out empty, and one read by many + /// executions is charged for each. + #[test] + fn warp_batch_charges_every_execution() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP"); + const BUDGET: u32 = 1 << 27; + // 2^26 vertices each, as much as a draw is let run: two fill it. + for (times, records, filled) in [(1u32, 3u64, 2usize), (2, 1, 1), (1, 1, 1), (3, 1, 0)] { + let (_src, src_ptr, src_gpu) = warp.shared_buffer(64 << 10); + let (_budget, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (back, back_ptr, _) = warp.shared_buffer(1024); + let (_table, table_ptr, table_gpu) = warp.shared_buffer(batch::TABLE); + let dst = warp.default_uav(64 << 10); + batch::record(&pass, &warp.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu; 4], table_gpu); + // SAFETY: mapped buffers, which the list has not read yet. + let mut table = unsafe { + std::ptr::write_bytes(budget_ptr, 0, 256); + for r in 0..records { + for (w, word) in [1u32 << 24, 4, 5, 6].into_iter().enumerate() { + src_ptr.cast::().add(r as usize * 4 + w).write_volatile(word); + } + } + batch::Table::new(table_ptr, 0, [1, 0, 0, 0]) + }; + for _ in 0..times { + for r in 0..records { + assert_eq!(table.place(1, r * 16, 0), Some(r * u64::from(batch::SLOT))); + } + } + // SAFETY: an open list; the records are readable as arguments. + unsafe { + warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + warp.list.CopyBufferRegion(&back, 0, &dst, 0, 256); + } + warp.submit_and_wait(); + // SAFETY: the list has run; mapped words. + let (spent, out): (u32, Vec) = unsafe { + ( + budget_ptr.cast::().read_volatile(), + (0..records as usize).map(|r| back_ptr.cast::().add(r * batch::SLOT as usize / 4).read_volatile()).collect(), + ) + }; + assert_eq!(out.iter().filter(|&&v| v == 1 << 24).count(), filled, "{times} times {records}: {out:?}"); + assert!(out.iter().all(|&v| v == 0 || v == 1 << 24)); + assert_eq!(spent, BUDGET.min((1 << 26) * times * records as u32)); + } + } + + /// Two batches through a host list, twice (the second recording finds + /// the scratch buffer as the first one's end left it): executions with + /// nothing between them read what they asked for, of two source buffers, + /// the second batch while the first one's places are still read. With + /// the debug layer on no barrier names a state the buffer is not in. + #[test] + fn host_list_batches() { + let Some(host) = super::host() else { + return; + }; + let _ = host.log_messages(); + let Ok(list) = host.new_list() else { + return; + }; + let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + let signature = one_argument(&host.device, 2, 12); + let mut sources = Vec::new(); + for first in [1u32, 100] { + let Some((buffer, ptr)) = host.shared_buffer(1024) else { + return; + }; + for i in 0..16u32 { + for (w, word) in [first + i, 1, 1].into_iter().enumerate() { + // SAFETY: inside the mapping. + unsafe { ptr.cast::().add(i as usize * 8 + w).write_volatile(word) }; + } + } + sources.push(buffer); + } + let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else { + return; + }; + // SAFETY: a live buffer. + let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; + for _ in 0..2 { + // SAFETY: the mapping holds 256 bytes; nothing runs. + unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) }; + let mut expected = 0; + // More batches than one scratch buffer holds. + for k in 0..12u32 { + let (mut table, scratch) = + open_batch(&list, (1, &sources[0]), &[(1, sources[0].clone()), (2, sources[1].clone())]).unwrap(); + // SAFETY: an open list; the worker's root signature and + // pipeline; buffers the test holds until the list has run. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + } + for (id, record) in [(1u64, 3 + k % 4), (2, 5), (1, 0), (2, 5)] { + let at = table.place(id, u64::from(record) * 32, 2).unwrap(); + // SAFETY: as above. + unsafe { list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0) }; + expected += record + if id == 1 { 1 } else { 100 }; + } + } + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + assert_eq!(hits, expected, "every execution runs what it asked for"); + } + } + + /// What clamps of a frame cost on the card one by one and in batches + /// (ignored: a measurement): 2,355 executions of an empty dispatch, in + /// 49 lists' worth of runs, as in the captured frame. + #[test] + #[ignore] + fn batch_costs() { + let Some(mut gpu) = WarpHarness::on(false) else { + return; + }; + const EXECUTIONS: u32 = 2355; + let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile"); + let sig = gpu.signature(2, 12); + let groups: Vec = vec![1; 2048]; + let src = dispatch_records(&gpu, &groups, 32); + // SAFETY: a live buffer. + let src_gpu = unsafe { src.GetGPUVirtualAddress() }; + let budget = gpu.default_uav(256); + let hits = gpu.default_uav(256); + // SAFETY: live buffers. + let (budget_gpu, hits_gpu) = unsafe { (budget.GetGPUVirtualAddress(), hits.GetGPUVirtualAddress()) }; + let (_tables, tables_ptr, tables_gpu) = gpu.shared_buffer(batch::TABLE * 2400); + let dst = gpu.default_uav(4 << 20); + for run in [0u32, 2355 / 49, 5, 1] { + let mut best = f64::MAX; + for _ in 0..6 { + let mut state = D3D12_RESOURCE_STATE_COMMON; + let mut table = batch::Table::default(); + for i in 0..EXECUTIONS { + if run == 0 { + assert!(record_clamp_as(&gpu.clamp, &gpu.list, (&dst, state), budget_gpu, (&src, u64::from(i % 2048) * 32), None, (2, 12, 1), false)); + } else if i % run == 0 { + let k = u64::from(i / run) * batch::TABLE; + batch::record(&pass, &gpu.list, (&dst, state), budget_gpu, [src_gpu; 4], tables_gpu + k); + // SAFETY: the mapped table; the list has not run. + table = unsafe { batch::Table::new(tables_ptr.add(k as usize), 0, [1, 0, 0, 0]) }; + } + state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + let at = if run == 0 { 0 } else { table.place(1, u64::from(i % 2048) * 32, 2).unwrap() }; + // SAFETY: an open list; live buffers. + unsafe { + if run == 0 || i % run == 0 { + gpu.list.SetComputeRootSignature(&gpu.worker.root); + gpu.list.SetPipelineState(&gpu.worker.pso); + gpu.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + } + gpu.list.ExecuteIndirect(&sig, 1, &dst, at, None, 0); + } + } + let t = std::time::Instant::now(); + gpu.submit_and_wait(); + best = best.min(t.elapsed().as_secs_f64() * 1e3); + } + let what = if run == 0 { "each clamped on its own".to_owned() } else { format!("a batch every {run}") }; + println!("{EXECUTIONS} indirect dispatches, {what}: {best:.2} ms"); + } + } } /// The benchmark of the clamp and its barriers (ignored by default). diff --git a/crates/victory-gpu/src/indirect/batch.rs b/crates/victory-gpu/src/indirect/batch.rs new file mode 100644 index 0000000..1f65388 --- /dev/null +++ b/crates/victory-gpu/src/indirect/batch.rs @@ -0,0 +1,276 @@ +//! Clamps of many executions in one pass: the arguments of every indirect +//! execution between two points where they may change are bounded together, +//! at the first of them. +//! +//! The executions that come after it are not known yet when the pass is +//! recorded, so it reads what to clamp from a table of jobs in upload +//! memory, which the CPU goes on filling while the list is recorded: the +//! pass is as wide as the table and its threads past the count do nothing. +//! An execution that asks for a record already in the table (the title's +//! tile classes) reads the same clamped one. +//! +//! What the records charge the list's budget is as for records clamped +//! alone, times the executions that read them. + +use windows::Win32::Graphics::Direct3D12::*; + +use super::{Clamp, uav_barrier}; +use crate::host::transition; + +/// The jobs of one pass. +pub(crate) const JOBS: u32 = 256; +/// The bytes of its table in upload memory: the count, then the jobs. +pub(crate) const TABLE: u64 = 16 + 16 * JOBS as u64; +/// The bytes of a clamped record's place in the scratch buffer. +pub(crate) const SLOT: u32 = 32; +/// The source buffers a pass can read. +pub(crate) const SOURCES: usize = 4; +/// The most executions charged by one job: the most a record costs (2^26) +/// as often still fits 32 bits. +pub(crate) const TIMES: u32 = 31; + +pub(crate) const SOURCE: &str = r#" +#define RS "SRV(t0), SRV(t1), SRV(t2), SRV(t3), SRV(t4), UAV(u0), UAV(u1)" +ByteAddressBuffer src0 : register(t0); +ByteAddressBuffer src1 : register(t1); +ByteAddressBuffer src2 : register(t2); +ByteAddressBuffer src3 : register(t3); +// The count, 12 bytes of nothing, then per job: source (bits 0-1), kind +// (4-7), words (8-11) and the executions that read it (16-31); the +// record's offset in the source; its place in the scratch buffer; nothing. +ByteAddressBuffer jobs : register(t4); +RWByteAddressBuffer dst_args : register(u0); +RWByteAddressBuffer budget : register(u1); +static const uint BUDGET = 1u << 27; +static const uint GROUPS = 1u << 20; +groupshared uint costs[64]; +groupshared uint fits[64]; +groupshared uint largest_asked; +groupshared uint all_asked; +uint load(uint source, uint at) { + if (source == 0) return src0.Load(at); + if (source == 1) return src1.Load(at); + if (source == 2) return src2.Load(at); + return src3.Load(at); +} +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { + uint count = jobs.Load(0); + bool active = id.x < count; + uint4 job = uint4(0, 0, 0, 0); + uint record[5] = {0, 0, 0, 0, 0}; + uint cost = 0; + uint asked = 0; + uint kind = 0; + uint words = 0; + if (gi == 0) { + largest_asked = 0; + all_asked = 0; + } + // As the clamp of one execution (`super::SOURCE`) bounds them. + if (active) { + job = jobs.Load4(16 + id.x * 16); + kind = (job.x >> 4) & 15; + words = min((job.x >> 8) & 15, 5); + for (uint w = 0; w < words; w++) { + record[w] = load(job.x & 3, job.y + w * 4); + } + if (kind <= 1) { + record[0] = min(record[0], 1u << 24); + record[1] = min(record[1], (1u << 26) / max(record[0], 1u)); + cost = record[0] * record[1]; + } else if (kind == 2) { + uint3 g = min(uint3(record[0], record[1], record[2]), uint3(65535u, 65535u, 65535u)); + if (g.z != 0 && g.x * g.y > GROUPS / g.z) { + g = uint3(0, 0, 0); + } + cost = g.x * g.y * g.z * 64u; + record[0] = g.x; + record[1] = g.y; + record[2] = g.z; + } else { + asked = record[0]; + record[0] = min(record[0], 65535u); + record[1] = min(record[1], 1u); + record[2] = min(record[2], 1u); + cost = record[0] * record[1] * record[2] * 128u; + } + cost *= job.x >> 16; + } + costs[gi] = cost; + GroupMemoryBarrierWithGroupSync(); + if (active && kind > 2) { + uint was; + InterlockedMax(largest_asked, asked, was); + InterlockedAdd(all_asked, min(asked, 1u << 24), was); + } + uint first = id.x - gi; + uint n = count > first ? min(64u, count - first) : 0u; + if (gi == 0 && n > 0) { + uint before; + budget.InterlockedOr(0, 0, before); + [allow_uav_condition] + while (before < BUDGET) { + uint next = before; + for (uint j = 0; j < n; j++) { + uint c = costs[j]; + if (c > 0 && next < BUDGET) { + next = (BUDGET - next <= c) ? BUDGET : (next + c); + } + } + if (next == before) break; + uint prev; + budget.InterlockedCompareExchange(0, before, next, prev); + if (prev == before) break; + before = prev; + } + uint at = before; + for (uint k = 0; k < n; k++) { + uint c = costs[k]; + uint fit = 1; + if (c > 0) { + fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u; + at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c); + } + fits[k] = fit; + } + } + GroupMemoryBarrierWithGroupSync(); + if (gi == 0 && n > 0 && all_asked > 0) { + uint was; + budget.InterlockedMax(4, largest_asked, was); + budget.InterlockedAdd(8, all_asked, was); + } + if (!active) { + return; + } + if (fits[gi] == 0) { + record[0] = 0; + record[1] = 0; + if (kind > 1) { + record[2] = 0; + } + } + for (uint s = 0; s < words; s++) { + dst_args.Store(job.z + s * 4, record[s]); + } +} +"#; + +/// The words of a record of `kind` (PC argument numbering). +pub(crate) fn words(kind: u32) -> Option { + super::min_stride(kind).map(|bytes| bytes / 4) +} + +/// A job's first word. +pub(crate) fn job(source: u32, kind: u32, times: u32) -> u32 { + source | (kind << 4) | (words(kind).unwrap_or(0) << 8) | (times << 16) +} + +/// The jobs of a pass as the CPU fills them ([`SOURCE`]), and where it +/// keeps which record is where. +#[derive(Default)] +pub(crate) struct Table { + /// The table in upload memory ([`TABLE`] bytes). + at: usize, + /// The place of the first clamped record in the scratch buffer. + base: u32, + /// The host copies it can read, by number ([`crate::shadow::Shadow::id`]; + /// 0: none). + sources: [u64; SOURCES], + /// How many executions each job is charged for so far. + times: Vec, + /// The job of a record (source, offset, kind). + known: std::collections::HashMap<(u32, u32, u32), u32>, +} + +impl Table { + /// A table at `at`, with no job yet. + /// + /// # Safety + /// `at` is [`TABLE`] bytes of mapped upload memory, 4-byte aligned, that + /// live until the list that reads them is recorded and is not run + /// before. + pub(crate) unsafe fn new(at: *mut u8, base: u32, sources: [u64; SOURCES]) -> Table { + // SAFETY: the caller's. + unsafe { at.cast::().write_volatile(0) }; + Table { at: at as usize, base, sources, ..Table::default() } + } + + /// The place in the scratch buffer of the record of `kind` at `offset` + /// of the host copy `id`, once the pass has run: a job of it is added if + /// there is none. `None` if the pass cannot read that copy or has no + /// room for another job. + pub(crate) fn place(&mut self, id: u64, offset: u64, kind: u32) -> Option { + let source = self.sources.iter().position(|&s| s == id)? as u32; + let offset = u32::try_from(offset).ok().filter(|o| o.is_multiple_of(4))?; + offset.checked_add(words(kind)? * 4)?; + let key = (source, offset, kind); + let table = self.at as *mut u32; + let place = |i: u32| u64::from(self.base + i * SLOT); + if let Some(&i) = self.known.get(&key) + && self.times[i as usize] < TIMES + { + self.times[i as usize] += 1; + // SAFETY: the job's own word of the table ([`Table::new`]). + unsafe { table.add(4 + 4 * i as usize).write_volatile(job(source, kind, self.times[i as usize])) }; + return Some(place(i)); + } + let i = self.times.len() as u32; + if i == JOBS { + return None; + } + self.times.push(1); + self.known.insert(key, i); + // SAFETY: inside the table: fewer than [`JOBS`] jobs before it. + unsafe { + let to = table.add(4 + 4 * i as usize); + to.write_volatile(job(source, kind, 1)); + to.add(1).write_volatile(offset); + to.add(2).write_volatile(self.base + i * SLOT); + to.add(3).write_volatile(0); + table.write_volatile(i + 1); + } + Some(place(i)) + } +} + +/// Records the pass over the table at `jobs` (a host address) into `dst`, +/// which is in state `before` and left in `INDIRECT_ARGUMENT`: after every +/// earlier shader write (the title's argument passes), before what reads +/// the clamped records. +pub(super) fn record( + c: &Clamp, + l: &ID3D12GraphicsCommandList, + (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES), + budget: u64, + sources: [u64; SOURCES], + jobs: u64, +) { + let after = transition( + dst, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + ); + // SAFETY: an open list; our root signature and pipeline; live buffers: + // the sources and the table are read in the common state (promoted). + unsafe { + l.ResourceBarrier(&[ + uav_barrier(), + transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]); + l.SetComputeRootSignature(&c.root); + l.SetPipelineState(&c.pso); + for (i, source) in sources.into_iter().enumerate() { + l.SetComputeRootShaderResourceView(i as u32, source); + } + l.SetComputeRootShaderResourceView(SOURCES as u32, jobs); + l.SetComputeRootUnorderedAccessView(SOURCES as u32 + 1, dst.GetGPUVirtualAddress()); + l.SetComputeRootUnorderedAccessView(SOURCES as u32 + 2, budget); + l.Dispatch(JOBS.div_ceil(64), 1, 1); + // Nothing else the pass writes is read before the next full wait + // (the budget, by the next pass): only the records have to be there. + l.ResourceBarrier(&[after]); + } +} diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 44c8965..a7104ac 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -742,6 +742,9 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> if let Some(list) = host_list(this) && !barriers.is_null() { + if count > 0 { + with_state(this, |_, state| state.synced()); + } // SAFETY: the title passes `count` barriers. let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) }; let mut host: Vec = barriers @@ -1396,7 +1399,14 @@ extern "system" fn set_pipeline(this: This, pipeline: This) { /// bottom of the pipe `(flags, control, address, size)`. Host lists order /// their own work and every submission is waited for, so there is nothing /// to do. -extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _size: u64) {} +/// (Arguments may be what earlier shaders wrote from here on: +/// `State::synced`.) +extern "system" fn sync(this: This, _flags: u32, _control: u32, _address: u64, _size: u64) { + #[cfg(windows)] + with_state(this, |_, state| state.synced()); + #[cfg(not(windows))] + let _ = this; +} /// Reset with console flags `(allocator, pipeline, flags)`; the flags only /// tune the console's command memory. @@ -1943,6 +1953,7 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { && let Some(list) = host_list(this) { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + with_state(this, |_, state| state.synced()); // SAFETY: the same layout; no resource named. let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; // SAFETY: an open list. diff --git a/crates/victory-gpu/src/replay/edit.rs b/crates/victory-gpu/src/replay/edit.rs index 08184a3..a9c7ce3 100644 --- a/crates/victory-gpu/src/replay/edit.rs +++ b/crates/victory-gpu/src/replay/edit.rs @@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet}; -use super::wire::{ALL, Barrier, Cmd, NONE, Va}; +use super::wire::{ALL, Barrier, Cmd, NONE, Va, slot}; /// The buffer the clamped arguments of all clamp passes lie in, in lists /// edited by [`clamps`]. @@ -298,6 +298,276 @@ pub fn skip_clamps(cmds: Vec, clamps: &[Clamp]) -> Vec { out } +/// The root signature, pipeline and table of the batched clamp +/// (`crate::indirect::batch`), and the scratch buffer it writes in the +/// first list of the frame (the next lists' are the ids before it), in lists +/// edited by [`batch_clamps`]. +pub const BATCH_ROOT: u32 = u32::MAX - 2; +pub const BATCH: u32 = u32::MAX - 3; +pub const BATCH_JOBS: u32 = u32::MAX - 4; +pub const BATCH_SCRATCH: u32 = u32::MAX - 16; + +/// What [`batch_clamps`] did to a list. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Batched { + /// Clamp passes before; after; the records the latter clamp. + pub clamps: u32, + pub batches: u32, + pub jobs: u32, + /// The bytes of the scratch buffer. + pub scratch: u64, +} + +/// A clamp batch being filled by [`batch_clamps`]. +struct Batch { + /// Where its table is in the jobs, and its root views in the list. + table: usize, + at: usize, + sources: Vec, + /// By source, offset and kind: the job, and how often it is read. + known: HashMap<(u32, u64, u32), (u32, u32)>, + n: u32, + base: u64, +} + +/// The list with its clamps done in batches, as `crate::draw` does with +/// `VICTORY_INDIRECT_BATCH`: one pass at the first execution after a +/// point where arguments may have changed (a wait for shader writes, with +/// dispatches since the batch before it; or a draw, with dispatches since +/// the last wait). `careful`: before indirect dispatches too, with +/// dispatches since the last wait. `compute`: the pipelines that are compute +/// ones. The tables go to `jobs` (the contents of [`BATCH_JOBS`]). +pub fn batch_clamps( + cmds: Vec, + psos: &HashSet, + compute: &HashSet, + scratch: u32, + careful: bool, + jobs: &mut Vec, +) -> (Vec, Batched) { + use crate::indirect::batch::{JOBS, SLOT, SOURCES, TIMES, job}; + const DISPATCH: u32 = 2; + let mut done = Batched::default(); + let scratches: HashSet = { + let mut next = 0; + let found = find_clamps(&cmds, psos, &mut next); + found.iter().map(|c| c.scratch).collect() + }; + if scratches.is_empty() { + return (cmds, done); + } + let of_clamp = + |b: &Barrier| matches!(b, Barrier::Transition { res, .. } if scratches.contains(res)); + let moved = |before, after| Barrier::Transition { + flags: 0, + res: scratch, + sub: ALL, + before, + after, + }; + // What the last clamp into a scratch buffer clamped: source, offset, + // kind. + let mut clamps: HashMap = HashMap::new(); + let (mut bound, mut constants, mut views) = (NONE, [0u32; 6], [(NONE, 0u64); 5]); + let mut out: Vec = Vec::with_capacity(cmds.len()); + let mut open: Option = None; + let (mut written, mut dirty, mut readable) = (true, true, false); + let mut cmds = cmds.into_iter().peekable(); + while let Some(c) = cmds.next() { + match &c { + // A clamp's own commands: its root signature and all it sets. + Cmd::RootSignature { + graphics: false, .. + } if matches!(cmds.peek(), Some(Cmd::Pipeline { pso }) if psos.contains(pso)) => {} + Cmd::Pipeline { pso } => { + bound = *pso; + if !psos.contains(pso) { + out.push(c); + } + } + Cmd::Constants { + graphics: false, + values, + offset, + .. + } if psos.contains(&bound) => { + for (i, v) in values.iter().enumerate() { + if let Some(c) = constants.get_mut(*offset as usize + i) { + *c = *v; + } + } + } + Cmd::RootView { + graphics: false, + param, + va: Va::At { res, offset }, + .. + } if psos.contains(&bound) => { + if let Some(v) = views.get_mut(*param as usize) { + *v = (*res, *offset); + } + } + Cmd::Dispatch { .. } if psos.contains(&bound) => { + done.clamps += 1; + let (source, offset) = views[1]; + clamps.insert( + views[3].0, + (source, offset + u64::from(constants[3]), constants[0]), + ); + // What it was clamped for follows: a batch is open by then. + let full = + |o: &Batch| !o.sources.contains(&source) && o.sources.len() == SOURCES; + if dirty && (constants[0] != DISPATCH || careful) || open.as_ref().is_some_and(full) + { + open = None; + } + if open.is_some() { + continue; + } + done.batches += 1; + let table = jobs.len(); + jobs.resize(table + 16 + 16 * 2048, 0); + out.push(Cmd::Barriers { + all: vec![ + Barrier::Uav { + flags: 0, + res: NONE, + }, + moved(if readable { INDIRECT_ARGUMENT } else { 0 }, UNORDERED_ACCESS), + ], + }); + readable = true; + out.push(Cmd::RootSignature { + graphics: false, + root: BATCH_ROOT, + }); + out.push(Cmd::Pipeline { pso: BATCH }); + let at = out.len(); + let mut view = |kind, param: usize, res, offset| { + out.push(Cmd::RootView { + graphics: false, + kind, + param: param as u32, + va: Va::At { res, offset }, + }); + }; + for i in 0..SOURCES { + view(slot::SRV, i, source, 0); + } + view(slot::SRV, SOURCES, BATCH_JOBS, table as u64); + view(slot::UAV, SOURCES + 1, scratch, 0); + view(slot::UAV, SOURCES + 2, views[4].0, views[4].1); + out.push(Cmd::Dispatch { + groups: [JOBS.div_ceil(64), 1, 1], + }); + out.push(Cmd::Barriers { + all: vec![moved(UNORDERED_ACCESS, INDIRECT_ARGUMENT)], + }); + open = Some(Batch { + table, + at, + sources: Vec::new(), + known: HashMap::new(), + n: 0, + base: done.scratch, + }); + (written, dirty) = (false, false); + } + Cmd::Barriers { all } => { + if all.iter().any(of_clamp) { + continue; + } + let waits = |b: &Barrier| matches!(b, Barrier::Uav { res: NONE, .. }); + if all.iter().any(waits) { + if written { + open = None; + } + dirty = false; + } + out.push(c); + } + Cmd::Indirect { + signature, + most, + args, + at, + count, + count_at, + } if clamps.contains_key(args) => { + let (source, offset, kind) = clamps.get(args).copied().unwrap_or_default(); + let Some(o) = &mut open else { + // Not clamped by any batch: left out, which shows. + continue; + }; + let slot = match o.sources.iter().position(|&s| s == source) { + Some(i) => i, + None => { + o.sources.push(source); + let i = o.sources.len() - 1; + if let Some(Cmd::RootView { + va: Va::At { res, .. }, + .. + }) = out.get_mut(o.at + i) + { + *res = source; + } + i + } + }; + let offset = offset + at; + let entry = o.known.entry((source, offset, kind)).or_insert((o.n, 0)); + entry.1 += 1; + let (i, times) = *entry; + if i == o.n { + o.n += 1; + done.jobs += 1; + done.scratch = o.base + u64::from(o.n * SLOT); + // Wider than the live pass where its table is longer. + if let Some(Cmd::Dispatch { groups }) = out.get_mut(o.at + SOURCES + 3) { + groups[0] = groups[0].max(o.n.div_ceil(64)); + } + } + let place = o.base + u64::from(i * SLOT); + let words = [ + job(slot as u32, kind, times.min(TIMES)), + offset as u32, + place as u32, + 0, + ]; + let mut put = |at: usize, w: u32| { + jobs[o.table + at..o.table + at + 4].copy_from_slice(&w.to_le_bytes()); + }; + for (k, w) in words.into_iter().enumerate() { + put(16 + 16 * i as usize + 4 * k, w); + } + put(0, o.n); + out.push(Cmd::Indirect { + signature: *signature, + most: *most, + args: scratch, + at: place, + count: *count, + count_at: *count_at, + }); + if compute.contains(&bound) { + (written, dirty) = (true, true); + } + } + Cmd::Dispatch { .. } => { + (written, dirty) = (true, true); + out.push(c); + } + _ => out.push(c), + } + } + if readable { + out.push(Cmd::Barriers { + all: vec![moved(INDIRECT_ARGUMENT, 0)], + }); + } + (out, done) +} + #[cfg(test)] mod tests { use super::*; @@ -501,4 +771,111 @@ mod tests { [(RESULTS, 12), (RESULTS, 0), (6, 0), (RESULTS, 256 + 24)] ); } + + #[test] + fn clamps_are_batched() { + use crate::indirect::batch::job; + let clamp = |kind, offset, records, source| { + let view = |param, res| Cmd::RootView { + graphics: false, + kind: 2, + param, + va: Va::At { res, offset: 0 }, + }; + vec![ + barriers(&[uav(0), moved(5, 0x200, 8)]), + Cmd::RootSignature { + graphics: false, + root: 8, + }, + pso(9), + Cmd::Constants { + graphics: false, + param: 0, + offset: 0, + values: vec![kind, 32, records, offset, 0, 0], + }, + view(1, source), + view(2, source), + view(3, 5), + view(4, 6), + go(), + barriers(&[uav(0), moved(5, 8, 0x200)]), + ] + }; + let run = |at| Cmd::Indirect { + signature: 1, + most: 1, + args: 5, + at, + count: 0, + count_at: 0, + }; + // A dispatch, two indirect ones with a wait of the title's between + // them, then draws: a window of two and another buffer's. + let mut list = vec![pso(1), go()]; + list.extend(clamp(2, 0, 1, 70)); + list.extend([pso(1), run(0)]); + list.extend(clamp(2, 64, 1, 70)); + list.extend([pso(1), run(0), barriers(&[uav(0)])]); + list.extend(clamp(2, 64, 1, 70)); + list.extend([pso(1), run(0)]); + list.extend(clamp(10, 128, 2, 70)); + list.extend([pso(2), run(0), run(32), run(32)]); + list.extend(clamp(10, 256, 1, 71)); + list.extend([pso(2), run(0)]); + let (clamps, compute) = (HashSet::from([9]), HashSet::from([1])); + let table = 16 + 16 * 2048; + for (careful, batches) in [(false, 3), (true, 4)] { + let mut jobs = Vec::new(); + let (out, done) = batch_clamps(list.clone(), &clamps, &compute, 99, careful, &mut jobs); + assert_eq!((done.clamps, done.batches, done.jobs), (5, batches, 6), "careful {careful}"); + assert_eq!(jobs.len(), table * batches as usize); + let passes = out.iter().filter(|c| matches!(c, Cmd::Pipeline { pso: BATCH })).count(); + assert_eq!(passes, batches as usize); + // Nothing of the clamps is left; the title's wait is. + assert!(!out.contains(&pso(9)) && out.contains(&barriers(&[uav(0)]))); + let names_5 = |c: &Cmd| matches!(c, Cmd::Barriers { all } if all.iter().any(|b| matches!(b, Barrier::Transition { res: 5, .. }))); + assert!(!out.iter().any(names_5)); + let places: Vec = out + .iter() + .filter_map(|c| match c { + Cmd::Indirect { args: 99, at, .. } => Some(*at), + _ => None, + }) + .collect(); + assert_eq!(places, [0, 32, 64, 96, 128, 128, 160]); + // The last table: two records, one read twice, then one of the + // other buffer. + let word = |i: usize| { + let at = jobs.len() - table + 4 * i; + u32::from_le_bytes(jobs[at..at + 4].try_into().unwrap()) + }; + assert_eq!(word(0), 3); + let all: Vec = (4..16).map(word).collect(); + assert_eq!( + all, + [ + [job(0, 10, 1), 128, 96, 0], + [job(0, 10, 2), 160, 128, 0], + [job(1, 10, 1), 256, 160, 0] + ] + .concat() + ); + let sources: Vec = out + .iter() + .filter_map(|c| match c { + Cmd::RootView { param: 1, va: Va::At { res, .. }, .. } => Some(*res), + _ => None, + }) + .collect(); + assert_eq!(sources.last(), Some(&71)); + // It ends common, as it began. + assert_eq!(out.last(), Some(&barriers(&[moved(99, 0x200, 0)]))); + } + // A list without clamps is left as it is. + let plain = vec![pso(1), go(), barriers(&[uav(0)])]; + let (out, done) = batch_clamps(plain.clone(), &clamps, &compute, 99, false, &mut Vec::new()); + assert_eq!((out, done), (plain, Batched::default())); + } } diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index 5ad96c5..21ea8df 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -65,9 +65,13 @@ pub struct Options { /// Where the picture goes (default: `replay.png` in the capture). pub image: Option, pub buffers: Buffers, + /// Of those, only the ones all of these match ([`chosen`]). + pub only_buffers: Vec, pub no_barriers: bool, pub merge_barriers: bool, pub skip_clamps: bool, + /// The clamps in batches (`edit::batch_clamps`); 2: carefully. + pub batch_clamps: u32, pub skip_hash_passes: bool, pub one_submit: bool, /// Copies of what the CPU wrote leave alone what the card wrote in this @@ -97,9 +101,11 @@ impl Default for Options { top: 20, image: None, buffers: Buffers::AsRecorded, + only_buffers: Vec::new(), no_barriers: false, merge_barriers: false, skip_clamps: false, + batch_clamps: 0, skip_hash_passes: false, one_submit: false, merge: true, @@ -118,6 +124,7 @@ impl Options { self.no_barriers || self.merge_barriers || self.skip_clamps + || self.batch_clamps > 0 || self.skip_hash_passes || self.one_submit || self.wait_all @@ -132,6 +139,7 @@ impl Options { no_barriers: false, merge_barriers: false, skip_clamps: false, + batch_clamps: 0, skip_hash_passes: false, one_submit: false, wait_all: false, @@ -245,6 +253,32 @@ impl Report { } } +/// Whether `--only-buffers` means a buffer: all of `only` match it. +/// `name=`, `min=`, `max=`, +/// `seen=`, `id=..`; with `!` in front: that does not. +fn chosen(r: &wire::Resource, only: &[String]) -> bool { + only.iter().all(|f| { + let (no, f) = match f.strip_prefix('!') { + Some(f) => (true, f), + None => (false, f.as_str()), + }; + let (key, value) = f.split_once('=').unwrap_or(("name", f)); + let number = value.parse().unwrap_or(0u64); + let is = match key { + "min" => r.desc.width >= number, + "max" => r.desc.width <= number, + "seen" => { + matches!(&r.place, Place::Committed { props, .. } if format!("{:?}", gpu::seen(props)).eq_ignore_ascii_case(value)) + } + "id" => value.split_once("..").is_some_and(|(a, b)| { + (a.parse().unwrap_or(0)..b.parse().unwrap_or(u32::MAX)).contains(&r.id) + }), + _ => r.name.contains(value), + }; + is != no + }) +} + fn median(v: &[f64]) -> f64 { let mut v = v.to_vec(); v.sort_by(f64::total_cmp); @@ -311,20 +345,65 @@ pub fn dump(folder: &Path, text: &str) -> Result> { Ok(out) } +/// Writes, one line each, the commands of lists (by their place in the +/// frame), and before them the frame's buffers: `--listing`. +pub fn listing(folder: &Path, lists: (u32, u32), line: &mut dyn FnMut(&str)) -> Result<()> { + let frame = Frame::read(&find(folder)?.join("frame.bin"))?; + let pipelines: HashMap = + frame.pipelines.iter().map(|p| (p.id, p.name.as_str())).collect(); + for r in &frame.resources { + if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { + let place = match &r.place { + Place::Committed { props, .. } => format!("{:?}", gpu::seen(props)), + other => format!("{other:?}"), + }; + line(&format!("buffer {} {} bytes, {place}: {}", r.id, r.desc.width, r.name)); + } + } + let mut place = 0; + for (i, s) in frame.submits.iter().enumerate() { + for &l in s.lists.iter().filter(|&&l| l != MISSING) { + let here = place; + place += 1; + if here < lists.0 || here > lists.1 { + continue; + } + line(&format!("list {here} of submission {i}")); + for (n, c) in Cmd::all(&frame.lists[l as usize].commands.0)?.iter().enumerate() { + match c { + Cmd::Pipeline { pso } => { + line(&format!("{n} Pipeline {pso} {}", pipelines.get(pso).copied().unwrap_or_default())); + } + c => line(&format!("{n} {c:?}")), + } + } + } + } + Ok(()) +} + /// Loads a capture and runs it: the whole of `victory replay`. The reports, /// with what each is of. pub fn replay(folder: &Path, options: &Options) -> Result> { let mut player = Player::load(folder, options)?; let mut out = Vec::new(); if options.compare && options.edited() { + // Turn by turn: what else the machine does falls on both. let image = Some(player.folder.join("replay-unchanged.png")); - out.push(( - "unchanged".into(), - player.run(&Options { - image, - ..options.plain() - })?, - )); + let plain = Options { + image, + ..options.plain() + }; + let mut a = player.prepare(&plain)?; + let mut b = player.prepare(options)?; + let (mut stamps_a, mut stamps_b) = (Vec::new(), Vec::new()); + for _ in 0..options.loops.max(1) { + stamps_a = player.once(&plain, &mut a)?; + stamps_b = player.once(options, &mut b)?; + } + out.push(("unchanged".into(), player.finish(&plain, a, &stamps_a)?)); + out.push(("with the experiments".into(), player.finish(options, b, &stamps_b)?)); + return Ok(out); } let what = if options.edited() { "with the experiments" @@ -468,7 +547,7 @@ impl Player { *at = Instant::now(); }; let mut at = Instant::now(); - player.make_resources(options.buffers)?; + player.make_resources(options.buffers, &options.only_buffers)?; step("resources", &mut at); player.make_pipelines()?; step("pipelines", &mut at); @@ -558,7 +637,7 @@ impl Player { } } - fn make_resources(&mut self, buffers: Buffers) -> Result<()> { + fn make_resources(&mut self, buffers: Buffers, only: &[String]) -> Result<()> { // A heap of memory the CPU sees becomes one the card may write too: // what the CPU wrote is put back by the card. let props = |p: &wire::HeapProps, buffer: bool| -> D3D12_HEAP_PROPERTIES { @@ -602,7 +681,7 @@ impl Player { for h in &self.frame.heaps { let desc = D3D12_HEAP_DESC { SizeInBytes: h.size, - Properties: props(&h.props, used_by_buffers_only.contains(&h.id)), + Properties: props(&h.props, only.is_empty() && used_by_buffers_only.contains(&h.id)), Alignment: h.alignment, Flags: D3D12_HEAP_FLAGS(h.flags & !DROP), }; @@ -613,8 +692,15 @@ impl Player { self._heaps.extend(heap.map(|heap| (h.id, heap))); } let mut failed = 0; + let mut moves: BTreeMap = BTreeMap::new(); for (index, r) in self.frame.resources.iter().enumerate() { let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; + let moved = is_buffer && chosen(r, only); + if moved && let Place::Committed { props, .. } = &r.place { + let seen = gpu::seen(props); + 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 made: Option = None; let clear: Option = r.clear.map(|c| { @@ -637,7 +723,7 @@ impl Player { None => Err(windows::core::Error::empty()), }, Place::Committed { props: p, flags } => { - let p = props(p, is_buffer); + let p = props(p, moved); let state = if p.Type == D3D12_HEAP_TYPE_READBACK { D3D12_RESOURCE_STATE_COPY_DEST } else { @@ -700,6 +786,11 @@ impl Player { if failed > 0 { self.note(format!("{failed} resources could not be made again")); } + if buffers != Buffers::AsRecorded { + self.notes.push(format!( + "--buffers is of, by how the CPU saw them (buffers, bytes): {moves:?}" + )); + } Ok(()) } @@ -1800,6 +1891,17 @@ impl Player { .push(format!("{} pipelines match --skip-shader", skip.len())); } let hash = self.pipelines_named(COMPARE); + let clamp = self.pipelines_named(CLAMP); + let compute: HashSet = self + .frame + .pipelines + .iter() + .filter(|p| p.parts.iter().any(|part| matches!(part, wire::Part::Code { kind, .. } if *kind == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS.0))) + .map(|p| p.id) + .collect(); + let mut batched = edit::Batched::default(); + let mut jobs = Vec::new(); + let mut scratches = Vec::new(); let (mut skipped, mut hashed, mut uavs, mut merged) = (0, 0, 0, 0); let mut place = 0; let mut out = Vec::new(); @@ -1818,6 +1920,24 @@ impl Player { { cmds = edit::skip_clamps(cmds, c); } + if o.batch_clamps > 0 { + let scratch = edit::BATCH_SCRATCH - here; + let done; + (cmds, done) = edit::batch_clamps( + cmds, + &clamp, + &compute, + scratch, + o.batch_clamps > 1, + &mut jobs, + ); + batched.clamps += done.clamps; + batched.batches += done.batches; + batched.jobs += done.jobs; + if done.scratch > 0 { + scratches.push((scratch, done.scratch)); + } + } let mut n; if !skip.is_empty() { (cmds, n) = edit::skip_pipelines(cmds, &skip); @@ -1839,6 +1959,15 @@ impl Player { } out.push(lists); } + if o.batch_clamps > 0 { + report.notes.push(format!( + "--batch-clamps: {} clamp passes became {}, of {} records", + batched.clamps, batched.batches, batched.jobs + )); + if let Err(e) = self.make_batches(&jobs, &scratches) { + report.notes.push(format!("--batch-clamps failed: {e:#}")); + } + } if !skip.is_empty() { report .notes @@ -1862,6 +1991,44 @@ impl Player { out } + /// What lists edited by [`edit::batch_clamps`] name: the pass, its + /// tables and scratch buffers. + fn make_batches(&mut self, jobs: &[u8], scratches: &[(u32, u64)]) -> Result<()> { + let (root, pso) = crate::indirect::batch_for(&self.device)?; + self.roots.insert(edit::BATCH_ROOT, root); + self.pipelines.insert(edit::BATCH, pso); + let (table, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_UPLOAD, + jobs.len().max(4) as u64, + D3D12_RESOURCE_FLAG_NONE, + )?; + // SAFETY: a mapping of as many bytes. + unsafe { std::ptr::copy_nonoverlapping(jobs.as_ptr(), data.cast(), jobs.len()) }; + let mut all = vec![(edit::BATCH_JOBS, table)]; + for &(id, bytes) in scratches { + let (scratch, _) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_DEFAULT, + bytes.next_multiple_of(64 << 10), + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + )?; + all.push((id, scratch)); + } + for (id, res) in all { + // SAFETY: a live buffer. + let va = unsafe { res.GetGPUVirtualAddress() }; + let object = Object { + res, + va, + index: 0, + subs: 1, + }; + self.objects.insert(id, object); + } + Ok(()) + } + /// The clamp passes of each list of the frame, in order, and their /// results in [`RESULTS`] (by a run that keeps them). fn clamp_results(&mut self, report: &mut Report) -> Result>> { @@ -2126,7 +2293,8 @@ impl Player { wait: bool, ) -> Vec { let version = self.version_of.get(submit).copied().unwrap_or(0); - let clamps = self.pipelines_named(CLAMP); + let mut clamps = self.pipelines_named(CLAMP); + clamps.insert(edit::BATCH); let compares = self.pipelines_named(COMPARE); let mesh: HashSet = self .frame @@ -2713,6 +2881,16 @@ impl Player { /// Runs the frame as the options say. pub fn run(&mut self, o: &Options) -> Result { + let mut made = self.prepare(o)?; + let mut stamps = Vec::new(); + for _ in 0..o.loops.max(1) { + stamps = self.once(o, &mut made)?; + } + self.finish(o, made, &stamps) + } + + /// The lists for a run as the options say. + fn prepare(&mut self, o: &Options) -> Result<(Sends, Report)> { let mut report = Report { notes: self.notes.clone(), ..Default::default() @@ -2724,45 +2902,51 @@ impl Player { Vec::new() }; let submits = self.edited(o, &mut report, &clamps); - let built = self.build(&submits, o)?; - let mut stamps = Vec::new(); - for _ in 0..o.loops.max(1) { - self.restore(o.restore)?; - self.fresh = false; - stamps = self.send(&built, o)?; - if let Some((db, _, hash, _)) = self.picture_now()? { - report.pictures.push((db, hash)); - } - let ms = |a: u32, b: u32| { - stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency - }; - let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect(); - let (Some(first), Some(last)) = (lists.first(), lists.last()) else { - bail!("no lists to run"); - }; - let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref()); - report.delta_ms.push( - delta - .filter(|d| d.first > first.first) - .map(|d| ms(d.first, d.last)) - .sum(), - ); - report.frame_ms.push(ms(first.first, last.last)); - let each = |l: &[Built]| match (l.first(), l.last()) { - (Some(a), Some(b)) => ms(a.first, b.last), - _ => 0.0, - }; - report.submits = built - .steps - .iter() - .map(|(_, l)| (l.len(), each(l))) - .collect(); - report - .busy_ms - .push(report.submits.iter().map(|s| s.1).sum()); + Ok((self.build(&submits, o)?, report)) + } + + /// One run of the frame, noted in the report; its timestamps. + fn once(&mut self, o: &Options, (built, report): &mut (Sends, Report)) -> Result> { + self.restore(o.restore)?; + self.fresh = false; + let stamps = self.send(built, o)?; + if let Some((db, _, hash, _)) = self.picture_now()? { + report.pictures.push((db, hash)); } + let ms = |a: u32, b: u32| { + stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency + }; + let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect(); + let (Some(first), Some(last)) = (lists.first(), lists.last()) else { + bail!("no lists to run"); + }; + let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref()); + report.delta_ms.push( + delta + .filter(|d| d.first > first.first) + .map(|d| ms(d.first, d.last)) + .sum(), + ); + report.frame_ms.push(ms(first.first, last.last)); + let each = |l: &[Built]| match (l.first(), l.last()) { + (Some(a), Some(b)) => ms(a.first, b.last), + _ => 0.0, + }; + report.submits = built + .steps + .iter() + .map(|(_, l)| (l.len(), each(l))) + .collect(); + report + .busy_ms + .push(report.submits.iter().map(|s| s.1).sum()); + Ok(stamps) + } + + /// The report after the last run. + fn finish(&mut self, o: &Options, (built, mut report): (Sends, Report), stamps: &[u64]) -> Result { if o.detailed { - self.detail(&built, &stamps, o, &mut report); + self.detail(&built, stamps, o, &mut report); } if self.merging { let notes = self.merge_notes(o.loops)?; diff --git a/docs/replay.md b/docs/replay.md index 352f976..88dd0f3 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -56,12 +56,15 @@ with the presented one. | switch | does | |---|---| -| `--compare` | runs the frame unchanged first and prints the difference | +| `--compare` | runs the frame unchanged and with the experiments turn by turn, and prints the difference | | `--skip-clamps` | no argument clamps and no barriers of their scratch buffers; draws read arguments kept from a first run | +| `--batch-clamps` / `--batch-clamps 2` | argument clamps in batches, as `VICTORY_INDIRECT_BATCH=2` / `=1` does | | `--skip-hash-passes` | no compare/rehash passes over card buffers | | `--no-barriers` | no unordered-access barriers | | `--merge-barriers` | joins barrier calls with no work between them | | `--buffers vram` / `sysmem` | all buffers in the card's / the PC's memory | +| `--only-buffers ` | with `--buffers`: only the buffers all of these match: `name=`, `min=`, `max=`, `seen=No`, `Cached` or `Combined`, `id=..`, or `!` and one of them (repeatable) | +| `--listing 3..7` | only writes the frame's buffers and those lists' commands | | `--one-submit` | one `ExecuteCommandLists`, with a full wait between the former ones | | `--only 3..7` | runs these lists; of the others only barriers | | `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) | From 0d5e4c8cbf18b5d30811d02446261a416cfad89c Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 22:14:03 -0600 Subject: [PATCH 168/445] What shaders wrote is landed on a few threads, beside the guards (VICTORY_LAND) The relay's thread merged some 1,500 pieces of 64 KiB (98 MB) a frame one after the other: 45 ms in the frame's shape, of them 22 ms copying and merging, 18 ms the kernel's faults on the first write to each page of memory just made writable, 5 ms protection calls. Now one AVX2 pass a piece, in jobs on four threads, through a view of ours of the title's pages that is never guarded (VICTORY_LAND_BESIDE): 8 ms. The log splits a landing's time. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 255 +++++++++--- crates/victory-gpu/src/inplace.rs | 38 +- crates/victory-gpu/src/land.rs | 556 +++++++++++++++++++++++++++ crates/victory-gpu/src/land/tests.rs | 433 +++++++++++++++++++++ crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/safecopy.rs | 364 +++++++++++++++++- crates/victory-gpu/src/shadow.rs | 328 +++++++++++++++- crates/victory-gpu/src/watch.rs | 66 +++- 8 files changed, 1960 insertions(+), 82 deletions(-) create mode 100644 crates/victory-gpu/src/land.rs create mode 100644 crates/victory-gpu/src/land/tests.rs diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 8e3572a..5989689 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1638,7 +1638,8 @@ static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atom /// settles: about 630 pieces and 40 MB a frame (run 104), each compared /// with the copy's CPU side byte by byte and put into title memory through /// the kernel. A piece is its own bytes of its copy and of title memory, -/// so eight threads take an eighth of them each. +/// so eight threads take an eighth of them each. (Not with [`relay`], whose +/// landings do not come here: `crate::land` has threads of its own.) fn wide_merge() -> bool { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1")) @@ -1970,13 +1971,16 @@ fn landable(line: &[Option], completed: u64) -> usize { /// For one plan of copies in the card's memory, with [`relay`]: `flags` /// holds, for every piece of every range of the plan, the copy, the /// piece's number in the copy and whether the compare flagged it there (or -/// did not run). The pieces to fetch, under whichever range: all of them -/// flagged under any. Two ranges of a plan may hold parts of the same +/// did not run). The pieces to fetch, under whichever range, in order: all +/// of them flagged under any. Two ranges of a plan may hold parts of the same /// 64 KiB piece; the compare hashes the whole piece for each and stores /// the hash, so the second of them may find it stored already and not /// flag it. -fn flagged_pieces(flags: &[(usize, u32, bool)]) -> std::collections::HashSet<(usize, u32)> { - flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect() +fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> { + let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect(); + pieces.sort_unstable(); + pieces.dedup(); + pieces } #[cfg(test)] @@ -2660,6 +2664,8 @@ struct RelayFetch { sent: u64, /// Buffer, mapping, bytes. buffer: Option<(ID3D12Resource, usize, u64)>, + /// What earlier fetches brought of flights not landed yet. + had: crate::land::Had, } /// The thread that lands flights ([`relay`]): as soon as the card has run @@ -2738,8 +2744,16 @@ fn relay_worker() { /// in the PC's memory goes into title memory. As [`hand_back`], each byte /// once, the pieces that differ found on several threads; but the merge is /// `Shadow::relay_merge`, which does not write the copy, and the ranges -/// are not done with here (each flight's are, afterwards). -fn relay_hand_back(back: &[Declared]) { +/// are not done with here (each flight's are, afterwards). In two steps: +/// what is to be looked through and what of it differs ([`RelayBack::look`], +/// which needs nothing that the fetch from the card's memory brings), and +/// the merge. +struct RelayBack { + work: Vec<(std::sync::Arc, usize, usize)>, + found: Option>>, +} + +fn relay_hand_back(back: &[Declared]) -> RelayBack { let mut work: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); for (shadow, declared) in back { if shadow.carded() { @@ -2752,27 +2766,71 @@ fn relay_hand_back(back: &[Declared]) { } work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to))); } - if work.is_empty() { - return; - } - #[cfg(feature = "diagnostics")] - let scanning = std::time::Instant::now(); - // Looked through without a lock: a piece that changes meanwhile (a - // later flight writing, the title's bytes going in) is found now or by - // that flight's landing, and the merge looks again under the lock. - let found = crate::shadow::find_all(&work); - #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64); - let (mut now, mut title) = (Vec::new(), Vec::new()); - for ((shadow, from, to), found) in work.iter().zip(found) { - let mut written = 0; - for (at, n) in found { - written += shadow.relay_merge(at, n, &mut now, &mut title); + RelayBack { work, found: None } +} + +impl RelayBack { + /// Looks the ranges through, once; its time counts as `stat`. + fn look(&mut self, stat: usize) { + if self.work.is_empty() || self.found.is_some() { + return; } - COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + let scanning = std::time::Instant::now(); + // Looked through without a lock: a piece that changes meanwhile (a + // later flight writing, the title's bytes going in) is found now or + // by that flight's landing, and the merge looks again under the + // lock. + self.found = Some(crate::shadow::find_all(&self.work)); + crate::land::spent(stat, scanning); #[cfg(feature = "diagnostics")] - crate::copystat::compared(*from, to - from, written); - let _ = (from, to); + crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64); + } + + /// What differs goes into title memory. + fn merge(mut self) { + use crate::land; + self.look(land::stat::SCAN); + let Some(found) = self.found else { + return; + }; + let merging = std::time::Instant::now(); + let mut written: Vec = Vec::new(); + if land::on() { + // Pieces in the same block of title memory in one job, in order. + let pieces: Vec<(usize, usize, usize)> = + found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect(); + let start = |i: usize| self.work[i].0.span().0 as usize; + let mut order: Vec = (0..pieces.len()).collect(); + order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK); + let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect(); + let jobs = land::jobs(&cut); + let put: Vec = self.work.iter().map(|_| Default::default()).collect(); + land::each(jobs.len(), &|j| { + let working = std::time::Instant::now(); + let mut notes = land::Notes::default(); + for &p in &order[jobs[j].clone()] { + let (i, at, n) = pieces[p]; + put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed); + } + notes.flush(); + land::spent(land::stat::BACK_ALL, working); + }); + land::count(land::stat::JOBS, jobs.len() as u64); + written.extend(put.iter().map(|p| p.load(Ordering::Relaxed))); + } else { + let (mut now, mut title) = (Vec::new(), Vec::new()); + for ((shadow, ..), found) in self.work.iter().zip(found) { + let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64; + written.push(found.into_iter().map(merge).sum()); + } + } + land::spent(land::stat::BACK, merging); + for ((_, from, to), written) in self.work.iter().zip(written) { + COPY_BACK[1].fetch_add(written, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::compared(*from, to - from, written as usize); + let _ = (from, to); + } } } @@ -2841,6 +2899,7 @@ fn late_line(frames: f64) { r[4] / 1000.0, ); } + crate::land::log(frames); card_steps::log(frames); #[cfg(feature = "diagnostics")] log_blame(frames); @@ -3641,6 +3700,7 @@ impl Host { event, sent: 0, buffer: None, + had: crate::land::Had::default(), }) } } @@ -3654,21 +3714,28 @@ impl Host { /// fetched under all ([`flagged_pieces`]); the fetch runs behind /// whatever was sent meanwhile, so it may bring a later flight's /// bytes, which that flight's landing then finds merged already; and - /// nothing is sent back up. - fn relay_card_back(&self, plans: &[&CardPlan], fetch: &mut Option) { + /// nothing is sent back up. `plans` come with the value signalled behind + /// their flight. `meanwhile` is called while the fetch is on its way, if + /// there is one. + fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option, meanwhile: &mut dyn FnMut()) { + use crate::land; + let gathering = std::time::Instant::now(); let differs = { let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize)) }; let mut pieces: Vec<(std::sync::Arc, usize, usize, u64)> = Vec::new(); let mut total = 0u64; + if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) { + fetch.had.landing(first); + } if let Some((differs, dwords)) = differs { // SAFETY: the mapping of the results. The compares of these // plans have run, and their dwords are given to no other plan // before these are done with (`card_done`). let differs = unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) }; let mut seen = std::collections::HashSet::new(); - for plan in plans { + for &(plan, behind) in plans { let flags: Vec<(usize, u32, bool)> = plan .ranges .iter() @@ -3683,11 +3750,20 @@ impl Host { for r in &plan.ranges { let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; for p in 0..r.span.pieces { - if !fetched.contains(&(copy, r.span.first + p)) { + if fetched.binary_search(&(copy, r.span.first + p)).is_err() { continue; } let (lo, hi) = r.shadow.card_piece(&r.span, p); - if lo < hi && seen.insert((copy, lo, hi)) { + if lo < hi && !seen.contains(&(copy, lo, hi)) { + let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo); + if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) { + land::count(land::stat::HAD, 1); + land::count(land::stat::HAD_BYTES, (hi - lo) as u64); + if land::skip_on() { + continue; + } + } + seen.insert((copy, lo, hi)); pieces.push((r.shadow.clone(), lo, hi, total)); total += (hi - lo) as u64; } @@ -3696,12 +3772,29 @@ impl Host { } } } + if land::on() { + // In the order they are landed, each byte of a copy once. + let keys: Vec = + pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect(); + total = 0; + pieces = land::ordered(&keys) + .into_iter() + .map(|(i, title, len)| { + let shadow = &pieces[i].0; + let lo = title - shadow.span().0 as usize; + let at = total; + total += len as u64; + (shadow.clone(), lo, lo + len, at) + }) + .collect(); + } + land::spent(land::stat::GATHER, gathering); if fetch.is_none() { *fetch = self.make_relay_fetch(); } // 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.sent_as).max().unwrap_or(0); + let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0); if pieces.is_empty() { // Nothing to fetch: every send so far is older than the next // fetch, if that goes to the queue the sends went to. @@ -3726,6 +3819,12 @@ impl Host { let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent); let copy_queue = f.queue.clone(); let waiting = std::time::Instant::now(); + // The flights the fetch runs behind: those in the line by now have + // been given to the queue. On the copy queue, those landed here. + let ahead = match copy_queue { + Some(_) => 0, + None => line().target, + }; // SAFETY: the list's last run was waited for by this thread; live // buffers (the copies are held by the plans); the fence and the // event are this thread's. @@ -3741,6 +3840,7 @@ impl Host { if let Some(queue) = ©_queue { queue.ExecuteCommandLists(&lists); queue.Signal(&fence, sent)?; + meanwhile(); fence.SetEventOnCompletion(sent, event)?; WaitForSingleObject(event, INFINITE); return Ok(behind); @@ -3753,6 +3853,7 @@ impl Host { drop(order); self.card_sent(); self.queue.Signal(&fence, sent)?; + meanwhile(); fence.SetEventOnCompletion(sent, event)?; WaitForSingleObject(event, INFINITE); Ok(after) @@ -3771,17 +3872,48 @@ impl Host { CARD_STATS[5].fetch_add(1, Ordering::Relaxed); CARD_STATS[6].fetch_add(us, Ordering::Relaxed); } - let mut title = Vec::new(); + let merging = std::time::Instant::now(); let mut written = 0; - for (shadow, lo, hi, at) in &pieces { - // SAFETY: the mapping of the fetched bytes, `total` of them; - // the copy into it has run. - let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) }; - let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title); - shadow.walls_merged(gpu.len(), merged); - written += merged; + if land::on() { + let titles: Vec<(usize, usize)> = + pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect(); + let jobs = land::jobs(&titles); + let put = std::sync::atomic::AtomicU64::new(0); + land::each(jobs.len(), &|j| { + let working = std::time::Instant::now(); + let mut notes = land::Notes::default(); + for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) { + let addressed: Vec<(usize, usize, usize)> = + run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect(); + // SAFETY: the mapping of the fetched bytes, `total` of + // them; the copy into it has run, and the next waits + // for this call. + put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed); + } + notes.flush(); + land::spent(land::stat::CARD_ALL, working); + }); + land::count(land::stat::JOBS, jobs.len() as u64); + written = put.into_inner(); + } else { + let mut title = Vec::new(); + for (shadow, lo, hi, at) in &pieces { + // SAFETY: the mapping of the fetched bytes, `total` of them; + // the copy into it has run. + let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) }; + let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title); + shadow.walls_merged(gpu.len(), merged); + written += merged as u64; + } + } + land::spent(land::stat::CARD, merging); + COPY_BACK[1].fetch_add(written, Ordering::Relaxed); + if let Some(f) = fetch.as_mut() { + f.had.fetched( + ahead, + pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)), + ); } - COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); // Sends up to `after` are of no use to any later merge. crate::shadow::relay_fetched(after); } @@ -3816,24 +3948,25 @@ impl Host { last_notes(&runs) )); } - let plans: Vec<&CardPlan> = flights.iter().filter_map(|f| f.card.as_ref()).collect(); - self.relay_card_back(&plans, fetch); + let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect(); + // (Each byte once: the ranges are joined.) let mut back: Vec = Vec::new(); for flight in &flights { - for (shadow, ranges) in &flight.back { + for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) { match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { - Some((_, all)) => { - for range in ranges { - if !all.contains(range) { - all.push(*range); - } - } - } + Some((_, all)) => all.extend_from_slice(ranges), None => back.push((shadow.clone(), ranges.clone())), } } } - relay_hand_back(&back); + let mut hand_back = relay_hand_back(&back); + self.relay_card_back(&plans, fetch, &mut || { + if crate::land::on() { + hand_back.look(crate::land::stat::SCAN_BESIDE); + } + }); + hand_back.merge(); + let finishing = std::time::Instant::now(); // Only now, and flight by flight: a range another flight // in the air declared too stays closed to refreshes. for flight in &flights { @@ -3841,6 +3974,7 @@ impl Host { shadow.copy_back_done(ranges); } } + crate::land::spent(crate::land::stat::DONE, finishing); COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); RELAY_STATS[0].fetch_add(1, Ordering::Relaxed); RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed); @@ -3849,8 +3983,9 @@ impl Host { // In the order given: what tells the title the card is done. let mut last = 0; let mut landed = Vec::new(); + let mut telling = std::time::Instant::now(); for item in items { - match item { + telling = match item { Late::Run(flight) => { last = flight.number; for &i in &flight.order { @@ -3863,16 +3998,24 @@ impl Host { own.landed(); } landed.push((flight.lists, flight.order)); + crate::land::spent(crate::land::stat::READ_BACKS, telling) } - Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), - Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value), - } + Late::Write(at, what, bytes) => { + what.write(at as *mut u8, bytes); + crate::land::spent(crate::land::stat::TOLD, telling) + } + Late::Signal(fence, value) => { + crate::fence::set(fence as crate::object::This, value); + crate::land::spent(crate::land::stat::TOLD, telling) + } + }; } if last > 0 { FINISHED.store(last, Ordering::Release); bury(last); } self.log_messages(); + crate::land::spent(crate::land::stat::REST, telling); RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); { let mut line = line(); diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 25461df..71e59d5 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -269,9 +269,12 @@ struct Views { views: BTreeMap, /// Sections by handle: bytes, and whether made committed. sections: Vec<(usize, u64, bool)>, + /// Our own view of a whole section, by its handle (0: the host gave + /// none), made when first asked for ([`beside`]) and kept. + whole: Vec<(usize, usize)>, } -static VIEWS: Mutex = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new() }); +static VIEWS: Mutex = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new(), whole: Vec::new() }); fn views() -> std::sync::MutexGuard<'static, Views> { VIEWS.lock().unwrap_or_else(|e| e.into_inner()) @@ -282,6 +285,9 @@ fn views() -> std::sync::MutexGuard<'static, Views> { pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { let mut v = views(); 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). + v.whole.retain(|w| w.0 != section); v.sections.push((section, bytes, committed)); } @@ -343,6 +349,36 @@ pub(crate) fn cover(at: usize, len: usize) -> Cover { cover_in(&views().views, at, len) } +/// Another address of the title memory `[at, at + len)`, if it is a view of +/// the title's pages, all of it one run of a section: in a view of ours of +/// the whole section, which is never guarded (`crate::watch`) nor changed. +/// +/// The section's pages are reserved and the runtime commits each before it +/// shows it, which holds for every view of the section. The caller holds +/// `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 Cover::Run(section, offset) = cover_in(&v.views, at, len) else { + return None; + }; + let base = match v.whole.iter().find(|w| w.0 == section) { + Some(w) => w.1, + None => { + let &(_, bytes, _) = v.sections.iter().find(|s| s.0 == section)?; + // SAFETY: the whole of a section the runtime made; a view the + // title sees is of it, so its handle is open. + let base = unsafe { mem::MapViewOfFile(section as _, mem::FILE_MAP_WRITE, 0, 0, bytes as usize) }.Value as usize; + if base == 0 { + tracing::warn!(error = %std::io::Error::last_os_error(), "no view of the title's pages beside its own"); + } + v.whole.push((section, base)); + base + } + }; + (base != 0).then(|| base + offset as usize) +} + /// 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/land.rs b/crates/victory-gpu/src/land.rs new file mode 100644 index 0000000..67ae9cd --- /dev/null +++ b/crates/victory-gpu/src/land.rs @@ -0,0 +1,556 @@ +//! What shaders wrote goes into title memory on a few threads +//! (`VICTORY_LAND`, on by default; `=0` merges piece by piece on the thread +//! that lands flights, as before). +//! +//! The relay's thread (`crate::host::relay`) was 58-60 ms of a 104 ms frame +//! landing (run record-1): some 1,500 pieces of 64 KiB, 98 MB, fetched from +//! copies in the card's memory, and each of them searched from both ends, +//! cleared room for, read from title memory, copied, merged and compared +//! again while it was put, one after the other; a lock and a protection +//! call to open the guard of each, and the kernel's fault on the first +//! write to each 4 KiB page of memory just made writable again. +//! +//! Here a piece is merged in one pass ([`crate::safecopy::merge`]): what +//! the card holds is compared with what it held 32 bytes at a time, title +//! memory is read only where they differ, just before the dwords that +//! change are stored. The pieces of a landing are cut into jobs for a few +//! threads kept for it ([`Pool`]). +//! +//! What stays in order: pieces in the same 64 KiB of title memory are in +//! one job, in the order they were given (two copies may hold the same +//! title memory); a landing's copies in the card's memory come before its +//! other copies; a landing is done, whole, before the title is told +//! anything and before the next one starts (`Host::relay_land`). +//! +//! With `VICTORY_LAND_BESIDE` (on by default) title memory that is a view of +//! the title's physical pages is written through a view of our own of the +//! same pages ([`crate::inplace::beside`]). The guards (`crate::watch`) are +//! read-only title views: they stay as they are, no protection changes, and +//! [`crate::watch::landed_beside`] notes the blocks written afterwards, so +//! that the next refresh takes them as before. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; + +/// The unit pieces are cut in (of title memory), and the guards' blocks. +pub(crate) const BLOCK: usize = 64 << 10; +/// The unit title memory is there or not in. +const PAGE: usize = 4096; +/// About this many bytes to a job. +const JOB: usize = 256 << 10; + +/// See the file. +pub(crate) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + std::env::var_os("VICTORY_LAND").is_none_or(|v| v != "0") && crate::safecopy::on() && crate::shadow::exact_back() + }) +} + +/// How many threads land, the relay's own counted (`VICTORY_LAND_THREADS`). +fn threads() -> usize { + static THREADS: OnceLock = OnceLock::new(); + *THREADS.get_or_init(|| { + let asked = std::env::var("VICTORY_LAND_THREADS").ok().and_then(|v| v.trim().parse().ok()); + asked.unwrap_or_else(|| std::thread::available_parallelism().map_or(2, |n| n.get() / 4).clamp(1, 4)).clamp(1, 16) + }) +} + +/// Whether views of the title's pages are written through one of ours. +fn beside_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAND_BESIDE").is_none_or(|v| v != "0")) +} + +/// Whether pieces an earlier fetch holds as they are now are left out +/// ([`Had`]; `VICTORY_LAND_SKIP=1`, off by default: counted either way). +pub(crate) fn skip_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAND_SKIP").is_some_and(|v| v == "1")) +} + +/// Since the last frame-rate line; microseconds first. +pub(crate) mod stat { + /// Which pieces to fetch; their list recorded and sent. + pub(crate) const GATHER: usize = 0; + /// Looking for what shaders wrote to copies in the PC's memory, the part + /// done while the fetch was on its way. + pub(crate) const SCAN_BESIDE: usize = 1; + /// The same, with nothing else to wait for. + pub(crate) const SCAN: usize = 2; + /// Merging what was fetched: until the last job is done, and the jobs' + /// time on all threads. + pub(crate) const CARD: usize = 3; + pub(crate) const CARD_ALL: usize = 4; + /// Merging what the scan found. + pub(crate) const BACK: usize = 5; + pub(crate) const BACK_ALL: usize = 6; + /// In the jobs: waiting for the lock against the title's bytes going in. + pub(crate) const LOCK: usize = 7; + /// In the jobs: guards opened before a write, or noted after one. + pub(crate) const NOTES: usize = 8; + /// The flights' ranges done with; reading back, resets; what the title + /// is told; the rest (the line's account). + pub(crate) const DONE: usize = 9; + pub(crate) const READ_BACKS: usize = 10; + pub(crate) const TOLD: usize = 11; + pub(crate) const REST: usize = 12; + /// Counts: pieces merged, those with a new byte, their 4 KiB pages, + /// those with a new byte, blocks of 32 bytes with a new byte, dwords put. + pub(crate) const PIECES: usize = 13; + pub(crate) const NEW_PIECES: usize = 14; + pub(crate) const PAGES: usize = 15; + pub(crate) const NEW_PAGES: usize = 16; + pub(crate) const NEW_BLOCKS: usize = 17; + pub(crate) const DWORDS: usize = 18; + /// Pieces put through a view of ours, through the title's; pages where + /// title memory was not there. + pub(crate) const BESIDE: usize = 19; + pub(crate) const DIRECT: usize = 20; + pub(crate) const MISSING: usize = 21; + /// Bytes asked for twice in a landing (fetched once); pieces and bytes + /// an earlier fetch held already. + pub(crate) const TWICE: usize = 22; + pub(crate) const HAD: usize = 23; + pub(crate) const HAD_BYTES: usize = 24; + /// Jobs. + pub(crate) const JOBS: usize = 25; + pub(crate) const COUNT: usize = 26; +} + +static STATS: [AtomicU64; stat::COUNT] = [const { AtomicU64::new(0) }; stat::COUNT]; + +pub(crate) fn count(which: usize, n: u64) { + STATS[which].fetch_add(n, Ordering::Relaxed); +} + +/// Adds the microseconds since `from` to `which`; now. +pub(crate) fn spent(which: usize, from: std::time::Instant) -> std::time::Instant { + let now = std::time::Instant::now(); + count(which, (now - from).as_micros() as u64); + now +} + +/// For the frame-rate line: where landing went, per frame. +pub(crate) fn log(frames: f64) { + let s: Vec = STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if s[stat::PIECES] == 0.0 && s[stat::REST] == 0.0 { + return; + } + let ms = |i: usize| s[i] / 1000.0; + let mb = |v: f64| v / (1 << 20) as f64; + tracing::info!( + "landing per frame (VICTORY_LAND={}, {} threads): which pieces to fetch {:.2} ms, then the fetches (the relay's line); \ + looking through copies in the PC's memory {:.2} ms beside them and {:.2} ms more; merging what was fetched {:.2} ms \ + ({:.2} ms on all threads, {:.0} jobs), merging the others {:.2} ms ({:.2} on all threads); of the threads' time \ + {:.2} ms waiting for the title's bytes going in, {:.2} ms opening or noting guards; then ranges done with {:.2} ms, \ + read-backs and lists {:.2}, the title told {:.2}, the rest {:.2}", + u8::from(on()), + threads(), + ms(stat::GATHER), + ms(stat::SCAN_BESIDE), + ms(stat::SCAN), + ms(stat::CARD), + ms(stat::CARD_ALL), + s[stat::JOBS], + ms(stat::BACK), + ms(stat::BACK_ALL), + ms(stat::LOCK), + ms(stat::NOTES), + ms(stat::DONE), + ms(stat::READ_BACKS), + ms(stat::TOLD), + ms(stat::REST), + ); + tracing::info!( + "landed per frame: {:.0} pieces, {:.0} with a new byte; of their {:.0} pages of 4 KiB {:.0} with a new byte ({:.1} MB), \ + {:.1} MB in blocks of 32 bytes with one, {:.2} MB put as dwords; {:.0} pieces through a view of ours \ + (VICTORY_LAND_BESIDE={}), {:.0} through the title's; {:.0} pages not there; asked for twice in a landing {:.1} MB; \ + held already by an earlier fetch {:.0} pieces {:.1} MB (VICTORY_LAND_SKIP={})", + s[stat::PIECES], + s[stat::NEW_PIECES], + s[stat::PAGES], + s[stat::NEW_PAGES], + mb(s[stat::NEW_PAGES] * PAGE as f64), + mb(s[stat::NEW_BLOCKS] * 32.0), + mb(s[stat::DWORDS] * 4.0), + s[stat::BESIDE], + u8::from(beside_on()), + s[stat::DIRECT], + s[stat::MISSING], + mb(s[stat::TWICE]), + s[stat::HAD], + mb(s[stat::HAD_BYTES]), + u8::from(skip_on()), + ); +} + +/// Threads kept for landing, and the work they are at. +struct Pool { + state: Mutex, + more: Condvar, + idle: Condvar, + /// One batch at a time. + turn: Mutex<()>, + threads: usize, +} + +struct State { + /// What to do with each number below `count`. + work: Option, + next: usize, + count: usize, + /// Helpers inside a call. + running: usize, + panicked: bool, +} + +#[derive(Clone, Copy)] +struct Work(*const (dyn Fn(usize) + Sync)); + +// SAFETY: the closure may be called from any thread (`Sync`), and +// `Pool::each` keeps it alive until no helper is inside a call. +unsafe impl Send for Work {} + +impl Pool { + fn state(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn new(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(), + idle: Condvar::new(), + turn: Mutex::new(()), + threads, + })); + 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 || pool.help()); + } + pool + } + + fn help(&self) { + let mut state = self.state(); + loop { + let Some((work, i)) = take(&mut state) else { + state = self.more.wait(state).unwrap_or_else(|e| e.into_inner()); + continue; + }; + state.running += 1; + drop(state); + // SAFETY: counted in `running`, so `each` has not returned. + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { (*work.0)(i) })); + state = self.state(); + state.running -= 1; + state.panicked |= ran.is_err(); + if state.running == 0 { + self.idle.notify_all(); + } + } + } + + /// Calls `f` with every number below `count`, on the pool's threads and + /// this one, and returns when every call has. + fn each(&self, count: usize, f: &(dyn Fn(usize) + Sync)) { + if count < 2 || self.threads < 2 { + (0..count).for_each(f); + return; + } + let _turn = self.turn.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: the lifetime is left out only until this call returns, and + // it does not before no helper is inside `f` and none can enter. + let work = Work(unsafe { std::mem::transmute::<*const (dyn Fn(usize) + Sync + '_), *const (dyn Fn(usize) + Sync + 'static)>(f) }); + let mut state = self.state(); + (state.work, state.next, state.count, state.panicked) = (Some(work), 0, count, false); + drop(state); + if count > self.threads { + self.more.notify_all(); + } else { + (1..count).for_each(|_| self.more.notify_one()); + } + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + loop { + let Some((_, i)) = take(&mut self.state()) else { break }; + f(i); + } + })); + let mut state = self.state(); + // (After a panic here: nothing more is begun.) + state.work = None; + while state.running > 0 { + state = self.idle.wait(state).unwrap_or_else(|e| e.into_inner()); + } + let panicked = state.panicked; + drop(state); + if let Err(panic) = ran { + std::panic::resume_unwind(panic); + } + assert!(!panicked, "a job of landing panicked"); + } +} + +/// The next number of the batch, if there is one. +fn take(state: &mut State) -> Option<(Work, usize)> { + let work = state.work?; + if state.next >= state.count { + return None; + } + state.next += 1; + Some((work, state.next - 1)) +} + +/// [`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); +} + +/// A piece to land: the copy's number, the title address, its bytes. +pub(crate) type Piece = (u64, usize, usize); + +/// `pieces` in the order they are landed: by the 64 KiB block of title +/// memory they lie in, those in one block in the order given (each is +/// within one block). Where one copy alone has pieces in a block, those +/// that overlap or touch are one piece: a landing's flights declare parts +/// of the same memory, and what overlapped came down and was merged twice. +/// Each with the number of the piece given that it begins with. +pub(crate) fn ordered(pieces: &[Piece]) -> Vec<(usize, usize, usize)> { + let mut order: Vec = (0..pieces.len()).collect(); + order.sort_by_key(|&i| pieces[i].1 / BLOCK); + let mut out: Vec<(usize, usize, usize)> = Vec::with_capacity(order.len()); + for group in order.chunk_by(|&a, &b| pieces[a].1 / BLOCK == pieces[b].1 / BLOCK) { + let alone = group.len() > 1 && group.iter().all(|&i| pieces[i].0 == pieces[group[0]].0); + if !alone { + out.extend(group.iter().map(|&i| (i, pieces[i].1, pieces[i].2))); + continue; + } + let mut sorted = group.to_vec(); + sorted.sort_by_key(|&i| pieces[i].1); + let begun = out.len(); + for i in sorted { + let (_, at, len) = pieces[i]; + match out[begun..].last_mut() { + Some(last) if at <= last.1 + last.2 => { + let end = (last.1 + last.2).max(at + len); + count(stat::TWICE, (last.2 + len - (end - last.1)) as u64); + last.2 = end - last.1; + } + _ => out.push((i, at, len)), + } + } + } + out +} + +/// Pieces (title address, bytes; in [`ordered`]'s order) as jobs: runs of +/// about [`JOB`] bytes that end where a block ends. +pub(crate) fn jobs(pieces: &[(usize, usize)]) -> Vec> { + let mut out: Vec> = Vec::new(); + let (mut from, mut bytes) = (0, 0); + for (i, &(at, len)) in pieces.iter().enumerate() { + let new_block = i == 0 || pieces[i - 1].0 / BLOCK != at / BLOCK; + if bytes >= JOB && new_block { + out.push(from..i); + (from, bytes) = (i, 0); + } + bytes += len; + } + if from < pieces.len() { + out.push(from..pieces.len()); + } + out +} + +/// What earlier fetches brought, for as long as a flight they ran behind +/// has not landed: per fetch, the value the host's fence had been given +/// behind the last flight sent before it, and by copy (its number) and +/// piece the offsets it brought. +/// +/// A fetch on the drawing queue runs behind everything sent before it, so +/// it brings what those flights' shaders wrote too, and the merge of it put +/// that into title memory. Their own landings flag the same pieces and +/// fetched them again, to find every byte merged. A piece that a fetch held +/// whole, behind the flight that flags it, has nothing more of that flight. +/// (Bytes left out of that merge, the title's that went up behind the +/// fetch, went up behind that flight too, and stand over what it wrote.) +#[derive(Default)] +pub(crate) struct Had(Vec<(u64, std::collections::HashMap<(u64, usize), (usize, usize)>)>); + +impl Had { + /// Flights from the one behind which `fence` is signalled on are landed + /// next: what is of no use to them is dropped. + pub(crate) fn landing(&mut self, fence: u64) { + self.0.retain(|had| had.0 >= fence); + } + + /// A fetch that ran behind every flight up to `fence` brought (copy, + /// title address, bytes) `pieces`. They are merged before the next ask. + pub(crate) fn fetched(&mut self, fence: u64, pieces: impl Iterator) { + let mut all = std::collections::HashMap::new(); + for (copy, at, len) in pieces { + // (Two parts of a block that do not touch: the longer one.) + let had = all.entry((copy, at / BLOCK)).or_insert((at, at + len)); + if len > had.1 - had.0 { + *had = (at, at + len); + } + } + self.0.push((fence, all)); + } + + /// Whether a fetch behind the flight of `fence` brought all of the + /// piece. + pub(crate) fn holds(&self, fence: u64, (copy, at, len): Piece) -> bool { + self.0.iter().any(|(behind, all)| { + *behind >= fence && all.get(&(copy, at / BLOCK)).is_some_and(|had| had.0 <= at && at + len <= had.1) + }) + } +} + +/// What a job wrote beside the guards, to be noted ([`Notes::flush`]). +#[derive(Default)] +pub(crate) struct Notes { + /// Pages of 4 KiB, by number. + pages: Vec, + /// Per piece, from the first such page to the last: address, bytes. + spans: Vec<(usize, usize)>, +} + +impl Notes { + /// At the end of a job: what it wrote beside the guards is noted. + pub(crate) fn flush(&mut self) { + if self.pages.is_empty() { + return; + } + let noting = std::time::Instant::now(); + crate::watch::landed_beside(&self.pages, &self.spans); + self.pages.clear(); + self.spans.clear(); + spent(stat::NOTES, noting); + } +} + +/// Lands one piece: `parts` (offsets from and to) of the bytes at `now`, +/// which the card wrote, go into title memory from `title` on and into +/// `held` ([`crate::safecopy::merge`] says how, and what `take` is). The +/// piece lies in one 64 KiB block of title memory. Returns the bytes put. +/// +/// # Safety +/// `now` and `held` are ours from 0 to the last part's end, and nothing but +/// the card writes `now` there, nothing but this call `held`. +pub(crate) unsafe fn piece( + title: usize, + now: *const u8, + held: *mut u8, + parts: &[(usize, usize)], + take: bool, + notes: &mut Notes, +) -> u64 { + // SAFETY: the caller's. + unsafe { piece_at(title, now, held, parts, take, notes, beside_on()) } +} + +/// [`piece`], and whether a view of ours is looked for. +/// +/// # Safety +/// [`piece`]'s. +unsafe fn piece_at( + title: usize, + now: *const u8, + held: *mut u8, + parts: &[(usize, usize)], + take: bool, + notes: &mut Notes, + beside: bool, +) -> u64 { + let Some(end) = parts.last().map(|p| p.1) else { + return 0; + }; + // From here until the piece is put the runtime changes no mapping: our + // view's address stays where the title sees `title`. Not waited for: if + // a change is under way, the title's own address does. + let reading = beside.then(crate::watch::title_memory_reading_now).flatten(); + let beside = reading.as_ref().and_then(|_| crate::inplace::beside(title, end)); + count(stat::PIECES, 1); + count(if beside.is_some() { stat::BESIDE } else { stat::DIRECT }, 1); + // The pages that differ, before any is written: none, and the guard + // stays; else it is opened once for the piece. + let mut differing = [true; BLOCK / PAGE + 1]; + let base = title / PAGE; + if beside.is_none() { + drop(reading); + differing.fill(false); + for_pages(title, parts, |from, n| { + // SAFETY: the caller's. + if unsafe { crate::safecopy::differ(now.add(from), held.add(from), n) } { + differing[(title + from) / PAGE - base] = true; + } + }); + let Some(first) = differing.iter().position(|&d| d) else { + for_pages(title, parts, |_, _| count(stat::PAGES, 1)); + return 0; + }; + let last = differing.iter().rposition(|&d| d).unwrap_or(first); + let (from, to) = (((base + first) * PAGE).max(title), ((base + last + 1) * PAGE).min(title + end)); + let opening = std::time::Instant::now(); + crate::watch::landing(from, to - from); + spent(stat::NOTES, opening); + } + let into = beside.unwrap_or(title); + let (mut pages, mut new_pages, mut blocks, mut dwords, mut missing) = (0, 0u64, 0, 0, 0); + let mut span: Option<(usize, usize)> = None; + for_pages(title, parts, |from, n| { + pages += 1; + if !differing[(title + from) / PAGE - base] { + return; + } + // SAFETY: the caller's; title memory, by an address that shows it + // (`beside`) or the title's own. + let done = unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) }; + blocks += done.new; + dwords += done.dwords; + missing += u64::from(!done.there); + if done.new > 0 { + new_pages += 1; + if beside.is_some() { + let page = (title + from) / PAGE; + // (Two parts in one page.) + if notes.pages.last() != Some(&page) { + notes.pages.push(page); + } + let s = span.get_or_insert((title + from, title + from + n)); + s.1 = title + from + n; + } + } + }); + if let Some((from, to)) = span { + notes.spans.push((from, to - from)); + } + count(stat::NEW_PIECES, u64::from(new_pages > 0)); + count(stat::PAGES, pages); + count(stat::NEW_PAGES, new_pages); + count(stat::NEW_BLOCKS, blocks); + count(stat::DWORDS, dwords); + count(stat::MISSING, missing); + crate::shadow::PUT[0].fetch_add(u64::from(dwords > 0), Ordering::Relaxed); + crate::shadow::PUT[2].fetch_add(dwords * 4, Ordering::Relaxed); + dwords * 4 +} + +/// `parts` of a piece that begins at `title`, cut where 4 KiB pages of title +/// memory end: offset and bytes. +fn for_pages(title: usize, parts: &[(usize, usize)], mut f: impl FnMut(usize, usize)) { + for &(from, to) in parts { + let mut at = from; + while at < to { + let n = (PAGE - (title + at) % PAGE).min(to - at); + f(at, n); + at += n; + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/victory-gpu/src/land/tests.rs b/crates/victory-gpu/src/land/tests.rs new file mode 100644 index 0000000..f2fef9f --- /dev/null +++ b/crates/victory-gpu/src/land/tests.rs @@ -0,0 +1,433 @@ +use super::*; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize}; +use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, PAGE_READWRITE}; + +struct Random(u64); + +impl Random { + fn next(&mut self) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 >> 8) as usize + } +} + +/// View memory as the runtime makes the title's: a view of a section, noted +/// as it notes it. Kept: the journal of what was written (`crate::watch`) +/// knows its addresses, which must not become another test's fresh memory. +struct Title { + at: usize, + len: usize, +} + +impl Title { + fn new(len: usize) -> Title { + // SAFETY: a pagefile section of our own and a view of it. + unsafe { + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null()); + assert!(!section.is_null()); + let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize; + assert_ne!(at, 0); + crate::inplace::title_memory_section(section as usize, len as u64, true); + crate::title_memory_remapped(at, len); + crate::inplace::title_memory_view(at, len, section as usize, 0); + Title { at, len } + } + } + + fn bytes(&self) -> &[u8] { + // SAFETY: the view. + unsafe { std::slice::from_raw_parts(self.at as *const u8, self.len) } + } +} + +/// Every number once, whatever the count and the threads, batch after batch +/// and from several callers. +#[test] +fn the_pool_calls_every_number_once() { + for threads in [1usize, 2, 4, 7] { + let pool = Pool::new(threads); + std::thread::scope(|s| { + for _ in 0..3 { + s.spawn(|| { + for round in 0..300usize { + let count = round * 7 % 50; + let calls: Vec = (0..count).map(|_| AtomicUsize::new(0)).collect(); + pool.each(count, &|i| { + calls[i].fetch_add(1, Ordering::Relaxed); + }); + assert!(calls.iter().all(|c| c.load(Ordering::Relaxed) == 1)); + } + }); + } + }); + } +} + +/// 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); + for bad in 0..8usize { + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + pool.each(8, &|i| assert_ne!(i, bad, "(expected)")); + })); + assert!(ran.is_err()); + let n = AtomicUsize::new(0); + pool.each(20, &|i| { + n.fetch_add(i, Ordering::Relaxed); + }); + assert_eq!(n.into_inner(), 190); + } +} + +/// The order pieces are landed in holds every byte of every piece, under its +/// copy, and no other; blocks come in order, pieces of several copies in one +/// block stay in the order given, and jobs never cut a block. +#[test] +fn ordered_pieces_hold_the_same_bytes() { + let mut random = Random(99); + for _ in 0..400 { + let count = random.next() % 40; + let pieces: Vec = (0..count) + .map(|_| { + let block = random.next() % 12 * BLOCK; + let from = random.next() % BLOCK / 4 * 4; + let to = (from + 4 + random.next() % BLOCK / 4 * 4).min(BLOCK); + (random.next() as u64 % 3, block + from, to - from) + }) + .collect(); + let out = ordered(&pieces); + let bytes = |copy: u64, at: usize, all: &[Piece]| all.iter().any(|p| p.0 == copy && p.1 <= at && at < p.1 + p.2); + let landed: Vec = out.iter().map(|&(i, at, len)| (pieces[i].0, at, len)).collect(); + for copy in 0..3 { + for at in (0..12 * BLOCK).step_by(1024 * 4) { + assert_eq!(bytes(copy, at, &pieces), bytes(copy, at, &landed), "{pieces:?}"); + } + } + assert!(out.iter().all(|&(_, at, len)| len > 0 && at / BLOCK == (at + len - 1) / BLOCK)); + assert!(out.windows(2).all(|w| w[0].1 / BLOCK <= w[1].1 / BLOCK)); + for block in 0..12 { + let given: Vec = pieces.iter().copied().filter(|p| p.1 / BLOCK == block).collect(); + let here: Vec = landed.iter().copied().filter(|p| p.1 / BLOCK == block).collect(); + if given.iter().any(|p| p.0 != given[0].0) { + assert_eq!(here, given); + } else { + assert!(here.windows(2).all(|w| w[0].1 + w[0].2 < w[1].1), "apart, in order"); + } + } + let cut: Vec<(usize, usize)> = out.iter().map(|&(_, at, len)| (at, len)).collect(); + let jobs = jobs(&cut); + assert_eq!(jobs.iter().cloned().flatten().collect::>(), (0..cut.len()).collect::>()); + for w in jobs.windows(2) { + assert_ne!(cut[w[0].end - 1].0 / BLOCK, cut[w[1].start].0 / BLOCK); + } + } +} + +/// A piece is left out only if a fetch behind its own flight, or behind a +/// later one, brought all of it, and is forgotten when that flight is done. +#[test] +fn only_what_a_fetch_behind_the_flight_brought_is_left_out() { + let mut had = Had::default(); + had.fetched(7, [(1, BLOCK, BLOCK), (2, 0x100, 0x200)].into_iter()); + assert!(had.holds(6, (1, BLOCK, BLOCK)) && had.holds(7, (1, BLOCK + 64, 128))); + assert!(!had.holds(8, (1, BLOCK, BLOCK)), "the fetch ran ahead of flight 8"); + assert!(!had.holds(7, (3, BLOCK, BLOCK)) && !had.holds(7, (1, 0, 64))); + assert!(had.holds(7, (2, 0x100, 0x200)) && !had.holds(7, (2, 0x100, 0x204)) && !had.holds(7, (2, 0xfc, 8))); + had.landing(7); + assert!(had.holds(7, (1, BLOCK, BLOCK))); + had.landing(8); + assert!(had.0.is_empty()); +} + +/// A piece landed through either address holds what the merge of one thread +/// and one pass ([`crate::safecopy::merge`]) is to leave, with parts left +/// out, wherever it begins and ends. +#[test] +fn a_piece_lands_what_the_card_wrote_in_its_parts() { + assert!(crate::safecopy::on()); + let title = Title::new(2 * BLOCK); + let mut random = Random(5); + for round in 0..300usize { + let from = (random.next() % 5000) & !3; + let len = (random.next() % BLOCK).min(BLOCK - from).max(1); + let base: Vec = (0..len).map(|_| random.next() as u8).collect(); + let (mut now, mut held) = (base.clone(), base.clone()); + for _ in 0..random.next() % 60 { + let at = random.next() % len; + let n = (random.next() % 300).min(len - at); + for b in &mut now[at..at + n] { + *b = random.next() as u8; + } + } + let mut there = base.clone(); + for _ in 0..random.next() % 60 { + there[random.next() % len] ^= 0x11; + } + // Left out: some ranges, anywhere. + let mut parts = vec![(0, len)]; + for _ in 0..round % 4 { + let a = random.next() % len; + let b = (a + random.next() % 200).min(len); + parts = parts + .into_iter() + .flat_map(|(x, y)| [(x, y.min(a)), (x.max(b), y)]) + .filter(|(x, y)| x < y) + .collect(); + } + // SAFETY: inside the view; `kernel_will_write`'s rule for our own + // writes: the guard goes first. + unsafe { + crate::watch::writing(title.at, 2 * BLOCK); + std::ptr::copy_nonoverlapping(there.as_ptr(), (title.at + from) as *mut u8, len); + } + // Guarded, as after a refresh, in two rounds of three. + if round % 3 != 0 { + assert!(crate::watch::writes(title.at, title.at + 2 * BLOCK, true).is_some()); + assert_eq!(crate::watch::writes(title.at, title.at + 2 * BLOCK, true).map(|w| w.1.len() > 2), Some(false)); + } + let asked = crate::watch::writes(title.at, title.at + BLOCK, true).expect("a view").0; + let mut notes = Notes::default(); + // SAFETY: vectors of `len` bytes. + let put = unsafe { piece(title.at + from, now.as_ptr(), held.as_mut_ptr(), &parts, true, &mut notes) }; + notes.flush(); + let mut expect_held = base.clone(); + let mut expect = there.clone(); + for &(a, b) in &parts { + for i in a..b { + if now[i] != base[i] { + expect[i] = now[i]; + expect_held[i] = now[i]; + } + } + } + assert!(held == expect_held, "round {round}"); + assert!(title.bytes()[from..from + len] == expect[..], "round {round}"); + // Told: a refresh from now on takes the block again. + let (_, written) = crate::watch::writes(title.at, title.at + BLOCK, true).expect("a view"); + let told = written.iter().any(|&(page, at)| page == title.at / BLOCK && at > asked); + assert!(told || put == 0, "round {round}: {put} bytes, {written:?} after {asked}"); + } +} + +/// Landings on several threads beside title threads that write the same +/// blocks (other dwords) and a thread that refreshes a copy, guarding what +/// it takes: no write of the title's is lost or undone, all the card wrote +/// arrives, and once everything stands still the next refresh takes the +/// last of it (no note is lost). +#[test] +fn landings_beside_the_title_and_its_refreshes_lose_nothing() { + assert!(crate::safecopy::on()); + const BLOCKS: usize = 24; + const LEN: usize = BLOCKS * BLOCK; + let title = Title::new(LEN); + let at = title.at; + // SAFETY: committed, aligned, touched as atomics or by the landing's + // stores of whole dwords. + let dword = |i: usize| unsafe { &*((at + i * 4) as *const AtomicU32) }; + let stop = AtomicBool::new(false); + // The copy: its bytes, and per block the asking that last took it. + let copy: Mutex<(Vec, Vec)> = Mutex::new((vec![0; LEN], vec![0; BLOCKS])); + let refresh = || { + let mut copy = copy.lock().unwrap_or_else(|e| e.into_inner()); + let (now, written) = crate::watch::writes(at, at + LEN, true).expect("a view"); + let (bytes, taken) = &mut *copy; + for block in 0..BLOCKS { + let write = written.iter().find(|w| w.0 == at / BLOCK + block).map_or(0, |w| w.1); + if taken[block] == 0 || write > taken[block] { + taken[block] = now; + let part = &mut bytes[block * BLOCK..(block + 1) * BLOCK]; + // SAFETY: inside the view; whoever writes it meanwhile is + // noted, and the block taken again. + assert!(unsafe { crate::safecopy::copy(part.as_mut_ptr(), (at + block * BLOCK) as *const u8, BLOCK) }); + } + } + }; + let mut held = vec![0u8; LEN]; + std::thread::scope(|s| { + let writers: Vec<_> = (0..3usize) + .map(|w| { + let stop = &stop; + s.spawn(move || { + let mut value = 1u32; + while !stop.load(Ordering::Relaxed) { + // Its own dwords, in every other block (in the rest + // only landings change anything). + for i in (w..LEN / 4).step_by(4 * 97).filter(|i| i * 4 / BLOCK % 2 == 0) { + assert_eq!(dword(i).swap(value, Ordering::Relaxed), value - 1, "dword {i}: undone"); + } + value += 1; + } + value - 1 + }) + }) + .collect(); + s.spawn(|| { + while !stop.load(Ordering::Relaxed) { + refresh(); + } + }); + let mut random = Random(77); + for round in 1..250u32 { + // The card's dwords: every fourth, from the third on, in some + // pages of some blocks. + let mut now = held.clone(); + for _ in 0..60 { + let page = random.next() % (LEN / PAGE); + for i in (page * 1024 + 3..(page + 1) * 1024).step_by(4) { + now[i * 4..i * 4 + 4].copy_from_slice(&(round * 4096 + i as u32).to_le_bytes()); + } + } + let pieces: Vec = (0..BLOCKS).map(|b| (1, at + b * BLOCK, BLOCK)).collect(); + let order = ordered(&pieces); + let cut: Vec<(usize, usize)> = order.iter().map(|&(_, at, len)| (at, len)).collect(); + let jobs = jobs(&cut); + let into = held.as_mut_ptr() as usize; + each(jobs.len(), &|j| { + let mut notes = Notes::default(); + for &(address, len) in &cut[jobs[j].clone()] { + let offset = address - at; + // SAFETY: each job its own pieces of the two vectors. + unsafe { + piece(address, now.as_ptr().add(offset), (into + offset) as *mut u8, &[(0, len)], true, &mut notes); + } + } + notes.flush(); + }); + assert!(held == now, "round {round}"); + for i in (3..LEN / 4).step_by(4 * 61) { + let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().expect("four")); + assert_eq!(dword(i).load(Ordering::Relaxed), expect, "round {round} dword {i}"); + } + } + stop.store(true, Ordering::Relaxed); + for (w, writer) in writers.into_iter().enumerate() { + let last = writer.join().expect("nothing undone"); + for i in (w..LEN / 4).step_by(4 * 97).filter(|i| i * 4 / BLOCK % 2 == 0) { + assert_eq!(dword(i).load(Ordering::Relaxed), last); + } + } + }); + refresh(); + let copy = copy.into_inner().unwrap_or_else(|e| e.into_inner()); + assert!(copy.0 == title.bytes(), "a write was not told to the copy"); +} + +/// What a frame's landing costs (ignored: a measurement): 1,536 pieces of +/// 64 KiB, 96 MB, of a 174 MB heap of view memory in 15 landings, each block +/// guarded by a refresh before it; three quarters of the pages of a piece +/// with new bytes, every dword of them. As before, and here on one thread +/// and more, through the title's address and through a view of ours. +#[test] +#[ignore] +fn what_landing_costs() { + assert!(crate::safecopy::on()); + const HEAP: usize = 2784 * BLOCK; + const COUNT: usize = 1536; + let title = Title::new(HEAP); + let mut held = vec![0u8; HEAP]; + let mut card = vec![0u8; COUNT * BLOCK]; + let busy = AtomicBool::new(true); + // The pieces: runs of eight blocks, scattered. + let pieces: Vec = (0..COUNT).map(|i| (i / 8 * 1021 % (HEAP / BLOCK / 8)) * 8 + i % 8).collect(); + std::thread::scope(|s| { + // Other threads of the process at work (what a protection change + // has to reach). + for _ in 0..6 { + s.spawn(|| { + let mut v = vec![0u64; 1 << 14]; + while busy.load(Ordering::Relaxed) { + for (i, x) in v.iter_mut().enumerate() { + *x = x.wrapping_mul(31).wrapping_add(i as u64); + } + } + }); + } + let mut round = 0u32; + // `guarded`: 2 as a refresh leaves them, 1 opened again before (that + // is timed beside), 0 not at all, as they were after the last. + let mut frame = |label: &str, dense: bool, guarded: u8, land: &dyn Fn(&[(usize, usize, usize)])| { + let mut best = f64::MAX; + let (mut guards, mut opening) = (f64::MAX, f64::MAX); + for _ in 0..5 { + round += 1; + for (k, &block) in pieces.iter().enumerate() { + for page in 0..16 { + if page % 4 == 3 { + continue; + } + let from = k * BLOCK + page * PAGE; + let step = if dense { 4 } else { 64 }; + // (The rest as held.) + let old = block * BLOCK + page * PAGE; + card[from..from + PAGE].copy_from_slice(&held[old..old + PAGE]); + for b in card[from..from + PAGE].chunks_exact_mut(step) { + b[..4].copy_from_slice(&round.wrapping_mul(0x0101_0101).to_le_bytes()); + } + } + let (a, b) = (k * BLOCK + 12 * PAGE, block * BLOCK + 12 * PAGE); + for page in [3usize, 7, 11, 15] { + let (a, b) = (a - 12 * PAGE + page * PAGE, b - 12 * PAGE + page * PAGE); + card[a..a + PAGE].copy_from_slice(&held[b..b + PAGE]); + } + } + let t = std::time::Instant::now(); + if guarded > 0 { + assert!(crate::watch::writes(title.at, title.at + HEAP, true).is_some()); + } + guards = guards.min(t.elapsed().as_secs_f64() * 1e3); + let t = std::time::Instant::now(); + if guarded == 1 { + pieces.iter().for_each(|block| crate::watch::landing(title.at + block * BLOCK, BLOCK)); + } + opening = opening.min(t.elapsed().as_secs_f64() * 1e3); + let all: Vec<(usize, usize, usize)> = pieces + .iter() + .enumerate() + .map(|(k, &block)| { + (title.at + block * BLOCK, card.as_ptr() as usize + k * BLOCK, held.as_mut_ptr() as usize + block * BLOCK) + }) + .collect(); + let t = std::time::Instant::now(); + for landing in all.chunks(COUNT / 15 + 1) { + land(landing); + } + best = best.min(t.elapsed().as_secs_f64() * 1e3); + } + println!("{label}: {best:.1} ms a frame to land; the guards before it {guards:.1} ms, opening them {opening:.1} ms"); + }; + for dense in [true, false] { + println!("{}", if dense { "every dword of three pages in four new" } else { "every sixteenth dword of them new" }); + let before: &dyn Fn(&[(usize, usize, usize)]) = &|landing| { + let mut scratch: Vec = Vec::new(); + for &(at, now, held) in landing { + crate::shadow::land_as_before(at, now, held, BLOCK, &mut scratch); + } + }; + frame("as before", dense, 2, before); + 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); + 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(); + let jobs = jobs(&cut); + pool.each(jobs.len(), &|j| { + let mut notes = Notes::default(); + for &(at, now, held) in &landing[jobs[j].clone()] { + // SAFETY: each its own bytes. + unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside) }; + } + notes.flush(); + }); + }); + } + } + } + busy.store(false, Ordering::Relaxed); + }); +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 2ecf3ab..4748fde 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -33,6 +33,8 @@ mod host; mod indirect; #[cfg(windows)] mod inplace; +#[cfg(windows)] +mod land; pub mod list; pub mod object; pub mod pipeline; diff --git a/crates/victory-gpu/src/safecopy.rs b/crates/victory-gpu/src/safecopy.rs index 24eb646..66bb68a 100644 --- a/crates/victory-gpu/src/safecopy.rs +++ b/crates/victory-gpu/src/safecopy.rs @@ -75,6 +75,65 @@ std::arch::global_asm!( "vzeroupper", "xor eax, eax", "ret", + ".globl victory_safe_merge", + ".globl victory_safe_merge_at", + ".globl victory_safe_merge_after", + ".globl victory_safe_merge_failed", + // rcx title memory, rdx what the card holds, r8 what it held when last + // looked at, r9 blocks of 32 bytes, fifth where the two counts go. Where + // a byte of the second differs from the third, it goes into title memory + // (as whole dwords, and only dwords that then differ from what is there) + // and into the third; each block of title memory is read just before it + // is written. rax: the blocks left when a page of title memory could not + // be read or written (0: all done). The counts: blocks in which the + // second and third differed, dwords stored in title memory. + "victory_safe_merge:", + "xor r10d, r10d", + "xor r11d, r11d", + "test r9, r9", + "jz 6f", + "vpcmpeqd ymm5, ymm5, ymm5", + "2:", + "vmovdqu ymm0, ymmword ptr [rdx]", + "vpcmpeqb ymm1, ymm0, ymmword ptr [r8]", + "vpmovmskb eax, ymm1", + "cmp eax, -1", + "je 5f", + "victory_safe_merge_at:", + "vmovdqu ymm2, ymmword ptr [rcx]", + "vpblendvb ymm3, ymm0, ymm2, ymm1", + "vpcmpeqd ymm4, ymm3, ymm2", + "vmovmskps eax, ymm4", + "xor eax, 255", + "jz 4f", + "cmp eax, 255", + "je 3f", + "vpxor ymm4, ymm4, ymm5", + "vpmaskmovd ymmword ptr [rcx], ymm4, ymm3", + "jmp 7f", + "3:", + "vmovdqu ymmword ptr [rcx], ymm3", + "victory_safe_merge_after:", + "7:", + "popcnt eax, eax", + "add r11, rax", + "4:", + "inc r10", + "vmovdqu ymmword ptr [r8], ymm0", + "5:", + "add rcx, 32", + "add rdx, 32", + "add r8, 32", + "dec r9", + "jnz 2b", + "6:", + "victory_safe_merge_failed:", + "vzeroupper", + "mov rax, qword ptr [rsp + 40]", + "mov qword ptr [rax], r10", + "mov qword ptr [rax + 8], r11", + "mov rax, r9", + "ret", ); unsafe extern "system" { @@ -86,6 +145,138 @@ unsafe extern "system" { fn victory_safe_put_at(); fn victory_safe_put_after(); fn victory_safe_put_failed(); + fn victory_safe_merge(title: *mut u8, now: *const u8, held: *mut u8, blocks: usize, counts: *mut [u64; 2]) -> usize; + fn victory_safe_merge_at(); + fn victory_safe_merge_after(); + fn victory_safe_merge_failed(); +} + +/// What [`merge`] did. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Merged { + /// Blocks of 32 bytes in which the card's bytes were new. + pub(crate) new: u64, + /// Dwords stored in title memory. + pub(crate) dwords: u64, + /// Whether title memory could be read and written wherever it had to be. + pub(crate) there: bool, +} + +/// What shaders wrote goes into title memory: every byte of `now` that +/// differs from the one in `held` goes to `title` and into `held`, every +/// other byte of both stays as it is. Title memory is read 32 bytes at a +/// time, each just before what changes of them is stored, and only the +/// dwords that change are stored (at ends that are no dword's, bytes): the +/// title's own threads may be writing those beside them. +/// +/// Where title memory cannot be read or written, the rest of `held` takes +/// `now` if `take` says so (the caller has the card's bytes nowhere else), +/// else it stays. +/// +/// # Safety +/// `now` and `held` are `len` bytes of ours, not overlapping, that nothing +/// else writes (but for `now` the card: it is read once); `title` is as +/// [`copy`]'s. The stretch lies in one page of 4 KiB of title memory. [`on`] +/// must have been asked. +pub(crate) unsafe fn merge(title: *mut u8, now: *const u8, held: *mut u8, len: usize, take: bool) -> Merged { + let mut out = Merged { there: true, ..Merged::default() }; + let mut at = 0; + while at < len { + let address = title.addr() + at; + let left = len - at; + if !address.is_multiple_of(4) || left < 4 { + // A dword only partly in the stretch: its bytes one by one. + // SAFETY: inside the stretch. + unsafe { + let byte = now.add(at).read_volatile(); + let mut there = 0u8; + if byte != held.add(at).read() { + out.new += 1; + let mut ok = copy(&mut there, title.add(at), 1); + if ok && there != byte { + ok = copy(title.add(at), &byte, 1); + out.dwords += u64::from(ok); + } + out.there &= ok; + if ok || take { + held.add(at).write(byte); + } + } + } + at += 1; + continue; + } + let into = address % 32; + let mut counts = [0u64; 2]; + if into != 0 || left < 32 { + // Part of a block: in a block of its own, equal beside the part. + let n = (32 - into).min(left) & !3; + let (mut new, mut old) = ([0u8; 32], [0u8; 32]); + // SAFETY: inside the stretch; the block of title memory around + // it lies in the same page, and nothing of it outside the part + // is stored (the two arrays are equal there). + unsafe { + std::ptr::copy_nonoverlapping(now.add(at), new.as_mut_ptr().add(into), n); + std::ptr::copy_nonoverlapping(held.add(at), old.as_mut_ptr().add(into), n); + let stuck = victory_safe_merge(title.wrapping_add(at).wrapping_sub(into), new.as_ptr(), old.as_mut_ptr(), 1, &mut counts); + out.there &= stuck == 0; + let from = if stuck != 0 && take { new.as_ptr() } else { old.as_ptr() }; + std::ptr::copy_nonoverlapping(from.add(into), held.add(at), n); + } + at += n; + } else { + let blocks = left / 32; + // SAFETY: whole blocks of the stretch. + let stuck = unsafe { victory_safe_merge(title.add(at), now.add(at), held.add(at), blocks, &mut counts) }; + if stuck != 0 { + out.there = false; + if take { + let from = at + (blocks - stuck) * 32; + // SAFETY: the blocks that were not done. + unsafe { std::ptr::copy_nonoverlapping(now.add(from), held.add(from), stuck * 32) }; + } + } + at += blocks * 32; + } + out.new += counts[0]; + out.dwords += counts[1]; + } + out +} + +/// Whether the `len` bytes at `a` and `b` differ. +/// +/// # Safety +/// Both are `len` bytes that can be read; the card may be writing them. +pub(crate) unsafe fn differ(a: *const u8, b: *const u8, len: usize) -> bool { + use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_or_si256, _mm256_setzero_si256, _mm256_testz_si256, _mm256_xor_si256}; + /// # Safety + /// [`differ`]'s; the processor has AVX2 (as the code above assumes). + #[target_feature(enable = "avx2")] + unsafe fn blocks(a: *const u8, b: *const u8, n: usize) -> bool { + let mut at = 0; + while at < n { + let mut any = _mm256_setzero_si256(); + for k in at..n.min(at + 4) { + // SAFETY: block `k`, inside both. + let (x, y) = unsafe { + (_mm256_loadu_si256(a.add(k * 32).cast::<__m256i>()), _mm256_loadu_si256(b.add(k * 32).cast::<__m256i>())) + }; + any = _mm256_or_si256(any, _mm256_xor_si256(x, y)); + } + if _mm256_testz_si256(any, any) == 0 { + return true; + } + at += 4; + } + false + } + // SAFETY: the caller's. + if unsafe { blocks(a, b, len / 32) } { + return true; + } + // SAFETY: the bytes behind the blocks. + (len / 32 * 32..len).any(|i| unsafe { a.add(i).read_volatile() != b.add(i).read_volatile() }) } /// Puts `now` at `dst` where it differs from `was`, whole dwords (as `dst` @@ -160,7 +351,11 @@ pub(crate) fn failing_exit(at: usize) -> Option { return Some(victory_safe_copy_failed as *const () as usize); } let (from, to) = (victory_safe_put_at as *const () as usize, victory_safe_put_after as *const () as usize); - (from..to).contains(&at).then_some(victory_safe_put_failed as *const () as usize) + if (from..to).contains(&at) { + return Some(victory_safe_put_failed as *const () as usize); + } + let (from, to) = (victory_safe_merge_at as *const () as usize, victory_safe_merge_after as *const () as usize); + (from..to).contains(&at).then_some(victory_safe_merge_failed as *const () as usize) } #[cfg(test)] @@ -266,6 +461,173 @@ mod tests { } } + /// [`merge`] against what it is to do, byte by byte, for every kind of + /// start, end and change: the bytes the card changed arrive in title + /// memory and in what it held, no dword without one is stored. + #[test] + fn a_merge_puts_what_the_card_changed_and_nothing_else() { + assert!(on()); + let pages = Pages::new(1 << 12); + let mut seed = 1u32; + let mut random = move || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed + }; + for round in 0..4000u32 { + let at = random() as usize % 100; + let len = random() as usize % 300; + let (from, to) = (at, (at + len).min(400)); + let n = to - from; + let base: Vec = (0..512).map(|_| random() as u8).collect(); + let was: Vec = base[from..to].to_vec(); + let mut held = was.clone(); + let mut now = was.clone(); + let mut title = base.clone(); + // The card's writes: dwords and single bytes; the title's: some + // in the same dwords, some the same values. + for _ in 0..random() % 12 { + if n > 0 { + let i = random() as usize % n; + now[i] = random() as u8; + } + let i = random() as usize % 512; + title[i] = if (from..to).contains(&i) && round % 3 == 0 { now[i - from] } else { random() as u8 }; + } + if round % 7 == 0 { + now.iter_mut().for_each(|b| *b = b.wrapping_add(1)); + } + // SAFETY: inside the allocation and the vectors. + let done = unsafe { + std::ptr::copy_nonoverlapping(title.as_ptr(), pages.0, 512); + merge(pages.0.add(from), now.as_ptr(), held.as_mut_ptr(), n, round % 2 == 0) + }; + assert!(done.there); + // SAFETY: inside the allocation. + let there = unsafe { std::slice::from_raw_parts(pages.0, 512) }; + for i in 0..512 { + let wrote = (from..to).contains(&i) && now[i - from] != was[i - from]; + let expect = if wrote { now[i - from] } else { title[i] }; + assert_eq!(there[i], expect, "round {round} byte {i} of {from}..{to}"); + } + assert_eq!(held, now, "round {round}"); + assert_eq!(done.new == 0, was == now); + // Found merged already. + // SAFETY: as above. + let again = unsafe { merge(pages.0.add(from), now.as_ptr(), held.as_mut_ptr(), n, false) }; + assert_eq!(again, Merged { new: 0, dwords: 0, there: true }); + } + } + + /// Title memory that is not there: what the card wrote stays to be + /// looked at again, or is taken, as asked; a page that only cannot be + /// written counts the same. + #[test] + fn a_merge_into_missing_memory_fails() { + assert!(on()); + let pages = Pages::new(1 << 13); + let mut old = 0; + for (missing, take) in [(true, false), (true, true), (false, false), (false, true)] { + for (at, len) in [(0usize, 4096usize), (4, 64), (7, 1), (40, 100)] { + let was = vec![1u8; len]; + let mut now = was.clone(); + now[len - 1] = 9; + let mut held = was.clone(); + // SAFETY: our allocation. + let done = unsafe { + if missing { + VirtualFree(pages.0.cast(), 4096, MEM_DECOMMIT); + } else { + VirtualProtect(pages.0.cast(), 4096, PAGE_READONLY, &mut old); + } + let done = merge(pages.0.add(at), now.as_ptr(), held.as_mut_ptr(), len, take); + VirtualAlloc(pages.0.cast(), 4096, MEM_COMMIT, PAGE_READWRITE); + VirtualProtect(pages.0.cast(), 4096, PAGE_READWRITE, &mut old); + done + }; + assert!(!done.there); + assert_eq!(held, if take { now.clone() } else { was.clone() }, "{missing} {take} {at} {len}"); + // Nothing to put: nothing fails. + let mut held = now.clone(); + // SAFETY: as above; the addresses are no one's. + let done = unsafe { merge(std::ptr::without_provenance_mut(0x1000 + at), now.as_ptr(), held.as_mut_ptr(), len, take) }; + assert!(done.there && done.new == 0); + } + } + } + + /// [`merge`] beside threads that write other dwords of the same memory: + /// none of their writes is lost or undone. + #[test] + fn merges_undo_no_write_of_other_threads() { + use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + assert!(on()); + let pages = Pages::new(1 << 12); + let base = pages.0 as usize; + // SAFETY: committed, aligned memory, only touched as atomics or by + // the merge's stores of whole dwords. + let dword = |i: usize| unsafe { &*((base + i * 4) as *const AtomicU32) }; + let stop = AtomicBool::new(false); + std::thread::scope(|s| { + let writers: Vec<_> = (0..2usize) + .map(|w| { + let stop = &stop; + s.spawn(move || { + let mut value = 1u32; + while !stop.load(Ordering::Relaxed) { + for i in (w..1024).step_by(4) { + // This thread's own dword: nobody else's value. + assert_eq!(dword(i).load(Ordering::Relaxed), value - 1, "dword {i}"); + dword(i).store(value, Ordering::Relaxed); + } + value += 1; + } + }) + }) + .collect(); + // The card's dwords: every fourth, from the third on. + let mut held = vec![0u8; 4096]; + for round in 1..3000u32 { + let mut now = held.clone(); + for i in (2..1024).step_by(4) { + if i * 7 % 5 != round as usize % 5 { + now[i * 4..i * 4 + 4].copy_from_slice(&(round + i as u32).to_le_bytes()); + } + } + // SAFETY: the allocation, whole. + let done = unsafe { merge(base as *mut u8, now.as_ptr(), held.as_mut_ptr(), 4096, false) }; + assert!(done.there); + for i in (2..1024).step_by(4) { + let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().unwrap()); + assert_eq!(dword(i).load(Ordering::Relaxed), expect); + } + for i in (3..1024).step_by(4) { + assert_eq!(dword(i).load(Ordering::Relaxed), 0); + } + } + stop.store(true, Ordering::Relaxed); + for w in writers { + w.join().expect("no write was undone"); + } + }); + } + + #[test] + fn differences_are_seen_wherever_they_are() { + for len in [0usize, 1, 31, 32, 33, 127, 128, 129, 200] { + let a = vec![7u8; len]; + // SAFETY: the vectors' bytes. + assert!(!unsafe { differ(a.as_ptr(), a.clone().as_ptr(), len) }); + for at in 0..len { + let mut b = a.clone(); + b[at] = 8; + // SAFETY: as above. + assert!(unsafe { differ(a.as_ptr(), b.as_ptr(), len) }, "{len} {at}"); + } + } + } + /// What the copies cost (ignored: a measurement): 64 KiB pieces of /// scattered memory into a buffer the card reads, by the kernel and here. #[test] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 882f00d..725f2c1 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -17,7 +17,7 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, RwLock}; use windows::Win32::Graphics::Direct3D12::ID3D12Resource; @@ -49,6 +49,11 @@ pub(crate) struct Shadow { /// GPU wrote differs. Room for the whole copy; only those ranges' bytes /// are set (and read). before: Mutex>>, + /// Held shared while pieces of the copy are landed (`crate::land`), each + /// its own bytes of it on several threads, and alone while title bytes + /// go in under shader writes ([`Shadow::merge_under_writes`]), which + /// takes `before`'s lock too. Taken ahead of that one. + merging: RwLock<()>, /// With snapshots kept ([`keeps`]): which 64 KiB pieces of the snapshot /// hold the copy's bytes as they are now, and whether the snapshot is /// counted in [`KEPT_BYTES`]. @@ -560,40 +565,34 @@ pub(crate) fn relay_fetched(number: u64) { /// writing: the next refresh would have put title bytes over what the /// second flight's shaders were writing. #[derive(Default)] -struct Flights(Vec<((usize, usize), u32, u64)>); +struct Flights(std::collections::HashMap<(usize, usize), (u32, u64)>); impl Flights { /// Submission `number` declares `range`: counted once for it, however /// often it declares it. fn declare(&mut self, range: (usize, usize), number: u64) { - match self.0.iter_mut().find(|f| f.0 == range) { - Some(f) => { - if f.2 != number { - f.1 += 1; - f.2 = number; - } - } - None => self.0.push((range, 1, number)), + let f = self.0.entry(range).or_insert((0, number)); + if f.0 == 0 || f.1 != number { + *f = (f.0 + 1, number); } } /// One submission that declared `ranges` (each once) is copied back: - /// the ranges no other submission still holds. + /// the ranges no other submission still holds, in order. fn done(&mut self, ranges: &[(usize, usize)]) -> Vec<(usize, usize)> { let mut free = Vec::new(); for range in ranges { - match self.0.iter().position(|f| f.0 == *range) { - Some(at) => { - self.0[at].1 = self.0[at].1.saturating_sub(1); - if self.0[at].1 == 0 { - self.0.swap_remove(at); - free.push(*range); - } + match self.0.get_mut(range) { + Some(f) if f.0 > 1 => f.0 -= 1, + Some(_) => { + self.0.remove(range); + free.push(*range); } // Not counted (declared before anything counted): free. None => free.push(*range), } } + free.sort_unstable(); free } } @@ -1412,7 +1411,7 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { /// Whether what shaders wrote goes into title memory run by run /// ([`put_changed`]; on by default, `VICTORY_EXACT_BACK=0` writes the whole /// stretch from the first changed byte to the last, as before). -fn exact_back() -> bool { +pub(crate) fn exact_back() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_EXACT_BACK").is_none_or(|v| v != "0")) } @@ -1490,6 +1489,27 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { written } +/// For `crate::land`'s measurement: a piece as [`Shadow::card_merge_relay`] +/// lands it without `VICTORY_LAND`: `n` bytes at `now`, `held` what the CPU's +/// side held, both the caller's alone. +#[cfg(test)] +pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, title: &mut Vec) { + // SAFETY: the caller's. + let (gpu, held) = unsafe { (std::slice::from_raw_parts(now as *const u8, n), std::slice::from_raw_parts_mut(held as *mut u8, n)) }; + let Some(first) = first_difference(gpu, held) else { + return; + }; + let last = last_difference(gpu, held).unwrap_or(first); + let n = last + 1 - first; + title.clear(); + title.resize(n, 0); + assert!(crate::host::read_into((start + first) as *const u8, title)); + let was = title.clone(); + if merge_piece(&gpu[first..=last], &mut held[first..=last], title) { + put_changed(start + first, &was, title); + } +} + #[cfg(test)] mod merge_tests { use super::{changed_runs, dword_runs}; @@ -1880,6 +1900,7 @@ impl Shadow { pending: Mutex::default(), flights: Mutex::default(), before: Mutex::default(), + merging: RwLock::default(), kept: Mutex::default(), used: AtomicU64::new(crate::host::moment()), asked: [AtomicU64::new(u64::MAX), AtomicU64::new(0)], @@ -2279,7 +2300,7 @@ impl Shadow { let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); if relay() { let free = self.flights.lock().unwrap_or_else(|e| e.into_inner()).done(ranges); - pending.retain(|r| !free.contains(r)); + pending.retain(|r| free.binary_search(r).is_err()); } else { pending.retain(|r| !ranges.contains(r)); } @@ -2455,6 +2476,7 @@ impl Shadow { // 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. @@ -2497,6 +2519,7 @@ impl Shadow { } } drop(before); + drop(_merging); // 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. @@ -2908,6 +2931,271 @@ impl Shadow { } } +impl Shadow { + /// [`Shadow::card_merge_relay`] of several pieces, each within one + /// 64 KiB block of title memory: from and to (offsets in the copy), and + /// where the fetched bytes are. On any thread: several may land pieces + /// of one copy, no two the same bytes. Returns the bytes put into title + /// memory. + /// + /// What is left out is as there, asked once for all of them: the notes + /// of bytes that went up (or are to go up) behind the fetch only move + /// from `dirty` to `sent`, with a later number, and grow only by + /// [`Shadow::merge_under_writes`], which the lock held here keeps out. + /// + /// # Safety + /// The third of each piece is the address of its bytes, which stay as + /// they are during the call. + pub(crate) unsafe fn land_card(&self, pieces: &[(usize, usize, usize)], fetched_after: u64, notes: &mut crate::land::Notes) -> u64 { + let Some(card) = &self.card else { + return 0; + }; + let waiting = std::time::Instant::now(); + let _merging = self.merging.read().unwrap_or_else(|e| e.into_inner()); + crate::land::spent(crate::land::stat::LOCK, waiting); + let (from, to) = pieces.iter().fold((usize::MAX, 0), |(a, b), p| (a.min(p.0), b.max(p.1))); + let skip: Vec<(usize, usize)> = { + let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); + let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner()); + dirty + .iter() + .copied() + .chain(sent.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1))) + .filter(|&(a, b)| a < to && b > from) + .collect() + }; + let mut put = 0; + for &(lo, hi, now) in pieces { + if lo >= hi || hi > self.len as usize { + continue; + } + let near: Vec<(usize, usize)> = skip.iter().copied().filter(|&(a, b)| a < hi && b > lo).collect(); + let parts: Vec<(usize, usize)> = outside(lo, hi, near).into_iter().map(|(a, b)| (a - lo, b - lo)).collect(); + // SAFETY: inside the mapping (checked above), in a range + // declared and not done with, which no refresh writes; the + // title's bytes are kept out by the lock; the caller's. + // Where title memory is not mapped the CPU's side keeps what + // the card wrote, as before. + let merged = + unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes) }; + self.walls_merged(hi - lo, merged as usize); + put += merged; + } + put + } + + /// [`Shadow::relay_merge`] of a piece `[at, at + n)` (within one 64 KiB + /// block of title memory) of a copy in the PC's memory; on any thread, + /// as [`Shadow::land_card`]. The copy is read once and never written. + /// Returns the bytes put into title memory. + pub(crate) fn land_back(&self, at: usize, n: usize, notes: &mut crate::land::Notes) -> u64 { + if self.card.is_some() || n == 0 || at + n > self.len as usize { + return 0; + } + let waiting = std::time::Instant::now(); + let _merging = self.merging.read().unwrap_or_else(|e| e.into_inner()); + crate::land::spent(crate::land::stat::LOCK, waiting); + // The snapshot's memory stays where it is until the range is done + // with (`copy_back_done`), which comes after this. + let Some(held) = self.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut().map(Vec::as_mut_ptr) else { + return 0; + }; + // SAFETY: inside the copy's mapping (checked above), which only the + // card writes there, and inside the snapshot's allocation, which + // holds the copy's length (`writing`): these offsets are in a range + // declared and not done with, whose bytes it holds, and the lock + // keeps out what else writes them. Title memory that is not there + // is looked at again when the next flight that declared the range + // lands. + unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes) } + } +} + +#[cfg(test)] +mod land_tests { + use super::{Card, PIECE, Shadow}; + use std::sync::Mutex; + use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + + /// A copy in the card's memory of title memory at `title` (its card side + /// is never looked at here), all bytes 0 on the CPU's side. + fn copy_of(title: usize, len: usize) -> Option { + let (buffer, data) = crate::host::host()?.shared_buffer(len as u64)?; + // SAFETY: the mapping, `len` bytes. + unsafe { std::ptr::write_bytes(data, 0, len) }; + let mut shadow = Shadow::new(buffer.clone(), data, 0, title as u64, len as u64); + shadow.card = Some(Card { + staging: buffer, + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + size: len as u64, + }); + Some(shadow) + } + + /// Memory that stays (`crate::watch` knows its addresses): private, or a + /// view noted as the runtime notes the title's. + fn memory(len: usize, view: bool) -> usize { + use windows_sys::Win32::System::Memory as mem; + // SAFETY: plain allocations of our own. + unsafe { + if !view { + return mem::VirtualAlloc(std::ptr::null(), len, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as usize; + } + let section = mem::CreateFileMappingW(-1isize as _, std::ptr::null(), mem::PAGE_READWRITE, 0, len as u32, std::ptr::null()); + let at = mem::MapViewOfFile(section, mem::FILE_MAP_WRITE, 0, 0, len).Value as usize; + crate::inplace::title_memory_section(section as usize, len as u64, true); + crate::title_memory_remapped(at, len); + crate::inplace::title_memory_view(at, len, section as usize, 0); + at + } + } + + fn random(seed: &mut u64) -> usize { + *seed ^= *seed << 13; + *seed ^= *seed >> 7; + *seed ^= *seed << 17; + (*seed >> 8) as usize + } + + /// [`Shadow::land_card`] leaves title memory and the CPU's side as + /// [`Shadow::card_merge_relay`] does, with title bytes that went up + /// behind the fetch, or have not gone up, left out. + #[test] + fn pieces_land_as_the_merge_one_by_one_lands_them() { + assert!(crate::safecopy::on()); + const LEN: usize = 3 * PIECE; + let mut seed = 0x1234_5678_9abcu64; + for view in [false, true] { + let (a, b) = (memory(LEN, view), memory(LEN, view)); + let (Some(one), Some(many)) = (copy_of(a, LEN), copy_of(b, LEN)) else { + return; // no host GPU + }; + // SAFETY: the two memories and the two mappings. + let bytes = |at: usize| unsafe { std::slice::from_raw_parts_mut(at as *mut u8, LEN) }; + for round in 0..40u32 { + let base: Vec = (0..LEN).map(|_| random(&mut seed) as u8).collect(); + let (mut held, mut title, mut now) = (base.clone(), base.clone(), base); + let (mut dirty, mut sent) = (Vec::new(), Vec::new()); + for k in 0..120 { + let at = random(&mut seed) % LEN / 4 * 4; + let n = (random(&mut seed) % 900 / 4 * 4).min(LEN - at); + match k % 4 { + 0 | 1 => now[at..at + n].fill(random(&mut seed) as u8), + 2 => title[at..at + n].fill(random(&mut seed) as u8), + // Title bytes put into the CPU's side meanwhile. + _ => { + let byte = random(&mut seed) as u8; + held[at..at + n].fill(byte); + title[at..at + n].fill(byte); + if k % 8 == 3 { + dirty.push((at, at + n)); + } else { + sent.push((at, at + n, u64::from(round % 3) + (k as u64 / 16))); + } + } + } + } + let after = 4u64; + for (shadow, at) in [(&one, a), (&many, b)] { + crate::watch::writing(at, LEN); + bytes(at).copy_from_slice(&title); + bytes(shadow.data as usize).copy_from_slice(&held); + let card = shadow.card.as_ref().expect("made with one"); + *card.dirty.lock().unwrap() = dirty.clone(); + *card.sent.lock().unwrap() = sent.clone(); + } + let pieces: Vec<(usize, usize)> = (0..3).map(|p| (p * PIECE + 16, (p + 1) * PIECE - 4)).collect(); + let mut scratch = Vec::new(); + for &(lo, hi) in &pieces { + one.card_merge_relay(lo, &now[lo..hi], after, &mut scratch); + } + let addressed: Vec<(usize, usize, usize)> = + pieces.iter().map(|&(lo, hi)| (lo, hi, now.as_ptr() as usize + lo)).collect(); + let mut notes = crate::land::Notes::default(); + // SAFETY: the fetched bytes are `now`'s. + unsafe { many.land_card(&addressed, after, &mut notes) }; + notes.flush(); + assert!(bytes(a) == bytes(b), "title memory, round {round}"); + assert!(bytes(one.data as usize) == bytes(many.data as usize), "the CPU's side, round {round}"); + } + } + } + + /// Landings of one copy on several threads, the title writing dwords of + /// the same blocks, and the title's bytes put into the CPU's side under + /// the shaders' writes ([`Shadow::merge_under_writes`]), all at once. The + /// card has never received the title's bytes: what is fetched holds older + /// ones there, which must not be taken for shaders' writes. + #[test] + fn landings_and_title_bytes_going_in_keep_each_others_bytes() { + assert!(crate::safecopy::on()); + const BLOCKS: usize = 16; + const LEN: usize = BLOCKS * PIECE; + let title = memory(LEN, true); + let Some(shadow) = copy_of(title, LEN) else { + return; // no host GPU + }; + shadow.pending.lock().unwrap().push((title, title + LEN)); + // SAFETY: committed, aligned; touched as atomics or by the landing's + // stores of whole dwords. + let dword = |i: usize| unsafe { &*((title + i * 4) as *const AtomicU32) }; + let stop = AtomicBool::new(false); + std::thread::scope(|s| { + let writer = s.spawn(|| { + let mut value = 1u32; + while !stop.load(Ordering::Relaxed) { + for i in (1..LEN / 4).step_by(4 * 331) { + assert_eq!(dword(i).swap(value, Ordering::Relaxed), value - 1, "dword {i}: undone"); + } + value += 1; + std::thread::sleep(std::time::Duration::from_micros(200)); + } + value - 1 + }); + s.spawn(|| { + while !stop.load(Ordering::Relaxed) { + let mut runs = usize::MAX; + assert!(!shadow.merge_under_writes(title, LEN, &mut runs)); + // Sent up, as the preparing of a submission would: noted + // with a number behind the fetches'. + let card = shadow.card.as_ref().expect("made with one"); + let mut dirty = card.dirty.lock().unwrap(); + let mut sent = card.sent.lock().unwrap(); + let moved: Vec<_> = std::mem::take(&mut *dirty).into_iter().map(|(a, b)| (a, b, 9)).collect(); + sent.extend(moved); + sent.sort_unstable(); + sent.dedup(); + } + }); + let mut now = vec![0u8; LEN]; + for round in 1..200u32 { + for block in (0..BLOCKS).filter(|b| (*b as u32 * 5 + round) % 3 != 0) { + for i in (block * PIECE / 4 + 3..(block + 1) * PIECE / 4).step_by(4) { + now[i * 4..i * 4 + 4].copy_from_slice(&(round << 20 | i as u32).to_le_bytes()); + } + } + let at = now.as_ptr() as usize; + crate::land::each(BLOCKS, &|b| { + let mut notes = crate::land::Notes::default(); + let (lo, hi) = (b * PIECE, (b + 1) * PIECE); + // SAFETY: the fetched bytes are `now`'s; each block once. + unsafe { shadow.land_card(&[(lo, hi, at + lo)], 8, &mut notes) }; + notes.flush(); + }); + for i in (3..LEN / 4).step_by(4 * 53) { + let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().expect("four")); + assert_eq!(dword(i).load(Ordering::Relaxed), expect, "round {round} dword {i}"); + } + } + stop.store(true, Ordering::Relaxed); + let last = writer.join().expect("nothing undone"); + assert!((1..LEN / 4).step_by(4 * 331).all(|i| dword(i).load(Ordering::Relaxed) == last)); + }); + } +} + struct Entry { end: u64, shadow: Option>, diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 27774d6..f8529a6 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -449,7 +449,28 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> { /// The 4 KiB pages of title memory that what shaders wrote was put into, /// and the frame it last was. -static LANDED: Mutex>> = Mutex::new(None); +static LANDED: Mutex>>> = Mutex::new(None); + +/// A page's number, spread: some 20,000 a frame are noted in [`LANDED`]. +#[derive(Default)] +struct PageHash(u64); + +impl std::hash::Hasher for PageHash { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for &byte in bytes { + self.write_u64(u64::from(byte)); + } + } + fn write_u64(&mut self, n: u64) { + self.0 = (self.0 ^ n).wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(26).wrapping_mul(0x9e37_79b9_7f4a_7c15); + } + fn write_usize(&mut self, n: usize) { + self.write_u64(n as u64); + } +} /// What shaders wrote is about to go into title memory at `[at, at + len)`. pub(crate) fn landing(at: usize, len: usize) { @@ -464,6 +485,42 @@ pub(crate) fn landing(at: usize, len: usize) { writing(at, len); } +/// What shaders wrote went into title memory through another view of the +/// same pages (`crate::inplace::beside`): `pages` (of 4 KiB, by number) +/// hold some of it, all of them in `spans` (address, bytes). +/// +/// Nothing faulted and no guard was opened. A guarded block stays read-only +/// and is noted as written, as [`guard`] notes one "written through the +/// runtime": the next asking reports it, to every copy that has it, and has +/// nothing to protect. Noted after the bytes are in, never before: a copy +/// that takes the block while they go in notes it clean, and this makes it +/// written again; noted before, such a copy would keep the half it read. +pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) { + { + let frame = crate::frame::current(); + let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); + let landed = landed.get_or_insert_with(Default::default); + for &page in pages { + landed.insert(page, frame); + } + } + { + let mut g = guards(); + let mut last = usize::MAX; + for &page in pages { + let block = page * KERNEL_PAGE / BLOCK; + if block != last { + g.clean.remove(&block); + last = block; + } + } + } + for &(at, len) in spans { + // A placed texture there changes with no descriptor written. + crate::descriptor::host::remapped(at, len); + } +} + /// Whether shaders' writes went into a page of `[at, at + len)` in the last /// `frames` frames. pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool { @@ -475,8 +532,9 @@ pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool { } /// Whether every block of `[at, at + len)` is view memory written since a -/// host copy last took it: guarded then, and the guard is off. (Written by -/// the title, or by us putting a flight's shader writes into it.) Not for +/// host copy last took it: guarded then, and the guard is off, or noted +/// written behind it. (Written by the title, or by us putting a flight's +/// shader writes into it, [`landed_beside`].) Not for /// blocks no copy ever took, which were never guarded: the caller's range /// lies in a copy a flight was given, which took all of it. pub(crate) fn written_since_taken(at: usize, len: usize) -> bool { @@ -485,7 +543,7 @@ pub(crate) fn written_since_taken(at: usize, len: usize) -> bool { } let g = guards(); (at / BLOCK..=(at + len - 1) / BLOCK) - .all(|b| !g.protected.contains(&b) && !g.clean.contains(&b) && !g.absent.contains(&b)) + .all(|b| !g.clean.contains(&b) && !g.absent.contains(&b)) } /// For view memory: the pages of `[start, end)`'s blocks written since From 007fe557302420f12a61da7a71ea09c72d64b53a Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 22:15:31 -0600 Subject: [PATCH 169/445] Steps done on the card take along what depends on them (VICTORY_CARD_STEPS) A buffer copy whose destination another step of the submission read was refused and waited for flights (10 ms a frame in run steps-1). Copies and fills that depend on a taken one, or it on them, are now taken too and done level by level in the steps' order; a fill of a texture's upload buffer as well. Reads on the CPU ahead of the copy are no reason to refuse. The waits for title memory changed under shader writes that came up behind it: pages of the title's constants have more changed runs than the 512 a submission sent up (4096 with the switch), and where it still waits, it waits for the flights that declared the range, not for everything. Diagnostics: refusals name the kind of step, waits under shader writes their reason and the host copy. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 93 +++- crates/victory-gpu/src/host/card_steps.rs | 566 +++++++++++++++++----- crates/victory-gpu/src/list.rs | 2 +- crates/victory-gpu/src/shadow.rs | 29 ++ 4 files changed, 539 insertions(+), 151 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 8e3572a..4acd7e4 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1677,10 +1677,9 @@ enum Step { /// A copy into title memory (destination, source, bytes): the title's /// buffer copies, which later refreshes must see. Copy(usize, usize, usize), - /// A copy of title memory into the list's own upload memory; if a - /// descriptor slot shows that memory and nothing else does (a constant - /// buffer of a table made for the draw), the title heap and the slot. - Fill(usize, usize, usize, Option<(usize, u32)>), + /// A copy of title memory into the list's own upload memory, and how + /// the card could bring the bytes instead. + Fill(usize, usize, usize, Option), /// Brings a range (address, bytes) of a buffer's host copy up to date: /// once per submission, whichever lists ask, until a `Copy` or `Run` /// intervenes. @@ -2291,13 +2290,23 @@ fn refused(why: &'static str) { *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why); } +/// The wait that comes next is for these ranges ([`stale_under_flights`]). +#[cfg(feature = "diagnostics")] +fn blame_stale(stale: &[(std::sync::Arc, usize, usize)]) { + if let Some((shadow, from, _)) = stale.first() { + let (start, len) = shadow.span(); + let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize); + BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from)); + } +} + /// The wait for what [`blame`] last named, or a wait of another reason than /// title memory read, took `us`. #[cfg(feature = "diagnostics")] fn blamed(why: usize, us: u64) { let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, "")); let (key, at) = match (why, named) { - (WHY_READ, Some(named)) => named, + (WHY_READ | WHY_STALE, Some(named)) => named, (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0), _ => { let kind = match why { @@ -2342,7 +2351,11 @@ fn log_blame(frames: f64) { us as f64 / 1e3 / frames, n as f64 / frames, passes.join(", "), - if why.is_empty() { "" } else { "; not done on the card: " }, + match (why.is_empty(), kind) { + (true, _) => "", + (_, "title memory changed under shader writes") => "; not put in under them: ", + _ => "; not done on the card: ", + }, ); } } @@ -2416,7 +2429,7 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op /// may write and that the title wrote since it was last copied. The /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so /// the title's bytes there would reach the card a submission late. -fn stale_under_flights(runs: &[&HostList]) -> bool { +fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc, usize, usize)> { use std::sync::Arc; // Per copy, the span of what is refreshed (a flush brings that much // up to date at most). @@ -2437,11 +2450,15 @@ fn stale_under_flights(runs: &[&HostList]) -> bool { // The title's bytes are put in beside the flights' writes; a // settle is still due where that could not be done. At most this // many changed runs go up to copies in the card's memory, each a - // copy of its own there. - let mut runs_left = 512; - return spans.iter().any(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left)); + // copy of its own there. With [`card_steps`] the pages of the + // title's ring of constants come here too, which were waited for + // before: hundreds of short runs each, at about 1.5 us a run. + let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 }; + spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left)); + return spans; } - spans.iter().any(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from)) + spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from)); + spans } /// A fence signal on a queue ([`late`]): goes behind the flights in the @@ -4295,6 +4312,40 @@ impl Host { working(was_working); } + /// For a submission of `runs` that refreshes the ranges `stale` of host + /// copies, which flights may be writing and the title wrote too + /// ([`stale_under_flights`]): the flights land first. `ranges` are + /// those of the submission's one asking, which is made again. + /// + /// With [`card_steps`] only the flights that declared them: a range of + /// a copy nobody declared any more is refreshed like any other. What + /// they landed is title memory written, so everything is asked and + /// looked at again; what is left after three times waits as before. + fn settle_stale( + &self, + submitted: &mut u64, + runs: &[&HostList], + mut stale: Vec<(std::sync::Arc, usize, usize)>, + ranges: &[(usize, usize)], + ) { + if relay_exact() && card_steps::stage() > 0 { + for _ in 0..3 { + #[cfg(feature = "diagnostics")] + blame_stale(&stale); + relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to))); + crate::watch::ask_once(ranges); + stale = stale_under_flights(runs); + if stale.is_empty() { + return; + } + } + } + #[cfg(feature = "diagnostics")] + blame_stale(&stale); + self.settle(submitted, WHY_STALE); + crate::watch::ask_once(ranges); + } + /// [`Host::execute`], or with `late` the first half of /// [`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 @@ -4396,13 +4447,13 @@ impl Host { // may write too, and this submission refreshes it. The flights // are settled, and the asking made again: the copy-back wrote // title memory, which other copies of it must see. - if behind && stale_under_flights(runs) { + let stale = if behind { stale_under_flights(runs) } else { Vec::new() }; + if !stale.is_empty() { let settling = std::time::Instant::now(); - self.settle(&mut submitted, WHY_STALE); + self.settle_stale(&mut submitted, runs, stale, &ranges); settled += settling.elapsed(); - crate::watch::ask_once(&ranges); } - } else if behind && stale_under_flights(runs) { + } else if behind && !stale_under_flights(runs).is_empty() { let settling = std::time::Instant::now(); self.settle(&mut submitted, WHY_STALE); settled += settling.elapsed(); @@ -5355,7 +5406,14 @@ impl HostList { pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) { self.deferred() .copies - .push(Step::Fill(dst as usize, src as usize, len, Some(slot))); + .push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1)))); + } + + /// As [`HostList::defer_fill`], for the beginning of a buffer + /// [`HostList::upload`] made. + pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) { + let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone())); + self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to)); } /// Brings `[address, address + len)` of a buffer's host copy up to date @@ -5407,7 +5465,8 @@ impl HostList { /// /// shortcut: one buffer per copy; pool them once uploads are frequent. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { - let (buffer, data) = host.upload_buffer(size)?; + // With [`card_steps`] the card may be the one that fills it. + let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? }; name(&buffer, || format!("list upload {size:#x}")); self.deferred().hold_upload(buffer.clone(), size); Some((buffer, data)) diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 6c1f622..fd24a2c 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -9,17 +9,21 @@ use crate::shadow::Shadow; /// The stage (`VICTORY_CARD_STEPS`; off by default): `1` constant buffers /// of descriptor tables (`Step::Fill` with a slot of its own), `2` the -/// title's buffer copies (`Step::Copy`) too. Only with the relay's second -/// stage (`relay_exact`). +/// title's buffer copies (`Step::Copy`) too, with the steps of the same +/// submission that depend on them. Only with the relay's second stage +/// (`relay_exact`). /// -/// Why: a root view has no size, so a pass that writes through one into the -/// title's 174 MB heap is declared to write all that is left of it, and -/// some pass of every flight does. The title's ring of constants lies in -/// the same heap. One constant buffer of 480 bytes and one copy of 20 KiB a -/// frame, at a new place of the ring each time, waited for nearly -/// everything in the air: 25-30 ms of a 105 ms frame, the submitting thread -/// standing (run record-1; with `VICTORY_FILL_TITLE=1` in run relaycopy-1 -/// the copy alone took over the wait). +/// Why: eleven dispatches a frame (the skinning passes, in two early +/// submissions) write through a view of the title's whole 174 MB heap, at +/// places they read out of job records in buffers: no bound of what they +/// write is known before they ran (frame capture replay2: 17af15c4015cb4b6, +/// 55679a0547649d0b, 89d08e561897d4e5, fdd56d97a806bcca and three more, +/// all through one view at offset 5920 of the title's bindless table). The +/// title's ring of constants lies in the same heap. One constant buffer of +/// 480 bytes and one copy of 20 KiB a frame, at a new place of the ring +/// each time, waited for these passes to land: 25-30 ms of a 105 ms frame, +/// the submitting thread standing (run record-1; with `VICTORY_FILL_TITLE=1` +/// in run relaycopy-1 the copy alone took over the wait). /// /// What is done: a list of ours goes to the card in front of the /// submission's lists, in the same call. It copies the bytes read from the @@ -41,8 +45,10 @@ use crate::shadow::Shadow; /// like any other list's (also under flights' declared writes: /// `stale_under_flights`, which settles if it cannot). Nothing of this /// submission writes these bytes earlier than our list: the steps are done -/// in front of all its lists in either case, and [`plan`] refuses when -/// another step of the submission writes what is read. Every draw that +/// in front of all its lists in either case, and among themselves in the +/// order they stand in wherever one depends on another: [`plan`] takes +/// every copy and fill of the submission that writes what a taken one +/// reads or writes, or reads what a taken one writes. Every draw that /// reads a buffer view of the heap relies on the same refresh and the same /// order; what is new is only that a constant buffer and a copy do too. /// Where a page is not mapped the host copy may hold other bytes than the @@ -54,9 +60,10 @@ use crate::shadow::Shadow; /// memory before the title is told anything of this flight (its /// bottom-of-pipe writes and fences come after, in order); CPU steps of /// later submissions that read it find it declared and wait, or are done -/// here. Refused: another step of the submission reads or writes the -/// destination on the CPU, or a refresh brings another host copy of it up -/// to date ([`plan`], [`elsewhere`]). While such a copy is in the air a +/// here. Refused: a step of the submission that cannot be taken (a texture, +/// vertices expanded, a fill of memory of another kind) reads the +/// destination behind the copy, or a refresh brings another host copy of it +/// up to date ([`plan`], [`elsewhere`]). While such a copy is in the air a /// submission that refreshes another host copy of its destination, or /// reads it in a step that is not checked otherwise, waits for it /// ([`copied_read`]); with the copy done on the CPU it was there at once. @@ -77,8 +84,22 @@ pub(super) fn stage() -> u32 { } /// The bytes of our buffer between reading and writing: what one submission -/// may do this way. -const BETWEEN: u64 = 1 << 20; +/// may do this way (each place read once, however many fills take it). +const BETWEEN: u64 = 4 << 20; + +/// The most steps of a submission done this way. +const MOST: usize = 4096; + +/// How a fill's bytes get where its list reads them, if the card brings +/// them. +#[derive(Clone)] +pub(super) enum FillTo { + /// A descriptor slot that shows the fill's memory, and nothing else does + /// (title heap, slot): it is made to show our buffer instead. + Slot(usize, u32), + /// A buffer the card can write, filled from its beginning. + Buffer(ID3D12Resource), +} /// Title memory something in the air writes: the host copy it goes through /// (`None`: none, the bytes reach title memory when the flight lands), from, @@ -167,7 +188,8 @@ pub(super) fn copied_read(copies: &[Writer], runs: &[&HostList]) -> bool { #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Does { Copy { dst: usize, src: usize, len: usize, asked: bool }, - Fill { src: usize, len: usize, asked: bool, slot: Option<(usize, u32)> }, + /// `to`: its memory can be given the bytes on the card. + Fill { src: usize, len: usize, asked: bool, to: bool }, /// Another read on the CPU (a texture, vertices expanded). Read { from: usize, to: usize, asked: bool }, /// A refresh of a host copy (named by its address). @@ -180,51 +202,125 @@ fn meet(a: (usize, usize), b: (usize, usize)) -> bool { a.0 < b.1 && b.0 < a.1 } -/// The steps of `does` (by place) to be done on the card: all that are -/// asked for, or why not. Our list does them all in front of the -/// submission's, every read before every write, so that is right only if no -/// step, asked for or not, writes what one of them reads or writes, and no -/// CPU step reads what one of them writes. -fn plan(does: &[Does], stage: u32) -> Result, &'static str> { - let mut asked = Vec::new(); +/// The bytes `d` reads and writes as a copy or a fill (empty ranges for +/// what it does not). +fn reads_writes(d: &Does) -> Option<((usize, usize), (usize, usize))> { + match *d { + Does::Copy { dst, src, len, .. } => Some(((src, src + len), (dst, dst + len))), + Does::Fill { src, len, .. } => Some(((src, src + len), (0, 0))), + _ => None, + } +} + +fn touched(ranges: &[(usize, usize)], r: (usize, usize)) -> bool { + touches(ranges, r.0, r.1) +} + +/// The steps of `does` (by place) to be done on the card, in order, each +/// with its level; or why not. All that are asked for, and every copy and +/// fill that is in the way of one that is done there: it writes what that +/// one reads or writes, or reads what it writes, whichever comes first. So +/// what is left on the CPU writes none of their bytes, and reads of them +/// 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. +/// +/// 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> { + 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"), + _ => Ok(()), + }; + let mut taken = vec![false; does.len()]; + let (mut read, mut written) = (Vec::new(), Vec::new()); + let mut more = Vec::new(); for (i, d) in does.iter().enumerate() { match *d { Does::Run => return Err("a step of ours runs"), Does::Read { asked: true, .. } => return Err("a texture reads it"), - Does::Fill { asked: true, slot: None, .. } => return Err("a fill without a descriptor slot of its own"), - Does::Copy { asked: true, .. } if stage < 2 => return Err("a buffer copy (VICTORY_CARD_STEPS=2 does it on the card)"), - Does::Copy { asked: true, .. } | Does::Fill { asked: true, .. } => asked.push(i), + Does::Copy { asked: true, .. } | Does::Fill { asked: true, .. } => more.push(i), _ => {} } } - for &i in &asked { - let (src, dst) = match does[i] { - Does::Copy { dst, src, len, .. } => ((src, src + len), Some((dst, dst + len))), - Does::Fill { src, len, .. } => ((src, src + len), None), - _ => continue, - }; - for (k, d) in does.iter().enumerate() { - let (read, written) = match *d { - Does::Copy { dst, src, len, .. } => (Some((src, src + len)), Some((dst, dst + len))), - Does::Fill { src, len, .. } => (Some((src, src + len)), None), - Does::Read { from, to, .. } => (Some((from, to)), None), - Does::Refresh { .. } | Does::Run => (None, None), - }; - if written.is_some_and(|w| meet(w, src)) { - return Err("a copy of the submission writes what it reads"); + while !more.is_empty() { + for i in std::mem::take(&mut more) { + takes(&does[i])?; + taken[i] = true; + if let Some((r, w)) = reads_writes(&does[i]) { + if w.0 < w.1 && meet(r, w) { + return Err("a copy onto itself"); + } + join_ranges(&mut read, [r]); + join_ranges(&mut written, [w]); } - let Some(dst) = dst else { + } + if taken.iter().filter(|t| **t).count() > MOST { + return Err("too many steps depend on it"); + } + for (i, d) in does.iter().enumerate() { + // A fill that cannot be taken is looked at below. + if taken[i] || matches!(d, Does::Fill { to: false, .. }) { continue; - }; - if k != i && written.is_some_and(|w| meet(w, dst)) { - return Err("another copy of the submission writes what it writes"); } - if read.is_some_and(|r| meet(r, dst)) { - return Err("a step of the submission reads what it writes"); + if let Some((r, w)) = reads_writes(d) + && (touched(&written, r) || touched(&written, w) || touched(&read, w)) + { + more.push(i); } } } - Ok(asked) + let order: Vec = (0..does.len()).filter(|&i| taken[i]).collect(); + // What stays on the CPU and reads what an earlier taken copy writes + // would read it too early. + let mut behind: Vec<(usize, usize)> = Vec::new(); + for (i, d) in does.iter().enumerate() { + if taken[i] { + if let Some((_, w)) = reads_writes(d) { + join_ranges(&mut behind, [w]); + } + continue; + } + match *d { + Does::Read { from, to, .. } if touched(&behind, (from, to)) => { + return Err("a texture or expanded vertices read what it writes"); + } + Does::Fill { src, len, .. } if touched(&behind, (src, src + len)) => { + return Err("a fill of memory the card cannot be given the bytes of reads what it writes"); + } + _ => {} + } + } + let mut out: Vec<(usize, u32)> = Vec::with_capacity(order.len()); + // The copies among them, which alone put others behind them or have to + // stand behind others. + let mut copies: Vec = Vec::new(); + for &i in &order { + let Some((r, w)) = reads_writes(&does[i]) else { + continue; + }; + let writes = w.0 < w.1; + let mut level = 0; + // Behind what writes what this reads or writes, and, if this + // writes, behind what reads it. + let ahead: Box> = + if writes { Box::new(0..out.len()) } else { Box::new(copies.iter().copied()) }; + for k in ahead { + let (j, at): (usize, u32) = out[k]; + let Some((jr, jw)) = reads_writes(&does[j]) else { + continue; + }; + if at >= level && (meet(jw, r) || meet(jw, w) || meet(jr, w)) { + level = at + 1; + } + } + if writes { + copies.push(out.len()); + } + out.push((i, level)); + } + Ok(out) } /// Whether a refresh of `does` brings a host copy other than `shadow` up to @@ -272,6 +368,7 @@ struct Op { len: usize, /// Its place in the buffer between. at: u64, + level: u32, to: To, } @@ -280,14 +377,18 @@ enum To { Copy(Arc, usize), /// A descriptor slot (title heap, slot). Slot(usize, u32), + /// A buffer's beginning. + Buffer(ID3D12Resource), } -/// Records what [`stage`] describes into `list` (open): `reads` are copied -/// into `between` (source, offset in it, offset in `between`, bytes), then -/// `writes` out of it (destination, offset in it, offset in `between`, -/// bytes). `between` is left readable as constants, the others in the -/// common state, as the submission's lists expect them. +/// Records a level of what [`stage`] describes into `list` (open): `reads` +/// are copied into `between` (source, offset in it, offset in `between`, +/// bytes), then `writes` out of it (destination, offset in it, offset in +/// `between`, bytes). `between` is left readable as constants (and must be +/// so, unless this is the `first` level), the others in the common state, +/// as the submission's lists expect them. fn record( + first: bool, list: &ID3D12GraphicsCommandList, between: &ID3D12Resource, reads: &[(&ID3D12Resource, u64, u64, u64)], @@ -305,23 +406,28 @@ fn record( } } let both = |b: &ID3D12Resource| dests.iter().any(|d| d.as_raw() == b.as_raw()); - let mut barriers = vec![transition(between, dest, source | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER)]; + let constants = source | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER; + let mut barriers = vec![transition(between, dest, constants)]; barriers.extend(sources.iter().map(|b| transition(b, source, if both(b) { dest } else { common }))); let done: Vec = dests.iter().map(|b| transition(b, dest, common)).collect(); // SAFETY: an open list; live buffers, and the callers' ranges lie in // them. The buffers start in the common state (the list is the first of // its call) and are promoted by their first use. unsafe { - // What earlier lists' shaders wrote, first. - list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { - Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, - Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, - Anonymous: D3D12_RESOURCE_BARRIER_0 { - UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { - pResource: std::mem::ManuallyDrop::new(None), - }), - }, - }]); + if first { + // What earlier lists' shaders wrote, first. + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + } else { + list.ResourceBarrier(&[transition(between, constants, dest)]); + } for &(buffer, offset, at, len) in reads { list.CopyBufferRegion(between, at, buffer, offset, len); } @@ -426,6 +532,8 @@ impl Host { fn take_steps(&self, written: &[(usize, usize)], runs: &[&HostList]) -> Result, &'static str> { let mut does = Vec::new(); + // Where the fills' bytes go. + let mut fills = std::collections::HashMap::new(); // Which step each is. One list's lock at a time: a submission may // name a list twice. let mut steps = Vec::new(); @@ -438,11 +546,16 @@ impl Host { len, asked: copy_blocked(written, dst, src, len).is_some(), }, - &Step::Fill(_, src, len, slot) => Does::Fill { - src, - len, - asked: read_blocked(written, src, len), - slot, + Step::Fill(_, src, len, to) => Does::Fill { + src: *src, + len: *len, + asked: read_blocked(written, *src, *len), + to: { + if let Some(to) = to { + fills.insert(does.len(), to.clone()); + } + to.is_some() + }, }, Step::Texture(staging) => { let (at, len) = staging.memory(); @@ -468,7 +581,7 @@ impl Host { if chosen.is_empty() { return Ok(None); } - let writers = { + let mut writers = { let line = line(); let mut all = writers(&line.line); all.extend(line.landing.iter().map(|w| Writer { @@ -478,24 +591,39 @@ impl Host { all }; let mut ops: Vec = Vec::with_capacity(chosen.len()); - let mut at = 0u64; - for &i in &chosen { - let (src, len) = match does[i] { - Does::Copy { src, len, .. } | Does::Fill { src, len, .. } => (src, len), - _ => continue, + // The places read (host copy, address, bytes, level): where in the + // buffer between their bytes are. + let mut places = std::collections::HashMap::new(); + let mut end = 0u64; + for &(i, level) in &chosen { + let Some(((src, _), (dst, _))) = reads_writes(&does[i]) else { + continue; + }; + let (Does::Copy { len, .. } | Does::Fill { len, .. }) = does[i] else { + continue; }; if len == 0 { return Err("nothing to read"); } - if at + len as u64 > BETWEEN { - return Err("too much at once"); - } let from = holder(&writers, src, src + len)?; - if !mapped(src, src + len) { - return Err("not all of what it reads is mapped"); - } + let place = (Arc::as_ptr(&from) as usize, src, len, level); + let at = match places.get(&place) { + Some(&at) => at, + None => { + if end + len as u64 > BETWEEN { + return Err("too much at once"); + } + if !mapped(src, src + len) { + return Err("not all of what it reads is mapped"); + } + let at = end; + end = (end + len as u64).next_multiple_of(256); + places.insert(place, at); + at + } + }; let to = match does[i] { - Does::Copy { dst, .. } => { + Does::Copy { .. } => { let to = holder(&writers, dst, dst + len)?; if elsewhere(&does, Arc::as_ptr(&to) as usize, dst, dst + len) { return Err("another host copy of what it writes is read"); @@ -503,35 +631,42 @@ impl Host { if !mapped(dst, dst + len) { return Err("not all of what it writes is mapped"); } + // What the steps behind it read of it is in that host + // copy, or nowhere. + writers.push(Writer { + shadow: Some(to.clone()), + from: dst, + to: dst + len, + copy: true, + }); To::Copy(to, dst) } - Does::Fill { slot: Some((heap, index)), .. } => To::Slot(heap, index), - _ => continue, + _ => match fills.get(&i) { + Some(FillTo::Slot(heap, index)) => To::Slot(*heap, *index), + Some(FillTo::Buffer(buffer)) => To::Buffer(buffer.clone()), + None => continue, + }, }; ops.push(Op { from: (from, src), len, at, + level, to, }); - at = (at + len as u64).next_multiple_of(256); } let Some(own) = self.own_list() else { return Err("no host list or buffer for it"); }; - let mut reads = Vec::new(); - let mut writes = Vec::new(); - let mut copied = Vec::new(); - // First every refresh, then the write: the bytes compared with are + // First every refresh, then the writes: the bytes compared with are // the title's. for op in &ops { op.from.0.refresh(&own.list, op.from.1 as u64, op.len as u64); - reads.push((&op.from.0.buffer, op.from.0.offset(op.from.1 as u64), op.at, op.len as u64)); if let To::Copy(to, dst) = &op.to { to.refresh(&own.list, *dst as u64, op.len as u64); - writes.push((&to.buffer, to.offset(*dst as u64), op.at, op.len as u64)); } } + let mut copied = Vec::new(); for op in &ops { if let To::Copy(to, dst) = &op.to { to.gpu_writes(&own.list, *dst as u64, op.len as u64); @@ -539,8 +674,26 @@ impl Host { } } #[cfg(feature = "diagnostics")] - own.list.note_op(|| format!("{} copies of title memory done on the card, {at} bytes (VICTORY_CARD_STEPS)", ops.len())); - record(&own.list.list, &own.between, &reads, &writes); + own.list.note_op(|| format!("{} copies of title memory done on the card, {end} bytes (VICTORY_CARD_STEPS)", ops.len())); + let levels = ops.iter().map(|op| op.level).max().unwrap_or(0); + for level in 0..=levels { + let mut reads = Vec::new(); + let mut writes = Vec::new(); + for op in ops.iter().filter(|op| op.level == level) { + let len = op.len as u64; + let read = (&op.from.0.buffer, op.from.0.offset(op.from.1 as u64), op.at, len); + // (Each place once.) + if places.remove(&(Arc::as_ptr(&op.from.0) as usize, op.from.1, op.len, level)).is_some() { + reads.push(read); + } + match &op.to { + To::Copy(to, dst) => writes.push((&to.buffer, to.offset(*dst as u64), op.at, len)), + To::Buffer(buffer) => writes.push((buffer, 0, op.at, len)), + To::Slot(..) => {} + } + } + record(level == 0, &own.list.list, &own.between, &reads, &writes); + } own.list.close(); // SAFETY: a live buffer. let gpu = unsafe { own.between.GetGPUVirtualAddress() }; @@ -552,6 +705,9 @@ impl Host { // (A heap that is gone: nothing can read the slot.) crate::descriptor::constant_slot(*heap, *index, gpu + op.at, op.len as u32); } + To::Buffer(_) => { + DONE[0].fetch_add(1, Ordering::Relaxed); + } To::Copy(..) => { DONE[1].fetch_add(1, Ordering::Relaxed); } @@ -561,7 +717,7 @@ impl Host { } Ok(Some(Taken { own, - steps: chosen.iter().map(|&i| steps[i]).collect(), + steps: chosen.iter().map(|&(i, _)| steps[i]).collect(), copied, })) } @@ -592,7 +748,7 @@ static NOTED: Mutex> = Mutex::new(None); fn noted(op: &Op) { let (to, dst) = match &op.to { To::Copy(to, dst) => (to.span(), *dst), - To::Slot(..) => ((0, 0), 0), + To::Slot(..) | To::Buffer(_) => ((0, 0), 0), }; let mut noted = NOTED.lock().unwrap_or_else(|e| e.into_inner()); let e = noted.get_or_insert_with(Default::default).entry((op.len, op.from.0.span(), to)).or_default(); @@ -646,11 +802,20 @@ mod tests { } fn fill(src: usize, len: usize, asked: bool) -> Does { - Does::Fill { src, len, asked, slot: Some((1, 2)) } + Does::Fill { src, len, asked, to: true } + } + + fn stuck(src: usize, len: usize) -> Does { + Does::Fill { src, len, asked: false, to: false } + } + + /// What is done on the card, as (place, level), in stage 2. + fn planned(does: &[Does]) -> Vec<(usize, u32)> { + plan(does, 2).unwrap() } /// Only what is asked for is taken, all of it, and a step that stands - /// in none of their ways changes nothing. + /// in none of their ways stays where it is. #[test] fn steps_apart_from_one_another_are_taken() { let does = [ @@ -660,44 +825,150 @@ mod tests { copy(3000, 6000, 100, true), fill(1000, 64, false), Does::Read { from: 3100, to: 4000, asked: false }, + stuck(3100, 5), ]; - assert_eq!(plan(&does, 2), Ok(vec![1, 3])); + 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, 1])); + 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![])); + // Ends that touch are apart. + let does = [ + copy(1000, 5000, 100, true), + copy(900, 9000, 100, false), + copy(1100, 9000, 5, false), + copy(4900, 9000, 100, false), + ]; + assert_eq!(planned(&does), [(0, 0)]); } - /// Everything that could make the card's order another than the CPU's - /// refuses the lot, wherever in the submission it stands. + /// What depends on a taken step, or it on it, is taken too, on the level + /// the order of the steps asks for. #[test] - fn steps_in_one_anothers_way_are_refused() { + fn steps_that_depend_on_one_another_are_taken_in_order() { let taken = copy(1000, 5000, 100, true); - let refused = |other: Does| { - assert!(plan(&[taken, other], 2).is_err(), "{other:?} after"); - assert!(plan(&[other, taken], 2).is_err(), "{other:?} before"); + // Reads what it writes, behind and ahead of it. + assert_eq!(planned(&[taken, fill(1099, 64, false)]), [(0, 0), (1, 1)]); + assert_eq!(planned(&[fill(1099, 64, false), taken]), [(0, 0), (1, 1)]); + assert_eq!(planned(&[taken, copy(7000, 1050, 10, false)]), [(0, 0), (1, 1)]); + // Writes what it reads, and what it writes. + assert_eq!(planned(&[copy(5099, 9000, 1, false), taken]), [(0, 0), (1, 1)]); + assert_eq!(planned(&[taken, copy(5099, 9000, 1, false)]), [(0, 0), (1, 1)]); + assert_eq!(planned(&[taken, copy(999, 9000, 2, false)]), [(0, 0), (1, 1)]); + // The same list twice. + assert_eq!(planned(&[taken, taken]), [(0, 0), (1, 1)]); + // A chain, with steps apart from it in between, and two fills of one + // copy on one level. + let does = [ + copy(8000, 7000, 50, false), + taken, + copy(2000, 1010, 20, false), + fill(90_000, 10, false), + fill(2000, 20, false), + fill(2010, 20, true), + copy(1000, 2005, 5, false), + fill(1000, 100, false), + ]; + assert_eq!(planned(&does), [(1, 0), (2, 1), (4, 2), (5, 2), (6, 2), (7, 3)]); + // A fill is in nobody's way. + assert_eq!(planned(&[taken, fill(5000, 100, false)]), [(0, 0)]); + // A copy ahead that a taken one only shares its source with. + assert_eq!(planned(&[copy(7000, 5000, 10, false), taken]), [(1, 0)]); + } + + /// 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. + #[test] + fn levels_do_what_the_order_does() { + let mut seed = 12345u32; + let mut random = move |n: u32| { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12345); + (seed >> 16) % n }; - for asked in [false, true] { - // Writes what it reads. - refused(copy(5099, 9000, 1, asked)); - // Writes what it writes. - refused(copy(999, 9000, 2, asked)); - // Reads what it writes. - refused(copy(7000, 1050, 10, asked)); - refused(fill(1099, 64, asked)); - refused(Does::Read { from: 900, to: 1001, asked }); + let (mut done, mut refused) = (0, 0); + for _ in 0..4000 { + let does: Vec = (0..2 + random(9)) + .map(|_| { + let (at, other, len) = (random(60) as usize, random(60) as usize, 1 + random(8) as usize); + let asked = random(4) == 0; + match random(8) { + 0..4 => copy(at, other, len, asked), + 4..6 => fill(at, len, asked), + 6 => stuck(at, len), + _ => Does::Read { from: at, to: at + len, asked: false }, + } + }) + .collect(); + let Ok(chosen) = plan(&does, 2) else { + refused += 1; + continue; + }; + done += 1; + let start: Vec = (0..80).collect(); + // One after the other: what each reads, and what is left. + let mut memory = start.clone(); + let mut wanted = Vec::new(); + for d in &does { + let (from, to) = match *d { + Does::Read { from, to, .. } => (from, to), + _ => reads_writes(d).unwrap().0, + }; + wanted.push(memory[from..to].to_vec()); + if let Does::Copy { dst, src, len, .. } = *d { + memory.copy_within(src..src + len, dst); + } + } + // The CPU's, then the card's. + let mut cpu = start.clone(); + let taken = |i: usize| chosen.iter().any(|c| c.0 == i); + for (i, d) in does.iter().enumerate().filter(|&(i, _)| !taken(i)) { + let (from, to) = match *d { + Does::Read { from, to, .. } => (from, to), + _ => reads_writes(d).unwrap().0, + }; + assert_eq!(cpu[from..to], wanted[i][..], "step {i} of {does:?}"); + if let Does::Copy { dst, src, len, .. } = *d { + cpu.copy_within(src..src + len, dst); + } + } + let mut card = cpu.clone(); + for level in 0..=chosen.iter().map(|c| c.1).max().unwrap_or(0) { + let of: Vec = chosen.iter().filter(|c| c.1 == level).map(|c| c.0).collect(); + let before = card.clone(); + for i in of { + let ((from, to), (dst, _)) = reads_writes(&does[i]).unwrap(); + assert_eq!(before[from..to], wanted[i][..], "step {i} of {does:?}: {chosen:?}"); + if matches!(does[i], Does::Copy { .. }) { + card[dst..dst + to - from].copy_from_slice(&before[from..to]); + } + } + } + assert_eq!(card, memory, "{does:?}: {chosen:?}"); } - refused(Does::Run); - // A texture that itself waits for flights; a fill with no slot. - refused(Does::Read { from: 1, to: 2, asked: true }); - refused(Does::Fill { src: 1, len: 1, asked: true, slot: None }); - // Into itself, and the same list twice. + assert!(done > 500 && refused > 100, "{done} {refused}"); + } + + /// What cannot be done on the card refuses the lot, where it stands in + /// the way. + #[test] + fn steps_in_the_way_are_refused() { + let taken = copy(1000, 5000, 100, true); + assert!(plan(&[taken, Does::Run], 2).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()); + // 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_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()); + // Into itself, and copies without stage 2. assert!(plan(&[copy(1000, 1050, 100, true)], 2).is_err()); - assert!(plan(&[taken, taken], 2).is_err()); - // A fill of what a copy writes, and copies without stage 2. - assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 2).is_err()); assert!(plan(&[taken], 1).is_err()); - // Ends that touch are apart. - assert!(plan(&[taken, copy(900, 9000, 100, false), copy(1100, 9000, 5, false), copy(4900, 9000, 100, false)], 2).is_ok()); + assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 1).is_err()); } #[test] @@ -735,11 +1006,14 @@ mod tests { let own = host.own_list().unwrap(); // Within `a` (there and back), from `a` to `b`, and a read alone. record( + true, &own.list.list, &own.between, &[(&a, 33, 0, 100), (&a, 2000, 256, 100), (&a, 5001, 512, 7), (&a, 9, 1024, 4)], &[(&a, 2000, 0, 100), (&a, 33, 256, 100), (&b, 77, 512, 7)], ); + // A level behind it, of what it wrote. + record(false, &own.list.list, &own.between, &[(&b, 77, 2048, 7)], &[(&b, 1077, 2048, 7)]); own.list.close(); // A list behind it that uses the buffers in other ways. let next = host.new_list().unwrap(); @@ -756,6 +1030,7 @@ mod tests { assert_eq!(a_bytes[2000..2100], was[33..133]); assert_eq!(a_bytes[33..133], was[2000..2100]); assert_eq!(b_bytes[77..84], was[5001..5008]); + assert_eq!(b_bytes[1077..1084], was[5001..5008]); assert_eq!(b_bytes[4096..4196], was[2000..2100]); // SAFETY: a mapping of 64 KiB. assert_eq!(unsafe { std::slice::from_raw_parts(out_data, 4) }, &was[9..13]); @@ -780,7 +1055,10 @@ mod tests { fn a_copy_behind_a_flight_reads_what_the_flight_wrote() { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; const LEN: usize = 4 << 20; - const WRITE_WATCH: u32 = 0x20_0000; + // Without it (`TEST_UNWATCHED=1`) the title's bytes cannot be put in + // under a flight's writes: the flights that declared them are waited + // for. + let write_watch = if std::env::var_os("TEST_UNWATCHED").is_some() { 0 } else { 0x20_0000 }; let Some(host) = host() else { return; }; @@ -789,7 +1067,7 @@ mod tests { // second, and back. let (title, start) = { // SAFETY: memory of our own, never freed. - let base = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, PAGE_READWRITE) }.cast::(); + let base = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | write_watch, PAGE_READWRITE) }.cast::(); assert!(!base.is_null()); // SAFETY: `LEN` bytes just committed. (unsafe { std::slice::from_raw_parts_mut(base, LEN) }, base as usize) @@ -831,10 +1109,21 @@ mod tests { for (i, b) in title[5300..5400].iter_mut().enumerate() { *b = seed(1300 + i) ^ 0x5c; } + // Thousands of runs of bytes of its own. + for b in title[1_700_000..1_708_000].iter_mut().step_by(2) { + *b = 1 + round as u8; + } // Into the second buffer, and within the first. let b = host.new_list().unwrap(); b.defer_copy((start + HALF + 100) as *mut u8, (start + 4001) as *const u8, 1500); b.defer_copy((start + 900_001) as *mut u8, (start + 4400) as *const u8, 777); + b.defer_copy((start + HALF + 10_000) as *mut u8, (start + 1_700_000) as *const u8, 8000); + // What depends on them: a copy of the first copy, upload memory + // filled from that, and the first one's bytes copied over. + b.defer_copy((start + 1_500_000) as *mut u8, (start + HALF + 600) as *const u8, 700); + let (staging, staged) = b.upload(host, 4096).unwrap(); + b.defer_fill_buffer(&staging, staged, (start + 1_500_100) as *const u8, 500); + b.defer_copy((start + HALF + 300) as *mut u8, (start + 8000) as *const u8, 64); b.close(); host.execute_own(&b); // What the first wrote, read by the next submission. @@ -852,17 +1141,28 @@ mod tests { }) .collect(); assert!(title[4000..6000] == wanted[..], "what the flight wrote, round {round}"); - assert!(title[HALF + 100..HALF + 1600] == wanted[1..1501], "the copy to the other buffer, round {round}"); + // (The copy over the first one's bytes came last.) + let mut over = wanted[1..1501].to_vec(); + over[200..264].fill(0); + assert!(title[HALF + 100..HALF + 1600] == over[..], "the copy to the other buffer, round {round}"); + assert!(title[1_500_000..1_500_700] == wanted[501..1201], "the copy behind a copy, round {round}"); + // SAFETY: the mapping, which the flight wrote and has landed. + let staged = unsafe { std::slice::from_raw_parts(staged, 500) }; + assert!(staged == &wanted[601..1101], "the fill behind it, round {round}"); assert!(title[900_001..900_778] == wanted[400..1177], "the copy within the buffer, round {round}"); - assert!(title[1_200_000..1_201_500] == wanted[1..1501], "the copy of the copy, round {round}"); + assert!(title[1_200_000..1_201_500] == over[..], "the copy of the copy, round {round}"); assert!(title[HALF..HALF + 100].iter().all(|&x| x == 0)); - assert!(title[HALF + 1600..].iter().all(|&x| x == 0)); + assert!(title[HALF + 1600..HALF + 10_000].iter().all(|&x| x == 0)); + assert!(title[HALF + 18_000..].iter().all(|&x| x == 0)); + let runs = &title[HALF + 10_000..HALF + 18_000]; + assert!(runs.chunks(2).all(|b| b == [1 + round as u8, 0]), "the runs, round {round}"); a.keep(&upload); lists.extend([a, b, c]); } assert_eq!(host.log_messages(), None); let done = DONE[1].load(Ordering::Relaxed) - before; - eprintln!("{done} of 24 copies were done on the card, {} submissions waited", DONE[3].load(Ordering::Relaxed)); - assert!(done >= 12, "only {done} copies were done on the card"); + eprintln!("{done} of 48 copies were done on the card, {} submissions waited", DONE[3].load(Ordering::Relaxed)); + eprintln!("settles for title memory under shader writes: {}", LATE_STATS[WHY_STALE].load(Ordering::Relaxed)); + assert!(done >= 20, "only {done} copies were done on the card"); } } diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 44c8965..995f187 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -971,7 +971,7 @@ extern "system" fn copy_texture_region( }; // The list owns this mapped D3D12 upload buffer. Wine can report // its address as MEM_FREE, so use the host-upload path. - list.defer_fill(staging, data, bytes as usize); + list.defer_fill_buffer(&buffer, staging, data, bytes as usize); from.resource = buffer.as_raw().cast_const().cast(); from.footprint.offset = 0; #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 882f00d..d8cade0 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1377,6 +1377,25 @@ mod wide_tests { /// compared, changed runs put in, and their bytes. static MERGED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; +/// Why [`Shadow::merge_under_writes`] last left the caller to wait. +static STALE_WHY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +fn note_stale(why: usize) { + STALE_WHY.store(why, Ordering::Relaxed); +} + +/// [`STALE_WHY`] in words (diagnostics). +#[cfg(feature = "diagnostics")] +pub(crate) fn stale_why() -> &'static str { + const WHY: [&str; 4] = [ + "the memory is not watched", + "the journal does not say what was written", + "more changed runs than a submission sends up", + "no snapshot", + ]; + WHY[STALE_WHY.load(Ordering::Relaxed).min(3)] +} + /// [`MERGED`], taken. pub(crate) fn merged_stats() -> [u64; 3] { [0, 1, 2].map(|i| MERGED[i].swap(0, Ordering::Relaxed)) @@ -2343,6 +2362,12 @@ impl Shadow { !self.pending.lock().unwrap_or_else(|e| e.into_inner()).is_empty() } + /// Whether one of those submissions may be writing in title memory + /// `[from, to)`. + pub(crate) fn writes_pending_in(&self, from: usize, to: usize) -> bool { + self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) + } + /// Whether [`Shadow::update`] of `[address, address + len)` would leave /// title bytes behind: a range shaders may be writing holds a page the /// title wrote since the copy last took it. The answer comes from the @@ -2418,6 +2443,7 @@ impl Shadow { return false; } if self.watched.load(Ordering::Relaxed) == NOT_WATCHED { + note_stale(0); return true; } let base = start / PAGE; @@ -2430,6 +2456,7 @@ impl Shadow { // those were all of run 99's cases: the flights were settled // 4-5 times a frame for "0 pages looked at". let Some((now, written)) = crate::watch::writes(a, e, true) else { + note_stale(1); return true; }; let stale: Vec = { @@ -2469,6 +2496,7 @@ impl Shadow { let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; let runs = changed_runs(title, held); if runs.len() > *runs_left { + note_stale(2); return true; } *runs_left -= runs.len(); @@ -2480,6 +2508,7 @@ impl Shadow { } } else { let Some(snapshot) = before.as_mut() else { + note_stale(3); return true; }; // SAFETY: the snapshot's allocation holds the copy's From e5841a05538d3794005d20a435ec06c865dca77c Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 22:17:48 -0600 Subject: [PATCH 170/445] Shader forms: lives of a spill lane, one lane of what a whole-wave section leaves Water transmission volumes and the rest of the upscaler translate. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 37 +++- crates/victory-shader/src/emit/wave.rs | 116 ++++++++++--- crates/victory-shader/src/ir.rs | 216 ++++++++++++++++++------ crates/victory-shader/src/resource.rs | 52 ++++++ 4 files changed, 344 insertions(+), 77 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index f5a547e..b4df3c2 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2762,6 +2762,18 @@ impl<'a> Lower<'a> { self.s.m.extract(entry, r, index % 4) } + /// Whether some instruction reads `v` as a number (or may, through a + /// join), rather than in a descriptor operand. + fn read_as_number(&self, v: Value) -> bool { + self.x.p.blocks.iter().any(|b| { + b.phis.iter().any(|p| p.args.contains(&v)) + || b.insts.iter().any(|i| { + matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_)) + && i.reads.iter().any(|r| r.1 == v) + }) + }) + } + /// Whether some instruction computes with `v` (scalar or vector /// arithmetic), rather than only naming it in a descriptor operand, /// moving it (at most `depth` moves are followed) or comparing it: a @@ -5983,11 +5995,23 @@ impl<'a> Lower<'a> { }; ((kind | u, 0x409), Some(kind)) } - Fields::Buffer { .. } => { + Fields::Buffer { idxen, format, .. } => { + let stride = used.map_or(0, |u| u.stride); + let counted = inst + .write(Reg::S(code + first + 2)) + .is_some_and(|v| self.read_as_number(v)); let props = if un.starts_with("buffer_load_format") || un.starts_with("buffer_store_format") { (10 | u, 0x409) + } else if !counted + && *idxen + && format.is_none() + && stride >= 4 + && stride.is_multiple_of(4) + { + // Nothing reads the count: the query is cleaned up. + (12 | u, stride) } else { // Structured ones too: the host's views of them are raw // (see `buffer`), which count bytes, and a size asked @@ -6859,6 +6883,17 @@ impl<'a> Lower<'a> { self.lane(inst, Some(true)); return Ok(()); } + // One lane of a VGPR a whole-wave section left. + if name == "v_readlane_b32" + && let Some(&(_, w)) = inst.writes.first() + && let Some(sh) = self.sections.get(&b).and_then(|s| { + s.iter().filter(|s| s.1.end < i).find_map(|s| s.1.reads.get(&w).copied()) + }) + { + let x = self.shape(sh, false)?; + self.vals.insert(w, Val::I32(x)); + return Ok(()); + } if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) { let r = if v.dpp.is_some() { Err("a compare with DPP") diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs index 1d7a91b..56f981b 100644 --- a/crates/victory-shader/src/emit/wave.rs +++ b/crates/victory-shader/src/emit/wave.rs @@ -143,6 +143,10 @@ pub(crate) enum Shape { pub(crate) struct Section { pub end: usize, pub shapes: HashMap, + /// What a `v_readlane_b32` of one lane takes, later in the block, from a + /// VGPR the section leaves (by the scalar it writes): the last lanes of + /// a reduction hold it before the first do. + pub reads: HashMap, } /// Every whole-wave section of `block`, by start index. @@ -180,8 +184,25 @@ pub(crate) fn sections(p: &Program, block: usize) -> HashMap { let Some(end) = end else { break; }; - let shapes = simulate(&insts[i + 1..end], wave, saved); - out.insert(i, Section { end, shapes }); + let (vec, uni) = simulate(&insts[i + 1..end], wave, saved); + let mut reads = HashMap::new(); + for later in insts[end + 1..].iter().filter(|i| i.name() == "v_readlane_b32") { + if let Fields::Valu(v) = &later.fields + && let (Some(Operand::Scalar { code, .. }), [Operand::Vector { reg, .. }, lane]) = + (v.dst, &v.src[..]) + && let Some(left) = later.read(Reg::V(*reg)).and_then(|x| vec.get(&x)) + && let Some(w) = later.write(Reg::S(code)) + && let Some(l) = lane_number(lane) + && let Some(&sym) = left.get(l as usize) + // (a lane's own value stays a lane read) + && !matches!(sym, Sym::Own(_)) + && let Some(shape) = single(sym, wave) + { + reads.insert(w, shape); + } + } + let shapes = shapes(vec, uni, wave); + out.insert(i, Section { end, shapes, reads }); i = end + 1; } out @@ -268,7 +289,19 @@ fn combine(op: Op, a: Sym, b: Sym) -> Sym { } } -fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { +/// The lane a `v_readlane_b32` names. +fn lane_number(op: &Operand) -> Option { + match *op { + Operand::Const(c) => crate::resource::inline(c), + Operand::Literal(x) => Some(x), + _ => None, + } +} + +/// The lanes' values of the VGPRs the section writes, and its scalars. +type Left = (HashMap>, HashMap); + +fn simulate(insts: &[Inst], wave: u32, saved: Value) -> Left { let all = if wave == 64 { u64::MAX } else { @@ -289,7 +322,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { .then(|| constant(inst)) .flatten(); let Some(k) = lo else { - return shapes(vec, uni, wave); + return (vec, uni); }; exec = (if name == "s_mov_b64" { k @@ -304,7 +337,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { .then(|| constant(inst)) .flatten() else { - return shapes(vec, uni, wave); + return (vec, uni); }; exec = ((exec & 0xFFFF_FFFF) | ((k & 0xFFFF_FFFF) << 32)) & all; continue; @@ -371,11 +404,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { else { continue; }; - let l = match *lane { - Operand::Const(c) => crate::resource::inline(c), - Operand::Literal(x) => Some(x), - _ => None, - }; + let l = lane_number(lane); let x = lanes(src, &vec, &uni); if let Some(w) = inst.write(Reg::S(code)) { let s = l @@ -664,7 +693,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { .collect(); vec.insert(dst, merged); } - shapes(vec, uni, wave) + (vec, uni) } fn constant(inst: &Inst) -> Option { @@ -688,19 +717,10 @@ fn constant(inst: &Inst) -> Option { } } -/// The shape of each value, where every lane agrees on one. -fn shapes( - vec: HashMap>, - uni: HashMap, - wave: u32, -) -> HashMap { - let all = if wave == 64 { - u64::MAX - } else { - u64::from(u32::MAX) - }; - let mut out = HashMap::new(); - let single = |s: Sym| match s { +/// The shape of a scalar. +fn single(s: Sym, wave: u32) -> Option { + let all = u64::MAX >> (64 - wave); + match s { Sym::K(k) => Some(Shape::K(k)), Sym::Own(x) | Sym::Uni(x) => Some(Shape::Value(x)), Sym::Red { @@ -718,9 +738,19 @@ fn shapes( high, } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), _ => None, - }; + } +} + +/// The shape of each value, where every lane agrees on one. +fn shapes( + vec: HashMap>, + uni: HashMap, + wave: u32, +) -> HashMap { + let all = u64::MAX >> (64 - wave); + let mut out = HashMap::new(); for (v, s) in uni { - if let Some(sh) = single(s) { + if let Some(sh) = single(s, wave) { out.insert(v, sh); } } @@ -1074,6 +1104,40 @@ mod tests { } } + /// A wave OR whose last step stays in the section's VGPR: the lower + /// lanes add the first half's to themselves, so only the upper ones + /// hold the whole, and the last lane is read after the section (an + /// upscaler's programs). + #[test] + fn one_lane_of_what_a_section_leaves_is_read_after_it() { + let words = |lane: u32| { + let mut w = WAVE_OR_V7_TO_S7[..14].to_vec(); // .. v_or_b32 v1, v2, v1 + w.extend([ + 0xD760_0007, + 0x0001_0101, // v_readlane_b32 s7, v1, 0 + 0x3802_0207, // v_or_b32 v1, s7, v1 + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] + 0xD760_0006, + 0x0001_0101 | lane << 9, // v_readlane_b32 s6, v1, lane + S_ENDPGM, + ]); + w + }; + let read = |lane: u32| { + let p = build(&words(lane), true); + let insts = &p.blocks[0].insts; + let saved = insts[0].write(Reg::S(4)).unwrap(); + let v7 = p.inputs.iter().find_map(|&(r, v)| (r == Reg::V(7)).then_some(v)).unwrap(); + let got = insts[insts.len() - 2].write(Reg::S(6)).unwrap(); + let sec = §ions(&p, 0)[&0]; + (sec.reads.get(&got).copied(), Shape::Active(Op::Or, v7, saved, 0)) + }; + let (found, whole) = read(63); + assert_eq!(found, Some(whole)); + // Lane 0 has the first half's alone: still a lane read. + assert_eq!(read(0).0, None); + } + /// `WaveActiveSum` of 16-bit floats, as compiled in /// `compute_graph_ops:CS_TransposeVecMatMulAlignedOperation` (0x19c on): the tree the /// lowering reproduces. A tree in another order is not followed. diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 5b659e3..577fbc1 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -15,6 +15,8 @@ //! operand's whole possible range: from the encoded register up to the //! program's VGPR count, all read (and all written, for a destination). +use std::collections::{HashMap, HashSet}; + use crate::ShaderError; use crate::gfx10::{self, Fields, Flow, Instruction, Operand}; @@ -149,7 +151,7 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result Result = parks.iter().flatten().map(|p| (p.1, p.3)).collect(); - slots.sort_unstable(); - slots.dedup(); // instruction -> the instruction that completes its pair let partner = |i: usize| -> Option { let (save, reg, code, lane) = parks[i]?; @@ -405,52 +410,163 @@ fn unspill( None } }; - let mut pairs: Vec<(u8, u32)> = Vec::new(); - for &(reg, lane) in &slots { - if !wave64 || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) || !slots.contains(&(reg, lane + 1)) { - continue; + // The store each parking instruction uses, and what the stores are lanes + // of: one per (VGPR, lane), or (`split`) one per life of it. + let stores_of = |split: bool| -> (Vec, Vec<(u8, u32)>) { + let slot = |i: usize| parks[i].map(|p| (p.1, p.3)); + // Instructions of one store, by the first of them. + let mut first: Vec = (0..list.len()).collect(); + if split { + fn root(first: &mut [usize], mut i: usize) -> usize { + while first[i] != i { + first[i] = first[first[i]]; + i = first[i]; + } + i + } + let at = |offset: usize| list.partition_point(|i| i.offset < offset); + for save in (0..list.len()).filter(|&i| parks[i].is_some_and(|p| p.0)) { + let mut seen = HashSet::new(); + let mut work = vec![save + 1]; + while let Some(from) = work.pop() { + for i in from..list.len() { + if slot(i).is_some() && slot(i) == slot(save) { + if parks[i].is_some_and(|p| p.0) { + break; + } + let (a, b) = (root(&mut first, save), root(&mut first, i)); + first[a.max(b)] = a.min(b); + } + let mut go = |to: usize| { + if seen.insert(to) { + work.push(to); + } + }; + match flows[i] { + Flow::Next if i + 1 < list.len() && leader(i + 1) => go(i + 1), + Flow::Next => continue, + Flow::Stop => {} + Flow::Jump(t) => go(at(t)), + Flow::Branch(t) => { + go(at(t)); + go(i + 1); + } + } + break; + } + } + } + for i in 0..list.len() { + first[i] = root(&mut first, i); + } + } else { + let mut of: HashMap<(u8, u32), usize> = HashMap::new(); + for i in 0..list.len() { + if let Some(s) = slot(i) { + first[i] = *of.entry(s).or_insert(i); + } + } } - let lower: Vec = (0..list.len()).filter(|&i| parks[i].is_some_and(|p| (p.1, p.3) == (reg, lane))).collect(); - let upper = parks.iter().flatten().filter(|p| (p.1, p.3) == (reg, lane + 1)).count(); - let partners: Vec> = lower.iter().map(|&i| partner(i)).collect(); - let mut distinct: Vec = partners.iter().flatten().copied().collect(); - distinct.sort_unstable(); - distinct.dedup(); - if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() { - pairs.push((reg, lane)); + let mut stores: Vec<((u8, u32), usize)> = (0..list.len()) + .filter(|&i| first[i] == i) + .filter_map(|i| Some((slot(i)?, i))) + .collect(); + stores.sort_unstable(); + let number = |i: usize| stores.iter().position(|s| s.1 == first[i]); + let of = (0..list.len()) + .map(|i| parks[i].and_then(|_| number(i)).unwrap_or(usize::MAX)) + .collect(); + (of, stores.into_iter().map(|s| s.0).collect()) + }; + // The stores that move as pairs (lower, upper) and every store's code; + // none if the spare codes do not suffice. + let plan = |split: bool| -> Option<(Vec, Vec<(usize, usize)>, Vec)> { + let (mut of, stores) = stores_of(split); + let mut pairs: Vec<(usize, usize)> = Vec::new(); + for (n, &(reg, lane)) in stores.iter().enumerate() { + if !wave64 || pairs.iter().any(|&(_, upper)| upper == n) { + continue; + } + let lower: Vec = (0..list.len()).filter(|&i| of[i] == n).collect(); + let partners: Vec> = lower.iter().map(|&i| partner(i)).collect(); + let mut distinct: Vec = partners.iter().flatten().copied().collect(); + distinct.sort_unstable(); + distinct.dedup(); + let Some(upper) = distinct.first().map(|&j| of[j]) else { + continue; + }; + if stores[upper] == (reg, lane + 1) + && partners.iter().all(Option::is_some) + && distinct.len() == lower.len() + && distinct.iter().all(|&j| of[j] == upper) + && of.iter().filter(|&&o| o == upper).count() == lower.len() + { + pairs.push((n, upper)); + } } - } - // Codes for the parked scalars: the trap temporaries (108..=123), then - // user SGPRs the program never names, from the top, then the codes past - // the machine's (`PARKED`..=254; 255 stays unused so that the code after a - // parked one always exists). A material resolve program parks up to 63 - // scalars and leaves about 20 machine codes unused. - let past = usize::from(PARKED); - let mut free = [false; 256]; - for c in (0..105).chain(108..=123) { - free[c] = !used[c]; - } - free[past..255].fill(true); - let mut codes: Vec<((u8, u32), u8)> = Vec::new(); - for &(reg, lane) in &pairs { - let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]); - // Not enough spare codes: leave the program as it is. - let Some(c) = at else { return Vec::new() }; - (free[c], free[c + 1]) = (false, false); - codes.push(((reg, lane), c as u8)); - codes.push(((reg, lane + 1), c as u8 + 1)); - } - for &slot in &slots { - if codes.iter().any(|c| c.0 == slot) { - continue; - } - let Some(c) = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c]) else { - return Vec::new(); + // Lives of one lane that move alike share a code, as they share the lane. + let role = |n: usize| { + let (lower, upper) = (pairs.iter().any(|p| p.0 == n), pairs.iter().any(|p| p.1 == n)); + (stores[n], u8::from(lower) + 2 * u8::from(upper)) }; - free[c] = false; - codes.push((slot, c as u8)); + let mut shared: Vec<_> = (0..stores.len()).map(role).collect(); + let place: Vec = { + let all = shared.clone(); + shared.sort_unstable(); + shared.dedup(); + all.iter().filter_map(|r| shared.binary_search(r).ok()).collect() + }; + for o in of.iter_mut().filter(|o| **o != usize::MAX) { + *o = place[*o]; + } + for p in &mut pairs { + *p = (place[p.0], place[p.1]); + } + pairs.sort_unstable(); + pairs.dedup(); + // Codes for the parked scalars: the trap temporaries (108..=123), then + // user SGPRs the program never names, from the top, then the codes past + // the machine's (`PARKED`..=254; 255 stays unused so that the code after a + // parked one always exists). A material resolve program parks up to 63 + // scalars and leaves about 20 machine codes unused. + let past = usize::from(PARKED); + let mut free = [false; 256]; + for c in (0..105).chain(108..=123) { + free[c] = !used[c]; + } + free[past..255].fill(true); + let mut codes: Vec> = vec![None; shared.len()]; + for &(lower, upper) in &pairs { + let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]); + // Not enough spare codes: leave the program as it is. + let c = at?; + (free[c], free[c + 1]) = (false, false); + codes[lower] = Some(c as u8); + codes[upper] = Some(c as u8 + 1); + } + for code in codes.iter_mut().filter(|c| c.is_none()) { + let c = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c])?; + free[c] = false; + *code = Some(c as u8); + } + Some((of, pairs, codes.into_iter().flatten().collect())) + }; + let Some(mut chosen) = plan(false) else { return Vec::new() }; + let lonely = |(of, pairs, _): &(Vec, Vec<(usize, usize)>, Vec)| { + (0..list.len()).any(|i| { + parks[i].is_some_and(|p| p.0) + && partner(i).is_some() + && !pairs.iter().any(|&(lower, upper)| of[i] == lower || of[i] == upper) + }) + }; + if wave64 + && lonely(&chosen) + && let Some(split) = plan(true) + && split.1.len() > chosen.1.len() + { + chosen = split; } - let code_of = |reg: u8, lane: u32| codes.iter().find(|c| c.0 == (reg, lane)).map(|c| c.1); + let (store, pairs, codes) = chosen; let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| { list[i] = gfx10::Instruction { offset: list[i].offset, @@ -466,11 +582,11 @@ fn unspill( const NOP: u32 = 0xBF80_0000; let mut edits: Vec<(usize, Option<(bool, u8, u8)>)> = Vec::new(); for i in 0..list.len() { - let Some((save, reg, code, lane)) = parks[i] else { + let Some((save, _, code, _)) = parks[i] else { continue; }; - let Some(slot) = code_of(reg, lane) else { return Vec::new() }; - if pairs.contains(&(reg, lane)) { + let slot = codes[store[i]]; + if pairs.iter().any(|p| p.0 == store[i]) { let Some(j) = partner(i) else { return Vec::new() }; // A save moves the pair where its second half is saved; a // restore where its first half is restored. @@ -478,7 +594,7 @@ fn unspill( let (dst, src) = if save { (slot, code) } else { (code, slot) }; edits.push((at, Some((true, dst, src)))); edits.push((gone, None)); - } else if lane > 0 && pairs.contains(&(reg, lane - 1)) { + } else if pairs.iter().any(|p| p.1 == store[i]) { // the upper half of a pair: moved with the lower } else { let (dst, src) = if save { (slot, code) } else { (code, slot) }; diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 6ef558c..835c067 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -2647,6 +2647,58 @@ pub(crate) mod tests { } } + /// Two lanes hold a pair (a lane mask, say) and later one of them a + /// scalar, as in a water volume program that parks more than the lanes + /// of one VGPR hold: the pair still moves as one. + #[test] + fn a_lane_spilled_to_again_later_does_not_split_an_earlier_pair() { + let pair = [ + 0xD761_0000u32, + 0x0001_0004, // v_writelane_b32 v0, s4, 0 + 0xD761_0000, + 0x0001_0205, // v_writelane_b32 v0, s5, 1 + 0xBE84_0380, // s_mov_b32 s4, 0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xD760_0004, + 0x0001_0100, // v_readlane_b32 s4, v0, 0 + 0xD760_0005, + 0x0001_0300, // v_readlane_b32 s5, v0, 1 + ]; + let scalar = [ + 0xD761_0000u32, + 0x0001_0006, // v_writelane_b32 v0, s6, 0 + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xD760_0006, + 0x0001_0100, // v_readlane_b32 s6, v0, 0 + S_ENDPGM, + ]; + let moves = |words: &[u32]| { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, true, 8).unwrap(); + let names: Vec<_> = p.blocks[0].insts.iter().map(|i| i.name()).collect(); + assert!(!names.iter().any(|n| n.contains("lane"))); + names.iter().filter(|n| **n == "s_mov_b64").count() + }; + assert_eq!(moves(&[&pair[..], &scalar].concat()), 2); + // A restore both saves reach keeps the lane one scalar. + let joined = [ + &pair[..4], + &[0xBF84_0002], // s_cbranch_scc0 past the second save + &scalar[..2], + &pair[4..], + &scalar[2..], + ] + .concat(); + assert_eq!(moves_anywhere(&joined), 0); + } + + fn moves_anywhere(words: &[u32]) -> usize { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, true, 8).unwrap(); + let insts = p.blocks.iter().flat_map(|b| &b.insts); + insts.filter(|i| i.name() == "s_mov_b64").count() + } + #[test] fn descriptors_joined_by_control_flow_are_traced_per_edge() { let r = track_words( From 017fb0b383f6b82de79e1f3506013e8e2f0255cf Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 22:17:50 -0600 Subject: [PATCH 171/445] What goes up to card copies: a check, and fetches caught in between put right VICTORY_FETCH_CHECK=1 (off by default): with VICTORY_RELAY_COPY a piece is fetched beside later submissions, and one of those that clears it and fills it again with the same is not flagged by its compare: title memory and the CPU's side kept what was in between, and the next refresh of the 64 KiB sent it up over the right bytes. The compare now gives the piece's hash with its flag; a fetch that is not that is made again by the next flight that may write the piece. (The test shows 11-12 of 12 wrong without it.) VICTORY_UPCOPY_CHECK=1 (diagnostics): at each send up, the words that the title did not change and the card holds another value of; every few seconds at rest, the words in which a copy's card side is not its CPU side, and whether they were declared as written and fetched. victory replay --upcopies: the same question of a captured frame, and which pieces were written undeclared (replay1 and replay2: compute 82a2ad6d07417d36 through views picked by index, 73-75 pieces a frame). Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 9 + crates/victory-gpu/src/host.rs | 118 ++- crates/victory-gpu/src/host/torn.rs | 342 ++++++++ crates/victory-gpu/src/host/upcheck.rs | 821 ++++++++++++++++++ crates/victory-gpu/src/indirect.rs | 12 +- crates/victory-gpu/src/replay/play.rs | 1 + crates/victory-gpu/src/replay/play/diverge.rs | 16 +- .../victory-gpu/src/replay/play/upcopies.rs | 342 ++++++++ crates/victory-gpu/src/shadow.rs | 80 +- docs/replay.md | 1 + 10 files changed, 1688 insertions(+), 54 deletions(-) create mode 100644 crates/victory-gpu/src/host/torn.rs create mode 100644 crates/victory-gpu/src/host/upcheck.rs create mode 100644 crates/victory-gpu/src/replay/play/upcopies.rs diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index f73ea08..bfa5243 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -111,6 +111,11 @@ pub(crate) struct Replay { /// Name resources the frame changes that the replay does not put back. #[arg(long)] check_written: bool, + /// Run the frame twice and say which words the copies of the CPU's sides + /// of card buffers bring that the card holds another value of, and what + /// shaders wrote that was not declared as written. + #[arg(long)] + upcopies: bool, /// Name what the heap slots hold that a command's constants name: /// `:`. #[arg(long)] @@ -182,6 +187,10 @@ pub(crate) fn run(r: Replay) -> Result<()> { let mut player = play::Player::load(&r.folder, &options)?; return player.check_written(&mut |line| println!("{line}")); } + if r.upcopies { + let mut player = play::Player::load(&r.folder, &options)?; + return player.upcopies(&options, &mut |line| println!("{line}")); + } let mut watched = Vec::new(); for text in &r.watch { let mut n = text diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 8e3572a..185cfb4 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1508,7 +1508,7 @@ struct CardWork { fetch: Prelude, root: ID3D12RootSignature, pso: ID3D12PipelineState, - /// One dword per piece compared, set where the piece differs: PC + /// One dword per piece compared, odd where the piece differs: PC /// memory, mapped (buffer, mapping, bytes). differs: (ID3D12Resource, usize, u64), /// Where the pieces that differ are fetched to: PC memory, mapped. @@ -1529,7 +1529,7 @@ static CARD_WORK: Mutex> = Mutex::new(None); /// The compare of a declared range of a copy in the card's memory with /// its bytes from before, one group per 64 KiB piece (cut at multiples of /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs` -/// gets a dword per piece, 1 where a byte differs. The offsets are widened +/// gets a dword per piece, odd where a byte differs. The offsets are widened /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a /// byte just outside the range costs a fetch that finds nothing. /// @@ -1579,7 +1579,9 @@ void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) { h = h.yzwx ^ (h >> 15); } if (compare != 0u) { - differs.Store(out_at + id.x * 4u, any(h != hashes.Load4(piece * 16u)) ? 1u : 0u); + // The flag, and above it 31 bits of the hash (`torn`). + uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u); + differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u)); // With the copy-back on its own thread: the next compare of the // piece finds what is written from here on. if (compare == 2u) hashes.Store4(piece * 16u, h); @@ -1589,6 +1591,12 @@ void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) { } "#; +/// The hash [`CARD_COMPARE`] gives of a piece with its flag. +#[cfg(test)] +pub(crate) fn piece_hash(bytes: &[u8]) -> u32 { + torn::hash(bytes) +} + /// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from /// dword `at` on (`mode` as the shader's `compare`): a group per piece, in /// parts a dispatch can hold. @@ -1670,6 +1678,8 @@ struct CardPlan { /// With [`relay`]: the number of the send to copies in the card's memory /// that the submission ran behind ([`QUEUE_ORDER`]). sent_as: u64, + /// With [`upcheck`]: the look at what it sent up. + looks: Option, } /// One piece of submission-time work, in recorded order. @@ -2660,6 +2670,8 @@ struct RelayFetch { sent: u64, /// Buffer, mapping, bytes. buffer: Option<(ID3D12Resource, usize, u64)>, + /// Pieces caught while a later flight was writing them. + suspects: torn::Suspects, } /// The thread that lands flights ([`relay`]): as soon as the card has run @@ -2840,6 +2852,15 @@ fn late_line(frames: f64) { r[3] / 1000.0, r[4] / 1000.0, ); + let t: Vec = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if t[0] > 0.0 { + tracing::info!( + "fetched pieces checked per frame (VICTORY_FETCH_CHECK): {:.1}, of which {:.2} were not what their flight ended with (caught while a later flight was at them, or title bytes went up meanwhile); {:.2} were found whole when fetched again", + t[0], + t[1], + t[2], + ); + } } card_steps::log(frames); #[cfg(feature = "diagnostics")] @@ -2855,6 +2876,8 @@ fn late_line(frames: f64) { } mod card_steps; +mod torn; +pub(crate) mod upcheck; #[cfg(test)] mod late_tests { @@ -3412,6 +3435,7 @@ impl Host { } } let mut used: Vec<(bool, Prelude)> = Vec::new(); + let mut looks = None; if !dirty.is_empty() { let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else { fail(format_args!("no host list to bring host copies in the card's memory up to date")); @@ -3424,6 +3448,9 @@ impl Host { (|| -> windows::core::Result<()> { allocator.Reset()?; list.Reset(allocator, None)?; + if upcheck::on() { + looks = upcheck::record(self, list, &dirty); + } // Every copy first, then one barrier call, then every // pass: a wait between each copy and its pass had the // card do them one after the other. @@ -3493,6 +3520,7 @@ impl Host { _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(), lists: used, sent_as, + looks, }; // Each byte once, as the copy-back joins the declared ranges. The // results go behind those of plans still in the air. @@ -3590,6 +3618,9 @@ impl Host { /// when nothing of ours is on the card, so the compare's results start /// from the beginning again. fn card_done(&self, plan: CardPlan) { + if let Some(looks) = plan.looks { + looks.read(); + } let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); let Some(work) = work.as_mut() else { return; @@ -3641,6 +3672,7 @@ impl Host { event, sent: 0, buffer: None, + suspects: torn::Suspects::default(), }) } } @@ -3660,45 +3692,24 @@ impl Host { let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize)) }; - let mut pieces: Vec<(std::sync::Arc, usize, usize, u64)> = Vec::new(); - let mut total = 0u64; + if fetch.is_none() { + *fetch = self.make_relay_fetch(); + } + // On the copy queue a later flight may be at a piece while it is + // fetched (`torn`). + let mut suspects = fetch.as_mut().filter(|f| f.queue.is_some() && torn::on()).map(|f| std::mem::take(&mut f.suspects)); + let mut pieces = Vec::new(); if let Some((differs, dwords)) = differs { // SAFETY: the mapping of the results. The compares of these // plans have run, and their dwords are given to no other plan // before these are done with (`card_done`). let differs = unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) }; - let mut seen = std::collections::HashSet::new(); - for plan in plans { - let flags: Vec<(usize, u32, bool)> = plan - .ranges - .iter() - .flat_map(|r| { - (0..r.span.pieces).map(move |p| { - let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| d != 0); - (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, flagged) - }) - }) - .collect(); - let fetched = flagged_pieces(&flags); - for r in &plan.ranges { - let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; - for p in 0..r.span.pieces { - if !fetched.contains(&(copy, r.span.first + p)) { - continue; - } - let (lo, hi) = r.shadow.card_piece(&r.span, p); - if lo < hi && seen.insert((copy, lo, hi)) { - pieces.push((r.shadow.clone(), lo, hi, total)); - total += (hi - lo) as u64; - } - } - crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); - } + pieces = torn::fetches(plans, differs, suspects.as_ref()); + for r in plans.iter().flat_map(|plan| &plan.ranges) { + crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); } } - if fetch.is_none() { - *fetch = self.make_relay_fetch(); - } + let total = pieces.last().map_or(0, |p| p.at + (p.to - p.from) as u64); // 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.sent_as).max().unwrap_or(0); @@ -3710,6 +3721,9 @@ impl Host { false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()), }; crate::shadow::relay_fetched(after); + if let (Some(f), Some(suspects)) = (fetch.as_mut(), suspects) { + f.suspects = suspects; + } return; } let Some(f) = fetch.as_mut() else { @@ -3733,8 +3747,8 @@ impl Host { (|| -> windows::core::Result { allocator.Reset()?; list.Reset(&allocator, None)?; - for (shadow, lo, hi, at) in &pieces { - list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64); + for p in &pieces { + list.CopyBufferRegion(&buffer, p.at, &p.shadow.buffer, p.from as u64, (p.to - p.from) as u64); } list.Close()?; let lists = [Some(list.cast::()?)]; @@ -3773,13 +3787,22 @@ impl Host { } let mut title = Vec::new(); let mut written = 0; - for (shadow, lo, hi, at) in &pieces { + for p in &pieces { // SAFETY: the mapping of the fetched bytes, `total` of them; // the copy into it has run. - let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) }; - let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title); - shadow.walls_merged(gpu.len(), merged); - written += merged; + let gpu = unsafe { std::slice::from_raw_parts((data + p.at as usize) as *const u8, p.to - p.from) }; + if let (Some((piece, Some(hash))), Some(suspects)) = (p.check, &mut suspects) { + suspects.fetched((p.shadow.id(), piece), torn::hash(gpu) == hash); + } + for &(lo, hi) in &p.merged { + let gpu = &gpu[lo - p.from..hi - p.from]; + let merged = p.shadow.card_merge_relay(lo, gpu, after, &mut title); + p.shadow.walls_merged(gpu.len(), merged); + written += merged; + } + } + if let (Some(f), Some(suspects)) = (fetch.as_mut(), suspects) { + f.suspects = suspects; } COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); // Sends up to `after` are of no use to any later merge. @@ -3939,7 +3962,7 @@ impl Host { let mut total = 0u64; for (i, r) in plan.ranges.iter().enumerate() { for p in 0..r.span.pieces { - if r.compared && differs[(r.at + p) as usize] == 0 { + if r.compared && !torn::flagged(differs[(r.at + p) as usize]) { continue; } let (lo, hi) = r.shadow.card_piece(&r.span, p); @@ -4345,12 +4368,18 @@ impl Host { // one at every present). static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); if !behind { + if upcheck::on() { + upcheck::at_rest(self); + } sweep(); SWEPT.store(now_ms(), Ordering::Relaxed); } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 { // With the present sent ahead nothing else brings a moment // with nothing in the air: one is made for the sweep. self.settle(&mut submitted, WHY_SYNC); + if upcheck::on() { + upcheck::at_rest(self); + } sweep(); SWEPT.store(now_ms(), Ordering::Relaxed); } @@ -4396,6 +4425,9 @@ impl Host { // may write too, and this submission refreshes it. The flights // are settled, and the asking made again: the copy-back wrote // title memory, which other copies of it must see. + if behind && upcheck::on() { + upcheck::reads(runs); + } if behind && stale_under_flights(runs) { let settling = std::time::Instant::now(); self.settle(&mut submitted, WHY_STALE); diff --git a/crates/victory-gpu/src/host/torn.rs b/crates/victory-gpu/src/host/torn.rs new file mode 100644 index 0000000..3ff46d6 --- /dev/null +++ b/crates/victory-gpu/src/host/torn.rs @@ -0,0 +1,342 @@ +//! Pieces of card copies that came down while a later flight was writing +//! them (`VICTORY_FETCH_CHECK`, with `VICTORY_RELAY_COPY`). +//! +//! On the copy queue a fetch runs beside later submissions (`relay_copy`), +//! so what comes down of a piece may be what it held in the middle of one: +//! a counter cleared and not counted up again, a list half filled. Such +//! bytes went into title memory and the copy's CPU side, to be put right by +//! that submission's own landing, which fetches what its compare flagged. +//! But the compare flags a piece only if it is not, at the submission's end, +//! what it was at the end of the one before. A piece cleared and filled +//! again with the same is not flagged, is not fetched, and the CPU's side +//! keeps the bytes from in between: until they go up with a refresh of +//! their 64 KiB, over the right ones. +//! +//! So the compare gives each piece's hash with its flag, and what came down +//! is hashed here too. The same hash: it is what the flight ended with. Not +//! the same: the piece is suspect (another flight was at it, or the title's +//! bytes went up to it meanwhile), and the next flight that may write it +//! fetches it whatever its compare says, until a fetch is found whole. +//! +//! What it costs: pieces are fetched whole where a flight declared a part +//! of one, and 64 KiB of what came down are hashed (some 4 us) just before +//! they are merged, which reads them again. + +use std::collections::{HashMap, HashSet}; + +use super::*; + +/// `VICTORY_FETCH_CHECK=1`; off by default until a run has shown how often a +/// piece is caught (the frame-rate line says so) and what the hashes cost +/// (3-4 ms of the landing thread's time for 96 MB, beside the merge). +pub(super) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_FETCH_CHECK").is_some_and(|v| v == "1")) +} + +/// A piece: its copy's number, and the piece. +pub(super) type Piece = (u64, u32); + +/// Since the last frame-rate line: pieces fetched and hashed, those found +/// suspect, and those fetched because an earlier fetch was. +pub(super) static STATS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// The pieces whose last fetch was not what a flight ended with. +#[derive(Default)] +pub(super) struct Suspects(HashSet); + +impl Suspects { + /// Whether a flight that may write `piece` fetches it, its compare + /// having flagged it or not. + pub(super) fn wanted(&self, piece: Piece, flagged: bool) -> bool { + flagged || self.0.contains(&piece) + } + + /// `piece` was fetched; `same`: it was what the last of the flights + /// landed ended with. + pub(super) fn fetched(&mut self, piece: Piece, same: bool) { + STATS[0].fetch_add(1, Ordering::Relaxed); + if same { + if self.0.remove(&piece) { + STATS[2].fetch_add(1, Ordering::Relaxed); + } + } else { + self.0.insert(piece); + STATS[1].fetch_add(1, Ordering::Relaxed); + } + } +} + +/// A piece to fetch. +pub(super) struct Fetch { + pub(super) shadow: std::sync::Arc, + /// The offsets fetched, and where they come down. + pub(super) from: usize, + pub(super) to: usize, + pub(super) at: u64, + /// The offsets merged: what flights declared of it. + pub(super) merged: Vec<(usize, usize)>, + /// With the check: the piece, and the hash the last flight that may + /// have written it ended with. + pub(super) check: Option<(u32, Option)>, +} + +/// What is fetched for `plans`, whose compares' results are in `differs`. +/// With `suspects`, pieces are fetched whole, with the hash to compare. +pub(super) fn fetches(plans: &[&CardPlan], differs: &[u32], suspects: Option<&Suspects>) -> Vec { + let mut out: Vec = Vec::new(); + let mut total = 0u64; + let mut seen = HashSet::new(); + // With `suspects`: where each piece is in `out`. + let mut index: HashMap = HashMap::new(); + for plan in plans { + let flags: Vec<(usize, u32, bool)> = plan + .ranges + .iter() + .flat_map(|r| { + (0..r.span.pieces).map(move |p| { + let piece = r.span.first + p; + let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| flagged(d)); + let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), piece), flagged)); + (std::sync::Arc::as_ptr(&r.shadow) as usize, piece, wanted) + }) + }) + .collect(); + let fetched = flagged_pieces(&flags); + for r in &plan.ranges { + let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; + if upcheck::on() { + upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize); + } + for p in 0..r.span.pieces { + let piece = r.span.first + p; + if !fetched.contains(&(copy, piece)) { + continue; + } + let (lo, hi) = r.shadow.card_piece(&r.span, p); + if lo >= hi || !seen.insert((copy, lo, hi)) { + continue; + } + if upcheck::on() { + upcheck::fetched(r.shadow.id(), lo); + } + if suspects.is_none() { + out.push(Fetch { + shadow: r.shadow.clone(), + from: lo, + to: hi, + at: total, + merged: vec![(lo, hi)], + check: None, + }); + total += (hi - lo) as u64; + continue; + } + let i = *index.entry((r.shadow.id(), piece)).or_insert_with(|| { + let (from, to) = r.shadow.card_hashed(piece); + out.push(Fetch { + shadow: r.shadow.clone(), + from, + to, + at: total, + merged: Vec::new(), + check: Some((piece, None)), + }); + total += (to - from) as u64; + out.len() - 1 + }); + out[i].merged.push((lo, hi)); + } + } + } + if suspects.is_some() { + // The hash of the last flight that may have written the piece. + for plan in plans { + for r in plan.ranges.iter().filter(|r| r.compared) { + for p in 0..r.span.pieces { + if let Some(&i) = index.get(&(r.shadow.id(), r.span.first + p)) + && let Some(&d) = differs.get((r.at + p) as usize) + && let Some((_, hash)) = &mut out[i].check + { + *hash = Some(folded(d)); + } + } + } + } + } + out +} + +/// Of a result of the compare: whether the piece differs. +pub(super) fn flagged(result: u32) -> bool { + result & 1 != 0 +} + +/// Of a result of the compare: the piece's hash, 31 bits of it. +pub(super) fn folded(result: u32) -> u32 { + result >> 1 +} + +/// The hash the compare on the card ([`CARD_COMPARE`]) makes of a piece +/// that holds `bytes` (a multiple of 16 of them), as [`folded`]. +pub(super) fn hash(bytes: &[u8]) -> u32 { + #[cfg(target_arch = "x86_64")] + if std::is_x86_feature_detected!("avx2") { + // SAFETY: the feature is there. + return unsafe { hash_avx2(bytes) }; + } + hash_plain(bytes) +} + +const MUL: [u32; 4] = [0x0100_0193, 0x9E37_79B1, 0x85EB_CA77, 0xC2B2_AE3D]; +const SEED: [u32; 4] = [0x9E37_79B9, 0x85EB_CA6B, 0xC2B2_AE35, 0x27D4_EB2F]; + +fn step(h: &mut [u32; 4], with: [u32; 4]) { + let x: [u32; 4] = std::array::from_fn(|i| (h[i] ^ with[i]).wrapping_mul(MUL[i])); + *h = std::array::from_fn(|i| x[(i + 1) % 4] ^ (x[i] >> 15)); +} + +/// The 64 threads' hashes as one, folded to 31 bits. +fn finish(parts: &[[u32; 4]; 64]) -> u32 { + let mut h = parts[0]; + for part in &parts[1..] { + step(&mut h, *part); + } + let f = h[0] ^ h[1].wrapping_mul(3) ^ h[2].wrapping_mul(5) ^ h[3].wrapping_mul(7); + f & 0x7FFF_FFFF +} + +fn seeds() -> [[u32; 4]; 64] { + std::array::from_fn(|thread| SEED.map(|s| s.wrapping_add(thread as u32))) +} + +fn tail(parts: &mut [[u32; 4]; 64], bytes: &[u8]) { + for (thread, chunk) in bytes.chunks_exact(16).enumerate() { + let with = std::array::from_fn(|i| u32::from_le_bytes([chunk[i * 4], chunk[i * 4 + 1], chunk[i * 4 + 2], chunk[i * 4 + 3]])); + step(&mut parts[thread], with); + } +} + +fn hash_plain(bytes: &[u8]) -> u32 { + let mut parts = seeds(); + for row in bytes.chunks(1024) { + tail(&mut parts, row); + } + finish(&parts) +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +fn hash_avx2(bytes: &[u8]) -> u32 { + use std::arch::x86_64::*; + let mut parts = seeds(); + let rows = bytes.chunks_exact(1024); + let rest = rows.remainder(); + let mul = _mm256_setr_epi32( + MUL[0] as i32, MUL[1] as i32, MUL[2] as i32, MUL[3] as i32, MUL[0] as i32, MUL[1] as i32, MUL[2] as i32, MUL[3] as i32, + ); + let state = parts.as_mut_ptr().cast::<__m256i>(); + for row in rows { + let from = row.as_ptr().cast::<__m256i>(); + for k in 0..32 { + // SAFETY: two threads' hashes of 16 bytes each, and their 32 of + // the row's 1,024 bytes. + unsafe { + let h = _mm256_xor_si256(_mm256_loadu_si256(state.add(k)), _mm256_loadu_si256(from.add(k))); + let x = _mm256_mullo_epi32(h, mul); + // y, z, w, x of each. + let turned = _mm256_shuffle_epi32::<0b00_11_10_01>(x); + _mm256_storeu_si256(state.add(k), _mm256_xor_si256(turned, _mm256_srli_epi32::<15>(x))); + } + } + } + tail(&mut parts, rest); + finish(&parts) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_wide_hash_is_the_plain_one() { + let bytes: Vec = (0..65_536u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect(); + for n in [0usize, 16, 32, 1008, 1024, 1040, 5000 & !15, 65_536] { + assert_eq!(hash(&bytes[..n]), hash_plain(&bytes[..n]), "{n} bytes"); + } + let mut other = bytes.clone(); + other[40_000] ^= 1; + assert_ne!(hash(&bytes), hash(&other)); + } + + /// A model of one piece. The card runs flights in order; each writes the + /// piece several times and its compare flags it if it ends otherwise + /// than the flight before. Each landing fetches what is wanted, on a + /// queue beside the drawing one: the fetch sees the piece as it is while + /// a later flight is at some step. Returns what the CPU's side holds in + /// the end, and the fetches. + fn landed(flights: &[&[u32]], seen: &[(usize, usize)], check: bool) -> (u32, u32) { + let piece: Piece = (1, 0); + let mut suspects = Suspects::default(); + let (mut held, mut ended, mut fetches) = (0, 0, 0); + for (f, steps) in flights.iter().enumerate() { + let before = ended; + ended = *steps.last().expect("a step"); + let flagged = ended != before; + if if check { !suspects.wanted(piece, flagged) } else { !flagged } { + continue; + } + fetches += 1; + // While flight `at` is after its step `step`. + let (at, step) = seen[f]; + assert!(at >= f); + held = flights[at][step]; + suspects.fetched(piece, held == ended); + } + (held, fetches) + } + + /// A counter that each flight clears and counts up to the same: the + /// first flight's fetch sees it cleared by the second, whose compare + /// flags nothing. + #[test] + fn a_piece_caught_in_between_is_fetched_again() { + let count: &[u32] = &[0, 3, 5]; + // The first is fetched while the second has cleared it. + assert_eq!(landed(&[count, count], &[(1, 0), (1, 2)], false), (0, 1), "the CPU's side keeps what was in between"); + assert_eq!(landed(&[count, count], &[(1, 0), (1, 2)], true), (5, 2)); + // And again, while the third was at it; the fourth finds it whole. + let four = [count; 4]; + assert_eq!(landed(&four, &[(1, 0), (2, 1), (3, 0), (3, 2)], true), (5, 4)); + // Fetched whole: no more fetches than without the check. + assert_eq!(landed(&four, &[(0, 2), (1, 2), (2, 2), (3, 2)], true), (5, 1)); + assert_eq!(landed(&four, &[(0, 2), (1, 2), (2, 2), (3, 2)], false), (5, 1)); + } + + /// What the hash costs (ignored: a measurement): pieces that just came + /// down, hashed alone, compared with what the CPU's side holds (as the + /// merge begins), and both. + #[test] + #[ignore] + fn hash_costs() { + let (bytes, held) = (vec![0x5Au8; 96 << 20], vec![0x5Au8; 96 << 20]); + let pieces = || bytes.chunks(64 << 10).zip(held.chunks(64 << 10)); + let compare = |a: &[u8], b: &[u8]| a.chunks(4096).zip(b.chunks(4096)).filter(|(a, b)| a != b).count() as u32; + for _ in 0..5 { + let mut all = 0u32; + let mut time = |f: &dyn Fn(&[u8], &[u8]) -> u32| { + let t = std::time::Instant::now(); + for (a, b) in pieces() { + all ^= f(a, b); + } + t.elapsed().as_secs_f64() * 1e3 + }; + let (hashed, compared, both) = ( + time(&|a, _| hash(a)), + time(&compare), + time(&|a, b| hash(a) ^ compare(a, b)), + ); + println!("96 MB: hashed {hashed:.2} ms, compared {compared:.2} ms, both {both:.2} ms ({all:#x})"); + } + } +} diff --git a/crates/victory-gpu/src/host/upcheck.rs b/crates/victory-gpu/src/host/upcheck.rs new file mode 100644 index 0000000..661b3d4 --- /dev/null +++ b/crates/victory-gpu/src/host/upcheck.rs @@ -0,0 +1,821 @@ +//! Diagnostics (`VICTORY_UPCOPY_CHECK=1`; off by default): whether what goes +//! up to a copy in the card's memory is older than what the card holds. +//! +//! What every send up rests on: outside ranges shaders may be writing, and +//! but for what the title wrote since, a copy's CPU side holds what its card +//! side holds. Two looks at that, both on the card: +//! +//! - **at each send**: a refresh tells what the CPU's side held before +//! ([`note`]) and what it took. Ahead of the send, in its place on the +//! queue, the card's words are compared with the former. A word the title +//! did not change (both are equal) and the card holds another value of is +//! one the send puts an older value over; +//! - **at rest**: every few seconds, when the flights were settled for the +//! sweep and nothing is in the air, every copy is compared whole with its +//! CPU side. A word that differs is one a later send would undo. The log +//! line says which buffers, what stands on the card, on the CPU's side and +//! in title memory, and whether the range was declared as written at all +//! (if not: a shader writes through a view nobody declared) and fetched +//! lately (if so: what came down was not what the card ended with). +//! +//! The looks cost memory and time (the bytes sent twice more, and each +//! copy read over the bus at rest): the check is not for runs that are timed. + +use std::collections::{BTreeMap, HashMap}; + +use windows::Win32::Foundation::CloseHandle; + +use super::*; +use crate::shadow::Shadow; + +pub(crate) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_UPCOPY_CHECK").is_some_and(|v| v == "1")) +} + +/// One dispatch looks at up to a piece: `words` words of the card's buffer +/// from `at`, beside `was` (what the CPU's side held when both were known to +/// be alike) and `new` (what the title has there now). Where the two are +/// equal and the card's word is another one, it is counted, and the first +/// found is kept: its offset, the card's value, the CPU's. +const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=5, b0), SRV(t0), SRV(t1), UAV(u0)" +cbuffer Look : register(b0) { uint at; uint words; uint was; uint now; uint found_at; }; +ByteAddressBuffer card : register(t0); +ByteAddressBuffer cpu : register(t1); +RWByteAddressBuffer found : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= words) return; + uint k = id.x * 4u, n; + uint c = card.Load(at + k), w = cpu.Load(was + k); + if (c == w || cpu.Load(now + k) != w) return; + found.InterlockedAdd(found_at, 1u, n); + if (n == 0u) found.Store3(found_at + 4u, uint3(at + k, c, w)); +} +"#; + +/// Bytes of an answer. +const ANSWER: u64 = 16; +const PIECE: usize = 64 << 10; + +struct Pass { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +fn pass(host: &Host) -> Option<&'static Pass> { + static PASS: OnceLock> = OnceLock::new(); + PASS.get_or_init(|| { + let code = compile(SOURCE, windows::core::s!("main"), windows::core::s!("cs_5_1")).ok()?; + // SAFETY: the code lives through the calls; the root signature is + // inside it. + unsafe { + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).ok()?; + let pso: ID3D12PipelineState = host + .device + .CreateComputePipelineState(&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() + }) + .ok()?; + Some(Pass { root, pso }) + } + }) + .as_ref() +} + +/// A piece a refresh took: its offset in the copy, what the CPU's side held +/// and what it holds now. +pub(crate) struct Taken { + at: usize, + was: Vec, + new: Vec, +} + +/// Refreshes since the last send, per copy (by its number). +static NOTED: Mutex>> = Mutex::new(BTreeMap::new()); + +/// At most this much is looked at per submission. +const MOST: usize = 128 << 20; + +/// Offsets `[at, at + was.len())` of `copy`'s CPU side held `was` and hold +/// `new` from here on. (Whole words: a word only partly in it is left out.) +pub(crate) fn note(copy: u64, at: usize, was: &[u8], new: &[u8]) { + let skip = at.wrapping_neg() & 3; + let n = was.len().min(new.len()).saturating_sub(skip) & !3; + if n == 0 { + return; + } + let mut noted = NOTED.lock().unwrap_or_else(|e| e.into_inner()); + noted.entry(copy).or_default().push(Taken { + at: at + skip, + was: was[skip..skip + n].to_vec(), + new: new[skip..skip + n].to_vec(), + }); +} + +/// A submission's look at what it sends up, until it has run. +pub(super) struct Looks { + found: (ID3D12Resource, usize), + _bytes: ID3D12Resource, + /// Per answer: the copy, and the bytes looked at. + of: Vec<(std::sync::Arc, usize)>, +} + +/// Per copy, since the last line: sends looked at, their bytes, words an +/// older value went over, and the first few of them. +#[derive(Default)] +struct Stale { + looked: u64, + bytes: u64, + sends: u64, + words: u64, + some: Vec, +} + +static STALE: Mutex> = Mutex::new(BTreeMap::new()); + +/// Records the looks at what `dirty` sends up into `list`, ahead of the +/// sends. +pub(super) fn record( + host: &Host, + list: &ID3D12GraphicsCommandList, + dirty: &[(std::sync::Arc, Vec<(usize, usize)>)], +) -> Option { + let mut noted = std::mem::take(&mut *NOTED.lock().unwrap_or_else(|e| e.into_inner())); + let mut all: Vec<(std::sync::Arc, Taken)> = Vec::new(); + let mut total = 0; + for (shadow, _) in dirty { + for taken in noted.remove(&shadow.id()).unwrap_or_default() { + total += 2 * taken.was.len(); + if total <= MOST { + all.push((shadow.clone(), taken)); + } + } + } + if all.is_empty() { + return None; + } + let pass = pass(host)?; + let (bytes, to) = host.shared_buffer(total.min(MOST) as u64)?; + let size = (all.len() as u64 * ANSWER).next_multiple_of(256); + let (found, answers) = host.shared_buffer(size)?; + // SAFETY: mappings of the sizes asked for; an open list, whose compute + // state is set whole by what follows; live buffers, the ranges in them. + unsafe { + std::ptr::write_bytes(answers, 0, size as usize); + list.SetComputeRootSignature(&pass.root); + list.SetPipelineState(&pass.pso); + list.SetComputeRootShaderResourceView(2, bytes.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, found.GetGPUVirtualAddress()); + let mut at = 0usize; + for (i, (shadow, taken)) in all.iter().enumerate() { + let n = taken.was.len(); + std::ptr::copy_nonoverlapping(taken.was.as_ptr(), to.add(at), n); + std::ptr::copy_nonoverlapping(taken.new.as_ptr(), to.add(at + n), n); + list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress()); + let constants = [taken.at as u32, (n / 4) as u32, at as u32, (at + n) as u32, (i as u64 * ANSWER) as u32]; + list.SetComputeRoot32BitConstants(0, 5, constants.as_ptr().cast(), 0); + list.Dispatch((n / 4).div_ceil(64) as u32, 1, 1); + at += 2 * n; + } + // The sends come after the looks. + let mut seen = std::collections::HashSet::new(); + let done: Vec = all + .iter() + .filter(|(s, _)| seen.insert(std::sync::Arc::as_ptr(s) as usize)) + .map(|(s, _)| transition(&s.buffer, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST)) + .collect(); + list.ResourceBarrier(&done); + } + Some(Looks { + found: (found, answers as usize), + _bytes: bytes, + of: all.into_iter().map(|(s, t)| (s, t.was.len())).collect(), + }) +} + +impl Looks { + /// The submission has run: what it found is counted. + pub(super) fn read(self) { + // SAFETY: the mapping holds an answer for each; the card has run. + let answers = unsafe { std::slice::from_raw_parts(self.found.1 as *const [u32; 4], self.of.len()) }; + let mut stale = STALE.lock().unwrap_or_else(|e| e.into_inner()); + for ((shadow, bytes), &[words, at, card, cpu]) in self.of.iter().zip(answers) { + let (start, len) = shadow.span(); + let e = stale.entry((start, len)).or_default(); + e.looked += 1; + e.bytes += *bytes as u64; + if words > 0 { + e.sends += 1; + e.words += u64::from(words); + if e.some.len() < 4 { + e.some.push(format!("{words} words from +{at:#x} (card {card:#x}, sent {cpu:#x}; {})", known(shadow.id(), at as usize))); + } + } + } + line(&mut stale); + } +} + +/// Once a second: what was found since. +fn line(stale: &mut BTreeMap<(u64, u64), Stale>) { + static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let now = now_ms(); + let said = SAID.load(Ordering::Relaxed); + if now < said + 1000 || SAID.compare_exchange(said, now, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + let all = std::mem::take(stale); + let sum = |f: fn(&Stale) -> u64| all.values().map(f).sum::(); + tracing::info!( + frame = crate::frame::current(), + "up-copy check: {} pieces ({} KB) sent up again in {} buffers; {} of them put an older value over {} words the card had written", + sum(|s| s.looked), + sum(|s| s.bytes) >> 10, + all.len(), + sum(|s| s.sends), + sum(|s| s.words), + ); + let mut worst: Vec<_> = all.into_iter().filter(|(_, s)| s.words > 0).collect(); + worst.sort_by_key(|(_, s)| std::cmp::Reverse(s.words)); + for ((start, len), s) in worst.into_iter().take(12) { + tracing::warn!( + "up-copy check: older values sent up to {start:#x}+{len:#x}: {} words in {} pieces: {}", + s.words, + s.sends, + s.some.join(", ") + ); + } +} + +/// Of a copy: the ranges shaders were declared to write (joined), and the +/// frame each piece was last fetched in. +#[derive(Default)] +struct Known { + declared: Vec<(usize, usize)>, + fetched: HashMap, +} + +static KNOWN: Mutex> = Mutex::new(BTreeMap::new()); + +/// Offsets `[from, to)` of a copy were declared as written. +pub(super) fn declared(copy: u64, from: usize, to: usize) { + let mut known = KNOWN.lock().unwrap_or_else(|e| e.into_inner()); + let known = known.entry(copy).or_default(); + if !known.declared.iter().any(|r| r.0 <= from && to <= r.1) { + join_ranges(&mut known.declared, [(from, to)]); + } +} + +/// A piece from offset `at` on of a copy was fetched. +pub(super) fn fetched(copy: u64, at: usize) { + let mut known = KNOWN.lock().unwrap_or_else(|e| e.into_inner()); + known.entry(copy).or_default().fetched.insert(at / PIECE, crate::frame::current()); +} + +fn known(copy: u64, at: usize) -> String { + let all = KNOWN.lock().unwrap_or_else(|e| e.into_inner()); + let Some(known) = all.get(©) else { + return "no shader was declared to write the buffer".into(); + }; + if !touches(&known.declared, at, at + 4) { + return "never declared as written there".into(); + } + // (Fetched pieces begin where title memory's do; the copy may begin + // inside one.) + let last = [at / PIECE, (at / PIECE).saturating_sub(1)].iter().filter_map(|p| known.fetched.get(p)).max().copied(); + match last { + Some(frame) => format!("declared; last fetched {} frames ago", crate::frame::current().saturating_sub(frame)), + None => "declared; never fetched".into(), + } +} + +/// Reads of title memory through one copy while a flight in the air may +/// write it through another: (reader, writer) by their spans: how often, and +/// the last range they share. +type Crossed = BTreeMap<((u64, u64), (u64, u64)), (u64, usize, usize)>; +static CROSSED: Mutex<(u64, Crossed)> = Mutex::new((0, BTreeMap::new())); + +/// Flights are in the air and `runs` are about to be prepared: which +/// refreshes of theirs read title memory that a flight may be writing through +/// another copy of it. Such a refresh takes what was there before the flight +/// (nothing waits for it), and no later one knows that it was too early but +/// for the landing's own write. +pub(super) fn reads(runs: &[&HostList]) { + let mut writes: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); + let mut all = Vec::new(); + for item in &super::line().line { + if let Late::Run(flight) = item { + for (shadow, ranges) in &flight.back { + writes.extend(ranges.iter().map(|&(a, b)| (shadow.clone(), a, b))); + join_ranges(&mut all, ranges.iter().copied()); + } + } + } + if writes.is_empty() { + return; + } + let mut crossed = CROSSED.lock().unwrap_or_else(|e| e.into_inner()); + for list in runs { + for step in &list.deferred().copies { + let Step::Refresh(shadow, at, len) = step else { + continue; + }; + let (from, to) = (*at, *at + *len); + if !touches(&all, from, to) { + continue; + } + for (writer, a, b) in &writes { + if *a < to && from < *b && !std::sync::Arc::ptr_eq(writer, shadow) { + let e = crossed.1.entry((shadow.span(), writer.span())).or_default(); + *e = (e.0 + 1, (*a).max(from), (*b).min(to)); + } + } + } + } + let now = now_ms(); + if now < crossed.0 + 4000 { + return; + } + crossed.0 = now; + let mut all: Vec<_> = std::mem::take(&mut crossed.1).into_iter().collect(); + all.sort_by_key(|(_, e)| std::cmp::Reverse(e.0)); + for (((r, rn), (w, wn)), (n, a, b)) in all.into_iter().take(12) { + tracing::warn!( + "up-copy check: {n} refreshes of {r:#x}+{rn:#x} read title memory that flights in the air may write through {w:#x}+{wn:#x} (the last at {a:#x}..{b:#x})" + ); + } +} + +/// A run of words that differ at rest. +struct Differs { + shadow: std::sync::Arc, + at: usize, + len: usize, + words: u32, +} + +/// Nothing is in the air, and nothing is sent meanwhile (the submission +/// lock is held): compares every copy in the card's memory with its CPU +/// side, every few seconds. +pub(super) fn at_rest(host: &Host) { + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let now = now_ms(); + if now < LAST.load(Ordering::Relaxed) + 4000 { + return; + } + let began = std::time::Instant::now(); + if look(host).is_none() { + tracing::warn!("up-copy check: the look at rest could not be made"); + } + tracing::info!(ms = began.elapsed().as_millis(), "up-copy check: the look at rest is done"); + LAST.store(now_ms(), Ordering::Relaxed); +} + +/// Sends `list` (recorded by `f`) and waits for it. +fn run(host: &Host, f: impl FnOnce(&ID3D12GraphicsCommandList)) -> Option<()> { + let (allocator, list) = host.make_prelude()?; + // SAFETY: objects of our own, waited for before they go. + unsafe { + allocator.Reset().ok()?; + list.Reset(&allocator, None).ok()?; + f(&list); + list.Close().ok()?; + let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + host.queue.ExecuteCommandLists(&[Some(list.cast().ok()?)]); + let done = host.queue.Signal(&fence, 1).and_then(|()| fence.SetEventOnCompletion(1, event)); + if done.is_ok() { + WaitForSingleObject(event, INFINITE); + } + let _ = CloseHandle(event); + done.ok() + } +} + +/// The words that differ. +fn look(host: &Host) -> Option { + let pass = pass(host)?; + let copies = crate::shadow::carded_copies(); + // (copy, offset, bytes) + let mut pieces: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); + for shadow in &copies { + // What has not gone up yet differs rightly. + let dirty = shadow.card_dirty_now(); + let len = shadow.span().1 as usize & !3; + for at in (0..len).step_by(PIECE) { + let n = PIECE.min(len - at); + if !dirty.iter().any(|&(a, b)| a < at + n && b > at) { + pieces.push((shadow.clone(), at, n)); + } + } + } + if pieces.is_empty() { + return Some(0); + } + let size = (pieces.len() as u64 * ANSWER).next_multiple_of(256); + let (found, answers) = host.shared_buffer(size)?; + // SAFETY: a mapping of that size. + unsafe { std::ptr::write_bytes(answers, 0, size as usize) }; + run(host, |list| { + // SAFETY: an open list; live buffers (held by `pieces`). + unsafe { + list.SetComputeRootSignature(&pass.root); + list.SetPipelineState(&pass.pso); + list.SetComputeRootUnorderedAccessView(3, found.GetGPUVirtualAddress()); + let mut bound = 0; + for (i, (shadow, at, n)) in pieces.iter().enumerate() { + let Some((staging, ..)) = shadow.card_sides() else { + continue; + }; + if bound != shadow.id() { + bound = shadow.id(); + list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress()); + list.SetComputeRootShaderResourceView(2, staging.GetGPUVirtualAddress()); + } + let at = *at as u32; + let constants = [at, (*n / 4) as u32, at, at, (i as u64 * ANSWER) as u32]; + list.SetComputeRoot32BitConstants(0, 5, constants.as_ptr().cast(), 0); + list.Dispatch((*n / 4).div_ceil(64) as u32, 1, 1); + } + } + })?; + // SAFETY: the mapping holds an answer for each; the card has run. + let answers = unsafe { std::slice::from_raw_parts(answers as *const [u32; 4], pieces.len()) }; + let differs: Vec = pieces + .iter() + .zip(answers) + .filter(|(_, a)| a[0] > 0) + .map(|((shadow, at, len), a)| Differs { + shadow: shadow.clone(), + at: *at, + len: *len, + words: a[0], + }) + .collect(); + let bytes: u64 = pieces.iter().map(|p| p.2 as u64).sum(); + let words: u64 = differs.iter().map(|d| u64::from(d.words)).sum(); + tracing::info!( + frame = crate::frame::current(), + "up-copy check at rest: {} copies, {} MB; {words} words in {} pieces of them differ from the CPU's side", + copies.len(), + bytes >> 20, + differs.len() + ); + if differs.is_empty() { + return Some(0); + } + // Per copy, what stands where, of a few pieces. + const SHOWN: usize = 64; + let shown = &differs[..differs.len().min(SHOWN)]; + let (held, data) = host.shared_buffer((SHOWN * PIECE) as u64)?; + run(host, |list| { + for (i, d) in shown.iter().enumerate() { + // SAFETY: an open list; live buffers, the ranges in them. + unsafe { list.CopyBufferRegion(&held, (i * PIECE) as u64, &d.shadow.buffer, d.at as u64, d.len as u64) }; + } + })?; + let mut by: BTreeMap<(u64, u64), (u64, usize, Vec)> = BTreeMap::new(); + for d in &differs { + let e = by.entry(d.shadow.span()).or_default(); + e.0 += u64::from(d.words); + e.1 += 1; + } + for (i, d) in shown.iter().enumerate() { + let (start, _) = d.shadow.span(); + // SAFETY: the mapping; the copy into it has run. + let card = unsafe { std::slice::from_raw_parts(data.add(i * PIECE).cast_const(), d.len) }; + let cpu = d.shadow.card_held(d.at, d.len); + let mut title = vec![0u8; d.len]; + let mapped = read_into((start as usize + d.at) as *const u8, &mut title); + // Of the words that differ: title memory holds the CPU side's + // value, the card's, another one. + let (mut as_cpu, mut as_card, mut other) = (0, 0, 0); + let mut first = None; + let (mut low, mut high) = (usize::MAX, 0); + for at in (0..d.len & !3).step_by(4) { + let word = |b: &[u8]| u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]); + let (c, h, t) = (word(card), word(&cpu), word(&title)); + if c == h { + continue; + } + (low, high) = (low.min(at), at); + first.get_or_insert((at, c, h, t)); + if t == h { + as_cpu += 1; + } else if t == c { + as_card += 1; + } else { + other += 1; + } + } + let Some((at, c, h, t)) = first else { + continue; + }; + if let Some(e) = by.get_mut(&d.shadow.span()) + && e.2.len() < 6 + { + e.2.push(format!( + "{} words in +{:#x}..{:#x} (title memory: {as_cpu} as the CPU's side, {as_card} as the card, {other} neither{}; first: \ + card {c:#x}, CPU {h:#x}, title {t:#x}; {})", + d.words, + d.at + low, + d.at + high + 4, + if mapped { "" } else { ", not all mapped" }, + known(d.shadow.id(), d.at + at) + )); + } + } + let mut by: Vec<_> = by.into_iter().collect(); + by.sort_by_key(|(_, e)| std::cmp::Reverse(e.0)); + for ((start, len), (words, pieces, some)) in by.into_iter().take(16) { + tracing::warn!( + "up-copy check at rest: {start:#x}+{len:#x}: {words} words in {pieces} pieces are not the CPU side's: {}", + some.join("; ") + ); + } + Some(words) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn notes_are_cut_to_whole_words() { + // Bytes 5..18 of a copy: the words at 8 and 12. + let (was, new): (Vec, Vec) = ((5..18).collect(), (105..118).collect()); + note(u64::MAX, 5, &was, &new); + let noted = NOTED.lock().unwrap_or_else(|e| e.into_inner()).remove(&u64::MAX).expect("noted"); + let [t] = ¬ed[..] else { panic!("one piece") }; + assert_eq!((t.at, &t.was[..], &t.new[..]), (8, &was[3..11], &new[3..11])); + } + + /// The tests below want processes of their own with the relay on: each + /// `VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 VICTORY_UPCOPY_CHECK=1 cargo + /// test -p victory-gpu --lib upcheck -- --ignored --test-threads=1 + /// `. + const LEN: usize = 4 << 20; + + /// Title memory of our own (write-watched, or a view of a section, which + /// is guarded), and the card copy of the title buffer it is. + fn title(resource: usize, view: bool) -> (&'static mut [u8], usize, std::sync::Arc) { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE, VirtualAlloc, + }; + const WRITE_WATCH: u32 = 0x20_0000; + // SAFETY: memory of our own, never freed. + let base = unsafe { + if view { + let section = CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, LEN as u32, std::ptr::null()); + assert!(!section.is_null()); + MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, LEN).Value.cast::() + } else { + VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, PAGE_READWRITE).cast::() + } + }; + assert!(!base.is_null()); + crate::shadow::register(resource, base as u64, LEN as u64); + let shadow = crate::shadow::find(base as u64, 64).expect("a copy"); + assert!(shadow.carded(), "the copy is in the card's memory"); + assert!(super::super::relay_exact() && super::super::relay_copy(), "set VICTORY_RELAY=2 VICTORY_RELAY_COPY=1"); + // SAFETY: `LEN` bytes just committed. + (unsafe { std::slice::from_raw_parts_mut(base, LEN) }, base as usize, shadow) + } + + /// Work for the card that takes some milliseconds. + struct Slow(ID3D12Resource, ID3D12Resource); + + impl Slow { + fn new(host: &Host) -> Slow { + Slow(host.uav_buffer(64 << 20).unwrap(), host.uav_buffer(64 << 20).unwrap()) + } + + fn record(&self, list: &HostList, times: usize) { + // SAFETY: an open list; live buffers. + unsafe { + for _ in 0..times { + list.list.CopyBufferRegion(&self.1, 0, &self.0, 0, 64 << 20); + list.list.ResourceBarrier(&[ + transition(&self.1, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON), + ]); + } + } + } + } + + /// A shader's stand-in: `bytes` go to offset `at` of the copy. + fn write(host: &Host, list: &HostList, shadow: &Shadow, at: usize, bytes: &[u8]) { + let (upload, data) = host.upload_buffer(bytes.len() as u64).unwrap(); + // SAFETY: the mapping; an open list and live buffers. + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len()); + list.list.CopyBufferRegion(&shadow.buffer, at as u64, &upload, 0, bytes.len() as u64); + list.list + .ResourceBarrier(&[transition(&shadow.buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]); + } + list.keep(&upload); + } + + /// What the card's side holds, nothing being in the air. + fn card(host: &Host, shadow: &Shadow) -> Vec { + let (held, data) = host.shared_buffer(LEN as u64).unwrap(); + // SAFETY: an open list; live buffers. + run(host, |list| unsafe { list.CopyBufferRegion(&held, 0, &shadow.buffer, 0, LEN as u64) }).unwrap(); + // SAFETY: the mapping; the copy has run. + unsafe { std::slice::from_raw_parts(data, LEN) }.to_vec() + } + + /// (e) of the list in `Host::relay_card_back`'s fetch: a flight's result + /// is fetched while the next flight is at the same bytes, which ends with + /// what it found. Without `VICTORY_FETCH_CHECK` title memory keeps what + /// was in between, and the next refresh of the 64 KiB sends it up. + #[test] + #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"] + fn a_result_caught_in_between_is_put_right() { + let Some(host) = host() else { + return; + }; + let (title, start, shadow) = title(0x3333, false); + let slow = Slow::new(host); + let (mut wrong, mut undone) = (0, 0); + let mut lists = Vec::new(); + const ROUNDS: usize = 12; + for round in 0..ROUNDS { + let result: Vec = (0..256).map(|i| (round * 17 + i + 1) as u8).collect(); + let between = vec![0u8; 256]; + let a = host.new_list().unwrap(); + shadow.refresh(&a, start as u64, LEN as u64); + shadow.gpu_writes(&a, start as u64, LEN as u64); + write(host, &a, &shadow, 1024, &result); + a.close(); + let b = host.new_list().unwrap(); + shadow.gpu_writes(&b, start as u64, LEN as u64); + write(host, &b, &shadow, 1024, &between); + slow.record(&b, 60); + write(host, &b, &shadow, 1024, &result); + b.close(); + host.execute_own(&a); + host.execute_own(&b); + settle_now(WHY_SYNC); + wrong += usize::from(title[1024..1280] != result[..]); + // The title writes beside it: the refresh takes the 64 KiB. + title[4096] = round as u8 + 1; + let c = host.new_list().unwrap(); + shadow.refresh(&c, start as u64, LEN as u64); + c.close(); + host.execute_own(&c); + settle_now(WHY_SYNC); + let holds = card(host, &shadow); + assert_eq!(holds[4096], round as u8 + 1, "the title's write is on the card"); + undone += usize::from(holds[1024..1280] != result[..]); + lists.extend([a, b, c]); + } + eprintln!( + "{wrong} of {ROUNDS} results wrong in title memory, {undone} undone on the card; pieces checked, suspect, put right: {:?}", + super::torn::STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect::>() + ); + assert_eq!(look(host), Some(0)); + assert_eq!((wrong, undone), (0, 0), "without VICTORY_FETCH_CHECK=1 most are wrong"); + } + + /// What nobody declared: a shader writes a piece through a view that was + /// not known. The title writes another byte of the piece: it goes up + /// whole, with title memory's older bytes, and the check says so. + #[test] + #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 VICTORY_UPCOPY_CHECK=1 and a process of its own"] + fn the_check_finds_an_undeclared_write_undone() { + let Some(host) = host() else { + return; + }; + assert!(on(), "set VICTORY_UPCOPY_CHECK=1"); + let (title, start, shadow) = title(0x4444, false); + let a = host.new_list().unwrap(); + shadow.refresh(&a, start as u64, LEN as u64); + shadow.gpu_writes(&a, start as u64, 1 << 16); + write(host, &a, &shadow, (5 << 16) + 512, &[0x77; 64]); + a.close(); + host.execute_own(&a); + settle_now(WHY_SYNC); + assert_eq!(card(host, &shadow)[(5 << 16) + 512], 0x77); + assert!(title[(5 << 16) + 512] == 0, "it never comes back"); + assert_eq!(look(host), Some(16), "the look at rest finds it"); + title[(5 << 16) + 9000] = 1; + let b = host.new_list().unwrap(); + shadow.refresh(&b, start as u64, LEN as u64); + b.close(); + host.execute_own(&b); + settle_now(WHY_SYNC); + let undone = card(host, &shadow)[(5 << 16) + 512] == 0; + let stale = STALE.lock().unwrap_or_else(|e| e.into_inner()); + let found = stale.get(&shadow.span()).map_or(0, |s| s.words); + eprintln!("undone on the card: {undone}; the check found {found} words"); + assert_eq!((undone, found), (true, 16)); + } + + /// Declared writes beside the title's own, in the same 64 KiB pieces and + /// dword by dword, flights landing while later ones are in the air: in + /// the end title memory and the card hold what each wrote last. (A byte + /// is written by flights or by the title, not both at a time.) + #[test] + #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"] + fn declared_writes_beside_the_titles_own_stay() { + let Some(host) = host() else { + return; + }; + for view in [false, true] { + beside(host, 0x5555 + usize::from(view), view); + } + } + + fn beside(host: &Host, resource: usize, view: bool) { + let (title, start, shadow) = title(resource, view); + let slow = Slow::new(host); + // A small generator: the runs are the same each time. + let mut seed = 0x1234_5678_9abc_def1u64; + let mut next = move |n: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as usize % n + }; + // What memory should hold: pieces 0..8 are used, words of them by + // turns the title's (even) and the shaders' (odd). + const USED: usize = 8 << 16; + let mut model = vec![0u8; USED]; + let mut lists = Vec::new(); + for round in 0..800usize { + // The title writes some of its words, flights in the air or not. + for _ in 0..next(24) { + let at = next(USED / 8) * 8; + let value = ((round as u32) << 8 | next(256) as u32).to_le_bytes(); + title[at..at + 4].copy_from_slice(&value); + model[at..at + 4].copy_from_slice(&value); + } + // A submission: reads all or a part, writes a declared part. + let list = host.new_list().unwrap(); + let (from, to) = match next(4) { + 0 => (0, LEN), + 1 => { + let a = next(8) << 16; + (a, a + (1 << 16)) + } + _ => { + let a = next(USED - 4096) & !255; + (a, a + 256 * (1 + next(16))) + } + }; + shadow.refresh(&list, (start + from) as u64, (to - from) as u64); + if next(5) > 0 { + shadow.gpu_writes(&list, (start + from) as u64, (to - from) as u64); + if next(3) == 0 { + slow.record(&list, 1 + next(3)); + } + for _ in 0..1 + next(6) { + let words = (to.min(USED) - from) / 8; + let at = from + next(words) * 8 + 4; + // Now and then something in between first. + if next(4) == 0 { + write(host, &list, &shadow, at, &[0xEE; 4]); + slow.record(&list, 1); + } + let value = if next(3) == 0 { [7, 7, 7, 7] } else { (0x8000_0000 | (round as u32) << 8 | next(256) as u32).to_le_bytes() }; + write(host, &list, &shadow, at, &value); + model[at..at + 4].copy_from_slice(&value); + } + } + list.close(); + host.execute_own(&list); + lists.push(list); + if round % 40 == 39 { + // Everything refreshed, landed and looked at. + let all = host.new_list().unwrap(); + shadow.refresh(&all, start as u64, LEN as u64); + all.close(); + host.execute_own(&all); + settle_now(WHY_SYNC); + let all = host.new_list().unwrap(); + shadow.refresh(&all, start as u64, LEN as u64); + all.close(); + host.execute_own(&all); + settle_now(WHY_SYNC); + lists.push(all); + assert_eq!(look(host), Some(0), "round {round}: the card's side is the CPU's side"); + let holds = card(host, &shadow); + let wrong = |held: &[u8]| (0..USED / 4).filter(|w| held[w * 4..w * 4 + 4] != model[w * 4..w * 4 + 4]).collect::>(); + let (on_card, in_title) = (wrong(&holds), wrong(title)); + assert!( + on_card.is_empty() && in_title.is_empty(), + "round {round}: words {on_card:x?} on the card and {in_title:x?} in title memory are not what was written last" + ); + } + } + } +} diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index f8f961b..4c19c17 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -773,7 +773,17 @@ void main() { } warp.submit_and_wait(); // SAFETY: as above. - [0, 1, 2].map(|piece| unsafe { differs_ptr.cast::().add(piece).read_volatile() }) + let found = [0, 1, 2].map(|piece| unsafe { differs_ptr.cast::().add(piece).read_volatile() }); + if mode == 0 { + return found; + } + // Above the flag, the hash: as `host::torn` makes it of the bytes. + for (piece, d) in found.iter().enumerate() { + // SAFETY: inside the mapping, which the card has read. + let bytes = unsafe { std::slice::from_raw_parts(now_ptr.add(piece * PIECE).cast_const(), PIECE) }; + assert_eq!(d >> 1, crate::host::piece_hash(bytes), "piece {piece}"); + } + found.map(|d| d & 1) }; let at = PIECE + 1234; // SAFETY (each): inside the mapping. diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index 5ad96c5..2c50537 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -31,6 +31,7 @@ use super::wire::{ pub mod diverge; mod merge; +mod upcopies; /// The name of the argument clamp's pipeline, by which its passes are /// recognised. diff --git a/crates/victory-gpu/src/replay/play/diverge.rs b/crates/victory-gpu/src/replay/play/diverge.rs index a297040..de9da17 100644 --- a/crates/victory-gpu/src/replay/play/diverge.rs +++ b/crates/victory-gpu/src/replay/play/diverge.rs @@ -12,19 +12,19 @@ const PIECE: usize = 64 << 10; /// Where a run's contents come down: for each resource (and subresource) the /// frame writes, its place in read-back memory. -struct Reader { +pub(super) struct Reader { blocks: Vec<(ID3D12Resource, usize)>, - parts: Vec, + pub(super) parts: Vec, } #[derive(Clone)] -struct Part { - id: u32, +pub(super) struct Part { + pub(super) id: u32, /// `None` for a buffer. sub: Option<(u32, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)>, block: usize, at: u64, - len: u64, + pub(super) len: u64, } /// One way to run commands `from..to` of a list. @@ -275,7 +275,7 @@ impl Player { } /// The states of textures at the frame's start. - fn start_states(&self) -> States { + pub(super) fn start_states(&self) -> States { let mut states = States::default(); for (id, all) in &self.start { let Some(o) = self.objects.get(id) else { @@ -412,7 +412,7 @@ impl Player { Ok(()) } - fn reader(&self, ids: &[u32]) -> Result { + pub(super) fn reader(&self, ids: &[u32]) -> Result { const BLOCK: u64 = 512 << 20; let mut parts = Vec::new(); let mut sizes: Vec = vec![0]; @@ -514,7 +514,7 @@ impl Player { } /// Hashes of all parts' pieces, as memory is now (in `states`). - fn hashes_now(&mut self, reader: &Reader, states: &States) -> Result>> { + pub(super) fn hashes_now(&mut self, reader: &Reader, states: &States) -> Result>> { let objects = &self.objects; for block in 0..reader.blocks.len() { let parts: Vec<&Part> = reader.parts.iter().filter(|p| p.block == block).collect(); diff --git a/crates/victory-gpu/src/replay/play/upcopies.rs b/crates/victory-gpu/src/replay/play/upcopies.rs new file mode 100644 index 0000000..e2a9cba --- /dev/null +++ b/crates/victory-gpu/src/replay/play/upcopies.rs @@ -0,0 +1,342 @@ +//! The copies of the CPU's sides of card buffers up to them, looked at: do +//! they bring words older than what the card holds? And do the frame's +//! shaders write card buffers outside what the host layer had declared as +//! written (its compare passes cover that)? + +use super::*; + +/// As the host layer cuts buffers. +const PIECE: u64 = 64 << 10; + +/// A copy up: submission, source, destination, offset, length. +type Up = (usize, u32, u32, u64, u64); + +/// A word a copy brings that the card holds another value of: its offset, +/// what the card holds, what was last put there before the card wrote, what +/// is brought. +type Word = (u64, [u32; 3]); + +impl Player { + /// The copies up in a submission's lists. + fn ups(&self, submit: usize, lists: &[Vec]) -> Vec { + let mut out = Vec::new(); + for c in lists.iter().flatten() { + if self.merged_copy(c).is_some() + && let Cmd::CopyBuffer { + dst, + dst_at, + src, + len, + .. + } = c + { + out.push((submit, *src, *dst, *dst_at, *len)); + } + } + out + } + + /// Where pieces begin in a card buffer, and those the host layer's + /// compares look at in a submission. + fn declared(&self, lists: &[Vec]) -> HashMap)> { + let compares = self.pipelines_named(COMPARE); + let mut out: HashMap)> = HashMap::new(); + for cmds in lists { + let (mut bound, mut constants, mut of) = (NONE, Vec::new(), NONE); + for c in cmds { + match c { + Cmd::Pipeline { pso } => bound = *pso, + Cmd::Constants { + graphics: false, + param: 0, + values, + .. + } => constants = values.clone(), + Cmd::RootView { + graphics: false, + param: 1, + va: Va::At { res, .. }, + .. + } => of = *res, + Cmd::Dispatch { .. } + if compares.contains(&bound) + && constants.len() >= 6 + && constants[5] != 0 => + { + let e = out + .entry(of) + .or_insert((u64::from(constants[1]), HashSet::new())); + e.1.extend((constants[0]..constants[0] + constants[3]).map(u64::from)); + } + _ => {} + } + } + } + out + } + + /// Bytes of buffers, as they are now. + fn slices(&mut self, all: &[(ID3D12Resource, u64, u64)]) -> Result>> { + let total: u64 = all.iter().map(|a| a.2).sum(); + if total == 0 { + return Ok(vec![Vec::new(); all.len()]); + } + let (back, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_READBACK, + total, + D3D12_RESOURCE_FLAG_NONE, + )?; + self.worker.run(|list| { + let mut at = 0; + for (res, from, len) in all { + // SAFETY: an open list; live buffers, ranges inside them. + unsafe { list.CopyBufferRegion(&back, at, res, *from, *len) }; + at += len; + } + })?; + let mut at = 0usize; + Ok(all + .iter() + .map(|(_, _, len)| { + // SAFETY: the mapping; the copies into it have run. + let bytes = + unsafe { std::slice::from_raw_parts(data.add(at), *len as usize) }.to_vec(); + at += *len as usize; + bytes + }) + .collect()) + } + + /// The heap slots that show a buffer, a few of each kind. + fn views_of(&self, id: u32) -> Vec { + let mut out = Vec::new(); + let mut shown = |kind: u8, at: String| { + let what = if kind == slot::UAV { "uav" } else { "srv" }; + if out.iter().filter(|l: &&String| l.starts_with(what)).count() < 6 { + out.push(format!("{what} {at}")); + } + }; + for h in &self.frame.descriptor_heaps { + for (first, n, s) in h.runs.iter().filter(|r| r.2.res == id) { + shown(s.kind, format!("heap {} slot {first:#x} ({n})", h.id)); + } + } + for (i, s) in self.frame.submits.iter().enumerate() { + for (heap, at, s) in s.views.iter().filter(|v| v.2.res == id) { + shown( + s.kind, + format!("heap {heap} slot {at:#x} from submission {i} on"), + ); + } + } + out + } + + /// Runs the frame twice, submission by submission, and says what the + /// copies up would have put over what the card wrote in both runs alike, + /// and what was written undeclared. + pub fn upcopies(&mut self, o: &Options, say: &mut dyn FnMut(String)) -> Result<()> { + let mut report = Report::default(); + self.set_merging(true)?; + let submits = self.edited(o, &mut report, &[]); + let built = self.build(&submits, o)?; + let ids: Vec = self + .masters + .iter() + .map(|m| m.0) + .filter(|id| { + self.card_writes.contains(id) + && self.frame.resources[self.objects[id].index] + .name + .ends_with("on the card") + }) + .collect(); + let reader = self.reader(&ids)?; + say(format!( + "{} buffers on the card that the frame writes, {} MB", + ids.len(), + reader.parts.iter().map(|p| p.len).sum::() >> 20 + )); + // What a shader that picks a view to write through by an index could + // write. + let mut shown: BTreeMap = BTreeMap::new(); + for s in self + .frame + .descriptor_heaps + .iter() + .flat_map(|h| h.runs.iter().map(|r| &r.2)) + { + if s.kind == slot::UAV + && let Some(o) = self.objects.get(&s.res) + { + let d = &self.frame.resources[o.index].desc; + if d.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { + *shown.entry(s.res).or_default() = d.width; + } + } + } + say(format!( + "unordered views of {} buffers in the heaps at the start, {} MB of them", + shown.len(), + shown.values().sum::() >> 20 + )); + let states = self.start_states(); + let mut runs: Vec)>> = Vec::new(); + for run in 0..2 { + self.restore(true)?; + self.fresh = false; + let mut found: Vec<(Up, Vec)> = Vec::new(); + let mut was = if run == 0 { + self.hashes_now(&reader, &states)? + } else { + Vec::new() + }; + for (i, (delta, lists)) in built.steps.iter().enumerate() { + if let Some(d) = delta { + // SAFETY: a closed list, waited for. + unsafe { + self.worker + .queue + .ExecuteCommandLists(&[Some(d.list.cast()?)]) + }; + self.worker.idle()?; + } + let ups = self.ups(i, &submits[i]); + if !ups.is_empty() { + let mut asked = Vec::new(); + for &(_, src, dst, at, len) in &ups { + let Some(base) = self.merger.as_ref().and_then(|m| m.bases.get(&dst)) + else { + bail!("a copy up without a base"); + }; + asked.push((self.objects[&dst].res.clone(), at, len)); + asked.push((base.clone(), at, len)); + asked.push((self.objects[&src].res.clone(), at, len)); + } + let bytes = self.slices(&asked)?; + for (k, up) in ups.iter().enumerate() { + let (now, base, new) = + (&bytes[k * 3], &bytes[k * 3 + 1], &bytes[k * 3 + 2]); + let word = |b: &[u8], i: usize| { + u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) + }; + let mut words = Vec::new(); + for at in (0..now.len() / 4 * 4).step_by(4) { + let w = [word(now, at), word(base, at), word(new, at)]; + if w[0] != w[2] { + words.push((up.3 + at as u64, w)); + } + } + found.push((*up, words)); + } + } + let all: Vec> = lists + .iter() + .map(|l| l.list.cast::().map(Some)) + .collect::>()?; + if !all.is_empty() { + // SAFETY: closed lists, waited for. + unsafe { self.worker.queue.ExecuteCommandLists(&all) }; + self.worker.idle().context("the card was lost")?; + } + if run > 0 { + continue; + } + let now = self.hashes_now(&reader, &states)?; + let mut declared = self.declared(&submits[i]); + for (_, _, dst, at, len) in &ups { + let e = declared.entry(*dst).or_default(); + let skew = e.0; + e.1.extend((*at + skew) / PIECE..(*at + len + skew).div_ceil(PIECE)); + } + for (p, (a, b)) in was.iter().zip(&now).enumerate() { + let id = reader.parts[p].id; + let differ: Vec = (0..a.len()).filter(|&k| a[k] != b[k]).collect(); + if differ.is_empty() { + continue; + } + let outside: Vec = differ + .iter() + .map(|&k| k as u64) + .filter(|&k| match declared.get(&id) { + None => true, + // (A copy that does not begin on a piece: the + // hashes' piece lies over two of the compare's.) + Some((skew, pieces)) => { + let first = (k * PIECE + skew) / PIECE; + let last = ((k + 1) * PIECE + skew - 1) / PIECE; + !(first..=last).any(|p| pieces.contains(&p)) + } + }) + .collect(); + if !outside.is_empty() { + say(format!( + "submission {i}: {} of {} changed pieces of {} were not declared as written, the first {:#x?}", + outside.len(), + differ.len(), + self.called(id), + &outside[..outside.len().min(8)] + )); + for line in self.views_of(id) { + say(format!(" {line}")); + } + } + } + was = now; + } + runs.push(found); + } + let [first, second] = &runs[..] else { + bail!("not two runs"); + }; + // What the card wrote in both runs alike, and what comes is another + // value: the title's, or an old one. + let (mut same, mut old, mut differ, mut all, mut titles) = (0u64, 0u64, 0u64, 0u64, 0u64); + let mut by: BTreeMap<(u32, u64), (u64, u64, Vec)> = BTreeMap::new(); + for ((up, a), (_, b)) in first.iter().zip(second) { + all += up.4 / 4; + let b: HashMap = b.iter().copied().collect(); + for (at, [now, base, new]) in a { + if now == base { + titles += 1; + continue; + } + if b.get(at).is_none_or(|other| other[0] != *now) { + differ += 1; + continue; + } + same += 1; + let back = new == base; + old += u64::from(back); + let e = by.entry((up.2, at / PIECE)).or_default(); + e.0 += 1; + e.1 += u64::from(back); + if e.2.len() < 6 { + e.2.push(format!( + "submission {} +{at:#x}: card {now:#x}, before {base:#x}, comes {new:#x}", + up.0 + )); + } + } + } + say(format!( + "{} copies up of {all} words: {titles} bring something new where the card had not written; where it had and another \ + value comes: {differ} words differ between the runs, {same} the card wrote alike in both ({old} of them would get \ + back what stood there before the card wrote)", + first.len(), + )); + let mut by: Vec<_> = by.into_iter().collect(); + by.sort_by_key(|b| std::cmp::Reverse(b.1.0)); + for ((id, piece), (n, back, some)) in by.into_iter().take(40) { + say(format!( + " {} piece {piece:#x}: {n} words, {back} back to before", + self.called(id) + )); + for line in some { + say(format!(" {line}")); + } + } + Ok(()) + } +} diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 882f00d..f910c6f 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -372,6 +372,11 @@ pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc, Vec<(usize, usize)>) out } +/// The copies in the card's memory (diagnostics: `crate::host::upcheck`). +pub(crate) fn carded_copies() -> Vec> { + CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter_map(std::sync::Weak::upgrade).collect() +} + /// Ranges in order, those that overlap or touch as one. fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> { ranges.sort_unstable(); @@ -439,9 +444,16 @@ fn card_piece_of(start: usize, len: usize, span: &CardSpan, i: u32) -> (usize, u (lo.max(span.from as usize), hi.min(span.to as usize)) } +/// The offsets [`Shadow::card_hashed`] gives, for a card's buffer of `size` +/// bytes for title memory from `start` on. +fn card_hashed_of(start: usize, size: usize, piece: usize) -> (usize, usize) { + let (lo, hi) = piece_at(start, size, piece); + (lo & !15, hi.next_multiple_of(16)) +} + #[cfg(test)] mod card_tests { - use super::{CardSpan, PIECE, card_piece_of, card_span_of, joined, joined_piece_runs}; + use super::{CardSpan, PIECE, card_hashed_of, card_piece_of, card_span_of, joined, joined_piece_runs}; /// Joined runs hold every piece of the runs given, once, and no other. #[test] @@ -497,6 +509,25 @@ mod card_tests { } /// Changed ranges are joined where they overlap or touch, and only there. + /// What is fetched of a piece to hash it is what the shader hashes. + #[test] + fn a_piece_is_hashed_here_as_on_the_card() { + for start in [0usize, 0x10_0000, 0xd_5edb_c780, 0x12_3456_7008] { + for size in [1usize << 16, 5 << 16, 0x20_0000] { + let span = card_span_of(start, 0, size); + for i in 0..span.pieces { + // As `CARD_COMPARE` has it. + let (piece, skew, size) = (span.first + i, span.skew, size as u32); + let lo = (piece * 65536).saturating_sub(skew); + let hi = ((piece + 1) * 65536 - skew).min(size); + let shader = (lo & !15, (hi + 15) & !15); + let here = card_hashed_of(start, size as usize, piece as usize); + assert_eq!((here.0 as u32, here.1 as u32), shader, "start {start:#x} size {size:#x} piece {piece}"); + } + } + } + } + #[test] fn ranges_join_where_they_touch() { assert_eq!(joined(vec![(8, 12), (0, 4), (4, 6), (10, 20), (30, 31)]), [(0, 6), (8, 20), (30, 31)]); @@ -965,6 +996,16 @@ mod difference_tests { /// The unit shader writes are looked for and put back in. const PIECE: usize = 64 << 10; +/// Calls `f` with `[from, to)` cut at multiples of [`PIECE`]. +fn for_pieces_of(from: usize, to: usize, mut f: impl FnMut(usize, usize)) { + let mut at = from; + while at < to { + let next = ((at / PIECE + 1) * PIECE).min(to); + f(at, next); + at = next; + } +} + /// Copies `len` bytes, on several threads if they are many: a snapshot of /// the world's big heap is 100-170 MB per submission, 2-4 GB a frame, and /// one thread copies some 8 GB/s. @@ -2680,7 +2721,16 @@ impl Shadow { let (from, to) = (from.max(start), to.min(end)); // SAFETY: inside the mapping (`from` and `to` are within the buffer). let at = unsafe { self.data.add(from - start) }; - crate::host::copy_mapped(at, from as *const u8, to - from, false); + if self.card.is_some() && from < to && crate::host::upcheck::on() { + for_pieces_of(from - start, to - start, |a, b| { + let was = self.card_held(a, b - a); + // SAFETY: inside the mapping, as above. + crate::host::copy_mapped(unsafe { self.data.add(a) }, (start + a) as *const u8, b - a, false); + crate::host::upcheck::note(self.id, a, &was, &self.card_held(a, b - a)); + }); + } else { + crate::host::copy_mapped(at, from as *const u8, to - from, false); + } // After the bytes are in: a snapshot taken meanwhile is not current. self.changed(from - start, to - start); self.card_changed(from - start, to - start); @@ -2709,6 +2759,24 @@ impl Shadow { } } + /// Diagnostics: of a copy in the card's memory, what its CPU side holds + /// at offsets `[at, at + len)` (cut to the copy). + pub(crate) fn card_held(&self, at: usize, len: usize) -> Vec { + let to = (at + len).min(self.len as usize); + if self.card.is_none() || at >= to { + return Vec::new(); + } + // SAFETY: inside the mapping; the caller holds the submission lock, + // under which it is written but for what is being landed. + unsafe { std::slice::from_raw_parts(self.data.add(at).cast_const(), to - at) }.to_vec() + } + + /// Diagnostics: the offsets whose bytes have not gone to the card's side + /// yet. + pub(crate) fn card_dirty_now(&self) -> Vec<(usize, usize)> { + self.card.as_ref().map_or_else(Vec::new, |c| c.dirty.lock().unwrap_or_else(|e| e.into_inner()).clone()) + } + /// Of a copy in the card's memory: the CPU's side (PC memory), the /// card side's bytes from before if made yet, and their size. pub(crate) fn card_sides(&self) -> Option<(&ID3D12Resource, Option, u64)> { @@ -2756,6 +2824,14 @@ impl Shadow { card_piece_of(self.start as usize, self.len as usize, span, i) } + /// The offsets the compare on the card hashes of a piece: what lies of + /// it in the card's buffer (which may be longer than the copy), widened + /// to 16 bytes. + pub(crate) fn card_hashed(&self, piece: u32) -> (usize, usize) { + let size = self.card.as_ref().map_or(self.len, |c| c.size) as usize; + card_hashed_of(self.start as usize, size, piece as usize) + } + /// The walls trace (`crate::host::walls_trace`): a piece of `fetched` /// bytes of this copy came back from the card and `written` of them /// went into title memory. Summed per buffer and logged once a frame: diff --git a/docs/replay.md b/docs/replay.md index 352f976..e2bb6e8 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -93,6 +93,7 @@ report counts them). `--no-merge` runs the copies as recorded. | `--watch ::` | which lists (with `--lists`: commands) change those words | | `--slots :` | the heap slots its constants name | | `--check-written` | that everything the frame changes is put back | +| `--upcopies` | runs the frame twice: which words the copies of the CPU's sides of card buffers bring that the card holds another value of (those the card wrote alike in both runs are the ones to look at), and which pieces shaders wrote that were not declared as written. The live check is `VICTORY_UPCOPY_CHECK=1` (`host/upcheck.rs`) | | `--dump ` | the DXIL of the pipelines named, in `shaders` | The `--diverge` family runs the recorded copies without the merge. From 9c2168a6434ea7034669e37f4bb375e850b988b0 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 22:09:38 -0600 Subject: [PATCH 172/445] Views guarded while they are mapped stay writable; tests take turns on WARP The runtime maps a view and then tells the write watch. A refresh on another thread could guard the new blocks in between, and the telling then forgot them and left them read-only: the title's next write to one was an access violation nobody takes. Told of a new view, the watch now gives the write access back; before an unmapping it only forgets, as before. The test binary's random crashes were d3d10warp.dll's own, with two tests on the software adapter at once: they take turns now. The watch's tests forget their guards before their memory is freed (another test's memory could get the address and inherit them), and three more are no longer tied to other tests' memory, the adapter's other work or a busy PC's timing. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/frame.rs | 36 ++++++--- crates/victory-gpu/src/indirect.rs | 17 +++- crates/victory-gpu/src/inplace.rs | 13 ++- crates/victory-gpu/src/lib.rs | 3 +- crates/victory-gpu/src/watch.rs | 108 +++++++++++++++++++++---- crates/victory-hle/src/modules/xmem.rs | 2 +- 6 files changed, 146 insertions(+), 33 deletions(-) diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 798b760..7863e22 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -208,7 +208,8 @@ mod tests { let mut second = 0; assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK); assert!(second > first); - assert!(before.elapsed() <= Duration::from_millis(50)); + // At the tick, not at the time-out (a busy PC may wake it late). + assert!(before.elapsed() <= Duration::from_millis(500)); assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT); // Tokens count frames, a frame started early on a time-out too. let mut early = 0; @@ -226,18 +227,29 @@ mod tests { // origin poll that times out (and starts the frame), then a // blocking flip wait. Each flip takes its own tick. const FLIP: u32 = 2; - assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK); + // (The ticks are far apart, and it may take a few tries: a busy PC + // wakes a wait tens of milliseconds late at times.) + assert_eq!(set_interval(null, null, 60_000, 3, 0), S_OK); let mut token = 0; - let flips: Vec = (0..4) - .map(|_| { - let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); - assert_eq!( - wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), - S_OK - ); - LAST[2].load(Ordering::Relaxed) - }) - .collect(); + let mut four = || -> Vec { + (0..4) + .map(|_| { + let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); + assert_eq!( + wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), + S_OK + ); + LAST[2].load(Ordering::Relaxed) + }) + .collect() + }; + let mut flips = four(); + for _ in 0..10 { + if flips.windows(2).all(|w| w[1] == w[0] + 1) { + break; + } + flips = four(); + } assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}"); // Even when a flip wait begins on the tick another just ended on. let (tick, _) = next_tick(FLIP); diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index af7f010..b8128ea 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -491,7 +491,7 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; @@ -521,10 +521,24 @@ void main() { event: HANDLE, clamp: Clamp, worker: Clamp, + /// Last, so given up last. + _turn: std::sync::MutexGuard<'static, ()>, + } + + /// The software adapter is one test's at a time. Two tests that compile + /// and run shaders on it at once (it is one device for the process) make + /// `d3d10warp.dll` (10.0.26100) crash now and then: access violations in + /// its own shader compiler, on its own worker threads, in 12% of runs of + /// all tests and 3% of runs of these alone on two threads; none in 100 + /// runs one after the other. + pub(crate) fn warp_turn() -> std::sync::MutexGuard<'static, ()> { + static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + TURN.lock().unwrap_or_else(|e| e.into_inner()) } impl WarpHarness { fn new() -> Option { + let turn = warp_turn(); // SAFETY: plain DXGI WARP query and D3D12 test harness setup. unsafe { let factory: IDXGIFactory4 = @@ -563,6 +577,7 @@ void main() { event, clamp, worker, + _turn: turn, }) } } diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 25461df..bcafed8 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -1099,6 +1099,7 @@ mod tests { /// driver is what a run with `VICTORY_INPLACE_PROBE=1` adds. #[test] fn warp_probe_opens_title_like_memory_and_the_gpu_sees_its_bytes() { + let _turn = crate::indirect::tests::warp_turn(); let Some(device) = warp() else { return }; if device.cast::().is_err() { eprintln!("no ID3D12Device13 here: parts of an allocation cannot be opened"); @@ -1122,6 +1123,7 @@ mod tests { /// whole is turned down without asking the host. #[test] fn warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset() { + let _turn = crate::indirect::tests::warp_turn(); let Some(device) = warp() else { return }; if device.cast::().is_err() { return; @@ -1142,7 +1144,16 @@ mod tests { assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address"); drop(placed); // Half of it decommitted: turned down, the host not asked. - assert_ne!(mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT), 0); + // The heap lets go of the pages a moment after its last + // reference, if the adapter is busy with other tests' work. + let gone = (0..500).any(|_| { + let done = mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(gone, "the heap keeps the pages"); assert!(matches!(place_part(&device, start, len), Err(None))); mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); } diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 2ecf3ab..ab6102e 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -68,5 +68,6 @@ pub use host::on_failure; pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; #[cfg(windows)] pub use watch::{ - title_memory_reading, title_memory_remapped, title_memory_remapping, writing as kernel_will_write, + title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping, + writing as kernel_will_write, }; diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 27774d6..74b0d80 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -732,10 +732,38 @@ pub fn title_memory_reading_now() -> Option { } } -/// The runtime mapped or unmapped title memory `[at, at + len)`: what it -/// shows is new and read-write, so it is no longer guarded (nor known -/// unmapped). +/// The runtime mapped title memory `[at, at + len)`: what it shows is new, +/// so it is no longer guarded (nor known unmapped), and read-write. +/// +/// The view is there before we are told of it, and a copy's refresh on +/// another thread may have guarded its blocks in between (it finds blocks +/// it knew absent committed, and holds [`GUARDS`], which we wait for). +/// Forgetting such a block and leaving it read-only would make the title's +/// next write to it an access violation nobody takes (`on_write` finds it +/// neither guarded nor writable) and a kernel read into it fail, so the +/// write access is given back. pub fn title_memory_remapped(at: usize, len: usize) { + open(&mut title_memory_changed(at, len), at, at.saturating_add(len)); +} + +/// The runtime is about to unmap title memory `[at, at + len)`: it is +/// nothing of ours any more. Its protection goes with it. +pub fn title_memory_unmapping(at: usize, len: usize) { + let mut g = title_memory_changed(at, len); + let blocks: Vec = g + .protected + .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) + .copied() + .collect(); + for block in blocks { + g.protected.remove(&block); + g.clean.remove(&block); + } +} + +/// Tells what keeps track of what title memory shows; the guards, with no +/// block of the range known unmapped. +fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, Guards> { // A placed texture there arrives, goes or changes with no descriptor // written. crate::descriptor::host::remapped(at, len); @@ -745,15 +773,11 @@ pub fn title_memory_remapped(at: usize, len: usize) { 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).copied().collect(); for block in absent { g.absent.remove(&block); } - let blocks: Vec = g.protected.range(range).copied().collect(); - for block in blocks { - g.protected.remove(&block); - g.clean.remove(&block); - } + g } /// Registers the handler that takes writes to guarded blocks, once, ahead @@ -843,16 +867,18 @@ mod tests { } as usize; assert_ne!(p, 0); let (start, end) = (p, p + 4 * PAGE); - let (_, before) = writes(start, end, false).expect("watched"); - assert!(before.is_empty()); + // The journal may hold pages of another test's memory that was here. + let (none, before) = writes(start, end, false).expect("watched"); + assert!(before.iter().all(|&(_, w)| w < none), "{before:?}"); // SAFETY: committed pages of ours. unsafe { ((p + PAGE + 8) as *mut u8).write(1) }; let (now, after) = writes(start, end, false).expect("watched"); - assert_eq!(after, [(p / PAGE + 1, now)]); + let new = |w: Vec<(usize, u64)>| w.into_iter().filter(|w| w.1 > none).collect::>(); + assert_eq!(new(after), [(p / PAGE + 1, now)]); // Another asker after the kernel's bit was cleared still sees it. let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched"); assert!(later > now); - assert_eq!(again, [(p / PAGE + 1, now)]); + assert_eq!(new(again), [(p / PAGE + 1, now)]); let mut plain = vec![0u8; PAGE]; assert!( writes( @@ -911,6 +937,9 @@ mod tests { guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect()) ); + // Before the view goes, as the runtime does: the address may be + // another test's the moment it is free. + title_memory_unmapping(view, 2 * BLOCK); // SAFETY: our view. unsafe { UnmapViewOfFile( @@ -919,7 +948,52 @@ mod tests { }, ) }; - title_memory_remapped(view, 2 * BLOCK); + } + + /// The runtime maps a view and then tells us; a copy's refresh on another + /// thread can guard it in between. Told, it is the title's to write: a + /// block left read-only and forgotten would be an access violation in + /// title code. + #[test] + fn a_block_guarded_before_we_were_told_of_its_view_can_be_written() { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile, + }; + // SAFETY: a pagefile section of two blocks, mapped read-write; the + // view holds it. + let view = unsafe { + let section = CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK); + CloseHandle(section); + view + }; + let at = view.Value as usize; + assert_ne!(at, 0); + // The refresh, then the runtime's word. + assert!(guard(at, at + 2 * BLOCK).is_some()); + assert!(!writable(at) && !writable(at + BLOCK)); + title_memory_remapped(at, 2 * BLOCK); + assert!(writable(at) && writable(at + BLOCK)); + // SAFETY: inside the view; a fault would end the process. + unsafe { ((at + 8) as *mut u8).write_volatile(1) }; + // Looked at again as new, and guarded again. + assert_eq!( + guard(at, at + 2 * BLOCK), + Some((at / PAGE..at / PAGE + 2).collect()) + ); + assert!(!writable(at)); + title_memory_unmapping(at, 2 * BLOCK); + // SAFETY: our view. + unsafe { UnmapViewOfFile(view) }; } #[test] @@ -934,7 +1008,7 @@ mod tests { struct View(MEMORY_MAPPED_VIEW_ADDRESS); impl Drop for View { fn drop(&mut self) { - title_memory_remapped(self.0.Value as usize, SIZE); + title_memory_unmapping(self.0.Value as usize, SIZE); // SAFETY: our view is still mapped. unsafe { UnmapViewOfFile(self.0) }; } @@ -1060,6 +1134,7 @@ mod tests { let mut local = [0u8; 16]; let at = local.as_mut_ptr() as usize; assert!(!is_view(at, at + local.len())); + title_memory_unmapping(p, 3 * BLOCK); // SAFETY: our views and placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); @@ -1069,7 +1144,6 @@ mod tests { } windows_sys::Win32::Foundation::CloseHandle(section); } - title_memory_remapped(p, 3 * BLOCK); } /// Blocks of a placeholder between views are reported once, then not @@ -1144,6 +1218,7 @@ mod tests { title_memory_remapped(p + BLOCK, BLOCK); assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + title_memory_unmapping(p, 3 * BLOCK); // SAFETY: our views and placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); @@ -1153,7 +1228,6 @@ mod tests { } windows_sys::Win32::Foundation::CloseHandle(section); } - title_memory_remapped(p, 3 * BLOCK); } /// A write or mapping that runs past the end of the address space (a diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index fe5b4c5..56d56ca 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -1028,7 +1028,7 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { continue; }; physical.forget_view(at, size, &slice); - victory_gpu::title_memory_remapped(at, size); + victory_gpu::title_memory_unmapping(at, size); // SAFETY: a view we mapped; it becomes a placeholder again. unsafe { UnmapViewOfFile2( From 875a63a49d725eee0ec3c565f0474151365da212 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 22:35:28 -0600 Subject: [PATCH 173/445] Buffers loaded past the cache are coherent; record counts of buffers picked from the heap A raw UAV buffer the program loads with GLC is globally coherent on the host (the upscaler's waits for other groups, the ped blend shapes): a load in a loop that only waits would be made once otherwise. Ten shaders change by it. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 67 +++++++++++++++----- crates/victory-shader/src/emit/size_tests.rs | 32 ++++++++++ 2 files changed, 83 insertions(+), 16 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index b4df3c2..899255f 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -254,6 +254,11 @@ struct Lower<'a> { stale: HashSet, /// See [`ordered_section`] (pixel programs). ordered: HashSet, + /// Raw UAV buffers (see [`Lower::entry`]) the program loads from past its + /// wave's cache (GLC): other groups write what it waits for. On the host + /// they are globally coherent; a load in a loop that only waits would + /// be made once otherwise. + coherent: HashSet<(usize, u32)>, mask_phis: HashMap, pending_masks: Vec<(V, usize, usize)>, data_phis: Vec<(V, usize, usize)>, @@ -1546,6 +1551,7 @@ impl<'a> Lower<'a> { data_phis: Vec::new(), read_phis: HashSet::new(), stale: HashSet::new(), + coherent: HashSet::new(), ordered: if x.native.stage == HwStage::Ps { ordered_section(p) } else { @@ -2219,6 +2225,7 @@ impl<'a> Lower<'a> { fn run(mut self) -> Result { let p = self.x.p; + self.find_coherent(); let order = crate::ir::reverse_postorder(&p.blocks); for (n, &b) in order.iter().enumerate() { self.rpo[b] = n; @@ -2811,15 +2818,7 @@ impl<'a> Lower<'a> { /// the program has an integer atomic on the same table entry, which /// takes no other view. fn is_counter(&self, src: &Source) -> bool { - let entry = |s: &Source| match s { - Source::Loaded { load, first } => self - .scalar - .get(load) - .filter(|a| a.dynamic.is_none()) - .map(|a| (a.param, a.offset + 4 * u32::from(*first))), - _ => None, - }; - let Some(this) = entry(src) else { + let Some(this) = self.entry(src) else { return false; }; self.x.res.descriptors.iter().any(|d| { @@ -2838,10 +2837,37 @@ impl<'a> Lower<'a> { | "image_atomic_umin" | "image_atomic_umax" ) - && entry(&d.source) == Some(this) + && self.entry(&d.source) == Some(this) }) } + /// Which table entry `src` is loaded from: its root parameter and byte. + fn entry(&self, src: &Source) -> Option<(usize, u32)> { + let Source::Loaded { load, first } = src else { + return None; + }; + let a = self.scalar.get(load).filter(|a| a.dynamic.is_none())?; + Some((a.param, a.offset + 4 * u32::from(*first))) + } + + /// See [`Lower::coherent`]. + fn find_coherent(&mut self) { + let found: Vec<_> = self + .x + .res + .descriptors + .iter() + .filter(|d| { + let i = &self.x.p.blocks[d.site.0].insts[d.site.1]; + matches!(&i.fields, Fields::Buffer { cache, .. } if cache.glc) + && i.name().starts_with("buffer_load_dword") + && self.used_kind(&d.source).is_some_and(|u| u.kind == ResourceType::Uav) + }) + .filter_map(|d| self.entry(&d.source)) + .collect(); + self.coherent.extend(found); + } + /// The kind of a view no instruction uses (in this program, or through /// another load of its address), by what the code reads of the /// descriptor the load `inst` at `site` writes to the SGPRs from `code`: @@ -3281,11 +3307,6 @@ impl<'a> Lower<'a> { if self.exchange.is_some() && !self.local { need(made.unwrap_or(0)); } - if std::env::var_os("VICTORY_DESC_WHY").is_some() { - let by = made.map(|b| &self.x.p.blocks[b]); - let def = by.and_then(|b| b.insts.iter().find(|i| i.writes.iter().any(|w| w.1 == lo))); - eprintln!("MASK-WHY {v:?} made in {made:?} by {:?} at {:x?}; read in block at {:#x}; phi {}", def.map(|i| i.name()), def.map(|i| i.machine.offset), self.x.p.blocks[self.cur_ir].offset, self.phi_at.contains_key(&lo)); - } return Err(MASK_ELSEWHERE); } let (x, y) = match self.ballots.get(&lo) { @@ -6089,9 +6110,20 @@ impl<'a> Lower<'a> { // A raw view counts bytes; the descriptor's record count is in elements. let n = field(self, 0); let stride = used.map_or(0, |u| u.stride); + let counted = inst + .write(Reg::S(code + first + 2)) + .is_some_and(|v| self.read_as_number(v)); let n = if props.0 & 0xFF == 11 && stride > 1 { let k = self.s.m.i32(stride); self.s.m.bin(c, Bin::UDiv, n, k) + } else if props.0 & 0xFF == 11 + && counted + && let Some(stride) = self.slot_stride(&src)? + { + // Picked from the heap: the host's table has the stride. + let (i32t, one) = (self.s.t.i32, self.s.m.i32(1)); + let k = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 39, &[stride, one]); + self.s.m.bin(c, Bin::UDiv, n, k) } else { n }; @@ -10765,7 +10797,10 @@ impl<'a> Lower<'a> { return Ok(()); } let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav); - let u = if uav { 0x1000 } else { 0 }; + let mut u = if uav { 0x1000 } else { 0 }; + if uav && !typed && self.entry(src).is_some_and(|e| self.coherent.contains(&e)) { + u |= 0x4000; + } let iu = self.s.m.undef(self.s.t.i32); if let Some((bits, signed)) = narrow { // Below a dword: raw buffers are read and written in dwords on diff --git a/crates/victory-shader/src/emit/size_tests.rs b/crates/victory-shader/src/emit/size_tests.rs index 5c6c40e..a0023b8 100644 --- a/crates/victory-shader/src/emit/size_tests.rs +++ b/crates/victory-shader/src/emit/size_tests.rs @@ -266,3 +266,35 @@ fn a_counter_texture_is_set_by_a_store_of_one_channel() { // A store of two channels says nothing about the view. assert!(program([0xF020_1308, 0x0002_0300], 0x7E06_0289).is_err()); } + +/// A load past the wave's cache (GLC) of a buffer other groups write: its +/// view is globally coherent on the host, as is every access to it. +#[test] +fn a_buffer_loaded_past_the_cache_is_coherent() { + let program = |load: u32| { + let words = [ + 0x7E04_028Bu32, // v_mov_b32 v2, 11 + 0xE070_0008, // buffer_store_dword v2, off, s[20:23], 0 offset:8 + 0x8005_0200, + load, // buffer_load_dword v3, off, s[20:23], 0 offset:8 + 0x8005_0300, + 0x7E08_0503, // v_readfirstlane_b32 s4, v3 + 0xBE85_0380, // s_mov_b32 s5, 0 + ]; + build(&[TABLE, &words, STORE].concat(), (8, 0)).expect("translates") + }; + let (plain, coherent) = (program(0xE030_0008), program(0xE030_C008)); + // the annotations of the store's and the load's handles + assert_ne!(plain.dxil, coherent.dxil); + let texel = [[0.0; 4]; 1]; + let views = [ + View::Texture(1, 1, &texel), + View::Texture(1, 1, &texel), + View::RawUav(3), + ]; + for shader in [&plain, &coherent] { + for (label, got) in run(shader, &views) { + assert_eq!(got[..3], [11, 0, 11], "{label}"); + } + } +} From 151816ce6d56eb262ed59afbf0afb779d4f522d6 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 22:37:55 -0600 Subject: [PATCH 174/445] Title bytes under overlapping shader writes once; textures on several threads; cheaper walks of a submission's steps Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 116 ++++++++++++++++++++++++++----- crates/victory-gpu/src/shadow.rs | 5 ++ 2 files changed, 104 insertions(+), 17 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 9e2fb5a..274c3c6 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2438,14 +2438,21 @@ fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc, usize, usize)> = Vec::new(); + // Where each copy is in it, if shaders may be writing it (none begins to + // while this runs): a frame has 20,000 refreshes of some 4,500 copies. + let mut places: ByCopy> = ByCopy::default(); for list in runs { for step in &list.deferred().copies { - if let Step::Refresh(shadow, address, len) = step - && shadow.writes_pending() - { - match spans.iter_mut().find(|s| Arc::ptr_eq(&s.0, shadow)) { - Some(s) => (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len)), - None => spans.push((shadow.clone(), *address, *address + *len)), + if let Step::Refresh(shadow, address, len) = step { + let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| { + shadow.writes_pending().then(|| { + spans.push((shadow.clone(), *address, *address + *len)); + spans.len() - 1 + }) + }); + if let Some(i) = *place { + let s = &mut spans[i]; + (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len)); } } } @@ -3029,18 +3036,22 @@ fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool { /// One list's lock at a time: a submission may name a list twice. fn declared_writes(runs: &[&HostList]) -> Vec { let mut back: Vec = Vec::new(); + // Where each copy is in it, and the ranges seen: dispatches declare the + // same ranges thousands of times a frame. + let mut places: ByCopy = ByCopy::default(); + let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault>::default(); for list in runs { for step in &list.deferred().copies { if let Step::GpuWrite(shadow, address, len) = step { - let range = (*address, *address + *len); - match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { - Some((_, ranges)) => { - if !ranges.contains(&range) { - ranges.push(range); - } - } - None => back.push((shadow.clone(), vec![range])), + let key = std::sync::Arc::as_ptr(shadow) as usize; + if !seen.insert((key, *address, *len)) { + continue; } + let i = *places.entry(key).or_insert_with(|| { + back.push((shadow.clone(), Vec::new())); + back.len() - 1 + }); + back[i].1.push((*address, *address + *len)); } } } @@ -5977,7 +5988,10 @@ impl HostList { } Step::Texture(staging) => { if batch.texture_due(staging) { - staging.refresh(); + batch.due.push(staging.clone()); + if !wide_textures() { + batch.refresh_textures(); + } } continue; } @@ -6168,8 +6182,29 @@ struct Batch { /// for every refresh of a submission was tens of millions of /// comparisons a frame. index: ByCopy, - /// Staging buffers (by address) refreshed since the last title write. + /// Staging buffers (by address) refreshed since the last title write, + /// or due to be. textures: std::collections::HashSet, + /// Those due ([`Batch::refresh_textures`]). + due: Vec>, +} + +/// Whether a submission's textures are brought up to date on several +/// threads (`VICTORY_WIDE_TEXTURES=0`: one after the other, where the lists +/// name them, as before). +/// +/// They are read, hashed and, if they changed, detiled into their staging +/// buffers: 5 ms a frame of the submitting thread, for some 16 MB. Each has +/// its own buffer, notes and lock, and is refreshed by the title's own +/// threads as it is. They are done before the next step that writes title +/// memory, as the copies' refreshes are, and before the lists go to the +/// card. What is new: the note of a list that its upload takes what the +/// buffer then holds (`texture.rs`, `dirty`) may come ahead of the refresh +/// an earlier list of the submission asked for, not behind it. The texture +/// is then uploaded by a later list too, once more than needed. +fn wide_textures() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0") && wide_refresh()) } impl Batch { @@ -6232,7 +6267,23 @@ impl Batch { self.textures.clear(); } + /// The textures due are brought up to date. + fn refresh_textures(&mut self) { + if self.due.len() < 2 || !wide_textures() { + self.due.drain(..).for_each(|staging| staging.refresh()); + return; + } + // The time counted is the time it took, not the threads' sum. + let started = std::time::Instant::now(); + let before = PREPARING[2].load(Ordering::Relaxed); + let due = std::mem::take(&mut self.due); + crate::shadow::wide_each(due.len(), move |i| due[i].refresh()); + let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before); + PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed); + } + fn flush(&mut self) { + self.refresh_textures(); self.index.clear(); if self.refreshes.is_empty() { return; @@ -7730,7 +7781,7 @@ mod refresh_tests { use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; assert!(crate::safecopy::on()); const LEN: usize = 24 * PAGE; - let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(400); + let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(120); let region = title(LEN, true); let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) }; let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)]; @@ -7896,6 +7947,37 @@ mod refresh_tests { }); } + /// The title's bytes put in under shader writes, for a copy of 174 MB + /// whose shader writes were declared as 40 ranges that overlap, with 12 + /// pages written since. Run with `--ignored --nocapture`, and with + /// `VICTORY_LIGHT_REFRESH=0` for the way it was. + #[test] + #[ignore] + fn bytes_under_overlapping_ranges() { + const BIG: usize = 174 << 20; + let big = title(BIG, true); + // SAFETY (both): the test's own memory. + unsafe { std::ptr::write_bytes(big as *mut u8, 1, BIG) }; + let copy = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true); + copy.update(big, BIG); + copy.take_dirty(); + for i in 0..40 { + copy.writing(big + i * 5920, BIG - i * 5920); + } + let mut best = f64::MAX; + for round in 0..30 { + for i in 0..12 { + unsafe { ((big + (i * 211 + round) % 2700 * PAGE + 64) as *mut u8).write_volatile(round as u8) }; + } + let started = std::time::Instant::now(); + let mut runs = usize::MAX; + assert!(!copy.merge_under_writes(big, BIG, &mut runs)); + best = best.min(started.elapsed().as_secs_f64() * 1e3); + copy.take_dirty(); + } + println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light()); + } + /// A range nothing wrote is known to be as it was, at its ends too, and /// is so no more once something wrote it. #[test] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 091c5ed..ba1f6fa 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2579,6 +2579,11 @@ impl Shadow { note_stale(0); return true; } + // The declared ranges overlap (views of the title's whole heap from + // dozens of offsets): as one range each page is asked about and + // compared once. Every byte of it is in a declared range, and of a + // 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 { From 68e10e57d6ee5ad6cce5ff189eaca7cae31350db Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 22:53:34 -0600 Subject: [PATCH 175/445] A DirectStorage queue starts its requests at the title's submit, not at half its capacity The title maps the pages of a batch, and fills in their page lists, in its own submit (image +0xe88f0): first the batch's mapping list (+0xf2c470, which writes the page lists at +0x55aa6a0), then the status entry, then our Submit. A list is a piece of one table, a number per 64 KiB of address range, that is only ever overwritten. Our queue submitted itself at half its capacity (2,079 of 4,159), which the title's batches (up to 4,095) pass three or four times a load: those requests ran up to 0.6 s before the lists were filled in, on page 0 (waited for) or on the page numbers an earlier mapping had left (known, so written: somebody else's memory). - A queue submits itself only when it is full of commands nobody submitted. VICTORY_DSTORAGE_HALF=1: at half, as before. - A list that changes during the write has its new pages written too. - "page list was not filled in yet" is said (as a warning) only of lists that were not: nearly all of its lines were waits for the page table's lock. - A read of a file the host refuses is logged and tried again, its destination opened again before. - VICTORY_DSTORAGE_TRACE=1 (a line per batch, and per request something is wrong with), 2 (every request). Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/dstorage.rs | 515 +++++++++++++++++++-- crates/victory-hle/src/modules/xmem.rs | 15 + 2 files changed, 479 insertions(+), 51 deletions(-) diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 87e635e..0c5c430 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -4,6 +4,10 @@ //! slots here are the ones the title calls, read from its call //! sites. Slots nobody has needed yet log their offset. //! +//! A request starts once it is submitted, not before: the title maps the +//! pages a batch is read into, and fills in their page lists, in its own +//! submit (`submit`). +//! //! Submitted requests of every queue run on one pool of workers, as the //! console's hardware runs them: in parallel, started in queue order, //! queues served by weighted round robin over their priorities (about 10x @@ -370,7 +374,7 @@ struct Lane { unsubmitted: Vec, /// Submitted, by sequence number: reads not started, status entries /// not written, reads running, and failures not yet reported. - reads: VecDeque<(u64, Request)>, + reads: VecDeque<(u64, Read)>, statuses: VecDeque<(u64, Status)>, running: BTreeSet, failures: BTreeMap, @@ -387,6 +391,7 @@ struct Job { lane: u64, seq: u64, request: Request, + note: Note, staging: u64, } @@ -498,8 +503,12 @@ fn work(scheduler: &'static Scheduler) { }; drop(lanes); let started = std::time::Instant::now(); + let traced = Traced::start(&job); let result = execute(&job.request); walls_request(&job.request, &result, started); + if let Some(traced) = traced { + traced.end(&job, &result); + } lanes = scheduler.lock(); lanes.finish(&job, result); lanes.count(&job, started); @@ -555,7 +564,7 @@ impl Lanes { .filter_map(|(&id, l)| Some((l.clock, l.reads.front()?.0, id))) .min()?; let lane = self.lanes.get_mut(&id)?; - let &(seq, request) = lane.reads.front()?; + let &(seq, Read { request, note }) = lane.reads.front()?; let staging = staging_bytes(&request); if self.staged > 0 && self.staged + staging > self.staging { self.starved = true; @@ -574,6 +583,7 @@ impl Lanes { lane: id, seq, request, + note, staging, }) } @@ -589,8 +599,9 @@ impl Lanes { } } - /// Moves a queue's enqueued commands to the workers. - fn submit(&mut self, id: u64) { + /// Moves a queue's enqueued commands to the workers; `early` when the + /// title has not asked for it ([`queue`]). + fn submit(&mut self, id: u64, early: bool) { let Some(class) = self.lanes.get(&id).map(|l| l.class) else { return; }; @@ -609,11 +620,15 @@ impl Lanes { if lane.reads.is_empty() { lane.clock = lane.clock.max(self.lane_now[class]); } + trace_batch(id, &lane.unsubmitted, early); for command in std::mem::take(&mut lane.unsubmitted) { let seq = self.next_seq; self.next_seq += 1; match command { - Command::Read(request) => lane.reads.push_back((seq, request)), + Command::Read(mut read) => { + read.note.submitted(&read.request, early); + lane.reads.push_back((seq, read)); + } Command::Status(status) => lane.statuses.push_back((seq, status)), } } @@ -734,10 +749,205 @@ const MEMORY_SOURCE: u64 = 1 << 22; const PAGE: usize = 64 * 1024; enum Command { - Read(Request), + Read(Read), Status(Status), } +/// An enqueued request, and what the trace knows of it. +#[derive(Clone, Copy)] +struct Read { + request: Request, + note: Note, +} + +/// The streaming trace (`VICTORY_DSTORAGE_TRACE`): 0 or unset: off; 1: a +/// line for every batch, and for every request whose page list, or whose +/// pages' mapping, changed when it should not have, or whose bytes another +/// running request writes too; 2: a line for every request. +fn trace() -> u8 { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + std::env::var("VICTORY_DSTORAGE_TRACE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0) + }) +} + +/// When a request was enqueued and submitted, and what its page list held +/// then (a hash; 0 without a list). Only filled in for the trace, but for +/// `early`. +#[derive(Clone, Copy, Default)] +struct Note { + enqueued: Option, + at_enqueue: u64, + submitted: Option, + at_submit: u64, + /// Started before the title's submit. + early: bool, +} + +impl Note { + fn enqueued(request: &Request) -> Note { + match trace() { + 0 => Note::default(), + _ => Note { + enqueued: Some(std::time::Instant::now()), + at_enqueue: list_hash(request), + ..Note::default() + }, + } + } + + fn submitted(&mut self, request: &Request, early: bool) { + self.early = early; + if trace() > 0 { + self.submitted = Some(std::time::Instant::now()); + self.at_submit = list_hash(request); + } + } +} + +/// A hash of the page numbers a request's list holds now; 0 without one. +fn list_hash(request: &Request) -> u64 { + list_of(request).map_or(0, |pages| { + // FNV-1a; never 0. + pages.iter().fold(0xcbf2_9ce4_8422_2325_u64, |h, &p| (h ^ p as u64).wrapping_mul(0x100_0000_01b3)) | 1 + }) +} + +/// The page numbers a request's list holds now. +fn list_of(request: &Request) -> Option> { + (request.options & PAGE_DESTINATION != 0 && !request.destination.is_null()).then(|| { + let (offset, len) = Traced::bytes(request); + read_list(request.destination.cast(), offset, len) + }) +} + +/// The trace's line for a batch: how much of it goes to pages, and how many +/// of those lists the title filled in since it enqueued them (its protocol: +/// most of them; a batch started `early` runs on what they held before). +fn trace_batch(queue: u64, commands: &[Command], early: bool) { + if trace() == 0 { + return; + } + let reads = || { + commands.iter().filter_map(|c| match c { + Command::Read(read) => Some(read), + Command::Status(_) => None, + }) + }; + let (mut to_pages, mut filled, mut empty) = (0, 0, 0); + for read in reads().filter(|r| r.request.options & PAGE_DESTINATION != 0) { + to_pages += 1; + filled += usize::from(list_hash(&read.request) != read.note.at_enqueue); + empty += usize::from(list_of(&read.request).is_some_and(|l| l.contains(&0))); + } + tracing::info!( + queue, + early, + commands = commands.len(), + to_pages, + lists_filled_since_enqueued = filled, + lists_not_filled = empty, + oldest_ms = reads().next().and_then(|r| r.note.enqueued).map_or(0, |t| t.elapsed().as_millis() as u64), + "dstorage trace: a batch" + ); +} + +/// The bytes of pages that running requests write, for the trace: by page +/// number, the request and its bytes in the page. +type Writers = HashMap>; +static WRITERS: Mutex> = Mutex::new(None); + +/// A running request in the trace. +struct Traced { + pages: Vec, + at_start: u64, + shown: Vec<(usize, usize)>, +} + +impl Traced { + fn start(job: &Job) -> Option { + if trace() == 0 { + return None; + } + let at_start = list_hash(&job.request); + let pages = list_of(&job.request).unwrap_or_default(); + let (offset, len) = Traced::bytes(&job.request); + { + let mut writers = WRITERS.lock().unwrap_or_else(|e| e.into_inner()); + let writers = writers.get_or_insert_with(Writers::new); + for (i, &page) in pages.iter().enumerate().filter(|(_, p)| **p != 0) { + let from = offset.max(i * PAGE) - i * PAGE; + let to = (offset + len).min((i + 1) * PAGE) - i * PAGE; + let others = writers.entry(page).or_default(); + for &(other, a, b) in others.iter().filter(|&&(_, a, b)| a < to && from < b) { + tracing::warn!( + page, + from, + to, + seq = job.seq, + other, + other_from = a, + other_to = b, + "dstorage trace: two running requests write the same bytes of a page" + ); + } + others.push((job.seq, from, to)); + } + } + let shown = super::xmem::pages_shown(&pages, offset, len); + Some(Traced { pages, at_start, shown }) + } + + /// Where in its first page a request's destination starts, and its size. + fn bytes(request: &Request) -> (usize, usize) { + ((request.page_offset & 0xffff) as usize, request.destination_size as usize) + } + + fn end(self, job: &Job, result: &Result<(), HRESULT>) { + let (offset, len) = Traced::bytes(&job.request); + let at_end = list_hash(&job.request); + let moved = super::xmem::pages_shown(&self.pages, offset, len) != self.shown; + { + let mut writers = WRITERS.lock().unwrap_or_else(|e| e.into_inner()); + let writers = writers.get_or_insert_with(Writers::new); + for page in &self.pages { + if let Some(others) = writers.get_mut(page) { + others.retain(|w| w.0 != job.seq); + if others.is_empty() { + writers.remove(page); + } + } + } + } + let note = &job.note; + // A request of the title's submit: its list is filled in by then, + // and stays. + let late = note.at_submit != self.at_start || self.at_start != at_end; + if trace() < 2 && !late && !moved && !note.early && result.is_ok() { + return; + } + let since = |t: Option| t.map_or(0, |t| t.elapsed().as_millis() as u64); + tracing::info!( + seq = job.seq, + queue = job.lane, + early = note.early, + list = format_args!("{:p}", job.request.destination), + page_offset = job.request.page_offset, + size = len, + enqueued_ms_ago = since(note.enqueued), + submitted_ms_ago = since(note.submitted), + at_enqueue = format_args!("{:016x}", note.at_enqueue), + at_submit = format_args!("{:016x}", note.at_submit), + at_start = format_args!("{:016x}", self.at_start), + at_end = format_args!("{at_end:016x}"), + list_changed_late = late, + mapping_changed = moved, + first_page = self.pages.first().copied().unwrap_or(0), + ok = result.is_ok(), + "dstorage trace: a request" + ); + } +} /// A status entry to write, holding a reference on its array. struct Status { @@ -763,7 +973,8 @@ extern "system" fn enqueue_request(this: QueueRef, request: *const Request) { let Some(&request) = (unsafe { request.as_ref() }) else { return; }; - queue(this, Command::Read(request)); + let note = Note::enqueued(&request); + queue(this, Command::Read(Read { request, note })); } extern "system" fn enqueue_status(this: QueueRef, array: Array, index: u32) { @@ -780,8 +991,25 @@ extern "system" fn enqueue_status(this: QueueRef, array: Array, index: u32) { queue(this, Command::Status(Status { array, index })); } -/// Adds a command to the queue; blocks while the queue is full, and -/// submits on its own once half of it is enqueued, as the console does. +/// Whether a queue submits itself once half of it is enqueued +/// (`VICTORY_DSTORAGE_HALF=1`), as DirectStorage for the PC does and as ours +/// did. The title's batches (up to 4,095 requests, in queues of 4,159) hold +/// more than half now and then, and it maps the pages they go to and fills +/// in their page lists in its own submit, after it has enqueued them all +/// (image +0xe88f0: the batch's mapping list first, at +0xf2c470, which +/// writes the page lists at +0x55aa6a0; then the status entry; then our +/// submit). So 2,079 requests, three or four times a load, ran on lists of +/// page 0, or, worse, of the pages the addresses had shown before: their +/// data went into whatever those pages belonged to by then, and the pages it +/// was for stayed as they were. +fn half_submits() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_DSTORAGE_HALF").is_some_and(|v| v == "1")) +} + +/// Adds a command to the queue; blocks while the queue is full. A queue +/// that is full of commands nobody submitted submits itself, since nothing +/// else could make room. fn queue(this: QueueRef, command: Command) { // SAFETY: a queue we created and the title still holds. let id = unsafe { &*this }.state.id; @@ -797,6 +1025,16 @@ fn queue(this: QueueRef, command: Command) { if lane.entries() + 1 < lane.capacity.max(2) { break; } + if !lane.unsubmitted.is_empty() && lane.reads.is_empty() && lane.running.is_empty() { + tracing::warn!( + queue = id, + commands = lane.unsubmitted.len(), + "dstorage: a queue full of commands that are not submitted submits itself" + ); + lanes.submit(id, true); + scheduler.work.notify_all(); + continue; + } lanes = scheduler .finished .wait(lanes) @@ -806,12 +1044,15 @@ fn queue(this: QueueRef, command: Command) { return; }; lane.unsubmitted.push(command); - if lane.unsubmitted.len() >= (lane.capacity / 2).max(1) { - lanes.submit(id); + if half_submits() && lane.unsubmitted.len() >= (lane.capacity / 2).max(1) { + lanes.submit(id, true); scheduler.work.notify_all(); } } +/// The title's submit, where its page lists become valid ([`half_submits`]): +/// the pages are mapped just before, also those under addresses without a +/// list (memory only the CPU sees). extern "system" fn submit(this: QueueRef) { // SAFETY: as above. let id = unsafe { &*this }.state.id; @@ -821,7 +1062,7 @@ extern "system" fn submit(this: QueueRef) { let mut lanes = scheduler.lock(); let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len()); tracing::debug!(commands = pending, "dstorage: submit"); - lanes.submit(id); + lanes.submit(id, false); scheduler.work.notify_all(); } @@ -996,6 +1237,9 @@ fn read_source(request: &Request) -> Result, HRESULT> { /// Nanoseconds workers spent reading files, for the debug summary. static READING: AtomicU64 = AtomicU64::new(0); +/// How often a read the host refuses is tried again (about 0.25 s in all). +const READ_RETRIES: u32 = 8; + /// Fills `out` (the source size) from the request's file or memory. fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { if request.options & MEMORY_SOURCE != 0 { @@ -1008,16 +1252,37 @@ fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { .state .file; let started = std::time::Instant::now(); - let mut done = 0; + let (mut done, mut tries) = (0, 0); let result = loop { if done == out.len() { break Ok(()); } - match file.seek_read(&mut out[done..], request.offset + done as u64) { + let error = match file.seek_read(&mut out[done..], request.offset + done as u64) { Ok(0) => break Err(END_OF_FILE), - Ok(n) => done += n, - Err(error) => break Err(from_win32(&error)), + Ok(n) => { + done += n; + continue; + } + Err(error) => error, + }; + // Title memory the GPU side guards again in the moment between our + // opening it and the kernel's write fails the read (and a busy host + // can refuse one): opened again and tried again, since the title + // never learns of a failed read. + tracing::warn!( + %error, + offset = request.offset, + size = out.len(), + done, + tries, + "dstorage: a read of the file failed" + ); + if tries == READ_RETRIES { + break Err(from_win32(&error)); } + std::thread::sleep(std::time::Duration::from_millis(1 << tries)); + tries += 1; + victory_gpu::kernel_will_write(out.as_ptr() as usize + done, out.len() - done); }; READING.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); result @@ -1031,7 +1296,7 @@ fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { fn into_destination( request: &Request, len: usize, - fill: impl FnOnce(&mut [u8]) -> Result, + mut fill: impl FnMut(&mut [u8]) -> Result, ) -> Result<(), HRESULT> { if request.options & PAGE_DESTINATION == 0 { // Raw reads land through the kernel, which does not fault into the @@ -1049,7 +1314,38 @@ fn into_destination( return filled; } let offset = (request.page_offset & 0xffff) as usize; - let pages = &page_list(request.destination.cast(), offset, len)[..]; + let list = request.destination.cast(); + let mut pages = page_list(list, offset, len); + // The title sees its destination through the pages its list names: if + // it names others by the time the data is written, they get it as well. + // (Said aloud: by the title's protocol a submitted request's list stays + // as it is.) + for _ in 0..3 { + into_pages(&pages, offset, len, &mut fill)?; + let now = read_list(list, offset, len); + if now == pages || !super::xmem::pages_known(&now, offset, len) { + break; + } + tracing::warn!( + list = format_args!("{list:p}"), + offset, + len, + first = pages.first(), + first_now = now.first(), + "dstorage: a destination's page list changed during the write; written to its new pages too" + ); + pages = now; + } + Ok(()) +} + +/// Runs `fill` on `len` bytes of `pages`, from `offset` into the first. +fn into_pages( + pages: &[usize], + offset: usize, + len: usize, + mut fill: impl FnMut(&mut [u8]) -> Result, +) -> Result<(), HRESULT> { // Consecutive pages of one allocation (the usual case): written in // place through one view. if let Some(mut window) = super::xmem::page_window(pages, offset, len) { @@ -1097,35 +1393,44 @@ fn into_destination( } } -/// The request's page numbers, one per 64 KiB of destination. The title -/// queues a request before it has filled its page list in, and a worker that -/// reads the list at once finds page 0 in it (pages of models and textures -/// that were then never written: walls missing for the whole run). So a list +/// The page numbers `list` holds now, one per 64 KiB of destination. +fn read_list(list: *const usize, offset: usize, len: usize) -> Vec { + (0..(offset + len).div_ceil(PAGE)) + // SAFETY: the title passes a page number per 64 KiB of + // destination, which holds at least `len` bytes from `offset`; + // it may be writing them. + .map(|i| unsafe { list.add(i).read_volatile() }) + .collect() +} + +/// The request's page numbers. A list is the part of the title's own page +/// table (one number per 64 KiB of its address range) that describes the +/// destination, filled in when the title submits the batch, so it is valid +/// here. It is only ever overwritten: an address the title unmapped keeps +/// the number of the page it had, which the title maps elsewhere soon after, +/// so a number the title owns says nothing about whether it is the right +/// one ([`half_submits`]). Page 0 does (an address never mapped yet): a list /// with a page the title does not own is read again for a while, up to /// 1.5 s; what it holds then is used as it is. fn page_list(list: *const usize, offset: usize, len: usize) -> Vec { - let read = || -> Vec { - (0..(offset + len).div_ceil(PAGE)) - // SAFETY: the title passes a page number per 64 KiB of - // destination, which holds at least `len` bytes from `offset`; - // it may be writing them. - .map(|i| unsafe { list.add(i).read_volatile() }) - .collect() - }; + let mut pages = read_list(list, offset, len); + if super::xmem::pages_known(&pages, offset, len) { + return pages; + } + // Timed from here: what took long before was the lock on the page table + // (which the title's mapping calls hold), not the list. let started = std::time::Instant::now(); - let mut pages = read(); - while !super::xmem::pages_known(&pages, offset, len) && started.elapsed().as_millis() < 1500 { + let mut known = false; + while !known && started.elapsed().as_millis() < 1500 { std::thread::sleep(std::time::Duration::from_millis(1)); - pages = read(); - } - let waited = started.elapsed(); - if waited.as_millis() >= 1 { - tracing::info!( - ms = waited.as_millis() as u64, - known = super::xmem::pages_known(&pages, offset, len), - "dstorage: a destination's page list was not filled in yet" - ); + pages = read_list(list, offset, len); + known = super::xmem::pages_known(&pages, offset, len); } + tracing::warn!( + ms = started.elapsed().as_millis() as u64, + known, + "dstorage: a destination's page list was not filled in yet" + ); pages } @@ -1387,7 +1692,45 @@ mod tests { } #[test] - fn half_a_queue_submits_itself() { + fn half_a_queue_waits_for_the_submit() { + use crate::modules::xmem; + // Two pages the title owns: the one its list still names from + // earlier, and the one it maps for this batch when it submits. + let mut pages = [0usize; 2]; + let mut n = 2; + assert_eq!(xmem::XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1); + let [stale, right] = pages; + let plain = pattern(64); + let mut list = [stale]; + let (queue, array) = (new_queue(1), status_array(1)); + // More than half of the queue's 128. + for i in 0..100 { + let mut r = request( + PAGE_DESTINATION | MEMORY_SOURCE, + list.as_mut_ptr().cast(), + plain.len(), + plain.as_ptr().cast(), + 0, + plain.len(), + ); + r.page_offset = i * 64; + enqueue(queue, &r); + } + std::thread::sleep(Duration::from_millis(50)); + // SAFETY: our own list, which a worker may be reading. + unsafe { std::ptr::write_volatile(list.as_mut_ptr(), right) }; + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + let bytes = |page: usize| -> Vec { + xmem::page_window(&[page], 0, 6400).unwrap().bytes().to_vec() + }; + assert!(bytes(stale) == [0; 6400], "written to the page the list named before"); + assert!(bytes(right) == plain.repeat(100), "not written to the page the list names"); + } + + #[test] + fn a_full_queue_submits_itself() { let (_dir, file) = file_with(&pattern(64)); let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT = call(factory(), 0x50); @@ -1401,11 +1744,80 @@ mod tests { let mut queue = std::ptr::null_mut(); assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK); let array = status_array(1); - let mut out = [0u8; 16]; - enqueue(queue, &request(0, out.as_mut_ptr().cast(), 16, file, 8, 16)); - enqueue_status(queue, array, 0); // the second of four: no submit needed + let mut outs = [[0u8; 16]; 4]; + for out in &mut outs[..2] { + enqueue(queue, &request(0, out.as_mut_ptr().cast(), 16, file, 8, 16)); + } + enqueue_status(queue, array, 0); + std::thread::sleep(Duration::from_millis(20)); + assert_eq!(result(array, 0), E_PENDING, "three of four: not submitted"); + // One more than fits: would wait for good. + for out in &mut outs[2..] { + enqueue(queue, &request(0, out.as_mut_ptr().cast(), 16, file, 8, 16)); + } assert_eq!(wait(array, 0), S_OK); - assert_eq!(out, pattern(64)[8..24]); + void(queue, 0x40); + assert!(outs[..2].iter().all(|out| out[..] == pattern(64)[8..24])); + } + + #[test] + fn a_list_that_changes_during_the_write_has_its_new_pages_written() { + use crate::modules::xmem; + let mut pages = [0usize; 4]; + let mut n = 4; + assert_eq!(xmem::XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1); + // In place (consecutive pages) and through a buffer. + for old in [[pages[0], pages[1]], [pages[1], pages[0]]] { + let new = [pages[3], pages[2]]; + let mut list = old; + let at = list.as_mut_ptr(); + let len = PAGE + 100; + let r = request(PAGE_DESTINATION, at.cast(), len, std::ptr::null(), 0, len); + let mut runs = 0; + let written = into_destination(&r, len, |out| { + runs += 1; + out.fill(0xa5); + // SAFETY: our own list. + unsafe { at.cast::<[usize; 2]>().write_volatile(new) }; + Ok(out.len()) + }); + assert_eq!((written, runs), (Ok(()), 2)); + assert!(xmem::page_window(&new[..1], 0, PAGE).unwrap().bytes().iter().all(|&b| b == 0xa5)); + assert!(xmem::page_window(&new[1..], 0, 100).unwrap().bytes().iter().all(|&b| b == 0xa5)); + for page in new { + xmem::page_window(&[page], 0, PAGE).unwrap().bytes().fill(0); + } + } + } + + #[test] + fn a_read_into_memory_guarded_for_a_moment_is_tried_again() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, PAGE_READONLY, VirtualAlloc, VirtualProtect, + }; + let plain = pattern(3 * 4096); + let (_dir, file) = file_with(&plain); + // SAFETY: a fresh allocation; its middle page is read-only until the + // thread opens it, as a guard of the GPU side's would be. + let at = unsafe { + VirtualAlloc(std::ptr::null(), plain.len(), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) + } as usize; + assert_ne!(at, 0); + let protect = move |to| { + let mut old = 0; + // SAFETY: as above. + unsafe { VirtualProtect((at + 4096) as *const _, 4096, to, &mut old) } + }; + assert_ne!(protect(PAGE_READONLY), 0); + let opener = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(20)); + protect(PAGE_READWRITE) + }); + let r = request(0, at as *mut c_void, plain.len(), file, 0, plain.len()); + assert_eq!(execute(&r), Ok(())); + assert_ne!(opener.join().unwrap(), 0); + // SAFETY: as above, all of it readable. + assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, plain.len()) }, plain); } /// Lanes without workers: what `start` picks, and when statuses land. @@ -1431,7 +1843,8 @@ mod tests { let mut r = request(options, std::ptr::null_mut(), 0, std::ptr::null(), 0, 0); (r.destination_size, r.source_size) = (size, size); let lane = lanes.lanes.get_mut(&id).unwrap(); - lane.unsubmitted.push(Command::Read(r)); + let note = Note::default(); + lane.unsubmitted.push(Command::Read(Read { request: r, note })); } #[test] @@ -1445,7 +1858,7 @@ mod tests { read(&mut l, id, 0, 4096); } } - (0..3).for_each(|id| l.submit(id)); + (0..3).for_each(|id| l.submit(id, false)); let mut started = [0u32; 3]; for _ in 0..330 { let job = l.start().unwrap(); @@ -1465,7 +1878,7 @@ mod tests { read(&mut l, 0, ZLIB, 60); read(&mut l, 0, ZLIB, 60); read(&mut l, 0, 0, 1000); // raw: straight to its destination - l.submit(0); + l.submit(0, false); let first = l.start().unwrap(); assert!(l.start().is_none(), "60 + 60 > 100"); l.finish(&first, Ok(())); @@ -1474,7 +1887,7 @@ mod tests { assert_eq!((second.staging, raw.staging), (60, 0)); // Alone, a request larger than the buffer still runs. read(&mut l, 0, ZLIB, 500); - l.submit(0); + l.submit(0, false); assert!(l.start().is_none()); l.finish(&second, Ok(())); assert!(l.start().is_some()); @@ -1498,7 +1911,7 @@ mod tests { for entry in unsafe { &(*array).state.entries }.iter() { entry.store(E_PENDING, Ordering::Release); } - l.submit(0); + l.submit(0, false); let jobs: Vec = (0..3).map(|_| l.start().unwrap()).collect(); // The last read and the first finish; the second then fails. l.finish(&jobs[2], Ok(())); diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index fe5b4c5..cee2795 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -722,6 +722,21 @@ pub(crate) fn pages_known(pages: &[usize], offset: usize, len: usize) -> bool { .is_some_and(|pages| pages.iter().all(|page| physical.pages.contains_key(page))) } +/// Where the title sees the pages under bytes `[offset, offset + len)` now, +/// in order (for the streaming trace: whether that changed while a request +/// wrote them). +pub(crate) fn pages_shown(pages: &[usize], offset: usize, len: usize) -> Vec<(usize, usize)> { + let physical = physical(); + let numbers = pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or_default(); + let mut shown: Vec<(usize, usize)> = numbers + .iter() + .filter_map(|n| physical.pages.get(n)) + .flat_map(|slice| physical.shown_at(slice, 1)) + .collect(); + shown.sort_unstable(); + shown +} + /// Copies `data` into physical pages, from `offset` bytes into the first, /// whether or not they are mapped anywhere (DirectStorage destinations). /// One view per run of consecutive pages, not one per page: each view From b1da7281489d0b6c88b99c9aa9ab66473455d20c Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:09:03 -0600 Subject: [PATCH 176/445] Writes through views picked from the heap come back (VICTORY_PICKED_WRITES) Off by default. A shader that stores through a view it picks by an index (37 compute programs of the title, 82a2ad6d07417d36 one of them) writes buffers nobody declared. With a submission that has one, the buffers found written that way are declared and landed as any; of the other buffers the heap shows unordered views of 32 MB a frame are compared on the card, in turn, and one that changed undeclared is found. Found late is not landed late. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 10 + crates/victory-gpu/src/frame.rs | 6 + crates/victory-gpu/src/host.rs | 76 ++++- crates/victory-gpu/src/host/torn.rs | 2 +- crates/victory-gpu/src/host/upcheck.rs | 45 +++ crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/picked.rs | 372 +++++++++++++++++++++++++ crates/victory-gpu/src/pipeline.rs | 21 +- 8 files changed, 523 insertions(+), 11 deletions(-) create mode 100644 crates/victory-gpu/src/picked.rs diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index c2f61ce..d5f24d6 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1044,6 +1044,9 @@ impl State { for stage in &p.stages { let t = stage.translated(); STORES.set(t.stores); + if t.stores && crate::picked::on() && crate::picked::picks(&stage.shader, &t.picks) { + crate::picked::runs_in(list); + } let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute); STORES.set(true); if made.iter().any(|m| m.1 == u32::MAX) { @@ -1469,6 +1472,7 @@ impl State { // 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 mut unordered = Vec::new(); for (n, &index) in slots.iter().enumerate() { ranges.remove(&index); let Some(handle) = heap.handle(index) else { @@ -1501,8 +1505,14 @@ impl State { 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)); + } ranges.insert(index, (shadow, address, address + len)); } + if crate::picked::on() { + crate::picked::shown(unordered, *passes % 16 == 1); + } let views = ranges.len() as u32; // Per host copy, the span its picked views cover. let mut spans: std::collections::HashMap, u64, u64)> = diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 84b74ba..44ebe21 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -84,6 +84,12 @@ pub(crate) fn current() -> u64 { FRAME.load(Ordering::Relaxed) } +/// For tests of what is done once a frame. +#[cfg(test)] +pub(crate) fn test_advance() { + FRAME.fetch_add(1, Ordering::Relaxed); +} + /// Per event kind (origin, vblank, flip and later kinds): the last tick a /// wait for it ended on. static LAST: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4c6a9f9..6bb0eb1 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1670,6 +1670,22 @@ struct CardRange { at: u32, /// Whether the card compares it; else every piece is fetched. compared: bool, + /// Looked at by `crate::picked`, and not declared: what is found changed + /// there was written through a view nobody declared. Not landed. + picked: bool, +} + +impl CardPlan { + /// `crate::picked` is told where what it looked at changed, by the + /// compare's results. + fn picked_found(&self, differs: &[u32]) { + for r in self.ranges.iter().filter(|r| r.picked) { + let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d))); + if let Some(p) = changed { + crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0); + } + } + } } /// What a submission does for copies in the card's memory. @@ -2946,6 +2962,7 @@ fn late_line(frames: f64) { } crate::land::log(frames); card_steps::log(frames); + crate::picked::log(frames); #[cfg(feature = "diagnostics")] log_blame(frames); if late_exact() { @@ -3463,7 +3480,9 @@ impl Host { /// `flown`: the submission is sent ahead with [`relay`]. Its compare /// then stores the hashes it makes (see [`flagged_pieces`] and /// `relay`). - fn card_before(&self, runs: &[&HostList], flown: bool) -> Option { + /// `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 { use std::sync::Arc; if !crate::shadow::cards() { return None; @@ -3487,6 +3506,10 @@ impl Host { } } } + let declared = crate::picked::with(declared, &picked.written); + // (Of a copy with a declared range here, that says it.) + let looked: Vec<&crate::picked::Range> = + picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect(); // With the relay: the order of the queue is held from here until // what is taken is on the queue, and the taking is numbered. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); @@ -3498,7 +3521,7 @@ impl Host { None => 0, }; let mut dirty = crate::shadow::card_dirty(sent_as); - if declared.is_empty() && dirty.is_empty() { + if declared.is_empty() && dirty.is_empty() && looked.is_empty() { return None; } let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); @@ -3506,7 +3529,7 @@ impl Host { // A copy whose shader writes are declared for the first time gets // its bytes from before, whole. let mut whole: Vec> = Vec::new(); - for (shadow, _) in &declared { + for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) { if shadow.card_make_before(|size| { let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?; name(&before, || "title buffer on the card, hashes of its pieces".into()); @@ -3631,12 +3654,30 @@ impl Host { span, at, compared, + picked: false, }); if compared { at += span.pieces; } } } + for (shadow, from, len) in looked { + let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); + if let Some(span) = shadow.card_span(*from, from + len) + && twin + && u64::from(at + span.pieces) * 4 <= work.differs.2 + { + plan.ranges.push(CardRange { + shadow: shadow.clone(), + declared: (*from, from + len), + span, + at, + compared: true, + picked: true, + }); + at += span.pieces; + } + } work.taken = at; if plan.ranges.iter().any(|r| r.compared) { let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else { @@ -3669,7 +3710,9 @@ impl Host { }; list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); - card_pass(list, &r.span, size as u32, r.at, if flown { 2 } else { 1 }); + // (What is only looked at keeps its hashes: what + // changed there is the next declared range's to land.) + card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 }); CARD_PASSES[2].fetch_add(1, Ordering::Relaxed); } list.Close()?; @@ -3795,9 +3838,11 @@ impl Host { let suspects = fetch.as_ref().map(|f| &f.suspects); let mut seen = std::collections::HashSet::new(); for &(plan, behind) in plans { + plan.picked_found(differs); let flags: Vec<(usize, u32, bool)> = plan .ranges .iter() + .filter(|r| !r.picked) .flat_map(|r| { (0..r.span.pieces).map(move |p| { let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d)); @@ -3807,7 +3852,7 @@ impl Host { }) .collect(); let fetched = flagged_pieces(&flags); - for r in &plan.ranges { + for r in plan.ranges.iter().filter(|r| !r.picked) { let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; if upcheck::on() { upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize); @@ -4166,7 +4211,8 @@ impl Host { // where the bytes come down. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new(); let mut total = 0u64; - for (i, r) in plan.ranges.iter().enumerate() { + plan.picked_found(differs); + for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) { for p in 0..r.span.pieces { if r.compared && !torn::flagged(differs[(r.at + p) as usize]) { continue; @@ -4708,7 +4754,13 @@ impl Host { self.settle(&mut submitted, WHY_MOST); settled += settling.elapsed(); } - let card = self.card_before(runs, flown); + // What shaders may write through views they pick: last, so that no + // refresh of this submission leaves it alone. + let picked = crate::picked::declare(runs); + for (shadow, at, len) in &picked.written { + shadow.writing(*at, *len); + } + let card = self.card_before(runs, &picked, flown); if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) { lists.push(Some(check)); } @@ -4724,7 +4776,7 @@ impl Host { if let Err(e) = signalled { fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); } - let back = declared_writes(runs); + let back = crate::picked::with(declared_writes(runs), &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); @@ -4844,7 +4896,7 @@ impl Host { if let Some(card) = &card { self.card_back(card, &mut submitted, &mut std::collections::HashSet::new()); } - let back = declared_writes(runs); + let back = crate::picked::with(declared_writes(runs), &picked.written); hand_back(&back); if let Some(card) = card { self.card_done(card); @@ -5969,6 +6021,12 @@ impl HostList { self.deferred().textures.insert(key) } + /// Whether `key` was asked about ([`HostList::first_use`]) since the + /// reset. + pub(crate) fn used(&self, key: usize) -> bool { + self.deferred().textures.contains(&key) + } + /// Runs `work` when the list is submitted, in order with its copies. /// `work` may write title memory (refreshes after it copy again). pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) { diff --git a/crates/victory-gpu/src/host/torn.rs b/crates/victory-gpu/src/host/torn.rs index 69f2f25..5faef19 100644 --- a/crates/victory-gpu/src/host/torn.rs +++ b/crates/victory-gpu/src/host/torn.rs @@ -109,7 +109,7 @@ impl Check { within.push(i); } // (The last flight's stands.) - for r in plans.flat_map(|plan| &plan.ranges).filter(|r| r.compared) { + for r in plans.flat_map(|plan| &plan.ranges).filter(|r| r.compared && !r.picked) { for p in 0..r.span.pieces { if let Some(&i) = index.get(&(r.shadow.id(), r.span.first + p)) && let Some(&d) = differs.get((r.at + p) as usize) diff --git a/crates/victory-gpu/src/host/upcheck.rs b/crates/victory-gpu/src/host/upcheck.rs index 661b3d4..b9bf815 100644 --- a/crates/victory-gpu/src/host/upcheck.rs +++ b/crates/victory-gpu/src/host/upcheck.rs @@ -720,6 +720,51 @@ mod tests { assert_eq!((undone, found), (true, 16)); } + /// A shader that writes through views it picks: its buffer is found when + /// it comes to it in turn, and what it writes from then on is landed. + #[test] + #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 VICTORY_PICKED_WRITES=1 VICTORY_PICKED_MB=1 and a process of its own"] + fn writes_through_picked_views_come_back() { + let Some(host) = host() else { + return; + }; + assert!(crate::picked::on(), "set VICTORY_PICKED_WRITES=1"); + let (title, start, shadow) = title(0x6666, true); + crate::picked::shown(vec![(shadow.clone(), start as u64, (start + LEN) as u64)], true); + let at = (37 << 16) + 512; + let mut lists = Vec::new(); + let mut back = Vec::new(); + for round in 0..12u8 { + // Turns go by frames. + crate::frame::test_advance(); + title[(37 << 16) + 9000] = round + 1; + let list = host.new_list().unwrap(); + shadow.refresh(&list, start as u64, LEN as u64); + crate::picked::runs_in(&list); + write(host, &list, &shadow, at, &[0x40 + round; 64]); + list.close(); + host.execute_own(&list); + settle_now(WHY_SYNC); + back.push(title[at..at + 64] == [0x40 + round; 64]); + // The title's own write beside it is on the card, and the + // shader's stays, once its buffer is known. + let next = host.new_list().unwrap(); + shadow.refresh(&next, start as u64, LEN as u64); + next.close(); + host.execute_own(&next); + settle_now(WHY_SYNC); + if *back.last().unwrap() { + let holds = card(host, &shadow); + assert_eq!((holds[(37 << 16) + 9000], holds[at]), (round + 1, 0x40 + round)); + assert_eq!(look(host), Some(0)); + } + lists.extend([list, next]); + } + eprintln!("came back, by round: {back:?}"); + let first = back.iter().position(|b| *b).expect("it is found"); + assert!(first <= 6 && back[first..].iter().all(|b| *b), "{back:?}"); + } + /// Declared writes beside the title's own, in the same 64 KiB pieces and /// dword by dword, flights landing while later ones are in the air: in /// the end title memory and the card hold what each wrote last. (A byte diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 8c5b164..219213a 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -39,6 +39,8 @@ pub mod list; pub mod object; pub mod pipeline; #[cfg(windows)] +mod picked; +#[cfg(windows)] mod pool; #[cfg(windows)] mod primitive; diff --git a/crates/victory-gpu/src/picked.rs b/crates/victory-gpu/src/picked.rs new file mode 100644 index 0000000..512a5d2 --- /dev/null +++ b/crates/victory-gpu/src/picked.rs @@ -0,0 +1,372 @@ +//! Buffers shaders write through views they pick from the heap by an index +//! they compute (`VICTORY_PICKED_WRITES=1`; off by default). +//! +//! Which views a draw or dispatch writes through is known from its tables +//! and root parameters, and their ranges are declared: what is written there +//! comes back to title memory (`Shadow::gpu_writes`). A view picked by an +//! index out of a buffer, per lane, names any of the heap's. What was +//! written through one stayed on the card: title memory, and the title's own +//! copies and textures made from it, never saw it, and a refresh of its 64 +//! KiB put title memory's older bytes over it. (Captures replay1 and +//! replay2: `[compute 82a2ad6d07417d36]` writes 4.6 MB a frame of a 24 MB +//! buffer so.) To declare all such a shader could write would be 987 MB of +//! 573 buffers for every list that runs one. +//! +//! Two things make it small. The compare on the card says what changed since +//! the last time it looked, whoever wrote it and whenever: looking now and +//! then misses no buffer, it only finds it later. And a buffer that was +//! written so once is written so again. So with a submission that has a +//! shader that stores through a picked view ([`stores_picked`]) +//! +//! - the buffers found written that way ([`found`]) are declared: compared +//! and landed with the submission, as any declared write; +//! - of the others that the heap shows unordered views of the next [`slice`] +//! in turn, once a frame, is compared, and nothing else: at 32 MB all of +//! them in some 30 frames. Where something changed that nobody declared, +//! the buffer is one of the first kind from then on. +//! +//! What is found late is not landed late: the title may have other things in +//! that memory by then. It goes to title memory with the next declared write +//! to its 64 KiB. So what is written once, into a buffer not found yet, stays +//! on the card as before. +//! +//! The declarations are the submission's, made when its refreshes are done +//! (`Host::submit`): no refresh of it finds a range closed on their account. +//! +//! Only copies in the card's memory: for those in the PC's, a declared range +//! is a snapshot and a compare on the CPU. (They hold 55 MB of the 987.) +//! +//! What it costs: the hashing of the slice and of the buffers found, and +//! what changed of the latter coming back. What else changes: a step on the +//! CPU that reads a buffer found waits for the flight, as it should always +//! have done. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed}; +use std::sync::{Arc, Mutex, OnceLock, Weak}; + +use crate::host::HostList; +use crate::shadow::Shadow; + +pub(crate) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PICKED_WRITES").is_some_and(|v| v == "1")) +} + +/// Bytes looked at in turn per frame (`VICTORY_PICKED_MB`). +fn slice() -> u64 { + static SLICE: OnceLock = OnceLock::new(); + *SLICE.get_or_init(|| { + let mb = std::env::var("VICTORY_PICKED_MB").ok().and_then(|v| v.trim().parse::().ok()); + mb.unwrap_or(32) << 20 + }) +} + +/// A list's key for [`HostList::first_use`]: it runs such a shader (no title +/// resource is there). +const KEY: usize = usize::MAX - 0x7a; + +/// `list` runs a shader that stores through a picked view. +pub(crate) fn runs_in(list: &HostList) { + list.first_use(KEY); +} + +/// [`crate::pipeline::Translated::picks`]: not asked yet, asked, the answers. +const UNKNOWN: u8 = 0; +const ASKED: u8 = 1; +const NO: u8 = 2; +const YES: u8 = 3; + +/// Whether `shader`, which stores to buffers, does so through a view it +/// picks. Tracing its descriptors takes some 50 ms, so a thread of ours does +/// it when the shader is first bound, and it is "no" until then: what it +/// writes is found some frames later in any case. (Of the 25,904 programs of +/// the title 2,923 store and have the view heap among their parameters; 37 +/// compute programs store through views they pick.) +pub(crate) fn picks(shader: &Arc, known: &AtomicU8) -> bool { + match known.load(Relaxed) { + YES => true, + UNKNOWN => { + if known.compare_exchange(UNKNOWN, ASKED, Relaxed, Relaxed).is_ok() { + ask(shader.clone()); + } + false + } + _ => false, + } +} + +fn ask(shader: Arc) { + use std::sync::mpsc::{Sender, channel}; + static ASKS: OnceLock>>> = OnceLock::new(); + let asks = ASKS.get_or_init(|| { + let (send, asks) = channel::>(); + let _ = std::thread::Builder::new().name("victory-picked".into()).spawn(move || { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL}; + // SAFETY: this thread's own. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL) }; + for shader in asks { + let yes = shader.programs().is_none_or(|all| all.iter().any(stores_picked)); + if yes { + tracing::info!(hash = %shader.hash, "a shader stores through views it picks from the heap (VICTORY_PICKED_WRITES=1)"); + } + if let Some(t) = shader.translated() { + t.picks.store(if yes { YES } else { NO }, Relaxed); + } + } + }); + Mutex::new(send) + }); + let _ = asks.lock().unwrap_or_else(|e| e.into_inner()).send(shader); +} + +/// Whether the code of `program` stores to a buffer through a descriptor +/// that its tables do not name: loaded from the view heap, or from a table at +/// an offset it computes (programs with the view heap among their parameters). Yes where that cannot be told. +fn stores_picked(program: &victory_shader::NativeProgram) -> bool { + use victory_shader::HwStage; + use victory_shader::gfx10::Fields; + use victory_shader::native::RootType; + use victory_shader::resource::{Role, Source}; + // (The programs that are translated.) + if !matches!(program.stage, HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms) { + return false; + } + let heap = |param: usize| program.layout.get(param).is_some_and(|p| p.root == RootType::ResourceHeap); + if !(0..program.layout.len()).any(heap) { + return false; + } + let Ok(p) = victory_shader::spill::build(program) else { + return true; + }; + // The structure is what takes time, and only per-lane descriptors need + // it. + let plain = victory_shader::resource::track(&p, &program.layout, program.stage, None); + let res = plain.or_else(|_| { + let st = victory_shader::structure::structure(&p); + victory_shader::resource::track(&p, &program.layout, program.stage, st.as_ref().ok()) + }); + let Ok(res) = res else { + return true; + }; + res.descriptors.iter().filter(|d| d.role == Role::Resource).any(|d| { + let inst = &p.blocks[d.site.0].insts[d.site.1]; + let stores = matches!(inst.fields, Fields::Buffer { .. }) && (inst.name().contains("store") || inst.name().contains("atomic")); + stores + && d.source.leaves().into_iter().any(|s| match s { + Source::Loaded { load, .. } | Source::Fetched { load, .. } => res + .scalar + .iter() + .find(|(site, _)| site == load) + .is_some_and(|(_, a)| heap(a.param) || a.dynamic.is_some()), + _ => false, + }) + }) +} + +/// A buffer the heap shows unordered views of: title addresses, from the +/// first to the last. +struct Shown { + copy: Weak, + from: u64, + to: u64, +} + +#[derive(Default)] +struct State { + shown: BTreeMap, + /// The copies (by number) found written through picked views. + found: BTreeSet, + /// Where the next slice begins: copy, offset from its first address. + next: (u64, u64), + /// The frame of the last slice. + frame: u64, +} + +static STATE: Mutex> = Mutex::new(None); + +impl State { + /// The ranges of the next `most` bytes in turn, at most all once. + fn turn(&mut self, most: u64) -> Vec<(u64, u64, u64)> { + let mut out: Vec<(u64, u64, u64)> = Vec::new(); + let mut left = most; + // (The one it begins in may come twice: its end first.) + for _ in 0..=self.shown.len() { + let (copy, offset) = self.next; + let Some((&id, s)) = self.shown.range(copy..).next().or_else(|| self.shown.iter().next()) else { + break; + }; + let offset = if id == copy { offset } else { 0 }; + let len = s.to - s.from; + let n = len.saturating_sub(offset).min(left); + if n > 0 && !self.found.contains(&id) { + if out.iter().any(|r| r.0 == id) { + break; + } + out.push((id, s.from + offset, n)); + left -= n; + if offset + n < len { + self.next = (id, offset + n); + break; + } + } + self.next = (id + 1, 0); + if left == 0 { + break; + } + } + out + } +} + +/// The pass over the heap's buffer views (`crate::draw`): the unordered ones +/// it looked at (copy, from, to); `all` if those are all there are. +pub(crate) fn shown(views: Vec<(Arc, u64, u64)>, all: bool) { + let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let state = state.get_or_insert_with(State::default); + if all { + state.shown.clear(); + } + for (copy, from, to) in views.into_iter().filter(|v| v.0.carded() && v.1 < v.2) { + let e = state.shown.entry(copy.id()).or_insert_with(|| Shown { + copy: Arc::downgrade(©), + from, + to, + }); + (e.from, e.to) = (e.from.min(from), e.to.max(to)); + } +} + +/// A range of a copy: title address and bytes. +pub(crate) type Range = (Arc, usize, usize); + +/// What is done with a submission. +#[derive(Default)] +pub(crate) struct Ranges { + /// To be declared. + pub(crate) written: Vec, + /// To be compared only. + pub(crate) looked: Vec, +} + +/// Of a submission that is about to go to the card, its refreshes done: what +/// is to be declared and looked at, if one of its lists runs a shader that +/// stores through a picked view. +pub(crate) fn declare(runs: &[&HostList]) -> Ranges { + if !on() || !runs.iter().any(|list| list.used(KEY)) { + return Ranges::default(); + } + let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let Some(state) = state.as_mut() else { + return Ranges::default(); + }; + let frame = crate::frame::current(); + let written: Vec<(u64, u64, u64)> = + state.found.iter().filter_map(|id| state.shown.get(id).map(|s| (*id, s.from, s.to - s.from))).collect(); + let mut looked = Vec::new(); + if state.frame != frame { + state.frame = frame; + looked = state.turn(slice()); + } + let of = |ranges: Vec<(u64, u64, u64)>, count: usize| -> Vec { + COUNTS[count].fetch_add(ranges.iter().map(|r| r.2).sum(), Relaxed); + ranges + .into_iter() + .filter_map(|(id, at, len)| Some((state.shown.get(&id)?.copy.upgrade()?, at as usize, len as usize))) + .collect() + }; + Ranges { written: of(written, 0), looked: of(looked, 1) } +} + +/// The compare found a piece changed (it begins at offset `at` of `copy`) +/// where it only looked: something wrote it through a view nobody declared. +pub(crate) fn found(copy: &Arc, at: usize) { + let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner()); + if state.get_or_insert_with(State::default).found.insert(copy.id()) { + let (start, len) = copy.span(); + tracing::info!( + "a buffer is written through views picked from the heap: {start:#x}+{len:#x} (first seen at +{at:#x}; VICTORY_PICKED_WRITES=1): \ + declared with every submission that may write it from here on" + ); + } +} + +/// Since the last frame-rate line: bytes declared, and bytes looked at. +static COUNTS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// For the frame-rate line. +pub(crate) fn log(frames: f64) { + if !on() { + return; + } + let [declared, looked] = [0, 1].map(|i| COUNTS[i].swap(0, Relaxed) as f64 / frames / (1 << 20) as f64); + let state = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let (shown, found) = state.as_ref().map_or((0, 0), |s| (s.shown.len(), s.found.len())); + tracing::info!( + "views picked from the heap, per frame (VICTORY_PICKED_WRITES=1): {declared:.1} MB declared for them, {looked:.1} MB \ + looked at in turn; unordered views of {shown} buffers on the card, {found} of them found written" + ); +} + +/// Declared writes, per copy, and those of `picked`. +pub(crate) fn with(mut back: Vec<(Arc, Vec<(usize, usize)>)>, picked: &[Range]) -> Vec<(Arc, Vec<(usize, usize)>)> { + for (copy, at, len) in picked { + let range = (*at, *at + *len); + match back.iter_mut().find(|b| Arc::ptr_eq(&b.0, copy)) { + Some((_, ranges)) if ranges.contains(&range) => {} + Some((_, ranges)) => ranges.push(range), + None => back.push((copy.clone(), vec![range])), + } + } + back +} + +#[cfg(test)] +mod tests { + use super::*; + + fn state(sizes: &[u64]) -> State { + let mut state = State::default(); + for (i, &n) in sizes.iter().enumerate() { + let from = (i as u64 + 1) << 32; + state.shown.insert(i as u64 * 3 + 2, Shown { copy: Weak::new(), from, to: from + n }); + } + state + } + + /// Every byte in turn, none left out, whatever the slice. + #[test] + fn all_buffers_are_looked_at_in_turn() { + let sizes = [100u64, 7, 1000, 1, 350]; + let total: u64 = sizes.iter().sum(); + for most in [1u64, 10, 99, 350, 1000, 5000] { + let mut s = state(&sizes); + let mut seen = std::collections::BTreeMap::::new(); + // (A turn ends with the list: it may take one more.) + let turns = total.div_ceil(most) + sizes.len() as u64 + 1; + for _ in 0..turns { + let turn = s.turn(most); + assert!(turn.iter().map(|r| r.2).sum::() <= most); + for (id, at, n) in turn { + let from = s.shown[&id].from; + for b in at - from..at - from + n.min(2000) { + *seen.entry(id << 32 | b).or_default() += 1; + } + } + } + assert_eq!(seen.len() as u64, total, "slices of {most}"); + } + } + + #[test] + fn what_was_found_has_no_turn() { + let mut s = state(&[64, 64, 64]); + s.found.insert(5); + let turn = s.turn(1000); + assert_eq!(turn.iter().map(|r| r.0).collect::>(), [2, 8]); + assert!(state(&[]).turn(10).is_empty()); + let mut all = state(&[64]); + all.found.insert(2); + assert!(all.turn(10).is_empty()); + } +} diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 1efa54c..2ace811 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -126,6 +126,9 @@ pub(crate) struct Translated { /// Whether the shader's code can store to buffer memory ([`stores`]); /// true when its code is not known. pub(crate) stores: bool, + /// Whether it stores through a view it picks from the heap by an index, + /// once asked (`crate::picked`). + pub(crate) picks: std::sync::atomic::AtomicU8, } #[cfg(windows)] @@ -172,6 +175,17 @@ impl Shader { } } +#[cfg(windows)] +impl Shader { + /// The console programs of the container; `None` if they are not known. + pub(crate) fn programs(&self) -> Option> { + use victory_shader::{Container, FourCC}; + let c = Container::parse(&self.container).ok()?; + let part = c.part(FourCC::DXIL).or(c.part(FourCC::ACCC))?; + victory_shader::native_programs(part.data).ok() + } +} + #[cfg(windows)] fn translate(container: &[u8]) -> Result { use victory_shader::{Container, FourCC, HwStage}; @@ -194,7 +208,12 @@ fn translate(container: &[u8]) -> Result { }) .map(|p| p.used) .unwrap_or_default(); - Ok(Translated { host, used, stores }) + Ok(Translated { + host, + used, + stores, + picks: Default::default(), + }) } /// The compute pipelines of the console's ray-tracing structure builder From 26d818c57f98624eefea1ada9d71098c5b25d686 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:10:44 -0600 Subject: [PATCH 177/445] Kernel reads, remapped views, freed memory and lost writes of title memory - What the kernel is writing (file reads) is not guarded by a refresh before the call is done (`kernel_writing`): the read would have failed. - A title thread that uses a page while the runtime remaps another page of the same view waits for that in the fault handler; it faulted on a page the title never gave up. - Blocks being unmapped are not guarded again, memory the title frees leaves no notes of its blocks (its VirtualFree is taken over), and other memory at an address once guarded or absent keeps its protection. - The second part of a submission's one asking has a number of its own. - What shaders wrote waits for a change of mapping instead of being lost; what could not be written is counted and said; zeros into title memory that went are no fault. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 53 +- crates/victory-gpu/src/land.rs | 22 +- crates/victory-gpu/src/land/tests.rs | 37 ++ crates/victory-gpu/src/lib.rs | 4 +- crates/victory-gpu/src/shadow.rs | 39 +- crates/victory-gpu/src/watch.rs | 573 ++++++++++++++++++++- crates/victory-hle/src/modules/dstorage.rs | 6 +- crates/victory-hle/src/modules/files.rs | 31 +- crates/victory-hle/src/modules/xmem.rs | 70 ++- 9 files changed, 803 insertions(+), 32 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index eeeae77..35093b0 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -704,6 +704,22 @@ fn warp_adapter() -> windows::core::Result { #[cfg(test)] mod tests { + /// Zeros for a title destination that went meanwhile are no fault. + #[test] + fn zeros_where_nothing_is_are_lost() { + use windows_sys::Win32::System::Memory::*; + // SAFETY: a reservation of ours, its first page committed. + unsafe { + let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::(); + assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null()); + at.write_bytes(7, 4096); + super::zero(at, 4096); + assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0)); + super::zero(at.add(4096), 4096); + VirtualFree(at.cast(), 0, MEM_RELEASE); + } + } + #[test] fn sparse_copies_preserve_islands_and_observe_remaps() { use windows_sys::Win32::System::Memory::*; @@ -6407,7 +6423,10 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b } #[cfg(feature = "diagnostics")] let moved = std::time::Instant::now(); - let whole = read(src, dst, len); + let since = crate::watch::changes(); + // (A title destination that is away only while the runtime changes a + // mapping beside it is written when that is done.) + let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len)); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64); if whole { @@ -6417,6 +6436,7 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b // not all mapped. Then the destination stays as it is (the kernel may // have written its first pages). if title_dst && !ask_first && !crate::texture::committed(dst, len) { + crate::watch::lost("a copy of the title's", dst as usize, len); return; } #[cfg(feature = "diagnostics")] @@ -6476,14 +6496,29 @@ fn read_pieces(src: *const u8, dst: *mut u8, len: usize) { if !read(at as *const u8, to, n) { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Unmapped, n as u64); - // SAFETY: inside the destination, which is mapped. - unsafe { to.write_bytes(0, n) }; + zero(to, n); } }); } }); } +/// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the +/// destination of a title's copy), which can go between the question whether +/// it is there and this. +fn zero(to: *mut u8, n: usize) { + static ZEROS: [u8; 4096] = [0; 4096]; + if n <= ZEROS.len() && crate::safecopy::on() { + // SAFETY: a destination that is not there fails the copy. + if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } { + crate::watch::lost("zeros", to as usize, n); + } + return; + } + // SAFETY: inside the destination, which is mapped. + unsafe { to.write_bytes(0, n) }; +} + /// Reads title memory at `src` into `dst`; false if a page of it is not /// readable. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool { @@ -6537,6 +6572,7 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; let direct = direct_writes(); + let since = crate::watch::changes(); let write = |at: usize, n: usize| { let from = src.wrapping_add(at - dst as usize); if crate::safecopy::on() { @@ -6563,7 +6599,16 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { for_pieces(dst as usize, len, 64 << 10, |at, n| { if !write(at, n) { for_pieces(at, n, 4 << 10, |at, n| { - write(at, n); + if write(at, n) { + return; + } + // The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a + // refresh guarded the block again since the caller opened + // it; and any where the runtime was changing a mapping. + crate::watch::writing(at, n); + if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) { + crate::watch::lost("a host copy's bytes", at, n); + } }); } }); diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 67ae9cd..c8cfc26 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -499,6 +499,7 @@ unsafe fn piece_at( spent(stat::NOTES, opening); } let into = beside.unwrap_or(title); + let since = crate::watch::changes(); let (mut pages, mut new_pages, mut blocks, mut dwords, mut missing) = (0, 0u64, 0, 0, 0); let mut span: Option<(usize, usize)> = None; for_pages(title, parts, |from, n| { @@ -508,7 +509,26 @@ unsafe fn piece_at( } // SAFETY: the caller's; title memory, by an address that shows it // (`beside`) or the title's own. - let done = unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) }; + let merge = |take| unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) }; + let mut done = merge(take && beside.is_some()); + if !done.there && beside.is_none() { + // Away only while the runtime changes a mapping beside it: the + // rest of it when that is done. What is still not there then is + // taken as the caller says. + let mut put = done.dwords; + let again = crate::watch::again_after_change(since, || { + done = merge(false); + put += done.dwords; + done.there + }); + if !again && take { + done = merge(true); + put += done.dwords; + } + done.dwords = put; + // (What was new to the first try was new.) + done.new = done.new.max(1); + } blocks += done.new; dwords += done.dwords; missing += u64::from(!done.there); diff --git a/crates/victory-gpu/src/land/tests.rs b/crates/victory-gpu/src/land/tests.rs index f2fef9f..64eef53 100644 --- a/crates/victory-gpu/src/land/tests.rs +++ b/crates/victory-gpu/src/land/tests.rs @@ -213,6 +213,43 @@ fn a_piece_lands_what_the_card_wrote_in_its_parts() { } } +/// A piece whose title memory is away only while the runtime changes a +/// mapping lands when that is done; where it stays away the copy's CPU side +/// takes the card's bytes (`take`) or not. +#[test] +fn a_piece_waits_for_a_change_of_mapping() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, VirtualAlloc, VirtualFree}; + assert!(crate::safecopy::on()); + // SAFETY: a reservation of ours, nothing of it committed. + let at = unsafe { VirtualAlloc(std::ptr::null(), BLOCK, MEM_RESERVE, PAGE_NOACCESS) } as usize; + assert_ne!(at, 0); + let now = [9u8; 100]; + for take in [true, false] { + let mut held = [0u8; 100]; + // SAFETY: arrays of 100 bytes. + let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], take, &mut Notes::default()) }; + assert_eq!((put, held), (0, [if take { 9 } else { 0 }; 100])); + } + let (began, wait) = std::sync::mpsc::channel(); + let change = std::thread::spawn(move || { + let _changing = crate::watch::title_memory_remapping(); + began.send(()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(50)); + // SAFETY: the reservation's first page. + assert!(!unsafe { VirtualAlloc(at as _, PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + }); + wait.recv().unwrap(); + let mut held = [0u8; 100]; + // SAFETY: as above. + let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], true, &mut Notes::default()) }; + change.join().unwrap(); + assert_eq!((put, held), (100, now)); + // SAFETY: committed by now. + assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 100) }, now); + // SAFETY: our reservation. + unsafe { VirtualFree(at as _, 0, MEM_RELEASE) }; +} + /// Landings on several threads beside title threads that write the same /// blocks (other dwords) and a thread that refreshes a copy, guarding what /// it takes: no write of the title's is lost or undone, all the card wrote diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index faabc53..d32be35 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -70,6 +70,6 @@ pub use host::on_failure; pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view}; #[cfg(windows)] pub use watch::{ - title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping, - writing as kernel_will_write, + kernel_writing, title_memory_freed, title_memory_reading, title_memory_remapped, title_memory_remapping, + title_memory_unmapping, writing as kernel_will_write, }; diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 091c5ed..d70895d 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1561,6 +1561,7 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { if crate::safecopy::on() { PUT[0].fetch_add(1, Ordering::Relaxed); PUT[2].fetch_add(merged.len() as u64, Ordering::Relaxed); + let since = crate::watch::changes(); // SAFETY: title memory; a page of it that is not there fails the // put, and the rest is put page by page. if unsafe { crate::safecopy::put_changed(at as *mut u8, title, merged) } { @@ -1569,8 +1570,14 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { let mut from = 0; while from < merged.len() { let n = (4096 - (at + from) % 4096).min(merged.len() - from); + let (was, now) = (&title[from..from + n], &merged[from..from + n]); // SAFETY: as above. - unsafe { crate::safecopy::put_changed((at + from) as *mut u8, &title[from..from + n], &merged[from..from + n]) }; + let put = || unsafe { crate::safecopy::put_changed((at + from) as *mut u8, was, now) }; + // A page that is away only while the runtime changes a mapping + // beside it gets its bytes when that is done. + if !put() && !crate::watch::again_after_change(since, put) { + crate::watch::lost("what shaders wrote", at + from, n); + } from += n; } return merged.len(); @@ -1614,7 +1621,35 @@ pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, ti #[cfg(test)] mod merge_tests { - use super::{changed_runs, dword_runs}; + use super::{changed_runs, dword_runs, put_changed}; + + /// What shaders wrote reaches a page that is away only while the runtime + /// changes a mapping; a page that stays away loses it, and nothing else. + #[test] + fn a_put_waits_for_a_change_of_mapping() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + // SAFETY: a reservation of ours, nothing of it committed. + let at = unsafe { VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS) } as usize; + assert_ne!(at, 0); + put_changed(at, &[0; 64], &[3; 64]); + let (began, wait) = std::sync::mpsc::channel(); + let change = std::thread::spawn(move || { + let _changing = crate::watch::title_memory_remapping(); + began.send(()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(50)); + // SAFETY: the reservation's first page. + assert!(!unsafe { VirtualAlloc(at as _, 4096, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + }); + wait.recv().unwrap(); + put_changed(at, &[0; 64], &[1; 64]); + change.join().unwrap(); + // SAFETY: committed by now. + assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 64) }, [1; 64]); + // SAFETY: our reservation. + unsafe { VirtualFree(at as _, 0, MEM_RELEASE) }; + } /// Whole dwords around every changed byte and no other, whatever the /// alignment; small gaps joined only when asked. diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index dfae9f4..f6ef170 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -279,13 +279,15 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) { } ask_once_end(); ask_ahead(ranges); + ask_rest(ranges); +} + +/// [`ask_once`] after its [`ask_ahead`]: what that left to `writes`, and the +/// asking stands. +fn ask_rest(ranges: &[(usize, usize)]) { let _all = Asking::hold_all(); let mut ahead = { let mut j = journal_mut(); - if j.ahead.is_empty() { - // `ask_ahead` asked nothing (fewer than two ranges). - j.ahead_asked = next_asking(); - } std::mem::take(&mut j.ahead) }; // `ask_ahead` leaves a range that lies alone to `writes`, which asks @@ -307,7 +309,12 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) { } } let mut j = journal_mut(); - let now = j.ahead_asked; + // A number of its own, and the one this asking stands under: between + // the two parts another thread may have asked about a range of the + // second, copied it, and the title written it since. Under the first + // part's number that write was older than the copy, and never copied. + let now = next_asking(); + j.ahead_asked = now; j.written.extend(written.into_iter().map(|page| (page, now))); j.kept = !ahead.is_empty(); j.ahead = ahead; @@ -622,12 +629,30 @@ struct Guards { /// 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, + /// 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, + /// Blocks (first, past the last) the kernel writes now + /// ([`kernel_writing`]), and blocks the runtime has unmapped in a change + /// not yet done ([`title_memory_unmapping`]). Not in the sets above, and + /// left as they are by [`guard`], which reports them written. + kernel: Vec<(usize, usize)>, + changing: Vec<(usize, usize)>, +} + +impl Guards { + fn left_alone(&self, block: usize) -> bool { + self.kernel.iter().chain(&self.changing).any(|&(first, last)| (first..last).contains(&block)) + } } static GUARDS: Mutex = Mutex::new(Guards { protected: BTreeSet::new(), clean: BTreeSet::new(), absent: BTreeSet::new(), + foreign: BTreeSet::new(), + kernel: Vec::new(), + changing: Vec::new(), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { @@ -795,6 +820,11 @@ fn guard(start: usize, end: usize) -> Option> { open = block >= uncommitted_until; if open { g.absent.remove(&block); + // The hole may have been given up, and its address be the + // title's heap's, or code's, now: not ours to guard. + if !is_view(block * BLOCK, (block + 1) * BLOCK) { + g.foreign.insert(block); + } } } if open { @@ -802,7 +832,7 @@ fn guard(start: usize, end: usize) -> Option> { if g.protected.contains(&block) { // Written through the runtime, still read-only. g.clean.insert(block); - } else { + } else if !g.foreign.contains(&block) && !g.left_alone(block) { run.get_or_insert(block); continue; } @@ -862,13 +892,13 @@ fn is_view(start: usize, end: usize) -> bool { /// block by block if they span views, leaving out any that fail, and /// noting those not committed (unmapped) absent. fn protect(g: &mut Guards, from: usize, to: usize) { - use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; + use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; let set = |from: usize, to: usize| { let mut old = 0; #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); // SAFETY: title view memory; only its protection changes. - let done = unsafe { + let mut done = unsafe { VirtualProtect( (from * BLOCK) as *const _, (to - from) * BLOCK, @@ -876,6 +906,13 @@ fn protect(g: &mut Guards, from: usize, to: usize) { &mut old, ) != 0 }; + if done && !matches!(old, PAGE_READWRITE | PAGE_READONLY) { + // What is there is not for us to guard (code, or memory the + // title protects itself): as it was. + // SAFETY: as above. + unsafe { VirtualProtect((from * BLOCK) as *const _, (to - from) * BLOCK, old, &mut old) }; + done = false; + } #[cfg(feature = "diagnostics")] { tally(5, (to - from) as u64); @@ -919,7 +956,7 @@ 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. fn open(g: &mut Guards, start: usize, end: usize) -> bool { - use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; + use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; let blocks: Vec = g .protected .range(start / BLOCK..end.div_ceil(BLOCK)) @@ -934,7 +971,15 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { PUBLISHED.clear(block); let mut old = 0; // SAFETY: a block we made read-only. - unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; + unsafe { + if VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) != 0 + && !matches!(old, PAGE_READONLY | PAGE_READWRITE) + { + // Not what we left there: the address is other memory's + // (code's, say), which keeps its protection. + VirtualProtect((block * BLOCK) as *const _, BLOCK, old, &mut old); + } + } } #[cfg(feature = "diagnostics")] if !blocks.is_empty() { @@ -961,6 +1006,41 @@ pub fn writing(at: usize, len: usize) { crate::descriptor::host::remapped(at, len); } +/// The kernel writes title memory `[at, at + len)` until what this returns +/// is dropped ([`kernel_writing`]). +pub struct KernelWrite(usize, usize); + +/// The runtime is about to have the kernel write title memory +/// `[at, at + len)` (a file read): its guarded blocks are opened, as by +/// [`writing`], and no refresh guards them again before what this returns is +/// dropped, at the end of that call. One that did would make the kernel's +/// write fail (the kernel does not fault into our handler): a read cut +/// short, which the title takes for what the file holds. +pub fn kernel_writing(at: usize, len: usize) -> KernelWrite { + let (first, last) = (at / BLOCK, at.saturating_add(len).div_ceil(BLOCK)); + { + let mut g = guards_timed(); + open(&mut g, at, at.saturating_add(len)); + if len != 0 { + g.kernel.push((first, last)); + } + } + crate::descriptor::host::remapped(at, len); + KernelWrite(first, if len == 0 { first } else { last }) +} + +impl Drop for KernelWrite { + fn drop(&mut self) { + if self.0 == self.1 { + return; + } + let mut g = guards(); + if let Some(i) = g.kernel.iter().position(|&r| r == (self.0, self.1)) { + g.kernel.swap_remove(i); + } + } +} + /// Held shared by a read of title memory in place, and alone by the runtime /// while it changes what title memory shows. /// @@ -980,12 +1060,149 @@ static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(()); /// ([`title_memory_remapping`]). pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>); +impl Drop for Remapping { + fn drop(&mut self) { + // The change is done: what is there now may be guarded. + if CHANGING.replace((false, false)).1 { + guards().changing.clear(); + } + CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } +} + +/// How often the runtime began or ended a change of what title memory +/// shows: odd while one is under way. +static CHANGES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +thread_local! { + /// This thread holds [`Remapping`]; and put blocks in + /// [`Guards::changing`]. + static CHANGING: std::cell::Cell<(bool, bool)> = const { std::cell::Cell::new((false, false)) }; +} + +/// For [`again_after_change`]: to be asked before what may fail. +pub(crate) fn changes() -> u64 { + CHANGES.load(std::sync::atomic::Ordering::SeqCst) +} + +/// `f` failed to read or write title memory, at some time since [`changes`] +/// said `since`. If the runtime changed a mapping in that time, the pages +/// may have been away for that moment only ([`MAPPING`]): again, when the +/// change is done. Whether `f` did it. +pub(crate) fn again_after_change(since: u64, mut f: impl FnMut() -> bool) -> bool { + let mut since = since; + for _ in 0..4 { + let now = change_done(); + if now == since { + return false; + } + since = now; + if f() { + return true; + } + } + false +} + +/// [`changes`], when no change is under way (or one has been for a second). +fn change_done() -> u64 { + let mut tries = 0; + let mut started = None; + loop { + let now = changes(); + if now.is_multiple_of(2) { + return now; + } + tries += 1; + if tries < 100 { + std::hint::spin_loop(); + continue; + } + if started.get_or_insert_with(std::time::Instant::now).elapsed().as_secs() >= 1 { + return now; + } + // SAFETY: gives the processor to another thread. + unsafe { windows_sys::Win32::System::Threading::Sleep(u32::from(tries > 200)) }; + } +} + +/// Faults of title threads that met a change of mapping and went on after +/// it ([`came_back`]). +static MET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A title thread's access to `at` (`write`: a write) faulted. Whether it +/// can be made now: if a change of mapping is under way, after it. +/// +/// The console changes one page's mapping and no other's. Here the rest of +/// a view is unmapped and mapped again ([`MAPPING`]), and a title thread that +/// uses a page of it just then, which the title never gave up, faulted +/// ("reserved, never committed", or read-only for the moment between our +/// forgetting a guarded block and its unmapping). It waits here instead. +/// Memory that is not there with no change under way is not waited for. +fn came_back(at: usize, write: bool) -> bool { + let there = || { + if !write { + return readable_view(at); + } + // (A refresh may have guarded the page that came back.) + open(&mut guards(), at, at + 1) || writable(at) + }; + let before = changes(); + if there() || again_after_change(before, there) { + MET.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return true; + } + false +} + +/// Whether `at` is in a committed page of a view that can be read. +fn readable_view(at: usize) -> bool { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, PAGE_READONLY, PAGE_READWRITE, VirtualQuery, + }; + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; + n != 0 + && info.State == MEM_COMMIT + && info.Type == MEM_MAPPED + && matches!(info.Protect, PAGE_READONLY | PAGE_READWRITE) +} + +/// Title memory that could not be written with what was to go there (what a +/// shader wrote, a title's copy): counted, and said at the 1st, 2nd, 4th, 8th +/// and so on. A page the title unmapped loses nothing by it; a page that is +/// there does. +pub(crate) fn lost(what: &'static str, at: usize, len: usize) { + static LOST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = LOST.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n.is_power_of_two() { + let there = writable(at); + tracing::warn!(n, what, at = format_args!("{at:#x}"), len, there, "title memory not written"); + } +} + + /// The runtime is about to map, unmap or move physical pages of title /// memory: until what it returns is dropped, no read of title memory in /// place is under way and none begins ([`title_memory_reading`]). Taken /// around the whole change, the unmapping and the mapping again. pub fn title_memory_remapping() -> Remapping { - Remapping(MAPPING.write().unwrap_or_else(|e| e.into_inner())) + // For the title's own threads ([`came_back`]). + install(); + let met = MET.load(std::sync::atomic::Ordering::Relaxed); + if met != 0 { + static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if met >= 2 * SAID.load(std::sync::atomic::Ordering::Relaxed) { + SAID.store(met, std::sync::atomic::Ordering::Relaxed); + tracing::info!(met, "accesses of title threads that waited for a change of mapping"); + } + } + let changing = MAPPING.write().unwrap_or_else(|e| e.into_inner()); + CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + CHANGING.set((true, false)); + Remapping(changing) } /// What a read of title memory in place holds ([`title_memory_reading`]). @@ -1025,9 +1242,20 @@ pub fn title_memory_remapped(at: usize, len: usize) { } /// The runtime is about to unmap title memory `[at, at + len)`: it is -/// nothing of ours any more. Its protection goes with it. +/// nothing of ours any more. Its protection goes with it. Until the change +/// is done ([`Remapping`]) no refresh guards what is there: one that did +/// before the unmapping would leave the address guarded, clean and known by +/// its bits ([`PUBLISHED`]) with no view behind it. pub fn title_memory_unmapping(at: usize, len: usize) { let mut g = title_memory_changed(at, len); + if CHANGING.get().0 && len != 0 { + CHANGING.set((true, true)); + let (first, last) = (at / BLOCK, at.saturating_add(len).div_ceil(BLOCK)); + match g.changing.last_mut() { + Some(before) if before.1 == first => before.1 = last, + _ => g.changing.push((first, last)), + } + } let blocks: Vec = g .protected .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) @@ -1040,6 +1268,58 @@ pub fn title_memory_unmapping(at: usize, len: usize) { } } +/// The title is about to free or decommit memory of its own, +/// `[at, at + len)`, or with no length the whole allocation at `at`: what +/// was noted of its blocks (guarded, clean, absent) would be taken for true +/// of the next memory at the address. +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 { + return; + }; + let end = if len != 0 { + at.saturating_add(len).div_ceil(BLOCK) + } else { + allocation_end(at, noted * BLOCK).div_ceil(BLOCK) + }; + if noted >= end { + return; + } + let absent: Vec = g.absent.range(first..end).copied().collect(); + for block in absent { + g.absent.remove(&block); + } + let foreign: Vec = g.foreign.range(first..end).copied().collect(); + for block in foreign { + g.foreign.remove(&block); + } + // (Memory that is still a view is not freed by that call, which fails: + // it must not stay read-only.) + open(&mut g, at, end * BLOCK); +} + +/// The end of the allocation at `at`, if `inside` lies in it; else `at`. +fn allocation_end(at: usize, inside: usize) -> usize { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; + let ask = |address: usize| { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(address as *const _, &mut info, size_of_val(&info)) }; + (n != 0 && info.AllocationBase as usize == at) + .then(|| (info.BaseAddress as usize).saturating_add(info.RegionSize)) + }; + let mut end = at; + let mut next = ask(inside.max(at)); + while let Some(to) = next { + end = to; + next = ask(to); + } + end +} + /// Tells what keeps track of what title memory shows; the guards, with no /// block of the range known unmapped. fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, Guards> { @@ -1052,10 +1332,14 @@ 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).copied().collect(); + let absent: Vec = g.absent.range(range.clone()).copied().collect(); for block in absent { g.absent.remove(&block); } + let foreign: Vec = g.foreign.range(range).copied().collect(); + for block in foreign { + g.foreign.remove(&block); + } g } @@ -1070,6 +1354,7 @@ pub(crate) fn install() { unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 { // SAFETY: the system passes the exception being dispatched. let r = unsafe { &*(*info).ExceptionRecord }; + const READ: usize = 0; const WRITE: usize = 1; // 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. @@ -1085,6 +1370,13 @@ pub(crate) fn install() { { return match ours { Some(exit) => fail(exit), + None if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS + && r.NumberParameters >= 2 + && r.ExceptionInformation[0] == READ + && came_back(r.ExceptionInformation[1], false) => + { + EXCEPTION_CONTINUE_EXECUTION + } None => EXCEPTION_CONTINUE_SEARCH, }; } @@ -1101,8 +1393,11 @@ pub(crate) fn install() { 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, None => EXCEPTION_CONTINUE_SEARCH, } } @@ -1229,6 +1524,255 @@ mod tests { }; } + /// A placeholder of `blocks` blocks, each its own. + fn placeholder(blocks: usize) -> usize { + use windows_sys::Win32::System::Memory::{ + MEM_PRESERVE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, VirtualAlloc2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a fresh placeholder, split. + unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + blocks * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); + for block in 0..blocks - 1 { + assert_ne!( + VirtualFree((p + block * BLOCK) as *mut _, BLOCK, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), + 0 + ); + } + p + } + } + + /// Private memory of `protect` in place of the placeholder of one block. + fn private_at(at: usize, protect: u32) { + use windows_sys::Win32::System::Memory::{MEM_REPLACE_PLACEHOLDER, VirtualAlloc2}; + // SAFETY: our placeholder. + let got = unsafe { + VirtualAlloc2( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + at as *const _, + BLOCK, + MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, + protect, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(got as usize, at); + } + + fn protection(at: usize) -> u32 { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; + // SAFETY: plain data the query fills in. + unsafe { + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery(at as *const _, &mut info, size_of_val(&info)); + info.Protect + } + } + + /// A refresh between the opening of a kernel read's destination and the + /// read itself leaves it open: the read lands, and is seen. + #[test] + fn a_refresh_leaves_open_what_the_kernel_is_writing() { + use std::io::{Read, Seek, Write}; + use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile}; + // SAFETY: a pagefile section of two blocks, mapped read-write. + let view = unsafe { + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK) + }; + let at = view.Value as usize; + assert_ne!(at, 0); + let pages = |block: usize| at / PAGE + block..at / PAGE + block + 1; + assert!(writes(at, at + 2 * BLOCK, true).is_some()); + assert!(published(at, at + 2 * BLOCK) || !light()); + let mut file = tempfile::tempfile().unwrap(); + file.write_all(b"from the disk").unwrap(); + file.rewind().unwrap(); + let writing = kernel_writing(at + 100, 13); + // The refresh: the block being written is new to it every time, and + // stays open; the other is as it was. + for _ in 0..2 { + assert_eq!(guard(at, at + 2 * BLOCK), Some(pages(0).collect())); + let (now, found) = writes(at, at + BLOCK, true).expect("a view"); + assert!(found.contains(&(at / PAGE, now))); + assert!(writable(at) && !writable(at + BLOCK)); + assert!(!published(at, at + BLOCK)); + } + // SAFETY: 13 bytes of our view, nothing else refers to them. + let into = unsafe { std::slice::from_raw_parts_mut((at + 100) as *mut u8, 13) }; + assert_eq!(file.read(into).expect("the kernel's write lands"), 13); + assert_eq!(into, b"from the disk"); + drop(writing); + // Seen by the next refresh, and guarded again. + assert_eq!(guard(at, at + 2 * BLOCK), Some(pages(0).collect())); + assert!(!writable(at)); + assert_eq!(guard(at, at + 2 * BLOCK), Some(Vec::new())); + title_memory_unmapping(at, 2 * BLOCK); + // SAFETY: our view. + unsafe { UnmapViewOfFile(view) }; + } + + /// A refresh during a change of mapping guards nothing the runtime has + /// begun to unmap: no note of it stays behind. + #[test] + fn nothing_is_guarded_between_our_forgetting_it_and_its_unmapping() { + use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile}; + // SAFETY: a pagefile section of a block, mapped read-write. + let view = unsafe { + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, BLOCK as u32, std::ptr::null()); + assert!(!section.is_null()); + MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, BLOCK) + }; + let at = view.Value as usize; + assert_ne!(at, 0); + assert!(writes(at, at + BLOCK, true).is_some()); + let changing = title_memory_remapping(); + title_memory_unmapping(at, BLOCK); + assert!(writes(at, at + BLOCK, true).is_some()); + { + let g = guards(); + assert!(!g.protected.contains(&(at / BLOCK)) && !g.clean.contains(&(at / BLOCK))); + } + assert!(!published(at, at + BLOCK)); + // SAFETY: our view. + unsafe { UnmapViewOfFile(view) }; + drop(changing); + assert!(!guards().left_alone(at / BLOCK)); + } + + /// Memory at an address where blocks were guarded or absent is not + /// taken for them: code stays code, private memory is not guarded. + #[test] + fn other_memory_at_a_guarded_address_keeps_its_protection() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, MapViewOfFile3, PAGE_EXECUTE_READ, + PAGE_EXECUTE_READWRITE, UnmapViewOfFile2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let p = placeholder(3); + // SAFETY: a section's block in place of the first placeholder. + let view = unsafe { + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, BLOCK as u32, std::ptr::null()); + assert!(!section.is_null()); + MapViewOfFile3( + section, + GetCurrentProcess(), + p as *const _, + 0, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, p); + // One block guarded, two absent. + assert_eq!(guard(p, p + 3 * BLOCK).map(|w| w.len()), Some(3)); + // Not told of what comes: the view goes, code is there; and private + // memory in the holes. + // SAFETY: our view. + assert_ne!(unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }, 0); + private_at(p, PAGE_EXECUTE_READ); + private_at(p + BLOCK, PAGE_READWRITE); + private_at(p + 2 * BLOCK, PAGE_EXECUTE_READWRITE); + let as_made = || { + assert_eq!(protection(p), PAGE_EXECUTE_READ); + assert_eq!(protection(p + BLOCK), PAGE_READWRITE); + assert_eq!(protection(p + 2 * BLOCK), PAGE_EXECUTE_READWRITE); + }; + let holes = [p / PAGE + 1, p / PAGE + 2]; + for _ in 0..2 { + let written = guard(p, p + 3 * BLOCK).expect("as a view"); + assert!(holes.iter().all(|page| written.contains(page)), "copied every time"); + as_made(); + } + writing(p, BLOCK); + as_made(); + title_memory_unmapping(p, 3 * BLOCK); + // SAFETY: our allocations. + unsafe { + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + } + } + + /// Memory the title frees leaves no note of its blocks, whether it names + /// its length or the allocation. + #[test] + fn freed_memory_leaves_no_notes() { + let p = placeholder(3); + let noted = |block: usize| { + let g = guards(); + let block = p / BLOCK + 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)); + // The middle allocation. + title_memory_freed(p + BLOCK, 0); + assert!(noted(0) && !noted(1) && noted(2)); + title_memory_freed(p, BLOCK); + assert!(!noted(0) && noted(2)); + // Nothing noted there: nothing to do, and nothing beside it. + title_memory_freed(p + BLOCK, 0); + assert!(noted(2)); + title_memory_freed(p + 2 * BLOCK, 0); + assert!(!noted(2)); + // SAFETY: our placeholders. + unsafe { + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + } + } + + /// A write between another thread's asking about a range and the second + /// part of a submission's one asking is later than what that thread + /// copied. + #[test] + fn the_rest_of_the_one_asking_has_a_number_of_its_own() { + // SAFETY: a fresh write-watched allocation, freed at the end. + let p = unsafe { + VirtualAlloc(std::ptr::null(), 4 * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) + } as usize; + assert_ne!(p, 0); + // One range: `ask_ahead` leaves it. + let ranges = [(p, p + 4 * PAGE)]; + ask_ahead(&ranges); + let (copied, _) = writes(p, p + 4 * PAGE, false).expect("watched"); + // SAFETY: committed pages of ours. + unsafe { ((p + PAGE) as *mut u8).write_volatile(1) }; + ask_rest(&ranges); + let last = journal().written.get(&(p / PAGE + 1)).copied(); + ask_once_end(); + assert!(last.is_some_and(|last| last > copied), "{last:?} is not after {copied}"); + // SAFETY: our allocation. + unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; + } + /// The runtime maps a view and then tells us; a copy's refresh on another /// thread can guard it in between. Told, it is the title's to write: a /// block left read-only and forgotten would be an access violation in @@ -1663,7 +2207,8 @@ mod many_askers_tests { // or past the guard. let word = at + page * PAGE + t * 8; // SAFETY (both): as above. - let reading = (next(3) == 0).then(super::title_memory_reading_now).flatten(); + // (Waited for: other tests hold changes of mapping.) + 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 { unsafe { (to as *mut u64).write_volatile(2) }; diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 87e635e..384a29a 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -1035,12 +1035,14 @@ fn into_destination( ) -> Result<(), HRESULT> { if request.options & PAGE_DESTINATION == 0 { // Raw reads land through the kernel, which does not fault into the - // GPU side's guard on title buffers; open them first. - victory_gpu::kernel_will_write(request.destination as usize, len); + // GPU side's guard on title buffers; open them first, and until the + // bytes are there. + let writing = victory_gpu::kernel_writing(request.destination as usize, len); // SAFETY: the title's destination holds `destination_size` bytes, at // least `len`, and nothing else writes it until completion. let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::(), len) }; let filled = fill(out).map(drop); + drop(writing); // Again now that the bytes are there: a texture looked at in between // was uploaded without them (`xmem::pages_written`). if super::xmem::stream_notice() { diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index 902c4a9..446263f 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -519,7 +519,7 @@ pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> Fi // fail there instead of faulting into its handler; the title's // synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned // destinations and retry a failed `ReadFile` forever. So the destination -// is opened first. +// is opened first, and not guarded again before the call is done. pub extern "system" fn ReadFile( file: *mut c_void, @@ -528,15 +528,36 @@ pub extern "system" fn ReadFile( read: *mut u32, overlapped: *mut c_void, ) -> i32 { - victory_gpu::kernel_will_write(buffer as usize, len as usize); - host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)( + let writing = victory_gpu::kernel_writing(buffer as usize, len as usize); + let done = host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)( file, buffer, len, read, overlapped, - ) + ); + // The call's error is the title's to ask for. + // SAFETY: plain calls. + let error = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + // shortcut: a read that goes on after the call (overlapped) is written + // into pages the kernel has locked by now: it lands all the same, but a + // refresh that guards its blocks before it does will not see it. + if done == 0 && error == windows_sys::Win32::Foundation::ERROR_IO_PENDING { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::info!(len, "ReadFile: a read of the title's goes on after the call")); + } + if done == 0 && error == windows_sys::Win32::Foundation::ERROR_NOACCESS { + static FAILED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = FAILED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::warn!(n, buffer = format_args!("{buffer:p}"), len, "ReadFile: the title's buffer could not be written"); + } + } + drop(writing); + // SAFETY: as above. + unsafe { windows_sys::Win32::Foundation::SetLastError(error) }; + done } /// The host CRT reads large requests straight into the caller's buffer. pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize { - victory_gpu::kernel_will_write(buffer as usize, size.saturating_mul(count)); + let _writing = victory_gpu::kernel_writing(buffer as usize, size.saturating_mul(count)); host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize)( buffer, size, count, stream, ) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 36dd2bd..f078dd1 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -1136,11 +1136,24 @@ pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL { moved.into() } +/// The title's own `VirtualFree`. What the GPU side noted of the memory goes +/// first: the address may be other memory's the moment it is free. +extern "system" fn title_virtual_free(address: *mut c_void, size: usize, kind: u32) -> BOOL { + const MEM_COALESCE_PLACEHOLDERS: u32 = 1; + // Splitting and joining placeholders changes nothing they show. + if kind & (MEM_PRESERVE_PLACEHOLDER | MEM_COALESCE_PLACEHOLDERS) == 0 { + victory_gpu::title_memory_freed(address as usize, size); + } + // SAFETY: the title's own arguments. + unsafe { VirtualFree(address, size, kind) } +} + pub(crate) fn module() -> HleModule { HleModule { name: "xmem", - dlls: &["xmem.dll"], + dlls: &["xmem.dll", "kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-*"], exports: vec![ + crate::HleExport { name: "VirtualFree", address: title_virtual_free as *const () as usize }, hle_export!(XMemAlloc), hle_export!(XMemFree), hle_export!(XMemAllocDefault), @@ -1383,7 +1396,9 @@ mod tests { let stop = stop.clone(); std::thread::spawn(move || { let mut reads = 0u64; - while !stop.load(Ordering::Relaxed) { + // (Once at least: the mapping thread may be done before this + // one's first turn.) + while reads == 0 || !stop.load(Ordering::Relaxed) { let _reading = victory_gpu::title_memory_reading(); // SAFETY: the page is mapped whenever no change of // mapping is under way, and none is while `_reading` @@ -1405,6 +1420,57 @@ mod tests { assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); } + /// A title thread that reads and writes a page of a view while other + /// pages of the view are unmapped and mapped again, as the console lets + /// it: the page was never given up. + #[test] + fn a_title_thread_goes_on_using_the_rest_of_a_view() { + use std::sync::atomic::{AtomicBool, Ordering}; + let pages = allocate(4); + for _ in 0..200 { + // A new reservation each time: the pieces of a view cut up stay + // cut up. + let a = XMemVirtualAlloc( + std::ptr::null_mut(), + 4 * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ); + assert!(!a.is_null()); + assert_eq!(XMemMapPhysicalPages(a, 4, pages.as_ptr()), a); + let (first, stop) = (a as usize, AtomicBool::new(false)); + // SAFETY: mapped read-write. + unsafe { (first as *mut u64).write_volatile(0) }; + std::thread::scope(|s| { + let title = s.spawn(|| { + let mut n = 0u64; + // SAFETY (the block): the first page is the title's all + // the time; a fault would end the process. + unsafe { + while !stop.load(Ordering::Relaxed) { + assert_eq!((first as *const u64).read_volatile(), n); + n += 1; + (first as *mut u64).write_volatile(n); + } + } + n + }); + // SAFETY: as above. + while !title.is_finished() && unsafe { (first as *const u64).read_volatile() } < 100 {} + for page in [3, 2, 1] { + let at = a.wrapping_byte_add(page * PAGE); + assert_eq!(XMemMapPhysicalPages(at, 1, std::ptr::null()), at); + assert_eq!(XMemMapPhysicalPages(at, 1, pages[page..].as_ptr()), at); + } + stop.store(true, Ordering::Relaxed); + assert!(title.join().expect("the title's thread never faulted") > 0); + }); + assert_eq!(XMemMapPhysicalPages(a, 4, std::ptr::null()), a); + } + assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1); + } + #[test] fn mapping_no_pages_changes_nothing() { let pages = allocate(2); From 74045e4682cbf34e381023ee0d24f97537b15dd3 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:12:04 -0600 Subject: [PATCH 178/445] Holes of view memory known by their bits; landed blocks taken; askings of views left out VICTORY_KNOWN_HOLES (on): a placeholder's holes are known until the runtime tells of a mapping or an allocation there; other holes are asked about with the guards' lock not held. VICTORY_LAND_TAKEN (on): a copy a landing went through is noted as up to date with it. The split tells more of the askings. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 1 + crates/victory-gpu/src/host.rs | 97 ++++- crates/victory-gpu/src/land.rs | 66 +++- crates/victory-gpu/src/land/tests.rs | 6 +- crates/victory-gpu/src/lib.rs | 2 +- crates/victory-gpu/src/shadow.rs | 45 ++- crates/victory-gpu/src/watch.rs | 478 ++++++++++++++++++++++--- crates/victory-hle/src/modules/xmem.rs | 3 + 8 files changed, 628 insertions(+), 70 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 52bf2e4..db68e67 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1678,6 +1678,7 @@ impl State { } #[cfg(feature = "diagnostics")] let refreshed = std::time::Instant::now(); + crate::watch::look_at_holes(); self.heap_textures(list, heap, host); #[cfg(feature = "diagnostics")] for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked, refreshed.elapsed()]) { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 461290c..4366959 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4596,7 +4596,7 @@ impl Host { for list in runs { for step in &list.deferred().copies { if let Step::Refresh(shadow, address, len) = step - && !shadow.unwatched() + && shadow.asked_ahead() { let span = spans .entry(std::sync::Arc::as_ptr(shadow) as usize) @@ -4606,6 +4606,8 @@ impl Host { } } let ranges: Vec<(usize, usize)> = spans.into_values().collect(); + #[cfg(feature = "diagnostics")] + SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed); crate::watch::ask_once(&ranges); #[cfg(feature = "diagnostics")] split.part(0); @@ -6087,9 +6089,11 @@ impl std::hash::Hasher for AddressHash { /// in under flights' writes; the lists' steps, the refreshes among them; the /// snapshots; what goes to copies in the card's memory; the lists sent; and /// of the steps: the refreshes, and the copies and fills (those with the -/// refreshes a copy of title memory flushes). +/// refreshes a copy of title memory flushes). Of the asking, which ranges it +/// is of. Of the refreshes, those before ranges are given to shaders, one +/// copy at a time: nanoseconds, and how many. #[cfg(feature = "diagnostics")] -static SPLIT: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8]; +static SPLIT: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11]; /// Since the last frame-rate line: flushes of refreshes, their refreshes, /// those known to copy nothing, and those done on several threads. @@ -6106,6 +6110,11 @@ impl Split { Split(std::cell::Cell::new(std::time::Instant::now())) } + /// Nanoseconds since the last part. + fn so_far(&self) -> u64 { + self.0.get().elapsed().as_nanos() as u64 + } + /// What came since the last part was part `i`. fn part(&self, i: usize) { let now = std::time::Instant::now(); @@ -6122,11 +6131,12 @@ fn split_line(frames: f64) { let h: Vec = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); let s: Vec = crate::shadow::send_stats().iter().map(|&n| n as f64 / (1 << 20) as f64 / frames).collect(); tracing::info!( - "preparing per frame, the submitting thread: {:.1} ms asking the write watch, {:.1} putting the title's bytes under flights' \ + "preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \ writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \ - several threads; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \ + several threads, {:.1} one at a time in {:.0} before shader writes; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \ card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})", ms[0], + ms[8], ms[1], ms[2], ms[6], @@ -6134,6 +6144,8 @@ fn split_line(frames: f64) { f[1], f[2], f[3], + ms[9], + ms[10] * 1e6, ms[7], ms[3], ms[4], @@ -6141,12 +6153,17 @@ fn split_line(frames: f64) { if crate::watch::light() { "on" } else { "off" }, ); tracing::info!( - "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB; view ranges: {:.0} answered by their \ + "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \ + written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \ bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \ waiting for the guards, {:.1} ms changing protections; pages taken again for the card: {:.1} MB compared, {:.1} MB of them \ as they were, {:.1} MB to go up (VICTORY_SEND_CHANGED)", a[0], a[1] / 1024.0, + a[11] / 1e6, + a[12], + a[10], + a[9], a[2], a[3], a[4], @@ -6286,7 +6303,12 @@ impl Batch { Self::update(&shadow, from, to); } #[cfg(feature = "diagnostics")] - SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + { + let ns = started.elapsed().as_nanos() as u64; + SPLIT[6].fetch_add(ns, Ordering::Relaxed); + SPLIT[9].fetch_add(ns, Ordering::Relaxed); + SPLIT[10].fetch_add(1, Ordering::Relaxed); + } } /// Brings `[from, to)` of a copy up to date, timed. @@ -6369,7 +6391,7 @@ impl Batch { let ranges: Vec<(usize, usize)> = self .refreshes .iter() - .filter(|r| !r.0.unwatched()) + .filter(|r| r.0.asked_ahead()) .map(|r| (r.1, r.2)) .collect(); crate::watch::ask_ahead(&ranges); @@ -7667,6 +7689,50 @@ mod refresh_tests { at } + /// Title memory of `blocks` pages in a placeholder, one view to a page, + /// and every fourth page not there: as a title that streams has it. + fn with_holes(blocks: usize) -> usize { + use windows_sys::Win32::System::Memory::{ + MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, + VirtualAlloc2, VirtualFree, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a placeholder and a section of our own. + unsafe { + let at = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + blocks * PAGE, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(at, 0); + let len = blocks * PAGE; + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null()); + for block in (0..blocks).filter(|b| b % 4 != 3) { + let to = at + block * PAGE; + VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER); + let view = MapViewOfFile3( + section, + GetCurrentProcess(), + to as *const _, + (block * PAGE) as u64, + PAGE, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ); + assert_eq!(view.Value as usize, to); + crate::title_memory_remapped(to, PAGE); + } + at + } + } + fn memory(len: usize) -> *mut u8 { // SAFETY: a plain allocation. unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() } @@ -8115,12 +8181,17 @@ mod refresh_tests { const EACH: usize = 224 << 10; const BIG: usize = 174 << 20; let watched = title(3000 * EACH, false); - let views = title(1400 * EACH, true); + // `VICTORY_BENCH_HOLES=0`: views without holes. + let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0"); + let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) }; + let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3; let big = title(BIG, true); // SAFETY: the test's own memory. unsafe { std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH); - std::ptr::write_bytes(views as *mut u8, 1, 1400 * EACH); + for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) { + std::ptr::write_bytes(at as *mut u8, 1, PAGE); + } std::ptr::write_bytes(big as *mut u8, 1, BIG); } let mut small = Vec::new(); @@ -8143,8 +8214,10 @@ mod refresh_tests { // The title's writes, and the relay's beside the submission. for _ in 0..9 { let at = views + random.below(1400 * EACH / 8) * 8; - // SAFETY: the test's own memory. - unsafe { (at as *mut u64).write_volatile(frame as u64) }; + if there(at) { + // SAFETY: the test's own memory. + unsafe { (at as *mut u64).write_volatile(frame as u64) }; + } } for _ in 0..60 { let at = watched + random.below(3000 * EACH / 8) * 8; diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 67ae9cd..d29e87e 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -133,6 +133,16 @@ pub(crate) fn spent(which: usize, from: std::time::Instant) -> std::time::Instan /// For the frame-rate line: where landing went, per frame. pub(crate) fn log(frames: f64) { + let t: Vec = TAKEN.iter().map(|t| t.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if t[0] > 0.0 { + tracing::info!( + "blocks landed in beside the guards per frame: {:.0}, {:.0} of them held by the copy they were landed through, which takes \ + them no more (VICTORY_LAND_TAKEN={})", + t[0], + t[1], + u8::from(taken()), + ); + } let s: Vec = STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); if s[stat::PIECES] == 0.0 && s[stat::REST] == 0.0 { return; @@ -416,8 +426,39 @@ pub(crate) struct Notes { pages: Vec, /// Per piece, from the first such page to the last: address, bytes. spans: Vec<(usize, usize)>, + /// Per piece put beside the guards, all of it: its 64 KiB block and the + /// copy it was landed through (which the job holds until the flush). + landed: Vec<(usize, *const crate::shadow::Shadow)>, } +// SAFETY: the pointers are used by the job that has the notes, in `flush`. +unsafe impl Send for Notes {} + +/// Whether a copy a landing went through is noted as up to date with it +/// (`VICTORY_LAND_TAKEN=0`: it is not, and the next refresh copies the 64 +/// KiB again and sends them up to the card, as before). +/// +/// What a landing puts into title memory the copy holds already: the card +/// wrote it there, and a copy in the card's memory was given it on the CPU's +/// side by the same merge. But the block counted as written, for that copy +/// as for every other one, so the next refresh copied the whole block, sent +/// it up and had the card hash it again: some 900 blocks a frame landed +/// beside the guards, of the 103 MB a frame that went up (run record-1). +/// +/// Why it may be left out ([`crate::shadow::Shadow::landed`]): the copy held +/// title memory's bytes of the block before the landing, if it had taken it +/// after the block's last noted write and no write was to be noted (the +/// block's bit, `crate::watch::block_published`), and the landing put the +/// same bytes into both. Only where one copy alone landed in the block. +fn taken() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAND_TAKEN").is_none_or(|v| v != "0")) +} + +/// Since the last frame-rate line: blocks landed in beside the guards, and +/// those of them the copy was noted as up to date with. +static TAKEN: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + impl Notes { /// At the end of a job: what it wrote beside the guards is noted. pub(crate) fn flush(&mut self) { @@ -425,9 +466,24 @@ impl Notes { return; } let noting = std::time::Instant::now(); - crate::watch::landed_beside(&self.pages, &self.spans); + let (now, blocks) = crate::watch::landed_beside(&self.pages, &self.spans); + TAKEN[0].fetch_add(blocks.len() as u64, Ordering::Relaxed); + if taken() { + for (block, before) in blocks { + let mut through = self.landed.iter().filter(|l| l.0 == block).map(|l| l.1); + let Some(copy) = through.next() else { + continue; + }; + if !copy.is_null() && through.all(|other| other == copy) { + // SAFETY: the job holds its copies until this is done. + let copy = unsafe { &*copy }; + TAKEN[1].fetch_add(u64::from(copy.landed(block, before, now)), Ordering::Relaxed); + } + } + } self.pages.clear(); self.spans.clear(); + self.landed.clear(); spent(stat::NOTES, noting); } } @@ -447,9 +503,10 @@ pub(crate) unsafe fn piece( parts: &[(usize, usize)], take: bool, notes: &mut Notes, + copy: *const crate::shadow::Shadow, ) -> u64 { // SAFETY: the caller's. - unsafe { piece_at(title, now, held, parts, take, notes, beside_on()) } + unsafe { piece_at(title, now, held, parts, take, notes, beside_on(), copy) } } /// [`piece`], and whether a view of ours is looked for. @@ -464,6 +521,7 @@ unsafe fn piece_at( take: bool, notes: &mut Notes, beside: bool, + copy: *const crate::shadow::Shadow, ) -> u64 { let Some(end) = parts.last().map(|p| p.1) else { return 0; @@ -527,6 +585,10 @@ unsafe fn piece_at( }); if let Some((from, to)) = span { notes.spans.push((from, to - from)); + // Not through a copy that is not to be noted, if that is asked: the + // block then has two. + let through = if missing == 0 { copy } else { std::ptr::null() }; + notes.landed.push((title / BLOCK, through)); } count(stat::NEW_PIECES, u64::from(new_pages > 0)); count(stat::PAGES, pages); diff --git a/crates/victory-gpu/src/land/tests.rs b/crates/victory-gpu/src/land/tests.rs index f2fef9f..32f2cea 100644 --- a/crates/victory-gpu/src/land/tests.rs +++ b/crates/victory-gpu/src/land/tests.rs @@ -192,7 +192,7 @@ fn a_piece_lands_what_the_card_wrote_in_its_parts() { let asked = crate::watch::writes(title.at, title.at + BLOCK, true).expect("a view").0; let mut notes = Notes::default(); // SAFETY: vectors of `len` bytes. - let put = unsafe { piece(title.at + from, now.as_ptr(), held.as_mut_ptr(), &parts, true, &mut notes) }; + let put = unsafe { piece(title.at + from, now.as_ptr(), held.as_mut_ptr(), &parts, true, &mut notes, std::ptr::null()) }; notes.flush(); let mut expect_held = base.clone(); let mut expect = there.clone(); @@ -292,7 +292,7 @@ fn landings_beside_the_title_and_its_refreshes_lose_nothing() { let offset = address - at; // SAFETY: each job its own pieces of the two vectors. unsafe { - piece(address, now.as_ptr().add(offset), (into + offset) as *mut u8, &[(0, len)], true, &mut notes); + piece(address, now.as_ptr().add(offset), (into + offset) as *mut u8, &[(0, len)], true, &mut notes, std::ptr::null()); } } notes.flush(); @@ -420,7 +420,7 @@ fn what_landing_costs() { let mut notes = Notes::default(); for &(at, now, held) in &landing[jobs[j].clone()] { // SAFETY: each its own bytes. - unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside) }; + unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside, std::ptr::null()) }; } notes.flush(); }); diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index faabc53..5976fa7 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -70,6 +70,6 @@ pub use host::on_failure; pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view}; #[cfg(windows)] pub use watch::{ - title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping, + title_memory_allocated, title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping, writing as kernel_will_write, }; diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index ba1f6fa..509e92e 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -908,6 +908,8 @@ fn give_back(v: Vec) { } const NOT_WATCHED: u8 = 2; +/// Watched, not by the kernel but by the guards, when last asked about. +const GUARDED: u8 = 3; /// Where `a` and `b` (of one length) first differ, compared eight bytes at /// a time. @@ -1976,6 +1978,14 @@ impl Shadow { self.watched.load(Ordering::Relaxed) == NOT_WATCHED } + /// Whether a submission asks the kernel about the copy's ranges ahead: + /// not of memory that is not watched, nor of view memory, which the + /// kernel would refuse (and with it the ranges asked about together). + pub(crate) fn asked_ahead(&self) -> bool { + let watched = self.watched.load(Ordering::Relaxed); + watched != NOT_WATCHED && (watched != GUARDED || !crate::watch::light()) + } + /// The copy's own number (see the field). pub(crate) fn id(&self) -> u64 { self.id @@ -2733,7 +2743,7 @@ impl Shadow { if from >= to { return true; } - if self.watched.load(Ordering::Relaxed) != 1 { + if !matches!(self.watched.load(Ordering::Relaxed), 1 | GUARDED) { return false; } // Around ranges shaders are writing the refresh asks gap by gap. @@ -2763,7 +2773,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) { - self.watched.store(1, Ordering::Relaxed); + let guarded = crate::watch::guarded(from, to); + self.watched.store(if guarded { GUARDED } else { 1 }, Ordering::Relaxed); let copied = self.copy_stale(from, to, now, &written); self.refresh_check(from, to); #[cfg(feature = "diagnostics")] @@ -3298,7 +3309,7 @@ impl Shadow { // Where title memory is not mapped the CPU's side keeps what // the card wrote, as before. let merged = - unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes) }; + 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); put += merged; } @@ -3328,7 +3339,33 @@ impl Shadow { // keeps out what else writes them. Title memory that is not there // is looked at again when the next flight that declared the range // lands. - unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes) } + unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes, self) } + } + + /// What shaders wrote in 64 KiB block `block` (of title memory) of this + /// copy was put into title memory beside the guard, which was noted as a + /// write with number `now`, `before` the number of the block's last write + /// before. If the copy held title memory's bytes of the block ahead of + /// that it holds them still, and is noted to ([`crate::land`] says why); + /// whether it was. + /// + /// That it did: it took the whole block after that write, and no other + /// came that is not noted yet. Looked at after the note, whatever comes + /// later has a number above it: a write of the title's takes the block's + /// bit, until an asking has noted it. + pub(crate) fn landed(&self, block: usize, before: u64, now: u64) -> bool { + let Some(page) = block.checked_sub(self.start as usize / PAGE) else { + return false; + }; + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + let Some(at) = copied.get_mut(page) else { + return false; + }; + let held = *at != 0 && *at >= before && crate::watch::block_published(block); + if held { + *at = (*at).max(now); + } + held } } diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 8c6a8be..dcb460d 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -140,11 +140,17 @@ fn kernel_written(first: usize, last: usize) -> Option> { &mut granularity, ) } != 0; + #[cfg(feature = "diagnostics")] + { + tally(10, u64::from(failed)); + tally(11, started.elapsed().as_nanos() as u64); + } if failed { return None; } #[cfg(feature = "diagnostics")] { + tally(12, count as u64); use crate::copystat::{C, add}; add(C::Watches, 1); add(C::WatchUs, started.elapsed().as_micros() as u64); @@ -534,6 +540,27 @@ impl Bits { } } + /// Whether a bit of `[first, last)` is set. + fn any(&self, first: usize, last: usize) -> bool { + let mut block = first; + while block < last { + let word = block / 64; + let until = ((word + 1) * 64).min(last); + let mask = (u64::MAX >> (64 - (until - block))) << (block % 64); + match self.piece(word) { + Some(piece) => { + if piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::SeqCst) & mask != 0 { + return true; + } + block = until; + } + // None of the piece's. + None => block = (word / Bits::WORDS + 1) * Bits::WORDS * 64, + } + } + false + } + /// Whether the bits of all of `[first, last)` are set (not so of none). fn all(&self, first: usize, last: usize) -> bool { let mut block = first; @@ -567,18 +594,146 @@ impl Bits { /// at the journal after that finds every earlier write in it. A write that /// comes while the bit is looked at is no different from one that comes just /// after an asking: the next asking finds the block open. +/// +/// So too for the blocks of placeholders that were copied as zeros +/// (`Guards::held`): nothing can be there before the runtime maps it, and +/// it tells of that ([`title_memory_remapped`]) before the title is. static PUBLISHED: Bits = Bits::new(); +/// The blocks read-only by our hand, or about to be: set under the guards' +/// lock ahead of the protection, cleared under it when the block is open +/// again. Who finds none set has no guard to open and need not wait for the +/// lock ([`writing`]): some 700 pieces a frame are landed in memory that is +/// no view. +static PROTECTED: Bits = Bits::new(); + /// 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) { + if g.clean.contains(page) || g.held.contains(page) { PUBLISHED.set(*page); } } } +/// Whether placeholders are known for what they are (`VICTORY_KNOWN_HOLES=0`: +/// every hole is looked at at every asking, as before). +/// +/// Most ranges asked about have holes, reservations the title maps its pages +/// into as it streams (231,000 regions, 1,125 of a frame's 1,530 asked view +/// ranges, run next1-1). Such a range was never known whole: each asking put +/// a question to Windows for each of its holes, under the guards' lock, and +/// 111 ms a frame of all threads' time went into waiting for that lock. +fn known_holes() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_KNOWN_HOLES").is_none_or(|v| v != "0") && light()) +} + +/// Whether `block` lies in a placeholder: a reservation in which pages come +/// to be only by mapping a view (or an allocation) in its place, which an +/// ordinary commit cannot do. +fn placeholder(block: usize) -> bool { + /// `MEMORY_REGION_INFORMATION` (ntddk). + #[repr(C)] + #[derive(Default)] + struct Region { + allocation_base: usize, + allocation_protect: u32, + region_type: u32, + region_size: usize, + commit_size: usize, + partition_id: usize, + node_preference: usize, + } + #[link(name = "ntdll", kind = "raw-dylib")] + unsafe extern "system" { + fn NtQueryVirtualMemory( + process: *mut std::ffi::c_void, + at: *const std::ffi::c_void, + class: u32, + out: *mut std::ffi::c_void, + len: usize, + returned: *mut usize, + ) -> i32; + } + // (Class 3 answers with the kind of memory in that word, not the flags.) + const MEMORY_REGION_INFORMATION_EX: u32 = 7; + const PLACEHOLDER_RESERVATION: u32 = 1 << 8; + let mut region = Region::default(); + // SAFETY: the answer's room and its size. + let status = unsafe { + NtQueryVirtualMemory( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + (block * BLOCK) as *const _, + MEMORY_REGION_INFORMATION_EX, + (&raw mut region).cast(), + size_of::(), + std::ptr::null_mut(), + ) + }; + status >= 0 && region.region_type & PLACEHOLDER_RESERVATION != 0 +} + +/// The runtime gave the title memory at `[at, at + len)`, allocated or +/// committed: what was known of holes there is asked again. +pub fn title_memory_allocated(at: usize, len: usize) { + if len == 0 || !known_holes() { + return; + } + let mut g = guards(); + let blocks: Vec = g.held.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); + for block in blocks { + g.held.remove(&block); + PUBLISHED.clear(block); + } +} + +/// Once a frame: a hundredth of the known holes are looked at, in case one +/// was filled with nobody telling ([`title_memory_allocated`], +/// [`title_memory_remapped`]), which no title we know does. +pub(crate) fn look_at_holes() { + const PARTS: usize = 100; + if !known_holes() { + return; + } + static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + 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(); + FROM.store(part.last().map_or(0, |b| b + 1), std::sync::atomic::Ordering::Relaxed); + part + }; + let mut until = 0; + for block in blocks { + if block >= until { + until = uncommitted_end(block); + } + if block >= until { + // (Or unmapped memory was mapped since the part was taken: told + // already, and forgotten.) + let mut g = guards(); + if g.held.remove(&block) { + PUBLISHED.clear(block); + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| { + tracing::warn!( + address = format_args!("{:#x}", block * BLOCK), + "a placeholder of the title's was filled with nobody telling (VICTORY_KNOWN_HOLES=0 asks every time)" + ); + }); + } + } + } +} + +/// Whether a block of `[start, end)` is view memory read-only by our hand: +/// the kernel keeps no written pages of it and would refuse an asking. +pub(crate) fn guarded(start: usize, end: usize) -> bool { + PROTECTED.any(start / BLOCK, end.div_ceil(BLOCK)) +} + /// Whether nothing of `[start, end)` can have been written since an asking /// noted it in the journal ([`PUBLISHED`]). fn published(start: usize, end: usize) -> bool { @@ -589,9 +744,11 @@ fn published(start: usize, end: usize) -> bool { /// askings and the KiB they walked; view ranges answered by their bits, by /// the guards whole clean, and block by block; blocks made read-only; blocks /// opened by ourselves; nanoseconds waiting for the guards' lock and -/// nanoseconds of changing protections (all threads). +/// nanoseconds of changing protections (all threads); questions to Windows +/// about holes; kernel askings refused; nanoseconds in kernel askings; the +/// 4 KiB pages they found written. #[cfg(feature = "diagnostics")] -static ASKS: [std::sync::atomic::AtomicU64; 9] = [const { std::sync::atomic::AtomicU64::new(0) }; 9]; +static ASKS: [std::sync::atomic::AtomicU64; 13] = [const { std::sync::atomic::AtomicU64::new(0) }; 13]; #[cfg(feature = "diagnostics")] fn tally(what: usize, n: u64) { @@ -600,7 +757,7 @@ fn tally(what: usize, n: u64) { /// [`ASKS`], taken. #[cfg(feature = "diagnostics")] -pub(crate) fn asks() -> [u64; 9] { +pub(crate) fn asks() -> [u64; 13] { std::array::from_fn(|i| ASKS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) } @@ -622,12 +779,15 @@ struct Guards { /// 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, + /// Of those, the ones in placeholders ([`known_holes`]). + held: BTreeSet, } static GUARDS: Mutex = Mutex::new(Guards { protected: BTreeSet::new(), clean: BTreeSet::new(), absent: BTreeSet::new(), + held: BTreeSet::new(), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { @@ -687,7 +847,12 @@ pub(crate) fn landing(at: usize, len: usize) { /// before they were did so with the number of an asking made before that, /// which is under the one given here, and takes it again; noted before, a /// copy could read the older bytes with a number above the note's. -pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) { +/// +/// Returns the note's number, and for each 64 KiB block noted the number of +/// the block's last write before (0: none is known). +pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64, Vec<(usize, u64)>) { + let mut before = Vec::with_capacity(spans.len()); + let noted; { let frame = crate::frame::current(); let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); @@ -699,11 +864,12 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) { { let mut j = journal_mut(); let now = next_asking(); + noted = now; let mut last = usize::MAX; for &page in pages { let block = page * KERNEL_PAGE / PAGE; if block != last { - j.written.insert(block, now); + before.push((block, j.written.insert(block, now).unwrap_or(0))); last = block; } } @@ -712,6 +878,13 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) { // A placed texture there changes with no descriptor written. crate::descriptor::host::remapped(at, len); } + (noted, before) +} + +/// Whether every write of the title's to 64 KiB block `block` so far is in +/// the journal ([`PUBLISHED`]). +pub(crate) fn block_published(block: usize) -> bool { + light() && PUBLISHED.all(block, block + 1) } /// Whether shaders' writes went into a page of `[at, at + len)` in the last @@ -751,53 +924,64 @@ fn guard(start: usize, end: usize) -> Option> { // of the 68 ms a frame of "guards" (run 58). // `VICTORY_GUARD_ASK=1` asks every time, as before. static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); - let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && { - let g = guards_timed(); - let first = start / BLOCK; - g.protected.contains(&first) || g.absent.contains(&first) - }; + let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); + 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) + }); if !known && !is_view(start, end) { return None; } install(); - let mut g = guards_timed(); - let mut written = Vec::new(); - let mut run: Option = None; - let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); - // The range's clean blocks, in order: read off the set 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 set meanwhile is the block it stands at or ones before it. - let clean: Vec = g.clean.range(first..last).copied().collect(); - if clean.len() == last - first { - // Nothing written, mapped or new since the range was last taken. - #[cfg(feature = "diagnostics")] - tally(3, 1); - return Some(written); + // The holes that an ordinary commit may have filled, with no word of the + // runtime's. Windows is asked with the lock not held (the range is, no + // other thread asks about it: `ASKING`); what the runtime tells meanwhile + // 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 { + // Nothing written, mapped or new since the range was last taken. + #[cfg(feature = "diagnostics")] + tally(3, 1); + return Some(Vec::new()); + } + g.absent.range(first..last).filter(|block| !g.held.contains(block)).copied().collect() + }; + let mut came: Vec = Vec::new(); + let mut uncommitted_until = first; + for block in unsure { + // One question for the blocks of a region. + if block >= uncommitted_until { + uncommitted_until = uncommitted_end(block); + #[cfg(feature = "diagnostics")] + tally(9, 1); + } + if block >= uncommitted_until { + came.push(block); + } } + let mut g = guards_timed(); #[cfg(feature = "diagnostics")] tally(4, 1); - let mut next_clean = 0; - let mut uncommitted_until = first; + for block in &came { + g.absent.remove(block); + } + 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 { - while next_clean < clean.len() && clean[next_clean] < block { - next_clean += 1; - } - let is_clean = next_clean < clean.len() && clean[next_clean] == block; - let mut open = block < last && !is_clean; - if open && g.absent.contains(&block) { - // Ordinary commits need no runtime mapping notification. Reuse - // this asking's query for the following blocks in the same region. - if block >= uncommitted_until { - uncommitted_until = uncommitted_end(block); - } - open = block >= uncommitted_until; - if open { - g.absent.remove(&block); - } - } - if open { + 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) { // Written through the runtime, still read-only. @@ -887,15 +1071,30 @@ fn protect(g: &mut Guards, from: usize, to: usize) { g.protected.extend(from..to); g.clean.extend(from..to); }; + // Ahead of the protection (`PROTECTED`). + (from..to).for_each(|block| PROTECTED.set(block)); if set(from, to) { note(g, from, to); return; } + let mut uncommitted_until = from; for block in from..to { - if set(block, block + 1) { + // (Not one question a block of a region that is not there.) + if block >= uncommitted_until && set(block, block + 1) { note(g, block, block + 1); - } else if block < uncommitted_end(block) { + continue; + } + PROTECTED.clear(block); + if block >= uncommitted_until { + uncommitted_until = uncommitted_end(block); + #[cfg(feature = "diagnostics")] + tally(9, 1); + } + if block < uncommitted_until { g.absent.insert(block); + if known_holes() && placeholder(block) { + g.held.insert(block); + } } } } @@ -935,6 +1134,7 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { let mut old = 0; // SAFETY: a block we made read-only. unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; + PROTECTED.clear(block); } #[cfg(feature = "diagnostics")] if !blocks.is_empty() { @@ -949,7 +1149,8 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { /// reads into its own memory. pub fn writing(at: usize, len: usize) { // The length is the title's (`fread`'s size times count, saturated). - { + let last = at.saturating_add(len).div_ceil(BLOCK); + if !light() || PROTECTED.any(at / BLOCK, last) { let mut g = guards_timed(); #[cfg(feature = "diagnostics")] let held = g.protected.len(); @@ -1037,6 +1238,7 @@ pub fn title_memory_unmapping(at: usize, len: usize) { g.protected.remove(&block); g.clean.remove(&block); PUBLISHED.clear(block); + PROTECTED.clear(block); } } @@ -1055,6 +1257,9 @@ fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, let absent: Vec = g.absent.range(range).copied().collect(); for block in absent { g.absent.remove(&block); + if g.held.remove(&block) { + PUBLISHED.clear(block); + } } g } @@ -1704,6 +1909,183 @@ mod many_askers_tests { // of these writes.) } + /// A range of a placeholder with views in it is known whole, its holes + /// among it, until something is mapped into one, unmapped from it or + /// allocated there. A hole that is no placeholder's is asked about. + #[test] + fn holes_are_known_until_the_runtime_tells() { + use windows_sys::Win32::System::Threading::GetCurrentProcess; + const BLOCKS: usize = 8; + // SAFETY (all): a placeholder and a section of our own, which stay. + let (at, section) = unsafe { + let at = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + BLOCKS * PAGE, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (BLOCKS * PAGE) as u32, std::ptr::null()); + (at, section) + }; + let map = |block: usize| unsafe { + let to = at + block * PAGE; + VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER); + let view = MapViewOfFile3( + section, + GetCurrentProcess(), + to as *const _, + (block * PAGE) as u64, + PAGE, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ); + assert_eq!(view.Value as usize, to); + super::title_memory_remapped(to, PAGE); + }; + map(1); + map(5); + assert!(super::placeholder(at / PAGE) && super::placeholder(at / PAGE + 7) && !super::placeholder(at / PAGE + 5)); + let end = at + BLOCKS * PAGE; + let ask = |since: u64| -> (u64, Vec) { + let (now, written) = writes(at, end, true).expect("a view"); + (now, written.into_iter().filter(|w| w.1 > since).map(|w| w.0 - at / PAGE).collect()) + }; + let (first, all) = ask(0); + assert_eq!(all, (0..BLOCKS).collect::>()); + assert!(super::published(at, end), "with its holes"); + // Written; mapped into; unmapped. + unsafe { ((at + 5 * PAGE) as *mut u8).write_volatile(1) }; + assert!(!super::published(at, end)); + let (second, all) = ask(first); + assert_eq!(all, [5]); + map(2); + assert!(!super::published(at, end)); + let (third, all) = ask(second); + assert_eq!(all, [2]); + unsafe { ((at + 2 * PAGE) as *mut u8).write_volatile(1) }; + let (fourth, all) = ask(third); + assert_eq!(all, [2]); + super::title_memory_unmapping(at + 5 * PAGE, PAGE); + unsafe { + let view = MEMORY_MAPPED_VIEW_ADDRESS { Value: (at + 5 * PAGE) as *mut _ }; + UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER); + } + let (fifth, all) = ask(fourth); + assert_eq!(all, [5]); + assert!(super::published(at, end)); + // Told of memory there, though there is none: asked about again. + super::title_memory_allocated(at, PAGE); + assert!(!super::published(at, end)); + let (_, all) = ask(fifth); + assert_eq!(all, []); + // A reservation of the ordinary kind is no placeholder. + let plain = unsafe { VirtualAlloc(std::ptr::null(), PAGE, MEM_RESERVE, PAGE_NOACCESS) } as usize; + assert!(!super::placeholder(plain / PAGE)); + super::look_at_holes(); + assert!(!super::published(at, end), "block 0 stays asked about"); + assert!(super::published(at + PAGE, end), "the others are as they were"); + super::title_memory_unmapping(at, BLOCKS * PAGE); + } + + /// Pages mapped into a placeholder, written and unmapped again, each by a + /// thread of its own as the runtime does it, while others ask about all + /// of it: what was written, and that a page came or went, is told to + /// whoever asks after it, and blocks are known by their bits meanwhile. + #[test] + fn no_mapping_is_lost_between_askers() { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + const BLOCKS: usize = 12; + // SAFETY (all): a placeholder and a section of our own, which stay. + let (at, section) = unsafe { + let at = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + BLOCKS * PAGE, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + for block in 0..BLOCKS - 1 { + VirtualFree((at + block * PAGE) as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER); + } + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (BLOCKS * PAGE) as u32, std::ptr::null()); + (at, section as usize) + }; + let end = at + BLOCKS * PAGE; + let (stop, by_bits) = (AtomicBool::new(false), AtomicUsize::new(0)); + let number = |written: &[(usize, u64)], block: usize| written.iter().find(|w| w.0 == at / PAGE + block).map_or(0, |w| w.1); + std::thread::scope(|s| { + let mappers: Vec<_> = (0..4usize) + .map(|t| { + let number = &number; + s.spawn(move || { + for round in 0..120 { + let block = t * 3 + round % 3; + let to = at + block * PAGE; + let (before, _) = writes(at, end, true).expect("a view"); + unsafe { + let view = MapViewOfFile3( + section as _, + GetCurrentProcess(), + to as *const _, + (block * PAGE) as u64, + PAGE, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ); + assert_eq!(view.Value as usize, to); + super::title_memory_remapped(to, PAGE); + (to as *mut u8).write_volatile(round as u8); + } + let (mapped, written) = writes(at, end, true).expect("a view"); + assert!(number(&written, block) > before, "mapped and written: not told"); + unsafe { ((to + 9) as *mut u8).write_volatile(round as u8) }; + let (again, written) = writes(to, to + PAGE, true).expect("a view"); + assert!(number(&written, block) > mapped, "written again: not told"); + super::title_memory_unmapping(to, PAGE); + unsafe { + let view = MEMORY_MAPPED_VIEW_ADDRESS { Value: to as *mut _ }; + assert_ne!(UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER), 0); + } + let _ = again; + } + }) + }) + .collect(); + for t in 0..3usize { + let (stop, by_bits) = (&stop, &by_bits); + s.spawn(move || { + let mut k = t; + while !stop.load(Ordering::Relaxed) { + k = (k * 5 + 3) % 64; + let (from, to) = (at + k % 6 * PAGE, end - k / 8 % 5 * PAGE); + by_bits.fetch_add(usize::from(super::published(from, to)), Ordering::Relaxed); + assert!(writes(from, to, true).is_some()); + } + }); + } + let failed = mappers.into_iter().map(|m| m.join()).filter(Result::is_err).count(); + stop.store(true, Ordering::Relaxed); + assert_eq!(failed, 0); + }); + assert!(by_bits.into_inner() > 0, "the bits answered none"); + // All unmapped: known whole, and nothing but holes. + writes(at, end, true).expect("a view"); + assert!(super::published(at, end)); + super::title_memory_unmapping(at, BLOCKS * PAGE); + } + /// A block's bit goes with everything that makes it the title's to write, /// or forgets it. #[test] diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 5aa88d1..31ba575 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -162,6 +162,9 @@ pub extern "system" fn XMemVirtualAlloc( "XMemVirtualAlloc" ); } + if !at.is_null() && !placeholder { + victory_gpu::title_memory_allocated(at as usize, size); + } at } From 26a801e21a82f86e0744caaadc4b1e9f90487f74 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:24:05 -0600 Subject: [PATCH 179/445] Immediate sampler slots are kept apart by comparison mode (upstream 2286e03) One constant used by a comparison and an ordinary sample became a comparison sampler for both. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 41 +++++------ crates/victory-shader/src/emit/mod.rs | 92 +++++++++++++++++++++++++ 2 files changed, 109 insertions(+), 24 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 899255f..c44548a 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -50,7 +50,7 @@ enum Val { pub(crate) struct Lowered { pub dxil: Vec, - /// Bit n: immediate sampler n is used for comparisons. + /// Bit n: immediate sampler n is a comparison sampler. pub cmp_samplers: u64, pub root_cbvs: Vec, pub root_srvs: Vec, @@ -6467,23 +6467,8 @@ impl<'a> Lower<'a> { Ok(h) } Source::Constant(words) if sampler => { - let words: [u32; 4] = words - .get(..4) - .and_then(|w| w.try_into().ok()) - .ok_or("a sampler constant")?; - let n = match self.samplers.iter().position(|w| *w == words) { - Some(n) => n, - None => { - self.samplers.push(words); - self.samplers.len() - 1 - } - }; - if props.0 & 0x8000 != 0 { - // shortcut: one sampler used with and without comparison - // would need two static samplers; it becomes a comparison one. - self.s.cmp_samplers |= 1 << n; - } - Ok(self.s.sampler_handle(self.cur, n as u32)) + let n = self.register_sampler(words, props.0 & 0x8000 != 0)?; + Ok(self.s.sampler_handle(self.cur, n)) } Source::Constant(_) => Err("a constant resource descriptor"), Source::Built { address, .. } => { @@ -6594,22 +6579,30 @@ impl<'a> Lower<'a> { Ok(phi) } - /// Registers an immediate sampler constant and returns its slot index. + /// Registers an immediate sampler constant and returns its slot index: a + /// constant used with and without comparison takes one slot for each. fn register_sampler(&mut self, words: &[u32], cmp: bool) -> Result { let words: [u32; 4] = words .get(..4) .and_then(|w| w.try_into().ok()) .ok_or("a sampler constant")?; - let n = match self.samplers.iter().position(|w| *w == words) { + let slot = self + .samplers + .iter() + .enumerate() + .position(|(n, w)| *w == words && (self.s.cmp_samplers >> n & 1 != 0) == cmp); + let n = match slot { Some(n) => n, None => { + let n = self.samplers.len(); + if n >= u64::BITS as usize { + return Err("more than 64 immediate sampler slots"); + } self.samplers.push(words); - self.samplers.len() - 1 + self.s.cmp_samplers |= u64::from(cmp) << n; + n } }; - if cmp && n < 64 { - self.s.cmp_samplers |= 1 << n; - } Ok(n as u32) } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index d919660..eb30697 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -989,6 +989,98 @@ mod tests { assert!(lower(unmarked).is_err()); } + #[test] + fn immediate_sampler_slots_distinguish_comparison_uses() { + let words = [ + 0xBE81_0380u32, // s_mov_b32 s1, 0 + 0xF40C_0000, + 0xFA00_0000, // s_load_dwordx8 s[0:7], s[0:1], null + 0xBE88_0380, // s_mov_b32 s8, 0 + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0x7E00_02F0, // v_mov_b32 v0, 0.5 (comparison reference) + 0x7E02_02F0, // v_mov_b32 v1, 0.5 (u) + 0x7E04_02F0, // v_mov_b32 v2, 0.5 (v) + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xF080_0108, + 0x0040_0301, // image_sample v3, v[1:2], s[0:7], s[8:11] + 0xF0A0_0108, + 0x0040_0400, // image_sample_c v4, v[0:2], s[0:7], s[8:11] + 0xF0BC_0108, + 0x0040_0500, // image_sample_c_lz v5, v[0:2], s[0:7], s[8:11] + 0xF080_0108, + 0x0040_0601, // image_sample v6, v[1:2], s[0:7], s[8:11] + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xF800_180F, + 0x0605_0403, // exp mrt0, v3, v4, v5, v6 done vm + 0xBF81_0000, + ]; + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 7, + layout: vec![crate::native::RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![crate::native::UsedResource { + kind: crate::native::ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let output = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }; + let osg1 = container::signature(&[output], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let out = emit(&c, &native, &p, &st, &io, &res).unwrap(); + + let sampler = StaticSampler::from_words([0; 4]); + let comparison = StaticSampler { + filter: sampler.filter | 0x80, + ..sampler + }; + assert_eq!(out.samplers, [[0; 4]; 2]); + assert_eq!(out.static_samplers, [sampler, comparison]); + #[cfg(windows)] + if let Some(path) = super::validator::Validator::default_path() { + let mut v = super::validator::Validator::load(Some(&path)).unwrap(); + v.validate(&mut out.dxil.clone()).unwrap(); + } + } + /// A wave64 compute program that writes only EXEC's high dword /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was /// opaque and keyed by the unchanged low dword, so building its lane bit From 77b82c9c22c97700277789e45265882515084046 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:24:23 -0600 Subject: [PATCH 180/445] Mesh primitive exports: corner indices are nine bits, the edge flags dropped (upstream c0228d9) Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 9 +- crates/victory-shader/src/emit/mod.rs | 178 ++++++++++++++++++++++++ crates/victory-shader/src/io.rs | 8 +- 3 files changed, 188 insertions(+), 7 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c44548a..062bf06 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -11354,8 +11354,11 @@ impl<'a> Lower<'a> { Ok(()) } - /// Mesh: `exp prim` as the lane's primitive. Bit 31 culls it (all - /// indices 0: no area). + /// Mesh: `exp prim` as the lane's primitive. Each corner takes ten + /// bits: a 9-bit vertex index and, above it, its edge flag (bits 9, 19 + /// and 29), which only the console's edge-flag rasterisation reads and + /// which is no part of the index. Bit 31 culls it (all indices 0: no + /// area). fn emit_indices(&mut self, e: &Export, guard: Option) -> Result<(), Why> { let v = e.values[0].ok_or("a primitive export without its indices")?; let x = self.i32_of(v)?; @@ -11388,7 +11391,7 @@ impl<'a> Lower<'a> { }); let mut indices = [z; 3]; for (k, slot) in indices.iter_mut().enumerate() { - let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x3FF)); + let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x1FF)); let i = self.s.m.bin(c, Bin::LShr, x, shift); let i = self.s.m.bin(c, Bin::And, i, mask); if let Some(n) = written { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index eb30697..986e669 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -1318,6 +1318,184 @@ mod tests { assert_eq!(c[4..20], ours[..], "our hash differs from the validator's"); } + /// Triangle (0, 1, 2), each corner's 9-bit index in its 10-bit field. + const TRIANGLE: u32 = 1 << 10 | 2 << 20; + /// The edge flags of the three corners (bits 9, 19 and 29). + const EDGE_FLAGS: u32 = 1 << 9 | 1 << 19 | 1 << 29; + /// The culling bit. + const CULL: u32 = 1 << 31; + + /// A one-wave (32-lane) triangle mesh program whose lanes all export + /// primitive `prim` and, as vertex `lane`, the position + /// (lane & 1 ? 3 : -1, lane & 2 ? 3 : -1, 0.5, 1): triangle (0, 1, 2) + /// covers the whole target. + fn triangle_mesh(prim: u32) -> Result { + let words = [ + 0xD765_0001u32, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0x0001_00C1, + 0x3604_0281, // v_and_b32 v2, 1, v1 + 0x3606_0282, // v_and_b32 v3, 2, v1 + 0x7E04_0D02, // v_cvt_f32_u32 v2, v2 + 0x7E06_0D03, // v_cvt_f32_u32 v3, v3 + 0x1008_04F6, // v_mul_f32 v4, 4.0, v2 + 0x0608_08F3, // v_add_f32 v4, -1.0, v4 + 0x100A_06F4, // v_mul_f32 v5, 2.0, v3 + 0x060A_0AF3, // v_add_f32 v5, -1.0, v5 + 0x7E0C_02F0, // v_mov_b32 v6, 0.5 + 0x7E0E_02F2, // v_mov_b32 v7, 1.0 + 0x7E12_02FF, // v_mov_b32 v9, prim + prim, + 0xF800_0941, // exp prim v9, off, off, off done + 0x0000_0009, + 0xF800_08CF, // exp pos0 v4, v5, v6, v7 done + 0x0706_0504, + 0xBF81_0000, // s_endpgm + ]; + let native = NativeProgram { + stage: HwStage::Ms, + wave64: false, + vgprs: 10, + layout: vec![], + used: vec![], + io: StageIo::Ms(crate::native::MeshIo { + outputs: vec![], + clip_cntl: 0, + threads: 32, + max_vertices: 32, + max_primitives: 32, + topology: 2, + lds_bytes: 0, + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let position = SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }; + let osg1 = container::signature(&[position], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes)?; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let st = structure::structure(&p)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native)?; + emit(&c, &native, &p, &st, &io, &res) + } + + /// A primitive export's corners are 9-bit indices: the edge flag above + /// each (bits 9, 19, 29) is no part of it. Masking ten bits made a + /// flagged corner index 512 or more, past any mesh program's vertices + /// (the draw test below shows the triangle). Flagged, unflagged and + /// culled exports translate, and dxil.dll, where there is one, takes + /// each module. + #[test] + fn primitive_export_indices_drop_the_edge_flags() { + #[cfg(windows)] + let mut validator = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) + .ok(); + for prim in [ + TRIANGLE, + TRIANGLE | EDGE_FLAGS, + TRIANGLE | EDGE_FLAGS | CULL, + ] { + let ms = triangle_mesh(prim).unwrap_or_else(|e| panic!("{prim:#x}: {e}")); + #[cfg(windows)] + if let Some(v) = validator.as_mut() { + v.validate(&mut ms.dxil.clone()) + .unwrap_or_else(|e| panic!("{prim:#x}: {e}")); + } + } + } + + /// A triangle mesh program on the host GPU and on WARP (where they have + /// mesh shaders): triangle (0, 1, 2) covers the target with its corners' + /// edge flags set as without them; with the culling bit, nothing is lit. + #[test] + #[cfg(windows)] + fn edge_flagged_triangles_draw_as_unflagged_ones() { + use super::host::{Draw, Host, Root}; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_FEATURE_D3D12_OPTIONS7, D3D12_FEATURE_DATA_D3D12_OPTIONS7, + D3D12_MESH_SHADER_TIER_NOT_SUPPORTED, D3D12_SHADER_VISIBILITY_MESH, + }; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let ps = constant_color(); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + // SAFETY: the query writes the structure of the given size. + let queried = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + }; + if queried.is_err() || options.MeshShaderTier == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED { + eprintln!("no mesh shaders on the {label} device; skipped"); + continue; + } + for (prim, culled) in [ + (TRIANGLE, false), + (TRIANGLE | EDGE_FLAGS, false), + (TRIANGLE | EDGE_FLAGS | CULL, true), + ] { + let ms = triangle_mesh(prim).unwrap(); + let root = host + .root_signature_for(&[(&ms, D3D12_SHADER_VISIBILITY_MESH)]) + .unwrap(); + let pso = host + .mesh_pipeline_with(&root, &ms.dxil, &ps) + .unwrap_or_else(|e| panic!("{label}: mesh pipeline: {e}")); + let texels = host + .draw( + &root, + &pso, + &Draw { + roots: vec![(0, Root::Constants(vec![0]))], + textures: &[], + samplers: &[], + vertices: &[], + stride: 0, + size: (16, 16), + mesh_groups: 1, + }, + ) + .unwrap_or_else(|e| panic!("{label}: draw: {e}")); + let lit = texels.iter().filter(|t| t[3] != 0.0).count(); + if culled { + assert_eq!(lit, 0, "{label}, {prim:#x}: a culled triangle lit texels"); + continue; + } + assert!( + texels.iter().all(|t| *t == [1.0, 0.5, 0.25, 1.0]), + "{label}, {prim:#x}: {lit} of 256 texels lit" + ); + } + eprintln!("{label}: edge-flagged triangles drew"); + ran += 1; + } + if ran == 0 { + eprintln!("no device with mesh shaders; skipped"); + } + } + /// A pixel shader interpolating at sample positions (PERSP_SAMPLE /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency: /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1) diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index 3899cc9..ba53eb0 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -26,10 +26,10 @@ //! index from the wave index (s3 bits 24-27) and the lane (`v_mbcnt`), and //! its group id from v5 of the first lane (`v_readfirstlane`: the group //! times the group size). Lane n exports vertex n (`exp pos`, `exp param`) -//! and primitive n (`exp prim`: 10-bit vertex indices at bits 0, 10, 20, -//! bit 31 culls); `param` entries with bit 7 are per-primitive outputs. One -//! lane sends the output counts (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices | -//! primitives << 12). +//! and primitive n (`exp prim`: 9-bit vertex indices at bits 0, 10, 20, +//! each with an edge flag above it, bit 31 culls); `param` entries with +//! bit 7 are per-primitive outputs. One lane sends the output counts +//! (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices | primitives << 12). use crate::ShaderError; use crate::gfx10::{Fields, Operand}; From c5a2f8d6fd018da23599dadaf0721c7637360b81 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:24:50 -0600 Subject: [PATCH 181/445] Upstream instruction fixes: 64-bit literals, exact normalized ends, flat offsets, rare forms Ports of 7d04943 (a signed 64-bit operand sign-extends its literal), 645391b (a normalized buffer format's ends load as exactly 1.0 and -1.0), 40f30be (FLAT offsets ignore bit 11), 3d71ad1, 344704e, 5d6889e, 78c1267, c3a04e2, e3fe5bf and the tests 259ba31, 8610ffb, 41b2472, 45ed8e3, 8d67fa5. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 195 +++++++++++++++- crates/victory-shader/src/emit/valu_tests.rs | 222 +++++++++++++++++++ crates/victory-shader/src/gfx10/fields.rs | 31 ++- crates/victory-shader/src/gfx10/mod.rs | 15 ++ crates/victory-shader/src/gfx10/sp3.rs | 80 ++++++- 5 files changed, 529 insertions(+), 14 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 062bf06..c3bda73 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5226,6 +5226,10 @@ impl<'a> Lower<'a> { let x = crate::resource::inline(*k).ok_or("a special operand")?; Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 })) } + // Of a signed operand, a literal sign-extends too. + Some(&Operand::Literal(x)) if name.ends_with("_i64") => { + Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 })) + } _ => Ok(l.s.m.i32(0)), } }; @@ -5312,6 +5316,20 @@ impl<'a> Lower<'a> { l.s.m.cmp(c, pred::NE, o, z) }; return match name { + "s_quadmask_b64" => { + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let low = self.quad_mask(a); + let high = self.quad_mask(b); + let k8 = self.s.m.i32(8); + let high = self.s.m.bin(c, Bin::Shl, high, k8); + let mask = self.s.m.bin(c, Bin::Or, low, high); + let zero = self.s.m.i32(0); + self.set(lo, Val::I32(mask)); + self.set(hi, Val::I32(zero)); + let nonzero = self.s.m.cmp(c, pred::NE, mask, zero); + self.set(scc, Val::Bit(nonzero)); + Ok(()) + } "s_bcnt1_i32_b64" => { let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); let i32t = self.s.t.i32; @@ -5437,6 +5455,10 @@ impl<'a> Lower<'a> { let (r, carry): (V, Option) = match name { "s_mov_b32" => (src32(self, 0)?, None), "s_movk_i32" => (sext16(self), None), + "s_quadmask_b32" => { + let pixels = src32(self, 0)?; + (self.quad_mask(pixels), None) + } "s_cselect_b32" => { let cond = self.scc_in(inst)?; let (a, b) = (src32(self, 0)?, src32(self, 1)?); @@ -5630,6 +5652,29 @@ impl<'a> Lower<'a> { Ok(()) } + /// Packs whether each consecutive group of four pixels has a set bit. + fn quad_mask(&mut self, pixels: V) -> V { + let c = self.cur; + let one = self.s.m.i32(1); + let shifted = self.s.m.bin(c, Bin::LShr, pixels, one); + let mut mask = self.s.m.bin(c, Bin::Or, pixels, shifted); + // Fold each nibble into its bottom bit, then gather those bits into + // the low byte in three stages without needing a 64-bit operation. + for (distance, keep) in [ + (2, 0x1111_1111), + (3, 0x0303_0303), + (6, 0x000f_000f), + (12, 0x0000_00ff), + ] { + let distance = self.s.m.i32(distance); + let shifted = self.s.m.bin(c, Bin::LShr, mask, distance); + let combined = self.s.m.bin(c, Bin::Or, mask, shifted); + let keep = self.s.m.i32(keep); + mask = self.s.m.bin(c, Bin::And, combined, keep); + } + mask + } + /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the /// scalar and vector add-with-carry instructions set it. fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option) -> (V, V) { @@ -6300,20 +6345,34 @@ impl<'a> Lower<'a> { l.s.m.bin(c, Bin::AShr, t, k) }; let f32t = self.s.t.f32; + // A normalized format's ends are exactly 1.0 and -1.0. The host + // may divide through a reciprocal and land just below 1.0: RDNA + // 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 max = self.s.m.f32((((1u64 << w) - 1) as f32).to_bits()); + 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 (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); float(self, q) } Numeric::Snorm => { let s = signed(self); let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); - let max = self.s.m.f32((((1u64 << (w - 1)) - 1) as f32).to_bits()); + 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 lo = self.s.m.f32((-1.0f32).to_bits()); - let q = self.binary(35, q, lo); + // 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); + let q = self.s.m.select(c, at_top, one, q); + let low = self.s.m.i32(top.wrapping_neg()); + let minus_one = self.s.m.f32((-1.0f32).to_bits()); + let at_bottom = self.s.m.cmp(c, pred::SLE, s, low); + let q = self.s.m.select(c, at_bottom, minus_one, q); float(self, q) } Numeric::Uscaled => { @@ -7623,6 +7682,17 @@ impl<'a> Lower<'a> { let r = self.s.m.cast(c, op, a, self.s.t.f32); float(self, r) } + "v_cvt_off_f32_i4" => { + // The low nibble as a signed 4-bit integer, over 16. + let a = s(self, 0)?; + let k28 = self.s.m.i32(28); + let a = self.s.m.bin(c, Bin::Shl, a, k28); + let a = self.s.m.bin(c, Bin::AShr, a, k28); + let f = self.s.m.cast(c, Cast::SiToFp, a, self.s.t.f32); + let k = self.s.m.f32(0.0625f32.to_bits()); + let r = self.s.m.bin(c, Bin::Mul, f, k); + float(self, r) + } "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { // Each source is f32, or with op_sel_hi the low (op_sel: high) // f16 half; neg_hi is the absolute value here. @@ -8058,8 +8128,14 @@ impl<'a> Lower<'a> { let x = crate::resource::inline(k).ok_or("a special operand")?; Ok(self.s.m.int_const(i64t, i64::from(x as i32))) } + // A signed 64-bit operand sign-extends its 32-bit literal, as + // the hardware does (LLVM's AMDGPU operand rules). + Operand::Literal(x) if inst.name().ends_with("_i64") => { + Ok(self.s.m.int_const(i64t, i64::from(x as i32))) + } _ => { - // Literals and the null register: zero-extended. + // Literals (of unsigned and bit operands) and the null + // register: zero-extended. let x = self.operand(inst, &op)?; Ok(self.s.m.cast(c, Cast::ZExt, x, i64t)) } @@ -9012,6 +9088,18 @@ impl<'a> Lower<'a> { let b = self.s.m.bin(c, op, b, sh); self.s.m.bin(c, Bin::Mul, a, b) } + "v_mul_hi_u32_u24" | "v_mul_hi_i32_i24" => { + // The high dword of the same 48-bit product: the low 24 bits + // of each operand, zero- or sign-extended, multiplied. + let (a, b) = (s(self, 0)?, s(self, 1)?); + let signed = name == "v_mul_hi_i32_i24"; + let (sh, op) = (k(self, 8), if signed { Bin::AShr } else { Bin::LShr }); + let a = self.s.m.bin(c, Bin::Shl, a, sh); + let a = self.s.m.bin(c, op, a, sh); + let b = self.s.m.bin(c, Bin::Shl, b, sh); + let b = self.s.m.bin(c, op, b, sh); + self.mul_hi(a, b, signed) + } "v_bfe_u32" | "v_bfe_i32" => { let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); let w = m31(self, w); @@ -9090,6 +9178,44 @@ impl<'a> Lower<'a> { let m = self.s.m.bin(c, Bin::Mul, a, b); self.s.m.bin(c, Bin::Add, m, d) } + "v_sad_u8" | "v_sad_hi_u8" | "v_sad_u16" | "v_sad_u32" | "v_msad_u8" => { + // src2 plus the sum of the unsigned differences |a - b| of + // the operands' bytes, halves or whole dwords, wrapping at 32 + // bits. v_sad_hi_u8 adds the sum shifted to the high half; + // v_msad_u8 leaves out a byte whose mask byte (src1) is 0. + let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let (width, parts) = match name { + "v_sad_u16" => (16, 2), + "v_sad_u32" => (32, 1), + _ => (8, 4), + }; + let zero = k(self, 0); + let mut sum = zero; + for i in 0..parts { + let (mut x, mut y) = (a, b); + if width < 32 { + let (sh, mask) = (k(self, width * i), k(self, (1 << width) - 1)); + x = self.s.m.bin(c, Bin::LShr, x, sh); + x = self.s.m.bin(c, Bin::And, x, mask); + y = self.s.m.bin(c, Bin::LShr, y, sh); + y = self.s.m.bin(c, Bin::And, y, mask); + } + let above = self.s.m.cmp(c, pred::IUGT, x, y); + let hi = self.s.m.select(c, above, x, y); + let lo = self.s.m.select(c, above, y, x); + let mut diff = self.s.m.bin(c, Bin::Sub, hi, lo); + if name == "v_msad_u8" { + let masked = self.s.m.cmp(c, pred::NE, y, zero); + diff = self.s.m.select(c, masked, diff, zero); + } + sum = self.s.m.bin(c, Bin::Add, sum, diff); + } + if name == "v_sad_hi_u8" { + let k16 = k(self, 16); + sum = self.s.m.bin(c, Bin::Shl, sum, k16); + } + self.s.m.bin(c, Bin::Add, sum, d) + } "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32" | "v_med3_u32" => { let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); @@ -11990,6 +12116,55 @@ mod tests { } } + /// Lowers a one-thread compute program that copies four root constants + /// (s0..s3) into v1..v4, runs `body`, and stores v0 to a raw buffer from a + /// descriptor table, so the vector instructions in `body` have an effect. + fn lowers_valu(body: &[u32]) -> Result<(), crate::ShaderError> { + let mut words = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xFA00_0000, + ]; + // v_mov_b32 v1..v4, s0..s3 + words.extend((0..4u32).map(|i| 0x7E00_0200 | (i + 1) << 17 | i)); + words.extend_from_slice(body); + words.extend_from_slice(&[ + 0xE070_0000, // buffer_store_dword v0, off, s[8:11], 0 + 0x8002_0000, + S_ENDPGM, + ]); + let constants = RootParam { + sgprs: 4, + ..root(RootType::Constants, 0, 0) + }; + let buffer = UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }; + lower_with( + &words, + vec![constants, root(RootType::Table, 4, 1)], + vec![buffer], + ) + .map(|_| ()) + } + + #[test] + fn the_24_bit_multiplies_lower_both_halves() { + // VOP2 `op v0, v1, v2`: v_mul_i32_i24 and v_mul_u32_u24 (the low + // dword) and v_mul_hi_i32_i24 and v_mul_hi_u32_u24 (the high one). + for op in [0x09u32, 0x0A, 0x0B, 0x0C] { + let word = op << 25 | 2 << 9 | 0x101; + lowers_valu(&[word]).unwrap_or_else(|e| panic!("VOP2 {op:#x}: {e}")); + } + } + #[test] fn buffer_cache_invalidations_lower_as_no_ops() { // MUBUF opcode 0x071/0x072 with no data operand: the title asks the @@ -11998,6 +12173,16 @@ mod tests { assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv"); } + #[test] + fn sums_of_absolute_differences_lower() { + // VOP3 `op v0, v1, v2, v3`: v_sad_u8, v_sad_hi_u8, v_sad_u16, + // v_sad_u32 and v_msad_u8. + for op in [0x15Au32, 0x15B, 0x15C, 0x15D, 0x171] { + let words = [0xD400_0000 | op << 16, 0x101 | 0x102 << 9 | 0x103 << 18]; + lowers_valu(&words).unwrap_or_else(|e| panic!("VOP3 {op:#x}: {e}")); + } + } + #[test] fn a_scalar_carry_chain_reaches_the_select() { // The high dword of a 64-bit add or subtract, then a select on the diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index f5c2014..ee69d98 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -259,6 +259,39 @@ fn run_cases_on( assert!(ran > 0, "no SM 6.6 device available ({devices:?})"); } +#[test] +fn scalar_quad_masks_pack_nibbles_and_set_scc() { + let pack_words = |opcode: u32| { + [ + 0xBE90_0000 | opcode << 8, // s_quadmask s16, s0 (pairs for b64) + sop2(0x0a, 18, 129, 128), // s_cselect_b32 s18, 1, 0 + sop2(0x1e, 18, 18, 144), // s_lshl_b32 s18, s18, 16 + sop2(0x10, 16, 16, 18), // s_or_b32 s16, s16, s18 + vop1(1, 0, sgpr(16)), // v_mov_b32 v0, s16 + ] + }; + let cases = [ + ([0, 0, 0, 0], [0, 0]), + ([0x8000_0420, 0x0100_0001, 0, 0], [0x1_0086, 0x1_4186]), + ([0, 0x8000_0000, 0, 0], [0, 0x1_8000]), + ([u32::MAX, u32::MAX, 0, 0], [0x1_00ff, 0x1_ffff]), + ]; + let inputs = cases.map(|(input, _)| input); + for (wide, opcode) in [0x2c, 0x2d].into_iter().enumerate() { + let shader = build_valu_cs(&pack_words(opcode)); + run_cases(&shader, &inputs, |backend, i, _, got| { + assert_eq!(got, cases[i].1[wide], "{backend}, opcode {opcode:#x}"); + }); + } + let high = build_valu_cs(&[ + 0xBE90_2D00, // s_quadmask_b64 s[16:17], s[0:1] + vop1(1, 0, sgpr(17)), + ]); + run_cases(&high, &inputs, |backend, _, _, got| { + assert_eq!(got, 0, "{backend}: high dword"); + }); +} + fn is_f16_nan(bits: u16) -> bool { (bits & 0x7FFF) > 0x7C00 } @@ -287,6 +320,33 @@ fn f16_to_f32(bits: u16) -> f32 { f32::from_bits(f32_bits) } +#[test] +fn normalized_buffer_formats_load_their_ends_exactly() { + // tbuffer_load_format_x. + let x = 0; + // (format, dword stored, value loaded) + let cases: &[(u8, u32, f32)] = &[ + (1, 0xFF, 1.0), // 8_UNORM + (7, 0xFFFF, 1.0), // 16_UNORM + (2, 0x7F, 1.0), // 8_SNORM: the top, the one above the lowest, the lowest + (2, 0x81, -1.0), + (2, 0x80, -1.0), + (8, 0x7FFF, 1.0), // 16_SNORM + (8, 0x8001, -1.0), + (8, 0x8000, -1.0), + ]; + for &(format, stored, want) in cases { + let shader = tbuffer_load_of_v1(x, format); + run_cases(&shader, &[[stored, 0, 0, 0]], |backend, _, _, got| { + assert_eq!( + got, + want.to_bits(), + "{backend}: format {format} of {stored:#x} = {got:#010x}, want {want}", + ); + }); + } +} + #[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. @@ -486,6 +546,77 @@ fn max_and_min_order_negative_zero_below_positive_zero() { } } +/// The f16 forms go through the same `max_min` helper, after widening to f32. +#[test] +fn f16_max_and_min_order_negative_zero_below_positive_zero() { + let (pz, nz) = (0_u32, 0x8000_u32); + let cases = [ + [nz, pz, nz, 0], + [pz, nz, nz, 0], + [nz, pz, pz, 0], + [pz, nz, pz, 0], + ]; + let ops = [ + ("v_max_f16", 0x139, pz), + ("v_min_f16", 0x13A, nz), + ("v_max3_f16", 0x354, pz), + ("v_min3_f16", 0x351, nz), + ]; + for (name, op, want) in ops { + let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); + run_cases(&shader, &cases, |backend, _, inp, got| { + // The f16 result is the low half of v0. + assert_eq!(got & 0xFFFF, want, "{backend}: {name} {inp:x?}"); + }); + } +} + +#[test] +fn v_min3_max3_med3_integer_forms_match_rdna2() { + // v_{min3,max3,med3}_{i32,u32} v0, v1, v2, v3 (VOP3 0x152..0x159). + type Pick = fn([u32; 3]) -> u32; + let ops: [(&str, u16, Pick); 6] = [ + ("v_min3_i32", 0x152, |t| { + t.into_iter().min_by_key(|&x| x as i32).unwrap() + }), + ("v_min3_u32", 0x153, |t| t.into_iter().min().unwrap()), + ("v_max3_i32", 0x155, |t| { + t.into_iter().max_by_key(|&x| x as i32).unwrap() + }), + ("v_max3_u32", 0x156, |t| t.into_iter().max().unwrap()), + ("v_med3_i32", 0x158, |mut t| { + t.sort_by_key(|&x| x as i32); + t[1] + }), + ("v_med3_u32", 0x159, |mut t| { + t.sort_unstable(); + t[1] + }), + ]; + // Every ordering of three values, with the sign bit set on some so that + // the signed and unsigned answers differ. + let values = [0u32, 1, 0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF]; + let mut cases = Vec::new(); + for a in values { + for b in values { + for c in values { + cases.push([a, b, c, 0]); + } + } + } + for (name, op, pick) in ops { + let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); + run_cases(&shader, &cases, |backend, _, inp, got| { + let want = pick([inp[0], inp[1], inp[2]]); + assert_eq!( + got, want, + "{backend}: {name}({:#010x}, {:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], inp[2], + ); + }); + } +} + #[test] fn v_med3_f16_matches_rdna2_with_nan() { // v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357) @@ -579,6 +710,31 @@ fn v_cmp_lg_is_false_for_nan() { } } +#[test] +fn v_cvt_off_f32_i4_uses_the_signed_low_nibble() { + // v_cvt_off_f32_i4 v0, v1 (VOP1 opcode 0x00e) + let shader = build_valu_cs(&[vop1(0x00e, 0, vgpr(1))]); + let nibble = |n: u32| (((n as i32) << 28) >> 28) as f32 / 16.0; + + let mut cases: Vec = (0..16).collect(); + // Bits above the low nibble are ignored. + cases.extend([0xABCD_EF05, 0xFFFF_FFF8, 0x1234_5670, 0x8000_000F, 0x0000_00F7]); + let inputs: Vec<[u32; 4]> = cases.iter().map(|&x| [x, 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = nibble(cases[i]).to_bits(); + assert_eq!( + got, want, + "{backend}: v_cvt_off_f32_i4({:#010x}) = {got:#010x} ({:?}), want {want:#010x}", + inp[0], + f32::from_bits(got), + ); + }); + // Spot-check the reference itself: 0x5 -> 0.3125, 0x8 -> -0.5, 0xF -> -0.0625. + assert_eq!(nibble(0xABCD_EF05), 0.3125); + assert_eq!(nibble(8), -0.5); + assert_eq!(nibble(0xF), -0.0625); +} + #[test] fn v_fract_f32_never_returns_one() { // v_fract_f32 v0, v1 (VOP1 opcode 0x020) @@ -865,6 +1021,40 @@ fn v_cvt_u16_and_i16_f16_saturate() { } } +#[test] +fn v_cvt_f16_u16_and_i16_widen_the_integer_first() { + // v_mov_b32 v0, 0; v_cvt_f16_u16 / v_cvt_f16_i16 v0, v1 (VOP1 0x050 / 0x051). + // Only integers f16 holds exactly: how the others round is the narrowing's + // business, not this conversion's. `None`: the result depends on rounding. + let cases: &[(u16, Option, Option)] = &[ + // (u16 / i16 input bits, f16 of the unsigned value, f16 of the signed value) + (0x0000, Some(0x0000), Some(0x0000)), // 0 + (0x0001, Some(0x3C00), Some(0x3C00)), // 1.0 + (0x07FF, Some(0x67FF), Some(0x67FF)), // 2047, the last integer below 2048 that f16 holds + (0x8000, Some(0x7800), Some(0xF800)), // 32768 / -32768 + (0xFC00, Some(0x7BE0), Some(0xE400)), // 64512 / -1024 + (0xFFFE, None, Some(0xC000)), // 65534 does not fit f16 / -2 + (0xFFFF, None, Some(0xBC00)), // 65535 does not fit f16 / -1 + ]; + for (op, what, pick) in [ + (0x050u16, "v_cvt_f16_u16", 0usize), + (0x051, "v_cvt_f16_i16", 1), + ] { + let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| [u32::from(c.0), 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, _, got| { + let want = if pick == 0 { cases[i].1 } else { cases[i].2 }; + let Some(want) = want else { return }; + assert_eq!( + got, + u32::from(want), + "{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}", + cases[i].0, + ); + }); + } +} + #[test] fn v_sin_and_v_cos_f16_reduce_large_turns() { let sin_shader = build_valu_cs(&[vop1(0x060, 0, vgpr(1))]); @@ -946,6 +1136,38 @@ fn v_sin_and_v_cos_f16_reduce_large_turns() { }); } +/// A 32-bit literal in a signed 64-bit operand is sign-extended (an +/// unsigned one's is zero-extended): -100 compared with `v[1:2]`, and +/// shifted by `s_ashr_i64`. +#[test] +fn signed_64_bit_operands_sign_extend_their_literal() { + const MINUS_100: u32 = -100_i32 as u32; + let check = |name: &str, body: &[u32], cases: &[([u32; 4], u32)]| { + let shader = build_valu_cs(body); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!(got, want, "{backend}: {name} {inp:x?}"); + }); + }; + // v_cmp_*_i64 s6, v[1:2], -100 (VOP3, literal src1), then + // v_cndmask_b32 v0, 0, 1, s6. + let compare = |op: u16| { + let [a, b] = vop3(op, 6, vgpr(1), 255, 0); + let [c, d] = vop3(0x101, 0, 0x80, 0x81, sgpr(6)); + [a, b, MINUS_100, c, d] + }; + // An i64 as the two input dwords of `v[1:2]`. + let pair = |n: i64| [n as u32, (n >> 32) as u32, 0, 0]; + let eq = [(pair(-100), 1), ([MINUS_100, 0, 0, 0], 0), (pair(0), 0)]; + check("v_cmp_eq_i64", &compare(0x0A2), &eq); + let lt = [(pair(-200), 1), (pair(-50), 0), (pair(0), 0)]; + check("v_cmp_lt_i64", &compare(0x0A1), <); + // s_ashr_i64 s[6:7], -100, 4; v_mov_b32 v0, s7: the high dword. + let ashr = [sop2(0x23, 6, 255, 0x84), MINUS_100, vop1(0x001, 0, sgpr(7))]; + check("s_ashr_i64", &ashr, &[([0; 4], u32::MAX)]); +} + #[test] fn bfe_signed_and_unsigned_match_rdna2() { // v_bfe_i32 v0, v1, v2, v3 (VOP3 opcode 0x149) diff --git a/crates/victory-shader/src/gfx10/fields.rs b/crates/victory-shader/src/gfx10/fields.rs index 2773b3c..bcc0dd3 100644 --- a/crates/victory-shader/src/gfx10/fields.rs +++ b/crates/victory-shader/src/gfx10/fields.rs @@ -235,19 +235,32 @@ impl Instruction { } Encoding::Sopp => Fields::Sopp { imm: w0 as u16 }, Encoding::Smem => { - let data = match name { - "s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => None, - n if n.starts_with("s_dcache_discard") => None, - "s_memtime" | "s_memrealtime" => Some(2), - _ => Some(data_dwords(name)), + let sdata = (w0 >> 6 & 0x7F) as u8; + // s_atc_probe*: SDATA is a 7-bit immediate, not an SGPR. The + // buffer form's resource is 4 dwords. GLC and DLC are not operands. + let probe = matches!(name, "s_atc_probe" | "s_atc_probe_buffer"); + let data = if probe { + Some(Operand::Literal(u32::from(sdata))) + } else { + match name { + "s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => None, + n if n.starts_with("s_dcache_discard") => None, + "s_memtime" | "s_memrealtime" => Some(scalar(sdata, 2)), + _ => Some(scalar(sdata, data_dwords(name))), + } }; - let base = 2 + 2 * u8::from(name.starts_with("s_buffer_")); + let base = + 2 + 2 * u8::from(name.starts_with("s_buffer_") || name == "s_atc_probe_buffer"); Fields::Smem { - data: data.map(|d| scalar((w0 >> 6 & 0x7F) as u8, d)), + data, base: scalar(((w0 & 0x3F) << 1) as u8, base), offset: (w1 << 11) as i32 >> 11, soffset: scalar((w1 >> 25) as u8, 1), - cache: cache(bit(w0, 16), false, bit(w0, 14)), + cache: if probe { + Cache::default() + } else { + cache(bit(w0, 16), false, bit(w0, 14)) + }, } } Encoding::Vop1 | Encoding::Vop2 | Encoding::Vopc | Encoding::Vop3 | Encoding::Vop3p => { @@ -405,6 +418,8 @@ impl Instruction { saddr: (self.encoding != Encoding::Flat) .then(|| scalar(saddr, 1 + u8::from(self.encoding == Encoding::Global))), offset: match self.encoding { + // GFX10 FLAT offsets are 11-bit and unsigned: the + // hardware ignores bit 11. Encoding::Flat => (w0 & 0x7FF) as i16, _ => ((w0 << 4) as i16) >> 4, }, diff --git a/crates/victory-shader/src/gfx10/mod.rs b/crates/victory-shader/src/gfx10/mod.rs index f029ff4..57e6ea2 100644 --- a/crates/victory-shader/src/gfx10/mod.rs +++ b/crates/victory-shader/src/gfx10/mod.rs @@ -352,6 +352,21 @@ mod tests { .collect() } + #[test] + fn flat_offsets_ignore_bit_eleven() { + let offset = |word0: u32| { + let code = bytes(&[word0, 0x0000_0001, S_ENDPGM]); + match decode(&code).unwrap()[0].fields(false) { + Fields::Flat { offset, .. } => offset, + fields => panic!("{fields:?}"), + } + }; + // flat_load_dword v0, v[1:2]: the FLAT offset is 11-bit and + // unsigned, so bit 11 is ignored (0x800 -> 0, 0xfff -> 0x7ff). + assert_eq!(offset(0xDC30_0800), 0); + assert_eq!(offset(0xDC30_0FFF), 0x7FF); + } + #[test] fn tables_are_sorted() { for t in [ diff --git a/crates/victory-shader/src/gfx10/sp3.rs b/crates/victory-shader/src/gfx10/sp3.rs index 0ca5ab4..baf0e82 100644 --- a/crates/victory-shader/src/gfx10/sp3.rs +++ b/crates/victory-shader/src/gfx10/sp3.rs @@ -137,6 +137,12 @@ fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { cache, } => { if let Some(data) = data { + let data = match (name, data) { + ("s_atc_probe" | "s_atc_probe_buffer", Operand::Literal(imm)) => { + atc_immediate(*imm) + } + _ => data.to_string(), + }; let off = match (soffset, offset) { (Operand::Scalar { code: NULL, .. }, 0) => soffset.to_string(), (Operand::Scalar { code: NULL, .. }, _) => { @@ -335,6 +341,15 @@ fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { out } +/// `s_atc_probe` immediate: 0..=64 in decimal, larger values in hex. +fn atc_immediate(imm: u32) -> String { + if imm <= 64 { + imm.to_string() + } else { + format!("0x{imm:x}") + } +} + /// Cache flags; images write `dlc` first. fn flags(out: &mut String, cache: &Cache, dlc_first: bool) { let dlc = (cache.dlc, " dlc"); @@ -660,7 +675,7 @@ fn valu(name: &str, v: &Valu, encoding: Encoding) -> String { #[cfg(test)] mod tests { - use crate::gfx10::{Fields, Operand, decode}; + use crate::gfx10::{Cache, Fields, Operand, decode}; /// Text of each instruction in `words` (a straight-line program). fn texts(words: &[u32], wave64: bool) -> Vec { @@ -700,6 +715,69 @@ mod tests { ); } + /// `s_atc_probe` / `s_atc_probe_buffer`: SDATA is a 7-bit immediate, the + /// buffer resource is 4 dwords, and GLC/DLC are not operands. + /// + /// Words checked with `llvm-mc -arch=amdgcn -mcpu=gfx1030 --disassemble`. + /// The offset keeps this printer's 6-digit hex (`0x000064`, not `0x64`). + #[test] + fn atc_probe_immediate_is_not_a_register() { + let cases = [ + ( + [0xF498_01C2, 0xFA00_0064], + "s_atc_probe 7, s[4:5], 0x000064", + Operand::Literal(7), + Operand::Scalar { code: 4, dwords: 2 }, + ), + ( + [0xF498_1FF4, 0x0A00_0001], + "s_atc_probe 0x7f, s[104:105], s5 offset:0x000001", + Operand::Literal(0x7f), + Operand::Scalar { + code: 104, + dwords: 2, + }, + ), + ( + [0xF498_0000, 0xFA00_0000], + "s_atc_probe 0, s[0:1], null", + Operand::Literal(0), + Operand::Scalar { code: 0, dwords: 2 }, + ), + ( + [0xF49C_01C4, 0xFA00_0020], + "s_atc_probe_buffer 7, s[8:11], 0x000020", + Operand::Literal(7), + Operand::Scalar { code: 8, dwords: 4 }, + ), + ( + [0xF499_41C2, 0xFA00_0000], + "s_atc_probe 7, s[4:5], null", + Operand::Literal(7), + Operand::Scalar { code: 4, dwords: 2 }, + ), + ]; + for (words, text, data, base) in cases { + assert_eq!(one(&words, false), text, "{words:08x?}"); + assert_eq!(one(&words, true), text, "{words:08x?}"); + let mut code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + code.extend(0xBF81_0000u32.to_le_bytes()); + let inst = &decode(&code).unwrap()[0]; + let Fields::Smem { + data: got, + base: got_base, + cache, + .. + } = inst.fields(false) + else { + panic!("not an SMEM instruction"); + }; + assert_eq!(got, Some(data), "{words:08x?}"); + assert_eq!(got_base, base, "{words:08x?}"); + assert_eq!(cache, Cache::default(), "{words:08x?}"); + } + } + #[test] fn lane_masks_follow_the_wave_size() { let cmp = [0x7C08_06F0]; // v_cmp_gt_f32 with 0.5 and v3 From 011735ff809d8655f697d5b2749e2a79d5faabb1 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:24:56 -0600 Subject: [PATCH 182/445] Anisotropic samplers with point mips keep them where the card has them (upstream e45bacd, 23fc8a5, 7dfa86f) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/pipeline/host.rs | 15 +++++- crates/victory-shader/src/emit/host.rs | 14 ++++- crates/victory-shader/src/emit/sampler.rs | 64 ++++++++++++++++++++++- 3 files changed, 90 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 9acd1d2..706758d 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -437,6 +437,19 @@ impl HostPipeline { } let host = host()?; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default(); + // SAFETY: the feature query writes the structure of the given size. + // Older runtimes may not recognize OPTIONS19; that means no support. + let aniso_point_mip_supported = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS19, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + } + .is_ok() + && options.AnisoFilterWithPointMipSupported.as_bool(); + // The root signature the translated shaders' bindings define. let mut params: Vec = Vec::new(); // The ranges table parameters point at, alive until the root @@ -544,7 +557,7 @@ impl HostPipeline { } for (n, s) in t.static_samplers.iter().enumerate() { samplers.push(D3D12_STATIC_SAMPLER_DESC { - Filter: D3D12_FILTER(s.filter as i32), + Filter: D3D12_FILTER(s.filter_for_host(aniso_point_mip_supported) as i32), AddressU: D3D12_TEXTURE_ADDRESS_MODE(s.address[0] as i32), AddressV: D3D12_TEXTURE_ADDRESS_MODE(s.address[1] as i32), AddressW: D3D12_TEXTURE_ADDRESS_MODE(s.address[2] as i32), diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 8f5407a..4bb533f 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -185,12 +185,24 @@ impl Host { ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); } + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default(); + // SAFETY: the feature query writes the structure of the given size. + // Older runtimes may not recognize OPTIONS19; that means no support. + let aniso_point_mip_supported = unsafe { + self.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS19, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + } + .is_ok() + && options.AnisoFilterWithPointMipSupported.as_bool(); let mut samplers = Vec::new(); for &(s, vis) in stages { for (n, d) in s.static_samplers.iter().enumerate() { let [u, v, w] = d.address.map(|a| D3D12_TEXTURE_ADDRESS_MODE(a as i32)); samplers.push(D3D12_STATIC_SAMPLER_DESC { - Filter: D3D12_FILTER(d.filter as i32), + Filter: D3D12_FILTER(d.filter_for_host(aniso_point_mip_supported) as i32), AddressU: u, AddressV: v, AddressW: w, diff --git a/crates/victory-shader/src/emit/sampler.rs b/crates/victory-shader/src/emit/sampler.rs index e10c0c1..ca010e5 100644 --- a/crates/victory-shader/src/emit/sampler.rs +++ b/crates/victory-shader/src/emit/sampler.rs @@ -34,6 +34,18 @@ pub struct StaticSampler { impl Eq for StaticSampler {} impl StaticSampler { + /// The filter supported by the host device. Anisotropic point-mip + /// filtering is optional (`D3D12_OPTIONS19`); older devices retain the + /// previous linear-mip approximation. Comparison/min/max reduction + /// bits and the sampler's LOD bounds are unchanged. + pub fn filter_for_host(&self, aniso_point_mip_supported: bool) -> u32 { + if !aniso_point_mip_supported && self.filter & !0x180 == 0x54 { + self.filter | 1 + } else { + self.filter + } + } + /// Decodes the four sampler words. pub fn from_words(w: [u32; 4]) -> Self { let bits = |word: u32, at: u32, n: u32| word >> at & ((1 << n) - 1); @@ -47,7 +59,7 @@ impl StaticSampler { _ => 0, }; let filter = if mag >= 2 || min >= 2 { - 0x55 | reduction << 7 + 0x54 | u32::from(mip == 2) | reduction << 7 } else { (min & 1) << 4 | (mag & 1) << 2 | u32::from(mip == 2) | reduction << 7 }; @@ -122,4 +134,54 @@ mod tests { (0x1D5, 16, 15.0) ); } + + #[test] + fn anisotropic_samplers_preserve_mip_point_filtering() { + for (reduction, base) in [(0u32, 0x54u32), (1, 0x154), (2, 0x1D4)] { + let w0 = reduction << 29; + for mip in [0u32, 1] { + let w2 = (mip << 26) | 0x00F0_0000; // mag = 3, min = 3 + let s = StaticSampler::from_words([w0, 0x00FF_F000, w2, 0]); + assert_eq!(s.filter, base, "reduction={reduction} mip={mip}"); + } + let w2 = (2 << 26) | 0x00F0_0000; // mip = 2 (linear) + let s = StaticSampler::from_words([w0, 0x00FF_F000, w2, 0]); + assert_eq!(s.filter, base | 1, "reduction={reduction} mip=2"); + } + // Mixed anisotropic mag (2) with linear min (1) and point mip (1). + let mixed = StaticSampler::from_words([0, 0, (1 << 26) | (1 << 22) | (2 << 20), 0]); + assert_eq!(mixed.filter, 0x54); + } + + #[test] + fn host_filter_falls_back_without_changing_reduction_or_lod() { + for (filter, fallback) in [(0x54, 0x55), (0xD4, 0xD5), (0x154, 0x155), (0x1D4, 0x1D5)] { + for mip in [0u32, 1] { + let s = StaticSampler { + filter, + ..StaticSampler::from_words([0, 0x0054_0100, (mip << 26) | 0x00F0_0000, 0]) + }; + assert_eq!(s.filter_for_host(false), fallback); + assert_eq!(s.filter_for_host(true), filter); + assert_eq!( + (s.min_lod, s.max_lod), + if mip == 0 { (0.0, 0.0) } else { (1.0, 5.25) } + ); + } + } + } + + #[test] + fn host_filter_keeps_other_filters_unchanged() { + for reduction in [0, 0x80, 0x100, 0x180] { + for base in [0, 1, 4, 5, 0x10, 0x11, 0x14, 0x15, 0x55] { + let s = StaticSampler { + filter: base | reduction, + ..StaticSampler::from_words([0; 4]) + }; + assert_eq!(s.filter_for_host(false), s.filter); + assert_eq!(s.filter_for_host(true), s.filter); + } + } + } } From 75cfb234e5bf9fa4e1e9912bd6d850860e82f5da Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:25:15 -0600 Subject: [PATCH 183/445] Upstream graphics state fixes: rectangle attributes, sampler bounds, A8 copies, depth footprints Ports of 6f36cdf (normalized attributes of rectangle lists), 97c8783 (A8_UNORM is not of the R8 typeless family), b956320 (copy footprints of depth-stencil textures), c1c3281 (the descriptor ring's wrap), e6fe8ec and e34cb53 (CreateSamplerX bounds), 691236d (appended elements are aligned). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 28 ++++- crates/victory-gpu/src/pipeline/host.rs | 69 ++++++++++- crates/victory-gpu/src/primitive.rs | 48 +++++++- crates/victory-gpu/src/resource.rs | 97 +++++++++++++--- crates/victory-gpu/src/sampler.rs | 132 ++++++++++++++++++++-- 5 files changed, 344 insertions(+), 30 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 213a11a..39cfb15 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -861,8 +861,12 @@ impl HostHeap { let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n && n < self.too_long.load(std::sync::atomic::Ordering::Relaxed); let n = n as usize; - // Search from `next` on, then from the start. - let starts = (*next as usize..self.dynamic as usize).chain(0..*next as usize); + // Search from `next` on, then from the start (extending past cursor by + // n - 1 so contiguous runs crossing the cursor are not missed). + let cursor = *next as usize; + let end = self.dynamic as usize; + let second_end = cursor.saturating_add(n.saturating_sub(1)).min(end); + let starts = (cursor..end).chain(0..second_end); let mut run = 0; let mut found = None; let mut last = usize::MAX; @@ -2836,4 +2840,24 @@ mod tests { assert_eq!(heap.dynamic(50), Some(4)); assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); } + + /// Contiguous free dynamic slot ranges that cross the search cursor are found. + #[test] + fn dynamic_allocation_finds_contiguous_range_crossing_search_cursor() { + let Some(heap) = HostHeap::new(false, 4) else { + return; // no host GPU + }; + // Allocate slots 0..8, advancing cursor to 8. + let a = heap.dynamic(8).unwrap(); + // Allocate slots 8..16, advancing cursor to 16. + let b = heap.dynamic(8).unwrap(); + assert_eq!((a, b), (4, 12)); + + // Release slots 10..14 (crossing cursor at 12). + // Before the fix, a request of 4 slots starting search at 12 scanned 12..end then 0..12, + // missing the contiguous run at 10..14. + heap.release(14, 4); + let c = heap.dynamic(4); + assert_eq!(c, Some(14)); + } } diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 706758d..e3559c3 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -296,13 +296,19 @@ impl GraphicsState { .map(|e| { let slot = e.InputSlot.min(31) as usize; let format = e.Format.0 as u32; + let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32); + // An appended element starts at the next multiple of + // min(4, its size) after the previous one, where D3D12 (and + // vkd3d) place it; the host pipeline gets the title's + // descriptions, so the offsets read here must match. let offset = if e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT { next[slot] + .checked_next_multiple_of(bytes.clamp(1, 4)) + .unwrap_or(u32::MAX) } else { e.AlignedByteOffset }; - let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32); - next[slot] = offset + bytes; + next[slot] = offset.saturating_add(bytes); Input { slot: slot as u32, offset, @@ -1444,4 +1450,63 @@ mod tests { assert_eq!(run_draw(0.6, 1.0), 0, "depth 0.5 outside [0.6, 1.0] must be rejected"); assert_eq!(run_draw(0.4, 0.6), 255, "depth 0.5 inside [0.4, 0.6] must pass"); } + + fn element(format: DXGI_FORMAT, offset: u32) -> D3D12_INPUT_ELEMENT_DESC { + D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(c"TEXCOORD".as_ptr().cast()), + SemanticIndex: 0, + Format: format, + InputSlot: 0, + AlignedByteOffset: offset, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + InstanceDataStepRate: 0, + } + } + + fn offsets(inputs: &[D3D12_INPUT_ELEMENT_DESC]) -> Vec { + let state = GraphicsState { + inputs: inputs.to_vec(), + ..GraphicsState::default() + }; + state.elements().iter().map(|e| e.offset).collect() + } + + /// An appended element after one of 1 or 2 bytes started right after + /// it; D3D12 aligns it to min(4, its size), so the rectangle expansion + /// read its vertices from the wrong bytes. + #[test] + fn appended_elements_are_aligned() { + const APPEND: u32 = D3D12_APPEND_ALIGNED_ELEMENT; + // RG8 (2 bytes) then RG32 float: 4, not 2. + let a = [ + element(DXGI_FORMAT_R8G8_UNORM, 0), + element(DXGI_FORMAT_R32G32_FLOAT, APPEND), + ]; + assert_eq!(offsets(&a), [0, 4]); + // R8 then R16 float: 2, not 1; then R8 packs right after it. + let b = [ + element(DXGI_FORMAT_R8_UNORM, 0), + element(DXGI_FORMAT_R16_FLOAT, APPEND), + element(DXGI_FORMAT_R8_UNORM, APPEND), + ]; + assert_eq!(offsets(&b), [0, 2, 4]); + // Already aligned layouts are unchanged. + let c = [ + element(DXGI_FORMAT_R8G8B8A8_UNORM, 0), + element(DXGI_FORMAT_R32G32_FLOAT, APPEND), + element(DXGI_FORMAT_R32G32B32_FLOAT, APPEND), + ]; + assert_eq!(offsets(&c), [0, 4, 12]); + } + + /// An explicit offset near 4 GiB overflowed the next appended offset + /// (a panic in debug builds). + #[test] + fn a_huge_explicit_offset_does_not_overflow() { + let inputs = [ + element(DXGI_FORMAT_R32G32B32A32_FLOAT, u32::MAX - 8), + element(DXGI_FORMAT_R32_FLOAT, D3D12_APPEND_ALIGNED_ELEMENT), + ]; + let _ = offsets(&inputs); + } } diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index 3f73ee7..180e43e 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -55,6 +55,8 @@ enum Kind { F16, Unorm8, Unorm16, + Snorm8, + Snorm16, } /// Component count and kind of the vertex formats rectangles use. @@ -69,7 +71,16 @@ fn components(format: u32) -> Option<(usize, Kind)> { 54 => (1, Kind::F16), 11 => (4, Kind::Unorm16), 35 => (2, Kind::Unorm16), + 56 => (1, Kind::Unorm16), 28 | 29 | 87 | 91 => (4, Kind::Unorm8), + 49 => (2, Kind::Unorm8), + 61 => (1, Kind::Unorm8), + 13 => (4, Kind::Snorm16), + 37 => (2, Kind::Snorm16), + 58 => (1, Kind::Snorm16), + 31 => (4, Kind::Snorm8), + 51 => (2, Kind::Snorm8), + 63 => (1, Kind::Snorm8), _ => return None, }) } @@ -78,8 +89,8 @@ impl Kind { fn bytes(self) -> usize { match self { Kind::F32 => 4, - Kind::F16 | Kind::Unorm16 => 2, - Kind::Unorm8 => 1, + Kind::F16 | Kind::Unorm16 | Kind::Snorm16 => 2, + Kind::Unorm8 | Kind::Snorm8 => 1, } } @@ -90,6 +101,8 @@ impl Kind { Kind::F16 => half_to_f32(u16::from_le_bytes([b[0], b[1]])), Kind::Unorm16 => f32::from(u16::from_le_bytes([b[0], b[1]])) / 65535.0, Kind::Unorm8 => f32::from(b[0]) / 255.0, + Kind::Snorm16 => (f32::from(i16::from_le_bytes([b[0], b[1]])) / 32767.0).max(-1.0), + Kind::Snorm8 => (f32::from(b[0] as i8) / 127.0).max(-1.0), } } @@ -103,6 +116,10 @@ impl Kind { b.copy_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_le_bytes()) } Kind::Unorm8 => b[0] = (v.clamp(0.0, 1.0) * 255.0).round() as u8, + Kind::Snorm16 => { + b.copy_from_slice(&((v.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes()) + } + Kind::Snorm8 => b[0] = (v.clamp(-1.0, 1.0) * 127.0).round() as i8 as u8, } } } @@ -218,6 +235,33 @@ mod tests { assert_eq!(dst[40..], vertex(4.0, 6.0)[..]); } + #[test] + fn normalized_attributes_are_interpolated_in_their_own_range() { + let vertex = |rg: [u8; 2], u16_value: u16, u8_value: u8, snorm8: i8, snorm16: i16| { + [ + &rg[..], + &u16_value.to_le_bytes(), + &[u8_value, snorm8 as u8], + &snorm16.to_le_bytes(), + ] + .concat() + }; + let src = [ + vertex([3, 250], 1000, 10, i8::MIN, -23000), + vertex([8, 200], 500, 3, -120, -18000), + vertex([20, 253], 10000, 100, -120, -32000), + ] + .concat(); + let mut dst = [0; 6 * 8]; + expand_rects( + &src, + &mut dst, + 8, + &[(0, 49), (2, 56), (4, 61), (5, 63), (6, 58)], + ); + assert_eq!(dst[40..], vertex([15, 255], 10500, 107, -127, -32767)); + } + /// `half_to_f32` reads subnormals, so an f16 rectangle output must be /// able to write them back instead of flushing every one to zero. #[test] diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 1b74262..3cdd30f 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -585,7 +585,7 @@ pub(crate) fn family(format: u32) -> u32 { (44, 47), (48, 52), (53, 59), - (60, 65), + (60, 64), (70, 72), (73, 75), (76, 78), @@ -695,8 +695,7 @@ const NO_FOOTPRINT: PlacedFootprint = PlacedFootprint { row_pitch: 0, }; -/// One subresource's size in an upload buffer: footprint (offset 0), rows -/// and bytes per row. Planes of depth-stencil formats are not told apart. +/// One subresource's upload footprint (offset 0), row count and unpadded row size. fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, u64)> { const PITCH: u64 = 256; if desc.dimension == BUFFER { @@ -716,11 +715,18 @@ fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, } else { u32::from(desc.depth_or_array_size).max(1) }; - let (mip, slice) = (index % mips, index / mips); - if slice >= slices { - return None; - } - let (element, block) = element(desc.format)?; + let mip = index % mips; + let plane = index / mips / slices; + let depth_stencil = matches!(desc.format, 19..=22 | 44..=47); + // Each plane contains all the mip levels and array slices. Depth and + // stencil copies use separate formats and 512-byte row alignment. + let (format, pitch_alignment) = match (depth_stencil, plane) { + (true, 0) => (39, 512), // DXGI_FORMAT_R32_TYPELESS + (true, 1) => (60, 512), // DXGI_FORMAT_R8_TYPELESS + (false, 0) => (desc.format, PITCH), + _ => return None, + }; + let (element, block) = element(format)?; let width = (desc.width >> mip).max(1).next_multiple_of(block); let height = (u64::from(desc.height) >> mip) .max(1) @@ -733,18 +739,18 @@ fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, let row_size = width / block * element; let footprint = PlacedFootprint { offset: 0, - format: desc.format, + format, width: u32::try_from(width).ok()?, height: u32::try_from(height).ok()?, depth, - row_pitch: u32::try_from(row_size.next_multiple_of(PITCH)).ok()?, + row_pitch: u32::try_from(row_size.next_multiple_of(pitch_alignment)).ok()?, }; Some((footprint, u32::try_from(height / block).ok()?, row_size)) } -/// Device method: where each subresource goes in an upload buffer, rows -/// 256-byte and subresources 512-byte aligned, as on PC. Unknown sizes give -/// the documented all-ones values. +/// Places subresources at 512-byte boundaries in an upload buffer. +/// Row pitch is aligned to 512 bytes for depth/stencil planes and 256 bytes +/// otherwise. Unknown sizes give the documented all-ones values. pub(crate) extern "system" fn copyable_footprints( _: This, desc: *const ResourceDesc, @@ -2559,6 +2565,22 @@ mod tests { use super::*; use crate::object::slot; + #[test] + fn a8_unorm_is_not_in_the_r8_typeless_family() { + // DXGI_FORMAT values: 60 R8_TYPELESS, 61 R8_UNORM, 62 R8_UINT, + // 63 R8_SNORM, 64 R8_SINT, 65 A8_UNORM. The R8 typeless family is + // 60..=64; A8_UNORM has no typeless family and cannot be cast to R8, + // so it must stand alone rather than fold into R8_TYPELESS. + assert_eq!(family(60), 60); + for f in 61..=64 { + assert_eq!(family(f), 60); + } + assert_eq!(family(65), 65); + // Boundaries: 59 belongs to the preceding family, 66 is unmapped. + assert_eq!(family(59), 53); + assert_eq!(family(66), 66); + } + type Release = extern "system" fn(This) -> u32; type Map = extern "system" fn(This, u32, *const c_void, *mut *mut u8) -> HRESULT; type Address = extern "system" fn(This) -> u64; @@ -2790,6 +2812,55 @@ mod tests { assert_eq!(t, u64::MAX, "no second subresource"); } + #[test] + fn depth_stencil_footprints_follow_the_pc_plane_order() { + // Native D3D12 reports the same layout for both depth/stencil families + // and their view formats. Mips vary fastest, then array slices, then planes. + let expected = [ + (512, 39, 16, 8), + (4_608, 39, 8, 4), + (6_656, 39, 16, 8), + (10_752, 39, 8, 4), + (12_800, 60, 16, 8), + (16_896, 60, 8, 4), + (18_944, 60, 16, 8), + (23_040, 60, 8, 4), + ]; + for format in (19..=22).chain(44..=47) { + let desc = ResourceDesc { + depth_or_array_size: 2, + ..texture(16, 8, format, 2) + }; + let mut layouts = [NO_FOOTPRINT; 8]; + let (mut rows, mut sizes, mut total) = ([0; 8], [0; 8], 0); + copyable_footprints( + std::ptr::null(), + &desc, + 0, + 8, + 512, + layouts.as_mut_ptr(), + rows.as_mut_ptr(), + sizes.as_mut_ptr(), + &mut total, + ); + + assert_eq!( + layouts.map(|l| (l.offset, l.format, l.width, l.height)), + expected, + "format {format}" + ); + assert!( + layouts.iter().all(|l| l.depth == 1 && l.row_pitch == 512), + "format {format}" + ); + assert_eq!(rows, [8, 4, 8, 4, 8, 4, 8, 4], "format {format}"); + assert_eq!(sizes, [64, 32, 64, 32, 16, 8, 16, 8], "format {format}"); + assert_eq!(total, 24_072, "format {format}"); + assert!(subresource(&desc, 8).is_none(), "format {format}"); + } + } + /// A 4x4 texture filled from a title buffer through our list and queue, /// then read back from the host GPU. #[cfg(windows)] diff --git a/crates/victory-gpu/src/sampler.rs b/crates/victory-gpu/src/sampler.rs index ee95da3..2132273 100644 --- a/crates/victory-gpu/src/sampler.rs +++ b/crates/victory-gpu/src/sampler.rs @@ -47,30 +47,58 @@ impl Fields { } else { linear(self.min) << 4 | linear(self.mag) << 2 | u32::from(self.mip == 2) }; + let min_lod = finite_lod(self.min_lod, 0.0); + // Without a mip filter the console clamps sampling to `min_lod`. + let max_lod = if self.mip == 0 { + min_lod + } else { + finite_lod(self.max_lod, min_lod).max(min_lod) + }; D3D12_SAMPLER_DESC { Filter: D3D12_FILTER((reduction << 7 | filter) as i32), - AddressU: D3D12_TEXTURE_ADDRESS_MODE(self.address[0] as i32), - AddressV: D3D12_TEXTURE_ADDRESS_MODE(self.address[1] as i32), - AddressW: D3D12_TEXTURE_ADDRESS_MODE(self.address[2] as i32), - MipLODBias: self.bias, + AddressU: address_mode(self.address[0]), + AddressV: address_mode(self.address[1]), + AddressW: address_mode(self.address[2]), + MipLODBias: if self.bias.is_nan() { + 0.0 + } else { + self.bias + .clamp(D3D12_MIP_LOD_BIAS_MIN, D3D12_MIP_LOD_BIAS_MAX) + }, MaxAnisotropy: if aniso { self.anisotropy.clamp(1, 16) } else { 1 }, - ComparisonFunc: D3D12_COMPARISON_FUNC(self.compare.max(1) as i32), - BorderColor: self.border, - MinLOD: self.min_lod, - // Without a mip filter the console samples mip 0 only. - MaxLOD: if self.mip == 0 { - self.min_lod + ComparisonFunc: if reduction == 1 { + D3D12_COMPARISON_FUNC(self.compare as i32) } else { - self.max_lod + D3D12_COMPARISON_FUNC_NEVER }, + BorderColor: self.border, + MinLOD: min_lod, + MaxLOD: max_lod, } } } +/// Maps a console address mode (`1..=5`) to host D3D12, falling back to `CLAMP`. +fn address_mode(mode: u32) -> D3D12_TEXTURE_ADDRESS_MODE { + match mode { + 1..=5 => D3D12_TEXTURE_ADDRESS_MODE(mode as i32), + _ => D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + } +} + +/// Sanitizes an LOD bound for D3D12, substituting `fallback` for `NaN` and clamping infinities. +fn finite_lod(value: f32, fallback: f32) -> f32 { + if value.is_nan() { + fallback + } else { + value.clamp(-D3D12_FLOAT32_MAX, D3D12_FLOAT32_MAX) + } +} + /// The console's sampler description (27 words): flags, magnification, /// minification, mip and depth filters, filter mode, three address modes, /// minimum and maximum LOD, LOD bias, secondary bias, anisotropy, its bias @@ -116,4 +144,86 @@ mod tests { w[16] = 1; assert_eq!(console(&w).Filter.0, 0x5); } + + #[test] + fn mip_none_clamps_to_min_lod_and_inverted_lod_range_clamps() { + let mut w = [0u32; 27]; + w[3] = 0; // mip none + w[9] = 3.0f32.to_bits(); + w[10] = 8.0f32.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (3.0, 3.0)); + + w[9] = f32::NAN.to_bits(); + w[10] = 8.0f32.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (0.0, 0.0)); + + w[9] = f32::INFINITY.to_bits(); + w[10] = 8.0f32.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (D3D12_FLOAT32_MAX, D3D12_FLOAT32_MAX)); + + w[3] = 2; // linear mips + w[9] = 4.0f32.to_bits(); + w[10] = 1.0f32.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (4.0, 4.0)); + + w[9] = f32::NAN.to_bits(); + w[10] = f32::INFINITY.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (0.0, D3D12_FLOAT32_MAX)); + + w[9] = 2.5f32.to_bits(); + w[10] = f32::NAN.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (2.5, 2.5)); + + w[9] = f32::NEG_INFINITY.to_bits(); + w[10] = f32::NEG_INFINITY.to_bits(); + let d = console(&w); + assert_eq!( + (d.MinLOD, d.MaxLOD), + (-D3D12_FLOAT32_MAX, -D3D12_FLOAT32_MAX) + ); + } + + #[test] + fn bias_address_and_comparison_stay_in_host_bounds() { + let mut w = [0u32; 27]; + w[6..9].copy_from_slice(&[0, 6, 3]); + w[11] = 24.0f32.to_bits(); + w[16] = 99; + let d = console(&w); + assert_eq!(d.MipLODBias, D3D12_MIP_LOD_BIAS_MAX); + assert_eq!( + [d.AddressU, d.AddressV, d.AddressW], + [D3D12_TEXTURE_ADDRESS_MODE_CLAMP; 3] + ); + assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_NEVER); + + w[11] = (-24.0f32).to_bits(); + w[5] = 1; // minimum reduction + w[16] = 4; // less-or-equal, ignored when reduction != 1 + let d = console(&w); + assert_eq!(d.MipLODBias, D3D12_MIP_LOD_BIAS_MIN); + assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_NEVER); + + w[11] = f32::NAN.to_bits(); + w[5] = 0; // plain mode, reduction == 1 from compare == 4 + w[6..9].copy_from_slice(&[1, 4, 5]); + w[16] = 4; + let d = console(&w); + assert_eq!(d.MipLODBias, 0.0); + assert_eq!( + [d.AddressU, d.AddressV, d.AddressW], + [ + D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE_BORDER, + D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE, + ] + ); + assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_LESS_EQUAL); + } } From 4e3e0654bf9b2cb554849123a95d51b3ce3d7b4e Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:25:32 -0600 Subject: [PATCH 184/445] Typed buffer loads of 16-bit channels pack two per register; skipped devices say why (upstream c430b1d, 100de0e) Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/diff_tests.rs | 36 ++++++++----- crates/victory-shader/src/emit/lower.rs | 44 +++++++++++++-- crates/victory-shader/src/emit/mod.rs | 9 ++-- crates/victory-shader/src/emit/valu_tests.rs | 54 +++++++++++++++++-- .../src/emit/waterfall_tests.rs | 9 ++-- 5 files changed, 128 insertions(+), 24 deletions(-) diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index 4727b92..b43a0a7 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -718,9 +718,12 @@ fn translated_shaders_draw_as_pc_ones() { eprintln!("no console or PC compiler; skipped"); return; }; - let Ok(host) = Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let dir = std::env::temp_dir().join(format!("victory-diff-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -874,9 +877,12 @@ fn translated_mesh_shaders_draw_as_pc_ones() { eprintln!("no console or PC compiler; skipped"); return; }; - let Ok(host) = Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let dir = std::env::temp_dir().join(format!("victory-diff-ms-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -991,9 +997,12 @@ fn float_semantics_are_the_consoles() { eprintln!("no console compiler; skipped"); return; }; - let Ok(host) = Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let dir = std::env::temp_dir().join(format!("victory-float-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -1080,9 +1089,12 @@ fn translated_compute_matches_pc() { eprintln!("no console or PC compiler; skipped"); return; }; - let Ok(host) = Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let dir = std::env::temp_dir().join(format!("victory-diff-cs-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c3bda73..7598738 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6414,6 +6414,39 @@ impl<'a> Lower<'a> { Ok(out) } + /// 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 + /// others become f16. + fn d16_channels(&mut self, format: u8, channels: Vec) -> Result, Why> { + let (_, numeric) = buffer_format(format).ok_or("a buffer format")?; + let c = self.cur; + let mut halves = Vec::new(); + for x in channels { + halves.push(if matches!(numeric, Numeric::Uint | Numeric::Sint) { + let m = self.s.m.i32(0xFFFF); + self.s.m.bin(c, Bin::And, x, m) + } else { + let (f, i32t) = (self.as_float(x), self.s.t.i32); + self.s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) + }); + } + let mut out = Vec::new(); + for pair in halves.chunks(2) { + out.push(match *pair { + [lo, hi] => { + let k16 = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, hi, k16); + self.s.m.bin(c, Bin::Or, lo, hi) + } + [lo] => lo, + _ => unreachable!("chunks of one or two"), + }); + } + Ok(out) + } + /// The byte offset a buffer descriptor built around a root descriptor adds /// (constant and computed parts); none for other descriptors. fn built_offset(&mut self, src: &Source) -> Result<(u32, Option), Why> { @@ -10808,8 +10841,9 @@ impl<'a> Lower<'a> { "buffer_load_sshort" => Some((16, true)), _ => None, }; - // d16: two 16-bit channels per VGPR, low half first. - let d16 = name.starts_with("buffer_") && name.contains("_format_d16_"); + // d16: two 16-bit channels per VGPR, low half first (buffer and + // tbuffer formats alike). + let d16 = name.contains("_format_d16_"); let plain = name.replace("_format_d16_", "_format_"); let (typed, count) = match plain .strip_prefix("buffer_load_") @@ -11143,7 +11177,11 @@ impl<'a> Lower<'a> { let Some(Operand::Vector { reg, .. }) = *data else { return Err("a buffer result"); }; - for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() { + let mut xs = self.format_load(h, off, f, count)?; + if d16 { + xs = self.d16_channels(f, xs)?; + } + for (k, x) in xs.into_iter().enumerate() { self.write(inst, Reg::V(reg + k as u8), x, guard); } return Ok(()); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 986e669..248e8c9 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -1252,9 +1252,12 @@ mod tests { #[test] #[cfg(windows)] fn stub_pipeline_is_created() { - let Ok(host) = super::host::Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match super::host::Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let ps = super::HostShader { stage: crate::HwStage::Ps, diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index ee69d98..65c0c9d 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -219,9 +219,12 @@ fn run_cases_on( let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let mut ran = 0; for &(label, warp) in devices { - let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); - continue; + let host = match Host::new(warp) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 {label} device ({e}); skipped"); + continue; + } }; let (root, pso) = host .compute_pipeline(shader) @@ -320,6 +323,51 @@ fn f16_to_f32(bits: u16) -> f32 { f32::from_bits(f32_bits) } +/// MTBUF `op vdata, off, s[srsrc:srsrc+3], 0 format:format` (at byte 0). +const fn mtbuf(op: u8, vdata: u8, srsrc: u8, format: u8) -> [u32; 2] { + [ + 0x3A << 26 | (format as u32 & 0x7F) << 19 | (op as u32 & 7) << 16, + 0x80 << 24 + | (op as u32 >> 3 & 1) << 21 + | (srsrc as u32 >> 2 & 0x1F) << 16 + | (vdata as u32) << 8, + ] +} + +/// Stores `v1` to the buffer, then reads it back into `v0` with the tbuffer +/// load `op` in buffer format `format`. +fn tbuffer_load_of_v1(op: u8, format: u8) -> HostShader { + let mut body = buffer_store_dword(1, 8, 0).to_vec(); + body.extend(mtbuf(op, 0, 8, format)); + build_valu_cs(&body) +} + +#[test] +fn tbuffer_d16_loads_pack_two_channels_per_dword() { + // tbuffer_load_format_d16_x and tbuffer_load_format_d16_xy. + let (x, xy) = (8, 9); + // (opcode, format, dword stored, dword loaded) + let cases: &[(u8, u8, u32, u32)] = &[ + // 16_16_FLOAT: the f16 pair (1.0, 2.0) as it was stored. + (xy, 29, 0x4000_3C00, 0x4000_3C00), + // 16_16_UINT: the 16-bit integers as they were stored. + (xy, 27, 0xBEEF_1234, 0xBEEF_1234), + // 16_16_UNORM: 0.0 and 1.0, as f16. + (xy, 23, 0xFFFF_0000, 0x3C00_0000), + // 16_FLOAT, one channel: the high half is 0. + (x, 13, 0x4000_3C00, 0x0000_3C00), + ]; + for &(op, format, stored, want) in cases { + let shader = tbuffer_load_of_v1(op, format); + run_cases(&shader, &[[stored, 0, 0, 0]], |backend, _, _, got| { + assert_eq!( + got, want, + "{backend}: d16 opcode {op} format {format} of {stored:#010x} = {got:#010x}, want {want:#010x}", + ); + }); + } +} + #[test] fn normalized_buffer_formats_load_their_ends_exactly() { // tbuffer_load_format_x. diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 31dadd6..85e2b1a 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -115,9 +115,12 @@ pub(super) fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec .lock() .unwrap_or_else(|e| e.into_inner()); for (label, warp) in [("hardware", false), ("warp", true)] { - let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); - continue; + let host = match Host::new(warp) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 {label} device ({e}); skipped"); + continue; + } }; let (root, pso) = match host.compute_pipeline(shader) { Ok(p) => p, From fbc183085801939cac7b469eb0ce5956d8e0377f Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:40:43 -0600 Subject: [PATCH 185/445] DirectStorage reads files on a handle per worker; its page lookups do not wait for the title's mapping calls - All 24 workers read each file through one handle, whose reads the host does one after the other: 48 KiB at random from levels.rpf gave 185 MB/s where a handle per worker gives 990 (5 GB/s against 14 from the cache). VICTORY_DSTORAGE_IO=one|handles|overlapped|direct (handles). - xmem: the title's pages by number, and where it sees them, each have a lock of their own, apart from the one its mapping calls hold while the host maps, commits and unmaps. Looking pages up, filling one and telling of it, 24 threads beside one that maps: 2.7 million requests a second for 0.57, 145,000 maps a second for 60,000. A view is noted before the GPU side is told of it, so that a write between the two is not missed. - Title memory is not touched with these locks held. Benchmarks: read_bench (VICTORY_BENCH_FILE), map_bench, both ignored. Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/Cargo.toml | 1 + crates/victory-hle/src/modules/dstorage.rs | 268 ++++++++++++++++++++- crates/victory-hle/src/modules/xmem.rs | 268 ++++++++++++++------- 3 files changed, 448 insertions(+), 89 deletions(-) diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index a2fa943..3522b74 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -24,6 +24,7 @@ windows-sys = { workspace = true, features = [ "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_Debug", + "Win32_System_IO", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Power", diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 0c5c430..9c0ec37 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -149,7 +149,8 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened"); // SAFETY: a handle we just opened and nobody else owns. let file = unsafe { std::fs::File::from_raw_handle(handle) }; - let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file }); + let files = Files::new(file, Io::chosen()); + let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { files }); WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept)); put(out, file) } @@ -263,7 +264,184 @@ static FACTORY_VTABLE: Methods<16> = Methods([ // Files. struct File { - file: std::fs::File, + files: Files, +} + +/// How files are read (`VICTORY_DSTORAGE_IO`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Io { + /// `one`: all workers through the one handle, as before. The host does + /// the reads of a handle one after the other. + One, + /// `handles`: a handle for each worker. + Handles, + /// `overlapped`: one handle, whose reads the host does side by side. + Overlapped, + /// `direct`: a handle for each worker, past the host's file cache. + Direct, +} + +impl Io { + fn chosen() -> Io { + static CHOSEN: OnceLock = OnceLock::new(); + *CHOSEN.get_or_init(|| { + let io = match std::env::var("VICTORY_DSTORAGE_IO").as_deref().map(str::trim) { + Ok("one") => Io::One, + Ok("handles") => Io::Handles, + Ok("overlapped") => Io::Overlapped, + Ok("direct") => Io::Direct, + _ => Io::DEFAULT, + }; + tracing::info!(?io, "dstorage: how files are read (VICTORY_DSTORAGE_IO)"); + io + }) + } + + const DEFAULT: Io = Io::Handles; +} + +/// A file as the workers read it: the handle the title opened, and those +/// made from it when a worker first reads. +struct Files { + first: std::fs::File, + others: Box<[OnceLock>]>, + io: Io, +} + +impl Files { + fn new(first: std::fs::File, io: Io) -> Files { + let workers = std::thread::available_parallelism().map_or(4, |n| n.get()); + let others = match io { + Io::One => 0, + Io::Overlapped => 1, + Io::Handles | Io::Direct => workers, + }; + Files { first, others: (0..others).map(|_| OnceLock::new()).collect(), io } + } + + #[cfg(test)] + fn open_for_test(path: &str, io: Io) -> Files { + Files::new(std::fs::File::open(path).unwrap(), io) + } + + /// Reads at `offset`; as [`FileExt::seek_read`]. + fn read_at(&self, out: &mut [u8], offset: u64) -> std::io::Result { + use windows_sys::Win32::Storage::FileSystem::{FILE_FLAG_NO_BUFFERING, FILE_FLAG_OVERLAPPED}; + let flags = match self.io { + Io::One | Io::Handles => 0, + Io::Overlapped => FILE_FLAG_OVERLAPPED, + Io::Direct => FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, + }; + let other = match self.others.len() { + 0 => None, + n => self.others[this_thread() % n].get_or_init(|| reopen(&self.first, flags)).as_ref(), + }; + match (other, self.io) { + (Some(file), Io::Overlapped) => read_overlapped(file, out, offset), + (Some(file), Io::Direct) => read_direct(file, out, offset), + (file, _) => file.unwrap_or(&self.first).seek_read(out, offset), + } + } +} + +/// A number for this thread: 0 for the first that asks, and so on. +fn this_thread() -> usize { + static NEXT: AtomicU32 = AtomicU32::new(0); + thread_local! { + static NUMBER: usize = NEXT.fetch_add(1, Ordering::Relaxed) as usize; + } + NUMBER.with(|n| *n) +} + +/// Another handle to `file`, for reading; `None` if the host gives none +/// (then the first one is used). +fn reopen(file: &std::fs::File, flags: u32) -> Option { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Foundation::{GENERIC_READ, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, ReOpenFile}; + // SAFETY: a file we hold open. + let handle = unsafe { ReOpenFile(file.as_raw_handle(), GENERIC_READ, FILE_SHARE_READ, flags) }; + if handle == INVALID_HANDLE_VALUE { + tracing::warn!(error = %std::io::Error::last_os_error(), flags, "dstorage: a file could not be opened again"); + return None; + } + // SAFETY: a handle just opened, ours alone. + Some(unsafe { std::fs::File::from_raw_handle(handle) }) +} + +/// A read through a handle opened for overlapped reads, waited for. +fn read_overlapped(file: &std::fs::File, out: &mut [u8], offset: u64) -> std::io::Result { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Foundation::{CloseHandle, ERROR_HANDLE_EOF, ERROR_IO_PENDING, HANDLE}; + use windows_sys::Win32::Storage::FileSystem::ReadFile; + use windows_sys::Win32::System::IO::{GetOverlappedResult, OVERLAPPED}; + use windows_sys::Win32::System::Threading::CreateEventW; + /// Set when this thread's read is done. + struct Event(HANDLE); + impl Drop for Event { + fn drop(&mut self) { + // SAFETY: our own event. + unsafe { CloseHandle(self.0) }; + } + } + thread_local! { + static DONE: Event = + // SAFETY: a plain manual-reset event. + Event(unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) }); + } + DONE.with(|done| { + if done.0.is_null() { + return Err(std::io::Error::last_os_error()); + } + let mut overlapped = OVERLAPPED { hEvent: done.0, ..Default::default() }; + overlapped.Anonymous.Anonymous.Offset = offset as u32; + overlapped.Anonymous.Anonymous.OffsetHigh = (offset >> 32) as u32; + let len = out.len().min(1 << 30) as u32; + let mut n = 0; + // SAFETY: `out` and `overlapped` stay until the read is done, which + // is waited for. + let mut read = unsafe { + ReadFile(file.as_raw_handle(), out.as_mut_ptr(), len, std::ptr::null_mut(), &mut overlapped) + } != 0; + let mut error = std::io::Error::last_os_error(); + if read || error.raw_os_error() == Some(ERROR_IO_PENDING as i32) { + // SAFETY: as above. + read = unsafe { GetOverlappedResult(file.as_raw_handle(), &overlapped, &mut n, 1) } != 0; + error = std::io::Error::last_os_error(); + } + match error.raw_os_error() { + _ if read => Ok(n as usize), + Some(code) if code == ERROR_HANDLE_EOF as i32 => Ok(0), + _ => Err(error), + } + }) +} + +/// A read past the file cache: of the whole sectors around the bytes, into +/// a buffer of this thread's, unless `out` takes them as they are. +fn read_direct(file: &std::fs::File, out: &mut [u8], offset: u64) -> std::io::Result { + /// Every disk's sectors are at most this; offsets, sizes and addresses + /// are multiples of it. + const SECTOR: usize = 4096; + /// Read at a time. + const MOST: usize = 1 << 20; + let sector = SECTOR as u64; + if offset % sector == 0 && out.len() % SECTOR == 0 && out.as_ptr() as usize % SECTOR == 0 { + return read_overlapped(file, out, offset); + } + thread_local! { + static BUFFER: std::cell::RefCell> = std::cell::RefCell::new(vec![0; MOST + SECTOR]); + } + BUFFER.with_borrow_mut(|buffer| { + let skip = buffer.as_ptr().align_offset(SECTOR); + let before = (offset % sector) as usize; + let len = (before + out.len()).next_multiple_of(SECTOR).min(MOST); + let aligned = &mut buffer[skip..skip + len]; + let read = read_overlapped(file, aligned, offset - before as u64)?; + let n = read.saturating_sub(before).min(out.len()); + out[..n].copy_from_slice(&aligned[before..before + n]); + Ok(n) + }) } static FILE_VTABLE: Methods<8> = Methods([ @@ -1248,16 +1426,16 @@ fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { return Ok(()); } // SAFETY: a file object we created; the title keeps it open. - let file = &unsafe { &*request.source.cast::>() } + let files = &unsafe { &*request.source.cast::>() } .state - .file; + .files; let started = std::time::Instant::now(); let (mut done, mut tries) = (0, 0); let result = loop { if done == out.len() { break Ok(()); } - let error = match file.seek_read(&mut out[done..], request.offset + done as u64) { + let error = match files.read_at(&mut out[done..], request.offset + done as u64) { Ok(0) => break Err(END_OF_FILE), Ok(n) => { done += n; @@ -1820,6 +1998,86 @@ mod tests { assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, plain.len()) }, plain); } + /// What ways of reading a file give, at `VICTORY_BENCH_FILE` (a file of + /// the title's, only read): 24 threads, requests of 48 KiB at random, + /// first from places nobody read lately, then the same once more. + /// `VICTORY_BENCH_FILE=... cargo test --release -p victory-hle --lib + /// read_bench -- --ignored --nocapture` + #[test] + #[ignore = "a benchmark"] + fn read_bench() { + const THREADS: usize = 24; + const SIZE: usize = 48 << 10; + const READS: usize = 12_000; + let path = std::env::var("VICTORY_BENCH_FILE").expect("VICTORY_BENCH_FILE"); + let len = std::fs::metadata(&path).unwrap().len(); + let mut seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() as u64 | 1; + let mut random = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for round in 0..2 { + for mode in [Io::One, Io::Handles, Io::Overlapped, Io::Direct] { + let file = Files::open_for_test(&path, mode); + let at: Vec = (0..READS).map(|_| random() % (len - SIZE as u64) & !15).collect(); + for pass in ["cold", "again"] { + let next = std::sync::atomic::AtomicUsize::new(0); + let busy = AtomicU64::new(0); + let start = Instant::now(); + std::thread::scope(|s| { + for _ in 0..THREADS { + s.spawn(|| { + let mut out = vec![0u8; SIZE]; + while let Some(&at) = at.get(next.fetch_add(1, Ordering::Relaxed)) { + let began = Instant::now(); + let mut done = 0; + while done < SIZE { + done += file.read_at(&mut out[done..], at + done as u64).unwrap(); + } + busy.fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); + } + }); + } + }); + let took = start.elapsed().as_secs_f64(); + println!( + "{round} {mode:?} {pass}: {:.0} MB/s, {:.2} ms a read", + (READS * SIZE) as f64 / took / 1e6, + busy.load(Ordering::Relaxed) as f64 / READS as f64 / 1e3 + ); + } + } + } + } + + /// Every way of reading a file gives its bytes, also past its end. + #[test] + fn every_way_of_reading_gives_the_same_bytes() { + let plain = pattern(300_001); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("data.bin"); + std::fs::write(&path, &plain).unwrap(); + for mode in [Io::One, Io::Handles, Io::Overlapped, Io::Direct] { + let file = Files::open_for_test(path.to_str().unwrap(), mode); + for (at, len) in [(0, 4096), (1, 100), (4095, 2), (8192, 200_000), (12_345, 250_000), (299_990, 11), (300_000, 1)] { + let mut out = vec![0u8; len]; + let mut done = 0; + while done < len { + let n = file.read_at(&mut out[done..], (at + done) as u64).unwrap(); + assert_ne!(n, 0, "{mode:?} {at} {len}"); + done += n; + } + assert!(out == plain[at..at + len], "{mode:?} {at} {len}"); + } + let mut out = [0u8; 16]; + assert_eq!(file.read_at(&mut out, 299_999).unwrap(), 2, "{mode:?}"); + assert_eq!(file.read_at(&mut out, 300_001).unwrap(), 0, "{mode:?}"); + assert_eq!(file.read_at(&mut out, 400_000).unwrap(), 0, "{mode:?}"); + } + } + /// Lanes without workers: what `start` picks, and when statuses land. fn lanes(staging: u64) -> Lanes { Lanes { diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 5aa88d1..fa55626 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -11,7 +11,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::{Arc, LazyLock, Mutex, MutexGuard}; +use std::sync::{Arc, LazyLock, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; use windows_sys::Win32::Foundation::{ CloseHandle, ERROR_COMMITMENT_LIMIT, HANDLE, INVALID_HANDLE_VALUE, @@ -435,65 +435,74 @@ struct Slice { #[derive(Default)] struct Physical { - next_page: usize, - pages: HashMap, /// Mapped views by address: their length and what they show. views: BTreeMap, - /// The other way: the views (by address) that show a page, by the page's - /// section and index. Views of more than [`SHORT`] pages are in `long`. - shown: HashMap<(usize, usize), Vec>, - long: Vec, } -/// Pages of a view noted page by page in [`Physical::shown`]. +/// The title's pages by number. +struct Pages { + next_page: usize, + pages: HashMap, +} + +/// Where the title sees its pages: [`Physical::views`] the other way. +/// Locked apart from them, and only for a moment ([`PAGES`]). +#[derive(Default)] +struct Shown { + /// The addresses that show a page, by the page's section and index. + /// Views of more than [`SHORT`] pages are in `long`. + pages: HashMap<(usize, usize), Vec>, + /// Address, bytes, section, first page. + long: Vec<(usize, usize, usize, usize)>, +} + +/// Pages of a view noted page by page in [`Shown::pages`]. const SHORT: usize = 64; -impl Physical { - fn note_view(&mut self, base: usize, len: usize, slice: &Slice) { +/// Taken after [`PHYSICAL`] where both are. +static SHOWN: LazyLock> = LazyLock::new(Default::default); + +fn shown_mut() -> RwLockWriteGuard<'static, Shown> { + SHOWN.write().unwrap_or_else(|e| e.into_inner()) +} + +impl Shown { + fn note(&mut self, base: usize, len: usize, slice: &Slice) { + let section = Arc::as_ptr(&slice.section) as usize; if len / PAGE > SHORT { - self.long.push(base); + self.long.push((base, len, section, slice.index)); return; } - let section = Arc::as_ptr(&slice.section) as usize; for k in 0..len / PAGE { - self.shown.entry((section, slice.index + k)).or_default().push(base); + self.pages.entry((section, slice.index + k)).or_default().push(base + k * PAGE); } } - fn forget_view(&mut self, base: usize, len: usize, slice: &Slice) { + fn forget(&mut self, base: usize, len: usize, slice: &Slice) { if len / PAGE > SHORT { - self.long.retain(|&b| b != base); + self.long.retain(|view| view.0 != base); return; } let section = Arc::as_ptr(&slice.section) as usize; for k in 0..len / PAGE { let key = (section, slice.index + k); - if let Some(views) = self.shown.get_mut(&key) { - views.retain(|&b| b != base); - if views.is_empty() { - self.shown.remove(&key); + if let Some(at) = self.pages.get_mut(&key) { + at.retain(|&at| at != base + k * PAGE); + if at.is_empty() { + self.pages.remove(&key); } } } } - /// Where the title sees `n` pages from `slice` on: addresses and bytes. - fn shown_at(&self, slice: &Slice, n: usize) -> Vec<(usize, usize)> { + /// Where the title sees the page at `slice`: addresses and bytes. + fn at(&self, slice: &Slice) -> Vec<(usize, usize)> { let section = Arc::as_ptr(&slice.section) as usize; - let mut out: Vec<(usize, usize)> = Vec::new(); - for k in 0..n { - for &base in self.shown.get(&(section, slice.index + k)).into_iter().flatten() { - if let Some((_, s)) = self.views.get(&base) { - out.push((base + (slice.index + k - s.index) * PAGE, PAGE)); - } - } - } - for &base in &self.long { - let Some((len, s)) = self.views.get(&base) else { continue }; - let from = slice.index.max(s.index); - let to = (slice.index + n).min(s.index + len / PAGE); - if Arc::as_ptr(&s.section) as usize == section && from < to { - out.push((base + (from - s.index) * PAGE, (to - from) * PAGE)); + let mut out: Vec<(usize, usize)> = + self.pages.get(&(section, slice.index)).into_iter().flatten().map(|&at| (at, PAGE)).collect(); + for &(base, len, of, index) in &self.long { + if of == section && (index..index + len / PAGE).contains(&slice.index) { + out.push((base + (slice.index - index) * PAGE, PAGE)); } } out @@ -510,13 +519,13 @@ pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) { return; } let mut seen: Vec<(usize, usize)> = { - let physical = physical(); let numbers = pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or_default(); - numbers - .iter() - .filter_map(|n| physical.pages.get(n)) - .flat_map(|slice| physical.shown_at(slice, 1)) - .collect() + let slices: Vec = { + let table = page_table(); + numbers.iter().filter_map(|n| table.pages.get(n)).cloned().collect() + }; + let shown = SHOWN.read().unwrap_or_else(|e| e.into_inner()); + slices.iter().flat_map(|slice| shown.at(slice)).collect() }; seen.sort_unstable(); let mut runs: Vec<(usize, usize)> = Vec::new(); @@ -538,18 +547,35 @@ pub(crate) fn stream_notice() -> bool { *ON } -static PHYSICAL: LazyLock> = LazyLock::new(|| { - Mutex::new(Physical { - // Page numbers are opaque to titles; 0 stays unused. - next_page: 0x10_0000, - ..Default::default() - }) -}); +/// The views, changed by the title's mapping calls; held for as long as +/// those take (the host maps, commits and unmaps under it). +static PHYSICAL: LazyLock> = LazyLock::new(Default::default); fn physical() -> MutexGuard<'static, Physical> { PHYSICAL.lock().unwrap_or_else(|e| e.into_inner()) } +/// The title's pages. Apart from the views: DirectStorage looks pages up at +/// every request, from 24 workers, and used to wait there for the title's +/// mapping calls (12,000 waits of 1 to 170 ms in a load of 90 s). Written +/// only where the title allocates or frees pages. Taken after [`PHYSICAL`] +/// where both are. +static PAGES: LazyLock> = LazyLock::new(|| { + RwLock::new(Pages { + // Page numbers are opaque to titles; 0 stays unused. + next_page: 0x10_0000, + pages: HashMap::new(), + }) +}); + +fn page_table() -> RwLockReadGuard<'static, Pages> { + PAGES.read().unwrap_or_else(|e| e.into_inner()) +} + +fn page_table_mut() -> RwLockWriteGuard<'static, Pages> { + PAGES.write().unwrap_or_else(|e| e.into_inner()) +} + /// `count` is in and out (pages wanted, pages given); all or nothing here. pub extern "system" fn XMemAllocatePhysicalPages( flags: u64, @@ -603,18 +629,22 @@ pub extern "system" fn XMemAllocatePhysicalPages( window: std::sync::OnceLock::new(), committed: (0..n.div_ceil(64)).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(), }); - let mut physical = physical(); - let first = physical.next_page; - physical.next_page += n * FRAMES; + let mut table = page_table_mut(); + let first = table.next_page; + table.next_page += n * FRAMES; for index in 0..n { let slice = Slice { section: section.clone(), index, }; - let number = first + index * FRAMES; - physical.pages.insert(number, slice); + table.pages.insert(first + index * FRAMES, slice); + } + // Title memory is touched without our locks: a fault there may wait for + // a mapping call, which takes them. + drop(table); + for index in 0..n { // SAFETY: the title passes room for `n` page numbers. - unsafe { pages.add(index).write(number) }; + unsafe { pages.add(index).write(first + index * FRAMES) }; } 1 } @@ -629,11 +659,13 @@ pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> B if pages.is_null() { return 0; } - let mut physical = physical(); - for i in 0..n { - // SAFETY: the title passes `n` page numbers. - physical.pages.remove(&unsafe { *pages.add(i) }); - } + // SAFETY: the title passes `n` page numbers. + let numbers = unsafe { std::slice::from_raw_parts(pages, n) }.to_vec(); + let mut table = page_table_mut(); + // Dropped without the lock: the last page of a section unmaps its window. + let gone: Vec = numbers.iter().filter_map(|number| table.pages.remove(number)).collect(); + drop(table); + drop(gone); 1 } @@ -689,16 +721,15 @@ impl Drop for View { /// The pages behind bytes `[offset, offset + len)` of `pages` (64 KiB /// each), as runs of consecutive slices of one section: each run's first -/// slice and its length in pages. One look at the page table, which the -/// title's own mapping calls share with every DirectStorage worker. `None` +/// slice and its length in pages. One look at the page table. `None` /// if a page is unknown or `pages` ends early. fn runs(pages: &[usize], offset: usize, len: usize) -> Option> { let end = offset.checked_add(len)?; let pages = pages.get(offset / PAGE..end.div_ceil(PAGE))?; - let physical = physical(); + let table = page_table(); let mut runs: Vec<(Slice, usize)> = Vec::new(); for page in pages { - let Some(slice) = physical.pages.get(page) else { + let Some(slice) = table.pages.get(page) else { tracing::warn!(page, offset, len, "a physical page the title does not own (any more)"); return None; }; @@ -717,25 +748,25 @@ fn runs(pages: &[usize], offset: usize, len: usize) -> Option bool { - let physical = physical(); + let table = page_table(); pages .get(offset / PAGE..(offset + len).div_ceil(PAGE)) - .is_some_and(|pages| pages.iter().all(|page| physical.pages.contains_key(page))) + .is_some_and(|pages| pages.iter().all(|page| table.pages.contains_key(page))) } /// Where the title sees the pages under bytes `[offset, offset + len)` now, /// in order (for the streaming trace: whether that changed while a request /// wrote them). pub(crate) fn pages_shown(pages: &[usize], offset: usize, len: usize) -> Vec<(usize, usize)> { - let physical = physical(); let numbers = pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or_default(); - let mut shown: Vec<(usize, usize)> = numbers - .iter() - .filter_map(|n| physical.pages.get(n)) - .flat_map(|slice| physical.shown_at(slice, 1)) - .collect(); - shown.sort_unstable(); - shown + let slices: Vec = { + let table = page_table(); + numbers.iter().filter_map(|n| table.pages.get(n)).cloned().collect() + }; + let shown = SHOWN.read().unwrap_or_else(|e| e.into_inner()); + let mut at: Vec<(usize, usize)> = slices.iter().flat_map(|slice| shown.at(slice)).collect(); + at.sort_unstable(); + at } /// Copies `data` into physical pages, from `offset` bytes into the first, @@ -822,6 +853,10 @@ pub extern "system" fn XMemMapPhysicalPages( pages: *const usize, ) -> *mut c_void { let base = address as usize; + // Read before any lock is taken: a fault in title memory may wait for + // the mapping call that holds them. + // SAFETY: the title passes `n` page numbers, or null. + let pages = (!pages.is_null()).then(|| unsafe { std::slice::from_raw_parts(pages, n) }.to_vec()); let mut physical = physical(); // Until the pages are mapped again: `unmap` takes whole views away and // maps what stays of them again, and a mapped view is a reservation @@ -829,23 +864,25 @@ pub extern "system" fn XMemMapPhysicalPages( // into that gap (`victory_gpu::title_memory_remapping`). let _changing = victory_gpu::title_memory_remapping(); unmap(&mut physical, base, n * PAGE); - if pages.is_null() { + let Some(pages) = pages else { return address; - } - // SAFETY: the title passes `n` page numbers. - let pages = unsafe { std::slice::from_raw_parts(pages, n) }; + }; + let slices: Vec> = { + let table = page_table(); + pages.iter().map(|page| table.pages.get(page).cloned()).collect() + }; let mut i = 0; while i < n { - let Some(first) = physical.pages.get(&pages[i]).cloned() else { + let Some(first) = slices[i].clone() else { tracing::warn!(page = pages[i], "XMemMapPhysicalPages: unknown page"); return std::ptr::null_mut(); }; // One view per run of consecutive slices of one section. - let run = 1 + pages[i + 1..] + let run = 1 + slices[i + 1..] .iter() .zip(1..) - .take_while(|&(page, k)| { - physical.pages.get(page).is_some_and(|s| { + .take_while(|&(slice, k)| { + slice.as_ref().is_some_and(|s| { Arc::ptr_eq(&s.section, &first.section) && s.index == first.index + k }) }) @@ -960,11 +997,14 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }; return false; } + // Noted before the GPU side is told: bytes DirectStorage put in earlier, + // without notice at these addresses ([`pages_written`]), are there by + // the time the copies of them go. + shown_mut().note(base, len, &slice); // New contents, read-write: the GPU side's copies no longer guard it. victory_gpu::title_memory_remapped(base, len); // What the range shows now, for the GPU side's in-place census. victory_gpu::title_memory_view(base, len, slice.section.handle as usize, (slice.index * PAGE) as u64); - physical.note_view(base, len, &slice); physical.views.insert(base, (len, slice)); true } @@ -1043,7 +1083,7 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { let Some((size, slice)) = physical.views.remove(&at) else { continue; }; - physical.forget_view(at, size, &slice); + shown_mut().forget(at, size, &slice); victory_gpu::title_memory_unmapping(at, size); // SAFETY: a view we mapped; it becomes a placeholder again. unsafe { @@ -1461,6 +1501,66 @@ mod tests { assert_eq!(XMemFreePhysicalPages(2, pages.as_ptr()), 1); } + /// What a title that maps and unmaps pages all the time costs the + /// workers that write others: 24 threads look pages up, fill one and + /// tell of it, as a request does, while one maps. + /// `cargo test --release -p victory-hle --lib map_bench -- --ignored --nocapture` + #[test] + #[ignore = "a benchmark"] + fn map_bench() { + use std::sync::atomic::AtomicU64; + use std::time::{Duration, Instant}; + let pages = allocate(1024); + let a = XMemVirtualAlloc(std::ptr::null_mut(), 1024 * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE) as usize; + for mapping in [false, true] { + let (done, waited, worst, maps) = + (AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)); + let until = Instant::now() + Duration::from_secs(3); + std::thread::scope(|s| { + if mapping { + s.spawn(|| { + let at: Vec<*mut c_void> = (0..256).map(|i| (a + i * PAGE) as *mut c_void).collect(); + while Instant::now() < until { + assert_eq!(XMemMapPhysicalPagesScatter(at.as_ptr(), 256, pages.as_ptr()), 1); + assert_eq!(XMemMapPhysicalPagesScatter(at.as_ptr(), 256, std::ptr::null()), 1); + maps.fetch_add(512, Ordering::Relaxed); + } + }); + } + for t in 0..24 { + let (pages, done, waited, worst) = (&pages, &done, &waited, &worst); + s.spawn(move || { + let mut i = 256 + t * 16; + while Instant::now() < until { + let page = &pages[i..=i]; + i = if i == 256 + t * 16 + 15 { 256 + t * 16 } else { i + 1 }; + let began = Instant::now(); + assert!(pages_known(page, 0, PAGE)); + let mut window = page_window(page, 0, PAGE).unwrap(); + let looked = began.elapsed(); + window.bytes().fill(t as u8); + let began = Instant::now(); + pages_written(page, 0, PAGE); + let took = (looked + began.elapsed()).as_nanos() as u64; + waited.fetch_add(took, Ordering::Relaxed); + worst.fetch_max(took, Ordering::Relaxed); + done.fetch_add(1, Ordering::Relaxed); + } + }); + } + }); + let n = done.load(Ordering::Relaxed).max(1); + println!( + "mapping {mapping}: {:.0} requests/s, {:.1} us of each on lookups and notices (worst {:.1} ms); {:.0} maps/s", + n as f64 / 3.0, + waited.load(Ordering::Relaxed) as f64 / n as f64 / 1e3, + worst.load(Ordering::Relaxed) as f64 / 1e6, + maps.load(Ordering::Relaxed) as f64 / 3.0 + ); + } + assert_eq!(XMemFreePhysicalPages(1024, pages.as_ptr()), 1); + } + /// `n` pages of one new allocation. fn allocate(n: usize) -> Vec { let (mut pages, mut given) = (vec![0; n], n); @@ -1474,7 +1574,7 @@ mod tests { /// The bytes of one page, through a view of our own. fn page_bytes(page: usize) -> Vec { - let slice = physical().pages.get(&page).cloned().expect("known page"); + let slice = page_table().pages.get(&page).cloned().expect("known page"); View::map(&slice, 1).expect("mapped").bytes().to_vec() } From 8dd30ab472697c47b141c273c2a00f8ce1c00520 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:44:25 -0500 Subject: [PATCH 186/445] A write through one view of a page is seen at its other views; page writes counted; levels on demand (off); warm-up; card memory numbers Memory sync: - The guard over every view of a physical page (code by myokex, victory-amd c6dc4d8, after pull request #115 by Spexivus, its correction by joroyt and a part of VIctory #1122 by tightfall): the title shows one page at several addresses and a copy was guarded at one only. 0.8 to 1.0 million writes through another view in a five-minute run on the test machine. VICTORY_VIEW_GUARD=0 turns it off. - Kernel reads into title memory are read beside and copied in (Joshua Odom, 10ea38e). - Writes of the storage layer into physical pages are counted where the title has the pages mapped and can open the guards there (VICTORY_PAGE_WRITES, off: counted only). Failed page-destination reads are retried. Card memory: - Levels on demand, off unless VICTORY_LEVELS_ON_DEMAND=1: a texture the title fills takes card memory for the levels the title holds; held levels get memory only while the card has room and are asked for again. Its test runs on the software adapter; not run on a card yet. - Refused texture slots are held back so a pass reaches the slots behind them; room can be kept for card copies of title buffers (off). Tools: translate --warm all; the shader cache is keyed on the translator's source; counters for copy-back races, page writes and the copies the texture sweep never lets go; a walls trace. Game runs of these changes on an RTX 4070: five five-minute runs without a device loss or a failed request. This merged tree was built; its test suites were run on the tree the changes come from (gpu 129, hle 97). Co-Authored-By: Claude Fable 5.2 --- README.md | 48 + apps/victory/src/main.rs | 11 + apps/victory/src/translate.rs | 81 ++ crates/victory-formats/src/texture.rs | 147 +- crates/victory-gpu/src/copystat.rs | 22 + crates/victory-gpu/src/descriptor.rs | 44 +- crates/victory-gpu/src/descriptor/host.rs | 514 ++++++- crates/victory-gpu/src/draw.rs | 51 +- crates/victory-gpu/src/host.rs | 26 +- crates/victory-gpu/src/inplace.rs | 100 +- crates/victory-gpu/src/lib.rs | 5 +- crates/victory-gpu/src/list.rs | 10 + crates/victory-gpu/src/resource.rs | 314 +++- crates/victory-gpu/src/shader_cache.rs | 108 +- crates/victory-gpu/src/shadow.rs | 536 ++++++- crates/victory-gpu/src/texture.rs | 266 +++- crates/victory-gpu/src/tiles.rs | 1419 +++++++++++++++++++ crates/victory-gpu/src/watch.rs | 364 ++++- crates/victory-hle/src/modules/d3d12x.rs | 13 + crates/victory-hle/src/modules/dstorage.rs | 85 +- crates/victory-hle/src/modules/files.rs | 75 +- crates/victory-hle/src/modules/gameinput.rs | 2 +- crates/victory-hle/src/modules/xmem.rs | 125 ++ crates/victory-shader/build.rs | 65 + crates/victory-shader/src/emit/mod.rs | 27 + 25 files changed, 4218 insertions(+), 240 deletions(-) create mode 100644 crates/victory-gpu/src/tiles.rs create mode 100644 crates/victory-shader/build.rs diff --git a/README.md b/README.md index 7dc43e2..8c99e40 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,12 @@ developer or publisher. - **[XCL](https://github.com/ivall/xcl)** by ivall and its contributors (GPL-2.0-only) was used as a reference for how the same title behaves under another layer. Fixes inspired by it were written anew in VIctory's code. +- The guard over every view of a memory page is code by **myokex** + ([victory-amd](https://github.com/myokex/victory-amd), commit `c6dc4d8`), which + adapts pull request #115 here by Spexivus, its correction by joroyt and a part of + VIctory #1122 by tightfall. The read-beside fix for kernel reads into title + memory is by **Joshua Odom** (commit `10ea38e` of the same fork family). Both + are carried here unchanged apart from one merge conflict. - This fork's changes were developed with [Claude Code](https://claude.com/claude-code). ## Status of this fork (2026-11-25) @@ -38,6 +44,48 @@ Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, | Frame rate in the world | 2-4 fps: 420-450 ms per frame by default, 240-350 ms with the newer switches (`VICTORY_RELAY=2`, or `VICTORY_LATE_WAIT=3 VICTORY_WIDE_BACK=1 VICTORY_CARD_BUFFERS_MIN_MB=1 VICTORY_CARD_BUFFERS_MB=1024`); it started at 3-6 seconds per frame | | Stability | no driver hang or device loss in normal runs (a hang introduced by the wave64 update was found and fixed: its barrier form for 64-lane programs is now off unless `VICTORY_WAVE_WIDE=1`) | +### Newest (2026-11-25, later the same day) + +Memory sync between the title's memory and the copies on the card: +- **A write through one view of a physical page is seen by the copies taken + through its other views** (`VICTORY_VIEW_GUARD=0` turns it off). The title + shows one page at several addresses and a copy was guarded at one of them + only. Measured on the test machine: 0.8 to 1.0 million such writes in a + five-minute run, every one of which used to leave a copy stale. Since it + went in, the first room had its walls in the later frames of 4 runs out of + 4 (2 of 5 before); the room's very first shot still comes up without walls + in some runs. +- Kernel reads into title memory are read beside and copied in, so a block + guarded again in between no longer fails the read. +- Writes of the storage layer into physical pages are counted where the title + has those pages mapped (10,000 to 50,000 guarded blocks of copies lay under + them in every run) and can open the guards there: + `VICTORY_PAGE_WRITES=guards` (off by default; `1`, `slots`, `all` do more). +- Failed page-destination reads are retried (`VICTORY_DSTORAGE_RETRIES=0` = as before). + +Card memory (the test card is full from the first frame of the world: 85 to +99 % of its budget for a whole run, about 26,000 texture copies let go and +3,400 made again in five minutes, 2.8 GB of render targets that are all in +use): +- Levels on demand, **off by default** (`VICTORY_LEVELS_ON_DEMAND=1`): a + texture the title fills takes card memory only for the levels the title + holds (2.2 to 3.0 GB of the copies were levels it does not hold). Its test + runs on the software adapter; it has not run on a card yet. +- Refused texture slots are held back for a few seconds so that a pass + reaches the slots behind them (`VICTORY_FULL_CARD_PASS=0` = as before); + room can be kept for the card copies of title buffers + (`VICTORY_CARD_ROOM_FOR_BUFFERS=1`, off). + +Tools and diagnostics: +- `victory translate --warm all --jobs N` translates every + shader ahead of a run, on the processor only (about 4.5 to 6.5 minutes + here); the shader cache is keyed on the translator's source, so a new + build that does not touch the translator starts warm. +- Counters, all off or diagnostics-only: `VICTORY_MERGE_RACE=1` (title bytes + a copy-back is about to put back to older values: none found in 138,000 + copy-backs), `VICTORY_WALLS_TRACE`, `VICTORY_CARD_ACCOUNTING`, and a census + of the copies the texture sweep never lets go. + ### What this fork changed (summary) Rendering: diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index 842ce77..ead9f7c 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -84,6 +84,13 @@ enum Command { /// Worker threads (default: every logical core). #[arg(long)] jobs: Option, + /// Warm the run's shader cache: a file of shader hashes (the 16 + /// hex digits a run's log names a shader by, anywhere in a line); + /// the containers with those hashes are translated into the + /// cache and nothing else is done. Set `VICTORY_HOST_WAVE` and + /// `VICTORY_VIEW_LIMIT` to what the run's log says of the host. + #[arg(long)] + warm: Option, }, /// Prepare, map and bind a title executable; with --execute, run it. Run { @@ -152,6 +159,7 @@ fn main() -> Result<()> { pipelines, list, jobs, + warm, } => { // `VICTORY_VIEW_LIMIT=`: translate as on a host whose view heap is capped if let Some(n) = std::env::var("VICTORY_VIEW_LIMIT").ok().and_then(|v| v.parse().ok()) { @@ -161,6 +169,9 @@ fn main() -> Result<()> { if let Some(n) = std::env::var("VICTORY_HOST_WAVE").ok().and_then(|v| v.parse().ok()) { victory_shader::emit::set_host_max_wave(n); } + if let Some(file) = warm { + return translate::warm(paths, &file, jobs); + } translate::run(paths, validate, pipelines, list, jobs) } Command::Run { diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 1d13ae2..640d210 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -152,6 +152,87 @@ struct Checks { host: Option<(Host, emit::HostShader)>, } +/// `translate --warm `: the containers whose hash the file names are +/// translated into the run's shader cache, on `jobs` threads; nothing is +/// made on the GPU. A run of the title then finds them there instead of +/// translating each at its first use. +pub fn warm(paths: Vec, file: &Path, jobs: Option) -> Result<()> { + // `--warm all`: every container found, whatever its hash. + let all = file.as_os_str() == "all"; + let mut wanted: HashSet = HashSet::new(); + if !all { + let text = std::fs::read_to_string(file)?; + for line in text.lines() { + for word in line.split(|c: char| !c.is_ascii_hexdigit()) { + if word.len() == 16 { + wanted.insert(word.to_ascii_lowercase()); + } + } + } + anyhow::ensure!(!wanted.is_empty(), "no 16-digit shader hash in {}", file.display()); + } + // `VICTORY_WARM_SECONDS=`: stop taking new shaders after n seconds + // (what is done stays in the cache; the next warm-up goes on from there). + let limit = std::env::var("VICTORY_WARM_SECONDS").ok().and_then(|v| v.trim().parse::().ok()); + let cfg = victory_core::Config::load()?; + victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + let paths = crate::default_paths(paths)?; + let threads = jobs.unwrap_or(4).max(1); + let began = std::time::Instant::now(); + let done = Mutex::new(HashSet::new()); + let counts = [const { AtomicUsize::new(0) }; 5]; + for root in &paths { + for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) { + if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { + continue; + } + let Ok(data) = std::fs::read(entry.path()) else { + continue; + }; + let jobs = sources(&data); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads.min(jobs.len()) { + s.spawn(|| { + while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + let Some(bytes) = job.bytes() else { + continue; + }; + let hash = blake3::hash(&bytes).to_hex()[..16].to_owned(); + if limit.is_some_and(|n| began.elapsed().as_secs() >= n) { + counts[3].fetch_add(1, Ordering::Relaxed); + break; + } + if (!all && !wanted.contains(&hash)) || !lock(&done).insert(hash) { + continue; + } + let n = counts[4].fetch_add(1, Ordering::Relaxed) + 1; + if n.is_multiple_of(1000) { + println!("warm-up {n} shaders so far, {:.0} s", began.elapsed().as_secs_f64()); + } + let which = match victory_hle::modules::d3d12x::warm_shader(&bytes) { + Ok(true) => 0, + Ok(false) => 1, + Err(_) => 2, + }; + counts[which].fetch_add(1, Ordering::Relaxed); + } + }); + } + }); + } + } + let [translated, there, failed] = [0, 1, 2].map(|i| counts[i].load(Ordering::Relaxed)); + let asked = if all { "all".to_owned() } else { wanted.len().to_string() }; + let stopped = if counts[3].load(Ordering::Relaxed) > 0 { " (stopped at the time limit)" } else { "" }; + println!( + "warm-up {asked} hashes asked, {} found: {translated} translated now, {there} in the cache already, {failed} do not translate; {:.1} s on {threads} threads{stopped}", + translated + there + failed, + began.elapsed().as_secs_f64() + ); + Ok(()) +} + pub fn run( paths: Vec, validate: bool, diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index a1f72e4..fa719c9 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -594,9 +594,7 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| { - linear[l..][..len].copy_from_slice(&tiled[t..][..len]); - }) + self.walk::(tiled, linear, mip, slice, row_pitch, depth_pitch) } /// The reverse of [`Layout::detile`]: linear rows into tiled memory. @@ -609,22 +607,19 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| { - tiled[t..][..len].copy_from_slice(&linear[l..][..len]); - }) + self.walk::(linear, tiled, mip, slice, row_pitch, depth_pitch) } - /// Visits contiguous runs as (tiled byte offset, linear byte offset, length). + /// Copies contiguous runs in one direction between the two layouts. #[allow(clippy::too_many_arguments)] - fn walk( + fn walk( &self, - tiled_len: usize, + src: &[u8], + dst: &mut [u8], mip: u32, slice: u32, - linear_len: usize, row_pitch: usize, depth_pitch: usize, - mut copy: impl FnMut(usize, usize, usize), ) -> Result<(), Error> { let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; let depth = m.depth; @@ -650,6 +645,11 @@ impl Layout { .and_then(|(depth_offset, row_offset)| depth_offset.checked_add(row_offset)) .and_then(|offset| offset.checked_add(bytes)) .ok_or(Error::TooSmall)?; + let (tiled_len, linear_len) = if DETILE { + (src.len(), dst.len()) + } else { + (dst.len(), src.len()) + }; if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes { return Err(Error::TooSmall); } @@ -672,12 +672,12 @@ impl Layout { runs.push((first_tiled, first_linear, bytes - first_linear)); } // A mip can end partway through the last run. Check the other runs - // once so each row can copy them with a compile-time length. + // once so each row can copy them as fixed-size chunks. let (body, last) = runs.split_at(runs.len().saturating_sub(1)); - let run_len = body - .first() - .map(|run| run.2) - .filter(|&len| body.iter().all(|run| run.2 == len)); + let chunk_size = body.first().map(|run| run.2).filter(|&size| { + body.iter() + .all(|&(offset, _, len)| len == size && offset.is_multiple_of(size)) + }); for z in 0..depth { let (s, inner) = self.split(first + z); let base = u64::from(s) * self.slice_size + m.offset; @@ -685,16 +685,22 @@ impl Layout { let linear_row = z as usize * depth_pitch + y as usize * row_pitch; if linear { let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64; - copy(tiled_row as usize, linear_row, bytes); + copy_run::(src, dst, tiled_row as usize, linear_row, bytes); } else { let tiled_row = (base + self.row(m, y, inner)) as usize; - match run_len { - Some(8) => copy_runs::<8>(body, tiled_row, linear_row, &mut copy), - Some(16) => copy_runs::<16>(body, tiled_row, linear_row, &mut copy), - Some(32) => copy_runs::<32>(body, tiled_row, linear_row, &mut copy), - _ => copy_runs::<0>(body, tiled_row, linear_row, &mut copy), + match chunk_size { + Some(8) if tiled_row.is_multiple_of(8) => { + copy_runs::<8, DETILE>(src, dst, body, tiled_row, linear_row) + } + Some(16) if tiled_row.is_multiple_of(16) => { + copy_runs::<16, DETILE>(src, dst, body, tiled_row, linear_row) + } + Some(32) if tiled_row.is_multiple_of(32) => { + copy_runs::<32, DETILE>(src, dst, body, tiled_row, linear_row) + } + _ => copy_runs::<0, DETILE>(src, dst, body, tiled_row, linear_row), } - copy_runs::<0>(last, tiled_row, linear_row, &mut copy); + copy_runs::<0, DETILE>(src, dst, last, tiled_row, linear_row); } } } @@ -702,16 +708,47 @@ impl Layout { } } -/// Copy micro-tile runs inline at a known width, or use each run's length for N = 0. -fn copy_runs( +fn copy_run( + src: &[u8], + dst: &mut [u8], + tiled: usize, + linear: usize, + len: usize, +) { + let (from, to) = if DETILE { + (tiled, linear) + } else { + (linear, tiled) + }; + dst[to..][..len].copy_from_slice(&src[from..][..len]); +} + +/// A row of equal runs is contiguous in linear memory. Treat it as a +/// slice of arrays so only the tiled chunk needs a bounds check per copy. +/// Use the byte ranges for irregular runs and the last run of each row. +fn copy_runs( + src: &[u8], + dst: &mut [u8], runs: &[(usize, usize, usize)], tiled_row: usize, linear_row: usize, - copy: &mut impl FnMut(usize, usize, usize), ) { - for &(tiled, linear, len) in runs { - let len = if N == 0 { len } else { N }; - copy(tiled_row + tiled, linear_row + linear, len); + if N == 0 { + for &(tiled, linear, len) in runs { + copy_run::(src, dst, tiled_row + tiled, linear_row + linear, len); + } + } else if DETILE { + let tiled = src.as_chunks::().0; + let linear = dst[linear_row..][..runs.len() * N].as_chunks_mut::().0; + for (out, &(offset, ..)) in linear.iter_mut().zip(runs) { + *out = tiled[(tiled_row + offset) / N]; + } + } else { + let tiled = dst.as_chunks_mut::().0; + let linear = src[linear_row..][..runs.len() * N].as_chunks::().0; + for (input, &(offset, ..)) in linear.iter().zip(runs) { + tiled[(tiled_row + offset) / N] = *input; + } } } @@ -968,6 +1005,58 @@ mod tests { } } + #[test] + fn tiled_chunks_match_element_offsets_with_odd_row_pitches() { + for swizzle in [ + Swizzle::SW_256B_S, + Swizzle::SW_256B_D, + Swizzle::SW_4KB_S, + Swizzle::SW_4KB_D, + Swizzle::SW_64KB_S, + Swizzle::SW_64KB_D, + ] { + for n in [1, 2, 4, 8, 16] { + let l = Layout::new(&Desc { + depth: 2, + ..desc(73, 39, 7, n, swizzle) + }) + .unwrap(); + let n = n as usize; + let tiled: Vec<_> = (0..l.size) + .map(|i| (i.wrapping_mul(0x9e37_79b9) >> 24) as u8) + .collect(); + let mut retiled = vec![0xbb; tiled.len()]; + let mut expected_tiled = retiled.clone(); + for slice in 0..l.slices { + for (mip, m) in l.mips.iter().enumerate() { + let mip = mip as u32; + let bytes = m.width as usize * n; + let pitch = bytes + 3; + // Keep padding between rows, with exactly the active + // bytes in the last row. + let len = (m.height as usize - 1) * pitch + bytes; + let mut linear = vec![0xcc; len]; + let mut expected = linear.clone(); + for y in 0..m.height { + for x in 0..m.width { + let src = l.offset(mip, x, y, slice).unwrap() as usize; + let dst = y as usize * pitch + x as usize * n; + expected[dst..][..n].copy_from_slice(&tiled[src..][..n]); + expected_tiled[src..][..n].copy_from_slice(&tiled[src..][..n]); + } + } + l.detile(&tiled, mip, slice, &mut linear, pitch, len) + .unwrap(); + assert_eq!(linear, expected, "{swizzle:?} {n} mip {mip} slice {slice}"); + l.tile(&mut retiled, mip, slice, &expected, pitch, len) + .unwrap(); + } + } + assert_eq!(retiled, expected_tiled, "{swizzle:?} {n}"); + } + } + } + /// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to /// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12, /// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first. diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 204b6c4..ba56d63 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -743,6 +743,22 @@ fn log_memory() { mb(card[0]), mb(card[3]), ); + let targets = crate::resource::targets_census(); + tracing::info!( + "host copies the sweep never lets go: {} the host renders to or writes {:.0} MB ({} of them placed {:.0} MB); of them {} have title memory that is not mapped now {:.0} MB, {} were not used for 30 s and are held by no list and no slot {:.0} MB, {} are both {:.0} MB; and {} copies of textures the title fills that the host copied into {:.0} MB", + targets[0], + mb(targets[1]), + targets[10], + mb(targets[11]), + targets[2], + mb(targets[3]), + targets[4], + mb(targets[5]), + targets[6], + mb(targets[7]), + targets[8], + mb(targets[9]), + ); tracing::info!( "memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \ {:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \ @@ -1121,6 +1137,12 @@ pub(crate) fn log(frames: f64) { c[C::GpuWritesLeftOut as usize], mb(c[C::GpuWritesLeftOutBytes as usize]), ); + let [together, written, mapped] = + [0, 1, 2].map(|n| crate::watch::ALIASES[n].load(std::sync::atomic::Ordering::Relaxed)); + tracing::info!( + "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" + ); // 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/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 8485014..9305bf5 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -353,7 +353,11 @@ struct Views { shape_index: std::collections::BTreeMap, } -static VIEWS: std::sync::Mutex = std::sync::Mutex::new(Views { +/// Read far more often than written: every slot a draw reads through a +/// table is looked up here, on several recording threads at once in the +/// world. Readers share it; only a view not seen before (a new table entry +/// or shape) and a released resource take it alone. +static VIEWS: std::sync::RwLock = std::sync::RwLock::new(Views { list: Vec::new(), index: std::collections::BTreeMap::new(), by_resource: std::collections::BTreeMap::new(), @@ -480,6 +484,12 @@ impl Views { Some(View::Placed(unordered, resource, desc)) } + /// The record words of `view` as a table entry, if it has one. + fn entry_of(&self, view: &View) -> Option<[u32; 2]> { + let &i = self.index.get(view)?; + Some([i, self.list[i as usize].1]) + } + /// The record words of `view` as a table entry: its entry (a new or a /// freed one if the view is not there yet) and that entry's generation. fn entry(&mut self, view: View) -> [u32; 2] { @@ -522,8 +532,10 @@ fn words_for(view: View) -> [u32; 2] { View::Placed(unordered, resource, desc) => { let (shape, address) = shape_of(*unordered, resource, desc); if address >> PLACED_ADDRESS_BITS == 0 { - let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(shape) = views.shape(shape) { + // Nearly every placed view has a shape seen before. + let known = views_read().shape_index.get(&shape).copied(); + let shape = known.or_else(|| views_write().shape(shape)); + if let Some(shape) = shape { NAMED_WHOLE[1].fetch_add(1, Relaxed); return placed_words(shape, address); } @@ -532,7 +544,19 @@ fn words_for(view: View) -> [u32; 2] { _ => {} } } - VIEWS.lock().unwrap_or_else(|e| e.into_inner()).entry(view) + // A view written before keeps its entry and generation. + if let Some(words) = views_read().entry_of(&view) { + return words; + } + views_write().entry(view) +} + +fn views_read() -> std::sync::RwLockReadGuard<'static, Views> { + VIEWS.read().unwrap_or_else(|e| e.into_inner()) +} + +fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> { + VIEWS.write().unwrap_or_else(|e| e.into_inner()) } /// For the memory line: the distinct views kept ([`Views`]), those of them @@ -546,7 +570,7 @@ fn words_for(view: View) -> [u32; 2] { #[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn views_kept() -> [u64; 8] { use std::sync::atomic::Ordering::Relaxed; - let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let views = views_read(); let each = size_of::<(View, u32)>() as u64; let shape = size_of::() as u64; let (mut constants, mut placed) = (0, 0); @@ -697,7 +721,7 @@ pub(crate) fn forget(resource: usize) { .lock() .unwrap_or_else(|e| e.into_inner()) .remove(&resource); - let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let mut views = views_write(); let Some(entries) = views.by_resource.remove(&resource) else { return; }; @@ -722,12 +746,12 @@ pub(crate) fn forget(resource: usize) { fn view_at(i: u32, generation: u32) -> Option { match generation >> KIND_SHIFT { 0 => { - let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let views = views_read(); let (view, current) = views.list.get(i as usize)?; (*current == generation).then(|| view.clone()) } CONSTANT => Some(constant_of(i, generation)), - PLACED => VIEWS.lock().unwrap_or_else(|e| e.into_inner()).placed_of(i, generation), + PLACED => views_read().placed_of(i, generation), _ => None, } } @@ -1104,8 +1128,8 @@ mod tests { View::Placed(_, r, _) => *r == resource, _ => false, }; - let entries = || VIEWS.lock().unwrap().list.iter().filter(|(v, _)| mine(v)).count(); - let shapes = || VIEWS.lock().unwrap().shapes.iter().filter(|s| s.1 == resource).count(); + let entries = || VIEWS.read().unwrap().list.iter().filter(|(v, _)| mine(v)).count(); + let shapes = || VIEWS.read().unwrap().shapes.iter().filter(|s| s.1 == resource).count(); for n in 0..20_000u64 { let address = 0x6_0000_0000 + n * 0x100; create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at); diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 7b18b45..49e4ca1 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -85,7 +85,66 @@ pub(crate) struct HostHeap { /// by slot and by address ([`Spans`]): which slots a newer view of /// other memory there makes stale, and which to look at again when the /// runtime maps, unmaps or writes memory ([`remapped`]). - placed: Mutex, + placed: std::sync::Arc>, +} + +/// The spans of every view heap made ([`HostHeap::placed`]), for the +/// texture code, which has no heap at hand ([`next_start`], +/// [`first_viewed`]). +static PLACED_SPANS: Mutex>>> = Mutex::new(Vec::new()); + +/// Where the next texture placed inside `[start, end)` starts, past the +/// first bytes of the one at `start` ([`HEAD`]): what is there of the +/// texture at `start` ends there, whatever its full size. `None`: no view +/// in a slot shaders pick by index describes memory in that range. +pub(crate) fn next_start(start: u64, end: u64) -> Option { + let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner()); + heaps + .iter() + .filter_map(std::sync::Weak::upgrade) + .filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).next_start(start, end)) + .min() +} + +/// The lowest level that a view of the placed texture at `start` shows, +/// over the slots shaders pick by index that hold one now. The title +/// views a texture from the first level it holds. `None`: no such slot. +pub(crate) fn first_viewed(start: u64) -> Option { + let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner()); + heaps + .iter() + .filter_map(std::sync::Weak::upgrade) + .filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).first_viewed(start)) + .min() +} + +/// Levels on demand (`crate::tiles`): where the placed textures start +/// whose first level with memory changed since a texture pass last took +/// them ([`HostHeap::texture_views_remade`]). +static RESHOWN: Mutex> = Mutex::new(Vec::new()); + +/// The first level with memory of the placed texture at `start` changed: +/// its slots are made again at the next texture pass. +pub(crate) fn levels_changed(start: u64) { + RESHOWN.lock().unwrap_or_else(|e| e.into_inner()).push(start); +} + +/// Levels on demand (`crate::tiles`): where the placed textures start +/// whose last upload left a held level without tiles (the card had no +/// room, or no heap could be had), and when (`crate::host::moment`). A +/// texture pass makes their slots due again once the card has room +/// ([`HostHeap::texture_slots_waiting`]). +static WAITING: Mutex> = Mutex::new(std::collections::BTreeMap::new()); + +/// The last upload of the placed texture at `start` left a held level +/// without tiles. A texture picked by index is uploaded once and then +/// only when its memory is found changed, and its staging buffer goes +/// with the upload: without this the level stayed empty (the texture +/// blurred, or black if no level had tiles) for as long as the title left +/// its memory alone, where a texture refused for want of room is tried +/// again. +pub(crate) fn levels_waiting(start: u64) { + WAITING.lock().unwrap_or_else(|e| e.into_inner()).insert(start, crate::host::moment()); } /// Title memory by the placed texture views that describe it: per span of @@ -110,6 +169,8 @@ pub(crate) struct Spans { rule: Rule, by_start: std::collections::BTreeMap)>, by_slot: std::collections::HashMap, + /// The level each slot's view starts at ([`Spans::shows`]). + first: std::collections::HashMap, /// The bytes a placed texture takes, by resource description: worked /// out once for each (a title writes the views of a few thousand /// descriptions, thousands of times a frame). @@ -227,8 +288,30 @@ impl Spans { stale } + /// The view in slot `index` starts at level `first` of its texture. + fn shows(&mut self, index: u32, first: u32) { + self.first.insert(index, first); + } + + /// The lowest level a view of the texture at `start` starts at. + fn first_viewed(&self, start: u64) -> Option { + self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).min().copied() + } + + /// The first span that starts inside `[start, end)` past the first + /// [`HEAD`] bytes of it. + fn next_start(&self, start: u64, end: u64) -> Option { + self.by_start.range(start.saturating_add(HEAD)..end).next().map(|(at, _)| *at) + } + + /// The slots that hold a view of the texture at `start`. + fn slots_at(&self, start: u64) -> Vec { + self.by_start.get(&start).map(|span| span.1.iter().copied().collect()).unwrap_or_default() + } + /// Slot `index` holds no placed texture view any more. fn forget(&mut self, index: u32) { + self.first.remove(&index); let Some(start) = self.by_slot.remove(&index) else { return; }; @@ -248,6 +331,76 @@ impl Spans { .flat_map(|span| span.1.iter().copied()) .collect() } + + /// The slots of the textures that hold bytes of `[start, end)`, for a + /// write there: as [`Spans::slots_in`], but when a texture starts at + /// `start` itself the one before it is left out (it ends where that + /// one starts, and a request that fills a texture begins at its first + /// byte: `slots_in` would name its neighbour with every such write). + fn slots_holding(&self, start: u64, end: u64) -> Vec { + if end <= start { + return Vec::new(); + } + let before = if self.by_start.contains_key(&start) { + None + } else { + self.by_start.range(..start).next_back().filter(|(_, span)| span.0 > start).map(|(_, span)| span) + }; + before + .into_iter() + .chain(self.by_start.range(start..end).map(|(_, span)| span)) + .flat_map(|span| span.1.iter().copied()) + .collect() + } +} + +/// Title memory written behind the guards' back whose bytes are there +/// (DirectStorage's reads into physical pages, at the addresses the title +/// has them mapped; `crate::watch::title_memory_written`), since a texture +/// pass last took the ranges ([`page_written`]). Kept apart from +/// [`REMAPPED`] so that what such writes do is counted by itself. +static PAGE_WRITTEN: Mutex> = Mutex::new(Vec::new()); + +/// Since the start: such ranges kept for a pass; ranges dropped because no +/// pass took them; slots of placed textures that held bytes of them when a +/// pass took them; of those, the slots whose texture had been uploaded +/// before the write (out of the queue, or in it after an upload): they are +/// the ones that kept the bytes from before, and the ones made due when +/// `VICTORY_PAGE_WRITES` asks for it. +pub(crate) static PAGE_WRITES: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Frames from the pass that takes a written range to the look at its +/// slots: the levels of one texture arrive in a few requests, and a look +/// two frames on takes those of the next frame with it. +const PAGE_WRITE_AFTER: u64 = 2; + +/// The bytes of a write the guards do not see are in title memory `[at, +/// at + len)`: the placed textures there changed with no descriptor +/// written and nothing mapped. Kept for the next texture pass +/// ([`HostHeap::texture_slots_page_written`]), as [`remapped`] keeps its +/// ranges; locks one mutex and calls nothing. +pub(crate) fn page_written(at: usize, len: usize) { + use std::sync::atomic::Ordering::Relaxed; + /// Ranges kept until a pass takes them. + const MOST: usize = 1 << 15; + let (start, end) = (at as u64, at.saturating_add(len) as u64); + if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) { + return; + } + let mut ranges = PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + PAGE_WRITES[0].fetch_add(1, Relaxed); + if let Some(last) = ranges.last_mut() + && last.1 == start + { + last.1 = end; + return; + } + if ranges.len() >= MOST { + PAGE_WRITES[1].fetch_add(ranges.len() as u64, Relaxed); + ranges.clear(); + } + ranges.push((start, end)); } /// Title memory the runtime mapped, unmapped or is about to write since a @@ -373,6 +526,10 @@ struct Waiting { pub(crate) struct TextureQueue { slots: std::collections::BTreeMap, writes: u64, + /// Slots held back because the card had no room for the host copy + /// they need ([`TextureQueue::hold`]), each with the write it was + /// held as. + held: std::collections::BTreeMap, } impl TextureQueue { @@ -449,6 +606,37 @@ impl TextureQueue { } } + /// The card has no room for the host copy slot `index` needs: it is + /// not handed out again before frame `due`, or before the card has + /// room again ([`TextureQueue::room`]). Nothing else of it changes: it + /// is not a slot "waiting for its memory", and when it is due it has + /// its old place among the slots never looked at. (It stayed due, so + /// every pass on a full card looked at the same few hundred slots + /// again and stopped there, and the slots behind them were never + /// reached: the ones whose host copy exists and only wants bringing up + /// to date, and the ones whose memory went, which is what lets host + /// copies go and makes room.) + fn hold(&mut self, index: u32, write: u64, due: u64) { + if let Some(w) = self.same(index, write) { + w.due = w.due.max(due); + self.held.insert(index, write); + } + } + + /// The card has room again at `frame`: the slots held back for lack of + /// it are due now, as if they had never been held. Returns how many. + fn room(&mut self, frame: u64) -> usize { + let held = std::mem::take(&mut self.held); + let mut back = 0; + for (index, write) in held { + if let Some(w) = self.same(index, write) { + w.due = w.due.min(frame); + back += 1; + } + } + back + } + /// Slot `index` was uploaded with `mapped` bytes of its memory there, /// not all of it: looked at again from frame `due`. fn partly(&mut self, index: u32, write: u64, due: u64, mapped: u64) { @@ -770,7 +958,16 @@ impl HostHeap { tabled: (0..if sampler { 0 } else { count }) .map(|_| std::sync::atomic::AtomicU32::new(0)) .collect(), - placed: Mutex::default(), + placed: { + let spans = std::sync::Arc::>::default(); + if !sampler { + PLACED_SPANS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(std::sync::Arc::downgrade(&spans)); + } + spans + }, }; // A slot never written is undefined: shaders reading one (a slot // the title wrote in a way we do not know, or a table entry no @@ -981,6 +1178,16 @@ impl HostHeap { textures.later(index, write, frame, most); } + /// See [`TextureQueue::hold`]. + pub(crate) fn texture_slot_held(&self, index: u32, write: u64, due: u64) { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).hold(index, write, due); + } + + /// See [`TextureQueue::room`]. + pub(crate) fn texture_slots_room(&self, frame: u64) -> usize { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).room(frame) + } + /// Bytes of title slot `index`'s memory that were mapped when it was /// last uploaded in part (0: not uploaded, or whole). pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 { @@ -999,6 +1206,7 @@ impl HostHeap { /// whose pass runs first takes them (a title has one view heap). 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())); if ranges.is_empty() { return 0; @@ -1018,6 +1226,54 @@ impl HostHeap { slots.len() } + /// Takes the ranges of title memory written behind the guards' back + /// since the last call ([`page_written`]) and finds the slots whose + /// placed texture holds bytes of them ([`Spans::slots_holding`]). A + /// slot whose texture was uploaded before the write shows the bytes + /// from before: with `VICTORY_PAGE_WRITES` (`crate::watch::page_writes`, + /// bit 2) it is due again [`PAGE_WRITE_AFTER`] frames on, as memory + /// mapped under it would make it ([`HostHeap::texture_slots_remapped`]); + /// its host copy exists, so the upload needs no room on the card. A + /// slot still waiting for its first upload is left as it is: that + /// upload takes the bytes that are there by then. Slots tables read + /// are left to their draws. Counted either way; returns how many slots + /// it made due. + fn texture_slots_page_written(&self, frame: u64) -> usize { + let ranges = std::mem::take(&mut *PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner())); + if ranges.is_empty() { + return 0; + } + self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2] + } + + /// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end): + /// the slots that held bytes of them, those of them uploaded before, + /// and those made due (the latter, if `due`). + fn slots_written_under(&self, ranges: &[(u64, u64)], frame: u64, due: bool) -> [usize; 3] { + use std::sync::atomic::Ordering::Relaxed; + let mut slots: Vec = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect() + }; + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let held = slots.len(); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + // Uploaded before: out of the queue, or in it after an upload (in + // part, or whole and being looked at again). + slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0)); + PAGE_WRITES[2].fetch_add(held as u64, Relaxed); + PAGE_WRITES[3].fetch_add(slots.len() as u64, Relaxed); + if !due { + return [held, slots.len(), 0]; + } + for &slot in &slots { + textures.changed(slot, frame, frame + PAGE_WRITE_AFTER); + } + [held, slots.len(), slots.len()] + } + /// Whether host slot `index` is made from the very record the title /// has at `handle` now. Its host texture then exists (a slot keeps what /// it views), so bringing that texture up to date takes no memory of @@ -1048,6 +1304,101 @@ impl HostHeap { .is_some_and(Option::is_some) } + /// Levels on demand (`crate::tiles`): makes again the host slots of the + /// placed textures whose first level with memory changed since the + /// last call ([`levels_changed`]), each from the view it was made + /// from, so that it shows the texture from that level ([`make`]). Only + /// slots that are made; a slot draws read through a table is made by + /// its draw. Returns how many it made. + /// shortcut: the starts are kept in one place for all heaps; the heap + /// whose pass runs first takes them (a title has one view heap). + /// Levels on demand (`crate::tiles`): the card has room, so the slots + /// of up to [`Self::WAITING_A_PASS`] placed textures whose upload left + /// a held level without tiles at least a second ago + /// ([`levels_waiting`]) are due again from the next frame, as memory + /// mapped under them would make them + /// ([`HostHeap::texture_slots_remapped`]): the upload then gives the + /// level its tiles. To be called only while the card has room: without + /// it the upload would give nothing again. Slots tables read are left + /// to their draws (`texture.rs` `upload` asks again for those). Returns + /// how many slots it made due. + /// shortcut: kept in one place for all heaps, as the starts below. + pub(crate) fn texture_slots_waiting(&self, frame: u64) -> usize { + if self.sampler { + return 0; + } + let starts: Vec = { + let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()); + if waiting.is_empty() { + return 0; + } + let starts: Vec = waiting + .iter() + .filter(|&(_, &since)| crate::host::long_ago(since, 1000, 2)) + .map(|(&start, _)| start) + .take(Self::WAITING_A_PASS) + .collect(); + for start in &starts { + waiting.remove(start); + } + starts + }; + if starts.is_empty() { + return 0; + } + let mut slots: Vec = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + starts.iter().flat_map(|&start| placed.slots_at(start)).collect() + }; + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + for &slot in &slots { + textures.changed(slot, frame, frame + 1); + } + crate::tiles::STATS[10].fetch_add(slots.len() as u64, std::sync::atomic::Ordering::Relaxed); + slots.len() + } + + /// Textures a pass asks again for their levels + /// ([`HostHeap::texture_slots_waiting`]): the first ones given tiles + /// may take the room the others were asked for, and an upload that + /// gives nothing is a whole texture staged and copied for nothing. + const WAITING_A_PASS: usize = 128; + + pub(crate) fn texture_views_remade(&self) -> usize { + if self.sampler { + return 0; + } + let starts = std::mem::take(&mut *RESHOWN.lock().unwrap_or_else(|e| e.into_inner())); + if starts.is_empty() { + return 0; + } + let slots: Vec = { + 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 { + continue; + }; + if key == 0 { + continue; + } + let Some(view) = view_at(key as u32, (key >> 32) as u32) else { + continue; + }; + if let Some(kept) = make(&view, self.cpu(slot)) { + self.keep(slot, kept); + remade += 1; + } + } + remade + } + /// The memory of the texture title slot `index` views is not mapped /// (any more): a host slot made from it becomes null again, so that /// the host copy can be let go (`crate::resource::let_go_idle`; a slot @@ -1204,21 +1555,27 @@ impl HostHeap { Some(View::Placed(false, resource, desc)) if resource[0] != 1 && !self.tabled_lately(index, crate::frame::current()) => { - Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32)) + // (And the level the view starts at: word 4 of a texture + // view's description, after format, dimension, mapping + // and a pad.) + Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32, desc[4])) } _ => None, }; let stale = { use std::sync::atomic::Ordering::Relaxed; let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); - let span = placed_view - .and_then(|(resource, start)| Some((start, start.saturating_add(placed.bytes(resource)?)))); + let span = placed_view.and_then(|(resource, start, first)| { + Some((start, start.saturating_add(placed.bytes(resource)?), first)) + }); match span { - Some((start, end)) => { + Some((start, end, first)) => { SPANNED[0].fetch_min(start, Relaxed); SPANNED[1].fetch_max(end, Relaxed); placed.rule = stale_rule(); - placed.note(index, start, end, !seen) + let stale = placed.note(index, start, end, !seen); + placed.shows(index, first); + stale } None => { placed.forget(index); @@ -2104,6 +2461,32 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { return None; } + // Levels on demand (`crate::tiles`): a texture made level by + // level is shown from the first level that is the title's + // and has memory, if the title's view starts before it (a + // level without memory reads zeros: a black texture). The + // title's own view mostly starts there already. + if let Some(first) = crate::resource::first_shown(resource) + && first > 0 + { + // SAFETY: a live resource. + let own = unsafe { texture.GetDesc() }; + // The texture's own view (the title gave none): all of it. + let whole = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: own.Format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: u32::MAX, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + }; + crate::tiles::show_from(desc.get_or_insert(whole), first, u32::from(own.MipLevels)); + } // SAFETY: a live texture and a slot of our heap. unsafe { device.CreateShaderResourceView( @@ -2209,6 +2592,11 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { let len = u64::from(resource[4]) | u64::from(resource[5]) << 32; let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]); + // An empty title buffer: nothing to view, and no host copy to + // look for (#70: such views were in flight at device removals). + if len == 0 { + return None; + } if *unordered { buffer_uav(address, len, uav_desc(words), at) } else { @@ -2449,6 +2837,29 @@ mod tests { assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D); } + /// What the texture code asks of the spans (levels on demand): where + /// the next texture starts inside a span, the lowest level a view of a + /// texture shows, and a texture's slots. + #[test] + fn spans_say_the_next_start_and_the_lowest_level_viewed() { + let mut spans = Spans::default(); + // A 512x512 texture of 0x56000 bytes viewed from levels 3 and 1, + // and the next one 0x6000 after it (run 188). + spans.note(1, 0x1_0000, 0x1_0000 + 0x5_6000, true); + spans.shows(1, 3); + spans.note(2, 0x1_0000, 0x1_0000 + 0x5_6000, true); + spans.shows(2, 1); + spans.note(3, 0x1_6000, 0x1_6000 + 0x5_6000, true); + assert_eq!(spans.next_start(0x1_0000, 0x1_0000 + 0x5_6000), Some(0x1_6000)); + assert_eq!(spans.next_start(0x1_6000, 0x1_6000 + 0x5_6000), None); + assert_eq!(spans.first_viewed(0x1_0000), Some(1)); + assert_eq!(spans.first_viewed(0x1_6000), None); + assert_eq!(spans.slots_at(0x1_0000), vec![1, 2]); + // The view from level 1 goes: the texture is viewed from level 3. + spans.forget(2); + assert_eq!(spans.first_viewed(0x1_0000), Some(3)); + } + /// Views of one placed texture are told from views of others by the /// address and the resource description, not by what they show. #[test] @@ -2566,6 +2977,38 @@ mod tests { assert!(q.due(16, 100).iter().any(|d| d.0 == 98)); } + /// Slots held back for lack of room on the card are not handed out + /// until their frame, keep their place, are not counted as waiting + /// for their memory, and all come back at once when the card has room; + /// a slot written again meanwhile is the title's new write. + #[test] + fn slots_held_for_lack_of_room_come_back_when_there_is_room() { + let mut q = TextureQueue::default(); + for i in 0..4u32 { + q.written(20 + i, 1, 0, false); + } + let due = q.due(1, 100); + assert_eq!(due.len(), 4); + // The card is full: slots 20 and 21 are held back until frame 101. + for &(index, write) in due.iter().filter(|d| d.0 < 22) { + q.hold(index, write, 101); + } + let now: Vec = q.due(2, 100).into_iter().map(|d| d.0).collect(); + assert!(!now.contains(&20) && !now.contains(&21)); + assert!(now.contains(&22) && now.contains(&23)); + assert_eq!(q.census(2)[2], 0, "held slots do not wait for their memory"); + // Due again at their frame, in the order they had. + assert_eq!(q.due(101, 100), due); + // Slot 21 is written again while held: due as written. + q.written(21, 3, 0, false); + assert!(q.due(3, 100).iter().any(|d| d.0 == 21)); + // Room again at frame 5: slot 20 is due at once, and only it was + // still held as it was. + assert_eq!(q.room(5), 1); + assert!(q.due(5, 100).iter().any(|d| d.0 == 20)); + assert_eq!(q.room(6), 0); + } + /// Textures of which only the smallest levels are held, packed into /// one another's address range (the three of run 188: 0x2c000 bytes /// each at full size, their starts 0x2000 and 0x4000 apart): writing @@ -2659,6 +3102,63 @@ mod tests { assert_eq!(spans.slots_in(at + 0x32000, at + 0x33000), [] as [u32; 0]); } + /// A write names the textures that hold its bytes: the one that + /// starts where the write starts, not the neighbour before it, whose + /// held levels end there. + #[test] + fn a_write_at_the_start_of_a_packed_texture_names_it_alone() { + let mut spans = Spans::default(); + let at = 0x7_0000_0000u64; + assert!(spans.note(1, at, at + 0x2c000, true).is_empty()); + assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty()); + assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty()); + // A request that fills the second texture's held levels. + assert_eq!(spans.slots_in(at + 0x2000, at + 0x6000), [1, 2]); + assert_eq!(spans.slots_holding(at + 0x2000, at + 0x6000), [2]); + // From inside the first one's held levels on: both. + assert_eq!(spans.slots_holding(at + 0x1000, at + 0x3000), [1, 2]); + // A whole 64 KiB page: every texture that starts in it. + assert_eq!(spans.slots_holding(at, at + 0x10000), [1, 2, 3]); + // Past the last start, the last one; past all, or no bytes, none. + assert_eq!(spans.slots_holding(at + 0x20000, at + 0x21000), [3]); + assert_eq!(spans.slots_holding(at + 0x32000, at + 0x33000), [] as [u32; 0]); + assert_eq!(spans.slots_holding(at + 0x2000, at + 0x2000), [] as [u32; 0]); + } + + /// A write behind the guards' back under a placed texture: a slot + /// waiting for its first upload is left alone, one uploaded before is + /// counted, and made due two frames on when that is asked for. (The + /// ranges are handed over here, not through the list all heaps share.) + #[test] + fn a_page_write_makes_an_uploaded_texture_slot_due_when_asked() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + // 64x64 BC7, one mip, at an address no test and no title uses. + let at = 0x7fed_0000_0000u64; + let mut desc = [0u32; 16]; + (desc[10], desc[11]) = (at as u32, (at >> 32) as u32); + let view = View::Placed(false, [3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc); + assert!(heap.note_buffer(1, Some(&view), false).is_empty()); + let written = [(at, at + 0x1000)]; + // Waiting for its first upload: held, not uploaded, nothing done. + assert_eq!(heap.slots_written_under(&written, 50, true), [1, 0, 0]); + let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0]; + assert_eq!(queued, 1); + heap.texture_slot_done(1, write, None); + assert_eq!(slots(u64::MAX), []); + // Uploaded and out of the queue. Memory elsewhere: nothing. + assert_eq!(heap.slots_written_under(&[(at + 0x10_0000, at + 0x10_1000)], 60, true), [0, 0, 0]); + // Under it, counted only: it stays out of the queue. + assert_eq!(heap.slots_written_under(&written, 60, false), [1, 1, 0]); + assert_eq!(slots(u64::MAX), []); + // Under it, asked for: due two frames on, not before. + assert_eq!(heap.slots_written_under(&written, 60, true), [1, 1, 1]); + assert_eq!(slots(61), []); + assert_eq!(slots(62), [1]); + } + /// `VICTORY_STALE_TEXTURES=0`: nothing is ever stale, and a view that /// overlaps others is left out of the spans, as before. #[test] diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 29f34cf..ee74cc4 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -385,6 +385,20 @@ pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0), /// new ones, since the start. pub(crate) static HEAP_TEXTURES_REUPLOADED_FULL: AtomicU64 = AtomicU64::new(0); +/// Whether a pass over the textures picked by index on a full card holds +/// back the slots that need a new host copy (`VICTORY_FULL_CARD_PASS=0`: +/// no, as before: they stay due, each pass looks at the same ones again +/// and stops at the 257th). Held back, such a slot is looked at again +/// after about four seconds or as soon as the card has room, and the pass +/// goes on to the slots behind it: the ones whose host copy exists and +/// only wants bringing up to date, and the ones whose memory went (letting +/// their host copies go is what makes room). What is uploaded while the +/// card has room is the same either way. +fn full_card_pass() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_FULL_CARD_PASS").is_none_or(|v| v != "0")) +} + /// Whether a texture that has its host copy is still brought up to date /// while the card has no room for new ones (`VICTORY_REUPLOAD_WHEN_FULL=0`: /// no). @@ -1587,7 +1601,10 @@ impl State { static NEXT: AtomicU64 = AtomicU64::new(0); let now = crate::host::now_ms().max(1); let next = NEXT.load(Ordering::Relaxed); - let due_now = if next == 0 { !room } else { now >= next }; + // (With levels on demand the card may never be without room: the + // lines then start with the first texture made that way.) + let by_level = crate::tiles::STATS[4].load(Ordering::Relaxed) > 0; + let due_now = if next == 0 { !room || by_level } else { now >= next }; if !due_now || NEXT.compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed).is_err() { return; } @@ -1687,9 +1704,22 @@ impl State { once!("textures picked by index: the card has no room for more; they wait"); } let mut refused = 0; + // Room again: the slots held back while the card was full are due + // now (`full_card_pass`). + if room { + host.texture_slots_room(frame); + } // Slots whose texture's memory the runtime mapped, unmapped or // wrote since the last pass are due again. host.texture_slots_remapped(frame); + // Levels on demand: the slots of textures whose first level with + // memory changed since the last pass are made again from it. + host.texture_views_remade(); + // And with room, the textures whose upload left a held level + // without the card's memory are uploaded again. + if room { + host.texture_slots_waiting(frame); + } let (due, census) = host.texture_slots_due(frame, 4096); HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed); for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) { @@ -1844,7 +1874,15 @@ impl State { && heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle)); if !has_its_texture { refused += 1; - if refused > 256 { + if full_card_pass() { + // Held back for the frames of about four seconds + // (`most`), or until the card has room; the pass + // goes on, within a count that bounds one pass. + host.texture_slot_held(index, write, frame + most); + if refused > 1024 { + break; + } + } else if refused > 256 { break; } continue; @@ -3258,13 +3296,16 @@ fn view_state(view: Option<&View>) -> String { memory_state(address, crate::resource::placed_bytes(r).unwrap_or(0)) ), }; - format!("placed texture view_format={} {state}", d[0]) + // (Last, so that readers of the older lines still find + // theirs: the level the view starts at, and how many it shows.) + format!("placed texture view_format={} {state} view_levels={}+{}", d[0], d[4], d[5] as i32) } Some(View::Shader(r, d)) if crate::resource::texture_memory(*r as This).is_some() => { format!( - "texture object {r:#x} view_format={} {}", + "texture object {r:#x} view_format={} {} view_levels={}", d.as_ref().map_or(0, |d| d[0]), - texture_state(*r as This) + texture_state(*r as This), + d.as_ref().map_or("all".to_owned(), |d| format!("{}+{}", d[4], d[5] as i32)) ) } Some(v) => format!("{v:?}").chars().take(80).collect(), diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 492ae72..6559af1 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -679,7 +679,7 @@ fn create() -> windows::core::Result { /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). /// Reject it before creating a device in diagnostics' software-only mode. -fn warp_adapter() -> windows::core::Result { +pub(crate) fn warp_adapter() -> windows::core::Result { // SAFETY: plain DXGI adapter queries. unsafe { let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; @@ -2698,7 +2698,8 @@ fn declared_writes(runs: &[&HostList]) -> Vec { /// ([`read_backs`]), the frame's main pass by scissor rectangle with its /// culling dispatches (`draw.rs`, `walls_census`), the shader-written /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host -/// copies found stale after their refresh (`shadow.rs`), and, in the +/// copies found stale after their refresh (`shadow.rs`; only with +/// `VICTORY_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the /// runtime, the read requests that fail (with 2: every request). pub(crate) fn walls_trace() -> bool { static ON: OnceLock = OnceLock::new(); @@ -5607,6 +5608,13 @@ fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, us } impl Host { + /// The queue everything of ours runs on, for a call that must go to it + /// in order with the lists (`crate::tiles`: a texture's levels are + /// given memory ahead of the list that uploads them). + pub(crate) fn queue(&self) -> &ID3D12CommandQueue { + &self.queue + } + /// A buffer in the upload heap, mapped for writing. /// A buffer of `size` bytes the card writes and we read (a read back), /// in the state copies into it need. @@ -5854,6 +5862,7 @@ impl Meter { "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)", crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed) ); + crate::tiles::status(); { let [queued, due, away, partly, oldest] = [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed)); @@ -5877,6 +5886,19 @@ impl Meter { crate::descriptor::host::STALE[4].load(Ordering::Relaxed) ); } + { + let mode = crate::watch::page_writes(); + let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed)); + let [kept, dropped, slots, uploaded] = + [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed)); + tracing::info!( + "writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (VICTORY_PAGE_WRITES: unset counts, 1 acts, guards, slots, all)", + bytes >> 20, + if mode & 1 != 0 { "opened, taken again" } else { "left as they were" }, + if mode & 4 != 0 { "told as well" } else { "counted only" }, + if mode & 2 != 0 { "made due again" } else { "left as they were" } + ); + } #[cfg(feature = "diagnostics")] tracing::info!( "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms", diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 25461df..60751b5 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -267,11 +267,17 @@ pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size: struct Views { /// By address: bytes, the section's handle, the offset in it. views: BTreeMap, + /// By section and byte offset of a 64 KiB page: the address of that + /// page in every view that shows it. A write through one view of a + /// page is a write of the bytes every other view shows + /// (`crate::watch` guards them all). + pages: BTreeMap<(usize, u64), Vec>, /// Sections by handle: bytes, and whether made committed. sections: Vec<(usize, u64, bool)>, } -static VIEWS: Mutex = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new() }); +static VIEWS: Mutex = + Mutex::new(Views { views: BTreeMap::new(), pages: BTreeMap::new(), sections: Vec::new() }); fn views() -> std::sync::MutexGuard<'static, Views> { VIEWS.lock().unwrap_or_else(|e| e.into_inner()) @@ -288,7 +294,17 @@ pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { /// The runtime mapped `[at, at + len)` as a view of `section` from /// `offset` on. Call after [`crate::title_memory_remapped`] of the range. pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { - views().views.insert(at, (len, section, offset)); + { + let mut v = views(); + v.views.insert(at, (len, section, offset)); + for k in 0..len.div_ceil(K64) { + v.pages.entry((section, offset + (k * K64) as u64)).or_default().push(at + k * K64); + } + } + // This view is writable from now on: a guard over the same bytes at + // another view must look at them again, and the pages are noted written + // there (`crate::watch`). + crate::watch::views_mapped(section, offset, len); } /// What `[at, at + len)` showed is gone ([`crate::title_memory_remapped`]): @@ -303,10 +319,88 @@ pub(crate) fn views_gone(at: usize, len: usize) { let first = v.views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at).map(|(base, _)| *base); let gone: Vec = first.into_iter().chain(v.views.range(at.saturating_add(1)..end).map(|(base, _)| *base)).collect(); for base in gone { - v.views.remove(&base); + let Some((bytes, section, offset)) = v.views.remove(&base) else { + continue; + }; + for k in 0..bytes.div_ceil(K64) { + let key = (section, offset + (k * K64) as u64); + if let Some(pages) = v.pages.get_mut(&key) { + let page = base + k * K64; + pages.retain(|&shown| shown != page); + if pages.is_empty() { + v.pages.remove(&key); + } + } + } } } +/// The title views that overlap `[start, end)`, as `(address, bytes)`. +pub(crate) fn views_between(start: usize, end: usize) -> Vec<(usize, usize)> { + if start >= end { + return Vec::new(); + } + let v = views(); + let mut out = Vec::new(); + if let Some((&base, &(bytes, _, _))) = v.views.range(..=start).next_back() + && base + bytes > start + { + out.push((base, bytes)); + } + for (&base, &(bytes, _, _)) in v.views.range(start.saturating_add(1)..end) { + out.push((base, bytes)); + } + out +} + +/// The address of the 64 KiB page shown at `page` in every title view that +/// shows it, `page`'s own address included; empty if `page` is not a view. +pub(crate) fn pages_of(page: usize) -> Vec { + let v = views(); + let Some((&base, &(bytes, section, offset))) = v.views.range(..=page).next_back() else { + return Vec::new(); + }; + let within = page.wrapping_sub(base); + if within >= bytes || !within.is_multiple_of(K64) { + return Vec::new(); + } + v.pages.get(&(section, offset + within as u64)).cloned().unwrap_or_default() +} + +/// The title views that show any of the physical bytes `[offset, offset + +/// len)` of `section`, as `(address, bytes)` ranges in address order; not +/// those of a page shown in very many views (`MANY_VIEWS`). +pub(crate) fn views_of_section(section: usize, offset: u64, len: usize) -> Vec<(usize, usize)> { + if len == 0 { + return Vec::new(); + } + let v = views(); + let end = offset.saturating_add(len as u64); + let mut pages: Vec = Vec::new(); + let mut at = offset - offset % K64 as u64; + while at < end { + if let Some(shown) = v.pages.get(&(section, at)) + && shown.len() <= crate::watch::MANY_VIEWS + { + pages.extend(shown.iter().copied()); + } + match at.checked_add(K64 as u64) { + Some(next) => at = next, + None => break, + } + } + pages.sort_unstable(); + pages.dedup(); + let mut runs: Vec<(usize, usize)> = Vec::with_capacity(pages.len()); + for page in pages { + match runs.last_mut() { + Some((first, bytes)) if *first + *bytes == page => *bytes += K64, + _ => runs.push((page, K64)), + } + } + runs +} + /// How the views cover `[at, at + len)`. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub(crate) enum Cover { diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index db53f11..e001a47 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -50,6 +50,8 @@ pub mod shader_cache; mod memory; #[cfg(windows)] mod shadow; +#[cfg(windows)] +mod tiles; pub mod signature; #[cfg(windows)] mod texture; @@ -62,5 +64,6 @@ pub use host::on_failure; pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; #[cfg(windows)] pub use watch::{ - title_memory_reading, title_memory_remapped, title_memory_remapping, writing as kernel_will_write, + title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_written, + writing as kernel_will_write, }; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 44c8965..f9edaab 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -861,6 +861,9 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { // Depth textures shaders also write: what they wrote, first. list.twin_use(dst, false, true); list.twin_use(src, false, false); + // A destination made level by level gets its levels' memory + // ahead of this list (`crate::tiles`). + crate::texture::card_writes(list, dst, to, None); ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); crate::texture::host_written(dst); @@ -994,6 +997,11 @@ extern "system" fn copy_texture_region( // A depth texture shaders also write: what they wrote, first (the // source above too). list.twin_use(dst.resource, false, true); + // A destination made level by level gets the level's memory ahead + // of this list (`crate::tiles`): the title's bake copies each level + // of its result into a block-compressed texture of that kind, and + // a copy into a level without memory is dropped. + crate::texture::card_writes(list, dst.resource, to, Some(dst.footprint.offset as u32)); ensure_state(list, dst.resource, COPY_DEST); crate::texture::host_written(dst.resource); let mut to_location = dst; @@ -1147,6 +1155,8 @@ extern "system" fn resolve( // Depth textures shaders also write: what they wrote, first. list.twin_use(dst, false, true); list.twin_use(src, false, false); + // As for a copy (`crate::tiles`). + crate::texture::card_writes(list, dst, to, Some(dst_sub)); ensure_state(list, dst, RESOLVE_DEST); ensure_state(list, src, RESOLVE_SOURCE); crate::texture::host_written(dst); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index e4fee24..d701973 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -244,22 +244,24 @@ pub(crate) fn pc_format(format: u32) -> u32 { /// (NVIDIA) refused the whole texture, so every pass that wrote it drew /// nothing. There 8-bit RGBA stands in: the same channels in the same /// order, every 4-bit level exact and every 5-bit level within 1/510. +/// The title also renders to R9G9B9E5 (67), which no PC GPU does: 16-bit +/// float RGBA stands in, with at least R9G9B9E5's precision and range. /// The title's pipelines and views of such targets name the stand-in too /// ([`view_format`], the host view checks). /// shortcut: copies between such a target and a texture the title fills /// itself in the 16-bit format are skipped ([`stands_in`]); convert them /// if a pass turns out to need one. pub(crate) fn target_format(format: u32) -> u32 { - const STAND_INS: [(u32, u32); 2] = [(86, 28), (115, 28)]; + const STAND_INS: [(u32, u32); 3] = [(86, 28), (115, 28), (67, 10)]; let Some(i) = STAND_INS.iter().position(|&(f, _)| f == format) else { return format; }; #[cfg(windows)] { use windows::Win32::Graphics::Direct3D12::*; - static REFUSED: std::sync::OnceLock<[bool; 2]> = std::sync::OnceLock::new(); + static REFUSED: std::sync::OnceLock<[bool; 3]> = std::sync::OnceLock::new(); let refused = REFUSED.get_or_init(|| { - STAND_INS.map(|(f, _)| { + STAND_INS.map(|(f, to)| { let Some(host) = crate::host::host() else { return false; }; @@ -279,7 +281,7 @@ pub(crate) fn target_format(format: u32) -> u32 { | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0; let refused = asked.is_err() || support.Support1.0 & both != both; if refused { - tracing::info!(format = f, "the host does not render to this format: 8-bit RGBA stands in"); + tracing::info!(format = f, stand_in = to, "the host does not render to this format: a stand-in is used"); } refused }) @@ -1125,6 +1127,10 @@ pub(crate) struct HostTexture { /// Whether its contents come from title memory ([`fills`]): counted in /// [`KINDS`] while it lives. filled: bool, + /// Made without memory of its own (`crate::tiles`): the tiles its + /// levels have been given. Its `bytes` are 0: what it holds of the card + /// is counted there. + pub(crate) tiled: Option, } /// What a title texture has on the host: its host copy and, for a depth @@ -1303,7 +1309,49 @@ fn hosted(this: This, make: bool) -> Option { .clear .as_ref() .map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast::()); - let Some(texture) = host_texture(&r.desc, r.host.state, clear) else { + // Levels on demand (`crate::tiles`): a texture the title places in + // memory and fills, of a megabyte or more, that does not hold all + // its levels now, is made without memory and given it level by + // level. It does not hold them all if its memory is not all + // mapped, if the next texture starts inside its span, or if a + // view of it starts below level 0. Every other texture, and this + // one if the card will not have it so, is made as before. + const TEXTURE_2D: u32 = 3; + let mut tiled = None; + let mut texture = None; + let shape_fits = fills(&r.desc) + && r.desc.dimension == TEXTURE_2D + && r.desc.depth_or_array_size == 1 + && r.desc.mip_levels > 1 + && r.desc.sample_count <= 1; + if shape_fits && r.host.placed.load(Relaxed) && crate::tiles::wanted() { + let bytes = footprint(&r.desc).map_or(0, |f| f.size); + let start = r.data() as u64; + // What the upload can read: a console layout, no XOR mode + // (`crate::texture` `staging`). + let readable = texture_layout(&r.desc).is_some_and(|t| !t.planes[0].layout.desc.swizzle.xor()); + let partly = readable + && bytes >= crate::tiles::floor() + && (!crate::texture::committed(r.data().cast_const(), bytes as usize) + || crate::descriptor::host::next_start(start, start.saturating_add(bytes)).is_some() + || crate::descriptor::host::first_viewed(start).is_some_and(|first| first > 0)); + let reserved = if partly { host_texture_as(&r.desc, r.host.state, clear, true) } else { None }; + let cut = reserved + .as_ref() + .zip(crate::host::host()) + .and_then(|(t, host)| crate::tiles::Tiled::make(&host.device, t, u32::from(r.desc.mip_levels))); + // (Both or neither: a reserved texture the card will not cut + // into tiles is dropped here, and the old kind is made below.) + if cut.is_some() { + tiled = cut; + texture = reserved; + } + } + let texture = match texture { + Some(texture) => Some(texture), + None => host_texture(&r.desc, r.host.state, clear), + }; + let Some(texture) = texture else { r.host.refused.store(true, Relaxed); return None; }; @@ -1320,7 +1368,10 @@ fn hosted(this: This, make: bool) -> Option { ); } let state = crate::host::legal_state(&texture, crate::host::texture_state(r.host.state)); - let mut host = HostTexture::new(texture, state); + let mut host = match tiled { + Some(tiled) => HostTexture::new_tiled(texture, state, tiled), + None => HostTexture::new(texture, state), + }; host.filled = fills(&r.desc); if host.filled { KINDS[0].fetch_add(1, Relaxed); @@ -1371,7 +1422,9 @@ pub(crate) fn room() -> bool { let mb = std::env::var("VICTORY_TEXTURE_BUDGET_MB").ok()?; mb.trim().parse::().ok().map(|mb| mb << 20) }); - let filled = KINDS[1].load(Relaxed); + // (With the tiles of the copies made level by level, whose own bytes + // count as none: `crate::tiles`.) + let filled = KINDS[1].load(Relaxed) + crate::tiles::given_total(); if let Some(limit) = limit { return filled < limit; } @@ -1379,11 +1432,31 @@ pub(crate) fn room() -> bool { return true; } match crate::host::host().and_then(|h| h.video_memory()) { - Some([budget, used, ..]) => used < budget / 100 * room_percent(), + // What is kept for card copies of title buffers not made yet + // counts as used (`crate::shadow::card_room_kept`; 0 by default). + Some([budget, used, ..]) => used + crate::shadow::card_room_kept() < budget / 100 * room_percent(), None => filled < WITHOUT_BUDGET, } } +/// [`room`] as it was at most a tenth of a second ago, for a question +/// asked of many textures a frame ([`room`] asks the system each time). +#[cfg(windows)] +pub(crate) fn room_lately() -> bool { + use std::sync::atomic::Ordering::Relaxed; + // The tenth of a second of the last asking, counted from 1, and its + // answer in the lowest bit. + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let tenth = crate::host::now_ms() / 100 + 1; + let last = LAST.load(Relaxed); + if last >> 1 == tenth { + return last & 1 != 0; + } + let room = room(); + LAST.store((tenth << 1) | u64::from(room), Relaxed); + room +} + /// The share of the card's budget, in percent, up to which host copies of /// textures picked by index are made ([`room`]): 90 unless /// `VICTORY_TEXTURE_ROOM_PERCENT` says another (50 to 97). At 90 about a @@ -1474,7 +1547,8 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, return; } let began = std::time::Instant::now(); - let mut copies: Vec<(usize, ResourceDesc, u64)> = Vec::new(); + // (The last: made level by level, its bytes are those of its tiles.) + let mut copies: Vec<(usize, ResourceDesc, u64, bool)> = Vec::new(); // Textures the title fills without a host copy: never one, one let go. let mut without = [0u64; 2]; { @@ -1487,7 +1561,10 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, } let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); match made.as_ref() { - Some((host, _)) => copies.push((r.data() as usize, r.desc, host.bytes)), + Some((host, _)) => copies.push(match &host.tiled { + Some(tiled) => (r.data() as usize, r.desc, tiled.given_bytes(), true), + None => (r.data() as usize, r.desc, host.bytes, false), + }), None => without[usize::from(r.host.gone.load(Relaxed))] += 1, } } @@ -1508,9 +1585,16 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, // a level not mapped; with the largest level not mapped; with no // level mapped; copies without a console layout (not asked). let mut c = [0u64; 7]; - for &(memory, desc, bytes) in &copies { + // Of the copies: made level by level, and the bytes of their tiles. + let mut on_demand = [0u64; 2]; + for &(memory, desc, bytes, by_level) in &copies { c[0] += 1; c[1] += bytes; + if by_level { + on_demand[0] += 1; + on_demand[1] += bytes; + continue; + } let Some(layout) = texture_layout(&desc).map(|t| t.planes[0].layout.clone()) else { c[6] += 1; continue; @@ -1587,6 +1671,7 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, [gone[0], gone[1] >> 20, gone[2], gone[3] >> 20, gone[4], gone[5] >> 20, gone[6]]; let [let_go, let_go_mb, again, again_mb, made] = [since[0], since[1] >> 20, since[2], since[3] >> 20, since[4]]; let walk_ms = began.elapsed().as_millis() as u64; + let [by_level_n, by_level_mb] = [on_demand[0], on_demand[1] >> 20]; tracing::info!( "card accounting: room {room}, the card {used_mb} MB in use of a budget of {budget_mb} MB; host copies of textures the title \ fills: {copies_n} alive {copies_mb} MB, of which {unmapped_mb} MB are levels whose title memory is not mapped ({partly} copies \ @@ -1597,7 +1682,8 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, all mapped {never_whole_mb} MB, {never_part} in part {never_part_mb} MB mapped, {never_none} not mapped); {gone_n} whose host \ copy was let go ({gone_mb} MB: {gone_whole} all mapped {gone_whole_mb} MB, {gone_part} in part {gone_part_mb} MB mapped, \ {gone_none} not mapped); since the line before: {let_go} host copies let go {let_go_mb} MB, {again} made again {again_mb} MB, \ - {made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own" + {made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own; of the host \ + copies {by_level_n} are made level by level and hold {by_level_mb} MB of tiles (in the MB alive, not in the levels not mapped)" ); WALKING.store(false, Relaxed); }; @@ -1688,6 +1774,66 @@ pub(crate) fn let_go_idle() { } } +/// For the memory line: the host copies the sweep never lets go +/// ([`let_go_idle`] takes only copies of textures the title fills that the +/// host never copied into), by what would say they are dead weight. A +/// count and the bytes (twins included) of: the copies the host renders to +/// or writes; of them, those whose title memory is not mapped now (its +/// first page); those nothing has used for 30 seconds and 60 frames and +/// that no list and no slot holds; those that are both; the copies of +/// textures the title fills that the host copied into; and, of the first, +/// the placed ones. Render-target copies grew from 2,319 MB at the world's +/// first frame to 3,075 MB 150 s later in run 197 and never shrank, while +/// 26,517 copies of filled textures were let go to stay under the card's +/// line. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn targets_census() -> [u64; 12] { + use std::sync::atomic::Ordering::Relaxed; + let mut c = [0u64; 12]; + let all = textures(); + for &at in all.iter() { + // SAFETY: as in `let_go_idle`. + let r = unsafe { &*(at as *const Resource) }; + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + let Some((host, twin)) = made.as_ref() else { + continue; + }; + let copied_into = host.filled && crate::texture::host_wrote(at); + if host.filled && !copied_into { + continue; + } + let bytes = host.bytes + twin.as_ref().map_or(0, |t| t.colour.bytes); + let mut add = |i: usize| { + c[i] += 1; + c[i + 1] += bytes; + }; + if copied_into { + add(8); + continue; + } + add(0); + let placed = r.host.placed.load(Relaxed); + // Its first page: what is there of a texture starts there. + let unmapped = placed && !crate::texture::committed(r.data().cast_const(), 1); + let idle = crate::host::long_ago(r.host.used.load(Relaxed), 30_000, 60) + && std::sync::Arc::strong_count(host) == 1 + && crate::host::references(&host.texture) == 1; + if unmapped { + add(2); + } + if idle { + add(4); + } + if unmapped && idle { + add(6); + } + if placed { + add(10); + } + } + c +} + /// For the memory line: title textures with a host copy the host renders /// to or writes and those copies' bytes (twins included); title textures /// without a host copy and the bytes of title memory they are; host copies @@ -1772,6 +1918,24 @@ impl HostTexture { state: std::sync::atomic::AtomicU32::new(state), bytes, filled: false, + tiled: None, + } + } + + /// A texture made without memory of its own (`crate::tiles`): counted + /// as a host texture of no bytes. + fn new_tiled( + texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, + state: u32, + tiled: crate::tiles::Tiled, + ) -> HostTexture { + HOST_TEXTURES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + HostTexture { + texture, + state: std::sync::atomic::AtomicU32::new(state), + bytes: 0, + filled: false, + tiled: Some(tiled), } } } @@ -1843,6 +2007,18 @@ fn host_texture( desc: &ResourceDesc, state: u32, clear: *const c_void, +) -> Option { + host_texture_as(desc, state, clear, false) +} + +/// [`host_texture`]; `reserved`: without memory of its own, to be given +/// tiles level by level (`crate::tiles`). +#[cfg(windows)] +fn host_texture_as( + desc: &ResourceDesc, + state: u32, + clear: *const c_void, + reserved: bool, ) -> Option { use windows::Win32::Graphics::Direct3D12::*; const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access @@ -1898,23 +2074,40 @@ fn host_texture( ..Default::default() }; let mut texture: Option = None; - // SAFETY: the description has the host layout (checked size, same - // fields); the out pointer is ours. - let made = unsafe { - host.device.CreateCommittedResource( - &heap, - D3D12_HEAP_FLAG_NONE, - (&raw const d).cast(), - D3D12_RESOURCE_STATES( - crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, - ), - // The same layout: format, then color or depth and stencil. - clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), - &mut texture, - ) + let made = if reserved { + // The card's own layout of 64 KiB tiles, which a reserved texture + // must have. + d.layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE.0 as u32; + // SAFETY: as below; a texture the title fills has no clear value. + unsafe { + host.device.CreateReservedResource( + (&raw const d).cast(), + D3D12_RESOURCE_STATES( + crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, + ), + None, + &mut texture, + ) + } + } else { + // SAFETY: the description has the host layout (checked size, same + // fields); the out pointer is ours. + unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES( + crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, + ), + // The same layout: format, then color or depth and stencil. + clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), + &mut texture, + ) + } }; if let Err(e) = made { - tracing::warn!(error = %e, desc = ?d, "no host texture"); + tracing::warn!(error = %e, desc = ?d, reserved, "no host texture"); } if let Some(t) = &texture { crate::host::name(t, || { @@ -1924,6 +2117,73 @@ fn host_texture( texture } +/// The host copy of title texture `this` if it is made and was made +/// without memory of its own (`crate::tiles`); it is not made here. +#[cfg(windows)] +pub(crate) fn host_tiled(this: This) -> Option { + if this.is_null() || !crate::tiles::wanted() { + return None; + } + hosted(this, false).map(|(host, _)| host).filter(|host| host.tiled.is_some()).map(OnDemand) +} + +/// The first level a view of title texture `this` may show, if its host +/// copy is made level by level and some level is held and has memory +/// (`crate::tiles::Tiled::first_shown`). +#[cfg(windows)] +pub(crate) fn first_shown(this: This) -> Option { + host_tiled(this)?.tiled()?.first_shown() +} + +/// A host copy made without memory of its own (`crate::tiles`), as a +/// submission-time step of a list holds it. +#[cfg(windows)] +pub(crate) struct OnDemand(std::sync::Arc); + +// SAFETY: the host texture is named only in queue calls, which any thread +// may make; what it has been given is behind a lock of its own. +#[cfg(windows)] +unsafe impl Send for OnDemand {} +// SAFETY: as above. +#[cfg(windows)] +unsafe impl Sync for OnDemand {} + +#[cfg(windows)] +impl OnDemand { + pub(crate) fn tiled(&self) -> Option<&crate::tiles::Tiled> { + self.0.tiled.as_ref() + } + + /// [`crate::tiles::Tiled::uploaded`]; `memory`: where the texture's + /// title memory starts (its slots are made again if the first level + /// they may show changed). + /// Held levels get tiles only while the card has room ([`room`]). + /// Returns whether a level is still without its tiles: the caller + /// records the upload again later. + pub(crate) fn uploaded(&self, held: u32, memory: u64) -> bool { + let Some(tiled) = &self.0.tiled else { + return false; + }; + let (changed, waiting) = tiled.uploaded(&self.0.texture, held, room()); + if changed { + crate::descriptor::host::levels_changed(memory); + } + if waiting { + crate::tiles::STATS[9].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + waiting + } + + /// [`crate::tiles::Tiled::card_wrote`]; `memory` as above. + pub(crate) fn card_wrote(&self, levels: u32, memory: u64) { + if let Some(tiled) = &self.0.tiled + && tiled.card_wrote(&self.0.texture, levels) + { + crate::descriptor::host::levels_changed(memory); + } + } +} + /// A texture's console memory and description; `None` for buffers. pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> { if this.is_null() { diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 34ac4ac..c5365c4 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -1,7 +1,7 @@ //! Translated shaders kept on disk (decision 0003): under the configured -//! cache folder, keyed by the container's content and by the VIctory build -//! that translated it (the BLAKE3 of our executable), so a rebuilt -//! translator never serves an old translation. Entries go through +//! cache folder, keyed by the container's content and by the translator +//! that translated it (its source fingerprint and settings, see `build`), so +//! a changed translator never serves an old translation. Entries go through //! `victory-pipeline`'s content-addressed cache, which writes them //! atomically; an entry that does not read back is translated again. //! @@ -37,60 +37,58 @@ pub(crate) fn counts() -> (u64, u64) { (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed)) } -/// What identifies this build: the BLAKE3 of our executable file and of -/// the translation settings it runs with (the loop limit, which a -/// diagnostics build can change at run time). -fn build() -> &'static [u8; 32] { - static BUILD: OnceLock<[u8; 32]> = OnceLock::new(); - BUILD.get_or_init(|| { - let exe = std::env::current_exe().and_then(std::fs::read); - let limit = victory_shader::emit::loop_limit(); - if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT { - tracing::warn!( - limit, - "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner" - ); - } - match exe { - Ok(mut bytes) => { - bytes.extend_from_slice(&limit.to_le_bytes()); - // So is the view heap's null slot (it differs by host GPU): - // a translation cached without the clamp must not be served. - crate::descriptor::host::probe_view_limit(); - bytes.extend_from_slice(&victory_shader::emit::view_heap_limit().to_le_bytes()); - // Which group barriers wait is part of the translation too. - bytes.push(victory_shader::emit::group_sync()); - // So are the switches that pick the form of a wave64 program: - // without them here a run with `VICTORY_WAVE_WIDE=0` was - // served the translations an earlier run of the same - // executable had cached with the switch unset. - for name in [ - "VICTORY_WAVE_WIDE", - "VICTORY_WAVE_DEEP_SKIPS", - "VICTORY_WAVE_OWN_BITS", - "VICTORY_F16_NEAREST", - ] { - bytes.extend_from_slice(name.as_bytes()); - bytes.push(b'='); - if let Some(value) = std::env::var_os(name) { - bytes.extend_from_slice(value.as_encoded_bytes()); - } - bytes.push(0); +/// What identifies the translation, besides the container: the shader +/// crate's fingerprint (its source, every switch it reads, the host facts the +/// device gave it, the loop limit, barrier waits and clean-up passes) and +/// this file's encoding of the result. Not the whole executable any more: a +/// rebuild that leaves the translator alone keeps its translations (each new +/// build used to translate the title's thousands of shaders again, which kept +/// the first minutes of every test run short of pipelines). +/// `VICTORY_SHADER_CACHE_KEY=exe` restores the old key (the executable's hash). +/// Worked out per lookup, so a translation made before the device said its +/// wave size is never filed under the later key. +fn build() -> [u8; 32] { + static WARNED: std::sync::Once = std::sync::Once::new(); + let limit = victory_shader::emit::loop_limit(); + if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT { + WARNED.call_once(|| tracing::warn!(limit, "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner")); + } + static EXE: OnceLock> = OnceLock::new(); + let exe = EXE.get_or_init(|| { + if std::env::var_os("VICTORY_SHADER_CACHE_KEY").is_some_and(|v| v == "exe") { + match std::env::current_exe().and_then(std::fs::read) { + Ok(bytes) => Some(*blake3::hash(&bytes).as_bytes()), + Err(e) => { + tracing::warn!(error = %e, "cannot read our executable; keying on the translator"); + None } - // And which clean-up passes ran over the translated code. - bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes()); - *blake3::hash(&bytes).as_bytes() - } - Err(e) => { - // Without it no entry can be trusted: a fresh key per run. - tracing::warn!(error = %e, "cannot read our executable; shader cache unused"); - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default(); - *blake3::hash(&now.as_nanos().to_le_bytes()).as_bytes() } + } else { + None } - }) + }); + let mut h = blake3::Hasher::new(); + h.update(b"victory shader cache key 2\0"); + if let Some(exe) = exe { + h.update(exe); + } + h.update(&victory_shader::emit::translation_fingerprint()); + h.update(include_bytes!("shader_cache.rs")); + *h.finalize().as_bytes() +} + +/// The offline warm-up (`victory translate --warm`): `container` is +/// translated into the cache unless it is there already. `Ok(true)`: it +/// was translated now. Needs [`use_shader_cache`] and the same host facts +/// the run will have (`victory_shader::emit::translation_fingerprint`). +pub fn warm(container: &[u8]) -> Result { + let cache = CACHE.get().ok_or("no shader cache")?; + let ran = AtomicBool::new(false); + let translate = |c: &[u8]| { + ran.store(true, Ordering::Relaxed); + victory_shader::emit::translate(c).map_err(|e| e.to_string()) + }; + cached(cache, &build(), container, translate).map(|_| ran.load(Ordering::Relaxed)) } /// The translation of a console shader container, from the cache when @@ -98,7 +96,7 @@ fn build() -> &'static [u8; 32] { pub(crate) fn host_shader(container: &[u8]) -> Result { let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); match CACHE.get() { - Some(cache) => cached(cache, build(), container, translate), + Some(cache) => cached(cache, &build(), container, translate), None => translate(container), } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 133e871..f47de44 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -162,6 +162,40 @@ fn card_limits() -> (u64, u64) { /// Bytes alive of copies' card sides, and of their "before" twins. static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; +/// Whether the texture queue leaves room on the card for the card copies +/// of title buffers that are not made yet +/// (`VICTORY_CARD_ROOM_FOR_BUFFERS=1`; off by default). +/// +/// The copies are made in one burst when the world loads (run 189: 94 of +/// its 95 within two seconds, right before the first world frame), and +/// [`card_for`] makes one only while the card is under eight tenths of its +/// budget. That held as long as the textures picked by index filled the +/// card after the burst. Since the texture queue keeps packed neighbours +/// (52b8060) it fills the card while the world loads: 85% and more at the +/// burst in runs 190 to 192, so one copy of 95 was made, the CPU looked +/// for shader writes in 600 to 720 MB a frame where it had been 30, and +/// the frame went from about 240 to 370-470 ms. +/// +/// With the switch, the texture queue's rule (`resource::room`) counts the +/// part of [`card_limits`]' second number that no copy has taken yet as +/// used, and a copy may be made up to nine tenths of the budget: the room +/// it takes was kept for it. After the burst what is kept is what the +/// burst left of the limit (87 MB of 1,024 in run 189). +fn card_room_kept_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_BUFFERS").is_some_and(|v| v == "1")) +} + +/// The bytes of the card's memory the texture queue leaves free for card +/// copies of title buffers not made yet ([`card_room_kept_on`]): 0 with +/// the switch off or without card copies. +pub(crate) fn card_room_kept() -> u64 { + if !card_room_kept_on() || !cards() { + return 0; + } + card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed)) +} + /// The copies in the card's memory. static CARDED: Mutex>> = Mutex::new(Vec::new()); @@ -212,8 +246,11 @@ fn card_for(size: u64) -> Option { // queue's own rule (`resource::room`: nine tenths of the budget) counts // them, so the card's use stays where it was and the textures' share // shrinks by the copies' bytes, at most `card_limits`' second number. + // (With `card_room_kept_on` the texture queue kept this copy's room + // free, and the copy may go up to the queue's own line.) + let tenths = if card_room_kept_on() { 9 } else { 8 }; if let Some([budget, used, ..]) = host.video_memory() - && used + size > budget / 10 * 8 + && used + size > budget / 10 * tenths { return None; } @@ -598,6 +635,155 @@ fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, out } +/// The runs of 4-byte words of title memory (cut on its addresses; +/// `read` and `merged` are of the memory at `address`) that hold a byte in +/// which `merged` differs from `read`, as (offset, bytes) in order to +/// `put`. A shader stores words, so these are what the card wrote; every +/// other byte of `merged` is the title's as it was read. +fn word_runs(address: usize, read: &[u8], merged: &[u8], mut put: impl FnMut(usize, usize)) { + let n = read.len().min(merged.len()); + let mut i = 0; + while i < n { + // Equal bytes are passed over, 32 at a time while they last. + match first_difference(&read[i..n], &merged[i..n]) { + Some(d) => i += d, + None => break, + } + // From the word that holds this byte (or the stretch's first + // byte) to the end of the last word in a row that holds one. + let first = i - ((address + i) & 3).min(i); + let mut end = first; + while end < n { + let word = (((address + end) | 3) + 1 - address).min(n); + if read[end..word] == merged[end..word] { + break; + } + end = word; + } + put(first, end - first); + i = end; + } +} + +/// Whether the merges that write a stretch of title memory back +/// ([`Shadow::relay_merge`], [`Shadow::card_merge`], +/// [`Shadow::card_merge_relay`]) look, right before that write, for title +/// bytes it is about to put back to older values (`VICTORY_MERGE_RACE=1`; +/// off by default). Logging only: [`merge_race`]. +fn merge_race_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_MERGE_RACE").is_some_and(|v| v == "1")) +} + +/// [`merge_race`]'s sums. Of frame `frame`, and in `total` since the +/// start: stretches written back, their bytes, title bytes put back to +/// older values, bytes the title and the card both changed, stretches with +/// either, the runs a write of the card's words alone makes +/// ([`word_runs`]) and their bytes. `said`: the frame's first stretches +/// with either. `quiet`: frames since the last line. +struct MergeRace { + frame: u64, + now: [u64; 7], + said: Vec, + total: [u64; 7], + quiet: u64, +} + +static MERGE_RACE: Mutex = + Mutex::new(MergeRace { frame: 0, now: [0; 7], said: Vec::new(), total: [0; 7], quiet: 0 }); + +/// With [`merge_race_on`], right before a merge writes `merged` over title +/// memory at `address` (a stretch of the copy of the title buffer `copy`: +/// start and bytes): title memory is read once more and compared with +/// `read`, what the merge read of it before. A byte that changed in +/// between and that the write-back stores with its value as first read +/// (the card did not change it) is a title byte put back to an older +/// value; one the write-back stores with the card's byte is one both +/// changed. Only bytes the write-back stores are looked at. Summed per +/// frame; a line for every frame that has any, and one every 100 frames +/// whatever it holds, so that "none" is said, not assumed. +/// +/// A lower bound: a title write that lands after this read (while the +/// write-back itself runs) is not seen, nor one that wrote a byte and then +/// its old value again. Costs one more read and two compares of every +/// stretch written back, on the thread that merges. +fn merge_race(read: Option<&[u8]>, copy: (u64, u64), address: usize, merged: &[u8], which: &'static str) { + if !merge_race_on() { + return; + } + let Some(read) = read else { + return; + }; + let n = read.len().min(merged.len()); + let (read, merged) = (&read[..n], &merged[..n]); + let mut runs: Vec<(usize, usize)> = Vec::new(); + word_runs(address, read, merged, |off, len| runs.push((off, len))); + let whole = [(0, n)]; + let looked: &[(usize, usize)] = &whole; + let mut again = vec![0u8; n]; + let (mut put_back, mut both, mut first) = (0u64, 0u64, None); + if crate::host::read_into(address as *const u8, &mut again) { + for &(off, len) in looked { + for i in off..off + len { + if again[i] == read[i] || again[i] == merged[i] { + continue; + } + if merged[i] == read[i] { + put_back += 1; + first.get_or_insert(i); + } else { + both += 1; + } + } + } + } + let frame = crate::frame::current(); + let mut race = MERGE_RACE.lock().unwrap_or_else(|e| e.into_inner()); + if race.frame != frame { + race.quiet += 1; + if race.now[4] > 0 || race.quiet >= 100 { + tracing::info!( + frame = race.frame, + stretches = race.now[0], + stretch_bytes = race.now[1], + put_back = race.now[2], + both_changed = race.now[3], + stretches_hit = race.now[4], + word_runs = race.now[5], + word_run_bytes = race.now[6], + stretches_since_start = race.total[0], + stretch_bytes_since_start = race.total[1], + put_back_since_start = race.total[2], + both_changed_since_start = race.total[3], + stretches_hit_since_start = race.total[4], + word_runs_since_start = race.total[5], + word_run_bytes_since_start = race.total[6], + first = ?race.said, + "merge race: title bytes that changed between a merge's read of title memory and its write-back of what shaders wrote, in this frame (VICTORY_MERGE_RACE=1)" + ); + race.quiet = 0; + } + race.frame = frame; + race.now = [0; 7]; + race.said.clear(); + } + let hit = u64::from(put_back + both > 0); + let run_bytes: u64 = runs.iter().map(|r| r.1 as u64).sum(); + let add = [1, n as u64, put_back, both, hit, runs.len() as u64, run_bytes]; + for (i, v) in add.iter().enumerate() { + race.now[i] += v; + race.total[i] += v; + } + if hit > 0 && race.said.len() < 8 { + race.said.push(format!( + "{which}: copy {:#x}+{:#x} stretch {address:#x}+{n:#x}: {put_back} put back (first at {:#x}), {both} both changed", + copy.0, + copy.1, + address + first.unwrap_or(0) + )); + } +} + #[cfg(test)] mod relay_tests { use super::{Flights, changed_runs, merge_piece, outside}; @@ -857,51 +1043,54 @@ fn give_back(v: Vec) { const NOT_WATCHED: u8 = 2; -/// Where `a` and `b` (of one length) first differ, compared eight bytes at -/// a time. +// Fixed-size equality compiles to two SIMD comparisons on Windows x64. +// Only the first or last unequal chunk needs a byte-wise search. +const DIFF_CHUNK: usize = 32; + +/// Where `a` and `b` first differ within their common length. fn first_difference(a: &[u8], b: &[u8]) -> Option { - let whole = a.len().min(b.len()) / 8 * 8; - let from = a[..whole] - .as_chunks::<8>().0.iter() - .zip(b[..whole].chunks_exact(8)) - .position(|(x, y)| x != y) - .map_or(whole, |word| word * 8); - a[from..].iter().zip(&b[from..]).position(|(x, y)| x != y).map(|i| from + i) + let len = a.len().min(b.len()); + let (a_chunks, a_tail) = a[..len].as_chunks::(); + let (b_chunks, b_tail) = b[..len].as_chunks::(); + let (offset, a, b) = match a_chunks.iter().zip(b_chunks).position(|(x, y)| x != y) { + Some(i) => (i * DIFF_CHUNK, &a_chunks[i][..], &b_chunks[i][..]), + None => (len - a_tail.len(), a_tail, b_tail), + }; + a.iter().zip(b).position(|(x, y)| x != y).map(|i| offset + i) } -/// Where `a` and `b` (of one length) last differ. +/// Where `a` and `b` last differ within their common length. fn last_difference(a: &[u8], b: &[u8]) -> Option { - let whole = a.len().min(b.len()) / 8 * 8; - if let Some(i) = a[whole..].iter().zip(&b[whole..]).rposition(|(x, y)| x != y) { - return Some(whole + i); + let len = a.len().min(b.len()); + let (a_chunks, a_tail) = a[..len].as_chunks::(); + let (b_chunks, b_tail) = b[..len].as_chunks::(); + if let Some(i) = a_tail.iter().zip(b_tail).rposition(|(x, y)| x != y) { + return Some(len - a_tail.len() + i); } - let word = a[..whole] - .as_chunks::<8>().0.iter() - .zip(b[..whole].chunks_exact(8)) - .rposition(|(x, y)| x != y)? - * 8; - a[word..word + 8] + let chunk = a_chunks.iter().zip(b_chunks).rposition(|(x, y)| x != y)?; + a_chunks[chunk] .iter() - .zip(&b[word..word + 8]) + .zip(&b_chunks[chunk]) .rposition(|(x, y)| x != y) - .map(|i| word + i) + .map(|i| chunk * DIFF_CHUNK + i) } #[cfg(test)] mod difference_tests { use super::{first_difference, last_difference}; - /// The word-wise searches agree with the byte-wise ones they replace. + /// The chunk searches agree with a byte-wise scan across chunk boundaries. #[test] fn differences_are_found_as_byte_by_byte() { - let base: Vec = (0..61u32).map(|i| (i * 7 + 3) as u8).collect(); - let same = base.clone(); - assert_eq!(first_difference(&base, &same), None); - assert_eq!(last_difference(&base, &same), None); - for len in [0usize, 1, 7, 8, 9, 16, 23, 61] { + let base: Vec = (0..98u32).map(|i| (i * 7 + 3) as u8).collect(); + for len in [0, 1, 31, 32, 33, 63, 64, 65, 97] { + let a = &base[1..1 + len]; + let same = a.to_vec(); + assert_eq!(first_difference(&same, a), None); + assert_eq!(last_difference(&same, a), None); for at in 0..len { for other in at..len { - let (a, mut b) = (&base[..len], base[..len].to_vec()); + let mut b = a.to_vec(); b[at] ^= 0x80; b[other] ^= 0x01; let first = a.iter().zip(&b).position(|(x, y)| x != y); @@ -912,6 +1101,19 @@ mod difference_tests { } } } + + #[test] + fn differences_ignore_bytes_past_the_shorter_slice() { + let a = [0; 65]; + let mut b = [0; 67]; + b[65] = 1; + assert_eq!(first_difference(&a, &b), None); + assert_eq!(last_difference(&b, &a), None); + b[32] = 1; + b[64] = 1; + assert_eq!(first_difference(&b, &a), Some(32)); + assert_eq!(last_difference(&a, &b), Some(64)); + } } /// The unit shader writes are looked for and put back in. @@ -1325,6 +1527,80 @@ mod wide_tests { } } +/// What [`Shadow::copy_back`] does with a piece that differs from the +/// snapshot: `host` is the copy's bytes there, `old` the snapshot's. From +/// the first byte that differs to the last, title memory is read into +/// `title` (scratch, sized to that stretch) by `read` (the stretch's offset +/// in the piece, where to), the GPU's bytes are put in and `host` takes the +/// result. The stretch's offset in the piece and its length if that changed +/// title memory; none if nothing differs or title memory is not there. +/// `runs` takes the runs of the stretch (offsets into `title`, lengths) +/// whose bytes are the GPU's and differ from the title's as read: only +/// those are to be written, so a title write that lands between the read +/// and the write elsewhere in the stretch stays (upstream VIctory #2009). +/// `mask` is scratch. +fn back_piece( + host: &mut [u8], + old: &[u8], + title: &mut Vec, + mask: &mut Vec, + runs: &mut Vec<(usize, usize)>, + read: impl FnOnce(usize, &mut [u8]) -> bool, +) -> Option<(usize, usize)> { + runs.clear(); + // From the first byte that differs to the last: title memory is read + // and written there only (a shader that sets a few words of a piece + // cost a read, a walk and a write of all 64 KiB of it). + let first = first_difference(host, old)?; + let last = last_difference(host, old).unwrap_or(first); + let n = last + 1 - first; + let (host, old) = (&mut host[first..=last], &old[first..=last]); + title.clear(); + title.resize(n, 0); + if !read(first, title) { + return None; + } + // Title memory with the GPU's bytes put in; the copy takes the title's + // bytes in turn. + // Without a branch, so the loop runs many bytes at a time: the GPU's + // byte where the copy's byte is not what it was before the submission + // and the title left its byte as it was, else the title's. (With the + // two searches above this was 44 ms a frame for 970 pieces.) + // Where the shader and the title both changed a byte while the GPU ran, + // the title's stays: the shader computed its byte from the copy's older + // data (one cleared a bit of a record the title had already replaced, + // and copying it back broke the title's object: an access violation + // through 0xffffffff00000000; PalmVIDev e0b70476, VIctory f39c6c2). + mask.clear(); + mask.resize(n, 0); + let mut differs = 0u8; + for (((t, h), o), m) in title.iter_mut().zip(host.iter_mut()).zip(old).zip(mask.iter_mut()) { + let gpu = if (*h != *o) & (*t == *o) { 0xffu8 } else { 0 }; + let merged = (*t & !gpu) | (*h & gpu); + *m = merged ^ *t; + differs |= *m; + *t = merged; + *h = merged; + } + if differs == 0 { + return None; + } + let mut i = 0; + while i < n { + while i < n && mask[i] == 0 { + i += 1; + } + let start = i; + while i < n && mask[i] != 0 { + i += 1; + } + if i > start { + runs.push((start, i - start)); + } + } + Some((first, n)) +} + /// Since the last frame-rate line, of [`Shadow::merge_under_writes`]: pages /// compared, changed runs put in, and their bytes. static MERGED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; @@ -1363,7 +1639,93 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { #[cfg(test)] mod merge_tests { - use super::changed_runs; + use super::{PIECE, back_piece, changed_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 + /// the first change to the last, and its scratch holds that stretch and + /// no more: not the 64 KiB per range it once was. + #[test] + fn a_piece_put_back_reads_only_its_stretch() { + let old: Vec = (0..PIECE).map(|i| (i * 7 + i / 251) as u8).collect(); + // The title wrote 7 and 40,000 since the snapshot; the GPU wrote 5, + // 9 and 40,000 (the GPU's byte wins where both wrote). + let mut title_memory = old.clone(); + title_memory[7] ^= 0x11; + title_memory[40_000] ^= 0x22; + let mut host = old.clone(); + for at in [5, 9] { + host[at] ^= 0x33; + } + let gpu = host.clone(); + let mut scratch = Vec::new(); + let (mut mask, mut runs) = (Vec::new(), Vec::new()); + let mut asked = None; + let read = |first: usize, into: &mut [u8]| { + asked = Some((first, into.len())); + into.copy_from_slice(&title_memory[first..first + into.len()]); + true + }; + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((5, 5))); + assert_eq!(asked, Some((5, 5))); + let mut wanted = title_memory[5..10].to_vec(); + wanted[0] = gpu[5]; + wanted[4] = gpu[9]; + assert_eq!(scratch, wanted); + assert_eq!(host[5..10], wanted); + // Only the GPU's two bytes are written back (upstream #2009). + assert_eq!(runs, [(0, 1), (4, 1)]); + // The copy outside the stretch is left as it was. + assert!(host[..5] == gpu[..5] && host[10..] == gpu[10..]); + assert!(scratch.capacity() < PIECE / 2, "scratch of {} bytes for a stretch of 5", scratch.capacity()); + + // Nothing differs: title memory is not read. + let mut same = old.clone(); + assert_eq!(back_piece(&mut same, &old, &mut scratch, &mut mask, &mut runs, |_, _| unreachable!()), None); + // Title memory not there: nothing to write, the copy unchanged. + let mut host = gpu.clone(); + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, _| false), None); + assert!(host == gpu); + // The GPU wrote what the title holds already: nothing to write. + let mut title_memory = old.clone(); + title_memory[5] = gpu[5]; + title_memory[9] = gpu[9]; + let mut host = gpu.clone(); + let read = |first: usize, into: &mut [u8]| { + into.copy_from_slice(&title_memory[first..first + into.len()]); + true + }; + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), None); + // A whole piece changed: the scratch grows to it. + let mut host: Vec = old.iter().map(|b| !b).collect(); + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, into| into.len() == PIECE), Some((0, PIECE))); + assert_eq!(scratch.len(), PIECE); + } + + /// A byte the shader and the title both changed while the GPU ran keeps + /// the title's (the shader computed it from the copy's older data); a + /// byte only the shader changed goes back, and only such bytes are in + /// the runs to write (PalmVIDev e0b70476, upstream #2009). + #[test] + fn a_byte_both_changed_keeps_the_titles_and_only_gpu_bytes_are_written() { + let old = vec![1u8, 2, 3, 4, 5, 6]; + let mut host = old.clone(); + host[1] = 20; // the GPU alone + host[3] = 40; // both + host[4] = 50; // the GPU alone + let mut title_memory = old.clone(); + title_memory[3] = 44; + title_memory[5] = 66; // the title alone + let (mut scratch, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new()); + let read = |first: usize, into: &mut [u8]| { + into.copy_from_slice(&title_memory[first..first + into.len()]); + true + }; + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((1, 4))); + assert_eq!(scratch, [20, 3, 44, 50], "the title's byte where both changed"); + assert_eq!(host[1..5], [20, 3, 44, 50], "the copy takes the result"); + assert_eq!(runs, [(0, 1), (3, 1)], "the GPU's bytes only"); + } /// The runs hold exactly the bytes that differ: putting them into the /// old bytes gives the new ones, and no run holds an equal byte. @@ -1504,6 +1866,51 @@ mod piece_tests { } } +/// The pages of `[a, e)` (title addresses, `a < e`) that a copy whose +/// first page is `base` must take from title memory before it holds the +/// title's bytes: those it never took (`copied` 0), whether or not the +/// title wrote them since tracking began, and those `written` (as +/// `crate::watch::writes` gives it, by page in order) shows written after +/// the copy took them. As [`Shadow::copy_stale`] decides it. +/// +/// [`Shadow::stale_under_writes`] and [`Shadow::merge_under_writes`] looked +/// at `written` alone, so a page of a range shaders may be writing that the +/// copy never took, and the title had not written lately, was neither +/// merged nor a reason to settle; the refresh leaves such ranges alone, and +/// shaders read zeros there (fxceless/victory-fork#206: missing geometry +/// with `VICTORY_LATE_WAIT`/`VICTORY_RELAY`). +fn stale_pages_in(base: usize, copied: &[u64], a: usize, e: usize, written: &[(usize, u64)]) -> Vec { + (a / PAGE..e.div_ceil(PAGE)) + .filter(|&page| page >= base) + .filter(|&page| match copied.get(page - base) { + None => false, + Some(0) => true, + Some(&at) => written + .binary_search_by_key(&page, |&(p, _)| p) + .is_ok_and(|i| written[i].1 > at), + }) + .collect() +} + +#[cfg(test)] +mod stale_tests { + use super::*; + + #[test] + fn pages_never_taken_are_stale_written_or_not() { + let base = 0x100; + let copied = [5, 0, 5, 5]; + let at = |page: usize| page * PAGE; + // Page 0x101 was never taken; page 0x102 was written after it was + // taken, page 0x103 before. + let written = [(0x102, 6), (0x103, 4)]; + assert_eq!(stale_pages_in(base, &copied, at(0x100), at(0x104), &written), [0x101, 0x102]); + // Part of a page counts as the page; pages outside the copy do not. + assert_eq!(stale_pages_in(base, &copied, at(0x101) + 8, at(0x101) + 16, &[]), [0x101]); + assert!(stale_pages_in(base, &copied, at(0x104), at(0x106), &[(0x104, 9)]).is_empty()); + } +} + /// Copies of windows outside buffers let go since the start, and their /// bytes. static LET_GO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; @@ -1927,44 +2334,27 @@ impl Shadow { for &(at, n) in &differing { self.changed(at, at + n); } - let mut title = vec![0u8; PIECE]; + // Sized to each stretch read (`back_piece`): a zeroed 64 KiB per + // range, most of whose ranges differ nowhere, was most of the + // work for small ranges. + let (mut title, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new()); for (at, n) in differing { // SAFETY: inside the mapping; only the submitting thread // writes it. let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; let old = &before[at - from..at - from + n]; - // From the first byte that differs to the last: title - // memory is read and written there only (a shader that sets - // a few words of a piece cost a read, a walk and a write of - // all 64 KiB of it). - let Some(first) = first_difference(host, old) else { + let read = |first: usize, title: &mut [u8]| crate::host::read_into((start + at + first) as *const u8, title); + let Some((first, n)) = back_piece(host, old, &mut title, &mut mask, &mut runs, read) else { continue; }; - let last = last_difference(host, old).unwrap_or(first); - let (at, n) = (at + first, last + 1 - first); - let (host, old) = (&mut host[first..=last], &old[first..=last]); - let title = &mut title[..n]; - if !crate::host::read_into((start + at) as *const u8, title) { - continue; - } - // Title memory with the GPU's bytes put in; the copy takes - // the title's bytes in turn. - // Without a branch, so the loop runs many bytes at a time: - // the GPU's byte where the copy's byte is not what it was - // before the submission, else the title's. (With the two - // searches above this was 44 ms a frame for 970 pieces.) - let mut differs = 0u8; - for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) { - let gpu = if *h != *o { 0xffu8 } else { 0 }; - let merged = (*t & !gpu) | (*h & gpu); - differs |= merged ^ *t; - *t = merged; - *h = merged; - } - if differs != 0 { - crate::watch::writing(start + at, n); - crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); - written += n; + let at = at + first; + crate::watch::writing(start + at, n); + // Only the GPU's bytes (upstream #2009): the rest of the + // stretch is the title's as read, and a title write landing + // there since stays. + for &(off, len) in &runs { + crate::host::write_mapped((start + at + off) as *mut u8, title[off..].as_ptr(), len); + written += len; } } // Our write shows as a title write at the copy's next refresh, @@ -2048,10 +2438,14 @@ impl Shadow { if !crate::host::read_into((start + at) as *const u8, title) { return 0; } + // The stretch as read: what the card did not change is the + // title's, and may have been written again since. + let as_read = merge_race_on().then(|| title.clone()); if !merge_piece(now, held, title) { return 0; } crate::watch::writing(start + at, n); + merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "pc relay"); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); n } @@ -2221,9 +2615,7 @@ impl Shadow { let base = start / PAGE; let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); busy.into_iter().any(|(a, e)| match crate::watch::asked(a, e) { - Some((_, written)) => written.into_iter().any(|(page, write)| { - page >= base && copied.get(page - base).is_none_or(|&at| at == 0 || write > at) - }), + Some((_, written)) => !stale_pages_in(base, &copied, a, e, &written).is_empty(), None => true, }) } @@ -2278,11 +2670,7 @@ impl Shadow { }; let stale: Vec = { let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - written - .into_iter() - .filter(|&(page, write)| page >= base && copied.get(page - base).is_none_or(|&at| at == 0 || write > at)) - .map(|(page, _)| page) - .collect() + stale_pages_in(base, &copied, a, e, &written) }; for page in stale { let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(e)); @@ -2435,7 +2823,7 @@ impl Shadow { /// title's that arrived between the refresh and the look. fn refresh_check(&self, from: usize, to: usize) { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1") || crate::host::walls_trace()) { + if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1")) { return; } const SAMPLE: usize = 256; @@ -2662,6 +3050,9 @@ impl Shadow { title.resize(n, 0); let mut written = 0; if crate::host::read_into((start + at) as *const u8, title) { + // The stretch as read: what the card did not change is the + // title's, and may have been written again since. + let as_read = merge_race_on().then(|| title.clone()); // As in `copy_back`: the card's byte where it is not what it // was before the submission, else the title's. let mut differs = 0u8; @@ -2674,6 +3065,7 @@ impl Shadow { } if differs != 0 { crate::watch::writing(start + at, n); + merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card"); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); written = n; } @@ -2738,6 +3130,9 @@ impl Shadow { title.clear(); title.resize(n, 0); let mapped = crate::host::read_into((start + at) as *const u8, title); + // The stretch as read: what the card did not change is the + // title's, and may have been written again since. + let as_read = (mapped && merge_race_on()).then(|| title.clone()); let mut changed = false; for (a, b) in outside(at, at + n, skip) { let (a, b) = (a - at, b - at); @@ -2749,6 +3144,7 @@ impl Shadow { return 0; } crate::watch::writing(start + at, n); + merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card relay"); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); n } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 34e7d51..bdac9f7 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -56,6 +56,19 @@ pub(crate) struct Staging { uploaded: std::sync::atomic::AtomicBool, /// When a list last recorded a use of it (`crate::host::moment`). used: std::sync::atomic::AtomicU64, + /// Levels on demand (`crate::tiles`): the texture's host copy was made + /// without memory of its own when the staging buffer was made. + on_demand: bool, + /// For such a texture: the levels that were the title's at the last + /// detiling (a bit a level; the staging buffer holds zeros for the + /// others), and what that was judged by ([`Staging::judgement`]). + detiled: std::sync::atomic::AtomicU32, + judged: [std::sync::atomic::AtomicU64; 2], + /// For such a texture: when an upload last left a held level without + /// tiles (`crate::host::moment`, never 0; 0: none did). The upload is + /// recorded again about a second later if the card has room by then + /// ([`upload`]). + waiting: std::sync::atomic::AtomicU64, } /// What a texture's staging buffer holds: the hash of the memory detiled @@ -225,6 +238,7 @@ pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool { if !first && before.is_none() { return true; } + card_writes(list, placed, to, None); crate::list::ensure_state(list, placed, COPY_DEST); let part = |texture: &ID3D12Resource, index: usize| D3D12_TEXTURE_COPY_LOCATION { // SAFETY: a borrowed pointer the location never releases. @@ -576,6 +590,32 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) }; use std::sync::atomic::Ordering::Relaxed; staging.used.store(crate::host::moment(), Relaxed); + // Levels on demand: a view of the texture now starts at another + // level, or another texture now starts inside its span, with no byte + // of its memory changed. The levels are judged anew: detiled again at + // this list's submission, and uploaded by this list. + if staging.on_demand && staging.judgement() != staging.judged() { + staging.forget(); + staging.dirty.store(true, Relaxed); + } + // Levels on demand: the last upload left a held level without tiles + // (the card had no room, or no heap could be had), and nothing else + // would record an upload again until the title writes the texture: the + // level stayed empty, the texture blurred or black. Asked again about + // once a second, and only when the card has room; the staging buffer + // still holds the level's bytes. + if staging.on_demand { + let since = staging.waiting.load(Relaxed); + if since != 0 && crate::host::long_ago(since, 1000, 2) { + if crate::resource::room_lately() { + staging.waiting.store(0, Relaxed); + staging.dirty.store(true, Relaxed); + crate::tiles::STATS[10].fetch_add(1, Relaxed); + } else { + staging.waiting.store(crate::host::moment().max(1), Relaxed); + } + } + } // The host texture has the staging buffer's contents: only the check // at submission is left, and what it finds changed the next list that // samples the texture uploads (a frame late where every list of the @@ -649,11 +689,207 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) staging.dirty.store(false, Relaxed); }); } - // Once per submission however many of its lists sample the texture. - list.defer_texture(staging); + // Levels on demand (`crate::tiles`): after the check below, in the + // order of this list's steps, and before the list is executed, the + // levels the staging buffer holds as the title's are given the card's + // memory if they have none. The list copies every level, so each one + // given here is written whole by it (the rest are copies into no + // memory, which the card drops). + let on_demand = if staging.on_demand { crate::resource::host_tiled(resource) } else { None }; + let Some(on_demand) = on_demand else { + // Once per submission however many of its lists sample the texture. + list.defer_texture(staging); + return; + }; + list.defer_texture(staging.clone()); + list.defer_host(move || { + let waiting = on_demand.uploaded(staging.detiled.load(Relaxed), staging.memory as u64); + staging.waiting.store(if waiting { crate::host::moment().max(1) } else { 0 }, Relaxed); + // A texture picked by index has no staging buffer after this + // upload: its slots are made due again by the texture pass. + if waiting { + crate::descriptor::host::levels_waiting(staging.memory as u64); + } + }); +} + +/// Levels on demand: the levels a list claimed for its zeros +/// (`crate::tiles::Tiled::claim`), held by the list's submission-time +/// step. A list that is reset without having been submitted gives the +/// claim up, or the next list that writes those levels would send no zeros +/// and what its write does not cover would be what the tiles' last owner +/// left. +struct Claimed { + on_demand: crate::resource::OnDemand, + fresh: u32, + ran: std::sync::atomic::AtomicBool, +} + +impl Drop for Claimed { + fn drop(&mut self) { + if self.fresh != 0 + && !*self.ran.get_mut() + && let Some(tiled) = self.on_demand.tiled() + { + tiled.unclaim(self.fresh); + } + } +} + +/// Levels on demand (`crate::tiles`): the card itself is about to write +/// title texture `resource` in `list` (a copy or a resolve into level +/// `level`, or into every level). If its host copy `texture` was made +/// without memory, the levels written get theirs when the list is +/// submitted, ahead of it on the queue; the ones that have none yet are +/// first written with zeros, here in the same list, so that what the +/// card's write does not cover is not what the tiles' last owner left. +/// To be called before the list is brought to the state of that write. +/// shortcut: two lists that write the same new level, submitted in the +/// other order than recorded, lose the first one's write under the zeros +/// of the other; so does an upload recorded and not yet submitted. +pub(crate) fn card_writes(list: &HostList, resource: This, texture: &ID3D12Resource, level: Option) { + let Some(on_demand) = crate::resource::host_tiled(resource) else { + return; + }; + let Some(tiled) = on_demand.tiled() else { + return; + }; + let levels = match level { + Some(level) => tiled.with_level(level), + None => tiled.every_level(), + }; + if levels == 0 { + return; + } + let fresh = tiled.claim(levels); + // Of them, the ones whose zeros could not be recorded. + let mut unzeroed = if host().is_none() { fresh } else { 0 }; + if fresh != 0 + && let Some(host) = host() + { + const COPY_DEST: u32 = 0x400; + crate::list::ensure_state(list, resource, COPY_DEST); + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + for level in (0..u32::from(d.MipLevels).min(32)).filter(|&level| fresh & (1u32 << level) != 0) { + let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut bytes = 0u64; + // SAFETY: outputs for one subresource. + unsafe { + host.device + .GetCopyableFootprints(&d, level, 1, 0, Some(&mut footprint), None, None, Some(&mut bytes)); + } + let Some((buffer, data)) = list.upload(host, bytes) else { + // (With the levels that share its tiles, if it is one of + // the small ones.) + unzeroed |= tiled.with_level(level); + continue; + }; + // SAFETY: a mapped buffer of `bytes` bytes, just made. + unsafe { std::ptr::write_bytes(data, 0, bytes as usize) }; + 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: level }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above; the list holds the buffer until it is reset. + pResource: unsafe { std::mem::transmute_copy(&buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint }, + }; + // SAFETY: an open list; both locations name live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + } + // A new level without its zeros gets no tiles from this list: the + // card's write into it is lost (the level reads zeros, as before the + // write), which is less wrong than a part write over what the tiles' + // last owner left. The next list that writes it claims it again. + unzeroed &= fresh; + if unzeroed != 0 { + tiled.unclaim(unzeroed); + } + let levels = levels & !unzeroed; + if levels == 0 { + return; + } + let memory = crate::resource::texture_memory(resource).map_or(0, |(memory, _)| memory as u64); + let step = Claimed { + on_demand, + fresh: fresh & !unzeroed, + ran: std::sync::atomic::AtomicBool::new(false), + }; + list.defer_host(move || { + step.ran.store(true, std::sync::atomic::Ordering::Relaxed); + step.on_demand.card_wrote(levels, memory); + }); } impl Staging { + /// Levels on demand: what says, beside the mapping, which levels of + /// the texture are the title's now. First the lowest level a live view + /// of the texture shows (0 without a view that says): the title's own + /// word, a texture it holds from level 3 on is viewed from level 3. + /// Then where the next texture placed in this one's span starts, in + /// bytes from this one's start (`u64::MAX`: none does): for a texture + /// viewed from level 0 although a neighbour sits where its large + /// levels would be. + fn judgement(&self) -> [u64; 2] { + let start = self.memory as u64; + let first = crate::descriptor::host::first_viewed(start).map_or(0, u64::from); + let limit = crate::descriptor::host::next_start(start, start.saturating_add(self.layout.size)) + .map_or(u64::MAX, |at| at - start); + [first, limit] + } + + /// What [`Staging::judgement`] said at the last detiling. + fn judged(&self) -> [u64; 2] { + use std::sync::atomic::Ordering::Relaxed; + [self.judged[0].load(Relaxed), self.judged[1].load(Relaxed)] + } + + /// Levels on demand: the levels that are the title's now, a bit a + /// level. A level is held if no view starts above it, its bytes end + /// before the next texture starts, and all of them are mapped. The + /// smallest levels share the texture's first block and are held + /// together. (The console layout: that block first, then the other + /// levels from the smallest up, level 0 last: + /// `victory_formats::texture::Layout`.) A texture this cannot tell + /// the levels of holds them all. + fn held_levels(&self, [first, limit]: [u64; 2]) -> u32 { + let mips = &self.layout.mips; + if self.layout.slices != 1 || mips.is_empty() || mips.len() > 32 { + return u32::MAX; + } + let tail = (self.layout.first_tail_mip as usize).min(mips.len()); + let there = |from: u64, to: u64| { + to > from && to <= limit && committed(self.memory.wrapping_add(from as usize), (to - from) as usize) + }; + let mut held = 0u32; + for (level, m) in mips.iter().enumerate().take(tail) { + let end = if level == 0 { self.layout.slice_size } else { mips[level - 1].offset }; + if level as u64 >= first && there(m.offset, end) { + held |= 1 << level; + } + } + if tail < mips.len() && there(0, self.layout.alignment.min(self.layout.slice_size)) { + for level in tail..mips.len() { + if level as u64 >= first { + held |= 1 << level; + } + } + } + held + } + + /// Forgets what the staging buffer was last filled from: the next + /// refresh detiles anew, whether the memory changed or not. + fn forget(&self) { + *self.last.lock().unwrap_or_else(|e| e.into_inner()) = Last::default(); + } + /// The title memory the texture is read from: address and bytes. pub(crate) fn memory(&self) -> (usize, usize) { (self.memory as usize, self.layout.size as usize) @@ -835,6 +1071,20 @@ impl Staging { /// Detiles `tiled` (the texture's memory) into the staging buffer. fn detile(&self, tiled: &[u8]) { self.dirty.store(true, std::sync::atomic::Ordering::Relaxed); + // Levels on demand: which levels are the title's is judged here, + // once, for what the staging buffer holds from now on. The step + // that gives levels their memory goes by this answer. + let held = if self.on_demand { + use std::sync::atomic::Ordering::Relaxed; + let judged = self.judgement(); + self.judged[0].store(judged[0], Relaxed); + self.judged[1].store(judged[1], Relaxed); + let held = self.held_levels(judged); + self.detiled.store(held, Relaxed); + held + } else { + u32::MAX + }; #[cfg(feature = "diagnostics")] if tiled.iter().all(|&b| b == 0) { tracing::debug!( @@ -852,6 +1102,11 @@ impl Staging { let linear = unsafe { std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len) }; + if mip < 32 && held & (1 << mip) == 0 { + // Not the title's: zeros, not what lies in that memory. + linear.fill(0); + continue; + } if let Err(e) = self.layout .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) @@ -1095,6 +1350,9 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 { /// The staging state of a title texture, made on first use. fn staging(resource: This, texture: &ID3D12Resource) -> Option> { + // Asked before the table is locked: the sweep lets go of a staging + // buffer with its texture's host side locked, in that order. + let on_demand = crate::resource::host_tiled(resource).is_some(); let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); let map = map.get_or_insert_with(HashMap::new); if let Some(s) = map.get(&(resource as usize)) { @@ -1162,6 +1420,10 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { dirty: std::sync::atomic::AtomicBool::new(true), uploaded: std::sync::atomic::AtomicBool::new(false), used: std::sync::atomic::AtomicU64::new(crate::host::moment()), + on_demand, + detiled: std::sync::atomic::AtomicU32::new(0), + judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2], + waiting: std::sync::atomic::AtomicU64::new(0), }); map.insert(resource as usize, s.clone()); Some(s) diff --git a/crates/victory-gpu/src/tiles.rs b/crates/victory-gpu/src/tiles.rs new file mode 100644 index 0000000..a8b98f6 --- /dev/null +++ b/crates/victory-gpu/src/tiles.rs @@ -0,0 +1,1419 @@ +//! Levels on demand: host copies of title textures that take the card's +//! memory level by level, as the title holds the levels. +//! +//! The title places a texture's whole chain of levels in its address space +//! and holds only some of them: the smallest first, at the start of the +//! texture's memory. The memory of the larger ones is either not mapped, +//! or belongs to the next texture, which the title packs where they would +//! be (run 188). A host copy was a committed texture: every level of it +//! took the card's memory from the first upload on. Run 189's accounting +//! line counted 2.2 to 3.0 GB of 4.3 to 5.5 GB of host copies in levels +//! whose title memory was not mapped, on some 1,600 copies; with about +//! 2.2 to 3.1 GB of render targets that filled the card, and textures +//! that needed a new host copy waited for room (the main character's face +//! among them, runs 188 and 189). +//! +//! Here such a texture is a reserved one (`CreateReservedResource`): it has +//! every level, so level numbers and sizes are what they were, but no +//! memory. The rules: +//! - A level is given tiles of a heap of ours (`UpdateTileMappings`, on the +//! queue) only in a submission-time step of a list that also writes all +//! of that level: the upload of the texture (`texture.rs` `upload`, which +//! copies every level from the staging buffer every time), or, before +//! the card itself writes the texture (a copy, a resolve), an upload of +//! every level with every level given (`texture.rs` `make_whole`). The +//! step runs when the list is submitted, before the list is executed, so +//! the mapping is ahead of the copy on the queue. Tiles hold what their +//! last owner left; no level is shown before it is written whole. +//! - Which levels are held is said by one function, at the moment the +//! staging buffer is filled (`Staging::held_levels`): the levels whose +//! title memory is mapped and lies before the start of the next texture +//! placed in this one's span. The staging buffer holds zeros for the +//! others, and the step gives tiles by that same answer. +//! - The small levels the card packs into shared tiles are given together +//! when any of them is held; the upload writes all of them (zeros for +//! the ones not held). +//! - A shader must not reach a level without memory (it reads zeros: a +//! black texture). The host view of a slot is made from the first level +//! that is held and has tiles ([`show_from`], `descriptor/host.rs` +//! `make`), and the slots of a texture are made again when that level +//! changes (`HostHeap::texture_views_remade`). +//! - shortcut: tiles are not taken back while the host copy lives. A level +//! the title lets go of, or that turns out to be the next texture's, +//! keeps its tiles; it is hidden by the views and written with zeros at +//! the next upload. Its tiles go back when the host copy does. +//! +//! Only for a texture the title places in memory and fills, two-dimensional, +//! one layer, more than one level, of [`floor`] bytes or more, whose memory +//! is not all its own when the host copy is made (`resource.rs` `hosted`); +//! every other texture is made as before. Off unless +//! `VICTORY_LEVELS_ON_DEMAND=1`. + +use std::sync::Mutex; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::host::host; + +/// The card's tile: 64 KiB. +const TILE: u64 = 64 << 10; + +/// Tiles in one heap of the pool (64 MiB). The largest level given is a +/// 4096x4096 one of one byte a texel: 256 tiles. +const HEAP_TILES: u32 = 1024; + +/// Since the start, or now: such textures alive; the bytes all their +/// levels would take; the bytes of the tiles given to them; the bytes of +/// the pool's heaps; such textures made in all; levels given; calls of +/// `UpdateTileMappings`; their microseconds; heaps given back to the card; +/// uploads that left a held level without tiles (the card had no room, or +/// no heap could be had); uploads recorded again for such a level. +pub(crate) static STATS: [AtomicU64; 11] = [const { AtomicU64::new(0) }; 11]; + +/// Whether textures are made this way: the switch +/// (`VICTORY_LEVELS_ON_DEMAND=1`; off by default), and a card that reads +/// zeros from, and drops writes to, levels without memory (tiled resources +/// tier 2). +pub(crate) fn wanted() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var_os("VICTORY_LEVELS_ON_DEMAND").is_some_and(|v| v == "1") { + return false; + } + let Some(host) = host() else { + return false; + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + // SAFETY: a plain query into a struct of its own size. + let asked = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + }; + let tier = options.TiledResourcesTier.0; + let on = asked.is_ok() && tier >= 2; + tracing::info!( + tier, + on, + floor_kb = floor() >> 10, + "host copies of title textures take the card's memory level by level (VICTORY_LEVELS_ON_DEMAND=1)" + ); + on + }) +} + +/// The bytes from which a texture is made this way: a megabyte, or +/// `VICTORY_LEVELS_MIN_KB`. (The accounting of run 189: the levels not +/// held are 1.9 MB a copy on some 1,600 copies; a 512x512 texture has six +/// tiles at most, and most of the calls for nothing.) +pub(crate) fn floor() -> u64 { + static BYTES: std::sync::OnceLock = std::sync::OnceLock::new(); + *BYTES.get_or_init(|| { + std::env::var("VICTORY_LEVELS_MIN_KB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map_or(1 << 20, |kb| kb.max(64) << 10) + }) +} + +/// The bytes of the tiles given to textures now: the card's memory they +/// hold (`resource.rs` `room` counts it with the other host copies). +pub(crate) fn given_total() -> u64 { + STATS[2].load(Ordering::Relaxed) +} + +/// One heap of the pool and its free runs of tiles (first tile, tiles), in +/// order, no two touching. +struct Heap { + heap: ID3D12Heap, + free: Vec<(u32, u32)>, +} + +// SAFETY: a heap of the device, named only in queue and device calls, which +// any thread may make; its free runs are plain numbers behind `POOL`'s lock. +unsafe impl Send for Heap {} + +impl Heap { + fn free_tiles(&self) -> u32 { + self.free.iter().map(|run| run.1).sum() + } +} + +/// The pool's heaps by place; a place is empty after its heap went back to +/// the card (a texture names its heaps by place). +static POOL: Mutex>> = Mutex::new(Vec::new()); + +/// `count` tiles of one heap, in as many runs as it takes, the lowest free +/// tiles first (single free tiles are used up before a long run is cut): +/// the heap, its place in the pool and the runs (first tile, tiles). A new +/// heap is made when no heap has that many free. +fn take(device: &ID3D12Device, count: u32) -> Option<(ID3D12Heap, usize, Vec<(u32, u32)>)> { + if count == 0 || count > HEAP_TILES { + return None; + } + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let found = pool.iter().position(|h| h.as_ref().is_some_and(|h| h.free_tiles() >= count)); + let index = match found { + Some(index) => index, + None => { + let desc = D3D12_HEAP_DESC { + SizeInBytes: u64::from(HEAP_TILES) * TILE, + Properties: D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut made: Option = None; + // SAFETY: plain creation; the out pointer is ours. + if let Err(e) = unsafe { device.CreateHeap::(&raw const desc, &raw mut made) } { + tracing::warn!(error = %e, "no heap for texture levels given on demand: those levels stay empty"); + return None; + } + let fresh = Heap { + heap: made?, + free: vec![(0, HEAP_TILES)], + }; + STATS[3].fetch_add(u64::from(HEAP_TILES) * TILE, Ordering::Relaxed); + match pool.iter().position(Option::is_none) { + Some(index) => { + pool[index] = Some(fresh); + index + } + None => { + pool.push(Some(fresh)); + pool.len() - 1 + } + } + } + }; + let h = pool[index].as_mut()?; + let mut runs = Vec::new(); + let mut left = count; + while left > 0 { + let &(start, tiles) = h.free.first()?; + let part = tiles.min(left); + runs.push((start, part)); + if part == tiles { + h.free.remove(0); + } else { + h.free[0] = (start + part, tiles - part); + } + left -= part; + } + Some((h.heap.clone(), index, runs)) +} + +/// Gives the runs `runs` of the pool's heap at `index` back; runs that +/// touch become one. A heap with every tile free goes back to the card, +/// unless it is the pool's only one. (Called when the texture that held +/// the tiles is dropped: nothing on the card reads through its mappings +/// any more, as for any host texture that is dropped.) +fn give_back(index: usize, runs: &[(u32, u32)]) { + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let Some(Some(h)) = pool.get_mut(index) else { + return; + }; + h.free.extend_from_slice(runs); + h.free.sort_unstable(); + let mut joined: Vec<(u32, u32)> = Vec::with_capacity(h.free.len()); + for &(from, tiles) in &h.free { + match joined.last_mut() { + Some(last) if last.0 + last.1 == from => last.1 += tiles, + _ => joined.push((from, tiles)), + } + } + h.free = joined; + let all_free = h.free_tiles() == HEAP_TILES; + if all_free && pool.iter().flatten().count() > 1 { + pool[index] = None; + STATS[3].fetch_sub(u64::from(HEAP_TILES) * TILE, Ordering::Relaxed); + STATS[8].fetch_add(1, Ordering::Relaxed); + } +} + +/// What is given so far to one texture. +struct Given { + /// Per level with tiles of its own: whether it has them. + levels: Vec, + /// Whether the small levels the card packs together have theirs. + packed: bool, + /// The runs taken: the heap's place, first tile, tiles. + runs: Vec<(usize, u32, u32)>, +} + +/// A host texture made without memory, and the tiles its levels have been +/// given. +pub(crate) struct Tiled { + /// Tiles of each level that has tiles of its own (level 0 first). + standard: Vec, + /// The tiles of the levels the card packs together (0: there are none); + /// they are the levels from `standard.len()` on. + packed: u32, + /// Levels in all. + levels: u32, + /// The bytes all its tiles would take. + pub(crate) full: u64, + given: Mutex, + /// The first level a view of the texture may show: the first one that + /// is held or was written by the card and has tiles (`u32::MAX`: none + /// yet). + shown: AtomicU32, + /// The levels held at the last upload (a bit a level). + held: AtomicU32, + /// The levels the card itself wrote, in lists submitted so far. + card: AtomicU32, + /// The levels a recorded list of the card's own writes has already + /// written with zeros first ([`Tiled::claim`]). + claimed: AtomicU32, +} + +impl Tiled { + /// For `texture`, just made reserved with `levels` levels and one + /// layer: how the card cuts it into tiles. `None` if the card will not + /// say, or cuts it in a way this does not handle; the caller then makes + /// the texture the old way. + pub(crate) fn make(device: &ID3D12Device, texture: &ID3D12Resource, levels: u32) -> Option { + if levels == 0 || levels > 16 { + return None; + } + let mut total = 0u32; + let mut packed = D3D12_PACKED_MIP_INFO::default(); + let mut shape = D3D12_TILE_SHAPE::default(); + let mut count = levels; + let mut tilings = vec![D3D12_SUBRESOURCE_TILING::default(); levels as usize]; + // SAFETY: outputs of our own, `count` tilings of them. + unsafe { + device.GetResourceTiling( + texture, + Some(&raw mut total), + Some(&raw mut packed), + Some(&raw mut shape), + Some(&raw mut count), + 0, + tilings.as_mut_ptr(), + ); + } + let standard_levels = u32::from(packed.NumStandardMips); + if total == 0 || standard_levels + u32::from(packed.NumPackedMips) != levels || standard_levels > count { + return None; + } + let mut standard = Vec::with_capacity(standard_levels as usize); + for tiling in &tilings[..standard_levels as usize] { + let tiles = tiling.WidthInTiles * u32::from(tiling.HeightInTiles) * u32::from(tiling.DepthInTiles); + if tiles == 0 || tiles > HEAP_TILES || tiling.StartTileIndexInOverallResource == D3D12_PACKED_TILE { + return None; + } + standard.push(tiles); + } + let packed_tiles = if packed.NumPackedMips > 0 { packed.NumTilesForPackedMips } else { 0 }; + if packed_tiles > HEAP_TILES { + return None; + } + let full = u64::from(total) * TILE; + STATS[0].fetch_add(1, Ordering::Relaxed); + STATS[1].fetch_add(full, Ordering::Relaxed); + STATS[4].fetch_add(1, Ordering::Relaxed); + Some(Tiled { + given: Mutex::new(Given { + levels: vec![false; standard.len()], + packed: false, + runs: Vec::new(), + }), + standard, + packed: packed_tiles, + levels, + full, + shown: AtomicU32::new(u32::MAX), + held: AtomicU32::new(0), + card: AtomicU32::new(0), + claimed: AtomicU32::new(0), + }) + } + + /// At the submission of a list that uploads every level of `texture` + /// from its staging buffer, of which `held` are the title's now (the + /// others are zeros there): tiles for the held ones that have none. + /// `room`: whether the card has room for more host copies + /// (`resource.rs` `room`). Without room no held level gets tiles: the + /// list still brings the levels that have theirs up to date (which + /// takes none of the card's memory), and its copies into the others go + /// nowhere. (An upload of a host copy that exists passes the full + /// card's gate in `draw.rs` on the ground that it takes no memory; + /// with tiles given here regardless, the line would not bound these + /// textures.) + /// Returns whether the first level a view may show changed, and + /// whether a level named is still without tiles (no room, or no heap + /// could be had): the caller has the upload recorded again later, or + /// the level would stay empty until the title writes the texture. + pub(crate) fn uploaded(&self, texture: &ID3D12Resource, held: u32, room: bool) -> (bool, bool) { + match host() { + Some(host) => self.uploaded_on(host.queue(), &host.device, texture, held, room), + None => (false, false), + } + } + + /// [`Tiled::uploaded`] on a queue and a device. + pub(crate) fn uploaded_on( + &self, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + held: u32, + room: bool, + ) -> (bool, bool) { + self.held.store(held, Ordering::Relaxed); + let card = self.card.load(Ordering::Relaxed); + let named = held | card; + // The levels the card itself writes are few and are not kept + // waiting: a write of the card's into no memory is lost. + let changed = self.give_on(queue, device, texture, named, if room { named } else { card }); + (changed, self.without(named) != 0) + } + + /// At the submission of a list in which the card itself writes the + /// levels `levels` of `texture` (after zeros, if they were new: + /// [`Tiled::claim`]): tiles for those that have none. Returns whether + /// the first level a view may show changed. + /// Only the levels this list writes get tiles here: a held level that + /// is waiting for room is written by no copy of this list, and tiles + /// hold what their last owner left. + pub(crate) fn card_wrote(&self, texture: &ID3D12Resource, levels: u32) -> bool { + match host() { + Some(host) => self.card_wrote_on(host.queue(), &host.device, texture, levels), + None => false, + } + } + + /// [`Tiled::card_wrote`] on a queue and a device. + pub(crate) fn card_wrote_on( + &self, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + levels: u32, + ) -> bool { + let card = self.card.fetch_or(levels, Ordering::Relaxed) | levels; + let changed = self.give_on(queue, device, texture, card | self.held.load(Ordering::Relaxed), levels); + // A level that got no tiles (no heap could be had): the list's + // zeros and its write went nowhere, so the next list that writes + // the level sends its zeros again. + let without = self.without(levels); + if without != 0 { + self.unclaim(without); + } + changed + } + + /// The bits of the levels that get their tiles with level `level`: + /// itself, or every level the card packs together if it is one of them. + pub(crate) fn with_level(&self, level: u32) -> u32 { + let first_packed = self.standard.len() as u32; + if level < first_packed { + 1 << level + } else if level < self.levels { + self.every_level() & !((1u32 << first_packed) - 1) + } else { + 0 + } + } + + /// Of `levels`, the ones that have no tiles now and that no list + /// recorded before has claimed: the caller's list writes them with + /// zeros before the card's own write, so that what the write does not + /// cover is not what the tiles' last owner left. + pub(crate) fn claim(&self, levels: u32) -> u32 { + let fresh = self.without(levels); + fresh & !self.claimed.fetch_or(fresh, Ordering::Relaxed) + } + + /// Gives up the claim on `levels` ([`Tiled::claim`]): the zeros of the + /// list that claimed them never reached tiles of theirs (the list was + /// reset without being submitted, the zeros could not be recorded, or + /// no tiles could be had), so the next list that writes them sends its + /// own. + /// shortcut: a second list recorded between the claim and this sends + /// no zeros; if it is the first whose write gets tiles, what that + /// write does not cover is what the tiles' last owner left. + pub(crate) fn unclaim(&self, levels: u32) { + self.claimed.fetch_and(!levels, Ordering::Relaxed); + } + + /// Of `levels` (a bit a level), the ones that have no tiles now. + pub(crate) fn without(&self, levels: u32) -> u32 { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + let first_packed = self.standard.len() as u32; + let mut without = 0; + for level in 0..self.levels.min(32) { + let has = if level < first_packed { given.levels[level as usize] } else { given.packed }; + if !has { + without |= 1 << level; + } + } + levels & without + } + + /// Gives tiles to the levels of `texture` that both `named` and `may` + /// name (a bit a level, level 0 the lowest) and that have none yet; + /// the levels the card packs together get theirs when any of them is + /// so named. `named`: the levels that are the title's or the card's + /// own, by which the first level a view may show is told; `may`: the + /// ones of them that may get tiles in this call. To be called only + /// from a submission-time step of a list that writes every level of + /// `may`, whole: the call is ahead of that list on `queue`, and tiles + /// hold what their last owner left. + /// Returns whether the first level a view may show changed + /// ([`Tiled::first_shown`]): the caller has the texture's slots made + /// again. + pub(crate) fn give_on( + &self, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + named: u32, + may: u32, + ) -> bool { + let has = |level: u32| level < 32 && named & (1 << level) != 0; + let now = |level: u32| level < 32 && named & may & (1 << level) != 0; + let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + let first_packed = self.standard.len() as u32; + // (subresource, tiles, the level if it has tiles of its own) to map now. + let mut wanted: Vec<(u32, u32, Option)> = Vec::new(); + for level in 0..first_packed { + if !given.levels[level as usize] && now(level) { + wanted.push((level, self.standard[level as usize], Some(level as usize))); + } + } + if self.packed > 0 && !given.packed && (first_packed..self.levels).any(now) { + wanted.push((first_packed, self.packed, None)); + } + for (subresource, tiles, level) in wanted { + let Some((heap, index, runs)) = take(device, tiles) else { + continue; + }; + let at = D3D12_TILED_RESOURCE_COORDINATE { + X: 0, + Y: 0, + Z: 0, + Subresource: subresource, + }; + let size = D3D12_TILE_REGION_SIZE { + NumTiles: tiles, + ..Default::default() + }; + // One region, the subresource's tiles in order, on as many + // ranges of the heap as the runs taken. + let flags = vec![D3D12_TILE_RANGE_FLAG_NONE; runs.len()]; + let starts: Vec = runs.iter().map(|run| run.0).collect(); + let counts: Vec = runs.iter().map(|run| run.1).collect(); + let began = std::time::Instant::now(); + // SAFETY: a live reserved texture and a live heap of ours; one + // region of `tiles` tiles from the subresource's first tile; + // `runs.len()` ranges whose counts add up to `tiles`, in three + // arrays of that length that live through the call. + unsafe { + queue.UpdateTileMappings( + texture, + 1, + Some(&raw const at), + Some(&raw const size), + &heap, + runs.len() as u32, + Some(flags.as_ptr()), + Some(starts.as_ptr()), + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + } + STATS[6].fetch_add(1, Ordering::Relaxed); + STATS[7].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); + match level { + Some(level) => given.levels[level] = true, + None => given.packed = true, + } + for &(start, count) in &runs { + given.runs.push((index, start, count)); + } + STATS[2].fetch_add(u64::from(tiles) * TILE, Ordering::Relaxed); + STATS[5].fetch_add(1, Ordering::Relaxed); + } + let with_tiles = |level: u32| { + if level < first_packed { + given.levels[level as usize] + } else { + given.packed + } + }; + let shown = (0..self.levels).find(|&level| has(level) && with_tiles(level)).unwrap_or(u32::MAX); + self.shown.swap(shown, Ordering::Relaxed) != shown + } + + /// The first level a view of the texture may show; `None` while no + /// level is both held and given (the views are then as the title made + /// them, and read zeros). + pub(crate) fn first_shown(&self) -> Option { + let shown = self.shown.load(Ordering::Relaxed); + (shown != u32::MAX).then_some(shown) + } + + /// Whether level `level` has tiles. + #[cfg(test)] + fn has_tiles(&self, level: u32) -> bool { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + match given.levels.get(level as usize) { + Some(&has) => has, + None => level < self.levels && given.packed, + } + } + + /// Whether every level has tiles. + #[cfg(test)] + fn whole(&self) -> bool { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + given.levels.iter().all(|&has| has) && (self.packed == 0 || given.packed) + } + + /// A bit for every level of the texture. + pub(crate) fn every_level(&self) -> u32 { + if self.levels >= 32 { u32::MAX } else { (1 << self.levels) - 1 } + } + + /// The bytes of the tiles it has now. + pub(crate) fn given_bytes(&self) -> u64 { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + given.runs.iter().map(|run| u64::from(run.2) * TILE).sum() + } +} + +impl Drop for Tiled { + fn drop(&mut self) { + let given = self.given.get_mut().unwrap_or_else(|e| e.into_inner()); + let mut bytes = 0; + let mut by_heap: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for &(index, start, tiles) in &given.runs { + by_heap.entry(index).or_default().push((start, tiles)); + bytes += u64::from(tiles) * TILE; + } + for (index, runs) in by_heap { + give_back(index, &runs); + } + STATS[0].fetch_sub(1, Ordering::Relaxed); + STATS[1].fetch_sub(self.full, Ordering::Relaxed); + STATS[2].fetch_sub(bytes, Ordering::Relaxed); + } +} + +/// Keeps a two-dimensional shader view from the levels before `first` of a +/// texture of `levels` levels: it starts at `first` if it started before +/// it, and shows as many levels fewer. A sample then lands on the first +/// level that has memory instead of reading zeros from one that has none; +/// level numbers and sizes a shader asks for count from that level. +pub(crate) fn show_from(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, first: u32, levels: u32) { + if desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D || first >= levels { + return; + } + // SAFETY: a 2D view's member of the union. + let view = unsafe { &mut desc.Anonymous.Texture2D }; + if first <= view.MostDetailedMip { + return; + } + let fewer = first - view.MostDetailedMip; + view.MostDetailedMip = first; + if view.MipLevels != u32::MAX { + view.MipLevels = view.MipLevels.saturating_sub(fewer).max(1); + } +} + +/// For the log, with the texture queue's line: what this saves, and what +/// the mapping calls cost since the line before. +pub(crate) fn status() { + static BEFORE: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + let s: Vec = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); + if s[4] == 0 { + return; + } + let calls = s[6] - BEFORE[0].swap(s[6], Ordering::Relaxed); + let micros = s[7] - BEFORE[1].swap(s[7], Ordering::Relaxed); + tracing::info!( + "textures with levels on demand: {} alive ({} made so far), {} MB of the card given to {} levels in all, \ + {} MB of the card not allocated for levels the title does not hold ({} MB if every level had memory); \ + the pool's heaps {} MB ({} given back to the card so far); since the line before: {} calls of \ + UpdateTileMappings in {} microseconds; in all {} calls, {} microseconds; {} uploads left a held \ + level without memory (no room on the card, or no heap), {} uploads were recorded again for one", + s[0], + s[4], + s[2] >> 20, + s[5], + s[1].saturating_sub(s[2]) >> 20, + s[1] >> 20, + s[3] >> 20, + s[8], + calls, + micros, + s[6], + s[7], + s[9], + s[10], + ); +} + +/// On the card, without the title: what levels on demand relies on, with +/// the pool and the mapping call of this module on a device of the test's +/// own. One test, one device: the pool is one for the process, and its +/// heaps belong to the device that made them. +/// +/// Run by name, alone, no game needed: +/// `cargo test -p victory-gpu --release -- --ignored levels_on_demand --nocapture` +/// +/// It runs on the SOFTWARE adapter unless `VICTORY_TILES_TEST_CARD=1`: on +/// that adapter nothing reaches the card or its driver, so nothing it does +/// can reset the driver or touch the screen. Wherever it runs, the debug +/// layer is switched on if Windows has it (the optional feature "Graphics +/// Tools"), its messages are printed after every step, and the test stops +/// at the first error or lost device with the step's name, before +/// anything else is sent. On the card it does not run without the layer, +/// and no wait is longer than 1.5 s. +#[cfg(test)] +mod tests { + use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + use windows::core::{Interface, s}; + + use super::*; + use crate::host::{compile, transition, warp_adapter}; + + const SIDE: u32 = 1024; + const LEVELS: u16 = 11; + + /// Two views of one texture read at the same place and level: the + /// first as the layer makes it for a texture whose level 0 has no + /// memory, the second as the title asked. + const LOOK: &str = r#" +#define RS "DescriptorTable(SRV(t0, numDescriptors = 2)), UAV(u0), StaticSampler(s0, filter = FILTER_MIN_MAG_MIP_POINT)" +Texture2D clamped : register(t0); +Texture2D whole : register(t1); +SamplerState nearest : register(s0); +RWByteAddressBuffer words : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void look() { + float4 a = clamped.SampleLevel(nearest, float2(0.3, 0.3), 0); + float4 b = whole.SampleLevel(nearest, float2(0.3, 0.3), 0); + words.Store(0, (uint)(a.x * 255.0 + 0.5)); + words.Store(4, (uint)(b.x * 255.0 + 0.5)); +} +"#; + + /// Where each level of a texture lies in a buffer of all of them: its + /// place, its rows, the bytes of a row that are the level's own, and + /// the buffer's bytes. + struct Laid { + footprints: Vec, + rows: Vec, + wide: Vec, + total: u64, + } + + struct Rig { + device: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + event: HANDLE, + submitted: u64, + /// The debug layer's messages, if Windows has the layer. + messages: Option, + /// What the test is doing, for the message when it stops. + step: &'static str, + /// On the card, not on the software adapter. + card: bool, + } + + impl Rig { + /// The software adapter, or the default one with + /// `VICTORY_TILES_TEST_CARD=1`; `None` without one, without tiled + /// resources of tier 2, or on the card without the debug layer. + fn new() -> Option { + // SAFETY: plain object creation on a device of our own. + unsafe { + let card = std::env::var_os("VICTORY_TILES_TEST_CARD").is_some_and(|v| v == "1"); + // The debug layer, before the device is made: a call that + // is not well formed is then refused and named by the + // runtime, not handed to the driver. + let mut layer: Option = None; + let layered = D3D12GetDebugInterface(&mut layer).is_ok() && layer.is_some(); + layer.iter().for_each(|l| l.EnableDebugLayer()); + if card && !layered { + eprintln!("no D3D12 debug layer (Windows optional feature \"Graphics Tools\"): not run on the card without it"); + return None; + } + let mut device: Option = None; + if card { + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + } else { + let adapter = warp_adapter().ok()?; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + } + let device = device?; + let messages = device.cast::().ok(); + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .ok()?; + eprintln!( + "levels on demand, {}: tiled resources tier {}, debug layer {}", + if card { "ON THE CARD" } else { "on the software adapter" }, + options.TiledResourcesTier.0, + if messages.is_some() { "on" } else { "not installed" } + ); + if options.TiledResourcesTier.0 < 2 { + return None; + } + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let allocator: ID3D12CommandAllocator = + device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + Some(Rig { + device, + queue, + allocator, + list, + fence, + event, + submitted: 0, + messages, + step: "making the device", + card, + }) + } + } + + /// Prints what the debug layer said since the last call; the first + /// error among it (as `host.rs` `log_messages` reads them). + fn said(&self) -> Option { + let queue = self.messages.as_ref()?; + let mut first_error = None; + // SAFETY: each message is read into a buffer of the size the + // queue reports, then the queue is emptied. + unsafe { + for i in 0..queue.GetNumStoredMessages() { + let mut size = 0; + if queue.GetMessage(i, None, &mut size).is_err() || size == 0 { + continue; + } + let mut buffer = vec![0u64; size.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::(); + if queue.GetMessage(i, Some(message), &mut size).is_ok() { + let m = &*message; + let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); + let text = String::from_utf8_lossy(text); + let text = text.trim_end_matches('\0'); + eprintln!("D3D12 says (severity {}, id {}): {text}", m.Severity.0, m.ID.0); + if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() { + first_error = Some(text.to_owned()); + } + } + } + queue.ClearStoredMessages(); + } + first_error + } + + /// Stops the test, naming the step, if the device is lost or the + /// debug layer reported an error: nothing more is sent after it. + fn check(&self, what: &str) { + let error = self.said(); + // SAFETY: a plain query. + let removed = unsafe { self.device.GetDeviceRemovedReason() }; + assert!(removed.is_ok(), "{}, {what}: the device is lost: {removed:?}", self.step); + assert!(error.is_none(), "{}, {what}: the debug layer reports an error: {}", self.step, error.unwrap_or_default()); + } + + /// Gives tiles as a submission would, and stops if the mapping + /// call was refused. + fn give(&self, tiled: &Tiled, texture: &ID3D12Resource, levels: u32) { + tiled.give_on(&self.queue, &self.device, texture, levels, levels); + self.check("tiles given"); + } + + /// Records with `record`, runs the list behind what is already on + /// the queue (tile mappings among it), waits for the card and + /// opens the list again. + fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) { + record(&self.list); + self.submitted += 1; + // SAFETY: our list, queue and fence; the allocator is reset + // only after the card finished everything recorded from it. + unsafe { + self.list.Close().unwrap(); + let run: ID3D12CommandList = self.list.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + self.queue.Signal(&self.fence, self.submitted).unwrap(); + self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap(); + // Never without end: a step is a few copies of a few + // megabytes. On the card the limit stays under Windows' own + // two seconds; the software adapter, which compiles its + // shader on first use and resets nothing, gets longer. + let limit = if self.card { 1500 } else { 20_000 }; + let waited = WaitForSingleObject(self.event, limit); + self.check("a submission"); + assert!( + waited == WAIT_OBJECT_0, + "{}: a submission did not finish within {limit} ms; stopped before another is sent", + self.step + ); + self.allocator.Reset().unwrap(); + self.list.Reset(&self.allocator, None).unwrap(); + } + } + + fn buffer(&self, kind: D3D12_HEAP_TYPE, flags: D3D12_RESOURCE_FLAGS, state: D3D12_RESOURCE_STATES, bytes: u64) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..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, + Flags: flags, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: plain buffer creation. + unsafe { + self.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + /// A square texture description of `side` texels and `levels` + /// levels; `reserved`: in the layout a texture without memory of + /// its own must have. + fn desc(format: DXGI_FORMAT, side: u32, levels: u16, reserved: bool) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(side), + Height: side, + DepthOrArraySize: 1, + MipLevels: levels, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: if reserved { D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE } else { D3D12_TEXTURE_LAYOUT_UNKNOWN }, + ..Default::default() + } + } + + /// A texture without memory, in the state copies into it need, and + /// how the card cuts it. + fn reserved(&self, desc: &D3D12_RESOURCE_DESC) -> (ID3D12Resource, Tiled) { + let mut made: Option = None; + // SAFETY: plain creation; a texture that is no target has no clear value. + let asked = unsafe { + self.device + .CreateReservedResource(desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made) + }; + // The layer's reason first, if it refused. + self.check("a texture without memory made"); + asked.expect("a reserved texture"); + let texture = made.expect("a reserved texture"); + let tiled = Tiled::make(&self.device, &texture, u32::from(desc.MipLevels)).expect("the card says how it cuts the texture"); + (texture, tiled) + } + + fn footprints(&self, desc: &D3D12_RESOURCE_DESC) -> Laid { + let levels = usize::from(desc.MipLevels); + let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); levels]; + let mut rows = vec![0u32; levels]; + let mut wide = vec![0u64; levels]; + let mut total = 0u64; + // SAFETY: outputs for `levels` subresources. + unsafe { + self.device.GetCopyableFootprints( + desc, + 0, + levels as u32, + 0, + Some(footprints.as_mut_ptr()), + Some(rows.as_mut_ptr()), + Some(wide.as_mut_ptr()), + Some(&mut total), + ); + } + Laid { + footprints, + rows, + wide, + total, + } + } + + /// An upload buffer of `total` bytes in which the bytes of each + /// level are `byte(level)`. + fn filled(&self, layout: &Laid, byte: impl Fn(usize) -> u8) -> ID3D12Resource { + let (footprints, rows) = (&layout.footprints, &layout.rows); + let upload = self.buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ, layout.total); + // SAFETY: the buffer is `total` bytes; each level's rows lie inside it. + unsafe { + let mut data = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut data)).unwrap(); + for (level, f) in footprints.iter().enumerate() { + let len = rows[level] as usize * f.Footprint.RowPitch as usize; + std::slice::from_raw_parts_mut(data.cast::().add(f.Offset as usize), len).fill(byte(level)); + } + upload.Unmap(0, None); + } + upload + } + + /// Copies every level of `texture` from `upload`, then every level + /// back, and gives for each level the first sixteen bytes read of + /// its first row and of the row and column half way (another tile + /// of a level of several). + fn round_trip( + &mut self, + texture: &ID3D12Resource, + layout: &Laid, + upload: Option<&ID3D12Resource>, + ) -> Vec<[Vec; 2]> { + let (footprints, rows) = (&layout.footprints, &layout.rows); + let back = self.buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST, layout.total); + self.run(|list| { + // SAFETY: an open list; the texture and buffers outlive the run. + unsafe { + if let Some(upload) = upload { + for (level, f) in footprints.iter().enumerate() { + list.CopyTextureRegion(&sub(texture, level as u32), 0, 0, 0, &placed(upload, *f), None); + } + } + list.ResourceBarrier(&[transition(texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + for (level, f) in footprints.iter().enumerate() { + list.CopyTextureRegion(&placed(&back, *f), 0, 0, 0, &sub(texture, level as u32), None); + } + list.ResourceBarrier(&[transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST)]); + } + }); + let mut read = Vec::new(); + // SAFETY: a read-back buffer of `total` bytes the finished list copied into. + unsafe { + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data)).unwrap(); + for (level, f) in footprints.iter().enumerate() { + let pitch = f.Footprint.RowPitch as usize; + let len = rows[level] as usize * pitch; + let bytes = std::slice::from_raw_parts(data.cast::().cast_const().add(f.Offset as usize), len); + // The bytes of a row that are the level's own (its + // blocks or texels; the rest of the pitch is padding). + let own = layout.wide[level] as usize; + let wide = own.min(len).min(16); + let first = bytes[..wide].to_vec(); + let middle = (rows[level] as usize / 2) * pitch + ((own / 2) & !15); + let far = if rows[level] >= 2 && own >= 32 && middle + wide <= len { + bytes[middle..middle + wide].to_vec() + } else { + first.clone() + }; + read.push([first, far]); + } + back.Unmap(0, None); + } + read + } + } + + fn sub(texture: &ID3D12Resource, index: u32) -> D3D12_TEXTURE_COPY_LOCATION { + 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: index }, + } + } + + fn placed(buffer: &ID3D12Resource, footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT) -> D3D12_TEXTURE_COPY_LOCATION { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint }, + } + } + + fn all(bytes: &[Vec; 2], want: u8) -> bool { + bytes.iter().all(|part| part.iter().all(|&b| b == want)) + } + + /// The levels from `first` on, a bit a level. + fn from_level(first: u32) -> u32 { + (u32::MAX << first) & ((1 << u32::from(LEVELS)) - 1) + } + + /// (i) Levels arrive one by one: after each step every level with + /// tiles reads back its own bytes and every level without reads zeros. + fn levels_arrive(rig: &mut Rig, format: DXGI_FORMAT) { + rig.step = if format == DXGI_FORMAT_BC7_UNORM { "step 1, levels arrive (BC7)" } else { "step 1, levels arrive (BC3)" }; + let desc = Rig::desc(format, SIDE, LEVELS, true); + let (texture, tiled) = rig.reserved(&desc); + // (The card packs the levels smaller than a tile into shared + // tiles; the software adapter may give each its own.) + eprintln!( + "format {}: {} levels with tiles of their own ({:?} tiles), {} tiles for the packed ones", + format.0, + tiled.standard.len(), + tiled.standard, + tiled.packed + ); + assert!(!rig.card || tiled.packed > 0, "on the card a 1024 texture has levels smaller than a tile"); + let layout = rig.footprints(&desc); + let upload = rig.filled(&layout, |level| level as u8 + 1); + for first in [3u32, 1, 0] { + // Ahead of the list on the queue, as at a submission. + rig.give(&tiled, &texture, from_level(first)); + let read = rig.round_trip(&texture, &layout, Some(&upload)); + for (level, bytes) in read.iter().enumerate() { + let want = if tiled.has_tiles(level as u32) { level as u8 + 1 } else { 0 }; + assert!(all(bytes, want), "format {} from level {first}: level {level} reads {bytes:?}, wanted {want}", format.0); + } + } + assert!(tiled.whole()); + assert_eq!(tiled.first_shown(), Some(0)); + } + + /// (ii) A copy on the card into a level without tiles is dropped; the + /// same copy in a list that runs after the level was given lands. + fn a_card_copy_lands_after_the_give(rig: &mut Rig) { + rig.step = "step 2, a copy on the card into a level without tiles"; + let format = DXGI_FORMAT_BC7_UNORM; + let desc = Rig::desc(format, SIDE, LEVELS, true); + let (texture, tiled) = rig.reserved(&desc); + let layout = rig.footprints(&desc); + // The last level with tiles of its own, and a texture of its size + // with every byte 0x5a to copy from. + let level = tiled.standard.len() as u32 - 1; + let source_desc = Rig::desc(format, SIDE >> level, 1, false); + let source_layout = rig.footprints(&source_desc); + let source_bytes = rig.filled(&source_layout, |_| 0x5a); + let mut made: Option = None; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + // SAFETY: plain texture creation. + unsafe { + rig.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &source_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made) + .unwrap(); + } + let source = made.unwrap(); + rig.run(|list| { + // SAFETY: an open list and live resources. + unsafe { + list.CopyTextureRegion(&sub(&source, 0), 0, 0, 0, &placed(&source_bytes, source_layout.footprints[0]), None); + list.ResourceBarrier(&[transition(&source, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + // No tiles yet: this copy goes nowhere. + list.CopyTextureRegion(&sub(&texture, level), 0, 0, 0, &sub(&source, 0), None); + } + }); + let before = rig.round_trip(&texture, &layout, None); + assert!(all(&before[level as usize], 0), "a copy into a level without tiles left {:?}", before[level as usize]); + // As `texture.rs` `card_writes` has it: the give at the list's + // submission, the copy in the list. + assert_ne!(tiled.claim(tiled.with_level(level)), 0, "the level is new"); + rig.give(&tiled, &texture, tiled.with_level(level)); + rig.run(|list| { + // SAFETY: as above. + unsafe { list.CopyTextureRegion(&sub(&texture, level), 0, 0, 0, &sub(&source, 0), None) }; + }); + let after = rig.round_trip(&texture, &layout, None); + assert!(all(&after[level as usize], 0x5a), "the copy after the give left {:?}", after[level as usize]); + assert_eq!(tiled.claim(tiled.with_level(level)), 0, "claimed once"); + } + + /// (iii) Tiles a texture gave back go to the next one, which reads + /// what was written into it and zeros where it has no tiles; what a + /// level given and not written reads is printed (the reason no level + /// is given outside a list that writes it). + fn a_reused_tile_reads_as_written(rig: &mut Rig) { + rig.step = "step 3, a reused tile"; + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let layout = rig.footprints(&desc); + let (first, first_tiles) = rig.reserved(&desc); + let level = first_tiles.standard.len() as u32 - 1; + rig.give(&first_tiles, &first, 1 << level); + let upload = rig.filled(&layout, |_| 0xa5); + let read = rig.round_trip(&first, &layout, Some(&upload)); + assert!(all(&read[level as usize], 0xa5)); + let runs = first_tiles.given.lock().unwrap().runs.clone(); + drop(first_tiles); + drop(first); + let (second, second_tiles) = rig.reserved(&desc); + rig.give(&second_tiles, &second, 1 << level); + let reused = second_tiles.given.lock().unwrap().runs == runs; + let unwritten = rig.round_trip(&second, &layout, None); + eprintln!( + "a level given tiles and not written reads {:?} (its tiles are the first texture's: {reused})", + &unwritten[level as usize][0][..4] + ); + let upload = rig.filled(&layout, |_| 0x3c); + let read = rig.round_trip(&second, &layout, Some(&upload)); + assert!(all(&read[level as usize], 0x3c), "the reused level reads {:?}", read[level as usize]); + assert!(all(&read[0], 0), "level 0 has no tiles and reads {:?}", read[0]); + } + + /// (iv) A level whose tiles come from several runs of the heap (single + /// free tiles between taken ones) reads as written in every tile. + fn a_level_on_several_ranges(rig: &mut Rig) { + rig.step = "step 4, a level on several ranges of the heap"; + // Three single tiles; the first and the last go back, the middle + // one stays taken. + let singles: Vec<_> = (0..3).map(|_| take(&rig.device, 1).expect("a tile")).collect(); + give_back(singles[0].1, &singles[0].2); + give_back(singles[2].1, &singles[2].2); + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let layout = rig.footprints(&desc); + let (texture, tiled) = rig.reserved(&desc); + // Level 1 of a 1024 texture: four tiles. + assert!(tiled.standard.len() > 1 && tiled.standard[1] >= 2); + rig.give(&tiled, &texture, 1 << 1); + let runs = tiled.given.lock().unwrap().runs.len(); + eprintln!("level 1 ({} tiles) was mapped on {runs} ranges", tiled.standard[1]); + assert!(runs >= 2, "the single free tiles were not used first"); + let upload = rig.filled(&layout, |_| 0x77); + let read = rig.round_trip(&texture, &layout, Some(&upload)); + assert!(all(&read[1], 0x77), "level 1 reads {:?}", read[1]); + give_back(singles[1].1, &singles[1].2); + } + + /// (v) A view made by [`show_from`] of a texture whose level 0 has no + /// tiles returns level 1's colour for a sample at level 0; the view as + /// the title asked returns zero. + fn the_view_starts_at_the_first_level_with_tiles(rig: &mut Rig) -> Option<()> { + rig.step = "step 5, the view from the first level with tiles"; + let cs = compile(LOOK, s!("look"), s!("cs_5_1")).ok()?; + let format = DXGI_FORMAT_R8G8B8A8_UNORM; + let desc = Rig::desc(format, SIDE, LEVELS, true); + let layout = rig.footprints(&desc); + let (texture, tiled) = rig.reserved(&desc); + // Every level but the largest; each level's bytes are sixteen + // times its number plus one. + rig.give(&tiled, &texture, from_level(1)); + assert_eq!(tiled.first_shown(), Some(1)); + let upload = rig.filled(&layout, |level| (level as u8 + 1) * 16); + rig.round_trip(&texture, &layout, Some(&upload)); + // SAFETY: plain object creation; the views are made in a heap + // that lives to the end of the function, of a live texture. + let (root, pipeline, views, words, back) = unsafe { + let root: ID3D12RootSignature = rig.device.CreateRootSignature(0, &cs[..]).ok()?; + let pipeline: ID3D12PipelineState = rig + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }) + .ok()?; + let views: ID3D12DescriptorHeap = rig + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .ok()?; + let as_asked = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: u32::MAX, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + }; + let mut shown = as_asked; + show_from(&mut shown, tiled.first_shown()?, u32::from(LEVELS)); + assert_eq!(shown.Anonymous.Texture2D.MostDetailedMip, 1); + let step = rig.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let mut at = views.GetCPUDescriptorHandleForHeapStart(); + rig.device.CreateShaderResourceView(&texture, Some(&raw const shown), at); + at.ptr += step; + rig.device.CreateShaderResourceView(&texture, Some(&raw const as_asked), at); + let words = rig.buffer( + D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + 256, + ); + let back = rig.buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST, 256); + (root, pipeline, views, words, back) + }; + // Before the one dispatch: the pipeline and both views are sound. + rig.check("the pipeline and the views made"); + rig.run(|list| { + // SAFETY: an open list and live objects. + unsafe { + list.ResourceBarrier(&[transition(&texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]); + list.SetDescriptorHeaps(&[Some(views.clone())]); + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pipeline); + list.SetComputeRootDescriptorTable(0, views.GetGPUDescriptorHandleForHeapStart()); + list.SetComputeRootUnorderedAccessView(1, words.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[transition(&words, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&back, 0, &words, 0, 16); + } + }); + // SAFETY: a read-back buffer the finished list copied sixteen bytes into. + let read = unsafe { + let mut data = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: 0, End: 16 }; + back.Map(0, Some(&range), Some(&mut data)).unwrap(); + let read = std::slice::from_raw_parts(data.cast::(), 2).to_vec(); + back.Unmap(0, None); + read + }; + eprintln!("a sample at level 0: {} through the view from level 1, {} through the view as asked", read[0], read[1]); + assert_eq!(read[0], 32, "the view from the first level with tiles reads level 1"); + assert_eq!(read[1], 0, "the view from level 0 reads a level without tiles"); + Some(()) + } + + fn a_full_card_keeps_new_levels_waiting(rig: &mut Rig) { + rig.step = "step 6, no room on the card: held levels wait, and get their tiles when asked again"; + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let (texture, tiled) = rig.reserved(&desc); + let layout = rig.footprints(&desc); + let upload = rig.filled(&layout, |level| level as u8 + 1); + let read_as_given = |rig: &mut Rig, what: &str| { + let read = rig.round_trip(&texture, &layout, Some(&upload)); + for (level, bytes) in read.iter().enumerate() { + let want = if tiled.has_tiles(level as u32) { level as u8 + 1 } else { 0 }; + assert!(all(bytes, want), "{what}: level {level} reads {bytes:?}, wanted {want}"); + } + }; + // No room: nothing is given, the held levels are said to wait, + // nothing is shown, every level reads zeros. + let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(3), false); + rig.check("an upload without room"); + assert!(!changed && waiting, "without room: changed {changed}, waiting {waiting}"); + assert_eq!(tiled.given_bytes(), 0, "without room no tile is given"); + assert_eq!(tiled.first_shown(), None); + read_as_given(rig, "without room"); + // Asked again with room: the same levels get theirs. + let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(3), true); + rig.check("the upload again, with room"); + assert!(changed && !waiting, "with room: changed {changed}, waiting {waiting}"); + assert!(tiled.has_tiles(3) && !tiled.has_tiles(2)); + assert_eq!(tiled.first_shown(), Some(3)); + read_as_given(rig, "with room"); + // More levels held and no room again: the ones that have tiles + // are brought up to date, the new ones wait, the view stays. + let before = tiled.given_bytes(); + let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(1), false); + rig.check("more levels held, without room"); + assert!(!changed && waiting, "more levels without room: changed {changed}, waiting {waiting}"); + assert_eq!(tiled.given_bytes(), before); + assert_eq!(tiled.first_shown(), Some(3)); + read_as_given(rig, "more levels without room"); + // The card's own write is not kept waiting, and brings only its + // own level: level 1 still waits although it is held. + assert_eq!(tiled.claim(1 << 0), 1 << 0); + let changed = tiled.card_wrote_on(&rig.queue, &rig.device, &texture, 1 << 0); + rig.check("the card's own write, without room"); + assert!(changed && tiled.has_tiles(0) && !tiled.has_tiles(1) && !tiled.has_tiles(2)); + assert_eq!(tiled.first_shown(), Some(0)); + assert_eq!(tiled.claim(1 << 0), 0, "a level with tiles is not claimed again"); + // With room everything held gets its tiles. + let (_, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(1), true); + rig.check("the last upload, with room"); + assert!(!waiting && tiled.whole()); + read_as_given(rig, "everything given"); + } + + fn a_claim_given_up_is_made_again(rig: &mut Rig) { + rig.step = "step 7, a claim whose zeros never landed is given up"; + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let (_texture, tiled) = rig.reserved(&desc); + let level = tiled.with_level(2); + assert_eq!(tiled.claim(level), level, "the level is new"); + assert_eq!(tiled.claim(level), 0, "claimed once"); + // The list that claimed it was reset without being submitted. + tiled.unclaim(level); + assert_eq!(tiled.claim(level), level, "claimed again after it was given up"); + // The small levels the card packs together are claimed together. + let small = tiled.with_level(u32::from(LEVELS) - 1); + assert!(!rig.card || small.count_ones() > 1, "on the card a 1024 texture has several levels in one tile"); + assert_eq!(tiled.claim(1 << (u32::from(LEVELS) - 1)), 1 << (u32::from(LEVELS) - 1)); + tiled.unclaim(small); + assert_eq!(tiled.claim(small), small); + } + + /// On the software adapter unless `VICTORY_TILES_TEST_CARD=1`. + #[test] + #[ignore = "on the card: run it by name with --ignored --nocapture"] + fn levels_on_demand_on_the_card() { + let Some(mut rig) = Rig::new() else { + eprintln!("no adapter with tiled resources of tier 2, or no debug layer for a run on the card; skipped"); + return; + }; + rig.check("the device made"); + levels_arrive(&mut rig, DXGI_FORMAT_BC7_UNORM); + levels_arrive(&mut rig, DXGI_FORMAT_BC3_UNORM); + a_card_copy_lands_after_the_give(&mut rig); + a_reused_tile_reads_as_written(&mut rig); + a_level_on_several_ranges(&mut rig); + a_full_card_keeps_new_levels_waiting(&mut rig); + a_claim_given_up_is_made_again(&mut rig); + if the_view_starts_at_the_first_level_with_tiles(&mut rig).is_none() { + eprintln!("the view test's shader or objects could not be made; that part was skipped"); + } + rig.step = "the end"; + rig.check("every step done"); + eprintln!( + "all steps passed {}", + if rig.card { "ON THE CARD" } else { "on the software adapter; VICTORY_TILES_TEST_CARD=1 is the run on the card" } + ); + let s: Vec = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); + eprintln!( + "{} calls of UpdateTileMappings took {} microseconds in all ({} a call); the pool's heaps {} MB, {} given back", + s[6], + s[7], + s[7] / s[6].max(1), + s[3] >> 20, + s[8] + ); + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 60089a7..bc7d3be 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -14,11 +14,14 @@ //! wholly uncommitted are skipped while they remain so; one query can //! confirm a whole region, including ordinary reservations between views. //! -//! shortcut: writes into physical pages through another view (xmem's -//! `write_physical`, DirectStorage's page destinations) are not seen at -//! the guarded addresses; they go to the texture pool, whose textures are -//! hashed, not guarded. A system call writing into a guarded block fails -//! (none is known to). +//! Writes into physical pages through another view are seen too: the +//! runtime tells us the views of the pages it wrote itself ([`writing`], +//! xmem's `write_physical` and DirectStorage's page destinations), and a +//! write by the title through any view of a guarded page faults like one +//! at the guarded address (the guard makes every view of the page +//! read-only, [`open`] gives them all back; not a page of more than +//! [`MANY_VIEWS`] views). A +//! system call writing into a guarded block fails (none is known to). use std::collections::{BTreeMap, BTreeSet}; use std::sync::Mutex; @@ -218,6 +221,12 @@ pub(crate) fn wrote(at: usize, len: usize) { } j.asked += 1; let now = j.asked; + // The asking that stands moves with it: `asked` and `writes` give it as + // "now", and a page noted written after "now" stays stale for every + // copy that takes it (copied at `now`, written at `now + 1`): copied + // again at every refresh, and a reason to settle flights + // (fxceless/victory-fork#410). + j.ahead_asked = now; for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) { j.written.insert(page, now); } @@ -379,12 +388,17 @@ struct Guards { /// 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, + /// Blocks whose physical page was guarded together with its other views + /// (those views' blocks are in it too): a write to one opens them all. + /// A write range can be huge (`fread`), so only these are looked up. + aliased: BTreeSet, } static GUARDS: Mutex = Mutex::new(Guards { protected: BTreeSet::new(), clean: BTreeSet::new(), absent: BTreeSet::new(), + aliased: BTreeSet::new(), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { @@ -508,8 +522,77 @@ fn is_view(start: usize, end: usize) -> bool { /// Makes blocks `[from, to)` read-only and notes them guarded and clean; /// block by block if they span views, leaving out any that fail, and -/// noting those not committed (unmapped) absent. +/// noting those not committed (unmapped) absent. The same physical pages +/// at every other view of them are made read-only too: a write through +/// 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) { + protect_here(g, from, to); + if !view_guard() { + return; + } + for (base, bytes) in crate::inplace::views_between(from.saturating_mul(BLOCK), to.saturating_mul(BLOCK)) { + let first = (base / BLOCK).max(from); + let last = (base.saturating_add(bytes).div_ceil(BLOCK)).min(to); + for block in first..last { + let shown = crate::inplace::pages_of(block * BLOCK); + // One view (nothing else to guard), or the page the title shows + // wherever it has nothing (thousands of views): each view of + // that one is guarded by itself. + if shown.len() < 2 || shown.len() > MANY_VIEWS { + continue; + } + #[cfg(feature = "diagnostics")] + ALIASES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + for alias in shown { + let alias = alias / BLOCK; + g.aliased.insert(alias); + if alias != block { + protect_alias(g, alias); + } + } + } + } +} + +/// Views of one page past which its views are not guarded together. +pub(crate) const MANY_VIEWS: usize = 64; + +/// Whether all the views of a guarded page are guarded together +/// (`VICTORY_VIEW_GUARD`). +fn view_guard() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_GUARD").is_none_or(|v| v != "0")) +} + +/// Diagnostics: blocks guarded together with their other views, blocks +/// opened because another view of theirs was written, and blocks opened +/// because a view of theirs was mapped; since the start. +#[cfg(feature = "diagnostics")] +pub(crate) static ALIASES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Makes `block` read-only: another view of pages a copy has just taken +/// through its own view, so that a write through this one faults too. It is +/// not noted clean. The copies of title memory at this view have not taken +/// the pages: noted clean, the block would not be reported written at their +/// next check and they would keep the bytes from before the write (`guard` +/// reports a block that is read-only and not clean as written, then notes it +/// clean). A block that is clean stays so: had the pages been written since +/// its copies took them, `open` would have opened it. +fn protect_alias(g: &mut Guards, block: usize) { + use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; + if g.protected.contains(&block) { + return; + } + let mut old = 0; + // SAFETY: title view memory; only its protection changes. + if unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READONLY, &mut old) } != 0 { + g.protected.insert(block); + } +} + +/// [`protect`] for one range, without the other views of its pages. +fn protect_here(g: &mut Guards, from: usize, to: usize) { use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; let set = |from: usize, to: usize| { let mut old = 0; @@ -557,8 +640,31 @@ 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. +/// 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 { + let any = open_here(g, start, end); + if start >= end || g.aliased.is_empty() { + return any; + } + let aliased: Vec = g.aliased.range(start / BLOCK..end.div_ceil(BLOCK)).copied().collect(); + for block in aliased { + g.aliased.remove(&block); + for alias in crate::inplace::pages_of(block * BLOCK) { + if alias / BLOCK != block && open_here(g, alias, alias.saturating_add(BLOCK)) { + #[cfg(feature = "diagnostics")] + ALIASES[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + g.aliased.remove(&(alias / BLOCK)); + } + } + any +} + +/// [`open`] for one range, without the other views of its pages. +fn open_here(g: &mut Guards, start: usize, end: usize) -> bool { use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; let blocks: Vec = g .protected @@ -586,6 +692,98 @@ pub fn writing(at: usize, len: usize) { crate::descriptor::host::remapped(at, len); } +/// What `VICTORY_PAGE_WRITES` asks to be done with a write the guards do +/// not see once its bytes are there ([`title_memory_written`]), as bits: +/// 1, the guarded blocks under it are opened and count as written (host +/// copies of buffers and textures read through tables take them again); +/// 2, the placed textures picked by index that lie under it are due again; +/// 4, both also for reads to plain addresses when they have finished. +/// Unset or `0`: nothing, counted only. `1`: bits 1 and 2. `guards`: bit 1 +/// alone. `slots`: bit 2 alone. `all`: everything. +pub(crate) fn page_writes() -> u8 { + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_PAGE_WRITES").as_deref().map(str::trim) { + Ok("1") => 3, + Ok("guards") => 1, + Ok("slots") => 2, + Ok("all") => 7, + _ => 0, + }) +} + +/// Since the start: writes into physical pages through the runtime's own +/// views that landed at addresses the title has mapped (one for each run +/// of addresses); their bytes; guarded blocks that lay under them (host +/// copies that would otherwise keep the bytes from before); reads to +/// plain addresses that finished. +pub(crate) static WRITTEN: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// The bytes of a write the guards do not see are there: title memory +/// `[at, at + len)`. `pages`: DirectStorage wrote them into physical pages +/// through a view of the runtime's own, and this is an address where the +/// title has those pages mapped (no title address faulted, nothing was +/// mapped or unmapped; the shortcut this file's header names). Otherwise a +/// read to a plain address has finished, of which [`writing`] was told +/// before it began. +/// +/// Upstream's c75fdba does the same for its trackers (its `Writing` marks +/// the pages once more when dropped; page destinations are reported at +/// each address showing them). Here it is counted always and acted on as +/// [`page_writes`] says. Called without the runtime's page-table lock; +/// takes the guards' lock, then, alone, the lock of the ranges kept for +/// the texture pass. +pub fn title_memory_written(at: usize, len: usize, pages: bool) { + use std::sync::atomic::Ordering::Relaxed; + if len == 0 { + return; + } + let mode = page_writes(); + let end = at.saturating_add(len); + if pages { + WRITTEN[0].fetch_add(1, Relaxed); + WRITTEN[1].fetch_add(len as u64, Relaxed); + } else { + WRITTEN[3].fetch_add(1, Relaxed); + if mode & 4 == 0 { + return; + } + } + { + let mut g = guards(); + let guarded = g.protected.range(at / BLOCK..end.div_ceil(BLOCK)).count() as u64; + if pages { + WRITTEN[2].fetch_add(guarded, Relaxed); + } + if mode & 1 != 0 && guarded != 0 { + open(&mut g, at, end); + } + } + // A placed texture there changed with no descriptor written. + crate::descriptor::host::page_written(at, len); +} + +/// The runtime mapped a view of the physical bytes `[offset, offset + len)` +/// of `section` (`crate::inplace::title_memory_view`): the view is +/// writable, so the same bytes guarded at another view must be checked +/// again — and are, the pages noted written, which also has the next check +/// guard the new view (`protect`). +pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) { + if !view_guard() { + return; + } + let ranges = crate::inplace::views_of_section(section, offset, len); + if ranges.is_empty() { + return; + } + let mut g = guards(); + for &(at, n) in &ranges { + if open_here(&mut g, at, at.saturating_add(n)) { + #[cfg(feature = "diagnostics")] + ALIASES[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } +} + /// Held shared by a read of title memory in place, and alone by the runtime /// while it changes what title memory shows. /// @@ -657,6 +855,10 @@ pub fn title_memory_remapped(at: usize, len: usize) { g.protected.remove(&block); g.clean.remove(&block); } + let aliased: Vec = g.aliased.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); + for block in aliased { + g.aliased.remove(&block); + } } /// Registers the handler that takes writes to guarded blocks, once, ahead @@ -1046,6 +1248,154 @@ mod tests { title_memory_remapped(p, 3 * BLOCK); } + /// A pagefile section mapped twice: two views of the same physical + /// pages, the second left for the test; the section handle, the two + /// addresses. + fn two_views(bytes: usize) -> (usize, usize, usize) { + use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, + }; + // SAFETY: a fresh pagefile section, mapped twice; the views keep + // the section alive and the handle is closed by the caller. + unsafe { + let section = CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE, + 0, + bytes as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + let one = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes).Value as usize; + let two = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes).Value as usize; + assert_ne!(one, 0); + assert_ne!(two, 0); + crate::inplace::title_memory_view(one, bytes, section as usize, 0); + crate::inplace::title_memory_view(two, bytes, section as usize, 0); + (section as usize, one, two) + } + } + + /// The section of [`two_views`] is closed and its views unmapped; the + /// guard is told they are gone first. + fn drop_views(section: usize, views: &[usize], bytes: usize) { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Memory::{MEMORY_MAPPED_VIEW_ADDRESS, UnmapViewOfFile}; + for &view in views { + title_memory_remapped(view, bytes); + // SAFETY: a view of the section mapped by `two_views`. + unsafe { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { + Value: view as *mut _, + }) + }; + } + // SAFETY: the section's last reference. + unsafe { CloseHandle(section as *mut std::ffi::c_void) }; + } + + /// The title wrote the pages of a guarded texture through another view + /// of them: the fault at that view is the guard's to see, and the + /// guarded view's next check reports the pages written. + #[test] + fn a_write_through_another_view_is_reported_at_the_guarded_one() { + const SIZE: usize = 2 * BLOCK; + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + // The first check takes it in (and every view of its pages). + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + // Writing through the other view faults into the handler, which + // opens that view and the guarded one: the next check sees it. + // SAFETY: the second view, read-write once the handler has opened it. + unsafe { ((other + BLOCK + 8) as *mut u8).write(1) }; + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + drop_views(section, &[guarded, other], SIZE); + } + + /// A view of guarded pages is mapped anew: it is writable, so the + /// guarded view checks its pages again (and guards the new view). + #[test] + fn a_view_mapped_beside_a_guarded_one_makes_it_check_again() { + const SIZE: usize = 2 * BLOCK; + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + title_memory_remapped(other, SIZE); + crate::inplace::title_memory_view(other, SIZE, section, 0); + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + drop_views(section, &[guarded, other], SIZE); + } + + /// A write of the runtime's own, told at one view of the pages + /// (`writing`): the other views' next checks report the pages written. + #[test] + fn a_write_told_at_one_view_is_reported_at_the_others() { + const SIZE: usize = 2 * BLOCK; + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + writing(other + BLOCK, BLOCK); + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + // Half a page and the next: both blocks, not just the first's. + writing(other + BLOCK / 2, BLOCK); + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + drop_views(section, &[guarded, other], SIZE); + } + + /// Both views of the pages are checked, each for a copy of its own + /// (the title shows one physical page at several addresses, and each + /// address has its host copy): a write through either is reported at + /// both, whichever is checked first. Guarding the pages for the first + /// view's check must not note the second view clean, or its copy would + /// keep the bytes from before the write. + #[test] + fn a_write_is_reported_at_every_checked_view() { + const SIZE: usize = 2 * BLOCK; + let (section, one, two) = two_views(SIZE); + let pages = |view: usize, block: usize| (view + block * BLOCK) / PAGE; + assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0), pages(one, 1)])); + assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0), pages(two, 1)]), "the second view's first check"); + assert_eq!(guard(one, one + SIZE), Some(Vec::new()), "nothing written yet"); + assert_eq!(guard(two, two + SIZE), Some(Vec::new()), "nothing written yet"); + // SAFETY: the second view, read-write once the handler has opened it. + unsafe { ((two + BLOCK + 8) as *mut u8).write(1) }; + assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 1)])); + assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 1)]), "written through this view, checked second"); + // SAFETY: the first view, as above. + unsafe { ((one + 8) as *mut u8).write(1) }; + assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0)])); + assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0)]), "written through this view, checked second"); + assert_eq!(guard(one, one + SIZE), Some(Vec::new())); + assert_eq!(guard(two, two + SIZE), Some(Vec::new())); + drop_views(section, &[one, two], SIZE); + } + + /// A page shown in more than `MANY_VIEWS` views is guarded at each by + /// itself: the others stay writable, and nothing looks through them all. + #[test] + fn a_page_of_many_views_is_guarded_one_view_at_a_time() { + let (section, one, two) = two_views(BLOCK); + let filler = one + (1 << 45); + for n in 0..MANY_VIEWS { + crate::inplace::title_memory_view(filler + n * BLOCK, BLOCK, section, 0); + } + assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE])); + assert!(writable(two), "another view of it is left alone"); + // SAFETY: the guarded view, opened by the handler. + unsafe { ((one + 8) as *mut u8).write(1) }; + assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE])); + title_memory_remapped(filler, MANY_VIEWS * BLOCK); + drop_views(section, &[one, two], BLOCK); + } + /// A write or mapping that runs past the end of the address space (a /// title's `fread` with a huge count) covers up to the end; the sum used /// to overflow. Up there no test has guarded blocks. diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index 23bbccf..abda4a6 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -36,6 +36,19 @@ fn host_gpu_failed(what: &str) -> ! { unreachable!("the process has ended") } +/// The offline warm-up: see `victory_gpu::shader_cache::warm`. +pub fn warm_shader(container: &[u8]) -> Result { + #[cfg(windows)] + { + victory_gpu::shader_cache::warm(container) + } + #[cfg(not(windows))] + { + let _ = container; + Err("no shader cache on this host".into()) + } +} + /// Keeps the host's translations of the title's shaders in `dir` (a /// folder of the cache) across runs, and its compiled pipelines beside it /// (`pipelines`). diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 4c17b8e..8208880 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -863,8 +863,25 @@ fn execute(request: &Request) -> Result<(), HRESULT> { return Err(fail(E_INVALIDARG, "source larger than destination")); } let size = request.source_size as usize; - return into_destination(request, size, |out| read_into(request, out).map(|()| size)) - .map_err(|hr| fail(hr, "copying")); + // A file read into a title address is the kernel's write, and the + // kernel does not fault into the GPU side's guard: a block guarded + // again between `kernel_will_write` and the read (the guard over all + // the views of a page protects other views from other threads) made + // the read fail with ERROR_INVALID_USER_BUFFER, and the title stops + // at the failed request (runs amd-C and amd-C2, seconds after the + // world's first frame). It is read beside and copied in: our copy + // faults into the guard like the title's own writes. + let bounce = options & (PAGE_DESTINATION | MEMORY_SOURCE) == 0; + return into_destination(request, size, |out| { + if !bounce { + return read_into(request, out).map(|()| size); + } + let mut data = vec![0; size]; + read_into(request, &mut data)?; + out.copy_from_slice(&data); + Ok(size) + }) + .map_err(|hr| fail(hr, "copying")); } let tables = if bc != 0 { Some(bcpack_tables()?) } else { None }; let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?; @@ -1034,13 +1051,22 @@ fn into_destination( fill: impl FnOnce(&mut [u8]) -> Result, ) -> Result<(), HRESULT> { if request.options & PAGE_DESTINATION == 0 { - // Raw reads land through the kernel, which does not fault into the - // GPU side's guard on title buffers; open them first. + // Opens the guarded blocks and tells the GPU side a placed texture + // there changes. `fill` writes from user mode (a file read is read + // beside first, see `execute`), so a block guarded again meanwhile + // faults into the guard instead of failing the write. victory_gpu::kernel_will_write(request.destination as usize, len); // SAFETY: the title's destination holds `destination_size` bytes, at // least `len`, and nothing else writes it until completion. let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::(), len) }; - return fill(out).map(drop); + let filled = fill(out).map(drop); + // Said again now that the bytes are there (upstream's c75fdba holds + // the blocks open over the read and marks them once more at its + // end): a copy or a texture pass that took the memory while the + // read was under way took what was there before. Counted; acted on + // only with `VICTORY_PAGE_WRITES=all`. + victory_gpu::title_memory_written(request.destination as usize, len, false); + return filled; } let offset = (request.page_offset & 0xffff) as usize; // SAFETY: the title passes a page number per 64 KiB of destination, @@ -1054,20 +1080,33 @@ fn into_destination( // Consecutive pages of one allocation (the usual case): written in // place through one view. if let Some(mut window) = super::xmem::page_window(pages, offset, len) { - return fill(window.bytes()).map(drop); + let filled = fill(window.bytes()).map(drop); + drop(window); + // The title maps pages where the card reads them and has them + // filled afterwards: the GPU side's copies of those addresses + // learn of the bytes only from this (upstream c75fdba, fork PR + // #571). After a decode that failed part way too: what it wrote + // is there. + super::xmem::pages_written(pages, offset, len); + return filled; } let mut data = vec![0; len]; let n = fill(&mut data)?; - // A page the title has just made, or a view the host refuses for a moment (commit - // or address space short while a load maps many at once), can come right a little - // later: tried again before the request fails (`VICTORY_DSTORAGE_RETRIES`, default 12, - // about 1.5 s in all). + // A page the title has just made, or a view the host refuses for a + // moment, comes right a little later: the write is tried again before + // the request fails (`VICTORY_DSTORAGE_RETRIES`, 12 tries, about 0.9 s + // in all; 0: not tried again, as before). Runs 175-178 lost 12 to 446 + // reads a launch here, all in one second of the loading; the one build + // that tried again (run 165) lost none of 13. static RETRIES: std::sync::OnceLock = std::sync::OnceLock::new(); let retries = *RETRIES.get_or_init(|| { - std::env::var("VICTORY_DSTORAGE_RETRIES").ok().and_then(|v| v.parse().ok()).unwrap_or(12) + std::env::var("VICTORY_DSTORAGE_RETRIES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(12) }); + // Since the start: writes that succeeded on a later try, and writes + // given up. + static RETRIED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; let mut written = super::xmem::write_physical(pages, offset, &data[..n]); - let mut tries = 0; + let mut tries = 0u32; while !written && tries < retries { std::thread::sleep(std::time::Duration::from_millis((2u64 << tries.min(6)).min(128))); tries += 1; @@ -1075,12 +1114,28 @@ fn into_destination( } if written { if tries > 0 { - tracing::info!(offset, len, tries, "dstorage: a destination's physical pages written after a retry"); + let on_a_retry = RETRIED[0].fetch_add(1, Ordering::Relaxed) + 1; + tracing::info!( + offset, + len, + tries, + on_a_retry, + given_up = RETRIED[1].load(Ordering::Relaxed), + "dstorage: a destination's physical pages written after a retry" + ); } + // As above, after the write that succeeded. + super::xmem::pages_written(pages, offset, n); Ok(()) } else { - let known = super::xmem::pages_known(pages, offset, len); - tracing::warn!(known, last_error = std::io::Error::last_os_error().raw_os_error(), "dstorage: retries used up"); + let given_up = RETRIED[1].fetch_add(1, Ordering::Relaxed) + 1; + tracing::warn!( + known = super::xmem::pages_known(pages, offset, len), + tries, + given_up, + on_a_retry = RETRIED[0].load(Ordering::Relaxed), + "dstorage: retries used up (VICTORY_DSTORAGE_RETRIES)" + ); // Said aloud: the title never reads a request's result // (it only polls for completion), so a destination left unwritten // is a model or texture that silently holds whatever its pages diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index 902c4a9..d13c3bc 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -519,7 +519,10 @@ pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> Fi // fail there instead of faulting into its handler; the title's // synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned // destinations and retry a failed `ReadFile` forever. So the destination -// is opened first. +// is opened first. A block guarded again before the kernel writes it (the +// guard over all the views of a page protects other views from other +// threads) fails that `ReadFile`, and the title's retry opens it again; +// `fread` has no such retry and reads beside instead (see there). pub extern "system" fn ReadFile( file: *mut c_void, @@ -534,12 +537,38 @@ pub extern "system" fn ReadFile( ) } -/// The host CRT reads large requests straight into the caller's buffer. +/// The host CRT reads large requests straight into the caller's buffer +/// through the kernel, whose write fails on a guarded block instead of +/// faulting into the guard. So the bytes are read beside, a chunk at a time +/// (a caller may ask for far more than the file holds), and copied in from +/// user mode, where a guarded block faults into the guard like the title's +/// own writes. Returns the items read, as the CRT does; the bytes of a +/// partial last item are copied too, as the CRT leaves them. pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize { - victory_gpu::kernel_will_write(buffer as usize, size.saturating_mul(count)); - host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize)( - buffer, size, count, stream, - ) + let read = host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize); + let total = size.saturating_mul(count); + if buffer.is_null() || total == 0 { + // The CRT's own checks and answer (EINVAL, or nothing to read). + return read(buffer, size, count, stream); + } + const CHUNK: usize = 1 << 20; + let mut beside = vec![0u8; total.min(CHUNK)]; + let mut done = 0; + while done < total { + let want = (total - done).min(CHUNK); + let n = read(beside.as_mut_ptr(), 1, want, stream); + if n > 0 { + victory_gpu::kernel_will_write(buffer as usize + done, n); + // SAFETY: the caller's buffer holds `size * count` bytes, and + // `done + n` is at most that. + unsafe { std::ptr::copy_nonoverlapping(beside.as_ptr(), buffer.add(done), n) }; + done += n; + } + if n < want { + break; + } + } + done / size } pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File { @@ -751,6 +780,40 @@ mod tests { assert_eq!((&out, n), (b"0123456789", 10)); } + #[test] + fn fread_reads_beside_in_chunks() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("data.bin"); + // Over two chunks, and not a whole number of 3-byte items. + let bytes: Vec = (0..(5 << 19) + 1).map(|i| (i * 7 + i / 251) as u8).collect(); + std::fs::write(&path, &bytes).unwrap(); + let fclose = host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32); + let open = || { + let f = _wfopen(w(&path.to_string_lossy()).as_ptr(), w("rb").as_ptr()); + assert!(!f.is_null()); + f + }; + + // Asked for far more than the file holds: the whole file, in items. + let f = open(); + let mut out = vec![0xaau8; bytes.len() + 64]; + let items = fread(out.as_mut_ptr(), 3, out.len() / 3, f); + assert_eq!(items, bytes.len() / 3); + assert_eq!(&out[..bytes.len()], &bytes[..], "the partial last item's bytes too"); + assert!(out[bytes.len()..].iter().all(|&b| b == 0xaa), "nothing past what was read"); + fclose(f); + + // Exact reads continue where the last one stopped. + let f = open(); + let mut a = vec![0u8; 1000]; + let mut b = vec![0u8; (1 << 20) + 5]; + assert_eq!(fread(a.as_mut_ptr(), 1000, 1, f), 1); + assert_eq!(fread(b.as_mut_ptr(), 1, b.len(), f), b.len()); + assert_eq!(a, bytes[..1000]); + assert_eq!(b, bytes[1000..1000 + b.len()]); + fclose(f); + } + fn text(v: &[u16]) -> String { String::from_utf16_lossy(&v[..v.len() - 1]) } diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 6cb89fa..838826e 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -58,7 +58,7 @@ const KEYBOARD: usize = PADS + 1; const DEVICES: usize = PADS + 2; /// Readings kept per device for next/previous lookups. -const HISTORY: usize = 32; +const HISTORY: usize = 256; const POLL: Duration = Duration::from_millis(8); /// The keyboard's stand-in gamepad (virtual key, button); README lists it. diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 5f717bf..e898459 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -364,12 +364,25 @@ struct Slice { index: usize, } +impl Slice { + /// The key in `Physical::shown` of the page `k` pages after this one. + fn key(&self, k: usize) -> (usize, usize) { + (Arc::as_ptr(&self.section) as usize, self.index + k) + } +} + #[derive(Default)] struct Physical { next_page: usize, pages: HashMap, /// Mapped views by address: their length and what they show. views: BTreeMap, + /// Where each page shows: by its section and its index there, the + /// address of that page in every view that shows it now ([`shown_at`]; + /// as upstream's c75fdba keeps it). The title maps pages where the + /// card reads them and has them filled afterwards by DirectStorage, + /// which writes through views of our own. + shown: HashMap<(usize, usize), Vec>, } static PHYSICAL: LazyLock> = LazyLock::new(|| { @@ -596,6 +609,58 @@ pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option< }) } +/// The title addresses that show bytes `[offset, offset + len)` of `pages` +/// now, byte for byte, as runs (address, bytes) in address order: a write +/// to the pages through a view of our own ([`page_window`], +/// [`write_physical`]) lands there too, and nothing that watches those +/// addresses sees it (the GPU side's guards fault only on a write at the +/// guarded address itself). Empty if no view shows them. Byte for byte, +/// not by whole pages: the title packs several small textures into one +/// page and fills each with a request of its own. +pub(crate) fn shown_at(pages: &[usize], offset: usize, len: usize) -> Vec<(usize, usize)> { + let Some(end) = offset.checked_add(len) else { + return Vec::new(); + }; + let first = offset / PAGE; + let Some(touched) = pages.get(first..end.div_ceil(PAGE)) else { + return Vec::new(); + }; + let mut pieces: Vec<(usize, usize)> = Vec::new(); + { + let physical = physical(); + for (i, page) in touched.iter().enumerate() { + let Some(addresses) = physical.pages.get(page).and_then(|slice| physical.shown.get(&slice.key(0))) else { + continue; + }; + // The bytes of this page that the write covers. + let lo = if i == 0 { offset % PAGE } else { 0 }; + let hi = (end - (first + i) * PAGE).min(PAGE); + pieces.extend(addresses.iter().map(|&at| (at + lo, hi - lo))); + } + } + pieces.sort_unstable(); + let mut runs: Vec<(usize, usize)> = Vec::new(); + for (at, bytes) in pieces { + match runs.last_mut() { + Some((start, n)) if *start + *n == at => *n += bytes, + _ => runs.push((at, bytes)), + } + } + runs +} + +/// Bytes `[offset, offset + len)` of `pages` have been written through a +/// view of our own: the GPU side is told at every title address that +/// shows them (`victory_gpu::title_memory_written`; what it does with it +/// is `VICTORY_PAGE_WRITES`' to say, and it counts either way). Call when +/// the bytes are there, and without the page table's lock ([`shown_at`] +/// takes and leaves it). +pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) { + for (at, bytes) in shown_at(pages, offset, len) { + victory_gpu::title_memory_written(at, bytes, true); + } +} + /// Maps `n` pages at `address`, in place of what is mapped there; null /// `pages` unmaps. Returns `address`, or null if a page or the host fails. pub extern "system" fn XMemMapPhysicalPages( @@ -746,6 +811,9 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { victory_gpu::title_memory_remapped(base, len); // What the range shows now, for the GPU side's in-place census. victory_gpu::title_memory_view(base, len, slice.section.0 as usize, (slice.index * PAGE) as u64); + for k in 0..len.div_ceil(PAGE) { + physical.shown.entry(slice.key(k)).or_default().push(base + k * PAGE); + } physical.views.insert(base, (len, slice)); true } @@ -824,6 +892,15 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { let Some((size, slice)) = physical.views.remove(&at) else { continue; }; + for k in 0..size.div_ceil(PAGE) { + let key = slice.key(k); + if let Some(addresses) = physical.shown.get_mut(&key) { + addresses.retain(|&a| a != at + k * PAGE); + if addresses.is_empty() { + physical.shown.remove(&key); + } + } + } victory_gpu::title_memory_remapped(at, size); // SAFETY: a view we mapped; it becomes a placeholder again. unsafe { @@ -1306,6 +1383,54 @@ mod tests { assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); } + /// Pages say where the title has them mapped, byte for byte (after + /// fork PR #571's test; its runs are whole pages). + #[test] + fn pages_say_where_they_are_mapped() { + let pages = allocate(3); + let reserve = |n: usize| { + let at = XMemVirtualAlloc(std::ptr::null_mut(), n * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + assert!(!at.is_null()); + at + }; + // `b` keeps a page unmapped at either end, so that no run at `b` + // ever touches one at `a`, wherever the host puts the two. + let (a, b) = (reserve(3), reserve(4)); + assert!(shown_at(&pages, 0, 3 * PAGE).is_empty(), "mapped nowhere"); + // All three at `a`; the last two at `b`, from its second page on. + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + let second = b.wrapping_byte_add(PAGE); + assert_eq!(XMemMapPhysicalPages(second, 2, pages[1..].as_ptr()), second); + let (a, second) = (a as usize, second as usize); + let sorted = |mut runs: Vec<(usize, usize)>| { + runs.sort_unstable(); + runs + }; + assert_eq!(shown_at(&pages, 0, PAGE), vec![(a, PAGE)]); + // A request for part of a page names those bytes alone. + assert_eq!(shown_at(&pages, 0x4000, 0x3000), vec![(a + 0x4000, 0x3000)]); + // Across two pages, shown at two addresses each: one run at each. + assert_eq!( + shown_at(&pages, PAGE + 1, PAGE), + sorted(vec![(a + PAGE + 1, PAGE), (second + 1, PAGE)]) + ); + // A page unmapped in the middle of a view: the rest still shows. + let middle = (a + PAGE) as *mut c_void; + assert_eq!(XMemMapPhysicalPages(middle, 1, std::ptr::null()), middle); + assert_eq!( + shown_at(&pages, 0, 3 * PAGE), + sorted(vec![(a, PAGE), (a + 2 * PAGE, PAGE), (second, 2 * PAGE)]) + ); + // Too few pages for the bytes: nothing (the write fails too). + assert!(shown_at(&pages, 0, 3 * PAGE + 1).is_empty()); + for (at, n) in [(a, 3), (second, 2)] { + let at = at as *mut c_void; + assert_eq!(XMemMapPhysicalPages(at, n, std::ptr::null()), at); + } + assert!(shown_at(&pages, 0, 3 * PAGE).is_empty()); + assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); + } + #[test] fn page_windows_cover_one_run_in_place() { let (a, b) = (allocate(3), allocate(1)); diff --git a/crates/victory-shader/build.rs b/crates/victory-shader/build.rs new file mode 100644 index 0000000..b102125 --- /dev/null +++ b/crates/victory-shader/build.rs @@ -0,0 +1,65 @@ +//! Fingerprint of the translator's own source, for the shader cache key +//! (`victory-gpu`'s `shader_cache`): a rebuilt executable whose translator did +//! not change keeps its cached translations. Also lists every `VICTORY_*` +//! switch the translator reads, whose values join the key at run time. +//! Reads only this crate's `src` folder; writes nothing but cargo directives. + +use std::path::{Path, PathBuf}; + +fn files(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + files(&p, out); + } else if p.extension().is_some_and(|x| x == "rs") { + out.push(p); + } + } +} + +/// FNV-1a, 64 bits, two lanes with different offsets: a mismatch only costs +/// a cache miss, so this need not be cryptographic. +fn fnv(state: &mut [u64; 2], bytes: &[u8]) { + for &b in bytes { + for (i, s) in state.iter_mut().enumerate() { + *s ^= u64::from(b) ^ (i as u64 * 0x9e); + *s = s.wrapping_mul(0x0000_0100_0000_01b3); + } + } +} + +fn main() { + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + println!("cargo:rerun-if-changed=src"); + println!("cargo:rerun-if-changed=Cargo.toml"); + let mut list = Vec::new(); + files(&src, &mut list); + list.sort(); + let mut state = [0xcbf2_9ce4_8422_2325u64, 0x8422_2325_cbf2_9ce4u64]; + let mut switches = std::collections::BTreeSet::new(); + for p in &list { + let rel = p.strip_prefix(&src).unwrap_or(p).to_string_lossy().replace('\\', "/"); + let text = std::fs::read(p).unwrap_or_default(); + fnv(&mut state, rel.as_bytes()); + fnv(&mut state, &(text.len() as u64).to_le_bytes()); + fnv(&mut state, &text); + let s = String::from_utf8_lossy(&text); + let mut rest = &s[..]; + while let Some(at) = rest.find("\"VICTORY_") { + let tail = &rest[at + 1..]; + let end = tail + .find(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')) + .unwrap_or(tail.len()); + if tail[end..].starts_with('"') { + switches.insert(tail[..end].to_string()); + } + rest = &tail[end..]; + } + } + println!("cargo:rustc-env=VICTORY_SHADER_SOURCE_HASH={:016x}{:016x}", state[0], state[1]); + let joined: Vec<_> = switches.into_iter().collect(); + println!("cargo:rustc-env=VICTORY_SHADER_SWITCHES={}", joined.join(",")); +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 5f2b298..3f6f9ff 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -188,6 +188,33 @@ pub fn shader_opt() -> u32 { *PASSES.get_or_init(|| parse_shader_opt(std::env::var("VICTORY_SHADER_OPT").ok().as_deref())) } +/// Everything a translation depends on besides the container: the +/// translator's own source (hashed at build time), the value of every +/// `VICTORY_*` switch it reads, the host facts the device hands it (widest +/// wave, view heap limit) and the settings above. The shader cache keys on +/// this instead of on the whole executable, so a rebuild that leaves the +/// translator alone keeps its translations. Call it after the device is made. +pub fn translation_fingerprint() -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(env!("VICTORY_SHADER_SOURCE_HASH").as_bytes()); + out.push(u8::from(cfg!(feature = "diagnostics"))); + out.push(u8::from(cfg!(debug_assertions))); + for name in env!("VICTORY_SHADER_SWITCHES").split(',').filter(|n| !n.is_empty()) { + out.extend_from_slice(name.as_bytes()); + out.push(b'='); + if let Some(value) = std::env::var_os(name) { + out.extend_from_slice(value.as_encoded_bytes()); + } + out.push(0); + } + out.extend_from_slice(&lower::host_max_wave().to_le_bytes()); + out.extend_from_slice(&shader::view_heap_limit().to_le_bytes()); + out.extend_from_slice(&loop_limit().to_le_bytes()); + out.push(group_sync()); + out.extend_from_slice(&shader_opt().to_le_bytes()); + out +} + /// `VICTORY_SHADER_OPT`'s value; every pass when it is unset or /// unreadable. Pure, for testing. fn parse_shader_opt(value: Option<&str>) -> u32 { From c27a8ec844479d0fa2b1c65c9a6c21bead4c2ee3 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:46:35 -0600 Subject: [PATCH 187/445] How much of a texture is mapped is read from the runtime's own record of its views The pass that uploads textures picked by index asked the host for every 64 KiB of every texture it looked at, and twice for each block that was not there (12,000 slots wait for their memory during a load, each looked at again and again): 146 us for a texture of 22 MB, 721 us with 1 MB of it there. The views of physical pages are known: 1.4 and 0.1 us. Memory that is in no view is asked of the host as before. VICTORY_MAPPED_BY_VIEWS=0: always. Measurement: cargo test --release -p victory-gpu --lib look_costs -- --ignored --nocapture Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/inplace.rs | 41 ++++++++++++++++++++++++++++ crates/victory-gpu/src/texture.rs | 44 +++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 56a883b..c9df9c1 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -329,6 +329,26 @@ pub(crate) fn views_gone(at: usize, len: usize) { } } +/// How many bytes of `[at, at + len)` views of physical pages show; `None` +/// if no view touches it (nothing is mapped there, or memory of another +/// kind). The runtime's own record of what it mapped: no question to the +/// host. +pub(crate) fn shown_bytes(at: usize, len: usize) -> Option { + let end = at.saturating_add(len); + let v = views(); + let first = v.views.range(..=at).next_back(); + let rest = v.views.range(at.saturating_add(1)..end.max(at.saturating_add(1))); + let (mut there, mut any) = (0u64, false); + for (&base, view) in first.into_iter().chain(rest) { + let (from, to) = (base.max(at), base.saturating_add(view.0).min(end)); + if from < to { + there += (to - from) as u64; + any = true; + } + } + any.then_some(there) +} + /// How the views cover `[at, at + len)`. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub(crate) enum Cover { @@ -1074,6 +1094,27 @@ mod tests { /// Views as the runtime tells them: a range inside one view, or over /// views that continue each other in one section, is one run; over /// views from elsewhere it is scattered; over a gap it has holes. + #[test] + fn the_views_say_how_much_of_a_range_is_there() { + const K64: usize = 64 << 10; + // Addresses nothing has: only the record is asked. + let at = 0x7ff1_0000_0000_usize; + for (block, blocks) in [(0, 1), (1, 1), (4, 2)] { + super::title_memory_view(at + block * K64, blocks * K64, 7, 0); + } + let shown = |from: usize, len: usize| super::shown_bytes(at + from, len); + assert_eq!(shown(0, 8 * K64), Some(4 * K64 as u64)); + assert_eq!(shown(100, K64), Some(K64 as u64)); + assert_eq!(shown(K64 + 100, 2 * K64), Some(K64 as u64 - 100)); + assert_eq!(shown(5 * K64 + 1, 10), Some(10)); + assert_eq!(shown(2 * K64, 2 * K64), None); + assert_eq!(shown(6 * K64, 2 * K64), None); + super::views_gone(at + K64, K64); + assert_eq!(shown(0, 2 * K64), Some(K64 as u64)); + super::views_gone(at, 8 * K64); + assert_eq!(shown(0, 8 * K64), None); + } + #[test] fn views_say_what_one_placed_buffer_could_show() { let mut views = BTreeMap::new(); diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 267597e..846cb66 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -1119,6 +1119,16 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 { } let start = at as usize; let end = start.saturating_add(len); + // Streamed textures lie in views of physical pages, of which the runtime + // knows which are there: one look, where the host was asked for every + // 64 KiB of the texture (and once more for each that is not there). + // `VICTORY_MAPPED_BY_VIEWS=0`: the host is asked, as before. + static BY_VIEWS: std::sync::OnceLock = std::sync::OnceLock::new(); + if *BY_VIEWS.get_or_init(|| std::env::var_os("VICTORY_MAPPED_BY_VIEWS").is_none_or(|v| v != "0")) + && let Some(there) = crate::inplace::shown_bytes(start, len) + { + return there; + } if !committed(at, 1) && !committed((end - 1) as *const u8, 1) { return 0; } @@ -1417,6 +1427,40 @@ mod allocation_costs { drop(all); } + /// What a look at how much of a texture is there costs: by questions to + /// the host, and by the runtime's record of its views. + #[test] + #[ignore = "a measurement, not a check"] + fn look_costs() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const BLOCK: usize = 64 << 10; + for (name, blocks, there) in [("350 KB, all there", 6, 6), ("22 MB, all there", 350, 350), ("22 MB, 1 MB there", 350, 16)] { + let make = || { + // SAFETY: a reservation of our own, of which the first part + // is committed and touched. + unsafe { + let at = VirtualAlloc(std::ptr::null(), blocks * BLOCK, MEM_RESERVE, PAGE_READWRITE); + VirtualAlloc(at, there * BLOCK, MEM_COMMIT, PAGE_READWRITE); + std::ptr::write_bytes(at.cast::(), 1, there * BLOCK); + at as usize + } + }; + let (asked, noted) = (make(), make()); + for block in 0..there { + crate::title_memory_view(noted + block * BLOCK, BLOCK, 9, 0); + } + for (how, at) in [("asking the host", asked), ("by the views", noted)] { + const N: u32 = 200; + let began = std::time::Instant::now(); + for _ in 0..N { + assert_eq!(super::mapped_bytes(at as *const u8, blocks * BLOCK), (there * BLOCK) as u64); + } + println!("{name}, {how}: {:.1} us a look", began.elapsed().as_secs_f64() * 1e6 / f64::from(N)); + } + crate::inplace::views_gone(noted, blocks * BLOCK); + } + } + #[test] #[ignore = "a measurement, not a check"] fn allocation_costs() { From bd80bbe13a4f6463833f0acdb2c47ec3c4309ad3 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:47:25 -0600 Subject: [PATCH 188/445] Words of the title's image logged each second (VICTORY_IMAGE_WATCH; off) Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/image_watch.rs | 100 ++++++++++++++++++++++++++ crates/victory-hle/src/lib.rs | 1 + crates/victory-hle/src/runtime.rs | 1 + 3 files changed, 102 insertions(+) create mode 100644 crates/victory-hle/src/image_watch.rs diff --git a/crates/victory-hle/src/image_watch.rs b/crates/victory-hle/src/image_watch.rs new file mode 100644 index 0000000..e5d6856 --- /dev/null +++ b/crates/victory-hle/src/image_watch.rs @@ -0,0 +1,100 @@ +//! Diagnostics (`VICTORY_IMAGE_WATCH`; off by default): words of the title's +//! image, logged once a second, for what a launch's own counters say (how +//! much of its streaming memory it uses, whether an allocation failed) where +//! two launches end up with different pictures. +//! +//! `VICTORY_IMAGE_WATCH=used=98d26d8:8,failed=98d26d0:1`: a name, the offset +//! in the image (hexadecimal) and the bytes (1, 2, 4 or 8). + +use std::time::Duration; + +struct Word { + name: String, + offset: usize, + bytes: usize, +} + +/// The words `text` names; what cannot be read of it is left out. +fn words(text: &str) -> Vec { + text.split(',') + .filter_map(|part| { + let (name, rest) = part.trim().split_once('=')?; + let (offset, bytes) = rest.split_once(':').unwrap_or((rest, "8")); + let offset = usize::from_str_radix(offset.trim().trim_start_matches("0x"), 16).ok()?; + let bytes = bytes.trim().parse().ok().filter(|n| matches!(n, 1 | 2 | 4 | 8))?; + Some(Word { name: name.trim().to_owned(), offset, bytes }) + }) + .collect() +} + +/// `word` of the image at `base`; `None` if it cannot be read. +fn read(base: usize, word: &Word) -> Option { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut value = [0u8; 8]; + // SAFETY: the kernel copies at most eight bytes into `value`, and fails + // where there is nothing to read. + let ok = unsafe { + ReadProcessMemory( + GetCurrentProcess(), + (base + word.offset) as *const _, + value.as_mut_ptr().cast(), + word.bytes, + std::ptr::null_mut(), + ) + }; + (ok != 0).then(|| u64::from_le_bytes(value)) +} + +/// Starts watching the image at `base`, if asked for. +pub(crate) fn start(base: usize) { + let Ok(text) = std::env::var("VICTORY_IMAGE_WATCH") else { + return; + }; + let words = words(&text); + if base == 0 || words.is_empty() { + return; + } + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("victory-image-watch".into()).spawn(move || { + let mut last = Vec::new(); + loop { + std::thread::sleep(Duration::from_secs(1)); + let now: Vec> = words.iter().map(|word| read(base, word)).collect(); + if now == last { + continue; + } + let values: Vec = words + .iter() + .zip(&now) + .map(|(word, value)| match value { + Some(value) => format!("{}={value:#x}", word.name), + None => format!("{}=?", word.name), + }) + .collect(); + tracing::info!("the title's image: {}", values.join(" ")); + last = now; + } + }); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn words_are_read_where_they_are_named() { + let all = words("used=98d26d8:8, failed = 0x10:1,odd=3:3,none"); + assert_eq!(all.len(), 2); + assert_eq!((all[0].name.as_str(), all[0].offset, all[0].bytes), ("used", 0x98d_26d8, 8)); + assert_eq!((all[1].name.as_str(), all[1].offset, all[1].bytes), ("failed", 0x10, 1)); + let memory = [0x11u8, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]; + let word = |offset, bytes| Word { name: String::new(), offset, bytes }; + let base = memory.as_ptr() as usize; + assert_eq!(read(base, &word(0, 4)), Some(0x4433_2211)); + assert_eq!(read(base, &word(2, 1)), Some(0x33)); + assert_eq!(read(8, &word(0, 8)), None); + } +} diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs index a61e988..447de82 100644 --- a/crates/victory-hle/src/lib.rs +++ b/crates/victory-hle/src/lib.rs @@ -12,6 +12,7 @@ //! then the host if [`HostPolicy`] allows that DLL, then `Missing`. mod host; +mod image_watch; pub mod modules; mod registry; pub mod runtime; diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index aed5c19..de8817d 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -10,6 +10,7 @@ static MAIN_IMAGE_BASE: AtomicUsize = AtomicUsize::new(0); /// `GetModuleHandle(NULL)` and friends to return this, not our own exe. pub fn set_main_image(base: usize) { MAIN_IMAGE_BASE.store(base, Ordering::Release); + crate::image_watch::start(base); } pub fn main_image() -> Option { From c651346a8c4528104ee20812da0f0c9cea2c674b Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:48:35 -0600 Subject: [PATCH 189/445] A refresh of a copy on the card sends the dwords title memory changed, and no others (VICTORY_SEND_CHANGED, on) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 61 ++++++++++--- crates/victory-gpu/src/safecopy.rs | 141 ----------------------------- crates/victory-gpu/src/shadow.rs | 133 ++++++++++++++++----------- 3 files changed, 127 insertions(+), 208 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 7023d67..65808ee 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -6257,7 +6257,7 @@ fn split_line(frames: f64) { let f: Vec = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); let a: Vec = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect(); let h: Vec = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); - let s: Vec = crate::shadow::send_stats().iter().map(|&n| n as f64 / (1 << 20) as f64 / frames).collect(); + let s: Vec = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect(); tracing::info!( "preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \ writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \ @@ -6284,8 +6284,8 @@ fn split_line(frames: f64) { "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \ written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \ bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \ - waiting for the guards, {:.1} ms changing protections; pages taken again for the card: {:.1} MB compared, {:.1} MB of them \ - as they were, {:.1} MB to go up (VICTORY_SEND_CHANGED)", + waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \ + as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)", a[0], a[1] / 1024.0, a[11] / 1e6, @@ -6299,9 +6299,10 @@ fn split_line(frames: f64) { a[6], a[7] / 1e6, a[8] / 1e6, - s[0], - s[1], - s[2], + s[0] / 1048576.0, + s[1] / 1048576.0, + s[2] / 1048576.0, + s[3], ); tracing::info!( "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures", @@ -8012,6 +8013,10 @@ mod refresh_tests { /// card's side of those that have one, hold what title memory holds, and /// title memory what was written last. /// + /// Into the first copy shaders write besides through a view nobody + /// declared, words the title does not write: nothing that goes up ever + /// puts an older value over those. + /// /// (It fails in the first rounds if `landed_beside` notes nothing, or /// only takes the block out of the guards' clean ones and leaves its bit, /// or if a fault leaves the bit; in some thousand rounds, @@ -8030,6 +8035,9 @@ mod refresh_tests { let data = memory(len); (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize) }; + // What was last written so, by offset. + let mut undeclared = std::collections::HashMap::new(); + let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0"); let stop = AtomicBool::new(false); // Also when an assertion fails on one of the threads. struct Stop<'a>(&'a AtomicBool); @@ -8134,6 +8142,16 @@ mod refresh_tests { let mut value = 1u32; for round in 0..rounds { check(round, &mut random, false); + if exact { + let c = &carded[0]; + let mut card = c.card.lock().unwrap(); + for _ in 0..40 { + value += 1; + let at = random.below(LEN / 32) * 32 + 4 * 6; + card.2[at..at + 4].copy_from_slice(&value.to_le_bytes()); + undeclared.insert(at, value); + } + } // The flight of this submission: its shaders' writes. for (which, c) in carded.iter().enumerate() { if c.flying.swap(true, Ordering::Acquire) { @@ -8179,7 +8197,17 @@ mod refresh_tests { let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len)); assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class); let card = c.card.lock().unwrap(); - assert_eq!(first(&card.2, there), None, "round {round}: a card copy's card side (class {})", c.class); + let mut side = card.2.clone(); + if c.class == carded[0].class { + // (They may have been landed meanwhile, by a flight + // that declared their range, and may not.) + for (&at, &value) in &undeclared { + let on_card = u32::from_le_bytes(side[at..at + 4].try_into().unwrap()); + assert_eq!(on_card, value, "round {round}: an older value at {at:#x}"); + side[at..at + 4].copy_from_slice(&there[at..at + 4]); + } + } + assert_eq!(first(&side, there), None, "round {round}: a card copy's card side (class {})", c.class); } assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy"); } @@ -8263,8 +8291,9 @@ mod refresh_tests { } } - /// A part of a copy in the card's memory taken again goes up only if it - /// differs (with `VICTORY_SEND_CHANGED=1`), whole when never taken. + /// Of a copy in the card's memory only the dwords title memory changed go + /// up, and none beside them, not even between two in 64 bytes; a page + /// never taken goes up whole. #[test] fn only_what_differs_goes_up() { let region = title(4 * PAGE, true); @@ -8283,18 +8312,24 @@ mod refresh_tests { copy.update(region, 4 * PAGE); let again = copy.take_dirty(); // SAFETY: as above. - unsafe { ((region + 2 * PAGE + 128) as *mut u8).write_volatile(9) }; + unsafe { + ((region + 2 * PAGE + 129) as *mut u8).write_volatile(9); + ((region + 2 * PAGE + 136) as *mut u32).write_volatile(9); + ((region + 2 * PAGE + 140) as *mut u32).write_volatile(9); + // The value that was there. + ((region + 2 * PAGE + 132) as *mut u32).write_volatile(0); + } copy.update(region, 4 * PAGE); let written = copy.take_dirty(); - if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") { + if std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0") { assert_eq!(again, []); - assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 192)]); + assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]); } else { assert_eq!(again, [(PAGE, 2 * PAGE)]); assert_eq!(written, [(2 * PAGE, 3 * PAGE)]); } // SAFETY: as above. - assert_eq!(unsafe { data.add(2 * PAGE + 128).read() }, 9); + assert_eq!(unsafe { data.add(2 * PAGE + 129).read() }, 9); } /// The refreshes of a frame as run record-1 had them: 30 submissions, the diff --git a/crates/victory-gpu/src/safecopy.rs b/crates/victory-gpu/src/safecopy.rs index aa331eb..66bb68a 100644 --- a/crates/victory-gpu/src/safecopy.rs +++ b/crates/victory-gpu/src/safecopy.rs @@ -75,46 +75,6 @@ std::arch::global_asm!( "vzeroupper", "xor eax, eax", "ret", - ".globl victory_safe_update", - ".globl victory_safe_update_at", - ".globl victory_safe_update_after", - ".globl victory_safe_update_failed", - // rcx destination, rdx source, r8 bytes (whole 64s, not none), r9 where - // the offset of the first 64 bytes that differed goes (-1: none did) and - // behind it the offset of the end of the last: stores the 64s that - // differ. eax: whether all could be read. - "victory_safe_update:", - "xor r10d, r10d", - "mov r11, -1", - "xor eax, eax", - "2:", - "victory_safe_update_at:", - "vmovdqu ymm0, ymmword ptr [rdx + r10]", - "vmovdqu ymm1, ymmword ptr [rdx + r10 + 32]", - "victory_safe_update_after:", - "vpxor ymm2, ymm0, ymmword ptr [rcx + r10]", - "vpxor ymm3, ymm1, ymmword ptr [rcx + r10 + 32]", - "vpor ymm2, ymm2, ymm3", - "vptest ymm2, ymm2", - "jz 3f", - "vmovdqu ymmword ptr [rcx + r10], ymm0", - "vmovdqu ymmword ptr [rcx + r10 + 32], ymm1", - "cmp r11, -1", - "cmove r11, r10", - "lea rax, [r10 + 64]", - "3:", - "add r10, 64", - "cmp r10, r8", - "jb 2b", - "mov qword ptr [r9], r11", - "mov qword ptr [r9 + 8], rax", - "vzeroupper", - "mov eax, 1", - "ret", - "victory_safe_update_failed:", - "vzeroupper", - "xor eax, eax", - "ret", ".globl victory_safe_merge", ".globl victory_safe_merge_at", ".globl victory_safe_merge_after", @@ -185,63 +145,12 @@ unsafe extern "system" { fn victory_safe_put_at(); fn victory_safe_put_after(); fn victory_safe_put_failed(); - fn victory_safe_update(dst: *mut u8, src: *const u8, len: usize, changed: *mut [usize; 2]) -> u32; - fn victory_safe_update_at(); - fn victory_safe_update_after(); - fn victory_safe_update_failed(); fn victory_safe_merge(title: *mut u8, now: *const u8, held: *mut u8, blocks: usize, counts: *mut [u64; 2]) -> usize; fn victory_safe_merge_at(); fn victory_safe_merge_after(); fn victory_safe_merge_failed(); } -/// What [`update`] found. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Updated { - /// Every byte was the same already; nothing was stored. - Same, - /// The bytes that changed lie in these offsets. - Changed(usize, usize), - /// Not all of the source could be read; some may have been copied. - Failed, -} - -/// Makes `dst` hold what `src` holds, storing only what differs. The source -/// may change meanwhile: what is compared is what is stored, read once. -/// -/// # Safety -/// As [`copy`]'s, and the destination is memory of ours that nothing else -/// writes. -pub(crate) unsafe fn update(dst: *mut u8, src: *const u8, len: usize) -> Updated { - let whole = len / 64 * 64; - let (mut from, mut to) = (usize::MAX, 0); - if whole > 0 { - let mut changed = [usize::MAX, 0]; - // SAFETY: the source's faults leave through the failing exit; the - // rest is the caller's. - if unsafe { victory_safe_update(dst, src, whole, &mut changed) } == 0 { - return Updated::Failed; - } - [from, to] = changed; - } - if whole < len { - let mut rest = [0u8; 64]; - let rest = &mut rest[..len - whole]; - // SAFETY: as above; `rest` is ours. - unsafe { - if !copy(rest.as_mut_ptr(), src.add(whole), rest.len()) { - return Updated::Failed; - } - let held = std::slice::from_raw_parts_mut(dst.add(whole), rest.len()); - if held != rest { - held.copy_from_slice(rest); - (from, to) = (from.min(whole), len); - } - } - } - if from >= to { Updated::Same } else { Updated::Changed(from, to) } -} - /// What [`merge`] did. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct Merged { @@ -445,10 +354,6 @@ pub(crate) fn failing_exit(at: usize) -> Option { if (from..to).contains(&at) { return Some(victory_safe_put_failed as *const () as usize); } - let (from, to) = (victory_safe_update_at as *const () as usize, victory_safe_update_after as *const () as usize); - if (from..to).contains(&at) { - return Some(victory_safe_update_failed as *const () as usize); - } let (from, to) = (victory_safe_merge_at as *const () as usize, victory_safe_merge_after as *const () as usize); (from..to).contains(&at).then_some(victory_safe_merge_failed as *const () as usize) } @@ -504,52 +409,6 @@ mod tests { } } - /// An update makes the two the same, says where they differed (to 64 - /// bytes), stores nothing where they did not, and fails at a page that - /// is not there. - #[test] - fn updates_store_what_differs() { - assert!(on()); - let (src, dst) = (Pages::new(1 << 14), Pages::new(1 << 14)); - for len in [0usize, 1, 63, 64, 65, 200, 4096, 5000] { - for (da, sa) in [(0usize, 0usize), (3, 0), (0, 5)] { - for changed in [vec![], vec![0usize], vec![len / 2], vec![len.saturating_sub(1)], vec![1, len / 3, len / 2]] { - src.fill(); - // SAFETY: inside the two allocations. - unsafe { - std::ptr::write_bytes(dst.0, 0xEE, dst.1); - std::ptr::copy_nonoverlapping(src.0.add(sa), dst.0.add(da), len); - let at: std::collections::BTreeSet = changed.iter().copied().filter(|&i| i < len).collect(); - for &i in &at { - *src.0.add(sa + i) ^= 0x40; - } - let found = update(dst.0.add(da), src.0.add(sa), len); - match (at.iter().min(), at.iter().max()) { - (Some(&first), Some(&last)) => { - let Updated::Changed(from, to) = found else { - panic!("{len} {at:?}: {found:?}") - }; - assert_eq!(from, first / 64 * 64); - assert_eq!(to, ((last / 64 + 1) * 64).min(len)); - } - _ => assert_eq!(found, Updated::Same), - } - let (to, from) = (std::slice::from_raw_parts(dst.0, dst.1), std::slice::from_raw_parts(src.0, src.1)); - assert_eq!(to[da..da + len], from[sa..sa + len]); - assert!(to[..da].iter().chain(&to[da + len..]).all(|&x| x == 0xEE)); - } - } - } - } - // SAFETY: our allocation. - unsafe { - VirtualFree(src.0.add(4096).cast(), 4096, MEM_DECOMMIT); - assert_eq!(update(dst.0, src.0, 8192), Updated::Failed); - assert_eq!(update(dst.0, src.0.add(4096), 10), Updated::Failed); - assert_ne!(update(dst.0, src.0, 4096), Updated::Failed); - } - } - /// The dwords that changed are stored, and no byte of any other, at /// every alignment and length; a page that is not there fails. #[test] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index adaa766..b1a2a94 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1507,30 +1507,34 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { runs } -/// Whether pages of a copy in the card's memory that a refresh takes again -/// go up to the card only where they are not what the CPU's side holds -/// already (`VICTORY_SEND_CHANGED=1`; off by default). +/// 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=0`: the 64 KiB pages written since it last took +/// them, whole, as before). /// -/// A refresh copies the 64 KiB pages that were written since it last took -/// them, and all of each went up and was hashed there again. Most of them -/// the title did not write: the relay put what shaders wrote into title -/// memory, and the card and the CPU's side hold those bytes already -/// ([`Shadow::card_merge_relay`]). Run record-1: 1,500 pieces (98 MB) a -/// frame fetched from the card, 103 MB in 328 ranges sent up, 322 hash -/// passes, while the title's own writes took some 260 guards off. +/// A page that counts as written is mostly not the title's doing, or not all +/// of it: a word the title wrote, and around it what shaders wrote and the +/// title never touched; or only what the relay put into title memory, which +/// the card and the CPU's side hold already ([`Shadow::card_merge_relay`]). +/// Sent up whole, such a page goes over whatever the card holds there that +/// did not come back yet, or never will (a write through a view nobody +/// declared): what stood on the card, newer, was gone. /// -/// What it rests on: the card's side holds what the CPU's side holds, but -/// for ranges shaders may be writing (no refresh touches them) and what is -/// still to go up. A page's first taking always goes up whole, so does one -/// that could not be read; after that every byte that changes on the CPU's -/// side goes up (the bytes compared are the bytes stored). +/// What it rests on: the CPU's side is what the card's side was last known +/// to hold, for every range no shader may be writing (no refresh touches +/// the others). So a dword goes up only if title memory holds another value +/// of it than the CPU's side, which then holds it too; title memory is read +/// once, what is compared is what is stored and sent. Dwords, not bytes: +/// no shader writes less, and the title's bytes beside a changed one in its +/// dword are those the CPU's side holds. /// -/// Why it is not on by default: a shader that writes a copy through a view -/// nobody declared (`crate::draw`, buffers picked by index) breaks that -/// rule. Taken again, its page went up over what it wrote; with the switch -/// its bytes stay, as they would on the console, until the title changes the -/// same 64 bytes: clearing them to the zeros they held before is then no -/// change. +/// A page never taken goes up whole as long as no shader's write was ever +/// declared for the copy. After that it is compared as any other: the CPU's +/// side and the card's began as zeros, both. +/// +/// What it cannot know: that the title wrote a value over the same value. +/// Where a shader wrote in between, through a view nobody declared, the +/// shader's stays. fn send_changed() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| { @@ -1538,19 +1542,19 @@ fn send_changed() -> bool { if crate::copystat::mode() != 0 { return false; } - std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") && crate::safecopy::on() + std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0") }) } -/// Since the last frame-rate line, of pages taken again into copies in the +/// Since the last frame-rate line, of pages taken into copies in the /// card's memory ([`send_changed`]): bytes compared, those of pages that -/// held the same, and bytes to go up. -static SEND: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; +/// held the same, bytes to go up, and the runs they are. +static SEND: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; /// [`SEND`], taken. #[cfg(feature = "diagnostics")] -pub(crate) fn send_stats() -> [u64; 3] { - [0, 1, 2].map(|i| SEND[i].swap(0, Ordering::Relaxed)) +pub(crate) fn send_stats() -> [u64; 4] { + [0, 1, 2, 3].map(|i| SEND[i].swap(0, Ordering::Relaxed)) } /// Whether what shaders wrote goes into title memory run by run @@ -2993,34 +2997,47 @@ impl Shadow { /// 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 { - if !known || self.card.is_none() || !send_changed() { - return self.copy(from, to); + thread_local! { + /// A page of title memory, as read. + static TITLE: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } + let Some(card) = self.card.as_ref().filter(|_| send_changed()) else { + return self.copy(from, to); + }; + let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none(); let start = self.start as usize; - let mut at = from; - while at < to { - let n = (PAGE - at % PAGE).min(to - at); - // SAFETY: inside the mapping of the copy's CPU side, which - // nothing else writes there: no shader's range holds it. - let found = unsafe { crate::safecopy::update(self.data.add(at - start), at as *const u8, n) }; - SEND[0].fetch_add(n as u64, Ordering::Relaxed); - match found { - crate::safecopy::Updated::Same => { + TITLE.with_borrow_mut(|title| { + title.resize(PAGE, 0); + let mut at = from; + while at < to { + let n = (PAGE - at % PAGE).min(to - at); + let title = &mut title[..n]; + // (Pages that are not there read as zeros.) + crate::host::copy_mapped(title.as_mut_ptr(), at as *const u8, n, false); + // SAFETY: inside the mapping of the copy's CPU side, which + // nothing else reads or writes there (the card copies from + // it): 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), n) }; + let was = crate::host::upcheck::on().then(|| held.to_vec()); + let runs = if whole { vec![(0, n)] } else { dword_runs(at, held, title, 0) }; + for &(a, len) in &runs { + held[a..a + len].copy_from_slice(&title[a..a + len]); + self.changed(at - start + a, at - start + a + len); + } + self.card_changed_runs(runs.iter().map(|&(a, len)| (at - start + a, at - start + a + len))); + if let Some(was) = was { + crate::host::upcheck::note(self.id, at - start, &was, held); + } + SEND[0].fetch_add(n as u64, Ordering::Relaxed); + if runs.is_empty() { SEND[1].fetch_add(n as u64, Ordering::Relaxed); } - crate::safecopy::Updated::Changed(a, b) => { - SEND[2].fetch_add((b - a) as u64, Ordering::Relaxed); - self.changed(at - start + a, at - start + b); - self.card_changed(at - start + a, at - start + b); - } - // A page is not there: as before, around it, and all of it - // goes up. - crate::safecopy::Updated::Failed => { - self.copy(at, at + n); - } + SEND[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed); + SEND[3].fetch_add(runs.len() as u64, Ordering::Relaxed); + at += n; } - at += n; - } + }); to - from } @@ -3055,16 +3072,24 @@ impl Shadow { /// The CPU side's bytes at offsets `[from, to)` changed: they go to the /// card's side before the next submission. fn card_changed(&self, from: usize, to: usize) { + self.card_changed_runs(std::iter::once((from, to))); + } + + /// [`Shadow::card_changed`] of each of `runs`. + fn card_changed_runs(&self, runs: impl Iterator) { let Some(card) = &self.card else { return; }; - if from >= to { + let mut runs = runs.filter(|r| r.0 < r.1).peekable(); + if runs.peek().is_none() { return; } let mut dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); - match dirty.last_mut() { - Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)), - _ => dirty.push((from, to)), + for (from, to) in runs { + match dirty.last_mut() { + Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)), + _ => dirty.push((from, to)), + } } } From c05f949c4b7a0eece6066043afcd9b7ab8754811 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:50:34 -0600 Subject: [PATCH 190/445] victory replay --pixel: which commands change a pixel, in every target After each command that can change a texture, the texel under a point of the picture is copied out; commands that changed one are named with their pipeline and the values before and after. The listing names textures. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 69 ++ crates/victory-gpu/src/replay/edit.rs | 4 + crates/victory-gpu/src/replay/play.rs | 15 +- crates/victory-gpu/src/replay/play/pixel.rs | 843 ++++++++++++++++++++ docs/replay.md | 24 + 5 files changed, 954 insertions(+), 1 deletion(-) create mode 100644 crates/victory-gpu/src/replay/play/pixel.rs diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index c10b13e..0455ec7 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -136,6 +136,26 @@ pub(crate) struct Replay { /// Only write the frame's buffers and the commands of these lists (`3..7`). #[arg(long)] listing: Option, + /// Say which commands change the pixel: `,` of the presented + /// picture, or `[.]:,` of a texture + /// (repeatable). With --lists, only those are looked into. + #[arg(long)] + pixel: Vec, + /// With --pixel: the size of the picture the points are of (`1280x720`), + /// if it is another than the presented one's. + #[arg(long)] + of: Option, + /// With --pixel: depth targets too. + #[arg(long)] + depth: bool, + /// With --pixel: leave out textures that shaders may write (unordered + /// access). + #[arg(long)] + targets_only: bool, + /// With --pixel: indirect calls whose draws are run one by one: + /// `:` (repeatable). + #[arg(long)] + split: Vec, /// Use the D3D12 debug layer (slow). #[arg(long)] debug_layer: bool, @@ -149,6 +169,12 @@ fn range(text: &str) -> Option<(u32, u32)> { } } +/// Two numbers with `by` between them. +fn pair(text: &str, by: char) -> Option<(u32, u32)> { + let (a, b) = text.split_once(by)?; + Some((a.trim().parse().ok()?, b.trim().parse().ok()?)) +} + pub(crate) fn run(r: Replay) -> Result<()> { if let Some(text) = &r.dump { for line in play::dump(&r.folder, text)? { @@ -201,6 +227,47 @@ pub(crate) fn run(r: Replay) -> Result<()> { let player = play::Player::load(&r.folder, &options)?; return player.slots(list, command, &mut |line| println!("{line}")); } + if !r.pixel.is_empty() { + let mut player = play::Player::load(&r.folder, &options)?; + let mut pixels = play::pixel::Pixels { + depth: r.depth, + written: !r.targets_only, + ..Default::default() + }; + if let Some(text) = &r.lists { + pixels.lists = Some(range(text).with_context(|| format!("--lists {text}"))?); + } + let of = match &r.of { + Some(text) => Some(pair(text, 'x').with_context(|| format!("--of {text}"))?), + None => None, + }; + for text in &r.pixel { + let bad = || format!("--pixel {text}"); + match text.split_once(':') { + Some((what, at)) => { + let (id, sub) = what.split_once('.').unwrap_or((what, "0")); + let (x, y) = pair(at, ',').with_context(bad)?; + let id = id.parse().with_context(bad)?; + let sub = sub.parse().with_context(bad)?; + pixels.texels.push((id, sub, x, y)); + } + None => { + let (mut x, mut y) = pair(text, ',').with_context(bad)?; + if let (Some((w, h)), Some((pw, ph))) = (of, player.picture_size()) { + x = x * pw / w.max(1); + y = y * ph / h.max(1); + } + pixels.points.push((x, y)); + } + } + } + for text in &r.split { + pixels + .split + .push(pair(text, ':').with_context(|| format!("--split {text}"))?); + } + return player.pixel(&options, &pixels, &mut |line| println!("{line}")); + } if r.check_written { let mut player = play::Player::load(&r.folder, &options)?; return player.check_written(&mut |line| println!("{line}")); @@ -277,6 +344,8 @@ mod tests { assert_eq!(super::range("3..7"), Some((3, 7))); assert_eq!(super::range("5"), Some((5, 5))); assert_eq!(super::range("x"), None); + assert_eq!(super::pair("12,7", ','), Some((12, 7))); + assert_eq!(super::pair("12", ','), None); assert_eq!(super::range("1..x"), None); } } diff --git a/crates/victory-gpu/src/replay/edit.rs b/crates/victory-gpu/src/replay/edit.rs index a9c7ce3..e4f1f98 100644 --- a/crates/victory-gpu/src/replay/edit.rs +++ b/crates/victory-gpu/src/replay/edit.rs @@ -8,6 +8,10 @@ use super::wire::{ALL, Barrier, Cmd, NONE, Va, slot}; /// The buffer the clamped arguments of all clamp passes lie in, in lists /// edited by [`clamps`]. pub const RESULTS: u32 = u32::MAX - 1; +/// The buffer texels are read back through (`play::pixel`). +pub const PROBE: u32 = u32::MAX - 2; +/// A buffer of the card's that depth goes through on the way there. +pub const SCRATCH: u32 = u32::MAX - 3; const INDIRECT_ARGUMENT: i32 = 0x200; const UNORDERED_ACCESS: i32 = 0x8; diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index c833679..3c74d1d 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -31,6 +31,7 @@ use super::wire::{ pub mod diverge; mod merge; +pub mod pixel; mod upcopies; /// The name of the argument clamp's pipeline, by which its passes are @@ -359,6 +360,12 @@ pub fn listing(folder: &Path, lists: (u32, u32), line: &mut dyn FnMut(&str)) -> other => format!("{other:?}"), }; line(&format!("buffer {} {} bytes, {place}: {}", r.id, r.desc.width, r.name)); + } else { + let d = &r.desc; + line(&format!( + "texture {} {}x{}x{} mips {} f{}: {}", + r.id, d.width, d.height, d.depth, d.mips, d.format, r.name + )); } } let mut place = 0; @@ -464,6 +471,8 @@ pub struct Player { card_writes: HashSet, /// The results of clamp passes ([`RESULTS`]). results: Option, + /// Other buffers of ours that commands name. + extra: HashMap, commands: Vec>, /// Resources in the states of the start (not those of the end). fresh: bool, @@ -531,6 +540,7 @@ impl Player { merging: false, card_writes: HashSet::new(), results: None, + extra: HashMap::new(), commands, fresh: true, at: States::default(), @@ -628,7 +638,10 @@ impl Player { if id == RESULTS { return self.results.as_ref(); } - self.objects.get(&id).map(|o| &o.res) + self.objects + .get(&id) + .map(|o| &o.res) + .or_else(|| self.extra.get(&id)) } fn va(&self, va: &Va) -> u64 { diff --git a/crates/victory-gpu/src/replay/play/pixel.rs b/crates/victory-gpu/src/replay/play/pixel.rs new file mode 100644 index 0000000..e79fce9 --- /dev/null +++ b/crates/victory-gpu/src/replay/play/pixel.rs @@ -0,0 +1,843 @@ +//! What draws a pixel: `--pixel`. After every command that can change a +//! texture, the texel under the pixel is copied out of it (of a draw: of its +//! targets, where the pixel lies in its viewport, and of the textures shaders +//! may write; of a dispatch: of those; of a copy, clear or resolve: of where +//! it goes), and commands that changed one are named with the values before +//! and after. + +use super::edit::{PROBE, SCRATCH}; +use super::*; + +/// What to look at. +#[derive(Clone, Debug, Default)] +pub struct Pixels { + /// Points of the presented picture. + pub points: Vec<(u32, u32)>, + /// Texels of textures: resource, subresource, place. + pub texels: Vec<(u32, u32, u32, u32)>, + /// Only these lists are looked into. + pub lists: Option<(u32, u32)>, + /// Depth targets too (a copy of the whole target for each draw). + pub depth: bool, + /// Textures shaders may write too. + pub written: bool, + /// Indirect draws that are run one by one: list, command. + pub split: Vec<(u32, u32)>, +} + +/// Bytes a sample has. +const ROOM: u64 = 512; +/// The most samples of one run. +const MOST: usize = 1 << 20; + +#[derive(Clone, Debug)] +struct Sample { + list: u32, + command: usize, + /// Of a split draw: which one. + part: u32, + before: bool, + spot: Spot, + pso: u32, + what: &'static str, +} + +/// A texture's part that a sample can be taken from. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct Spot { + res: u32, + sub: u32, + x: u32, + y: u32, + z: u32, + /// The point of the picture it stands for (or [`OWN`]). + point: usize, + format: i32, + depth: bool, +} + +/// In [`Spot::point`]: a texel asked for by itself. +const OWN: usize = usize::MAX; + +/// The texel of a target of `size` that shows the point `(x, y)` of a picture +/// of `picture`, drawn through `view` (x, y, width, height): none if the +/// target has another shape than the picture. +fn texel( + (x, y): (u32, u32), + picture: (u32, u32), + view: [f32; 4], + size: (u32, u32), +) -> Option<(u32, u32)> { + let (w, h) = (picture.0 as f32, picture.1 as f32); + if !same_shape((view[2], view[3]), (w, h)) || view[2] < 16.0 { + return None; + } + let a = (view[0] + (x as f32 + 0.5) / w * view[2]).floor(); + let b = (view[1] + (y as f32 + 0.5) / h * view[3]).floor(); + (a >= 0.0 && b >= 0.0 && a < size.0 as f32 && b < size.1 as f32).then_some((a as u32, b as u32)) +} + +fn same_shape(a: (f32, f32), b: (f32, f32)) -> bool { + (0.97..1.03).contains(&(a.0 * b.1 / (a.1 * b.0).max(1e-6))) +} + +/// A float from a small one's bits (5 bits of exponent, `mantissa` of +/// mantissa, no sign). +fn small(bits: u32, mantissa: u32) -> f32 { + let (e, m) = ( + bits >> mantissa & 31, + (bits & ((1 << mantissa) - 1)) as f32, + ); + let unit = (1u32 << mantissa) as f32; + match e { + 0 => m / unit * 2f32.powi(-14), + 31 if m == 0.0 => f32::INFINITY, + 31 => f32::NAN, + e => (1.0 + m / unit) * 2f32.powi(e as i32 - 15), + } +} + +/// Bytes of a texel of a format; 0 for formats not read. +fn texel_bytes(format: i32) -> usize { + match format { + 1..=4 => 16, + 5..=8 => 12, + 9..=22 => 8, + 23..=47 => 4, + 48..=59 => 2, + 60..=65 => 1, + 67 | 85..=93 => 4, + _ => 0, + } +} + +/// A texel in words. +fn texel_text(format: i32, b: &[u8]) -> String { + let n = texel_bytes(format); + if n == 0 || b.len() < n { + return format!("{b:02x?}"); + } + let word = |i: usize| u32::from_le_bytes([b[i * 4], b[i * 4 + 1], b[i * 4 + 2], b[i * 4 + 3]]); + let float = |i: usize| f32::from_bits(word(i)); + let short = |i: usize| u16::from_le_bytes([b[i * 2], b[i * 2 + 1]]); + let half = |i: usize| { + let v = small(u32::from(short(i) & 0x7FFF), 10); + if short(i) >> 15 != 0 { -v } else { v } + }; + let unorm16 = |i: usize| f32::from(short(i)) / 65535.0; + let snorm16 = |i: usize| f32::from(short(i) as i16) / 32767.0; + let unorm8 = |i: usize| f32::from(b[i]) / 255.0; + let snorm8 = |i: usize| f32::from(b[i] as i8) / 127.0; + let all: Vec = match format { + 1 | 2 => (0..4).map(float).collect(), + 5 | 6 => (0..3).map(float).collect(), + 9 | 10 => (0..4).map(half).collect(), + 11 => (0..4).map(unorm16).collect(), + 13 => (0..4).map(snorm16).collect(), + 15 | 16 => (0..2).map(float).collect(), + 23 | 24 => vec![ + (word(0) & 1023) as f32 / 1023.0, + (word(0) >> 10 & 1023) as f32 / 1023.0, + (word(0) >> 20 & 1023) as f32 / 1023.0, + (word(0) >> 30) as f32 / 3.0, + ], + 26 => vec![ + small(word(0) & 2047, 6), + small(word(0) >> 11 & 2047, 6), + small(word(0) >> 22, 5), + ], + 27..=29 | 87 | 90 | 91 => (0..4).map(unorm8).collect(), + 31 => (0..4).map(snorm8).collect(), + 33 | 34 => (0..2).map(half).collect(), + 35 => (0..2).map(unorm16).collect(), + 37 => (0..2).map(snorm16).collect(), + 39..=41 => vec![float(0)], + 48 | 49 => (0..2).map(unorm8).collect(), + 51 => (0..2).map(snorm8).collect(), + 53 | 54 => vec![half(0)], + 55 | 56 => vec![unorm16(0)], + 58 => vec![snorm16(0)], + 60 | 61 => vec![unorm8(0)], + 63 => vec![snorm8(0)], + _ => Vec::new(), + }; + let all: Vec = all.iter().map(|v| format!("{v:.5}")).collect(); + format!("{} {:02x?}", all.join(" "), &b[..n]).trim().to_owned() +} + +/// One draw of an indirect call that has many. +fn part_of(c: &Cmd, i: u32, stride: u32) -> Cmd { + match c { + Cmd::Indirect { + signature, + args, + at, + .. + } => Cmd::Indirect { + signature: *signature, + most: 1, + args: *args, + at: at + u64::from(i) * u64::from(stride), + count: NONE, + count_at: 0, + }, + c => c.clone(), + } +} + +fn transition(res: u32, sub: u32, before: u32, after: u32) -> Barrier { + Barrier::Transition { + flags: 0, + res, + sub, + before: before as i32, + after: after as i32, + } +} + +/// What is known of the frame's textures. +struct Textures { + /// Formats copies have. + copied_as: HashMap, + /// Textures shaders may write and that have the picture's shape. + shaped: Vec, + /// The viewport targets of a size were last drawn through. + drawn: HashMap<(u32, u32), [f32; 4]>, +} + +impl Player { + fn texture(&self, id: u32) -> Option<&wire::Resource> { + let o = self.objects.get(&id)?; + let r = &self.frame.resources[o.index]; + (r.desc.dimension != D3D12_RESOURCE_DIMENSION_BUFFER.0 && r.desc.samples[0] <= 1) + .then_some(r) + } + + /// What a view of a target is of: subresource, depth slice, size, format. + fn seen_by(&self, s: &Slot) -> Option<(u32, u32, (u32, u32), i32)> { + let r = self.texture(s.res)?; + let word = |i: usize| { + u32::from_le_bytes([ + s.desc[i * 4], + s.desc[i * 4 + 1], + s.desc[i * 4 + 2], + s.desc[i * 4 + 3], + ]) + }; + let (mut mip, mut slice, mut z, mut format) = (0, 0, 0, 0); + if s.described != 0 { + format = word(0) as i32; + match (s.kind, word(1) as i32) { + // 2D, 2D array and 3D views. + (slot::RTV, 4) => mip = word(2), + (slot::RTV, 5) => (mip, slice) = (word(2), word(3)), + (slot::RTV, 8) => (mip, z) = (word(2), word(3)), + (slot::DSV, 3) => mip = word(3), + (slot::DSV, 4) => (mip, slice) = (word(3), word(4)), + _ => return None, + } + } + if format == 0 { + format = r.desc.format; + } + let mips = u32::from(r.desc.mips.max(1)); + let mip = mip.min(mips - 1); + let size = ( + (r.desc.width as u32 >> mip).max(1), + (r.desc.height >> mip).max(1), + ); + Some((mip + slice * mips, z, size, format)) + } + + /// Width and height of the presented picture. + pub fn picture_size(&self) -> Option<(u32, u32)> { + self.frame.presents.last().map(|p| (p.width, p.height)) + } + + /// Says which commands change the texels under points of the picture. + pub fn pixel(&mut self, o: &Options, p: &Pixels, say: &mut dyn FnMut(String)) -> Result<()> { + let picture = self.picture_size().context("no picture was presented")?; + self.set_merging(o.merge)?; + let mut report = Report::default(); + let submits = self.edited(o, &mut report, &[]); + let counts = self.counts_of(o, p, &submits)?; + let mut samples: Vec = Vec::new(); + let made = self.sampled(p, &submits, picture, &counts, &mut samples)?; + let bytes = self.probed(o, &made, samples.len() as u64 * ROOM)?; + say(format!( + "{} texels taken; picture {}x{}; points {:?}", + samples.len(), + picture.0, + picture.1, + p.points + )); + report.notes.drain(..).for_each(&mut *say); + let mut last: HashMap<(u32, u32, (u32, u32), usize), Vec> = HashMap::new(); + let mut said = None; + for (i, s) in samples.iter().enumerate() { + let t = &s.spot; + let n = texel_bytes(t.format).max(1); + let now = bytes[i * ROOM as usize..][..n].to_vec(); + let was = last.insert((t.res, t.sub, (t.x, t.y), t.point), now.clone()); + if was.as_ref() == Some(&now) { + continue; + } + let point = match t.point { + OWN => String::new(), + n => format!("point {n} "), + }; + let spot = format!( + " {point}{} sub {} at {},{}:", + self.called(t.res), + t.sub, + t.x, + t.y + ); + let now = texel_text(t.format, &now); + if s.before { + // Seen for the first time, or changed by what is not looked + // into. + if was.is_some() { + say(format!("{spot} changed unseen to {now}")); + } + continue; + } + if said != Some((s.list, s.command, s.part)) { + said = Some((s.list, s.command, s.part)); + let part = match p.split.contains(&(s.list, s.command as u32)) { + true => format!(" draw {}", s.part), + false => String::new(), + }; + let of = match s.pso { + NONE => String::new(), + pso => format!(" of {pso} {}", self.pipeline_name(pso)), + }; + say(format!("{}:{}{part} {}{of}", s.list, s.command, s.what)); + } + let was = was.map_or("?".to_owned(), |w| texel_text(t.format, &w)); + say(format!("{spot} {was} -> {now}")); + } + Ok(()) + } + + /// Runs the frame with commands that copy to [`PROBE`], which is of + /// `len` bytes; its bytes after that. + fn probed(&mut self, o: &Options, submits: &[Vec>], len: u64) -> Result> { + let (back, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_READBACK, + len.max(4), + D3D12_RESOURCE_FLAG_NONE, + )?; + self.extra.insert(PROBE, back); + self.restore(o.restore)?; + let built = self.build(submits, o)?; + self.fresh = false; + self.send(&built, o)?; + // SAFETY: the mapping; the copies into it have run. + let bytes = unsafe { std::slice::from_raw_parts(data, len as usize) }.to_vec(); + self.extra.remove(&PROBE); + Ok(bytes) + } + + /// How many draws the calls to be split have. + fn counts_of( + &mut self, + o: &Options, + p: &Pixels, + submits: &[Vec>], + ) -> Result> { + let mut counts = HashMap::new(); + if p.split.is_empty() { + return Ok(counts); + } + const ARGS: u32 = 0x200; + let mut made = submits.to_vec(); + let mut asked: Vec<(u32, u32)> = Vec::new(); + for (here, cmds) in made.iter_mut().flatten().enumerate() { + let mut out = Vec::new(); + for (n, c) in std::mem::take(cmds).into_iter().enumerate() { + let key = (here as u32, n as u32); + if let Cmd::Indirect { + most, + count, + count_at, + .. + } = c + && p.split.contains(&key) + { + counts.insert(key, most); + if count != NONE { + out.push(Cmd::Barriers { + all: vec![transition(count, ALL, ARGS, COPY_SOURCE)], + }); + out.push(Cmd::CopyBuffer { + dst: PROBE, + dst_at: asked.len() as u64 * 4, + src: count, + src_at: count_at, + len: 4, + }); + out.push(Cmd::Barriers { + all: vec![transition(count, ALL, COPY_SOURCE, ARGS)], + }); + asked.push(key); + } + } + out.push(c); + } + *cmds = out; + } + let bytes = self.probed(o, &made, asked.len() as u64 * 4)?; + for (key, n) in asked.iter().zip(bytes.chunks_exact(4)) { + if let Some(most) = counts.get_mut(key) { + *most = (*most).min(u32::from_le_bytes([n[0], n[1], n[2], n[3]])); + } + } + Ok(counts) + } + + fn textures(&self, picture: (u32, u32)) -> Textures { + let textures = || { + self.frame + .resources + .iter() + .filter(|r| self.texture(r.id).is_some()) + }; + let shaped = textures() + .filter(|r| { + let d = &r.desc; + d.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D.0 + && d.flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0 + && d.width as u32 * 4 >= picture.0 + && same_shape( + (d.width as f32, d.height as f32), + (picture.0 as f32, picture.1 as f32), + ) + }) + .map(|r| r.id) + .collect(); + let copied_as = textures() + .map(|r| { + let f = gpu::footprints(&self.device, &gpu::to_desc(&r.desc), 0, 1).0; + (r.id, f[0].Footprint.Format.0) + }) + .collect(); + Textures { + copied_as, + shaped, + drawn: HashMap::new(), + } + } + + /// The spots of a texture (of its subresource `sub`) that is written not + /// as a target. + fn spots_of( + &self, + p: &Pixels, + t: &Textures, + picture: (u32, u32), + id: u32, + sub: u32, + out: &mut Vec, + ) { + let Some(r) = self.texture(id) else { return }; + let depth = r.desc.flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0; + for &(res, at, x, y) in &p.texels { + if res == id && (sub == at || sub == ALL) { + out.push(Spot { + res, + sub: at, + x, + y, + z: 0, + point: OWN, + format: r.desc.format, + depth, + }); + } + } + if r.desc.dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D.0 || !(sub == 0 || sub == ALL) { + return; + } + let size = (r.desc.width as u32, r.desc.height); + let whole = [0.0, 0.0, size.0 as f32, size.1 as f32]; + let view = t.drawn.get(&size).copied().unwrap_or(whole); + for (point, at) in p.points.iter().enumerate() { + if let Some((x, y)) = texel(*at, picture, view, size) { + out.push(Spot { + res: id, + sub: 0, + x, + y, + z: 0, + point, + format: r.desc.format, + depth, + }); + } + } + } + + /// Whether a texture is the one in use of those that share its memory. + fn in_use(&self, states: &States, id: u32) -> bool { + self.objects.get(&id).is_some_and(|o| { + !self.frame.resources[o.index].idle || states.used.contains_key(&id) + }) + } + + /// The commands that copy the texels of `spots` to [`PROBE`] from `first` + /// on; `copied`: a copy to them went before. + fn take( + &self, + spots: &[Spot], + first: u64, + states: &States, + t: &Textures, + copied: bool, + scratch: &mut u64, + out: &mut Vec, + ) { + let (mut to, mut from, mut copies) = (Vec::new(), Vec::new(), Vec::new()); + let mut moved = HashSet::new(); + for (i, s) in spots.iter().enumerate() { + let Some(r) = self.texture(s.res) else { + continue; + }; + let all = states.get(s.res).unwrap_or(vec![COMMON]); + let mut state = all + .get(s.sub as usize) + .or(all.first()) + .copied() + .unwrap_or(COMMON); + if copied && state == COMMON { + state = COPY_DEST; + } + if state & COPY_SOURCE == 0 && moved.insert((s.res, s.sub)) { + to.push(transition(s.res, s.sub, state, COPY_SOURCE)); + from.push(transition(s.res, s.sub, COPY_SOURCE, state)); + } + let offset = (first + i as u64) * ROOM; + if !s.depth { + copies.push(Cmd::CopyTexture { + dst: Loc::Placed { + res: PROBE, + offset, + format: t.copied_as.get(&s.res).copied().unwrap_or(r.desc.format), + size: [1, 1, 1], + pitch: 256, + }, + at: [0; 3], + src: Loc::Sub { + res: s.res, + sub: s.sub, + }, + part: Some([s.x, s.y, s.z, s.x + 1, s.y + 1, s.z + 1]), + }); + continue; + } + // Depth is only copied whole. + let mip = s.sub % u32::from(r.desc.mips.max(1)); + let w = (r.desc.width as u32 >> mip).max(1); + let h = (r.desc.height >> mip).max(1); + let bytes = texel_bytes(s.format) as u64; + let pitch = (w * bytes as u32).next_multiple_of(256); + *scratch = (*scratch).max(u64::from(pitch) * u64::from(h)); + copies.push(Cmd::CopyTexture { + dst: Loc::Placed { + res: SCRATCH, + offset: 0, + format: t.copied_as.get(&s.res).copied().unwrap_or(r.desc.format), + size: [w, h, 1], + pitch, + }, + at: [0; 3], + src: Loc::Sub { + res: s.res, + sub: s.sub, + }, + part: None, + }); + copies.push(Cmd::Barriers { + all: vec![transition(SCRATCH, ALL, COPY_DEST, COPY_SOURCE)], + }); + copies.push(Cmd::CopyBuffer { + dst: PROBE, + dst_at: offset, + src: SCRATCH, + src_at: u64::from(pitch) * u64::from(s.y) + u64::from(s.x) * bytes, + len: bytes, + }); + copies.push(Cmd::Barriers { + all: vec![transition(SCRATCH, ALL, COPY_SOURCE, COPY_DEST)], + }); + } + if !to.is_empty() { + out.push(Cmd::Barriers { all: to }); + } + out.extend(copies); + if !from.is_empty() { + out.push(Cmd::Barriers { all: from }); + } + } + + /// The frame's lists with copies of texels after commands. + fn sampled( + &mut self, + p: &Pixels, + submits: &[Vec>], + picture: (u32, u32), + counts: &HashMap<(u32, u32), u32>, + samples: &mut Vec, + ) -> Result>>> { + let strides: HashMap = self + .frame + .signatures + .iter() + .map(|s| (s.id, s.stride)) + .collect(); + let dispatching: HashSet = self + .frame + .signatures + .iter() + .filter(|s| { + s.args + .iter() + .any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32) + }) + .map(|s| s.id) + .collect(); + let mut t = self.textures(picture); + let mut states = self.start_states(); + let mut known: HashSet = HashSet::new(); + let mut made = Vec::new(); + let mut here = 0; + let mut scratch = 0u64; + for lists in submits { + let mut out_lists = Vec::new(); + for cmds in lists { + let wanted = p.lists.is_none_or(|(a, b)| (a..=b).contains(&here)); + let mut out = Vec::with_capacity(cmds.len()); + let mut pso = NONE; + let mut targets: Vec = Vec::new(); + let mut view: Option<[f32; 4]> = None; + for (n, c) in cmds.iter().enumerate() { + match c { + Cmd::Pipeline { pso: id } => pso = *id, + Cmd::Targets { colors, depth } => { + targets = colors.iter().chain(depth).copied().collect(); + } + Cmd::Viewports { all } => { + view = all.first().map(|v| [v[0], v[1], v[2], v[3]]); + } + _ => {} + } + let dispatches = matches!(c, Cmd::Dispatch { .. }) + || matches!(c, Cmd::Indirect { signature, .. } if dispatching.contains(signature)); + let draws = c.runs_shaders() && !dispatches; + let mut spots: Vec = Vec::new(); + let looked = wanted && c.works() && samples.len() < MOST; + for s in targets.iter().filter(|_| looked && draws) { + let Some((sub, z, size, format)) = self.seen_by(s) else { + continue; + }; + let depth = s.kind == slot::DSV; + let spot = |x, y, point| Spot { + res: s.res, + sub, + x, + y, + z, + point, + format, + depth, + }; + let view = view.unwrap_or([0.0, 0.0, size.0 as f32, size.1 as f32]); + for (point, at) in p.points.iter().enumerate() { + if let Some((x, y)) = texel(*at, picture, view, size) { + t.drawn.insert(size, view); + spots.push(spot(x, y, point)); + } + } + for &(res, at, x, y) in &p.texels { + if (res, at) == (s.res, sub) { + spots.push(spot(x, y, OWN)); + } + } + } + if looked && c.runs_shaders() { + let all = p.texels.iter().map(|t| t.0); + let some = p.written && (dispatches || !targets.is_empty()); + let all: HashSet = + all.chain(t.shaped.iter().copied().filter(|_| some)).collect(); + for id in all { + let writable = states + .get(id) + .is_some_and(|s| s.iter().any(|s| s & UNORDERED_ACCESS != 0)); + if writable && self.in_use(&states, id) { + self.spots_of(p, &t, picture, id, ALL, &mut spots); + } + } + } + let mut copied = false; + if looked { + let mut to = None; + match c { + Cmd::CopyTexture { + dst: Loc::Sub { res, sub }, + .. + } => to = Some((*res, *sub, true)), + Cmd::CopyResource { dst, .. } => to = Some((*dst, ALL, true)), + Cmd::Resolve { dst, dst_sub, .. } + | Cmd::ResolveRegion { dst, dst_sub, .. } => { + to = Some((*dst, *dst_sub, false)); + } + Cmd::ClearTarget { view, .. } | Cmd::ClearDepth { view, .. } => { + to = self.seen_by(view).map(|s| (view.res, s.0, false)); + } + _ => {} + } + if let Some((res, sub, is_copy)) = to { + copied = is_copy; + self.spots_of(p, &t, picture, res, sub, &mut spots); + } + } + let mut seen = HashSet::new(); + spots.retain(|s| { + (p.depth || !s.depth) && texel_bytes(s.format) > 0 && seen.insert(*s) + }); + let what = match c { + Cmd::Draw { .. } => "Draw", + Cmd::DrawIndexed { .. } => "DrawIndexed", + Cmd::DispatchMesh { .. } => "DispatchMesh", + Cmd::Dispatch { .. } => "Dispatch", + Cmd::Indirect { .. } if dispatches => "indirect Dispatch", + Cmd::Indirect { .. } => "indirect draw", + Cmd::ClearTarget { .. } | Cmd::ClearDepth { .. } => "clear", + Cmd::Resolve { .. } | Cmd::ResolveRegion { .. } => "resolve", + _ => "copy", + }; + let runs = if c.runs_shaders() { pso } else { NONE }; + let mut take = |before: bool, part: u32, spots: &[Spot], out: &mut Vec| { + let first = samples.len() as u64; + self.take(spots, first, &states, &t, copied && !before, &mut scratch, out); + samples.extend(spots.iter().map(|spot| Sample { + list: here, + command: n, + part, + before, + spot: *spot, + pso: runs, + what, + })); + }; + // What was not seen before this command, as it is now. + let new: Vec = + spots.iter().filter(|s| known.insert(**s)).copied().collect(); + if !new.is_empty() { + take(true, 0, &new, &mut out); + } + match (counts.get(&(here, n as u32)), c) { + (Some(&count), Cmd::Indirect { signature, .. }) => { + let stride = strides.get(signature).copied().unwrap_or(0); + for i in 0..count { + out.push(part_of(c, i, stride)); + take(false, i, &spots, &mut out); + } + } + _ => { + out.push(c.clone()); + if !spots.is_empty() { + take(false, 0, &spots, &mut out); + } + } + } + let mut all = Vec::new(); + states::changes(c, &mut all); + all.iter().for_each(|c| states.change(c)); + } + out_lists.push(out); + here += 1; + } + states.decay(); + made.push(out_lists); + } + if scratch > 0 { + let buffer = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_DEFAULT, + scratch, + D3D12_RESOURCE_FLAG_NONE, + )?; + self.extra.insert(SCRATCH, buffer.0); + } + Ok(made) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn points_lie_in_viewports_of_the_pictures_shape() { + let whole = |w: u32, h: u32| ([0.0, 0.0, w as f32, h as f32], (w, h)); + let picture = (3840, 2160); + let (view, size) = whole(1920, 1080); + assert_eq!(texel((3839, 2159), picture, view, size), Some((1919, 1079))); + assert_eq!(texel((0, 0), picture, view, size), Some((0, 0))); + let (view, size) = whole(2048, 2048); + assert_eq!(texel((0, 0), picture, view, size), None); + // A part of a larger target. + let part = [0.0, 0.0, 1920.0, 1080.0]; + assert_eq!( + texel((1920, 1080), picture, part, (3840, 2160)), + Some((960, 540)) + ); + let beside = [1920.0, 0.0, 1920.0, 1080.0]; + assert_eq!(texel((1920, 1080), picture, beside, (1920, 1080)), None); + } + + #[test] + fn texels_are_read() { + assert_eq!( + texel_text(41, &1.5f32.to_le_bytes()), + "1.50000 [00, 00, c0, 3f]" + ); + assert_eq!( + texel_text(28, &[255, 0, 0, 51]), + "1.00000 0.00000 0.00000 0.20000 [ff, 00, 00, 33]" + ); + assert!( + texel_text(10, &[0, 0x3C, 0, 0xBC, 0, 0, 0, 0x38]) + .starts_with("1.00000 -1.00000 0.00000 0.50000 ") + ); + let v = 0x3C0u32 | 0x380 << 11 | 0x200 << 22; + assert!(texel_text(26, &v.to_le_bytes()).starts_with("1.00000 0.50000 2.00000 ")); + assert_eq!(texel_text(42, &[1, 2, 3, 4]), "[01, 02, 03, 04]"); + // Too few bytes, or a format that is not read. + assert_eq!(texel_text(41, &[1]), "[01]"); + assert_eq!(texel_text(98, &[1, 2]), "[01, 02]"); + } + + #[test] + fn an_indirect_draw_is_taken_apart() { + let all = Cmd::Indirect { + signature: 1, + most: 8, + args: 2, + at: 100, + count: 3, + count_at: 4, + }; + let one = Cmd::Indirect { + signature: 1, + most: 1, + args: 2, + at: 124, + count: NONE, + count_at: 0, + }; + assert_eq!(part_of(&all, 2, 12), one); + } +} diff --git a/docs/replay.md b/docs/replay.md index a132db3..87ac4f8 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -77,6 +77,30 @@ leaves out waits or work can draw another picture and, with wild data, lose the device: save work in other programs first. Do not run the title at the same time. +## What draws a pixel + + victory replay --pixel 1234,567 [--of 1280x720] [--lists 40..80] + +runs the frame once with copies of the texel under the point after every +command that can change it, and names each command that did with its pipeline +(id, name, DXIL hashes) and the values before and after: draws with their +targets (where the viewport has the picture's shape), dispatches and draws with +the textures of the picture's shape shaders may write at that time, copies, +resolves and clears. `--of` is the size of the picture the point was read from +(a screenshot's). The commands are numbered `:` as in +`--listing`, `--slots` and `--looks`. + +| switch | does | +|---|---| +| `--pixel [.]:,` | a texel of one texture instead (repeatable, both kinds) | +| `--depth` | depth targets too: the whole target is copied after each draw | +| `--targets-only` | no textures of unordered access: fewer copies | +| `--split :` | the draws of that indirect call one by one, each named | +| `--lists 40..80` | only these lists are looked into | + +A texture that was changed by what is not looked into is reported as "changed +unseen". Copies of 3D textures' targets are of the slice drawn to. + ## Runs that differ Shaders that give out places with atomics (the title's culling) give other From 5b422ba020e7f59da4ba545e76f008ca5bc33a28 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:51:11 -0600 Subject: [PATCH 191/445] wip: submissions send their own bytes --- crates/victory-gpu/src/host.rs | 45 ++++- crates/victory-gpu/src/host/send.rs | 261 +++++++++++++++++++++++++ crates/victory-gpu/src/host/upcheck.rs | 182 +++++++++++++++-- crates/victory-gpu/src/picked.rs | 22 ++- crates/victory-gpu/src/shadow.rs | 88 ++++++++- 5 files changed, 575 insertions(+), 23 deletions(-) create mode 100644 crates/victory-gpu/src/host/send.rs diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 7023d67..a982d5c 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1704,6 +1704,8 @@ struct CardPlan { sent_as: u64, /// With [`upcheck`]: the look at what it sent up. looks: Option, + /// With [`send`]: the memory its sends come from. + sends: Option, } /// One piece of submission-time work, in recorded order. @@ -2957,6 +2959,17 @@ fn late_line(frames: f64) { r[3] / 1000.0, r[4] / 1000.0, ); + if send::own() { + let t: Vec = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "bytes of submissions' own sent up per frame (VICTORY_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \ + taking them out of the CPU sides", + t[0] / (1 << 20) as f64, + t[1], + t[2], + t[3] / 1000.0, + ); + } let t: Vec = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); if t[0] > 0.0 { tracing::info!( @@ -2983,6 +2996,7 @@ fn late_line(frames: f64) { } mod card_steps; +mod send; mod torn; pub(crate) mod upcheck; @@ -3517,7 +3531,7 @@ impl Host { } } } - let declared = crate::picked::with(declared, &picked.written); + 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> = picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect(); @@ -3554,6 +3568,8 @@ impl Host { } let mut used: Vec<(bool, Prelude)> = Vec::new(); let mut looks = None; + // The bytes as they are now, whatever later submissions put there. + let own = if send::own() { send::take(self, &dirty) } else { None }; if !dirty.is_empty() { let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else { fail(format_args!("no host list to bring host copies in the card's memory up to date")); @@ -3573,16 +3589,21 @@ impl Host { // pass: a wait between each copy and its pass had the // card do them one after the other. let mut sent = Vec::new(); + if let Some(own) = &own { + own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow))); + } for (shadow, ranges) in &dirty { let Some((staging, before, _)) = shadow.card_sides() else { continue; }; for &(a, b) in ranges { - list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64); + if own.is_none() { + list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64); + } 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); - if before.is_some() && !ranges.is_empty() { + if own.is_none() && before.is_some() && !ranges.is_empty() { sent.push(transition( &shadow.buffer, D3D12_RESOURCE_STATE_COPY_DEST, @@ -3614,7 +3635,7 @@ impl Host { ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect() }; // The same pieces in fewer passes (`rehash_runs`). - let runs = if rehash_runs() { crate::shadow::joined_piece_runs(runs) } else { runs }; + let runs = if rehash_runs() || own.is_some() { crate::shadow::joined_piece_runs(runs) } else { runs }; CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed); CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::(), Ordering::Relaxed); for run in runs { @@ -3639,6 +3660,7 @@ impl Host { lists: used, sent_as, looks, + sends: own.map(send::Own::memory), }; // Each byte once, as the copy-back joins the declared ranges. The // results go behind those of plans still in the air. @@ -3759,6 +3781,9 @@ impl Host { if let Some(looks) = plan.looks { looks.read(); } + if let Some(memory) = plan.sends { + send::give_back(memory); + } let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); let Some(work) = work.as_mut() else { return; @@ -4728,8 +4753,11 @@ impl Host { // may write too, and this submission refreshes it. The flights // are settled, and the asking made again: the copy-back wrote // title memory, which other copies of it must see. - if behind && upcheck::on() { - upcheck::reads(runs); + if upcheck::on() { + upcheck::order(runs); + if behind { + upcheck::reads(runs); + } } let stale = if behind { stale_under_flights(runs) } else { Vec::new() }; if !stale.is_empty() { @@ -6106,6 +6134,11 @@ impl HostList { copy_mapped(dst as *mut u8, src as *const u8, len, true); // With the submission's one asking: the journal learns it. crate::watch::wrote(dst, len); + // What the card holds there may be another value although + // ours did not change. + if send::own() { + crate::shadow::send_copied(dst, len); + } (started, len) } &Step::Fill(dst, src, len, _) => { diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs new file mode 100644 index 0000000..9227399 --- /dev/null +++ b/crates/victory-gpu/src/host/send.rs @@ -0,0 +1,261 @@ +//! What goes up to copies in the card's memory goes up as it was when its +//! submission was prepared (`VICTORY_SEND_OWN`, on by default; `0`: as +//! before). +//! +//! The sends were copies out of the copies' CPU sides, which the card makes +//! when it comes to the submission. By then later submissions are prepared +//! (two frames of them with `VICTORY_RELAY`), and their refreshes have +//! written the same CPU sides: the earlier submission's shaders then read a +//! later one's bytes. For what the title's CPU writes that is as on the +//! console (it does not write what the card still reads). But the title's +//! own buffer copies are commands in its lists, and those are done by us +//! when a submission is prepared: "a value to a buffer, a draw that reads +//! it" in one submission and the same with another value in the next is +//! ordinary, and both draws read the second value. +//! +//! So each submission's bytes are taken out of the CPU sides into memory of +//! the submission's own when they are taken from the dirty lists, and the +//! card copies them from there. Runs of a few words, which a refresh that +//! sends only what changed makes many of, go as pairs of offset and value, +//! stored by one dispatch per copy; the others as a copy each. + +use super::*; +use crate::shadow::Shadow; + +pub(super) fn own() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SEND_OWN").is_none_or(|v| v != "0")) +} + +/// Runs up to this many bytes go as pairs. +const SHORT: usize = 256; + +const SCATTER: &str = r#" +#define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0)" +cbuffer Part : register(b0) { uint at; uint count; }; +ByteAddressBuffer pairs : register(t0); +RWByteAddressBuffer card : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= count) return; + uint2 p = pairs.Load2(at + id.x * 8u); + card.Store(p.x, p.y); +} +"#; + +struct Pass { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +fn pass(host: &Host) -> Option<&'static Pass> { + static PASS: OnceLock> = OnceLock::new(); + PASS.get_or_init(|| { + let code = compile(SCATTER, windows::core::s!("main"), windows::core::s!("cs_5_1")).ok()?; + // SAFETY: the code lives through the calls; the root signature is + // inside it. + unsafe { + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).ok()?; + let pso: ID3D12PipelineState = host + .device + .CreateComputePipelineState(&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() + }) + .ok()?; + name(&pso, || "victory: changed words sent to the card".into()); + Some(Pass { root, pso }) + } + }) + .as_ref() +} + +/// Memory a submission's sends come from, mapped. +pub(super) struct Memory { + buffer: ID3D12Resource, + data: usize, + size: u64, +} + +// SAFETY: a D3D12 object (free-threaded) and its mapping, with one owner. +unsafe impl Send for Memory {} + +/// What submissions that have run gave back. +static SPARE: Mutex> = Mutex::new(Vec::new()); + +/// At most this much is kept. +const KEPT: u64 = 768 << 20; + +fn memory(host: &Host, size: u64) -> Option { + { + let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + let fit = spare.iter().enumerate().filter(|(_, m)| m.size >= size).min_by_key(|(_, m)| m.size).map(|(i, _)| i); + if let Some(i) = fit { + return Some(spare.swap_remove(i)); + } + } + let size = size.next_multiple_of(8 << 20); + let (buffer, data) = host.upload_buffer(size)?; + name(&buffer, || "bytes a submission sends up".into()); + Some(Memory { + buffer, + data: data as usize, + size, + }) +} + +/// The submission has run. +pub(super) fn give_back(memory: Memory) { + let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + spare.push(memory); + spare.sort_by_key(|m| std::cmp::Reverse(m.size)); + while spare.iter().map(|m| m.size).sum::() > KEPT { + spare.remove(0); + } +} + +/// Since the last frame-rate line: bytes copied, runs copied, words stored, +/// microseconds of taking them out of the CPU sides. +pub(super) static STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// One copy's sends: ranges copied (offset in the copy, in the memory, +/// bytes), and its pairs (where in the memory, how many). +struct Copy { + runs: Vec<(usize, u64, usize)>, + pairs: (u64, u32), +} + +/// Where a submission's bytes are taken to. +pub(super) struct Own { + memory: Memory, + copies: Vec, +} + +/// 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(); + pass(host)?; + // Runs of whole words of the copy: only those are pairs. (A byte beside + // them in a word may be the card's.) + let short = |&(a, b): &(usize, usize)| b - a <= SHORT && a % 4 == 0 && b % 4 == 0; + let mut at = 0u64; + let mut copies = Vec::with_capacity(dirty.len()); + for (_, ranges) in dirty { + let mut runs = Vec::new(); + for &(a, b) in ranges.iter().filter(|r| !short(r)) { + runs.push((a, at, b - a)); + at += ((b - a) as u64).next_multiple_of(16); + } + let words: usize = ranges.iter().filter(|r| short(r)).map(|r| (r.1 - r.0) / 4).sum(); + copies.push(Copy { runs, pairs: (at, words as u32) }); + at += (words as u64 * 8).next_multiple_of(16); + } + if at == 0 { + return None; + } + let memory = memory(host, at)?; + let mut moves: Vec<(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]; + 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. + unsafe { + let word = ((from + offset) as *const u32).read_unaligned(); + to.write([offset as u32, word]); + to = to.add(1); + } + } + } + } + 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); + crate::shadow::copy_all(moves); + STATS[3].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); + Some(Own { memory, copies }) +} + +impl Own { + /// Records the sends into `list`; the copies that `looked` says are in + /// `COPY_DEST`, the others in the common state. Those with a "before" are + /// left readable by compute shaders. + /// + /// # Safety + /// An open list of ours, whose compute state is set anew behind this. + pub(super) unsafe fn record( + &self, + host: &Host, + list: &ID3D12GraphicsCommandList, + dirty: &[(std::sync::Arc, Vec<(usize, usize)>)], + looked: impl Fn(&Shadow) -> bool, + ) { + let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + let write = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + let dest = D3D12_RESOURCE_STATE_COPY_DEST; + let (mut first, mut last) = (Vec::new(), Vec::new()); + for ((shadow, _), copy) in dirty.iter().zip(&self.copies) { + for &(a, from, n) in ©.runs { + // SAFETY: the caller's; live buffers, ranges inside them. + unsafe { list.CopyBufferRegion(&shadow.buffer, a as u64, &self.memory.buffer, from, n as u64) }; + } + let mut state = (looked(shadow) || !copy.runs.is_empty()).then_some(dest); + if copy.pairs.1 > 0 { + if let Some(was) = state { + first.push(transition(&shadow.buffer, was, write)); + } + state = Some(write); + } + let hashed = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); + if let Some(was) = state + && hashed + && (!copy.runs.is_empty() || copy.pairs.1 > 0) + { + last.push(transition(&shadow.buffer, was, read)); + } + } + // SAFETY: the caller's; live objects. + unsafe { + if !first.is_empty() { + list.ResourceBarrier(&first); + } + if let Some(pass) = pass(host) + && self.copies.iter().any(|c| c.pairs.1 > 0) + { + list.SetComputeRootSignature(&pass.root); + list.SetPipelineState(&pass.pso); + list.SetComputeRootShaderResourceView(1, self.memory.buffer.GetGPUVirtualAddress()); + for ((shadow, _), copy) in dirty.iter().zip(&self.copies).filter(|(_, c)| c.pairs.1 > 0) { + list.SetComputeRootUnorderedAccessView(2, shadow.buffer.GetGPUVirtualAddress()); + const MOST: u32 = 64 * D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; + let (at, words) = copy.pairs; + let mut done = 0; + while done < words { + let n = (words - done).min(MOST); + let constants = [at as u32 + done * 8, n]; + list.SetComputeRoot32BitConstants(0, 2, constants.as_ptr().cast(), 0); + list.Dispatch(n.div_ceil(64), 1, 1); + done += n; + } + } + } + if !last.is_empty() { + list.ResourceBarrier(&last); + } + } + } + + /// The memory, to be kept until the submission has run. + pub(super) fn memory(self) -> Memory { + self.memory + } +} diff --git a/crates/victory-gpu/src/host/upcheck.rs b/crates/victory-gpu/src/host/upcheck.rs index b9bf815..a33346b 100644 --- a/crates/victory-gpu/src/host/upcheck.rs +++ b/crates/victory-gpu/src/host/upcheck.rs @@ -112,12 +112,21 @@ pub(crate) fn note(copy: u64, at: usize, was: &[u8], new: &[u8]) { if n == 0 { return; } + let at = at + skip; + let (mut was, new) = (was[skip..skip + n].to_vec(), new[skip..skip + n].to_vec()); let mut noted = NOTED.lock().unwrap_or_else(|e| e.into_inner()); - noted.entry(copy).or_default().push(Taken { - at: at + skip, - was: was[skip..skip + n].to_vec(), - new: new[skip..skip + n].to_vec(), - }); + let noted = noted.entry(copy).or_default(); + // What was noted before in this submission has not gone up yet: the card + // knows what stood there before that. And what it took is not what goes + // up where this took it again. + for t in noted.iter_mut() { + let (a, b) = (at.max(t.at), (at + n).min(t.at + t.was.len())); + if a < b { + was[a - at..b - at].copy_from_slice(&t.was[a - t.at..b - t.at]); + t.new[a - t.at..b - t.at].copy_from_slice(&new[a - at..b - at]); + } + } + noted.push(Taken { at, was, new }); } /// A submission's look at what it sends up, until it has run. @@ -202,6 +211,11 @@ pub(super) fn record( } impl Looks { + /// Whether `shadow` was looked at: it is left in `COPY_DEST`. + pub(super) fn hold(&self, shadow: &Shadow) -> bool { + self.of.iter().any(|(s, _)| s.id() == shadow.id()) + } + /// The submission has run: what it found is counted. pub(super) fn read(self) { // SAFETY: the mapping holds an answer for each; the card has run. @@ -354,6 +368,69 @@ pub(super) fn reads(runs: &[&HostList]) { } } +/// The title's buffer copies that are out of their place in a submission: +/// by what is wrong, bytes and destination: how often, the last source, and +/// (for shader writes) how much was declared. +type Misplaced = BTreeMap<(&'static str, usize, usize), (u64, usize, usize)>; +static MISPLACED: Mutex<(u64, Misplaced)> = Mutex::new((0, BTreeMap::new())); + +/// A submission is about to be prepared: its title buffer copies are done on +/// the CPU then, all of them before the first of its draws runs. Where that +/// is not the order of its lists: what an earlier draw of it reads of the +/// destination, or shaders of it write there, or an earlier copy of it put +/// there for what lies between; and a source that shaders of it write first. +pub(super) fn order(runs: &[&HostList]) { + let (mut read, mut written, mut copied): (Vec<(usize, usize)>, Vec<(usize, usize)>, Vec<(usize, usize)>) = + (Vec::new(), Vec::new(), Vec::new()); + let meets = |all: &[(usize, usize)], from: usize, to: usize| all.iter().rev().find(|r| r.0 < to && from < r.1).copied(); + let mut misplaced = MISPLACED.lock().unwrap_or_else(|e| e.into_inner()); + for list in runs { + for step in &list.deferred().copies { + match step { + Step::Refresh(_, at, len) => read.push((*at, *at + *len)), + Step::GpuWrite(_, at, len) => written.push((*at, *at + *len)), + &Step::Copy(dst, src, len) => { + let mut say = |what: &'static str, range: (usize, usize)| { + let e = misplaced.1.entry((what, len, dst)).or_default(); + *e = (e.0 + 1, src, range.1 - range.0); + }; + if let Some(r) = meets(&written, src, src + len) { + say("its source is declared written earlier in the submission", r); + } + if let Some(r) = meets(&written, dst, dst + len) { + say("its destination is declared written earlier in the submission", r); + } + if let Some(r) = meets(&copied, dst, dst + len) { + say("its destination is copied to earlier in the submission", r); + } else if let Some(r) = meets(&read, dst, dst + len) { + say("its destination is read earlier in the submission", r); + } + copied.push((dst, dst + len)); + } + _ => {} + } + } + } + let now = now_ms(); + if now < misplaced.0 + 4000 { + return; + } + misplaced.0 = now; + let mut all: Vec<_> = std::mem::take(&mut misplaced.1).into_iter().collect(); + all.sort_by_key(|(_, e)| std::cmp::Reverse(e.0)); + let mut kinds: BTreeMap<&str, (u64, u64)> = BTreeMap::new(); + for ((what, len, _), (n, ..)) in &all { + let e = kinds.entry(what).or_default(); + *e = (e.0 + n, e.1 + n * *len as u64); + } + for (what, (n, bytes)) in kinds { + tracing::warn!("up-copy check, copies out of place: {n} ({bytes} bytes): {what}"); + } + for ((what, len, dst), (n, src, declared)) in all.into_iter().take(16) { + tracing::warn!("up-copy check, a copy out of place: {n} times {len:#x} bytes from {src:#x} to {dst:#x}: {what} ({declared:#x} bytes there)"); + } +} + /// A run of words that differ at rest. struct Differs { shadow: std::sync::Arc, @@ -567,6 +644,12 @@ mod tests { /// Title memory of our own (write-watched, or a view of a section, which /// is guarded), and the card copy of the title buffer it is. fn title(resource: usize, view: bool) -> (&'static mut [u8], usize, std::sync::Arc) { + let all = title_of(resource, view, LEN); + assert!(all.2.carded(), "the copy is in the card's memory"); + all + } + + fn title_of(resource: usize, view: bool, len: usize) -> (&'static mut [u8], usize, std::sync::Arc) { use windows_sys::Win32::System::Memory::{ CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE, VirtualAlloc, }; @@ -574,20 +657,19 @@ mod tests { // SAFETY: memory of our own, never freed. let base = unsafe { if view { - let section = CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, LEN as u32, std::ptr::null()); + let section = CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null()); assert!(!section.is_null()); - MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, LEN).Value.cast::() + MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value.cast::() } else { - VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, PAGE_READWRITE).cast::() + VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, PAGE_READWRITE).cast::() } }; assert!(!base.is_null()); - crate::shadow::register(resource, base as u64, LEN as u64); + crate::shadow::register(resource, base as u64, len as u64); let shadow = crate::shadow::find(base as u64, 64).expect("a copy"); - assert!(shadow.carded(), "the copy is in the card's memory"); assert!(super::super::relay_exact() && super::super::relay_copy(), "set VICTORY_RELAY=2 VICTORY_RELAY_COPY=1"); - // SAFETY: `LEN` bytes just committed. - (unsafe { std::slice::from_raw_parts_mut(base, LEN) }, base as usize, shadow) + // SAFETY: `len` bytes just committed. + (unsafe { std::slice::from_raw_parts_mut(base, len) }, base as usize, shadow) } /// Work for the card that takes some milliseconds. @@ -765,6 +847,81 @@ mod tests { assert!(first <= 6 && back[first..].iter().all(|b| *b), "{back:?}"); } + /// The title copies another value to the same bytes in each of three + /// submissions, and each has a draw (a copy here) that reads them. The + /// card is busy meanwhile, so all three are prepared before the first + /// runs: each must read its own. + fn each_reads_its_own(len: usize, resource: usize, carded: bool) { + let Some(host) = host() else { + return; + }; + let (title, start, shadow) = title_of(resource, true, len); + assert_eq!(shadow.carded(), carded, "where the copy is"); + let slow = Slow::new(host); + let (out, out_data) = host.shared_buffer(1 << 16).unwrap(); + let mut lists = Vec::new(); + const AT: usize = 8192; + // All there once. + let all = host.new_list().unwrap(); + shadow.refresh(&all, start as u64, len as u64); + all.close(); + host.execute_own(&all); + settle_now(WHY_SYNC); + lists.push(all); + let mut wrong = Vec::new(); + for round in 0..6u8 { + for v in 0..3u8 { + title[65_536 + usize::from(v) * 256..][..256].fill(round * 16 + v + 1); + } + let busy = host.new_list().unwrap(); + slow.record(&busy, 40); + busy.close(); + host.execute_own(&busy); + lists.push(busy); + for v in 0..3usize { + let list = host.new_list().unwrap(); + list.defer_copy((start + AT) as *mut u8, (start + 65_536 + v * 256) as *const u8, 256); + shadow.refresh(&list, (start + AT) as u64, 256); + // SAFETY: an open list; live buffers. + unsafe { + list.list.CopyBufferRegion(&out, (v * 256) as u64, &shadow.buffer, AT as u64, 256); + } + list.close(); + host.execute_own(&list); + lists.push(list); + } + settle_now(WHY_SYNC); + // SAFETY: a mapping of 64 KiB; the copies into it have run. + let read = unsafe { std::slice::from_raw_parts(out_data, 768) }; + for v in 0..3u8 { + let got = read[usize::from(v) * 256]; + if got != round * 16 + v + 1 { + wrong.push((round, v, got - round * 16)); + } + } + } + eprintln!("read another submission's value (round, submission, whose + 1): {wrong:?}"); + let stale = STALE.lock().unwrap_or_else(|e| e.into_inner()); + let found = stale.get(&shadow.span()).map_or(0, |s| s.words); + eprintln!("the check at sends found {found} words"); + assert!(wrong.is_empty()); + assert_eq!(found, 0); + // With the debug layer (`VICTORY_D3D12_DEBUG=1`, diagnostics). + assert_eq!(host.log_messages(), None); + } + + #[test] + #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"] + fn each_submission_reads_its_own_copy_on_the_card() { + each_reads_its_own(LEN, 0x7777, true); + } + + #[test] + #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"] + fn each_submission_reads_its_own_copy_in_pc_memory() { + each_reads_its_own(256 << 10, 0x8888, std::env::var_os("VICTORY_CARD_ALL").is_some_and(|v| v == "1")); + } + /// Declared writes beside the title's own, in the same 64 KiB pieces and /// dword by dword, flights landing while later ones are in the air: in /// the end title memory and the card hold what each wrote last. (A byte @@ -860,6 +1017,7 @@ mod tests { on_card.is_empty() && in_title.is_empty(), "round {round}: words {on_card:x?} on the card and {in_title:x?} in title memory are not what was written last" ); + assert_eq!(host.log_messages(), None); } } } diff --git a/crates/victory-gpu/src/picked.rs b/crates/victory-gpu/src/picked.rs index 512a5d2..3c9dd20 100644 --- a/crates/victory-gpu/src/picked.rs +++ b/crates/victory-gpu/src/picked.rs @@ -1,5 +1,5 @@ //! Buffers shaders write through views they pick from the heap by an index -//! they compute (`VICTORY_PICKED_WRITES=1`; off by default). +//! they compute (`VICTORY_PICKED_WRITES`; off by default, [`stage`]). //! //! Which views a draw or dispatch writes through is known from its tables //! and root parameters, and their ranges are declared: what is written there @@ -49,8 +49,24 @@ use crate::host::HostList; use crate::shadow::Shadow; pub(crate) fn on() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_PICKED_WRITES").is_some_and(|v| v == "1")) + stage() > 0 +} + +/// `VICTORY_PICKED_WRITES`: 0 (off), 1 (what is found is declared, so that +/// no refresh sends title memory over it while a flight may write it, and +/// not landed), 2 (landed too). +fn stage() -> u8 { + static STAGE: OnceLock = OnceLock::new(); + *STAGE.get_or_init(|| match std::env::var("VICTORY_PICKED_WRITES").as_deref() { + Ok("1") => 1, + Ok("2") => 2, + _ => 0, + }) +} + +/// Whether what is found is landed. +pub(crate) fn lands() -> bool { + stage() > 1 } /// Bytes looked at in turn per frame (`VICTORY_PICKED_MB`). diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index adaa766..7533d52 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -109,6 +109,8 @@ struct Card { /// ([`card_dirty`]), kept until a fetch sent after it has been merged. /// Locked inside `dirty`'s lock. sent: Mutex>, + /// Whether something was put into `dirty` since it was last taken. + touched: std::sync::atomic::AtomicBool, /// The buffers' bytes (the title buffer's, rounded up to 64 KiB). size: u64, } @@ -202,11 +204,14 @@ fn card_limits() -> (u64, u64) { *LIMITS.get_or_init(|| { let env_mb = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()); let vram_budget = crate::host::host().and_then(|h| h.video_memory()).map(|[budget, ..]| budget); - let (min_bytes, max_bytes) = resolve_card_limits( + let (mut min_bytes, max_bytes) = resolve_card_limits( vram_budget, env_mb("VICTORY_CARD_BUFFERS_MIN_MB"), env_mb("VICTORY_CARD_BUFFERS_MB"), ); + if card_all() { + min_bytes = 0; + } tracing::info!( vram_budget_mb = vram_budget.map(|b| b >> 20), card_buffers_min_mb = min_bytes >> 20, @@ -253,6 +258,36 @@ pub(crate) fn card_hash_bytes(size: u64) -> u64 { /// [`card_limits`] and below 1 GiB (the compare counts in 32 bits), and the /// host has what it takes (`Host::card_ready`). fn card_for(size: u64) -> Option { + let there = card_room_for(size); + if there.is_some() || !card_all() || size >= 1 << 30 { + return there; + } + // Two sides all the same, the card's in the PC's memory. + let host = host()?; + if !cards() || !host.card_ready() { + return None; + } + let (buffer, _) = host.shared_buffer(size)?; + CARD_BYTES[0].fetch_add(size, Ordering::Relaxed); + Some(buffer) +} + +/// Whether every title buffer's copy has two sides, however small +/// (`VICTORY_CARD_ALL=1`; off by default). +/// +/// A copy with one side, in the PC's memory, is what the card reads while +/// our refreshes write it: a submission that is prepared changes it under +/// the ones in the air ahead of it. The title's CPU does not write what they +/// still read, but its own buffer copies are done by us at preparing +/// (`crate::host::send` has the order of those right for copies with two +/// sides), and so are the bytes put in beside shaders' writes. +fn card_all() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ALL").is_some_and(|v| v == "1")) +} + +/// [`card_for`] in the card's own memory. +fn card_room_for(size: u64) -> Option { if !cards() { return None; } @@ -363,6 +398,7 @@ pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc, Vec<(usize, usize)>) let ranges = shadow .card .as_ref() + .filter(|c| c.touched.swap(false, Ordering::AcqRel)) .map(|c| { let mut dirty = c.dirty.lock().unwrap_or_else(|e| e.into_inner()); let ranges = std::mem::take(&mut *dirty); @@ -382,6 +418,39 @@ pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc, Vec<(usize, usize)>) out } +/// Copies of memory (from, to, bytes: apart), on several threads if they are +/// many. +pub(crate) fn copy_all(copies: Vec<(usize, usize, usize)>) { + let bytes: usize = copies.iter().map(|c| c.2).sum(); + if bytes > 4 << 20 { + wide(copy_jobs(copies)); + return; + } + for (src, dst, len) in copies { + // SAFETY: the caller's ranges. + unsafe { std::ptr::copy_nonoverlapping(src as *const u8, dst as *mut u8, len) }; + } +} + +/// A title buffer copy was done on the CPU into `[dst, dst + len)`: all of it +/// goes up to the copies in the card's memory that hold it, whether their +/// CPU side held the same before or not. Left out is what shaders in the air +/// may be writing (such a copy waits for them, or is done on the card). +pub(crate) fn send_copied(dst: usize, len: usize) { + for shadow in carded_copies() { + let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize); + let (from, to) = (dst.max(start), (dst + len).min(end)); + if from >= to { + continue; + } + let busy: Vec<(usize, usize)> = + shadow.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().copied().filter(|&(a, b)| a < to && b > from).collect(); + for (a, b) in outside(from, to, busy) { + shadow.copy(a, b); + } + } +} + /// The copies in the card's memory (diagnostics: `crate::host::upcheck`). pub(crate) fn carded_copies() -> Vec> { CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter_map(std::sync::Weak::upgrade).collect() @@ -2690,12 +2759,16 @@ impl Shadow { return true; } *runs_left -= runs.len(); + 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]); self.card_changed(at + r, at + r + m); MERGED[1].fetch_add(1, Ordering::Relaxed); MERGED[2].fetch_add(m as u64, Ordering::Relaxed); } + 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); @@ -3066,6 +3139,13 @@ impl Shadow { Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)), _ => dirty.push((from, to)), } + // (Under the lock: what takes the list sees it or finds it set.) + card.touched.store(true, Ordering::Release); + } + + /// Of a copy in the card's memory: where its CPU side is. + pub(crate) fn card_data(&self) -> *const u8 { + self.data } /// Diagnostics: of a copy in the card's memory, what its CPU side holds @@ -3313,6 +3393,7 @@ impl Shadow { before: Mutex::default(), dirty: Mutex::default(), sent: Mutex::default(), + touched: Default::default(), size: len.next_multiple_of(PIECE as u64), }); } @@ -3468,6 +3549,7 @@ mod land_tests { before: Mutex::default(), dirty: Mutex::default(), sent: Mutex::default(), + touched: Default::default(), size: len as u64, }); Some(shadow) @@ -3772,7 +3854,7 @@ fn lookup(address: u64, len: u64, any: bool) -> Option> { // (`crate::inplace::place_for`): the buffer is the title's own // memory. Not the big ones `cards` puts in the card's memory: those // are read too often to stay in the PC's. - let big = cards() && size >= card_limits().0; + let big = cards() && (size >= card_limits().0 || card_all()); if !big && let Some(placed) = crate::inplace::place_for(key.0, len, false) { entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false))); return entry.shadow.clone(); @@ -3794,6 +3876,7 @@ fn lookup(address: u64, len: u64, any: bool) -> Option> { before: Mutex::default(), dirty: Mutex::default(), sent: Mutex::default(), + touched: Default::default(), size, }; (on_card, Some(card)) @@ -4010,6 +4093,7 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option Date: Tue, 24 Nov 2026 23:52:47 -0600 Subject: [PATCH 192/445] Dynamic descriptor slots: the search goes past the cursor as far as it should The scan was cut to the heap's length, which left out the slots past the cursor a run that crosses it needs; upstream's corrected test (072fde0). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 37 ++++++++++++++--------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 39cfb15..c3c0228 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -870,7 +870,7 @@ impl HostHeap { let mut run = 0; let mut found = None; let mut last = usize::MAX; - for at in starts.take(if enough { DYNAMIC as usize } else { 0 }) { + for at in starts.take(if enough { usize::MAX } else { 0 }) { // A run cannot wrap past the end. if at != last.wrapping_add(1) { run = 0; @@ -2841,23 +2841,30 @@ mod tests { assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); } - /// Contiguous free dynamic slot ranges that cross the search cursor are found. #[test] - fn dynamic_allocation_finds_contiguous_range_crossing_search_cursor() { + fn dynamic_search_can_find_a_run_across_the_cursor() { let Some(heap) = HostHeap::new(false, 4) else { - return; // no host GPU + eprintln!("no host descriptor heap; skipped"); + return; }; - // Allocate slots 0..8, advancing cursor to 8. - let a = heap.dynamic(8).unwrap(); - // Allocate slots 8..16, advancing cursor to 16. - let b = heap.dynamic(8).unwrap(); - assert_eq!((a, b), (4, 12)); + let first = heap.dynamic(1).unwrap(); + let left = heap.dynamic(2).unwrap(); + let right = heap.dynamic(2).unwrap(); + let rest = heap.dynamic(heap.dynamic - 5).unwrap(); + assert_eq!((first, left, right, rest), (4, 5, 7, 9)); - // Release slots 10..14 (crossing cursor at 12). - // Before the fix, a request of 4 slots starting search at 12 scanned 12..end then 0..12, - // missing the contiguous run at 10..14. - heap.release(14, 4); - let c = heap.dynamic(4); - assert_eq!(c, Some(14)); + // Reallocating the left half puts the cursor back in the middle. + heap.release(left, 2); + assert_eq!(heap.dynamic(2), Some(left)); + heap.release(left, 2); + heap.release(right, 2); + assert_eq!(heap.dynamic(4), Some(left)); + assert_eq!(heap.dynamic(1), None); + + // A free slot at each physical end does not form a two-slot range. + heap.release(first, 1); + let last = first + heap.dynamic - 1; + heap.release(last, 1); + assert_eq!(heap.dynamic(2), None); } } From 84eae352a2daa0539f3e1e8e8a719bb03bac1ed8 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:51:20 -0600 Subject: [PATCH 193/445] Indirect dispatches of more than 65,535 groups run whole (VICTORY_INDIRECT_WIDE) The title's tile lists are dispatches of a group per tile: in the captured frame 2dc364df5d3278b8 asks for 67,440 groups (the one before it 67,272) and 940c2635dc1312f4 for 47,760, the 115,200 tiles of 2560x1440. The clamp cut the first to 65,535: 1,905 tiles at the list's end, the lowest of the picture, did not run. Up to 2^20 groups run as asked on AMD cards (a test on the card: every group once, under its number); more still runs 65,535. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit b856c46dd10bbb550157b255d113a3cca2f3f38a) --- crates/victory-gpu/src/indirect.rs | 116 +++++++++++++++++++++-- crates/victory-gpu/src/indirect/batch.rs | 5 +- 2 files changed, 113 insertions(+), 8 deletions(-) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index a4fa155..7d044ab 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -29,7 +29,7 @@ //! garbage records cannot run for seconds either. //! //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535 -//! groups per dimension and 2^20 per dispatch, one-dimensional mesh +//! groups per dimension, in x 2^20 ([`widest`]), and 2^20 per dispatch, one-dimensional mesh //! dispatches, the budget) cut legitimate work beyond them; raise them if //! the title needs more. @@ -107,9 +107,11 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { cost = count * instances; draw_counts = uint2(count, instances); } else if (active && kind == 2) { - uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u)); - // x * y fits 32 bits; the whole count may not. - if (g.z != 0 && g.x * g.y > GROUPS / g.z) { + uint3 g = src_args.Load3(src_at); + // Up to WIDEST groups in x run as asked (`widest`). + g = min(g, uint3(g.x <= WIDEST ? WIDEST : 65535u, 65535u, 65535u)); + // x * y fits 32 bits where it is looked at; the whole count may not. + if ((g.y != 0 && g.x > GROUPS / g.y) || (g.z != 0 && g.x * g.y > GROUPS / g.z)) { g = uint3(0, 0, 0); } cost = g.x * g.y * g.z * 64u; @@ -237,9 +239,42 @@ fn make_for(device: &ID3D12Device) -> windows::core::Result { make_from(device, SOURCE) } +/// The most groups in x that an indirect dispatch runs as the title asks: +/// 65,535 is the most D3D12 names for a dispatch, 2^20 ([`SOURCE`]'s GROUPS) +/// what is bounded here anyway (`VICTORY_INDIRECT_WIDE=0`: 65,535; a record +/// that asks for more still runs 65,535). +/// +/// The title's tile lists are dispatches of one group per tile, and two of +/// them are classes of the picture's 8x4 tiles, 115,200 in all at +/// 2560x1440: in a captured frame 67,440 and 47,760 (the program +/// 2dc364df5d3278b8 and 940c2635dc1312f4). Cut to 65,535 the first list lost +/// its last 1,905 tiles, the lowest of the picture. The console runs what it +/// is asked (its dispatch counts are 32 bits), and so does an AMD card, whose +/// dispatch packets and group numbers are the same; D3D12 does not look at +/// indirect counts. Other cards stay at 65,535. +fn widest(amd: bool) -> u32 { + let on = std::env::var_os("VICTORY_INDIRECT_WIDE").is_none_or(|v| v != "0"); + if amd && on { 1 << 20 } else { 65_535 } +} + +/// Whether `device` is an AMD card's. +fn amd(device: &ID3D12Device) -> bool { + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIAdapter1, IDXGIFactory4}; + // SAFETY: plain queries. + unsafe { + CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| f.EnumAdapterByLuid::(device.GetAdapterLuid())) + .and_then(|a| a.GetDesc1()) + .is_ok_and(|d| d.VendorId == 0x1002) + } +} + /// The clamp compiled from `source` (ours, or in the benchmark the one it /// replaced). fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result { + #[cfg(feature = "diagnostics")] + let batched = source == batch::SOURCE; + let source = &format!("#define WIDEST {}u\n{source}", widest(amd(device))); let mut code: Option = None; let mut errors: Option = None; // SAFETY: the source and names live through the call; out pointers ours. @@ -1027,11 +1062,11 @@ void main() { 1, [5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC], ); - // Record 2 exceeds 65,535 in X -> clamped to (65535, 1, 1). + // Record 2 exceeds what any card runs in X -> clamped to (65535, 1, 1). write_record( &mut initial_src, 2, - [100_000, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567], + [(1 << 20) + 1, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567], ); for slot in 3..MAX as usize { // Each garbage slot would clamp to 65535 * 16 * 1 = 1,048,560 groups @@ -1832,6 +1867,75 @@ void main() { sig.unwrap() } + /// An AMD card runs every group of an indirect dispatch of more than + /// 65,535, each under its own number: the title's tile lists + /// ([`widest`]), clamped one by one and in a batch. Others are not asked. + #[test] + fn card_runs_wide_indirect_dispatches() { + const CS: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer seen : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { + uint was; + seen.InterlockedAdd(0, 1, was); + seen.InterlockedMax(4, group.x, was); + seen.InterlockedMax(8, thread.x, was); + seen.InterlockedAdd(16 + group.x * 4, 1, was); +} +"#; + let Some(mut gpu) = WarpHarness::on(false) else { + return; + }; + if !amd(&gpu.device) || widest(true) == 65_535 { + return; + } + let worker = compile_cs(&gpu.device, CS).expect("the worker must compile"); + let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile"); + let sig = gpu.signature(2, 12); + for asked in [67_440u32, 115_200, 1 << 20, (1 << 20) + 1] { + let runs = if asked > 1 << 20 { 65_535 } else { asked }; + for batched in [false, true] { + let (src, src_ptr, src_gpu) = gpu.shared_buffer(1024); + let (_budget, budget_ptr, budget_gpu) = gpu.shared_buffer(256); + let (_table, table_ptr, table_gpu) = gpu.shared_buffer(batch::TABLE); + let size = 16 + (4 << 20) + 16; + let seen = gpu.default_uav(size); + let (back, back_ptr, _) = gpu.shared_buffer(size); + let dst = gpu.default_uav(64 << 10); + // SAFETY: mapped buffers, which nothing reads yet; an open + // list and live buffers. + unsafe { + std::ptr::write_bytes(budget_ptr, 0, 256); + for (w, word) in [asked, 1, 1].into_iter().enumerate() { + src_ptr.cast::().add(w).write_volatile(word); + } + if batched { + batch::record(&pass, &gpu.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu; 4], table_gpu); + assert_eq!(batch::Table::new(table_ptr, 0, [1, 0, 0, 0]).place(1, 0, 2), Some(0)); + } else { + let to = (&dst, D3D12_RESOURCE_STATE_COMMON); + assert!(record_clamp_as(&gpu.clamp, &gpu.list, to, budget_gpu, (&src, 0), None, (2, 12, 1), false)); + } + gpu.list.SetComputeRootSignature(&worker.root); + gpu.list.SetPipelineState(&worker.pso); + gpu.list.SetComputeRootUnorderedAccessView(0, seen.GetGPUVirtualAddress()); + gpu.list.ExecuteIndirect(&sig, 1, &dst, 0, None, 0); + gpu.list.ResourceBarrier(&[uav_barrier()]); + gpu.list.ResourceBarrier(&[transition(&seen, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + gpu.list.CopyBufferRegion(&back, 0, &seen, 0, size); + } + gpu.submit_and_wait(); + // SAFETY: the list has run; mapped words. + let word = |i: usize| unsafe { back_ptr.cast::().add(i).read_volatile() }; + assert_eq!([word(0), word(1), word(2)], [runs, runs - 1, runs - 1], "asked for {asked}, batched {batched}"); + let wrong = (0..runs as usize).find(|&g| word(4 + g) != 1); + assert_eq!((wrong, word(4 + runs as usize)), (None, 0), "every group once, asked for {asked}"); + } + } + } + /// What a batch's table says of records added to it: one job per /// record, charged for every execution that reads it, and none for what /// the pass cannot read. diff --git a/crates/victory-gpu/src/indirect/batch.rs b/crates/victory-gpu/src/indirect/batch.rs index 1f65388..ed25aa5 100644 --- a/crates/victory-gpu/src/indirect/batch.rs +++ b/crates/victory-gpu/src/indirect/batch.rs @@ -81,8 +81,9 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { record[1] = min(record[1], (1u << 26) / max(record[0], 1u)); cost = record[0] * record[1]; } else if (kind == 2) { - uint3 g = min(uint3(record[0], record[1], record[2]), uint3(65535u, 65535u, 65535u)); - if (g.z != 0 && g.x * g.y > GROUPS / g.z) { + uint3 g = uint3(record[0], record[1], record[2]); + g = min(g, uint3(g.x <= WIDEST ? WIDEST : 65535u, 65535u, 65535u)); + if ((g.y != 0 && g.x > GROUPS / g.y) || (g.z != 0 && g.x * g.y > GROUPS / g.z)) { g = uint3(0, 0, 0); } cost = g.x * g.y * g.z * 64u; From 18c01292113e42de36170b1df09b47308eda8198 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:59:54 -0600 Subject: [PATCH 194/445] Each submission's shaders read the bytes it was prepared with (VICTORY_SEND_OWN) On by default. Sends to card copies were copies out of their CPU sides made when the card came to them, and later submissions had written those by then: of three submissions that each copy a value to the same bytes and read them, all read the last one's (test: 12 of 12 wrong). The bytes are taken into memory of the submission's own at preparing; short runs go as one scatter per copy. Title buffer copies go up whether our side changed or not. VICTORY_CARD_ALL=1 (off): every title buffer's copy has two sides, so that this holds for the small ones too (they are written in place now, under the submissions in the air). VICTORY_PICKED_WRITES: 1 declares, 2 lands too. The check (VICTORY_UPCOPY_CHECK): what a submission took twice is no longer counted as older values sent; copies of the title's out of their place in a submission; copies held for unchanged that are not title memory's. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host/upcheck.rs | 32 ++++++ crates/victory-gpu/src/shadow.rs | 134 +++++++++++++++++++++---- 2 files changed, 144 insertions(+), 22 deletions(-) diff --git a/crates/victory-gpu/src/host/upcheck.rs b/crates/victory-gpu/src/host/upcheck.rs index a33346b..a483493 100644 --- a/crates/victory-gpu/src/host/upcheck.rs +++ b/crates/victory-gpu/src/host/upcheck.rs @@ -452,10 +452,42 @@ pub(super) fn at_rest(host: &Host) { if look(host).is_none() { tracing::warn!("up-copy check: the look at rest could not be made"); } + look_for_stale(); tracing::info!(ms = began.elapsed().as_millis(), "up-copy check: the look at rest is done"); LAST.store(now_ms(), Ordering::Relaxed); } +/// At rest: copies of title memory, whatever reads them (meshes too), that +/// are not what title memory holds although nothing told that it changed: a +/// refresh will not bring them up to date. +fn look_for_stale() { + const MOST: usize = 1 << 30; + let mut by: BTreeMap<(u64, u64), (bool, u64, usize, Vec)> = BTreeMap::new(); + let compared = crate::shadow::stale_pages(MOST, &mut |shadow, page, words, (at, copy, title)| { + let e = by.entry(shadow.span()).or_insert((shadow.carded(), 0, 0, Vec::new())); + e.1 += words as u64; + e.2 += 1; + if e.3.len() < 4 { + e.3.push(format!("{words} words in the 64 KiB at {page:#x} (the first at {at:#x}: the copy {copy:#x}, title memory {title:#x})")); + } + }); + tracing::info!( + "up-copy check at rest: {} MB of copies held for unchanged compared with title memory, {} copies are stale", + compared >> 20, + by.len() + ); + let mut by: Vec<_> = by.into_iter().collect(); + by.sort_by_key(|(_, e)| std::cmp::Reverse(e.1)); + for ((start, len), (carded, words, pages, some)) in by.into_iter().take(16) { + tracing::warn!( + "up-copy check at rest, stale: {start:#x}+{len:#x} ({}): {words} words in {pages} pages are not title memory's, and nothing \ + told of it: {}", + if carded { "on the card" } else { "in PC memory" }, + some.join("; ") + ); + } +} + /// Sends `list` (recorded by `f`) and waits for it. fn run(host: &Host, f: impl FnOnce(&ID3D12GraphicsCommandList)) -> Option<()> { let (allocator, list) = host.make_prelude()?; diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 4981967..ff87b91 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -108,7 +108,7 @@ struct Card { /// side, each with the number of the send that took it /// ([`card_dirty`]), kept until a fetch sent after it has been merged. /// Locked inside `dirty`'s lock. - sent: Mutex>, + sent: Mutex, /// Whether something was put into `dirty` since it was last taken. touched: std::sync::atomic::AtomicBool, /// The buffers' bytes (the title buffer's, rounded up to 64 KiB). @@ -376,6 +376,46 @@ fn window_card_for(size: u64) -> Option { buffer } +/// What went up, by send: its number, and the offsets, in order and joined +/// (a refresh sends thousands of runs of a few words). +#[derive(Default)] +struct SentRuns(Vec<(u64, Vec<(usize, usize)>)>); + +impl SentRuns { + fn note(&mut self, number: u64, ranges: Vec<(usize, usize)>) { + if ranges.is_empty() { + return; + } + let ranges = joined(ranges); + match self.0.iter_mut().find(|s| s.0 == number) { + Some((_, all)) => *all = joined([std::mem::take(all), ranges].concat()), + None => self.0.push((number, ranges)), + } + } + + /// Sends up to `number` are of no use any more. + fn forget(&mut self, number: u64) { + self.0.retain(|s| s.0 > number); + } + + /// Adds to `out` what sends after `number` took of `[from, to)`. + fn near(&self, number: u64, from: usize, to: usize, out: &mut Vec<(usize, usize)>) { + for (_, ranges) in self.0.iter().filter(|s| s.0 > number) { + let first = ranges.partition_point(|r| r.1 <= from); + out.extend(ranges[first..].iter().take_while(|r| r.0 < to).copied()); + } + } + + #[cfg(test)] + fn of(all: &[(usize, usize, u64)]) -> SentRuns { + let mut sent = SentRuns::default(); + for &(a, b, number) in all { + sent.note(number, vec![(a, b)]); + } + sent + } +} + /// The copies in the card's memory whose CPU side changed since they were /// last asked: each with the changed offsets, in order and joined where /// they touch. The ranges are taken: the caller copies them to the card's @@ -404,8 +444,8 @@ pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc, Vec<(usize, usize)>) let ranges = std::mem::take(&mut *dirty); if relay() { let mut sent = c.sent.lock().unwrap_or_else(|e| e.into_inner()); - sent.retain(|s| s.2 > fetched); - sent.extend(ranges.iter().map(|&(a, b)| (a, b, sent_as))); + sent.forget(fetched); + sent.note(sent_as, ranges.clone()); } ranges }) @@ -418,6 +458,65 @@ pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc, Vec<(usize, usize)>) out } +/// Diagnostics (`crate::host::upcheck`, nothing in the air): copies whose +/// pages the write watch and the guards hold for unchanged since they were +/// taken, compared with title memory, `most` bytes a call in turn. `say` gets +/// the copy, the title address of a page that is not the same, the words that +/// differ and the first of them (its address, the copy's value, title +/// memory's). Returns the bytes compared. +pub(crate) fn stale_pages(most: usize, say: &mut dyn FnMut(&Shadow, usize, usize, (usize, u32, u32))) -> usize { + static NEXT: AtomicU64 = AtomicU64::new(0); + let mut all: Vec> = buffers().values().filter_map(|e| e.shadow.clone()).collect(); + all.extend(LOOSE.lock().unwrap_or_else(|e| e.into_inner()).values().cloned()); + all.retain(|s| s.place.is_none() && s.watched.load(Ordering::Relaxed) == 1); + all.sort_by_key(|s| s.id); + let next = NEXT.load(Ordering::Relaxed); + let turn = all.partition_point(|s| s.id < next); + let mut done = 0; + let mut title = vec![0u8; PAGE]; + for shadow in all[turn..].iter().chain(&all[..turn]) { + if done >= most { + NEXT.store(shadow.id, Ordering::Relaxed); + break; + } + let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize); + // (What it finds written stays noted for the next refresh.) + let Some((_, written)) = crate::watch::writes(start, end, true) else { + continue; + }; + let written: std::collections::HashMap = written.into_iter().collect(); + let copied = shadow.copied.lock().unwrap_or_else(|e| e.into_inner()).clone(); + for (i, &at) in copied.iter().enumerate() { + let page = start / PAGE + i; + if at == 0 || written.get(&page).is_some_and(|&w| w > at) { + continue; + } + let (lo, hi) = ((page * PAGE).max(start), ((page + 1) * PAGE).min(end)); + let title = &mut title[..hi - lo]; + if !crate::host::read_into(lo as *const u8, title) { + continue; + } + done += hi - lo; + // SAFETY: inside the mapping; nothing is in the air and the + // submission lock is held. + let held = unsafe { std::slice::from_raw_parts(shadow.data.add(lo - start).cast_const(), hi - lo) }; + if held == title { + continue; + } + let word = |b: &[u8], k: usize| u32::from_le_bytes([b[k], b[k + 1], b[k + 2], b[k + 3]]); + let differ: Vec = (0..(hi - lo) & !3).step_by(4).filter(|&k| word(held, k) != word(title, k)).collect(); + // Written meanwhile: not stale, and the next refresh sees it. + let again = crate::watch::writes(lo, hi, true).is_none_or(|(_, w)| w.iter().any(|&(p, w)| p == page && w > at)); + if let Some(&k) = differ.first() + && !again + { + say(shadow, lo, differ.len(), (lo + k, word(held, k), word(title, k))); + } + } + } + done +} + /// Copies of memory (from, to, bytes: apart), on several threads if they are /// many. pub(crate) fn copy_all(copies: Vec<(usize, usize, usize)>) { @@ -3378,12 +3477,9 @@ impl Shadow { let skip: Vec<(usize, usize)> = { let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner()); - dirty - .iter() - .copied() - .chain(sent.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1))) - .filter(|&(a, b)| a < at + n && b > at) - .collect() + let mut skip: Vec<(usize, usize)> = dirty.iter().copied().filter(|&(a, b)| a < at + n && b > at).collect(); + sent.near(fetched_after, at, at + n, &mut skip); + skip }; title.clear(); title.resize(n, 0); @@ -3439,8 +3535,8 @@ impl Shadow { let mut dirty = card.dirty.lock().unwrap(); let ranges = std::mem::take(&mut *dirty); let mut sent = card.sent.lock().unwrap(); - sent.retain(|s| s.2 > merged); - sent.extend(ranges.iter().map(|&(a, b)| (a, b, number))); + sent.forget(merged); + sent.note(number, ranges.clone()); ranges } @@ -3476,12 +3572,9 @@ impl Shadow { let skip: Vec<(usize, usize)> = { let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner()); - dirty - .iter() - .copied() - .chain(sent.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1))) - .filter(|&(a, b)| a < to && b > from) - .collect() + let mut skip: Vec<(usize, usize)> = dirty.iter().copied().filter(|&(a, b)| a < to && b > from).collect(); + sent.near(fetched_after, from, to, &mut skip); + skip }; let mut put = 0; for &(lo, hi, now) in pieces { @@ -3650,7 +3743,7 @@ mod land_tests { bytes(shadow.data as usize).copy_from_slice(&held); let card = shadow.card.as_ref().expect("made with one"); *card.dirty.lock().unwrap() = dirty.clone(); - *card.sent.lock().unwrap() = sent.clone(); + *card.sent.lock().unwrap() = super::SentRuns::of(&sent); } let pieces: Vec<(usize, usize)> = (0..3).map(|p| (p * PIECE + 16, (p + 1) * PIECE - 4)).collect(); let mut scratch = Vec::new(); @@ -3709,10 +3802,7 @@ mod land_tests { let card = shadow.card.as_ref().expect("made with one"); let mut dirty = card.dirty.lock().unwrap(); let mut sent = card.sent.lock().unwrap(); - let moved: Vec<_> = std::mem::take(&mut *dirty).into_iter().map(|(a, b)| (a, b, 9)).collect(); - sent.extend(moved); - sent.sort_unstable(); - sent.dedup(); + sent.note(9, std::mem::take(&mut *dirty)); } }); let mut now = vec![0u8; LEN]; From 0fdcaa3b1a6510f13d8cf6dc8fe24c8de1c07c68 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 00:00:07 -0600 Subject: [PATCH 195/445] victory replay --flow, --images, --until; shader-info names the hashes Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 59 +++ apps/victory/src/shader.rs | 4 +- crates/victory-gpu/src/replay/play.rs | 11 + crates/victory-gpu/src/replay/play/look.rs | 445 +++++++++++++++++++++ docs/replay.md | 3 + 5 files changed, 521 insertions(+), 1 deletion(-) create mode 100644 crates/victory-gpu/src/replay/play/look.rs diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index c10b13e..2b78b53 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -136,6 +136,35 @@ pub(crate) struct Replay { /// Only write the frame's buffers and the commands of these lists (`3..7`). #[arg(long)] listing: Option, + /// Only write what the dispatches of these lists have bound (`3..7`). + #[arg(long)] + flow: Option, + /// With --flow: draws too. + #[arg(long)] + flow_draws: bool, + /// With --flow: heap slots shown from each place named. + #[arg(long, default_value_t = 40)] + flow_slots: u32, + /// Run the frame once and save textures as pictures in this folder, with + /// what values they hold (see --texture, --until). + #[arg(long)] + images: Option, + /// With --images: `[.]` (repeatable); none: all + /// that the frame's shaders write. + #[arg(long)] + texture: Vec, + /// With --images and no --texture: from this many texels on. + #[arg(long, default_value_t = 4096)] + least: u64, + /// With --images: the widest picture. + #[arg(long, default_value_t = 960)] + width: u32, + /// With --images: the values too. + #[arg(long)] + raw: bool, + /// The last command that runs, `:`; after it only barriers. + #[arg(long)] + until: Option, /// Use the D3D12 debug layer (slow). #[arg(long)] debug_layer: bool, @@ -160,6 +189,18 @@ pub(crate) fn run(r: Replay) -> Result<()> { let lists = range(text).with_context(|| format!("--listing {text}"))?; return play::listing(&r.folder, lists, &mut |line| println!("{line}")); } + if let Some(text) = &r.flow { + let lists = range(text).with_context(|| format!("--flow {text}"))?; + return play::look::flow(&r.folder, lists, r.flow_draws, r.flow_slots, &mut |line| println!("{line}")); + } + let until = match &r.until { + Some(text) => Some( + text.split_once(':') + .and_then(|(l, c)| Some((l.parse().ok()?, c.parse().ok()?))) + .with_context(|| format!("--until {text}: not :"))?, + ), + None => None, + }; let only = match &r.only { Some(text) => Some( range(text) @@ -189,6 +230,7 @@ pub(crate) fn run(r: Replay) -> Result<()> { wait_all: r.wait_all, wait_lists: r.wait_lists, only, + until, skip_shaders: r.skip_shader, compare: r.compare, debug: r.debug_layer, @@ -201,6 +243,23 @@ pub(crate) fn run(r: Replay) -> Result<()> { let player = play::Player::load(&r.folder, &options)?; return player.slots(list, command, &mut |line| println!("{line}")); } + if let Some(folder) = &r.images { + let mut which = Vec::new(); + for text in &r.texture { + let (id, sub) = text.split_once('.').unwrap_or((text, "0")); + let bad = || format!("--texture {text}"); + which.push((id.parse().with_context(bad)?, sub.parse().with_context(bad)?)); + } + let images = play::look::Images { + which, + least: r.least, + folder: folder.clone(), + width: r.width, + raw: r.raw, + }; + let mut player = play::Player::load(&r.folder, &options)?; + return player.images(&options, &images, &mut |line| println!("{line}")); + } if r.check_written { let mut player = play::Player::load(&r.folder, &options)?; return player.check_written(&mut |line| println!("{line}")); diff --git a/apps/victory/src/shader.rs b/apps/victory/src/shader.rs index 1c6e002..779f61c 100644 --- a/apps/victory/src/shader.rs +++ b/apps/victory/src/shader.rs @@ -169,7 +169,9 @@ pub fn run(paths: Vec, verbose: bool, disasm: bool) -> Result<()> { None => "no parsable DXIL program".to_owned(), } + &native; if verbose { - println!("{}{}: {line}", path.display(), source.label()); + // As a run's log and a replay name it (`hash=`). + let hash = blake3::hash(&bytes).to_hex(); + println!("{}{} #{}: {line}", path.display(), source.label(), &hash[..16]); for l in &listing { println!("{l}"); } diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index c833679..f3580f0 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -30,6 +30,7 @@ use super::wire::{ }; pub mod diverge; +pub mod look; mod merge; mod upcopies; @@ -84,6 +85,8 @@ pub struct Options { pub wait_lists: bool, /// Run only these lists (by their place in the frame). pub only: Option<(u32, u32)>, + /// The last command that runs (list, command); after it only barriers. + pub until: Option<(u32, usize)>, /// Skip what runs a pipeline whose name or shader hash has one of /// these in it. pub skip_shaders: Vec, @@ -113,6 +116,7 @@ impl Default for Options { wait_all: false, wait_lists: false, only: None, + until: None, skip_shaders: Vec::new(), compare: false, debug: false, @@ -1916,6 +1920,13 @@ impl Player { lists.push(edit::barriers_only(cmds)); continue; } + if let Some((list, command)) = o.until + && here >= list + { + let from = if here > list { 0 } else { (command + 1).min(cmds.len()) }; + let rest = cmds.split_off(from); + cmds.extend(edit::barriers_only(rest)); + } if o.skip_clamps && let Some(c) = clamps.get(here as usize) { diff --git a/crates/victory-gpu/src/replay/play/look.rs b/crates/victory-gpu/src/replay/play/look.rs new file mode 100644 index 0000000..42f534d --- /dev/null +++ b/crates/victory-gpu/src/replay/play/look.rs @@ -0,0 +1,445 @@ +//! What the passes of a frame read and write, and what textures hold after a +//! command: `--flow` and `--images`. + +use super::*; + +/// The bytes of a view's description as words. +fn word(s: &Slot, i: usize) -> u32 { + u32::from_le_bytes([s.desc[i * 4], s.desc[i * 4 + 1], s.desc[i * 4 + 2], s.desc[i * 4 + 3]]) +} + +/// A heap slot, where a frame's resources are known by their numbers only. +fn slot_text(s: &Slot, called: &dyn Fn(u32) -> String) -> String { + let kind = ["empty", "cbv", "srv", "uav", "sampler", "rtv", "dsv"] + .get(s.kind as usize) + .copied() + .unwrap_or("?"); + let res = if s.res == NONE { "null".into() } else { called(s.res) }; + match s.kind { + slot::EMPTY => "never written".into(), + slot::CBV => format!("cbv {res} +{:#x} size {:#x}", s.address(), word(s, 2)), + slot::SAMPLER => format!( + "sampler filter {:#x} address {} {} {} bias {} compare {} lod {}..{}", + word(s, 0), + word(s, 1), + word(s, 2), + word(s, 3), + f32::from_bits(word(s, 4)), + word(s, 6), + f32::from_bits(word(s, 11)), + f32::from_bits(word(s, 12)), + ), + _ if s.described == 0 => format!("{kind} of all: {res}"), + slot::SRV if word(s, 1) == 1 => format!( + "srv f{} first {} count {} stride {} flags {}: {res}", + word(s, 0), + word(s, 4), + word(s, 6), + word(s, 7), + word(s, 8) + ), + slot::UAV if word(s, 1) == 1 => format!( + "uav f{} first {} count {} stride {} flags {}: {res}", + word(s, 0), + word(s, 2), + word(s, 4), + word(s, 5), + word(s, 8) + ), + slot::SRV => format!( + "srv f{} dim {} [{} {} {} {} {}]: {res}", + word(s, 0), + word(s, 1), + word(s, 4), + word(s, 5), + word(s, 6), + word(s, 7), + word(s, 8) + ), + _ => format!( + "{kind} f{} dim {} [{} {} {} {}]: {res}", + word(s, 0), + word(s, 1), + word(s, 2), + word(s, 3), + word(s, 4), + word(s, 5) + ), + } +} + +/// What the lists' dispatches (with `draws`: draws too) have bound: pipeline, +/// root arguments, and what lies in the heap where a root constant that is a +/// place in it (32 bytes a slot) leads, `most` slots of each. Read from the +/// capture alone; no device is made. +pub fn flow( + folder: &Path, + lists: (u32, u32), + draws: bool, + most: u32, + line: &mut dyn FnMut(&str), +) -> Result<()> { + let frame = Frame::read(&find(folder)?.join("frame.bin"))?; + let pipelines: HashMap = frame.pipelines.iter().map(|p| (p.id, p)).collect(); + let resources: HashMap = frame.resources.iter().map(|r| (r.id, r)).collect(); + let called = |id: u32| match resources.get(&id) { + None => format!("#{id} (not there)"), + Some(r) if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 => { + format!("#{id} '{}' buffer {:#x}", r.name, r.desc.width) + } + Some(r) => format!( + "#{id} '{}' {}x{}x{} m{} f{}", + r.name, r.desc.width, r.desc.height, r.desc.depth, r.desc.mips, r.desc.format + ), + }; + let heaps: HashMap = + frame.descriptor_heaps.iter().map(|h| (h.id, h)).collect(); + let mut late: HashMap<(u32, u32), Slot> = HashMap::new(); + let mut place = 0; + for (i, s) in frame.submits.iter().enumerate() { + for (heap, at, slot) in &s.views { + late.insert((*heap, *at), *slot); + } + let slot_at = |heap: u32, at: u32| -> Slot { + if let Some(s) = late.get(&(heap, at)) { + return *s; + } + let Some(h) = heaps.get(&heap) else { + return Slot::EMPTY; + }; + let after = h.runs.partition_point(|r| r.0 <= at); + match after.checked_sub(1).map(|n| &h.runs[n]) { + Some((first, count, slot)) if at - first < *count => *slot, + _ => Slot::EMPTY, + } + }; + for &l in s.lists.iter().filter(|&&l| l != MISSING) { + let here = place; + place += 1; + if here < lists.0 || here > lists.1 { + continue; + } + line(&format!("list {here} of submission {i}")); + let mut pso = NONE; + let mut compute = false; + let mut heap = NONE; + let mut binds: BTreeMap<(bool, u32), (String, Vec)> = BTreeMap::new(); + let mut targets = String::new(); + for (n, c) in Cmd::all(&frame.lists[l as usize].commands.0)?.iter().enumerate() { + match c { + Cmd::Pipeline { pso: p } => { + pso = *p; + compute = pipelines.get(p).is_some_and(|p| { + p.parts.iter().any(|part| { + matches!(part, wire::Part::Code { kind, .. } if *kind == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS.0) + }) + }); + } + Cmd::RootSignature { graphics, .. } => binds.retain(|k, _| k.0 != *graphics), + Cmd::Heaps { heaps } => heap = heaps.first().copied().unwrap_or(NONE), + Cmd::RootView { graphics, kind, param, va } => { + let kind = ["?", "cbv", "srv", "uav"].get(*kind as usize).copied().unwrap_or("?"); + let text = match va { + Va::At { res, offset } => format!("{kind} {} +{offset:#x}", called(*res)), + Va::Null {} => format!("{kind} null"), + Va::Unknown { address } => format!("{kind} unknown {address:#x}"), + }; + binds.insert((*graphics, *param), (text, Vec::new())); + } + Cmd::Table { graphics, param, heap, slot } => { + binds.insert( + (*graphics, *param), + (format!("table heap {heap} slot {slot}"), Vec::new()), + ); + } + Cmd::Constants { graphics, param, offset, values } => { + let (_, all) = binds + .entry((*graphics, *param)) + .or_insert_with(|| ("constants".into(), Vec::new())); + let end = *offset as usize + values.len(); + if all.len() < end { + all.resize(end, 0); + } + all[*offset as usize..end].copy_from_slice(values); + } + Cmd::Targets { colors, depth } => { + targets = colors + .iter() + .chain(depth) + .map(|s| slot_text(s, &called)) + .collect::>() + .join("; "); + } + Cmd::CopyTexture { .. } + | Cmd::CopyResource { .. } + | Cmd::Resolve { .. } + | Cmd::ClearDepth { .. } + | Cmd::ClearTarget { .. } => line(&format!("{here}:{n} {c:?}")), + c if c.runs_shaders() && (compute || draws) => { + let name = pipelines.get(&pso).map_or("", |p| p.name.as_str()); + line(&format!("{here}:{n} {c:?} pso {pso} {name}")); + if !compute { + line(&format!(" targets {targets}")); + } + for ((graphics, param), (text, values)) in &binds { + if *graphics == compute { + continue; + } + if values.is_empty() { + line(&format!(" {param}: {text}")); + continue; + } + line(&format!(" {param}: {text} {values:x?}")); + for (k, v) in values.iter().enumerate() { + if v & 31 != 0 + || v >> 5 < 64 + || heaps.get(&heap).is_none_or(|h| v >> 5 >= h.count) + { + continue; + } + for m in 0..most { + let s = slot_at(heap, (v >> 5) + m); + if s.kind != slot::EMPTY { + let text = slot_text(&s, &called); + line(&format!(" [{k}]+{m} slot {}: {text}", (v >> 5) + m)); + } + } + } + } + } + _ => {} + } + } + } + } + Ok(()) +} + +fn half(b: &[u8]) -> f32 { + let h = u32::from(u16::from_le_bytes([b[0], b[1]])); + small(h & 0x7fff, 10) * if h >> 15 == 1 { -1.0 } else { 1.0 } +} + +/// A float of five exponent bits and `bits` of mantissa. +fn small(v: u32, bits: u32) -> f32 { + let m = (v & ((1 << bits) - 1)) as f32 / (1u32 << bits) as f32; + match v >> bits & 31 { + 0 => m * 2f32.powi(-14), + 31 if m > 0.0 => f32::NAN, + 31 => f32::INFINITY, + e => (1.0 + m) * 2f32.powi(e as i32 - 15), + } +} + +/// Bytes of a texel that [`texel`] knows. +fn texel_bytes(format: i32) -> Option { + Some(match format { + 1..=4 => 16, + 5..=8 => 12, + 9..=22 => 8, + 23..=47 | 67 | 87..=93 => 4, + 48..=59 => 2, + 60..=65 => 1, + _ => return None, + }) +} + +/// A texel as numbers (typeless formats as their usual ones; R32 as a +/// number as R9G9B9E5, which is what it mostly stands for). +fn texel(format: i32, b: &[u8]) -> [f32; 4] { + let u32_at = |i: usize| u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]); + let f32_at = |i: usize| f32::from_bits(u32_at(i)); + let u16_at = |i: usize| f32::from(u16::from_le_bytes([b[i], b[i + 1]])); + let u8_at = |i: usize| f32::from(b[i]); + match format { + 1 | 2 => [f32_at(0), f32_at(4), f32_at(8), f32_at(12)], + 3 | 4 => [u32_at(0) as f32, u32_at(4) as f32, u32_at(8) as f32, u32_at(12) as f32], + 5..=8 => [f32_at(0), f32_at(4), f32_at(8), 1.0], + 9 | 10 => [half(b), half(&b[2..]), half(&b[4..]), half(&b[6..])], + 11 => [0, 2, 4, 6].map(|i| u16_at(i) / 65535.0), + 12..=14 => [0, 2, 4, 6].map(u16_at), + 15 | 16 => [f32_at(0), f32_at(4), 0.0, 1.0], + 17 | 18 => [u32_at(0) as f32, u32_at(4) as f32, 0.0, 1.0], + 19..=22 => [f32_at(0), (u32_at(4) & 255) as f32, 0.0, 1.0], + 23..=25 => { + let v = u32_at(0); + [ + (v & 1023) as f32 / 1023.0, + (v >> 10 & 1023) as f32 / 1023.0, + (v >> 20 & 1023) as f32 / 1023.0, + (v >> 30) as f32 / 3.0, + ] + } + 26 => { + let v = u32_at(0); + [small(v & 2047, 6), small(v >> 11 & 2047, 6), small(v >> 22, 5), 1.0] + } + 27..=29 | 31 | 87..=93 => [0, 1, 2, 3].map(|i| u8_at(i) / 255.0), + 30 | 32 => [0, 1, 2, 3].map(u8_at), + 33 | 34 => [half(b), half(&b[2..]), 0.0, 1.0], + 35 => [u16_at(0) / 65535.0, u16_at(2) / 65535.0, 0.0, 1.0], + 36..=38 => [u16_at(0), u16_at(2), 0.0, 1.0], + 39..=41 => [f32_at(0); 4], + 42 | 43 | 67 => { + let v = u32_at(0); + let scale = 2f32.powi((v >> 27) as i32 - 24); + [(v & 511) as f32 * scale, (v >> 9 & 511) as f32 * scale, (v >> 18 & 511) as f32 * scale, 1.0] + } + 44..=47 => [(u32_at(0) & 0xff_ffff) as f32 / 16_777_215.0; 4], + 48 | 49 => [u8_at(0) / 255.0, u8_at(1) / 255.0, 0.0, 1.0], + 50..=52 => [u8_at(0), u8_at(1), 0.0, 1.0], + 53 | 54 => [half(b); 4], + 55 | 56 => [u16_at(0) / 65535.0; 4], + 57..=59 => [u16_at(0); 4], + 60 | 61 | 65 => [u8_at(0) / 255.0; 4], + 62..=64 => [u8_at(0); 4], + _ => [0.0; 4], + } +} + +/// Which textures to save, and how. +#[derive(Clone, Debug, Default)] +pub struct Images { + /// Resource and subresource; of none: all textures the frame's shaders + /// write, from this many texels on. + pub which: Vec<(u32, u32)>, + pub least: u64, + pub folder: PathBuf, + /// The widest picture. + pub width: u32, + /// The values too (`.bin`: rows of texels without padding). + pub raw: bool, +} + +impl Player { + /// Runs the frame once as the options say (`until` ends it early) and + /// saves what textures hold, with their least, mean and greatest values. + pub fn images(&mut self, o: &Options, images: &Images, say: &mut dyn FnMut(String)) -> Result<()> { + let mut made = self.prepare(o)?; + self.once(o, &mut made)?; + drop(made); + let mut which = images.which.clone(); + if which.is_empty() { + let texels = |r: &wire::Resource| r.desc.width * u64::from(r.desc.height) * u64::from(r.desc.depth); + which = self + .frame + .resources + .iter() + .filter(|r| { + r.desc.dimension != D3D12_RESOURCE_DIMENSION_BUFFER.0 + && self.card_writes.contains(&r.id) + && texels(r) >= images.least + }) + .map(|r| (r.id, 0)) + .collect(); + } + std::fs::create_dir_all(&images.folder)?; + for (id, sub) in which { + let Some(at) = self.objects.get(&id).map(|o| o.index) else { + say(format!("{id}: not there")); + continue; + }; + let r = &self.frame.resources[at]; + if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 || r.desc.samples[0] > 1 { + say(format!("{id}: a buffer or multisampled")); + continue; + } + let (name, own) = (r.name.clone(), r.desc.format); + let (f, _) = gpu::footprints(&self.device, &gpu::to_desc(&r.desc), sub, 1); + let f = f[0].Footprint; + let called = self.called(id); + // The planes of depth formats come back as these. + let format = if matches!(f.Format.0, 39 | 53 | 60) { f.Format.0 } else { own }; + let Some(bytes) = texel_bytes(format) else { + say(format!("{called}.{sub}: format {format} is not shown")); + continue; + }; + let Some(all) = self.contents_of(id, sub)? else { + continue; + }; + let (mut least, mut most, mut sum) = ([f32::INFINITY; 4], [f32::NEG_INFINITY; 4], [0f64; 4]); + let (mut zero, mut bad, mut n) = (0u64, 0u64, 0u64); + let slice = f.RowPitch as usize * f.Height as usize; + let mut raw = Vec::new(); + for y in 0..f.Height as usize * f.Depth as usize { + let from = y * f.RowPitch as usize; + let row = &all[from..from + f.Width as usize * bytes]; + if images.raw { + raw.extend_from_slice(row); + } + for t in row.chunks_exact(bytes) { + let v = texel(format, t); + n += 1; + if v.iter().any(|x| !x.is_finite()) { + bad += 1; + continue; + } + zero += u64::from(v[..3] == [0.0; 3]); + for c in 0..4 { + least[c] = least[c].min(v[c]); + most[c] = most[c].max(v[c]); + sum[c] += f64::from(v[c]); + } + } + } + let mean = sum.map(|s| s / (n - bad).max(1) as f64); + say(format!( + "{called}.{sub}: {}x{}x{} least {least:.4?} mean {mean:.4?} greatest {most:.4?}, {:.1}% zero, {bad} not numbers", + f.Width, + f.Height, + f.Depth, + zero as f64 * 100.0 / n.max(1) as f64, + )); + let stem: String = name + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '_') + .take(40) + .collect(); + let file = |end: String| images.folder.join(format!("{id:05}.{sub}_{stem}{end}")); + if images.raw { + std::fs::write(file(format!("_f{format}_{}x{}x{}.bin", f.Width, f.Height, f.Depth)), &raw)?; + } + // Values from 0 to 1 as they are, others bent so that the mean + // is a middle grey. Slices of a 3D texture beside each other. + let unit = most[..3].iter().all(|&m| m <= 1.0) && least[..3].iter().all(|&m| m >= 0.0); + let grey = ((mean[0] + mean[1] + mean[2]) / 3.0).max(1e-9) as f32; + let slices = f.Depth.clamp(1, 16); + let step = (f.Width * slices).div_ceil(images.width.max(64)).max(1); + let (w, h) = ((f.Width / step).max(1), (f.Height / step).max(1)); + let mut rgb = Vec::with_capacity((w * slices * h * 3) as usize); + for y in 0..h as usize { + for s in 0..slices as usize { + let z = s * f.Depth as usize / slices as usize; + for x in 0..w as usize { + let from = z * slice + y * step as usize * f.RowPitch as usize + x * step as usize * bytes; + let v = texel(format, &all[from..from + bytes]); + for c in &v[..3] { + let c = match c.max(0.0) { + _ if c.is_nan() => 1.0, + c if unit => c, + c => c / (c + grey), + }; + rgb.push((c.clamp(0.0, 1.0).powf(1.0 / 2.2) * 255.0) as u8); + } + } + } + } + std::fs::write(file(".png".into()), crate::capture::png(w * slices, h, &rgb))?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn texels() { + assert_eq!(texel(10, &[0, 0x3c, 0, 0xc0, 0, 0, 0, 0x38]), [1.0, -2.0, 0.0, 0.5]); + assert_eq!(texel(26, &(15u32 << 6 | 16 << 17 | 14 << 27).to_le_bytes()), [1.0, 2.0, 0.5, 1.0]); + assert_eq!(texel(67, &(16u32 << 27 | 256).to_le_bytes()), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(texel(24, &(1023u32 << 10).to_le_bytes()), [0.0, 1.0, 0.0, 0.0]); + assert!(texel(54, &[1, 0x7c])[0].is_nan()); + } +} diff --git a/docs/replay.md b/docs/replay.md index a132db3..42c0a61 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -97,6 +97,9 @@ report counts them). `--no-merge` runs the copies as recorded. | `--slots :` | the heap slots its constants name | | `--check-written` | that everything the frame changes is put back | | `--upcopies` | runs the frame twice: which words the copies of the CPU's sides of card buffers bring that the card holds another value of (those the card wrote alike in both runs are the ones to look at), and which pieces shaders wrote that were not declared as written. The live check is `VICTORY_UPCOPY_CHECK=1` (`host/upcheck.rs`) | +| `--flow ` | what the dispatches (`--flow-draws`: draws too) have bound: pipeline, root arguments, heap slots their constants lead to; no device is made | +| `--images ` | runs the frame once and saves the textures its shaders write (or `--texture [.]`, repeatable) as pictures, with least, mean and greatest values; `--raw`: the values too | +| `--until :` | nothing but barriers after that command | | `--dump ` | the DXIL of the pipelines named, in `shaders` | The `--diverge` family runs the recorded copies without the merge. From 0b5f191b86116510d1e1b804f6ae18c961103a00 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 00:00:07 -0600 Subject: [PATCH 196/445] A pipeline sync waits for shader writes on the host The console's syncs recorded nothing on the host, which orders nothing between dispatches by itself. The ray-tracing structure builder has no other wait between its stages. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/list.rs | 41 ++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 02ad326..cefffc5 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1396,16 +1396,43 @@ extern "system" fn set_pipeline(this: This, pipeline: This) { } /// Pipeline syncs: waits for earlier work and cache flushes, at the top or -/// bottom of the pipe `(flags, control, address, size)`. Host lists order -/// their own work and every submission is waited for, so there is nothing -/// to do. +/// bottom of the pipe `(flags, control, address, size)`. The host orders +/// nothing between dispatches by itself: what shaders wrote is waited for +/// here as at the title's barriers (the ray-tracing structure builder has +/// no other wait between its stages). /// (Arguments may be what earlier shaders wrote from here on: /// `State::synced`.) -extern "system" fn sync(this: This, _flags: u32, _control: u32, _address: u64, _size: u64) { +extern "system" fn sync(this: This, flags: u32, control: u32, address: u64, size: u64) { #[cfg(windows)] - with_state(this, |_, state| state.synced()); - #[cfg(not(windows))] - let _ = this; + { + with_state(this, |_, state| state.synced()); + if let Some(list) = host_list(this) { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + #[cfg(feature = "diagnostics")] + { + // The shapes of the title's calls, each once. + static SEEN: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let shape = (flags, control, address == 0); + if seen.len() < 64 && !seen.contains(&shape) { + seen.push(shape); + tracing::info!( + flags = format_args!("{flags:#x}"), + control = format_args!("{control:#x}"), + address = format_args!("{address:#x}"), + size = format_args!("{size:#x}"), + "a pipeline sync" + ); + } + crate::copystat::add(crate::copystat::C::WaitsForGroups, 1); + } + // SAFETY: the same layout; no resource named. + let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; + // SAFETY: an open list. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + } + } + let _ = (this, flags, control, address, size); } /// Reset with console flags `(allocator, pipeline, flags)`; the flags only From ba509c5a70c8583f393ce4cb4b39f570e5d6e7b7 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 00:00:08 -0600 Subject: [PATCH 197/445] Addresses of ray-tracing structures: views of a structure have no buffer A shader that walks a structure takes its address out of the structure's descriptor. The view has no resource, so the address came out 0 and every ray missed. Also: only programs that store by raw address declare the copies they reach that way as written. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 14 +++++++ crates/victory-gpu/src/draw.rs | 51 ++++++++++++++++++----- crates/victory-gpu/src/pipeline.rs | 21 ++++++++++ 3 files changed, 75 insertions(+), 11 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 213a11a..dbc9def 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1649,6 +1649,20 @@ pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> { )) } +/// The address a shader finds in a descriptor of title memory: where a +/// buffer view starts, or the ray-tracing structure of a structure's view +/// (no resource: the view's description holds the address, and the shader +/// walks the structure from there itself). +pub(crate) fn view_address(view: &View) -> Option { + const STRUCTURE: u32 = D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32; + match view { + View::Shader(_, Some(desc)) if desc[1] == STRUCTURE => { + Some(u64::from(desc[4]) | u64::from(desc[5]) << 32) + } + _ => buffer_range(view).map(|range| range.0), + } +} + /// The title memory the host slot of buffer view `view` is made on /// (address, bytes): the whole buffer the view is of, which is what /// [`make`] finds the host copy by. [`buffer_range`] is the part of it the diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 25c2917..88bcd33 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -960,15 +960,17 @@ impl State { once!(kind, "a shader reads a host value this build does not know"); return 0; } - // The title address of the buffer view at that dword of the table. - let address = match self.roots_ref(compute).get(usize::from(slot)) { - Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4) - .and_then(|view| crate::descriptor::host::buffer_range(&view)) - .map_or(0, |range| range.0), - _ => 0, - }; + let address = self.view_address(compute, slot, dword); if address == 0 { - once!(slot, dword, "a shader takes the address of a buffer view that is not there: it reads 0"); + // The first few say what lies there instead. + static SAID: AtomicU64 = AtomicU64::new(0); + if SAID.fetch_add(1, Ordering::Relaxed) < 8 { + let view = match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4), + _ => None, + }; + tracing::warn!(slot, dword, ?view, "a shader takes the address of a buffer view that is not there: it reads 0"); + } } if kind == USER_VIEW_ADDRESS { address as u32 @@ -977,10 +979,29 @@ impl State { } } + /// The title address the view at dword `dword` of the table in root + /// slot `slot` starts at, 0 without one. + fn view_address(&self, compute: bool, slot: u8, dword: u32) -> u64 { + match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4) + .and_then(|view| crate::descriptor::host::view_address(&view)) + .unwrap_or(0), + _ => 0, + } + } + /// For a shader that reads title memory by address /// ([`crate::memory`]): its directory, fault notes and view slots, - /// with the pages of the root views the list has set made ready. - fn memory_ready(&self, list: &HostList, compute: bool, writes: bool) -> Option { + /// with the pages made ready of the root views the list has set and of + /// the views whose addresses it takes (`t`: the ray-tracing structures + /// it walks). + fn memory_ready( + &self, + list: &HostList, + t: &crate::pipeline::Translated, + compute: bool, + writes: bool, + ) -> Option { let heap = match self.heaps[0] { 0 => None, h => crate::descriptor::heap(h as This).host(), @@ -993,6 +1014,11 @@ impl State { _ => {} } } + for u in &t.host.user_data { + if u.root == RootType::Other(victory_shader::emit::USER_VIEW_ADDRESS) { + addresses.push(self.view_address(compute, u.slot, u.dword)); + } + } crate::memory::ready(list, heap, &addresses, &constants, writes) } @@ -1179,7 +1205,10 @@ impl State { && !crate::pipeline::builder_quarantined(self.pipeline as This); // Title memory by address: what the shader finds it by. let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) { - let Some(ready) = self.memory_ready(list, compute, writes) else { + // Only through a store by address: what it stores through + // views is declared with them. + let writes = writes && t.stores_by_address; + let Some(ready) = self.memory_ready(list, &t, compute, writes) else { once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped"); return false; }; diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 2ace811..971a351 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -126,6 +126,8 @@ pub(crate) struct Translated { /// Whether the shader's code can store to buffer memory ([`stores`]); /// true when its code is not known. pub(crate) stores: bool, + /// Whether it can store through raw addresses ([`stores_by_address`]). + pub(crate) stores_by_address: bool, /// Whether it stores through a view it picks from the heap by an index, /// once asked (`crate::picked`). pub(crate) picks: std::sync::atomic::AtomicU8, @@ -198,6 +200,7 @@ fn translate(container: &[u8]) -> Result { }; let host = crate::shader_cache::host_shader(container)?; let stores = programs.is_empty() || programs.iter().any(stores); + let stores_by_address = programs.is_empty() || programs.iter().any(stores_by_address); let used = programs .into_iter() .find(|p| { @@ -212,6 +215,7 @@ fn translate(container: &[u8]) -> Result { host, used, stores, + stores_by_address, picks: Default::default(), }) } @@ -360,6 +364,23 @@ fn stores(program: &victory_shader::NativeProgram) -> bool { }) } +/// Whether a console program can store to memory through raw addresses +/// (`crate::memory`): a flat or global store or atomic, or code that does +/// not decode. The programs that only walk ray-tracing structures do not, +/// whatever they store through views. +#[cfg(windows)] +fn stores_by_address(program: &victory_shader::NativeProgram) -> bool { + use victory_shader::gfx10::{Encoding, decode}; + let Ok(code) = decode(&program.code) else { + return true; + }; + code.iter().any(|i| { + matches!(i.encoding, Encoding::Flat | Encoding::Global) + && i.name() + .is_none_or(|n| (n.contains("store") || n.contains("atomic")) && !n.contains("scratch")) + }) +} + #[repr(C)] struct Pipeline { object: Object, From 240ea7a2bf9f6836f5861d23221af1d4730f085d Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:53:57 -0600 Subject: [PATCH 198/445] Buffer views that begin between elements read their own bytes A view D3D12 cannot place (a raw view off 16 bytes, a structured one off 16 and off its stride, a typed one off its element) was null, and the shader read zeros: the colour-table bakes' parameter blocks are raw views at byte 8. Such a view now gets a copy of its own bytes. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit b2a3ce9ced69e669d2d56e20c2dca7011b7e405a) --- crates/victory-gpu/src/descriptor/host.rs | 189 ++++++++++++++++++++-- crates/victory-gpu/src/host.rs | 3 +- crates/victory-gpu/src/shadow.rs | 49 ++++++ 3 files changed, 225 insertions(+), 16 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 7b714c8..e37a6d6 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -545,6 +545,19 @@ pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync /// them for indexed reads (structured: the stride; raw: 1, the index is the /// byte; typed: the format's); `None` if `view` is not a buffer view. fn view_stride(view: &View) -> Option { + let (stride, raw, format) = view_elements(view)?; + Some(if stride > 0 { + stride + } else if raw { + 1 + } else { + crate::resource::element(format).map_or(0, |(bytes, _)| bytes as u32) + }) +} + +/// 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)> { const BUFFER: u32 = 1; let (words, unordered): (&[u32; 10], bool) = match view { View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false), @@ -555,26 +568,67 @@ fn view_stride(view: &View) -> Option { _ => return None, }; // SAFETY: buffer views' union members. - let (stride, raw, format) = unsafe { + Some(unsafe { if unordered { let d = uav_desc(words); let b = d.Anonymous.Buffer; - (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, d.Format) + (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, d.Format.0 as u32) } else { let d = srv_desc(words); let b = d.Anonymous.Buffer; - (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, d.Format) + (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, d.Format.0 as u32) } - }; - Some(if stride > 0 { - stride - } else if raw { - 1 - } else { - crate::resource::element(format.0 as u32).map_or(0, |(bytes, _)| bytes as u32) }) } +/// Whether a buffer view that begins `offset` bytes into its host copy begins +/// where no host view can: raw views begin on 16 bytes, others on a multiple +/// of their elements (`stride` of a structured one, which is made raw where it +/// can be, `element` of a typed one). The console's begin on any dword, and +/// the title puts parameter blocks at ring positions: a raw view of 128 bytes +/// at 8 (the colour table bakes'), structured ones of elements that are no +/// divisor of their place (the culling's 456-byte constants). Such a view gets +/// a copy of its own bytes ([`crate::shadow::own_bytes`]). +fn off_elements(offset: u64, stride: u32, raw: bool, element: u64) -> bool { + if offset.is_multiple_of(16) { + false + } else if raw { + true + } else if stride > 0 { + !offset.is_multiple_of(u64::from(stride)) + } else { + element > 0 && !offset.is_multiple_of(element) + } +} + +/// Whether views off their copy's elements get a copy of their own bytes. On by +/// default; `VICTORY_VIEW_BYTES=0` leaves them null, as before. +fn view_bytes() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_BYTES").is_none_or(|v| v != "0")) +} + +/// The copy the buffer view of `[start, start + len)` is made on: `shadow`, the one +/// its buffer has, or one of the view's own bytes ([`off_elements`]). +fn view_home( + shadow: std::sync::Arc, + start: u64, + len: u64, + (stride, raw, format): (u32, bool, u32), +) -> std::sync::Arc { + let Some(offset) = shadow.offset_in(start).map(|_| shadow.offset(start)) else { + return shadow; + }; + if offset.is_multiple_of(16) || !view_bytes() { + return shadow; + } + let element = crate::resource::element(format).map_or(0, |(bytes, _)| bytes); + if !off_elements(offset, stride, raw, element) { + return shadow; + } + crate::shadow::own_bytes(start, len).unwrap_or(shadow) +} + /// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for /// device-removed reports: a shader indexing a heap past its end faults. static GPU_RANGES: Mutex> = Mutex::new(Vec::new()); @@ -1716,9 +1770,10 @@ pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc Option { - let shadow = crate::shadow::find(address, len)?; - let offset = shadow.offset(address); + let mut shadow = crate::shadow::find(address, len)?; + let mut offset = shadow.offset(address); + let unit = element_size(&desc); + // SAFETY: a buffer view's union member. + let own = unsafe { &mut desc.Anonymous.Buffer }; + let start = address + own.FirstElement * unit; + let kind = (own.StructureByteStride, own.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, desc.Format.0 as u32); + let home = view_home(shadow.clone(), start, u64::from(own.NumElements) * unit, kind); + if !std::sync::Arc::ptr_eq(&home, &shadow) { + // Its own bytes: it begins where they do. + (shadow, offset) = (home, 0); + own.FirstElement = 0; + } // A structured view as a raw view of the same bytes (see `raw_window`). // SAFETY: a buffer view's union member. let structured = unsafe { desc.Anonymous.Buffer }; @@ -1878,7 +1944,29 @@ fn buffer_uav( mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE, ) -> Option { - let shadow = crate::shadow::find(address, len)?; + let mut shadow = crate::shadow::find(address, len)?; + let unit = { + // SAFETY: a buffer view's union member. + let b = unsafe { desc.Anonymous.Buffer }; + if b.StructureByteStride > 0 { + u64::from(b.StructureByteStride) + } else if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + } + }; + // SAFETY: a buffer view's union member. + let own = unsafe { &mut desc.Anonymous.Buffer }; + let start = address + own.FirstElement * unit; + let kind = (own.StructureByteStride, own.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, desc.Format.0 as u32); + let home = view_home(shadow.clone(), start, u64::from(own.NumElements) * unit, kind); + let mut address = address; + if !std::sync::Arc::ptr_eq(&home, &shadow) { + // Its own bytes: it begins where they do. + (shadow, address) = (home, start); + own.FirstElement = 0; + } // SAFETY: a live buffer. let flags = unsafe { shadow.buffer.GetDesc() }.Flags; if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { @@ -2571,6 +2659,77 @@ mod tests { assert!(buffer_view_ok(DXGI_FORMAT_UNKNOWN, 1, 10, 12, false, 4096)); } + /// Views that begin where no host view can: raw ones off 16 bytes, + /// structured ones off their elements (and off 16 bytes, where they are + /// made raw), typed ones off theirs. + #[test] + fn views_off_their_elements_are_told() { + // the colour table bakes' parameter block: raw, 8 bytes into its window + assert!(off_elements(8, 0, true, 4)); + assert!(!off_elements(0, 0, true, 4)); + assert!(!off_elements(48, 0, true, 4)); + // 456-byte elements: at one of them, on 16 bytes, at neither + assert!(!off_elements(456, 456, false, 0)); + assert!(!off_elements(32, 456, false, 0)); + assert!(off_elements(100, 456, false, 0)); + assert!(!off_elements(12, 0, false, 4)); + assert!(off_elements(12, 0, false, 8)); + } + + /// Such a view is made on a copy of its own bytes, and that copy is the one + /// brought up to date for it; another's is its buffer's. + #[test] + fn views_off_their_elements_get_a_copy_of_their_bytes() { + let Some(host) = host() else { + return; // no host GPU here + }; + let memory = vec![0u64; 1 << 13]; + let start = (memory.as_ptr() as u64).next_multiple_of(4096); + // SAFETY: a plain CPU-side heap of one view. + let cpu: ID3D12DescriptorHeap = unsafe { + host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 1, + ..Default::default() + }) + } + .unwrap(); + // SAFETY: a live heap. + let at = unsafe { cpu.GetCPUDescriptorHandleForHeapStart() }; + // Memory placed at `address`, seen as the title passes it: raw, 32 + // dwords, or four 456-byte elements. + let view = |address: u64, raw: bool| { + let resource: [u32; 14] = [1, 0, 0, 0, 4 * 456, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0]; + let mut desc = [0u32; 16]; + let words = if raw { + [39, 1, 5768, 0, 0, 0, 32, 0, 1, 0] + } else { + [0, 1, 5768, 0, 0, 0, 4, 456, 0, 0] + }; + desc[..10].copy_from_slice(&words); + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + View::Placed(false, resource, desc) + }; + let width = |v: &View| { + let made = make(v, at).expect("a view").expect("a buffer"); + // SAFETY: a live buffer. + unsafe { made.GetDesc() }.Width + }; + for (off, raw, len) in [(8, true, 128u64), (8, false, 4 * 456)] { + let v = view(start + off, raw); + assert_eq!(width(&v), len.next_multiple_of(256)); + let (copy, address, bytes) = buffer_copy(&v).unwrap(); + assert_eq!((copy.span(), address, bytes), ((start + off, len), start + off, len)); + } + for (off, raw) in [(16, true), (32, false)] { + let v = view(start + off, raw); + let (copy, ..) = buffer_copy(&v).unwrap(); + assert_ne!(copy.span().0, start + off, "its buffer's copy"); + // SAFETY: a live buffer. + assert_eq!(width(&v), unsafe { copy.buffer.GetDesc() }.Width); + } + } + /// The queue of textures picked by index serves the slots looked at /// before first, then the newest write and the oldest in turns; a /// slot whose memory is not there is looked at again after diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 3c7619a..e6c1552 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -7176,8 +7176,9 @@ impl Meter { du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed), du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed), refused = format!( - "{}; depth twins: {} alive, {} depth textures left without one; twin copies per frame: {twin_to_depth:.1} into depth textures, {twin_to_colour:.1} into twins; depth planes: {planes:.1} drawn from their twins per frame, {} times not given back to a twin, {} times used before the pass", + "{} ({} copies made of views off their buffer's elements); depth twins: {} alive, {} depth textures left without one; twin copies per frame: {twin_to_depth:.1} into depth textures, {twin_to_colour:.1} into twins; depth planes: {planes:.1} drawn from their twins per frame, {} times not given back to a twin, {} times used before the pass", crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed), + crate::shadow::OWN_MADE.load(Ordering::Relaxed), crate::resource::TWINS[0].load(Ordering::Relaxed), crate::resource::TWINS[1].load(Ordering::Relaxed), crate::resource::PLANES[1].load(Ordering::Relaxed), diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 261b497..b94250f 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -4191,6 +4191,55 @@ fn longest_tail(windows: impl Iterator, address: u64, end: u6 .min() } +/// Copies of single views' bytes ([`own_bytes`]), by (start, length), with +/// the use that last asked for each. +#[allow(clippy::type_complexity)] +static OWN: Mutex<(u64, BTreeMap<(u64, u64), (Arc, u64)>)> = Mutex::new((0, BTreeMap::new())); + +/// Copies [`OWN`] keeps: ring positions change every frame, so the least +/// recently asked for go (lists and heap slots using one keep its buffer +/// alive). +/// shortcut: a slot whose view goes unused while this many others are asked +/// for shows the buffer of a copy that is made anew at its next use. +const OWN_KEPT: usize = 1024; +/// The largest of them: one this long is no parameter block. +const OWN_MOST: u64 = 4 << 20; + +/// A host copy of the `len` bytes at `address` alone, for a view no host +/// view of its buffer's copy can stand for (it would not begin where host +/// views may; upstream 86a5ed6). What other views' shaders write there in the +/// same submission it does not see: it is as title memory is at the +/// submission, and what is written through it goes back there after. +/// `None`: no view the title made on purpose (off its dwords, empty or huge). +pub(crate) fn own_bytes(address: u64, len: u64) -> Option> { + if len == 0 || len > OWN_MOST || !address.is_multiple_of(4) { + return None; + } + let mut guard = OWN.lock().unwrap_or_else(|e| e.into_inner()); + let (tick, map) = &mut *guard; + *tick += 1; + if let Some((shadow, used)) = map.get_mut(&(address, len)) { + *used = *tick; + return Some(shadow.clone()); + } + if map.len() >= OWN_KEPT + && let Some(&oldest) = map.iter().min_by_key(|(_, (_, used))| *used).map(|(k, _)| k) + { + map.remove(&oldest); + } + let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(256))?; + crate::host::name(&buffer, || format!("title view {address:#x}+{len:#x}")); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let shadow = Arc::new(Shadow::new(buffer, data, gpu, address, len)); + map.insert((address, len), (shadow.clone(), *tick)); + OWN_MADE.fetch_add(1, Ordering::Relaxed); + Some(shadow) +} + +/// Copies of single views' bytes made since the start. +pub(crate) static OWN_MADE: AtomicU64 = AtomicU64::new(0); + /// Copies of title memory outside buffers, by (start, length). static LOOSE: Mutex>> = Mutex::new(BTreeMap::new()); From 7232f45847b6f1edcb9552b5c38f33ed34c4c7cd Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 00:20:28 -0600 Subject: [PATCH 199/445] Stores by raw address declare what their dispatch names, not every copy reached so far Also: victory replay --images writes the bytes of buffers. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/memory.rs | 51 +++++++++++++++------- crates/victory-gpu/src/replay/play/look.rs | 12 ++++- docs/replay.md | 2 +- 3 files changed, 46 insertions(+), 19 deletions(-) diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 67ebe7a..a85ee02 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -39,9 +39,12 @@ //! //! shortcut: a copy that is numbered is kept for the rest of the run, and //! there are at most [`COPIES`] of them (4 MiB windows mostly: 4 GiB at -//! most). Every dispatch of such a shader brings all numbered copies up to -//! date and, if it can store, declares all of them written (the bytes are -//! compared on the CPU afterwards, as for any unordered access view): a +//! most). Every list with such a shader brings all numbered copies up to +//! date. A dispatch that can store through raw addresses declares the +//! copies it names as written (the bytes are compared afterwards, as for +//! any unordered access view); what a stage stores through pointers it +//! reads out of memory is declared if a stage of the same list names the +//! copy, and otherwise stays in the host's copy until one does. A //! dirty-page mask written by the shader would bound both. use std::collections::HashMap; @@ -115,8 +118,19 @@ impl Memory { } /// Gives the page of `address` its copy, if it has none and the memory - /// is the title's. - fn map(&mut self, address: u64) { + /// is the title's; the place of its copy in `copies`. + fn map(&mut self, address: u64) -> Option { + self.make(address); + let page = address / PAGE; + if page >= u64::from(MEMORY_PAGES) - 1 { + return None; + } + // SAFETY: inside the directory's mapping. + let number = unsafe { self.directory.1.add(page as usize * 2).read() }; + (number as usize).checked_sub(1) + } + + fn make(&mut self, address: u64) { let page = address / PAGE; // The last entry stays empty: addresses past the directory read it. if page >= u64::from(MEMORY_PAGES) - 1 { @@ -226,10 +240,15 @@ impl Memory { } /// What a dispatch names: the copy around `address` and the 4 MiB - /// after it. - fn name(&mut self, address: u64) { - self.map(address); - self.map((address & !(CELL - 1)) + CELL); + /// after it; their places in `copies`. + fn name(&mut self, address: u64, named: &mut Vec) { + for at in [address, (address & !(CELL - 1)) + CELL] { + if let Some(n) = self.map(at) + && !named.contains(&n) + { + named.push(n); + } + } } } @@ -237,7 +256,7 @@ impl Memory { /// root arguments name gets its copies (`addresses`: its root views; /// `constants`: its root constants, see the module), every numbered copy /// has its view in `heap`'s run and is brought up to date when `list` is -/// submitted (and, with `writes`, copied back after). None if the host +/// submitted (and, with `writes`, the named ones copied back after). None if the host /// cannot hold it; the draw is then dropped. pub(crate) fn ready( list: &HostList, @@ -258,8 +277,9 @@ pub(crate) fn ready( m.take_faults(); } let numbered = m.copies.len(); + let mut named = Vec::new(); for &address in addresses { - m.name(address); + m.name(address, &mut named); } // A title address in two constants (low dword, then bits 32 to 39), or // in one in 256-byte units. A constant that only looks like one names @@ -269,10 +289,10 @@ pub(crate) fn ready( && (1..=0xFF).contains(&high) && c >= 0x1_0000 { - m.name(u64::from(c) | u64::from(high) << 32); + m.name(u64::from(c) | u64::from(high) << 32, &mut named); } if c >= 0x0100_0000 { - m.name(u64::from(c) << 8); + m.name(u64::from(c) << 8, &mut named); } } let key = std::ptr::from_ref(heap) as usize; @@ -295,15 +315,14 @@ pub(crate) fn ready( // shortcut: a copy another list numbers meanwhile is brought up to date // by that list's submission, which may run after this one's. const READ: usize = usize::MAX - 0x6d; - const WRITE: usize = usize::MAX - 0x6e; + const WRITE: usize = usize::MAX - 0x1_0000; let first_read = list.first_use(READ); - let first_write = writes && list.first_use(WRITE); for (n, shadow) in m.copies.iter().enumerate() { let (start, len) = shadow.span(); if first_read || n >= numbered { shadow.refresh(list, start, len); } - if writes && (first_write || n >= numbered) { + if writes && named.contains(&n) && list.first_use(WRITE - n) { #[cfg(feature = "diagnostics")] crate::host::wide_write(start, len, 1); shadow.gpu_writes(list, start, len); diff --git a/crates/victory-gpu/src/replay/play/look.rs b/crates/victory-gpu/src/replay/play/look.rs index 42f534d..62df3bc 100644 --- a/crates/victory-gpu/src/replay/play/look.rs +++ b/crates/victory-gpu/src/replay/play/look.rs @@ -340,8 +340,16 @@ impl Player { continue; }; let r = &self.frame.resources[at]; - if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 || r.desc.samples[0] > 1 { - say(format!("{id}: a buffer or multisampled")); + if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { + // A buffer: its bytes. + if let Some(all) = self.contents_of(id, 0)? { + std::fs::write(images.folder.join(format!("{id:05}.bin")), &all)?; + say(format!("{}: {} bytes", self.called(id), all.len())); + } + continue; + } + if r.desc.samples[0] > 1 { + say(format!("{id}: multisampled")); continue; } let (name, own) = (r.name.clone(), r.desc.format); diff --git a/docs/replay.md b/docs/replay.md index 54169e7..654bbb4 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -122,7 +122,7 @@ report counts them). `--no-merge` runs the copies as recorded. | `--check-written` | that everything the frame changes is put back | | `--upcopies` | runs the frame twice: which words the copies of the CPU's sides of card buffers bring that the card holds another value of (those the card wrote alike in both runs are the ones to look at), and which pieces shaders wrote that were not declared as written. The live check is `VICTORY_UPCOPY_CHECK=1` (`host/upcheck.rs`) | | `--flow ` | what the dispatches (`--flow-draws`: draws too) have bound: pipeline, root arguments, heap slots their constants lead to; no device is made | -| `--images ` | runs the frame once and saves the textures its shaders write (or `--texture [.]`, repeatable) as pictures, with least, mean and greatest values; `--raw`: the values too | +| `--images ` | runs the frame once and saves the textures its shaders write (or `--texture [.]`, repeatable) as pictures, with least, mean and greatest values; `--raw`: the values too; of a buffer named, its bytes | | `--until :` | nothing but barriers after that command | | `--dump ` | the DXIL of the pipelines named, in `shaders` | From 350f7f492b7e862840613e6caf358e923c56f889 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 00:29:19 -0600 Subject: [PATCH 200/445] Title buffer copies stand where the list has them (VICTORY_COPIES_IN_PLACE) On by default. They were all done on the CPU when their submission was prepared, ahead of its first draw: of copy, draw, copy, draw both draws read the second, and a source a shader writes earlier in the submission was read as it was before. The list copies now, in the destination's host copy, out of the source's host copy where shaders write it, else out of upload memory filled at submission; copies into textures take what shaders wrote too. Title memory and the reference of the host copy take the bytes at submission as before, so the landing finds only what the card made of them. VICTORY_WINDOWS_OWN=1 (off): windows have two sides as well. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 6 + crates/victory-gpu/src/host.rs | 83 ++++-- crates/victory-gpu/src/host/card_steps.rs | 12 + crates/victory-gpu/src/host/place.rs | 320 ++++++++++++++++++++++ crates/victory-gpu/src/host/upcheck.rs | 235 ++++++++++++++++ crates/victory-gpu/src/list.rs | 40 ++- crates/victory-gpu/src/shadow.rs | 65 +++++ 7 files changed, 738 insertions(+), 23 deletions(-) create mode 100644 crates/victory-gpu/src/host/place.rs diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index fae76c3..56d09da 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3046,6 +3046,12 @@ impl State { } } + /// A buffer was copied to: what was clamped of it ahead is clamped anew. + pub(crate) fn copied(&mut self) { + self.window = None; + self.batch = None; + } + /// The title waits for earlier work (a barrier or a pipeline sync). pub(crate) fn synced(&mut self) { if self.batch.as_ref().is_some_and(|b| b.wrote) { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 3c7619a..6b26209 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1376,11 +1376,10 @@ impl Drop for Counted { } /// A chunk of upload memory for lists' scratch data: the buffer, its -/// mapping and its host GPU address. +/// mapping. struct Chunk { - _buffer: ID3D12Resource, + buffer: ID3D12Resource, data: usize, - gpu: u64, } // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping, @@ -1472,14 +1471,11 @@ fn take_chunk(host: &Host, size: u64) -> Option { } let (buffer, data) = host.upload_buffer(size)?; name(&buffer, || "list scratch".into()); - // SAFETY: a live buffer. - let gpu = unsafe { buffer.GetGPUVirtualAddress() }; ALIVE[1].fetch_add(1, Ordering::Relaxed); ALIVE[2].fetch_add(size, Ordering::Relaxed); Some(Chunk { - _buffer: buffer, + buffer, data: data as usize, - gpu, }) } @@ -1746,6 +1742,9 @@ enum Step { /// Brings a texture's staging buffer up to date: once per submission, /// whichever lists sample it, until a `Copy` or `Run` intervenes. Texture(std::sync::Arc), + /// A title buffer copy that the list does on the card ([`place`]): what + /// is done on the CPU for it. + Placed(place::Placed), } /// What a list does on the CPU when it is submitted: copies between host @@ -2433,6 +2432,8 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op if written.is_empty() { return None; } + // Destinations of copies at their place, if a step reads them. + let mut placed: Vec<(usize, usize)> = Vec::new(); for list in runs { for step in &list.deferred().copies { match step { @@ -2472,11 +2473,23 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op } } Step::Run(_) => return Some(WHY_RUN), + Step::Placed(p) => match p.waits(written) { + place::Waits::No => {} + place::Waits::ForReaders => placed.push((p.dst, p.dst + p.len)), + place::Waits::Yes => { + if count { + LATE_STATS[15].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + blame("a buffer copy at its place", written, p.src, p.len); + } + return Some(WHY_READ); + } + }, Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {} } } } - None + (!placed.is_empty() && place::read_by(runs, placed)).then_some(WHY_READ) } /// With flights in the air, after the submission's write-watch asking: @@ -2997,6 +3010,16 @@ fn late_line(frames: f64) { } } crate::land::log(frames); + if place::on() { + let t: Vec = place::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "title buffer copies at their place in the lists, per frame (VICTORY_COPIES_IN_PLACE): {:.1} of {:.1} KB, {:.1} of them out of what shaders wrote; {:.2} copies into textures out of what shaders wrote", + t[0], + t[1] / 1024.0, + t[2], + t[3], + ); + } card_steps::log(frames); crate::picked::log(frames); #[cfg(feature = "diagnostics")] @@ -3012,6 +3035,7 @@ fn late_line(frames: f64) { } mod card_steps; +mod place; mod send; mod torn; pub(crate) mod upcheck; @@ -4788,8 +4812,10 @@ impl Host { } #[cfg(feature = "diagnostics")] split.part(1); + // What flights in the air may write. + let air = line().written.clone(); for list in runs { - list.run_deferred(&mut batch, |i| own.as_ref().is_some_and(|own| own.takes(list, i))); + list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i))); firsts.push(lists.len()); if let Some(prelude) = list.prelude() { lists.push(Some(prelude)); @@ -4828,6 +4854,11 @@ impl Host { shadow.writing(*at, *len); } let card = self.card_before(runs, &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(..) { + shadow.placed_copy(at, &bytes); + } if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) { lists.push(Some(check)); } @@ -5820,16 +5851,22 @@ impl HostList { /// `len` bytes of upload memory (256-byte aligned) until the list is /// reset: the host GPU address and the CPU pointer. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> { + let (buffer, at, data) = self.scratch_at(len)?; + // SAFETY: a live buffer. + Some((unsafe { buffer.GetGPUVirtualAddress() } + at, data)) + } + + /// [`HostList::scratch`]: the buffer, the offset in it and the CPU + /// pointer. + fn scratch_at(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> { let host = host()?; let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); let len = len.max(1).next_multiple_of(256); if len > SCRATCH_CHUNK { let (buffer, data) = host.upload_buffer(len)?; name(&buffer, || format!("list scratch {len:#x}")); - // SAFETY: a live buffer. - let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - self.deferred().hold_upload(buffer, len); - return Some((gpu, data)); + self.deferred().hold_upload(buffer.clone(), len); + return Some((buffer, 0, data)); } // The chunk in use while `len` fits in what is left of it, else the // next one (a list's first chunk may be a small one). @@ -5846,10 +5883,10 @@ impl HostList { s.chunks.push((chunk, size)); s.used = 0; } - let (data, gpu) = (s.chunks[s.current].0.data, s.chunks[s.current].0.gpu); + let (data, buffer) = (s.chunks[s.current].0.data, s.chunks[s.current].0.buffer.clone()); let at = s.used; s.used += len; - Some((gpu + at, (data + at as usize) as *mut u8)) + Some((buffer, at, (data + at as usize) as *mut u8)) } /// The bytes of scratch chunks the list holds now (after a reset: @@ -6127,7 +6164,7 @@ impl HostList { /// lists of a submission, through many ranges). Copies and fills that /// `taken` names (by their place) are left out: they are done on the /// card ([`card_steps`]). - fn run_deferred(&self, batch: &mut Batch, taken: impl Fn(usize) -> bool) { + fn run_deferred(&self, batch: &mut Batch, air: &[(usize, usize)], taken: impl Fn(usize) -> bool) { #[cfg(feature = "diagnostics")] use crate::copystat::{C, add}; // The time and the bytes of the copies and fills, some 13,000 a @@ -6166,6 +6203,17 @@ impl HostList { copy_mapped(dst as *mut u8, src as *const u8, len, false); (started, len) } + Step::Placed(p) => { + let started = std::time::Instant::now(); + let free = !touches(air, p.src, p.src + p.len) && !touches(air, p.dst, p.dst + p.len); + if free { + batch.title_written(); + } + if let Some(bytes) = p.prepare(free) { + batch.placed.push((p.shadow.clone(), p.dst, bytes)); + } + (started, p.len) + } Step::Refresh(shadow, address, len) => { #[cfg(feature = "diagnostics")] { @@ -6428,6 +6476,9 @@ struct Batch { textures: std::collections::HashSet, /// Those due ([`Batch::refresh_textures`]). due: Vec>, + /// What copies at their place in the submission's lists put into title + /// memory ([`place`]): the host copy, the title address, the bytes. + placed: Vec<(std::sync::Arc, usize, Vec)>, } /// Whether a submission's textures are brought up to date on several diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index fd24a2c..881d1b2 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -194,6 +194,8 @@ enum Does { Read { from: usize, to: usize, asked: bool }, /// A refresh of a host copy (named by its address). Refresh { shadow: usize, from: usize, to: usize }, + /// A copy that its list does on the card ([`place`]). + Placed { dst: usize, src: usize, len: usize }, /// Anything, anywhere. Run, } @@ -271,6 +273,15 @@ 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 { + 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 order: Vec = (0..does.len()).filter(|&i| taken[i]).collect(); // What stays on the CPU and reads what an earlier taken copy writes // would read it too early. @@ -572,6 +583,7 @@ impl Host { 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)); diff --git a/crates/victory-gpu/src/host/place.rs b/crates/victory-gpu/src/host/place.rs new file mode 100644 index 0000000..7d494e0 --- /dev/null +++ b/crates/victory-gpu/src/host/place.rs @@ -0,0 +1,320 @@ +//! The title's buffer copies, done on the card at their place in the list +//! (`VICTORY_COPIES_IN_PLACE`, on by default; `0`: all at submission, on the +//! CPU, as before). +//! +//! A buffer copy was done in title memory when its list was submitted, before +//! any draw of the submission ran, and the host copies refreshed after it. +//! That is another order than the list's: draws ahead of the copy read what +//! it put; of two copies to the same bytes with a draw behind each, both +//! draws read the second; a source that a dispatch of the same submission +//! writes first was read as it was before it; and a destination the +//! submissions in the air still read changed under them (where its host copy +//! has one side only, `crate::shadow::card_all`). +//! +//! Now the list copies, in the destination's host copy: out of the source's +//! host copy where shaders write that one, else out of upload memory of the +//! list that takes the source's bytes when the list is submitted (a source +//! shaders never wrote is the title's CPU's, or a copy's put there earlier in +//! the submission). What is written there is a shader's write from then on: +//! the bytes are declared, and what the card made of them is put into title +//! memory before the title is told of the submission. +//! +//! Title memory takes the copy at submission as well, as it did: fills of +//! upload memory, textures and host copies that lie over the same bytes read +//! it there. The reference of the destination's host copy takes the same +//! bytes ([`Shadow::placed_copy`]), so what the landing finds is what the card +//! made of them afterwards (a counter copied to zero and counted up; a source +//! that a shader wrote in between), and nothing is sent up over it. Where +//! flights in the air may write the source or the destination this is left to +//! the landing: what they wrote is not in title memory yet, and what they +//! will put there must not stand over this copy's bytes. If a step of the +//! submission reads the destination on the CPU, it waits for them instead +//! ([`Placed::waits`]). +//! +//! Copies to memory that has no host copy yet are done as before: nothing on +//! the card has read or written it. So are those of more than 8 MiB out of +//! memory shaders do not write (streaming). + +use super::*; +use crate::shadow::Shadow; + +pub(super) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_COPIES_IN_PLACE").is_none_or(|v| v != "0")) +} + +/// The most bytes copied out of memory shaders do not write. +const MOST: usize = 8 << 20; + +/// Since the last frame-rate line: copies at their place, their bytes, those +/// out of a host copy, and texture copies out of one. +pub(super) static STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// What the CPU does at submission for a copy at its place in a list. +pub(super) struct Placed { + pub(super) dst: usize, + pub(super) src: usize, + pub(super) len: usize, + /// The destination's host copy. + pub(super) shadow: std::sync::Arc, + /// Upload memory the list copies from, to be given the source's bytes. + from: Option, +} + +impl Placed { + /// Whether flights that write `written` are waited for. + pub(super) fn waits(&self, written: &[(usize, usize)]) -> Waits { + let source = touches(written, self.src, self.src + self.len); + if source && self.from.is_some() { + return Waits::Yes; + } + match source || touches(written, self.dst, self.dst + self.len) { + true => Waits::ForReaders, + false => Waits::No, + } + } + + /// At submission, in the order of the steps: the list's upload memory + /// takes the source's bytes and, if `free` (no flight in the air may write + /// source or destination), title memory at the destination does. Gives + /// the bytes if it took them. + pub(super) fn prepare(&self, free: bool) -> Option> { + if !free && self.from.is_none() { + return None; + } + let mut bytes = vec![0u8; self.len]; + // (What is not there reads as zeros, as any copy's source.) + copy_mapped(bytes.as_mut_ptr(), self.src as *const u8, self.len, false); + if let Some(to) = self.from { + // SAFETY: the list's own upload memory of that many bytes. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), to as *mut u8, self.len) }; + } + if !free { + return None; + } + copy_mapped(self.dst as *mut u8, bytes.as_ptr(), self.len, true); + crate::watch::wrote(self.dst, self.len); + // Title memory that is not all there was left alone. + let mut there = vec![0u8; self.len]; + (read_into(self.dst as *const u8, &mut there) && there == bytes).then_some(bytes) + } +} + +/// Whether a copy waits for flights before its submission is prepared: not; +/// yes, as it takes a source on the CPU that they may write; or only if +/// another step of the submission reads its destination on the CPU. +pub(super) enum Waits { + No, + ForReaders, + Yes, +} + +/// Whether a step of `runs` reads one of `ranges` on the CPU. +pub(super) fn read_by(runs: &[&HostList], mut ranges: Vec<(usize, usize)>) -> bool { + join_ranges(&mut ranges, []); + runs.iter().any(|list| { + list.deferred().copies.iter().any(|step| match step { + &Step::Copy(_, src, len) | &Step::Fill(_, src, len, _) => touches(&ranges, src, src + len), + Step::Texture(staging) => { + let (at, len) = staging.memory(); + touches(&ranges, at, at + len) + } + Step::Host(_, (from, to)) => touches(&ranges, *from, *to), + Step::Placed(p) => p.from.is_some() && touches(&ranges, p.src, p.src + p.len), + _ => false, + }) + }) +} + +/// Everything recorded so far is done, and seen, before what follows. +/// +/// # Safety +/// An open list. +unsafe fn wait_for_all(host: &Host, list: &ID3D12GraphicsCommandList) { + static ENHANCED: OnceLock = OnceLock::new(); + let enhanced = *ENHANCED.get_or_init(|| { + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default(); + // SAFETY: a feature structure of its size. + let known = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS12, + (&raw mut o).cast(), + size_of::() as u32, + ) + }; + known.is_ok() && o.EnhancedBarriersSupported.as_bool() + }); + // SAFETY: the caller's. + unsafe { + if enhanced && let Ok(list) = list.cast::() { + let all = [D3D12_GLOBAL_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC_ALL, + SyncAfter: D3D12_BARRIER_SYNC_ALL, + AccessBefore: D3D12_BARRIER_ACCESS_COMMON, + AccessAfter: D3D12_BARRIER_ACCESS_COMMON, + }]; + list.Barrier(&[D3D12_BARRIER_GROUP { + Type: D3D12_BARRIER_TYPE_GLOBAL, + NumBarriers: 1, + Anonymous: D3D12_BARRIER_GROUP_0 { + pGlobalBarriers: all.as_ptr(), + }, + }]); + return; + } + let alias = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::ManuallyDrop::new(None), + pResourceAfter: std::mem::ManuallyDrop::new(None), + }), + }, + }; + let uav = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }; + list.ResourceBarrier(&[alias, uav]); + } +} + +/// The host copy of `[src, src + len)` if shaders write it: what it holds at +/// a place in a list is not what title memory holds at submission. +fn shaders_own(src: usize, len: usize) -> Option> { + crate::shadow::peek(src as u64, len as u64).filter(|s| s.written() && !s.in_place()) +} + +impl HostList { + /// Copies `len` bytes of title memory at `src` to `dst`, at this place of + /// the list (see the file). `false` if it is to be done at submission. + pub(crate) fn place_copy(&self, dst: usize, src: usize, len: usize) -> bool { + if !on() { + return false; + } + let Some(host) = host() else { + return false; + }; + let Some(to) = crate::shadow::peek(dst as u64, len as u64).filter(|s| !s.in_place()) else { + return false; + }; + let own = shaders_own(src, len); + let scratch = match &own { + Some(_) => None, + None if len <= MOST => match self.scratch_at(len as u64) { + Some(scratch) => Some(scratch), + None => return false, + }, + None => return false, + }; + let at = to.offset(dst as u64); + // What the title's CPU wrote around and under it so far goes first. + to.refresh(self, dst as u64, len as u64); + // SAFETY (both): an open list; live buffers (the list holds the + // copies and its scratch memory), ranges inside them. + unsafe { wait_for_all(host, &self.list) }; + match (&own, &scratch) { + (Some(from), _) => { + from.refresh(self, src as u64, len as u64); + let offset = from.offset(src as u64); + if from.buffer.as_raw() == to.buffer.as_raw() { + let Some(between) = self.between(host, len as u64) else { + return false; + }; + unsafe { + self.list.CopyBufferRegion(&between, 0, &from.buffer, offset, len as u64); + self.list.ResourceBarrier(&[transition(&between, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + wait_for_all(host, &self.list); + self.list.CopyBufferRegion(&to.buffer, at, &between, 0, len as u64); + } + } else { + unsafe { self.list.CopyBufferRegion(&to.buffer, at, &from.buffer, offset, len as u64) }; + } + STATS[2].fetch_add(1, Ordering::Relaxed); + } + (None, Some((from, offset, _))) => unsafe { + self.list.CopyBufferRegion(&to.buffer, at, from, *offset, len as u64); + }, + (None, None) => return false, + } + unsafe { wait_for_all(host, &self.list) }; + STATS[0].fetch_add(1, Ordering::Relaxed); + STATS[1].fetch_add(len as u64, Ordering::Relaxed); + to.gpu_writes(self, dst as u64, len as u64); + let mut deferred = self.deferred(); + deferred.copies.push(Step::Placed(Placed { + dst, + src, + len, + shadow: to, + from: scratch.map(|s| s.2 as usize), + })); + deferred.refreshed.clear(); + true + } + + /// For a copy of `[src, src + len)` into a texture: a buffer (readable by + /// copies) that holds what shaders wrote there, at this place of the list. + /// `None` where shaders do not write it. + pub(crate) fn place_source(&self, src: usize, len: usize) -> Option { + if !on() { + return None; + } + let host = host()?; + let from = shaders_own(src, len)?; + let between = self.between(host, len as u64)?; + from.refresh(self, src as u64, len as u64); + STATS[3].fetch_add(1, Ordering::Relaxed); + // SAFETY: an open list; live buffers, ranges inside them. + unsafe { + wait_for_all(host, &self.list); + self.list.CopyBufferRegion(&between, 0, &from.buffer, from.offset(src as u64), len as u64); + self.list.ResourceBarrier(&[transition(&between, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + wait_for_all(host, &self.list); + } + Some(between) + } + + /// A buffer on the card for this recording alone. + fn between(&self, host: &Host, len: u64) -> Option { + let buffer = host.uav_buffer(len.next_multiple_of(1 << 16))?; + name(&buffer, || "bytes between copies".into()); + self.keep(&buffer); + Some(buffer) + } +} + +#[cfg(test)] +mod tests { + /// What copies with two sides cost to make (ignored: a measurement for + /// `VICTORY_CARD_ALL`): buffers of 64 KiB on the card and in the PC's + /// memory. + #[test] + #[ignore] + fn small_buffers_cost() { + let Some(host) = super::host() else { + return; + }; + const N: usize = 1000; + let used = || host.video_memory().map_or(0, |m| m[1] >> 20); + let before = used(); + let t = std::time::Instant::now(); + let card: Vec<_> = (0..N).map(|_| host.uav_buffer(1 << 16)).collect(); + let card_us = t.elapsed().as_micros() as f64 / N as f64; + let after = used(); + let t = std::time::Instant::now(); + let pc: Vec<_> = (0..N).map(|_| host.shared_buffer(1 << 16)).collect(); + let pc_us = t.elapsed().as_micros() as f64 / N as f64; + println!( + "{N} buffers of 64 KiB: on the card {card_us:.0} us each, {} MB of its memory; in the PC's memory {pc_us:.0} us each", + after.saturating_sub(before) + ); + drop((card, pc)); + } +} diff --git a/crates/victory-gpu/src/host/upcheck.rs b/crates/victory-gpu/src/host/upcheck.rs index a483493..d82a0c9 100644 --- a/crates/victory-gpu/src/host/upcheck.rs +++ b/crates/victory-gpu/src/host/upcheck.rs @@ -954,6 +954,241 @@ mod tests { each_reads_its_own(256 << 10, 0x8888, std::env::var_os("VICTORY_CARD_ALL").is_some_and(|v| v == "1")); } + /// What a draw of `list` reads at `at`: comes to `out`. + fn read_out(list: &HostList, shadow: &std::sync::Arc, at: usize, n: usize, out: (&ID3D12Resource, u64)) { + shadow.refresh(list, shadow.span().0 + at as u64, n as u64); + // SAFETY: an open list; live buffers. + unsafe { + list.list.CopyBufferRegion(out.0, out.1, &shadow.buffer, at as u64, n as u64); + list.list + .ResourceBarrier(&[transition(&shadow.buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); + } + } + + /// Copies, shader writes and reads in random order, within lists and + /// across submissions in the air, the title's CPU writing sources in + /// between: every read sees what stands before it, and in the end title + /// memory and the copies hold the last of everything. + fn in_order(resource: usize, sizes: [usize; 3]) { + let Some(host) = host() else { + return; + }; + let buffers: Vec<_> = sizes.iter().enumerate().map(|(i, &n)| title_of(resource + i, i == 0, n)).collect(); + let slow = Slow::new(host); + let (out, out_data) = host.shared_buffer(1 << 20).unwrap(); + let mut seed = 0x9e37_79b9_7f4a_7c15u64 ^ resource as u64; + let mut next = move |n: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as usize % n + }; + // Of each buffer: the first 4 KiB are the title's own (sources), the + // next 12 are written by copies and shaders. + const OWN: usize = 4096; + const ALL: usize = 16384; + // (Of the third only the first 4 KiB: shaders never write it.) + let mut model = [vec![0u8; ALL], vec![0u8; ALL], vec![0u8; ALL]]; + let mut titles: Vec<&'static mut [u8]> = Vec::new(); + let mut made = Vec::new(); + for (title, start, shadow) in buffers { + titles.push(title); + made.push((start, shadow)); + } + let mut lists = Vec::new(); + for (start, shadow) in &made { + let all = host.new_list().unwrap(); + shadow.refresh(&all, *start as u64, ALL as u64); + all.close(); + host.execute_own(&all); + lists.push(all); + } + settle_now(WHY_SYNC); + for round in 0..150 { + // (offset in `out`, what was expected, where from) + let mut expected: Vec<(usize, Vec, String)> = Vec::new(); + let mut told = String::new(); + for submission in 0..1 + next(5) { + for _ in 0..next(6) { + let (b, at) = (next(3), next(OWN / 64) * 64); + let value = next(255) as u8 + 1; + // (A copy with one side is what submissions in the air + // read: the title's CPU waits for them, as it does.) + if !made[b].1.carded() { + settle_now(WHY_SYNC); + } + titles[b][at..at + 64].fill(value); + model[b][at..at + 64].fill(value); + } + let list = host.new_list().unwrap(); + if next(3) == 0 { + slow.record(&list, 4 + next(12)); + } + for op in 0..1 + next(10) { + let word = |next: &mut dyn FnMut(usize) -> usize| OWN + next((ALL - OWN - 256) / 4) * 4; + match next(5) { + 0 | 1 => { + let (d, s) = (next(2), next(3)); + let n = 4 * (1 + next(64)); + let to = word(&mut next); + let from = if s == 2 || next(2) == 0 { next((OWN - 256) / 4) * 4 } else { word(&mut next) }; + if d == s && from < to + n && to < from + n { + continue; + } + assert!(list.place_copy(made[d].0 + to, made[s].0 + from, n), "done in the list"); + let bytes = model[s][from..from + n].to_vec(); + model[d][to..to + n].copy_from_slice(&bytes); + told += &format!("\n s{submission} op{op}: copy {d}+{to:#x} <- {s}+{from:#x} {n:#x}"); + } + 2 => { + let (b, at, n) = (next(2), word(&mut next), 4 * (1 + next(32))); + let value = next(255) as u8 + 1; + let (start, shadow) = &made[b]; + shadow.refresh(&list, (*start + at) as u64, n as u64); + shadow.gpu_writes(&list, (*start + at) as u64, n as u64); + write(host, &list, shadow, at, &vec![value; n]); + model[b][at..at + n].fill(value); + told += &format!("\n s{submission} op{op}: shader {b}+{at:#x} {n:#x} = {value:#x}"); + } + _ => { + let (b, n) = (next(2), 256); + let at = if next(4) == 0 { next((OWN - 256) / 4) * 4 } else { word(&mut next) }; + let place = expected.len() * 256; + read_out(&list, &made[b].1, at, n, (&out, place as u64)); + expected.push((place, model[b][at..at + n].to_vec(), format!("s{submission} op{op}: read {b}+{at:#x}"))); + } + } + } + list.close(); + host.execute_own(&list); + lists.push(list); + } + settle_now(WHY_SYNC); + for (at, bytes, what) in expected { + // SAFETY: inside the mapping; the copies into it have run. + let got = unsafe { std::slice::from_raw_parts(out_data.add(at), bytes.len()) }; + if let Some(k) = (0..bytes.len()).find(|&k| got[k] != bytes[k]) { + panic!("round {round}, {what}: at +{k:#x} {:#x}, not {:#x}{told}", got[k], bytes[k]); + } + } + for (b, title) in titles.iter().enumerate() { + if let Some(k) = (0..ALL).find(|&k| title[k] != model[b][k]) { + panic!("round {round}: title memory {b}+{k:#x} is {:#x}, not {:#x}{told}", title[k], model[b][k]); + } + } + // Brought up to date by the next, the copies hold it too. + let list = host.new_list().unwrap(); + for (b, (_, shadow)) in made.iter().enumerate() { + read_out(&list, shadow, 0, ALL, (&out, (b * ALL) as u64)); + } + list.close(); + host.execute_own(&list); + lists.push(list); + settle_now(WHY_SYNC); + for (b, model) in model.iter().enumerate() { + // SAFETY: as above. + let got = unsafe { std::slice::from_raw_parts(out_data.add(b * ALL), ALL) }; + if let Some(k) = (0..ALL).find(|&k| got[k] != model[k]) { + panic!("round {round}: the copy {b}+{k:#x} is {:#x}, not {:#x}{told}", got[k], model[k]); + } + } + if on() { + assert_eq!(look(host), Some(0), "round {round}"); + } + } + eprintln!( + "copies at their place, bytes, out of host copies, into textures: {:?}", + super::place::STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect::>() + ); + } + + /// Two buffers with two sides. + #[test] + #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"] + fn copies_stand_where_the_list_has_them_on_the_card() { + in_order(0x9100, [LEN, LEN, LEN]); + } + + /// One in the card's memory, one in the PC's (one side without + /// `VICTORY_CARD_ALL`). + #[test] + #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"] + fn copies_stand_where_the_list_has_them_mixed() { + in_order(0x9200, [LEN, 256 << 10, 256 << 10]); + } + + #[test] + #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"] + fn copies_stand_where_the_list_has_them_in_pc_memory() { + in_order(0x9300, [256 << 10, 256 << 10, LEN]); + } + + /// As the title records it: copy, draw, copy, draw in one list; a source + /// a shader writes first; a counter copied to zero and counted up. + #[test] + #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"] + fn copy_draw_copy_draw() { + let Some(host) = host() else { + return; + }; + let (title, start, shadow) = title_of(0x9400, true, LEN); + let (out, out_data) = host.shared_buffer(1 << 16).unwrap(); + let all = host.new_list().unwrap(); + shadow.refresh(&all, start as u64, LEN as u64); + all.close(); + host.execute_own(&all); + settle_now(WHY_SYNC); + title[0..64].fill(1); + title[64..128].fill(2); + title[128..192].fill(0); + let list = host.new_list().unwrap(); + const D: usize = 0x10000; + const S: usize = 0x20000; + assert!(list.place_copy(start + D, start, 64)); + read_out(&list, &shadow, D, 64, (&out, 0)); + assert!(list.place_copy(start + D, start + 64, 64)); + read_out(&list, &shadow, D, 64, (&out, 64)); + // A shader writes S, and it is copied on. + shadow.gpu_writes(&list, (start + S) as u64, 64); + write(host, &list, &shadow, S, &[7; 64]); + assert!(list.place_copy(start + D + 64, start + S, 64)); + read_out(&list, &shadow, D + 64, 64, (&out, 128)); + // Zero, counted up, taken away. + assert!(list.place_copy(start + D + 128, start + 128, 64)); + shadow.gpu_writes(&list, (start + D + 128) as u64, 64); + write(host, &list, &shadow, D + 128, &[5; 64]); + assert!(list.place_copy(start + D + 192, start + D + 128, 64)); + read_out(&list, &shadow, D + 192, 64, (&out, 192)); + // What a copy into a texture takes of S here. + let between = list.place_source(start + S, 64).expect("shaders write it"); + shadow.gpu_writes(&list, (start + S) as u64, 64); + write(host, &list, &shadow, S, &[9; 64]); + // SAFETY: an open list; live buffers. + unsafe { list.list.CopyBufferRegion(&out, 256, &between, 0, 64) }; + assert!(list.place_source(start + (1 << 20), 64).is_some(), "the buffer is written"); + // And zero for the next frame. + assert!(list.place_copy(start + D + 128, start + 128, 64)); + list.close(); + host.execute_own(&list); + settle_now(WHY_SYNC); + // SAFETY: the mapping; the copies into it have run. + let read = unsafe { std::slice::from_raw_parts(out_data, 320) }; + assert_eq!(read[256], 7, "what a texture takes"); + assert_eq!([read[0], read[64], read[128], read[192]], [1, 2, 7, 5], "what the draws read"); + assert_eq!( + [title[D], title[D + 64], title[D + 128], title[D + 192], title[S]], + [2, 7, 0, 5, 9], + "title memory" + ); + let holds = card(host, &shadow); + assert_eq!([holds[D], holds[D + 64], holds[D + 128], holds[D + 192], holds[S]], [2, 7, 0, 5, 9], "the card"); + assert_eq!(look(host), Some(0)); + // With the debug layer. + if let Some(said) = host.log_messages() { + eprintln!("{said}"); + } + } + /// Declared writes beside the title's own, in the same 64 KiB pieces and /// dword by dword, flights landing while later ones are in the air: in /// the end title memory and the card hold what each wrote last. (A byte diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 02ad326..032a831 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -808,6 +808,20 @@ fn buffer_range(buffer: This, offset: u64, len: u64) -> Option<*mut u8> { Some(unsafe { data.add(offset as usize) }) } +/// A copy of title memory that `list` records: on the card at its place in +/// the list ([`crate::host::HostList::place_copy`]), or at submission. +#[cfg(windows)] +fn buffer_copy(this: This, list: &crate::host::HostList, to: *mut u8, from: *const u8, len: usize) { + if len == 0 { + return; + } + if list.place_copy(to as usize, from as usize, len) { + with_state(this, |_, state| state.copied()); + } else { + list.defer_copy(to, from, len); + } +} + /// Buffer to buffer: both are host memory, copied at submission. extern "system" fn copy_buffer_region( this: This, @@ -822,7 +836,7 @@ extern "system" fn copy_buffer_region( && let Some(to) = buffer_range(dst, dst_offset, len) && let Some(from) = buffer_range(src, src_offset, len) { - list.defer_copy(to, from, len as usize); + buffer_copy(this, list, to, from, len as usize); } #[cfg(not(windows))] let _ = (this, dst, dst_offset, src, src_offset, len); @@ -875,7 +889,7 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { crate::resource::buffer_bytes(dst), crate::resource::buffer_bytes(src), ) { - list.defer_copy(to, from, a.min(b) as usize); + buffer_copy(this, list, to, from, a.min(b) as usize); } } #[cfg(not(windows))] @@ -969,12 +983,20 @@ extern "system" fn copy_texture_region( let Some(data) = buffer_range(src.resource, src.footprint.offset, bytes) else { return; }; - let Some((buffer, staging)) = list.upload(host, bytes) else { - return; + let buffer = match list.place_source(data as usize, bytes as usize) { + // What shaders wrote to it, at this place of the list. + Some(buffer) => buffer, + None => { + let Some((buffer, staging)) = list.upload(host, bytes) else { + return; + }; + // The list owns this mapped D3D12 upload buffer. Wine can + // report its address as MEM_FREE, so use the host-upload + // path. + list.defer_fill_buffer(&buffer, staging, data, bytes as usize); + buffer + } }; - // The list owns this mapped D3D12 upload buffer. Wine can report - // its address as MEM_FREE, so use the host-upload path. - list.defer_fill_buffer(&buffer, staging, data, bytes as usize); from.resource = buffer.as_raw().cast_const().cast(); from.footprint.offset = 0; #[cfg(feature = "diagnostics")] @@ -1298,6 +1320,10 @@ extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: && src != 0 { let len = len as usize; + if list.place_copy(dst as usize, src as usize, len) { + with_state(this, |_, state| state.copied()); + return; + } list.defer(move || { if crate::texture::committed(src as *const u8, len) && crate::texture::committed(dst as *const u8, len) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 261b497..3105b0a 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -73,6 +73,8 @@ pub(crate) struct Shadow { /// Asks for the copy that gave no length (root views: they read from /// their address to the copy's end, whatever lies there). unsized_asks: AtomicU64, + /// Whether shaders were ever declared to write it. + written: std::sync::atomic::AtomicBool, /// A number no other copy has had. Its address is no name for a copy: /// one let go and another made may share it. id: u64, @@ -352,6 +354,32 @@ static WINDOW_CARD_BYTES: AtomicU64 = AtomicU64::new(0); /// A buffer in the card's memory for a window of `size` bytes, if it is to /// be there ([`window_card_most`]). fn window_card_for(size: u64) -> Option { + let there = window_room_for(size); + if there.is_some() || !windows_own() || !cards() { + return there; + } + // Two sides all the same, the card's in the PC's memory. + let host = host()?; + if !host.card_ready() { + return None; + } + let (buffer, _) = host.shared_buffer(size)?; + WINDOW_CARD_BYTES.fetch_add(size, Ordering::Relaxed); + Some(buffer) +} + +/// Whether windows outside buffers have two sides too, so that submissions +/// in the air read the bytes they were prepared with (`VICTORY_WINDOWS_OWN=1`; +/// off by default: it takes the windows' bytes again, 3.3 GB in capture +/// replay2, and what changes in them under submissions in the air is what the +/// title's CPU writes, which it does not while they read it). +fn windows_own() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WINDOWS_OWN").is_some_and(|v| v == "1")) +} + +/// [`window_card_for`] in the card's own memory. +fn window_room_for(size: u64) -> Option { let most = window_card_most(); if most == 0 || !cards() { return None; @@ -2294,6 +2322,7 @@ impl Shadow { used: AtomicU64::new(crate::host::moment()), asked: [AtomicU64::new(u64::MAX), AtomicU64::new(0)], unsized_asks: AtomicU64::new(0), + written: Default::default(), id: { static NEXT: AtomicU64 = AtomicU64::new(1); NEXT.fetch_add(1, Ordering::Relaxed) @@ -2329,6 +2358,7 @@ impl Shadow { if self.place.is_some() { return; } + self.written.store(true, Ordering::Relaxed); let len = len.min(self.left(address)); list.defer_gpu_write(self, address as usize, len as usize); } @@ -3302,6 +3332,35 @@ impl Shadow { card.touched.store(true, Ordering::Release); } + /// Whether shaders were ever declared to write it. + pub(crate) fn written(&self) -> bool { + self.written.load(Ordering::Relaxed) + } + + /// `bytes` were put into title memory at `address`, and the submission + /// being prepared copies the same to the copy at that copy's place in its + /// list: the reference (the CPU's side of a copy in the card's memory, the + /// snapshot) takes them and nothing is sent. What the card makes of them + /// is then what differs from them when the submission has run. The range + /// is declared written by it, and its sends are taken. + pub(crate) fn placed_copy(&self, address: usize, bytes: &[u8]) { + let (from, to) = self.inside(address, bytes.len()); + if from >= to || self.place.is_some() { + return; + } + let bytes = &bytes[self.start as usize + from - address..][..to - from]; + let _merging = self.merging.write().unwrap_or_else(|e| e.into_inner()); + if self.card.is_some() { + // SAFETY: inside the mapping of the CPU's side, in a range no + // refresh writes; the lock keeps the landing out. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), self.data.add(from), bytes.len()) }; + } else if let Some(snapshot) = self.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + // SAFETY: the snapshot's allocation holds the copy's length. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), snapshot.as_mut_ptr().add(from), bytes.len()) }; + } + self.changed(from, to); + } + /// Of a copy in the card's memory: where its CPU side is. pub(crate) fn card_data(&self) -> *const u8 { self.data @@ -3981,6 +4040,12 @@ pub(crate) fn find_any(address: u64, len: u64) -> Option> { lookup(address, len, true) } +/// The copy [`find`] gives for a range inside a title buffer, if it was made. +pub(crate) fn peek(address: u64, len: u64) -> Option> { + let end = address.checked_add(len.max(1))?; + buffers().range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end).and_then(|(_, e)| e.shadow.clone()) +} + fn lookup(address: u64, len: u64, any: bool) -> Option> { let end = address.checked_add(len.max(1))?; let mut map = buffers(); From 6ae06963b2277be7985444ea73e7ea77e8816175 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 00:31:25 -0600 Subject: [PATCH 201/445] VICTORY_SEND_CHANGED off by default: run tile1-0 lost light and geometry with it Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 4 ++-- crates/victory-gpu/src/shadow.rs | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index e6c1552..089deb8 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -8116,7 +8116,7 @@ mod refresh_tests { }; // What was last written so, by offset. let mut undeclared = std::collections::HashMap::new(); - let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0"); + let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0"); let stop = AtomicBool::new(false); // Also when an assertion fails on one of the threads. struct Stop<'a>(&'a AtomicBool); @@ -8400,7 +8400,7 @@ mod refresh_tests { } copy.update(region, 4 * PAGE); let written = copy.take_dirty(); - if std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0") { + if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0") { assert_eq!(again, []); assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]); } else { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index b94250f..4933273 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1677,8 +1677,9 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { /// 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=0`: the 64 KiB pages written since it last took -/// them, whole, as before). +/// (`VICTORY_SEND_CHANGED=1`; off: the 64 KiB pages written since it last +/// took them, whole). Off since run tile1-0: the room lost its indirect light +/// and geometry exploded; run bis1-0, the same but for this, was right. /// /// A page that counts as written is mostly not the title's doing, or not all /// of it: a word the title wrote, and around it what shaders wrote and the @@ -1710,7 +1711,7 @@ fn send_changed() -> bool { if crate::copystat::mode() != 0 { return false; } - std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0") + std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0") }) } From a26859fc5f512e0db0d7522d3da821c038378ab7 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:46:49 -0500 Subject: [PATCH 202/445] The first room renders right: byte-copied descriptor records are mirrored, views off their copy's elements get their own bytes, card room for the first world frame, levels on demand run on the card - Descriptor records the title copies into its heap as bytes are mirrored before each submission (pull request #305 by Flyander, after upstream VIctory 86a5ed6), with a per-slot fingerprint so only records that changed are mirrored, the page read through the kernel, a switch (VICTORY_HEAP_SYNC=0) and a counter: about 40,000 records a frame on the test machine. - A buffer view off its copy's elements gets a copy of its own bytes (after upstream 86a5ed6; VICTORY_VIEW_OWN_COPY=0: refused as before). - Room on the card for the world's first-frame bursts: buffer copies (VICTORY_CARD_ROOM_FOR_BUFFERS, now on) and render targets (VICTORY_CARD_ROOM_FOR_TARGETS_MB, 3,072); a copy turned down gives its room up and is logged; the texture pass asks again every 32 MiB. 98 buffer copies made (945 MB) where earlier runs made 1; 25 MB compared on the processor a frame where it was 550 to 710. - Levels on demand: the fixes of pull request #747 by AscilCH. First run on a card (RTX 4070, VICTORY_LEVELS_ON_DEMAND=1): no device loss, 3.1 GB not allocated for levels the title does not hold. Still off by default. - The guarded blocks under storage writes into physical pages are opened by default (VICTORY_PAGE_WRITES=0: counted only). - Shaders: a program is translated with first-half interpolation pairs only if it was refused for one (with it on for every program 8,551 working pixel programs came out changed); parked lane-mask pairs, f64 conversions and sums, lane permutations: 14 more programs translate. - Counted, not fixed: an indirect compute pass asks for about 77,500 groups in x and is cut to 65,535. One five-minute game run of these changes on the test machine: no device loss, no failed request. This merged tree was built; its test suites were not run. Co-Authored-By: Claude Fable 5.2 --- README.md | 27 ++ crates/victory-gpu/src/descriptor.rs | 201 +++++++++++++++ crates/victory-gpu/src/descriptor/host.rs | 211 +++++++++++++++- crates/victory-gpu/src/draw.rs | 12 +- crates/victory-gpu/src/host.rs | 24 +- crates/victory-gpu/src/indirect.rs | 15 +- crates/victory-gpu/src/resource.rs | 40 ++- crates/victory-gpu/src/shadow.rs | 120 ++++++++- crates/victory-gpu/src/tiles.rs | 232 +++++++++++++++--- crates/victory-gpu/src/watch.rs | 71 +++++- crates/victory-shader/src/emit/lower.rs | 195 ++++++++++++++- crates/victory-shader/src/emit/mod.rs | 16 ++ .../victory-shader/src/emit/wave64_tests.rs | 82 ++++++- 13 files changed, 1188 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index 8c99e40..f9830ff 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,33 @@ Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, ### Newest (2026-11-25, later the same day) +**Update, the same night: the first room now renders right on the test +machine** (walls, textures, people, lamps), at 190 to 450 ms a frame (2 to 5 +frames a second): the picture work has caught up, the frame rate has not. +What did it, on top of the list below: +- Descriptor records the title copies into its heap as plain bytes are + mirrored before every submission (pull request #305 by Flyander, after + upstream VIctory 86a5ed6). Measured here: about 40,000 records a frame + that no call had announced; their host slots were empty or stale. +- A buffer view that does not start on an element of its buffer's host + copy gets a copy of its own bytes instead of being refused (after + upstream 86a5ed6): 3 to 6 such views a frame. +- Room on the card is kept for the render targets and buffer copies a + world makes in its first frame: 98 buffer copies are made (945 MB) where + the runs before made 1, and the processor no longer compares 550 to + 710 MB a frame looking for shader writes (25 MB now). +- Levels on demand ran on the card for the first time + (`VICTORY_LEVELS_ON_DEMAND=1`, still off by default; with the fixes of + pull request #747 by AscilCH): 3.1 GB of the card not allocated for + texture levels the title does not hold, no device loss. +- Guarded blocks under storage writes are opened by default; 14 more + shader programs translate; a program is translated with first-half + interpolation pairs only if it was refused for one (with that on for + every program, 8,551 working pixel programs came out changed). +- Known and counted, not fixed yet: an indirect compute pass asks for + about 77,500 thread groups in x where one dispatch runs 65,535 (the + rest is cut off). + Memory sync between the title's memory and the copies on the card: - **A write through one view of a physical page is seen by the copies taken through its other views** (`VICTORY_VIEW_GUARD=0` turns it off). The title diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 9305bf5..6aad6da 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -59,6 +59,10 @@ pub(crate) struct Heap { host: std::sync::OnceLock>, #[cfg(windows)] pending: std::sync::Mutex>, + /// Changed pages of a placed shader-visible heap. Some titles copy + /// descriptor records into it as bytes, without a descriptor API call. + #[cfg(windows)] + written: Option, } pub(crate) fn heap<'a>(this: This) -> &'a Heap { @@ -155,6 +159,119 @@ fn mirror(handle: u64) { } } +/// Mirrors records copied directly into placed shader-visible heaps. Calls +/// to `Create*View` are already mirrored by [`mirror`]; raw CPU copies leave +/// only write-watch pages to reveal which slots changed. +/// +/// Upstream VIctory 86a5ed6 does the same and counts 1,300 to 14,400 such +/// slots a frame in the world of the title this fork works on, against a +/// few hundred views made by calls; without it those host slots stayed +/// null, or went on showing what they showed before. +/// `VICTORY_HEAP_SYNC=0`: not done, as before. [`SYNCED`] counts. +#[cfg(windows)] +pub(crate) fn sync_heaps() { + use std::sync::atomic::Ordering::Relaxed; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC").is_none_or(|v| v != "0")) { + return; + } + let started = std::time::Instant::now(); + let (mut pages, mut looked, mut mirrored) = (0u64, 0u64, 0u64); + let mut page_bytes: Vec = Vec::new(); + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + for &(start, end, at) in heaps.iter() { + // SAFETY: registered heaps are live (removed when dropped). + let heap = unsafe { &*(at as *const Heap) }; + let (Some(Some(host)), Some(written), Some(step)) = + (heap.host.get(), &heap.written, increment(heap.desc.kind)) + else { + continue; + }; + let step = u64::from(step); + // Capped host heaps have no counterparts for the title slots reserved + // for per-draw tables; raw writes there must not be mirrored. + let mirrored_count = heap.desc.count.min(host.count()); + 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 { + let from = page.max(range_from); + let to = (page + crate::watch::PAGE).min(range_end); + // The page's records are read through the kernel, into a + // copy: a page the title unmaps meanwhile fails the read + // where 2,048 reads in place would fault. + page_bytes.resize(to - from, 0); + if crate::host::read_into(from as *const u8, &mut page_bytes) { + pages += 1; + let slots = changed_slots(from, to, start as usize, step, mirrored_count); + for index in slots { + let handle = start + index * step; + // A record that straddles the range's ends is left + // to the range that holds its first byte. + let Some(at) = (handle as usize).checked_sub(from) else { + continue; + }; + let Some(record) = page_bytes.get(at..at + step as usize) else { + continue; + }; + looked += 1; + // Only a record that is not the one last seen there + // (`HostHeap::mirror_copied`). + if host.mirror_copied(index as u32, handle, record) { + mirrored += 1; + } + } + } + page += crate::watch::PAGE; + } + } + } + drop(heaps); + for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, started.elapsed().as_micros() as u64]) { + count.fetch_add(n, Relaxed); + } +} + +/// 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 (mirrored), and the microseconds it took. +#[cfg(windows)] +pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// With the frame line: what [`sync_heaps`] did per frame over `frames`. +/// Nothing while no heap page changed. +#[cfg(windows)] +pub(crate) fn sync_line(frames: f64) { + let [pages, looked, mirrored, micros] = [0, 1, 2, 3].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + 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, {:.2} ms", + pages as f64 / frames, + looked as f64 / frames, + mirrored as f64 / frames, + micros as f64 / 1000.0 / frames + ); +} + +/// Title descriptor slots in a changed byte range that have host counterparts. +/// `range_end` is exclusive. +#[cfg(windows)] +fn changed_slots( + range_from: usize, + range_end: usize, + heap_start: usize, + step: u64, + mirrored_count: u32, +) -> std::ops::Range { + let from = (range_from - heap_start) as u64; + let to = (range_end - heap_start) as u64; + let first = from / step; + let last = to.div_ceil(step).min(u64::from(mirrored_count)); + first.min(last)..last +} + /// Gives back dynamic slots of the host heap behind the title heap at /// `heap`, if that heap still exists. #[cfg(windows)] @@ -970,6 +1087,10 @@ pub(crate) extern "system" fn create_heap( host: std::sync::OnceLock::new(), #[cfg(windows)] pending: Default::default(), + #[cfg(windows)] + written: (placed && visible) + .then(|| crate::watch::track(start as usize, size as usize, true)) + .flatten(), }); #[cfg(windows)] if visible { @@ -1027,6 +1148,34 @@ mod tests { create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], out) } + #[cfg(windows)] + #[test] + fn raw_heap_sync_stops_before_dynamic_host_slots() { + let start = 0x1000usize; + let step = 32; + let capped = 5; + assert_eq!( + changed_slots( + start + 3 * step + 4, + start + 4 * step + 8, + start, + step as u64, + capped + ), + 3..5 + ); + assert_eq!( + changed_slots( + start + 6 * step, + start + 9 * step, + start, + step as u64, + capped + ), + 5..5 + ); + } + #[test] fn heaps_hold_count_descriptors_from_their_start() { let null = std::ptr::null(); @@ -1053,6 +1202,58 @@ mod tests { assert_eq!(create(bad, none, &mut h), E_INVALIDARG); } + /// A descriptor copied into a placed heap as bytes is mirrored before + /// the next submission, even though no descriptor method saw the copy. + #[cfg(windows)] + #[test] + fn records_copied_as_bytes_are_made_at_the_next_sync() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + let memory = unsafe { + VirtualAlloc( + std::ptr::null(), + crate::watch::PAGE, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + ) + }; + assert!(!memory.is_null()); + let desc = HeapDesc { + kind: SAMPLERS, + count: 64, + flags: SHADER_VISIBLE, + nodes: 1, + }; + let placement = Placement { + address: memory as u64, + size: 64 * 16, + }; + let mut h: This = std::ptr::null(); + assert_eq!(create(desc, placement, &mut h), S_OK); + if let Some(host) = heap(h).host() { + let mut elsewhere = [0u64; 2]; + let source = elsewhere.as_mut_ptr() as u64; + let sampler = [21, 3, 3, 3, 0, 1, 0, 0, 0, 0, 0, 0x7f7f_ffff, 0]; + create_sampler(std::ptr::null(), &sampler, source); + // SAFETY: the heap slot and source both hold 16 descriptor bytes. + unsafe { + std::ptr::copy_nonoverlapping( + source as *const u8, + memory.cast::().add(5 * 16), + 16, + ) + }; + assert!(!host.made(5)); + sync_heaps(); + assert!(host.made(5)); + } + slot:: u32>(h, 0x10)(h); + // SAFETY: this allocation belongs to the test. + unsafe { VirtualFree(memory, 0, MEM_RELEASE) }; + } + #[test] fn views_survive_copies() { let null = std::ptr::null(); diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 49e4ca1..861106a 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -26,6 +26,10 @@ pub(crate) struct HostHeap { sampler: bool, /// The record (view index and generation) each slot was last made from. made: Mutex>, + /// A fingerprint of the record each slot held when the pass over + /// records copied in as bytes last looked at it + /// ([`HostHeap::mirror_copied`]; 0: never looked at). Made on first use. + copied: Mutex>, /// The host resource each slot views, held while the slot does: shaders /// index heaps directly, so a slot the title has not rewritten since it /// released the resource may still be read, and a freed host resource @@ -947,6 +951,7 @@ impl HostHeap { dynamic: extra, sampler, made: Mutex::new(vec![0; count as usize]), + copied: Mutex::new(Vec::new()), kept: Mutex::new(vec![None; (count + extra) as usize]), next: Mutex::new((0, vec![false; DYNAMIC as usize])), free: std::sync::atomic::AtomicU32::new(DYNAMIC), @@ -1789,6 +1794,45 @@ impl HostHeap { } } + /// For a slot on a page of the title's heap that changed with no call + /// (`super::sync_heaps`: the title copies records into its heap as + /// bytes): [`HostHeap::mirror`], if the `bytes` bytes of the record at + /// `handle` are not the ones this last saw there. True if it did. + /// + /// The page says only that something on it was written, and `mirror` + /// by itself would take every buffer or placed-texture record on it for + /// newly written each time (it leaves such a slot unmade until a draw + /// or a pass uses it): the texture queue's entry for the slot would + /// start again, and the buffer pass would look at 2,048 slots for one + /// that changed. + /// `record`: the record's bytes as the caller read them (through the + /// kernel, which fails on a page the title unmapped meanwhile where a + /// read in place would fault: the title unmaps heap pages too). + pub(crate) fn mirror_copied(&self, index: u32, handle: u64, record: &[u8]) -> bool { + if index >= self.count { + return false; + } + let n = record.len(); + // Never 0, which is "never looked at". + let print = u64::from_le_bytes(blake3::hash(record).as_bytes()[..8].try_into().unwrap_or([1; 8])) | 1; + { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if copied.is_empty() { + copied.resize(self.count as usize, 0); + } + let Some(last) = copied.get_mut(index as usize) else { + return false; + }; + // A slot never looked at that holds nothing: as it was. + if *last == print || (*last == 0 && record[..n].iter().all(|&b| b == 0)) { + return false; + } + *last = print; + } + self.mirror(index, handle, false); + true + } + /// Makes host slot `index` from the record the title has at `handle` /// if it changed since, and returns the view recorded there. Buffer /// views are made only for draws (`for_draw`), which also copy their @@ -1874,6 +1918,16 @@ impl HostHeap { Some(view) } + /// 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) + } + /// Whether host slot `index` shows `buffer`; `None` if it shows no /// resource (diagnostics: a buffer view's slot must show the host copy /// that is brought up to date for it). @@ -2041,6 +2095,18 @@ pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc Option<(u64, u64)> { /// The host resource a slot made by [`make`] views, if any. type Kept = Option; +/// Whether a buffer view off its buffer's elements gets a copy of its own +/// bytes (`VICTORY_VIEW_OWN_COPY=0`: it is refused and reads zeros, as +/// before). +fn own_copy_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_OWN_COPY").is_none_or(|v| v != "0")) +} + +/// The title memory (start, bytes) of a buffer view that cannot be made on +/// the host copy of its buffer: `count` elements of `element` bytes from +/// element `first` of the buffer at `base`, which lies `offset` bytes into +/// that copy, where `offset` is not a whole number of elements and the view +/// cannot be a raw view of the same bytes either ([`raw_window`]: +/// `unknown`, the view has no format, and `stride` is its structure's). +/// The host counts a view's first element from its buffer's start, so such +/// a view has no host view there; it is made on a copy of its own bytes +/// (`crate::shadow::exact`), where it starts at element 0. `None`: the +/// view is made on its buffer's copy, as every other. +fn own_bytes(offset: u64, base: u64, first: u64, count: u32, element: u64, stride: u32, unknown: bool) -> Option<(u64, u64)> { + own_bytes_if(own_copy_on(), offset, base, first, count, element, stride, unknown) +} + +#[allow(clippy::too_many_arguments)] +fn own_bytes_if( + on: bool, + offset: u64, + base: u64, + first: u64, + count: u32, + element: u64, + stride: u32, + unknown: bool, +) -> Option<(u64, u64)> { + if !on || element == 0 || count == 0 || offset.is_multiple_of(element) { + return None; + } + if unknown && raw_window(offset, first, count, stride).is_some() { + return None; + } + let start = base.checked_add(first.checked_mul(element)?)?; + Some((start, u64::from(count) * element)) +} + +/// Of a buffer view: its first element, its elements, the bytes of one (a +/// raw view's: 4), its structure's stride, and whether it has no format. +/// As [`buffer_srv`] and [`buffer_uav`] read them from the same words. +fn buffer_fields(view: &View) -> Option<(u64, u32, u64, u32, bool)> { + const BUFFER: u32 = 1; + let (words, unordered): (&[u32; 10], bool) = match view { + View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false), + View::Unordered(_, _, Some(d)) if d[1] == BUFFER => (d, true), + View::Placed(unordered, resource, d) if resource[0] == BUFFER => (d[..10].try_into().ok()?, *unordered), + _ => return None, + }; + if unordered { + let d = uav_desc(words); + // SAFETY: a buffer view's union member. + let b = unsafe { d.Anonymous.Buffer }; + let element = if b.StructureByteStride > 0 { + u64::from(b.StructureByteStride) + } else if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(d.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + }; + Some((b.FirstElement, b.NumElements, element, b.StructureByteStride, d.Format == DXGI_FORMAT_UNKNOWN)) + } else { + let d = srv_desc(words); + // SAFETY: a buffer view's union member. + let b = unsafe { d.Anonymous.Buffer }; + Some((b.FirstElement, b.NumElements, element_size(&d), b.StructureByteStride, d.Format == DXGI_FORMAT_UNKNOWN)) + } +} + /// A structured buffer view (`first`, `count` elements of `stride` bytes, /// `offset` bytes into its host copy) as a raw view of the same bytes: /// its first dword and its dwords. Translated shaders read untyped buffers @@ -2140,6 +2280,22 @@ fn buffer_srv( ) -> Option { let shadow = crate::shadow::find(address, len)?; let offset = shadow.offset(address); + // Off the elements of that copy: on a copy of its own bytes, from its + // element 0 (`own_bytes`). + let (shadow, offset) = { + // SAFETY: a buffer view's union member. + let b = unsafe { desc.Anonymous.Buffer }; + let unknown = desc.Format == DXGI_FORMAT_UNKNOWN; + match own_bytes(offset, address, b.FirstElement, b.NumElements, element_size(&desc), b.StructureByteStride, unknown) + .and_then(|(start, bytes)| crate::shadow::exact(start, bytes)) + { + Some(own) => { + desc.Anonymous.Buffer.FirstElement = 0; + (own, 0) + } + None => (shadow, offset), + } + }; // A structured view as a raw view of the same bytes (see `raw_window`). // SAFETY: a buffer view's union member. let structured = unsafe { desc.Anonymous.Buffer }; @@ -2211,6 +2367,29 @@ fn buffer_uav( at: D3D12_CPU_DESCRIPTOR_HANDLE, ) -> Option { let shadow = crate::shadow::find(address, len)?; + // Off the elements of that copy: on a copy of its own bytes, from its + // element 0 (`own_bytes`). + let (shadow, own) = { + // SAFETY: a buffer view's union member. + let b = unsafe { desc.Anonymous.Buffer }; + let element = if b.StructureByteStride > 0 { + u64::from(b.StructureByteStride) + } else if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + }; + let unknown = desc.Format == DXGI_FORMAT_UNKNOWN; + match own_bytes(shadow.offset(address), address, b.FirstElement, b.NumElements, element, b.StructureByteStride, unknown) + .and_then(|(start, bytes)| crate::shadow::exact(start, bytes)) + { + Some(own) => { + desc.Anonymous.Buffer.FirstElement = 0; + (own, true) + } + None => (shadow, false), + } + }; // SAFETY: a live buffer. let flags = unsafe { shadow.buffer.GetDesc() }.Flags; if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { @@ -2226,7 +2405,7 @@ fn buffer_uav( } else { crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) }; - let offset = shadow.offset(address); + let offset = if own { 0 } else { shadow.offset(address) }; // A structured view as a raw view of the same bytes (see `raw_window`). let window = (desc.Format == DXGI_FORMAT_UNKNOWN) .then(|| raw_window(offset, buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride)) @@ -3292,3 +3471,33 @@ mod tests { assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); } } + +#[cfg(test)] +mod own_copy_tests { + use super::own_bytes_if; + + /// A buffer view gets a copy of its own bytes only when it has no host + /// view on its buffer's copy: off that copy's elements, and not a + /// structured view that can be a raw view of the same bytes. + #[test] + fn a_view_off_its_copys_elements_gets_its_own_bytes() { + let base = 0xd_9000_0000u64; + // On an element: the buffer's copy (the two cases of every run's + // log are the ones below). + assert_eq!(own_bytes_if(true, 24, base, 3, 10, 12, 0, false), None); + assert_eq!(own_bytes_if(true, 0, base, 0, 10, 12, 0, false), None); + // A typed view of 12-byte elements, 5,222,240 bytes into its copy + // (8 past an element): its own bytes, from its first element. + assert_eq!(own_bytes_if(true, 5_222_240, base, 3, 10, 12, 0, false), Some((base + 36, 120))); + // A structured view of 32-byte elements 8 bytes in: not on 16, so + // no raw view of the copy either. + assert_eq!(own_bytes_if(true, 8, base, 2, 4, 32, 32, true), Some((base + 64, 128))); + // The same 16 bytes in: off its elements, but a raw view of the + // copy's bytes does (as before). + assert_eq!(own_bytes_if(true, 16, base, 2, 4, 32, 32, true), None); + // No elements, no size, or the switch off: as before. + assert_eq!(own_bytes_if(true, 8, base, 2, 0, 32, 32, true), None); + assert_eq!(own_bytes_if(true, 8, base, 2, 4, 0, 0, false), None); + assert_eq!(own_bytes_if(false, 8, base, 2, 4, 32, 32, true), None); + } +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index ee74cc4..d9768e1 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1698,7 +1698,12 @@ impl State { // makes room again: so the slots are still looked at (the pass // returned here, and a slot whose texture had been streamed out // kept its host copy for as long as the card was full). - let room = crate::resource::room(); + let mut room = crate::resource::room(); + // Bytes uploaded by this pass since the card was last asked + // whether it has room: asked again every 32 MiB (a pass may upload + // 192 MB and more, and one asking a pass let the queue run some + // 400 MB past its line while the world loaded: run 193). + let mut since_asked = 0u64; if !room { HEAP_TEXTURES_FULL.fetch_add(1, Ordering::Relaxed); once!("textures picked by index: the card has no room for more; they wait"); @@ -1962,6 +1967,11 @@ impl State { }; crate::texture::unstage(resource); SPENT.fetch_add(bytes, Ordering::Relaxed); + since_asked += bytes; + if room && since_asked >= 32 << 20 { + since_asked = 0; + room = crate::resource::room(); + } HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed); HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed); match memory { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6559af1..39f4f33 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1270,6 +1270,11 @@ pub(crate) fn dred_on() -> bool { /// budget buffers, a run late). static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +/// Since the last frame line: the largest group count in x an indirect +/// compute record asked for, and the records that asked for more than the +/// 65,535 one dispatch runs (cut to that: the groups past it do not run). +static COMPUTE_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + /// Whether each list of a submission runs and is timed on its own, slow /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics /// builds; the commands are noted with `VICTORY_D3D12_DRED` on). @@ -3990,6 +3995,9 @@ impl Host { self.settle(&mut submitted, why); } } + // Descriptors the title copied into placed heaps directly, before + // command lists that index those slots are submitted. + crate::descriptor::sync_heaps(); let behind = late && flying(); // Before this submission counts as started: what the sweep lets go // of is named by no list, and nothing runs now (behind flights the @@ -5116,7 +5124,12 @@ impl HostList { let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile()); MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed); MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed); - for k in 0..3 { + // And of its indirect compute records: the largest x asked + // for, and how many asked for more than a dispatch runs. + let (widest, cut) = (words.add(3).read_volatile(), words.add(4).read_volatile()); + COMPUTE_GROUPS[0].fetch_max(u64::from(widest), Ordering::Relaxed); + COMPUTE_GROUPS[1].fetch_add(u64::from(cut), Ordering::Relaxed); + for k in 0..5 { words.add(k).write_volatile(0); } }))); @@ -5799,6 +5812,13 @@ impl Meter { tracing::info!( "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame" ); + let compute_widest = COMPUTE_GROUPS[0].swap(0, Ordering::Relaxed); + let compute_cut = COMPUTE_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames; + tracing::info!( + "indirect compute dispatches: the largest group count in x asked for {compute_widest} (run: at most 65535), {compute_cut:.1} records per frame asked for more and were cut to that" + ); + crate::shadow::exact_line(frames); + crate::descriptor::sync_line(frames); late_line(frames); card_clock_line(frames, ms); crate::shadow::back_line(frames); @@ -5892,7 +5912,7 @@ impl Meter { let [kept, dropped, slots, uploaded] = [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed)); tracing::info!( - "writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (VICTORY_PAGE_WRITES: unset counts, 1 acts, guards, slots, all)", + "writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (VICTORY_PAGE_WRITES: unset or guards opens the guarded blocks, 0 counts only, 1, slots, all)", bytes >> 20, if mode & 1 != 0 { "opened, taken again" } else { "left as they were" }, if mode & 4 != 0 { "told as well" } else { "counted only" }, diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 321cc63..4088599 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -74,7 +74,20 @@ void main(uint3 id : SV_DispatchThreadID) { cost = count * instances; draw_counts = uint2(count, instances); } else if (kind == 2) { - uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u)); + uint3 asked = src_args.Load3(src_at); + // Diagnostics, in the budget buffer's words after the mesh ones: + // the largest x a compute record asked for, and the records that + // asked for more groups in x than one dispatch runs (they are cut + // to 65,535 below, so the groups past it never run). Not the + // garbage of a slot nothing wrote. + if (asked.x <= (1u << 24) && asked.y <= 64u && asked.z <= 64u) { + uint noted; + budget.InterlockedMax(12, asked.x, noted); + if (asked.x > 65535u) { + budget.InterlockedAdd(16, 1u, noted); + } + } + uint3 g = min(asked, uint3(65535u, 65535u, 65535u)); // x * y fits 32 bits; the whole count may not. if (g.z != 0 && g.x * g.y > GROUPS / g.z) { g = uint3(0, 0, 0); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index d701973..244a76c 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1433,12 +1433,48 @@ pub(crate) fn room() -> bool { } match crate::host::host().and_then(|h| h.video_memory()) { // What is kept for card copies of title buffers not made yet - // counts as used (`crate::shadow::card_room_kept`; 0 by default). - Some([budget, used, ..]) => used + crate::shadow::card_room_kept() < budget / 100 * room_percent(), + // (`crate::shadow::card_room_kept`) and for the render targets a + // world makes in its first frame ([`targets_room_kept`]) counts as + // used. + Some([budget, used, ..]) => { + used + crate::shadow::card_room_kept() + targets_room_kept() < budget / 100 * room_percent() + } None => filled < WITHOUT_BUDGET, } } +/// The bytes of the card's memory the texture queue leaves free for +/// render targets and other host copies the host itself writes that are +/// not made yet: `VICTORY_CARD_ROOM_FOR_TARGETS_MB` (3,072; 0: none, as +/// before) less what such copies hold now. +/// +/// Measured (runs 193, 197, 198): 652 MB of them before the world, 2,255 +/// to 2,352 MB right after its first frame, 2,800 to 3,100 MB two minutes +/// on, none of them idle (run 198's census). They are made with no room +/// test, in the same frame as the card copies of title buffers (762 MB), +/// after the texture queue has filled the card to its line with textures +/// written while the world loaded (7.3 GB of them at the first world frame +/// of run 193, of which 2.3 GB were let go again within 13 seconds). The +/// card then stood at 99 to 100.5 % of its budget, buffer copies were +/// turned down for good (31 of 95 made: the frame 355 ms where 95 give +/// 238), and the queue was refused from the first world frame on. With +/// their room kept, the queue stops that much earlier while the world +/// loads and gets it back as the targets are made. +#[cfg(windows)] +pub(crate) fn targets_room_kept() -> u64 { + use std::sync::atomic::Ordering::Relaxed; + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + let most = *MOST.get_or_init(|| { + std::env::var("VICTORY_CARD_ROOM_FOR_TARGETS_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map_or(3072 << 20, |mb| mb.min(8192) << 20) + }); + // Every host texture's bytes less those of the copies the title fills. + let targets = HOST_TEXTURES[1].load(Relaxed).saturating_sub(KINDS[1].load(Relaxed)); + most.saturating_sub(targets) +} + /// [`room`] as it was at most a tenth of a second ago, for a question /// asked of many textures a frame ([`room`] asks the system each time). #[cfg(windows)] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index f47de44..2ce495a 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -181,11 +181,27 @@ static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; /// used, and a copy may be made up to nine tenths of the budget: the room /// it takes was kept for it. After the burst what is kept is what the /// burst left of the limit (87 MB of 1,024 in run 189). +/// +/// On by default from the build after run 199 +/// (`VICTORY_CARD_ROOM_FOR_BUFFERS=0`: off, as before). Run 193 had it on and still made 31 copies of 95: the copies +/// and the world's render targets (+1,603 MB) arrive in the same first +/// world frame and raced for the 448 MB left under the line, and a copy +/// turned down is not asked for again (`lookup` asks once), while its room +/// went on being kept (616 MB to the end of the run). So now: the texture +/// queue also keeps room for the targets (`resource::targets_room_kept`), +/// a copy is made up to 97 hundredths of the budget (its room was kept), +/// and the room of a copy turned down is given up ([`CARD_REFUSED`]). fn card_room_kept_on() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_BUFFERS").is_some_and(|v| v == "1")) + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_BUFFERS").is_none_or(|v| v != "0")) } +/// Title buffers big enough for a copy in the card's memory that were +/// turned down for want of room, since the start, and their bytes: their +/// copies stay in the PC's memory for as long as the title keeps the +/// buffers, so no room is kept for them any more. +static CARD_REFUSED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + /// The bytes of the card's memory the texture queue leaves free for card /// copies of title buffers not made yet ([`card_room_kept_on`]): 0 with /// the switch off or without card copies. @@ -193,7 +209,7 @@ pub(crate) fn card_room_kept() -> u64 { if !card_room_kept_on() || !cards() { return 0; } - card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed)) + card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed)) } /// The copies in the card's memory. @@ -248,10 +264,30 @@ fn card_for(size: u64) -> Option { // shrinks by the copies' bytes, at most `card_limits`' second number. // (With `card_room_kept_on` the texture queue kept this copy's room // free, and the copy may go up to the queue's own line.) - let tenths = if card_room_kept_on() { 9 } else { 8 }; + let hundredths = if card_room_kept_on() { 97 } else { 80 }; if let Some([budget, used, ..]) = host.video_memory() - && used + size > budget / 10 * tenths + && used + size > budget / 100 * hundredths { + // Said, with the numbers it was decided by: run 193 made 31 copies + // of 95 and no line named the others. The first 64, then every + // 32nd. + let n = CARD_REFUSED[0].fetch_add(1, Ordering::Relaxed) + 1; + let bytes = CARD_REFUSED[1].fetch_add(size, Ordering::Relaxed) + size; + if n <= 64 || n.is_multiple_of(32) { + tracing::info!( + "no card copy for a title buffer of {} KiB: the card has {} MB in use of a budget of {} MB and a copy is made up to \ + {} MB; the copies made hold {} MB of at most {} MB; {} buffers turned down so far ({} MB), frame {}", + size >> 10, + used >> 20, + budget >> 20, + (budget / 100 * hundredths) >> 20, + CARD_BYTES[0].load(Ordering::Relaxed) >> 20, + most >> 20, + n, + bytes >> 20, + crate::frame::current() + ); + } return None; } if CARD_BYTES[0].fetch_add(size, Ordering::Relaxed) + size > most { @@ -3550,6 +3586,82 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option, u64)>)> = Mutex::new((0, BTreeMap::new())); + +/// Since the last frame line: askings for such copies, and copies made. +static EXACT_STATS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// A copy of the title memory `[address, address + len)` that starts at +/// `address` itself: for a buffer view whose bytes do not start on an +/// element of the copy its buffer has (`descriptor/host.rs` `own_bytes`). +/// A host view counts its first element from its buffer's start; a console +/// view starts at any address, and the title places views at ring +/// positions inside its big GPU heap. Such a view was refused and its slot +/// read zeros ("buffer view not on an element of its host copy", in every +/// run; upstream VIctory 86a5ed6 found its meshlet culling constants and +/// colour-bake parameter blocks among them and gives each a copy of its +/// own bytes, as here). +/// +/// The copy is brought up to date and written back like any other (a list +/// refreshes the copy its view's slot shows, `buffer_copy`). Kept by +/// (start, bytes) for as long as a list or a slot holds it; of the others, +/// those not asked for lately go once there are many (ring positions +/// change every frame). +pub(crate) fn exact(address: u64, len: u64) -> Option> { + /// Copies kept before the idle ones are looked for, and the askings an + /// idle one stays for. + const MANY: usize = 256; + const LATELY: u64 = 512; + if len == 0 { + return None; + } + EXACT_STATS[0].fetch_add(1, Ordering::Relaxed); + let mut guard = EXACT.lock().unwrap_or_else(|e| e.into_inner()); + let (tick, map) = &mut *guard; + *tick += 1; + let now = *tick; + if let Some((shadow, used)) = map.get_mut(&(address, len)) { + *used = now; + shadow.used.store(crate::host::moment(), Ordering::Relaxed); + return Some(shadow.clone()); + } + if map.len() >= MANY { + // Held by the map alone (no list), its buffer by the copy alone (no + // slot shows it), and not asked for lately. + map.retain(|_, (shadow, used)| { + Arc::strong_count(shadow) > 1 || crate::host::references(&shadow.buffer) > 1 || *used + LATELY > now + }); + } + let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(256))?; + crate::host::name(&buffer, || format!("title view {address:#x}+{len:#x}")); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let shadow = Arc::new(Shadow::new(buffer, data, gpu, address, len)); + map.insert((address, len), (shadow.clone(), now)); + EXACT_STATS[1].fetch_add(1, Ordering::Relaxed); + Some(shadow) +} + +/// With the frame line: the buffer views that got a copy of their own +/// bytes ([`exact`]), per frame over `frames`, and the copies kept now. +/// Nothing while there are none. +pub(crate) fn exact_line(frames: f64) { + let [asked, made] = [0, 1].map(|i| EXACT_STATS[i].swap(0, Ordering::Relaxed)); + if asked == 0 { + return; + } + let kept = EXACT.lock().unwrap_or_else(|e| e.into_inner()).1.len(); + tracing::info!( + "buffer views off their copy's elements (they were refused and read zeros; VICTORY_VIEW_OWN_COPY=0 refuses them again): \ + {:.1} asked for per frame, {:.1} copies of their own bytes made per frame, {kept} kept", + asked as f64 / frames, + made as f64 / frames + ); +} + #[cfg(test)] mod window_tests { use super::{WINDOW, cover, grid, holder, longest_tail, tail_of, window_of}; diff --git a/crates/victory-gpu/src/tiles.rs b/crates/victory-gpu/src/tiles.rs index a8b98f6..6d3c3d8 100644 --- a/crates/victory-gpu/src/tiles.rs +++ b/crates/victory-gpu/src/tiles.rs @@ -105,18 +105,19 @@ pub(crate) fn wanted() -> bool { }) } +fn parse_floor(value: Option<&str>) -> u64 { + value + .and_then(|v| v.trim().parse::().ok()) + .map_or(1 << 20, |kb| kb.max(64).saturating_mul(1024)) +} + /// The bytes from which a texture is made this way: a megabyte, or /// `VICTORY_LEVELS_MIN_KB`. (The accounting of run 189: the levels not /// held are 1.9 MB a copy on some 1,600 copies; a 512x512 texture has six /// tiles at most, and most of the calls for nothing.) pub(crate) fn floor() -> u64 { static BYTES: std::sync::OnceLock = std::sync::OnceLock::new(); - *BYTES.get_or_init(|| { - std::env::var("VICTORY_LEVELS_MIN_KB") - .ok() - .and_then(|v| v.trim().parse::().ok()) - .map_or(1 << 20, |kb| kb.max(64) << 10) - }) + *BYTES.get_or_init(|| parse_floor(std::env::var("VICTORY_LEVELS_MIN_KB").ok().as_deref())) } /// The bytes of the tiles given to textures now: the card's memory they @@ -304,14 +305,18 @@ impl Tiled { } let mut standard = Vec::with_capacity(standard_levels as usize); for tiling in &tilings[..standard_levels as usize] { - let tiles = tiling.WidthInTiles * u32::from(tiling.HeightInTiles) * u32::from(tiling.DepthInTiles); + let tiles = tiling + .WidthInTiles + .checked_mul(u32::from(tiling.HeightInTiles)) + .and_then(|n| n.checked_mul(u32::from(tiling.DepthInTiles))) + .unwrap_or(0); if tiles == 0 || tiles > HEAP_TILES || tiling.StartTileIndexInOverallResource == D3D12_PACKED_TILE { return None; } standard.push(tiles); } let packed_tiles = if packed.NumPackedMips > 0 { packed.NumTilesForPackedMips } else { 0 }; - if packed_tiles > HEAP_TILES { + if (packed.NumPackedMips > 0 && packed_tiles == 0) || packed_tiles > HEAP_TILES { return None; } let full = u64::from(total) * TILE; @@ -366,13 +371,16 @@ impl Tiled { held: u32, room: bool, ) -> (bool, bool) { + let held = held & self.every_level(); + let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); self.held.store(held, Ordering::Relaxed); let card = self.card.load(Ordering::Relaxed); let named = held | card; // The levels the card itself writes are few and are not kept // waiting: a write of the card's into no memory is lost. - let changed = self.give_on(queue, device, texture, named, if room { named } else { card }); - (changed, self.without(named) != 0) + let changed = self.give_locked(&mut given, queue, device, texture, named, if room { named } else { card }); + let missing = self.without_locked(&given, named) != 0; + (changed, missing) } /// At the submission of a list in which the card itself writes the @@ -397,12 +405,25 @@ impl Tiled { texture: &ID3D12Resource, levels: u32, ) -> bool { - let card = self.card.fetch_or(levels, Ordering::Relaxed) | levels; - let changed = self.give_on(queue, device, texture, card | self.held.load(Ordering::Relaxed), levels); - // A level that got no tiles (no heap could be had): the list's - // zeros and its write went nowhere, so the next list that writes - // the level sends its zeros again. - let without = self.without(levels); + let levels = levels & self.every_level(); + let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + let prev = self.card.load(Ordering::Relaxed); + let changed = self.give_locked( + &mut given, + queue, + device, + texture, + prev | levels | self.held.load(Ordering::Relaxed), + levels, + ); + // Only levels that actually received tiles (or already had them) saw + // the card's write; a level that got no tiles saw its zeros and write + // dropped, so neither `card` nor `claimed` should keep it. + let without = self.without_locked(&given, levels); + let backed = levels & !without; + if backed != 0 { + self.card.fetch_or(backed, Ordering::Relaxed); + } if without != 0 { self.unclaim(without); } @@ -446,6 +467,10 @@ impl Tiled { /// Of `levels` (a bit a level), the ones that have no tiles now. pub(crate) fn without(&self, levels: u32) -> u32 { let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + self.without_locked(&given, levels) + } + + fn without_locked(&self, given: &Given, levels: u32) -> u32 { let first_packed = self.standard.len() as u32; let mut without = 0; for level in 0..self.levels.min(32) { @@ -469,6 +494,7 @@ impl Tiled { /// Returns whether the first level a view may show changed /// ([`Tiled::first_shown`]): the caller has the texture's slots made /// again. + #[cfg(test)] pub(crate) fn give_on( &self, queue: &ID3D12CommandQueue, @@ -476,10 +502,22 @@ impl Tiled { texture: &ID3D12Resource, named: u32, may: u32, + ) -> bool { + let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + self.give_locked(&mut given, queue, device, texture, named, may) + } + + fn give_locked( + &self, + given: &mut Given, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + named: u32, + may: u32, ) -> bool { let has = |level: u32| level < 32 && named & (1 << level) != 0; let now = |level: u32| level < 32 && named & may & (1 << level) != 0; - let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); let first_packed = self.standard.len() as u32; // (subresource, tiles, the level if it has tiles of its own) to map now. let mut wanted: Vec<(u32, u32, Option)> = Vec::new(); @@ -607,24 +645,40 @@ impl Drop for Tiled { } } -/// Keeps a two-dimensional shader view from the levels before `first` of a -/// texture of `levels` levels: it starts at `first` if it started before -/// it, and shows as many levels fewer. A sample then lands on the first -/// level that has memory instead of reading zeros from one that has none; -/// level numbers and sizes a shader asks for count from that level. +/// Keeps a two-dimensional shader view (2D or 2D array) from the levels +/// before `first` of a texture of `levels` levels: it starts at `first` if +/// it started before it, shows as many levels fewer (clamped to the +/// remaining levels), and reduces `ResourceMinLODClamp` by the same shift so +/// the effective minimum LOD stays at the same resource level. pub(crate) fn show_from(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, first: u32, levels: u32) { - if desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D || first >= levels { + if first >= levels { return; } - // SAFETY: a 2D view's member of the union. - let view = unsafe { &mut desc.Anonymous.Texture2D }; - if first <= view.MostDetailedMip { - return; - } - let fewer = first - view.MostDetailedMip; - view.MostDetailedMip = first; - if view.MipLevels != u32::MAX { - view.MipLevels = view.MipLevels.saturating_sub(fewer).max(1); + let clamp = |most: &mut u32, mips: &mut u32, min_lod: &mut f32| { + if first <= *most { + return; + } + let fewer = first - *most; + *most = first; + if *mips != u32::MAX { + *mips = mips.saturating_sub(fewer).clamp(1, levels - first); + } + if *min_lod > 0.0 { + *min_lod = (*min_lod - fewer as f32).max(0.0); + } + }; + match desc.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE2D => { + // SAFETY: `ViewDimension` selects `Texture2D`. + let view = unsafe { &mut desc.Anonymous.Texture2D }; + clamp(&mut view.MostDetailedMip, &mut view.MipLevels, &mut view.ResourceMinLODClamp); + } + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { + // SAFETY: `ViewDimension` selects `Texture2DArray`. + let view = unsafe { &mut desc.Anonymous.Texture2DArray }; + clamp(&mut view.MostDetailedMip, &mut view.MipLevels, &mut view.ResourceMinLODClamp); + } + _ => {} } } @@ -1416,4 +1470,118 @@ void look() { s[8] ); } + + #[test] + fn floor_saturates_instead_of_wrapping() { + assert_eq!(parse_floor(None), 1 << 20); + assert_eq!(parse_floor(Some("0")), 64 << 10); + assert_eq!(parse_floor(Some("2048")), 2048 << 10); + assert_eq!(parse_floor(Some(&(1u64 << 54).to_string())), u64::MAX); + assert_eq!(parse_floor(Some(&u64::MAX.to_string())), u64::MAX); + } + + #[test] + fn show_from_clamps_2d_and_2d_array_and_adjusts_min_lod() { + let mut srv2d = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: 12, + PlaneSlice: 0, + ResourceMinLODClamp: 3.5, + }, + }, + }; + show_from(&mut srv2d, 3, 11); + // SAFETY: `ViewDimension` is `TEXTURE2D`. + let v2d = unsafe { srv2d.Anonymous.Texture2D }; + assert_eq!(v2d.MostDetailedMip, 3); + // Clamped to remaining levels (11 - 3 = 8), not 12 - 3 = 9. + assert_eq!(v2d.MipLevels, 8); + assert_eq!(v2d.ResourceMinLODClamp, 0.5); + + let mut srv_arr = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: 0, + MipLevels: 6, + FirstArraySlice: 0, + ArraySize: 1, + PlaneSlice: 0, + ResourceMinLODClamp: 1.5, + }, + }, + }; + show_from(&mut srv_arr, 2, 11); + // SAFETY: `ViewDimension` is `TEXTURE2DARRAY`. + let varr = unsafe { srv_arr.Anonymous.Texture2DArray }; + assert_eq!(varr.MostDetailedMip, 2); + assert_eq!(varr.MipLevels, 4); + assert_eq!(varr.ResourceMinLODClamp, 0.0); + } + + #[test] + fn card_wrote_failure_does_not_poison_card_mask() { + let Some(host) = host() else { + return; + }; + // A dummy live resource (never mapped because `take()` rejects `HEAP_TILES + 1`). + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = Rig::desc(DXGI_FORMAT_R8G8B8A8_UNORM, 64, 2, false); + let mut tex: Option = None; + // SAFETY: plain texture creation on the host device. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut tex, + ) + .unwrap(); + } + let tex = tex.unwrap(); + STATS[0].fetch_add(1, Ordering::Relaxed); + STATS[1].fetch_add(TILE, Ordering::Relaxed); + let mut tiled = Tiled { + // Level 0 demands > HEAP_TILES so `take()` fails deterministically. + standard: vec![HEAP_TILES + 1, 1], + packed: 0, + levels: 2, + full: TILE, + given: Mutex::new(Given { + levels: vec![false, false], + packed: false, + runs: Vec::new(), + }), + shown: AtomicU32::new(u32::MAX), + held: AtomicU32::new(0), + card: AtomicU32::new(0), + claimed: AtomicU32::new(0), + }; + assert_eq!(tiled.claim(1 << 0), 1 << 0); + let changed = tiled.card_wrote_on(host.queue(), &host.device, &tex, 1 << 0); + assert!(!changed); + assert_eq!(tiled.card.load(Ordering::Relaxed), 0, "failed tile allocation must not poison `card`"); + assert_eq!(tiled.first_shown(), None); + assert_eq!(tiled.claim(1 << 0), 1 << 0, "failed level must be unclaimed"); + // Even if level 0 later becomes allocatable, an upload with `room == false` + // that does not hold level 0 must not treat level 0 as card-owned. + tiled.standard[0] = 1; + let (changed, waiting) = tiled.uploaded_on(host.queue(), &host.device, &tex, 1 << 1, false); + assert!(!changed && waiting); + assert!(!tiled.has_tiles(0)); + assert_eq!(tiled.given_bytes(), 0); + } } diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index bc7d3be..9bfcb0a 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -33,6 +33,27 @@ pub(crate) const PAGE: usize = 64 << 10; /// The kernel's page, the unit of its answers. const KERNEL_PAGE: usize = 4096; +/// A title-memory range whose changed pages another subsystem needs to read. +pub(crate) struct Tracked { + start: usize, + end: usize, + seen: Mutex>, +} + +/// Tracks a runtime GPU-memory range, including physical-page views when +/// `views` is true. Other process memory is not tracked. +pub(crate) fn track(start: usize, len: usize, views: bool) -> Option { + let end = start.checked_add(len)?; + if len == 0 || writes(start, end, views).is_none() { + return None; + } + Some(Tracked { + start, + end, + seen: Mutex::default(), + }) +} + struct Journal { /// Numbers the askings; 0 is "never". asked: u64, @@ -377,6 +398,42 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve )) } +impl Tracked { + /// Takes changed pages of `[from, to)`, cut to the tracked range. A + /// partial page stays changed so a later take can read its other bytes. + pub(crate) fn take(&self, from: usize, to: usize) -> Vec<(usize, usize)> { + let (from, to) = (from.max(self.start), to.min(self.end)); + if from >= to { + return Vec::new(); + } + let Some((_, pages)) = writes(from, to, true) else { + return Vec::new(); + }; + let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner()); + let mut ranges: Vec<(usize, usize)> = Vec::new(); + for (page, write) in pages { + if seen.get(&page).is_some_and(|&last| last >= write) { + continue; + } + let (start, end) = ((page * PAGE).max(from), ((page + 1) * PAGE).min(to)); + if start >= end { + continue; + } + // Keep partial pages dirty: the caller has not taken the rest. + if (page * PAGE).max(self.start) >= from + && ((page + 1) * PAGE).min(self.end) <= to + { + seen.insert(page, write); + } + match ranges.last_mut() { + Some((_, last)) if *last == start => *last = end, + _ => ranges.push((start, end)), + } + } + ranges + } +} + /// Guarded blocks of view memory. const BLOCK: usize = PAGE; @@ -698,16 +755,22 @@ pub fn writing(at: usize, len: usize) { /// copies of buffers and textures read through tables take them again); /// 2, the placed textures picked by index that lie under it are due again; /// 4, both also for reads to plain addresses when they have finished. -/// Unset or `0`: nothing, counted only. `1`: bits 1 and 2. `guards`: bit 1 -/// alone. `slots`: bit 2 alone. `all`: everything. +/// Unset or `guards`: bit 1 alone. `0`: nothing, counted only (the default +/// until run 199). `1`: bits 1 and 2. `slots`: bit 2 alone. `all`: +/// everything. +/// (Bit 1 by default: in every run 10,000 to 50,000 guarded blocks of host +/// copies lay under such writes and kept the bytes from before; runs 197 +/// and 198 opened them, 9,766 and 10,796 blocks, with nothing worse for +/// it. Bit 2 makes texture slots due and is the one that flooded the +/// queue in an earlier form: still asked for by name.) pub(crate) fn page_writes() -> u8 { static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); *MODE.get_or_init(|| match std::env::var("VICTORY_PAGE_WRITES").as_deref().map(str::trim) { + Ok("0") => 0, Ok("1") => 3, - Ok("guards") => 1, Ok("slots") => 2, Ok("all") => 7, - _ => 0, + _ => 1, }) } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index bef2e3c..63c4de7 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1016,6 +1016,26 @@ fn own_bits_on() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0")) } +/// The refusal of a first half of an interpolation whose result is read +/// as data ([`Lower::interp`]). +pub(super) const FIRST_HALF: &str = "the first half of an interpolation"; + +thread_local! { + /// Whether first halves of interpolations are evaluated as the pair + /// they start ([`with_first_half_pairs`]). + static FIRST_HALF_PAIRS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Runs `translate` with first halves of interpolations evaluated as the +/// pair they start: the translation of a program refused with +/// [`FIRST_HALF`] (`VICTORY_FIRST_HALF=0`: refused again, as before). +pub(super) fn with_first_half_pairs(translate: impl FnOnce() -> R) -> R { + let before = FIRST_HALF_PAIRS.replace(true); + let result = translate(); + FIRST_HALF_PAIRS.set(before); + result +} + pub(super) fn host_max_wave() -> u32 { #[cfg(test)] if let Some(lanes) = TEST_HOST_WAVE.get() { @@ -1497,7 +1517,9 @@ impl<'a> Lower<'a> { // the other half of its dst, PS_DeferredTextured): evaluated as the pair it // starts. Approximate for those other bits (P0 + i P10 on the console); a // first half only the second half reads is gone before lowering. - if std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") { + // Only in the second translation of a program the first + // one refused for it ([`with_first_half_pairs`]). + if FIRST_HALF_PAIRS.get() && std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") { for (_, i) in &x.io.interps { if let Interp::Interpolated { first, .. } = i { for s in first { @@ -2083,8 +2105,9 @@ impl<'a> Lower<'a> { if !every { if halves { need(self.cur_ir); + return Err(WHERE); } - return Err(WHERE); + return Ok(self.half_sum_present(x)); } let c = self.cur; let i32t = self.s.t.i32; @@ -2112,6 +2135,61 @@ impl<'a> Lower<'a> { Ok(self.s.m.bin(c, Bin::Or, first, total)) } + /// [`Self::half_sum`] in one host wave of 64 where some lanes have left (a thread past + /// the end of the data returns early): the console runs the sum in every lane, a lane + /// outside EXEC with +0, so after step k every lane of an aligned run of 2^k lanes holds + /// that run's partial sum, the lanes that left included. A lane reads its partner run's + /// sum from the first lane of that run that is here, and +0 where none is (every lane of + /// the run left, so its terms were all +0). Lane 0's high half likewise: 0 if it left. + fn half_sum_present(&mut self, x: V) -> V { + let c = self.cur; + let i32t = self.s.t.i32; + self.s.flags |= flags::WAVE_OPS; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let here = self.s.m.bool(true); + let ballot = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[here]); + let (blo, bhi) = (self.s.m.extract(c, ballot, 0), self.s.m.extract(c, ballot, 1)); + let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let [zero, k31, k32] = [0, 31, 32].map(|k| self.s.m.i32(k)); + // The lanes of the run of `size` lanes at `base` that are here, from bit 0. + let present = |l: &mut Self, base: V, size: u32| -> V { + let upper = l.s.m.cmp(c, pred::IUGE, base, k32); + let word = l.s.m.select(c, upper, bhi, blo); + let at = l.s.m.bin(c, Bin::And, base, k31); + let bits = l.s.m.bin(c, Bin::LShr, word, at); + if size >= 32 { + bits + } else { + let m = l.s.m.i32((1u32 << size) - 1); + l.s.m.bin(c, Bin::And, bits, m) + } + }; + let mut sum = x; + for step in 0..6u32 { + let size = 1u32 << step; + let (bit, run) = (self.s.m.i32(size), self.s.m.i32(!(size - 1))); + let other = self.s.m.bin(c, Bin::Xor, lane, bit); + let base = self.s.m.bin(c, Bin::And, other, run); + let bits = present(self, base, size); + // FirstbitLo (dx.op 32): the run's first lane that is here + let first = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[bits]); + let any = self.s.m.cmp(c, pred::NE, bits, zero); + let first = self.s.m.select(c, any, first, zero); + let from = self.s.m.bin(c, Bin::Add, base, first); + let theirs = self.read_lane(sum, from); + let theirs = self.s.m.select(c, any, theirs, zero); + sum = self.add_halves(sum, theirs); + } + let (high, low, one) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(1)); + let lane0 = self.s.m.bin(c, Bin::And, blo, one); + let lane0 = self.s.m.cmp(c, pred::NE, lane0, zero); + let first = self.read_lane(x, zero); + let first = self.s.m.select(c, lane0, first, zero); + let first = self.s.m.bin(c, Bin::And, first, high); + let sum = self.s.m.bin(c, Bin::And, sum, low); + self.s.m.bin(c, Bin::Or, first, sum) + } + fn run(mut self) -> Result { let p = self.x.p; let order = crate::ir::reverse_postorder(&p.blocks); @@ -5617,6 +5695,18 @@ impl<'a> Lower<'a> { .find_map(|(s, _)| use_of(*s)) }; let use_at = use_of(site).or_else(twin); + // A descriptor nothing uses as one, whose size the code reads all the same (a + // texture picked from the heap by an index in a constant buffer, its width and + // height turned into a texel size; a buffer tested for being empty by its record + // count): the kind from its dwords and its used-resource entry. + let unused = if use_at.is_none() { + self.unused_descriptor_kind(inst, site, code, count) + } else { + None + }; + let (first, props, image, uav, used) = if let Some(kind) = unused { + kind + } else { let Some((at, first)) = use_at else { // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only // copies its dwords and compares them, lane against first lane, and every load @@ -5726,6 +5816,9 @@ impl<'a> Lower<'a> { } _ => return Err("a scalar memory read as data"), }; + (first, props, image, uav, used) + }; + let src = Source::Loaded { load: site, first }; let h = self.handle(site, &src, false, props)?; let c = self.cur; let i32t = self.s.t.i32; @@ -5793,8 +5886,10 @@ impl<'a> Lower<'a> { inst.write(Reg::S(code + first + k)) .is_some_and(|v| self.computed_with(v, 6)) }); + // (A descriptor nothing uses as one gets it whenever the host can tell it, as + // a buffer whose address alone is read does.) if first == 0 - && computed + && (computed || unused.is_some()) && let Some((lo, hi)) = self.view_address(site) { words.extend([(0, lo), (1, hi)]); @@ -5817,6 +5912,67 @@ impl<'a> Lower<'a> { Ok(()) } + /// What [`Self::descriptor_data`] makes of a descriptor load that nothing uses as a + /// descriptor but whose dwords the code reads: the first dword, the handle properties, + /// the image kind (none for a buffer), whether it is an unordered view, and its + /// used-resource entry. An image's eight dwords read as a 2D texture's, a buffer's four + /// as a raw view's where the code reads its record count (dword 2); none for anything + /// else (a constant buffer, a sampler, a buffer whose address alone is read). + // shortcut: an image whose kind nothing tells is taken for a 2D texture (the title's + // reads are texel sizes of 2D textures: puddle masks, shadow masks); a host view of + // another kind would answer its own sizes. + #[allow(clippy::type_complexity)] + fn unused_descriptor_kind( + &self, + inst: &Inst, + site: Site, + code: u8, + count: u32, + ) -> Option<(u8, (u32, u32), Option, bool, Option<&'a UsedResource>)> { + // Kept per lane and compared (`Resources::lane_copied`), or a sampler's: the cases + // `descriptor_data` handles on their own. + if self.x.res.lane_copied.contains(&site) + || self.x.res.descriptors.iter().any(|d| { + d.role == Role::Sampler + && d.source.leaves().into_iter().any( + |l| matches!(*l, Source::Loaded { load, .. } if load == site), + ) + }) + { + return None; + } + let used = self.used_kind(&Source::Loaded { + load: site, + first: 0, + }); + if used.is_some_and(|u| !matches!(u.kind, ResourceType::Srv | ResourceType::Uav)) { + return None; + } + let read = |k: u32| { + inst.write(Reg::S(code + k as u8)).is_some_and(|v| { + self.x + .p + .blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.reads.iter().any(|r| r.1 == v)) + }) + }; + let uav = used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + match count { + // width (dwords 1-2), height (2), levels (3), depth (4) + 8 if (1..5).any(read) && used.is_none_or(|u| u.dwords == 8) => { + Some((0, (2 | u, 0x409), Some(2), uav, used)) + } + // the record count + 4 if read(2) && used.is_none_or(|u| u.dwords == 4) => { + Some((0, (11 | u, 0), None, uav, used)) + } + _ => None, + } + } + /// `s_load_dword*` from the program's constant table. fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> { let Fields::Smem { @@ -7115,12 +7271,6 @@ impl<'a> Lower<'a> { let r = self.read_lane(x, from); int(self, r) } - "v_cvt_f32_f64" => { - let (lo, hi) = self.f64_pair(inst, 0)?; - let bits = self.f64_to_f32_bits(lo, hi); - let r = self.as_float(bits); - float(self, r) - } "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1" | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => { let mut a = s(self, 0)?; @@ -7138,6 +7288,12 @@ impl<'a> Lower<'a> { let r = self.s.m.cast(c, op, a, self.s.t.f32); float(self, r) } + "v_cvt_f32_f64" => { + let (lo, hi) = self.f64_pair(inst, 0)?; + let bits = self.f64_to_f32_bits(lo, hi); + let r = self.as_float(bits); + float(self, r) + } "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { // Each source is f32, or with op_sel_hi the low (op_sel: high) // f16 half; neg_hi is the absolute value here. @@ -8902,7 +9058,26 @@ impl<'a> Lower<'a> { fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { let Some(&interp) = self.interps.get(&site) else { - return Err("the first half of an interpolation"); + // The first half of a pair: its second half interpolates the + // attribute itself, so nothing needs this half's partial sum. + // But an f16 second half that writes the high half of the + // register this one wrote keeps the low half as it was (the + // console compiler reuses the register; the low half is not + // read), so the register needs a value: 0. + let name = inst.name(); + if name == "v_interp_p1_f32" || name == "v_interp_p1ll_f16" { + let dst = match &inst.fields { + Fields::Vintrp { dst, .. } => Some(*dst), + Fields::Valu(v) => v.dst, + _ => None, + }; + if let Some(Operand::Vector { reg, .. }) = dst { + let zero = self.s.m.i32(0); + self.write(inst, Reg::V(reg), zero, None); + return Ok(()); + } + } + return Err(FIRST_HALF); }; let name = inst.name(); let (dst, src) = match &inst.fields { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 3f6f9ff..5217df8 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -297,7 +297,23 @@ pub struct UserData { /// Translates the vertex, pixel, compute or mesh program of a console /// shader container. +/// +/// A program refused because the first half of an interpolation is read as +/// data is translated once more with first halves evaluated as the pair +/// they start (`lower::with_first_half_pairs`), and only such a program: +/// with that on for every program, 8,551 pixel programs of the title that +/// already translated came out changed (an extra evaluation in each), for +/// the sake of 9 that did not translate. pub fn translate(container: &[u8]) -> Result { + match translate_plain(container) { + Err(ShaderError::Unsupported { what, .. }) if what == lower::FIRST_HALF => { + lower::with_first_half_pairs(|| translate_plain(container)) + } + other => other, + } +} + +fn translate_plain(container: &[u8]) -> Result { let c = Container::parse(container)?; let dxil = c .part(FourCC::DXIL) diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index db82f33..55cc55d 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -95,10 +95,20 @@ fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram { /// `program()` for a host of 32-lane waves, with the branches closing `wide` taken wave-wide. fn lowered(native: &NativeProgram, p: &ir::Program, wide: &HashSet) -> Result { + lowered_on(native, p, wide, 32) +} + +/// [`lowered`] for a host whose waves have at most `host_wave` lanes. +fn lowered_on( + native: &NativeProgram, + p: &ir::Program, + wide: &HashSet, + host_wave: u32, +) -> Result { let st = structure::structure_wide(p, wide).expect("structure"); let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track"); let io = io::raise(p, native).expect("io::raise"); - let was = lower::TEST_HOST_WAVE.replace(Some(32)); + let was = lower::TEST_HOST_WAVE.replace(Some(host_wave)); let lowered = lower::lower(&lower::Parts { native, p, @@ -199,6 +209,76 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]); } +/// The console's 16-bit wave sum where the lanes at or past s0 have left the program (a +/// thread past the end of the data): on the console they add +0, and after each step of the +/// tree they hold their run's partial sum all the same. On a host of 64-lane waves (AMD) the +/// lanes that are here read each partner run's sum from a lane of it that is here. +#[test] +fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() { + let mut words = vec![ + 0x7DA8_0000, // v_cmpx_gt_u32 exec, s0, v0: the lanes below s0 stay + 0, // s_cbranch_execz to the end (filled in below) + 0x340C_0085, // v_lshlrev_b32 v6, 5, v0 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 + 0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7 + 0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7 + 0x4A0E_0EFF, + 0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7 + ]; + words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w })); + words.extend_from_slice(&[ + 0x7E00_0207, // v_mov_b32 v0, s7 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]); + // past every word after it, to the program's end + words[1] = 0xBF88_0000 | (words.len() as u32 - 2); + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = lowered_on(&native, &p, &HashSet::new(), 64).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let wide = |h: u16| { + if h == 0 { + 0.0 + } else { + f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13) + } + }; + let narrow = |f: f32| { + if f == 0.0 { + return 0; + } + let b = f.to_bits(); + let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF); + let rest = b & 0x1FFF; + (h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16 + }; + let add = |a: u16, b: u16| narrow(wide(a) + wide(b)); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut ran = false; + for stay in [64u32, 63, 40, 33, 32, 17, 5, 1] { + let terms: Vec = (0..64u32) + .map(|t| if t < stay { (0x3C00 + 37 * t) as u16 } else { 0 }) + .collect(); + let mut tree = terms.clone(); + while tree.len() > 1 { + tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect(); + } + let Some(got) = on_the_card(&shader, [stay, 0]) else { + return; + }; + ran = true; + // (the high half is lane 0's term's: zero) + assert_eq!(got, u32::from(tree[0]), "{stay} lanes stay: got {got:#x}, the console's tree {:#x}", tree[0]); + } + if ran { + eprintln!("ran on the hardware device: the console's tree with lanes gone, in every case"); + } +} + /// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2 /// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The /// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the From 955c8b49d9148e100c8888c3e91e28c47b338443 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 00:55:56 -0600 Subject: [PATCH 203/445] A texture filled while the runtime remaps takes the pages that are there With VICTORY_TEXTURE_NO_WAIT=1 a refresh that met the runtime remapping title memory read the whole chain or nothing. A texture the title holds only the smaller levels of is never all there, so nothing was read, and the upload recorded before put the staging buffer's zeros over the levels on the card. A staging buffer never filled now takes the pages that are there; what was away for the moment of a change is read after it, and a filling with less than was mapped makes the slots due again (at most 8 times in a row). VICTORY_TEXTURE_FILL=0: as before. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 74 +++++++++++++++++++ crates/victory-gpu/src/draw.rs | 1 + crates/victory-gpu/src/host.rs | 85 +++++++++++++++++++++- crates/victory-gpu/src/inplace.rs | 29 ++++++++ crates/victory-gpu/src/texture.rs | 87 +++++++++++++++++++++-- crates/victory-gpu/src/watch.rs | 16 +++++ 6 files changed, 282 insertions(+), 10 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index ce1dd06..101a39c 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -147,6 +147,36 @@ pub(crate) fn levels_waiting(start: u64) { WAITING.lock().unwrap_or_else(|e| e.into_inner()).insert(start, crate::host::moment()); } +/// Placed textures (by the start of their memory) filled while the runtime +/// was remapping with less than was mapped of them +/// (`crate::texture::fill_unlocked`), whose slots the next texture pass +/// makes due again; and how often in a row that was, which ends it: memory +/// that is shown and cannot be read would be uploaded again every frame. +static SHORT: Mutex<(std::collections::BTreeSet, std::collections::BTreeMap)> = + Mutex::new((std::collections::BTreeSet::new(), std::collections::BTreeMap::new())); + +/// Fillings in a row of one texture that got less than was mapped, after +/// which its slots wait for the next notice of its memory. +const SHORT_IN_A_ROW: u32 = 8; + +/// The placed texture at `start` was filled with less than was mapped. +pub(crate) fn read_short(start: u64) { + let mut short = SHORT.lock().unwrap_or_else(|e| e.into_inner()); + let times = short.1.entry(start).or_insert(0); + *times += 1; + if *times <= SHORT_IN_A_ROW { + short.0.insert(start); + } +} + +/// The placed texture at `start` was filled with all that was mapped. +pub(crate) fn read_all(start: u64) { + let mut short = SHORT.lock().unwrap_or_else(|e| e.into_inner()); + if !short.1.is_empty() { + short.1.remove(&start); + } +} + /// Title memory by the placed texture views that describe it: per span of /// memory (its start, its end at full size) the title slots holding a /// view of a texture that takes exactly that span. A console title need @@ -1284,6 +1314,30 @@ impl HostHeap { slots.len() } + /// Makes the slots of the textures filled with less than was mapped + /// ([`read_short`]) due from the next frame on. Returns how many. + pub(crate) fn texture_slots_short(&self, frame: u64) -> usize { + if self.sampler { + return 0; + } + let starts = std::mem::take(&mut SHORT.lock().unwrap_or_else(|e| e.into_inner()).0); + if starts.is_empty() { + return 0; + } + let mut slots: Vec = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + starts.iter().flat_map(|&start| placed.slots_at(start)).collect() + }; + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + for &slot in &slots { + textures.changed(slot, frame, frame + 1); + } + slots.len() + } + /// Takes the ranges of title memory written behind the guards' back /// since the last call ([`page_written`]) and finds the slots whose /// placed texture holds bytes of them ([`Spans::slots_holding`]). A @@ -2939,6 +2993,26 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { mod tests { use super::*; + /// A texture filled with less than was mapped is looked at again, but + /// not for ever: memory that is shown and cannot be read ends it, and a + /// filling that got everything starts the count anew. + #[test] + fn a_short_filling_is_looked_at_again_a_few_times() { + // An address no other test names. + let start = 0x7fee_1234_0000u64; + let pending = || super::SHORT.lock().unwrap().0.remove(&start); + for _ in 0..super::SHORT_IN_A_ROW { + super::read_short(start); + assert!(pending()); + } + super::read_short(start); + assert!(!pending()); + super::read_all(start); + super::read_short(start); + assert!(pending()); + super::read_all(start); + } + /// A null texture UAV keeps the title's dimension (3D for the world's /// wind field), and is 2D when the title names none. #[test] diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index ad4ab4c..599c08d 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1960,6 +1960,7 @@ impl State { // Slots whose texture's memory the runtime mapped, unmapped or // wrote since the last pass are due again. host.texture_slots_remapped(frame); + host.texture_slots_short(frame); // Levels on demand: the slots of textures whose first level with // memory changed since the last pass are made again from it. host.texture_views_remade(); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index af643ba..2ae863c 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -704,6 +704,41 @@ pub(crate) fn warp_adapter() -> windows::core::Result { #[cfg(test)] mod tests { + /// What is there of a range some of whose pages are not: those bytes, + /// counted, and zeros for the rest, whatever the buffer held. + #[test] + fn what_is_there_is_read_and_the_rest_is_zeros() { + use windows_sys::Win32::System::Memory::*; + const SIZE: usize = 0x8_0000; + // SAFETY: a reservation of ours; only committed pages are written. + unsafe { + let at = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::(); + assert!(!at.is_null()); + // 0-0x1_1000 and 0x3_0000-0x4_0000 are there. + for (from, len) in [(0, 0x1_1000), (0x3_0000, 0x1_0000)] { + assert!(!VirtualAlloc(at.add(from).cast(), len, MEM_COMMIT, PAGE_READWRITE).is_null()); + at.add(from).write_bytes(0x5a, len); + } + // From an address inside a page, as textures are packed. + let mut out = vec![0x77u8; SIZE - 0x300]; + assert_eq!(super::read_there(at.add(0x300), &mut out), 0x1_1000 - 0x300 + 0x1_0000); + for (i, &b) in out.iter().enumerate() { + let from = i + 0x300; + let there = from < 0x1_1000 || (0x3_0000..0x4_0000).contains(&from); + assert_eq!(b, if there { 0x5a } else { 0 }, "byte {from:#x}"); + } + // All there: one read. + let mut out = vec![0x77u8; 0x1_0000]; + assert_eq!(super::read_there(at.add(0x1000), &mut out), 0x1_0000); + assert!(out.iter().all(|&b| b == 0x5a)); + // Nothing there. + let mut out = vec![0x77u8; 0x1_0000]; + assert_eq!(super::read_there(at.add(0x5_0000), &mut out), 0); + assert!(out.iter().all(|&b| b == 0)); + assert_ne!(VirtualFree(at.cast(), 0, MEM_RELEASE), 0); + } + } + /// Zeros for a title destination that went meanwhile are no fault. #[test] fn zeros_where_nothing_is_are_lost() { @@ -6761,6 +6796,47 @@ pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool { read(src, dst.as_mut_ptr(), dst.len()) } +/// Reads what is there of the `dst.len()` bytes of title memory at `src`, +/// zeros for the rest; returns how many bytes were there. Safe while the +/// runtime remaps title memory (the kernel, or a copy that takes the fault, +/// reads). What the runtime's record says is mapped is read in one go each, +/// and by pieces where that fails; memory it has no record of by pieces. +pub(crate) fn read_there(src: *const u8, dst: &mut [u8]) -> usize { + dst.fill(0); + let (start, len) = (src as usize, dst.len()); + let mut got = 0; + let mut runs = crate::inplace::shown_runs(start, len); + if runs.is_empty() { + runs.push((start, len)); + } + for (at, n) in runs { + let piece = &mut dst[at - start..at - start + n]; + if read_into(at as *const u8, piece) { + got += n; + continue; + } + // (What failed may have written its first pages.) + piece.fill(0); + for_pieces(at, n, 64 << 10, |from, n| { + let piece = &mut dst[from - start..from - start + n]; + if read_into(from as *const u8, piece) { + got += n; + return; + } + piece.fill(0); + for_pieces(from, n, 4 << 10, |from, n| { + let piece = &mut dst[from - start..from - start + n]; + if read_into(from as *const u8, piece) { + got += n; + } else { + piece.fill(0); + } + }); + }); + } + got +} + /// Copies `len` bytes from `src` to `dst` unless a source page is not /// readable. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool { @@ -7079,11 +7155,14 @@ impl Meter { hold still (the runtime remapping it); the rest is reading, hashing and detiling" ); } - let [through, left] = [0, 1].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames); - if through + left > 0.0 { + let [through, left, filled, short] = + [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames); + if through + left + filled > 0.0 { tracing::info!( "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \ - {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there)" + {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there), \ + {filled:.1} first fillings from the pages there (VICTORY_TEXTURE_FILL=0: left empty), {short:.1} of them \ + with less than was mapped (looked at again)" ); } } diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 5bb24b7..82275c9 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -462,6 +462,28 @@ pub(crate) fn shown_bytes(at: usize, len: usize) -> Option { any.then_some(there) } +/// What of `[at, at + len)` views of physical pages show, in order, pieces +/// that touch as one: (address, bytes). Empty: nothing, or memory of another +/// kind. +pub(crate) fn shown_runs(at: usize, len: usize) -> Vec<(usize, usize)> { + let end = at.saturating_add(len); + let v = views(); + let first = v.views.range(..=at).next_back(); + let rest = v.views.range(at.saturating_add(1)..end.max(at.saturating_add(1))); + let mut runs: Vec<(usize, usize)> = Vec::new(); + for (&base, view) in first.into_iter().chain(rest) { + let (from, to) = (base.max(at), base.saturating_add(view.0).min(end)); + if from >= to { + continue; + } + match runs.last_mut() { + Some((run, bytes)) if *run + *bytes == from => *bytes += to - from, + _ => runs.push((from, to - from)), + } + } + runs +} + /// How the views cover `[at, at + len)`. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub(crate) enum Cover { @@ -1222,8 +1244,15 @@ mod tests { assert_eq!(shown(5 * K64 + 1, 10), Some(10)); assert_eq!(shown(2 * K64, 2 * K64), None); assert_eq!(shown(6 * K64, 2 * K64), None); + // The same as runs: views that touch are one, cut to the range. + let runs = |from: usize, len: usize| super::shown_runs(at + from, len); + assert_eq!(runs(0, 8 * K64), vec![(at, 2 * K64), (at + 4 * K64, 2 * K64)]); + assert_eq!(runs(100, K64), vec![(at + 100, K64)]); + assert_eq!(runs(5 * K64 + 1, 10), vec![(at + 5 * K64 + 1, 10)]); + assert_eq!(runs(2 * K64, 2 * K64), vec![]); super::views_gone(at + K64, K64); assert_eq!(shown(0, 2 * K64), Some(K64 as u64)); + assert_eq!(runs(0, 2 * K64), vec![(at, K64)]); super::views_gone(at, 8 * K64); assert_eq!(shown(0, 8 * K64), None); } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 1f4ee6b..56f2726 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -61,6 +61,9 @@ pub(crate) struct Staging { uploaded: std::sync::atomic::AtomicBool, /// When a list last recorded a use of it (`crate::host::moment`). used: std::sync::atomic::AtomicU64, + /// How many bytes of the texture's memory were mapped when a list last + /// recorded an upload of it ([`fill_unlocked`]; 0: not asked). + expected: std::sync::atomic::AtomicU64, /// Levels on demand (`crate::tiles`): the texture's host copy was made /// without memory of its own when the staging buffer was made. on_demand: bool, @@ -344,16 +347,38 @@ pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool { /// through the kernel costs about 0.6 ms a megabyte against 0.3 in place. /// /// What changes for the picture: a texture that arrives while the runtime -/// is remapping may show a frame later. It never shows partly read. +/// is remapping may show a frame later. A staging buffer that holds nothing +/// yet is filled with what is there all the same ([`fill_unlocked`]): a list +/// has recorded the upload from it by then. fn no_wait() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_NO_WAIT").is_some_and(|v| v == "1")) } +/// Whether a refresh that does not wait ([`no_wait`]) and finds a page +/// missing fills a staging buffer that was never filled from the pages that +/// are there (`VICTORY_TEXTURE_FILL=0`: it was left as it was made). +/// +/// Left for the next refresh, it was uploaded as it was: the upload is +/// recorded before the refresh, and a texture picked by index has no next +/// refresh (its staging buffer goes with the upload). A texture the title +/// holds only the smaller levels of is never all there, so whenever the +/// runtime was remapping at that moment, its levels became zeros on the +/// card, good ones too: of 16,135 textures a recorded frame's slots show, +/// 2,382 had zeros in the first level shown; 137 of that frame's 787 repeated +/// uploads put zeros over a filled level (run pic1-1; 68,700 refreshes left +/// in the 150 s of world of run play1). +fn fill_unlocked() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_FILL").is_none_or(|v| v != "0")) +} + /// Since the last frame-rate line, with [`no_wait`]: refreshes that read /// through the kernel because title memory was being remapped, and those -/// left for the next refresh because a page was not there. -pub(crate) static UNLOCKED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +/// left for the next refresh because a page was not there; staging buffers +/// filled from the pages there ([`fill_unlocked`]), and of them those that +/// got less than was mapped (their slots are looked at again). +pub(crate) static UNLOCKED: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; /// Since the last frame-rate line, of texture refreshes on every thread, in /// microseconds: waiting for the texture's own lock (another thread is @@ -658,6 +683,10 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexUploads, 1); + if no_wait() && fill_unlocked() { + let there = mapped_bytes(staging.memory, staging.layout.size as usize); + staging.expected.store(there, Relaxed); + } const COPY_DEST: u32 = 0x400; // A texture cut from a block may lie where another did: what the card // holds of that one is done with before the first upload into this one. @@ -1115,10 +1144,11 @@ impl Staging { /// A refresh while the runtime is remapping title memory ([`no_wait`]): /// the texture is read through the kernel, which fails if a page of it - /// is not there at this moment. Then nothing is taken and the texture - /// is looked at again at its next refresh (what was learnt about writes - /// to it is forgotten, so that it is not passed over as unwritten). - /// Returns the bytes read. + /// is not there at this moment. Then a staging buffer that was filled + /// before keeps what it holds and the texture is looked at again at its + /// next refresh (what was learnt about writes to it is forgotten, so + /// that it is not passed over as unwritten); one never filled takes the + /// pages that are there ([`Staging::fill`]). Returns the bytes read. fn refresh_unlocked(&self, last: &mut Last, size: usize) -> usize { use std::sync::atomic::Ordering::Relaxed; let read = with_read(size, |read| { @@ -1135,6 +1165,8 @@ impl Staging { if read { UNLOCKED[0].fetch_add(1, Relaxed); size + } else if last.hash.is_none() && fill_unlocked() { + self.fill(last, size) } else { UNLOCKED[1].fetch_add(1, Relaxed); last.asked = 0; @@ -1142,6 +1174,46 @@ impl Staging { } } + /// The first filling of the staging buffer while the runtime is + /// remapping title memory, of a texture not all of which can be read: + /// with the pages that are there, zeros for the others, as a partly + /// mapped texture is filled under the lock. Pages that are away only + /// for the moment of a change (the runtime unmaps the rest of a view to + /// change one page of it) are read when that change is over. If less + /// was read than was mapped when the upload was recorded, or is mapped + /// now, the texture's slots are looked at again. + fn fill(&self, last: &mut Last, size: usize) -> usize { + use std::sync::atomic::Ordering::Relaxed; + let start = self.memory as u64; + let mut there = 0; + let got = with_read(size, |read| { + let mut got = 0; + for _ in 0..4 { + got = crate::host::read_there(self.memory, read) as u64; + crate::watch::change_over(); + there = mapped_bytes(self.memory, size); + if got >= there { + break; + } + } + if got != 0 { + last.hash = Some(blake3::hash(read)); + self.detile(read); + } + got + }); + last.partial = Some(crate::frame::current()); + UNLOCKED[2].fetch_add(1, Relaxed); + if got < there.max(self.expected.load(Relaxed)) { + UNLOCKED[3].fetch_add(1, Relaxed); + last.asked = 0; + crate::descriptor::host::read_short(start); + } else { + crate::descriptor::host::read_all(start); + } + size + } + /// Detiles `tiled` (the texture's memory) into the staging buffer. fn detile(&self, tiled: &[u8]) { self.dirty.store(true, std::sync::atomic::Ordering::Relaxed); @@ -1512,6 +1584,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { dirty: std::sync::atomic::AtomicBool::new(true), uploaded: std::sync::atomic::AtomicBool::new(false), used: std::sync::atomic::AtomicU64::new(crate::host::moment()), + expected: std::sync::atomic::AtomicU64::new(0), on_demand, detiled: std::sync::atomic::AtomicU32::new(0), judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2], diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index fdd8ad6..e577459 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -1596,6 +1596,22 @@ pub(crate) fn again_after_change(since: u64, mut f: impl FnMut() -> bool) -> boo false } +/// Returns when the change of a mapping that is under way, if one is, is +/// over (or has been going on for 2 ms): pages it took away for its moment +/// are back. Another may have begun. +pub(crate) fn change_over() { + let now = changes(); + if now.is_multiple_of(2) { + return; + } + let started = std::time::Instant::now(); + while changes() == now && started.elapsed().as_millis() < 2 { + for _ in 0..50 { + std::hint::spin_loop(); + } + } +} + /// [`changes`], when no change is under way (or one has been for a second). fn change_done() -> u64 { let mut tries = 0; From 9e1014d4986291aead744351628904ae5d9c9d6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9rez?= Date: Tue, 24 Nov 2026 00:50:24 +0100 Subject: [PATCH 204/445] GPU: hold SHADER_HEAPS across descriptor mirror and check query offsets mirror() previously dropped the SHADER_HEAPS lock inside shader_slot() before using the returned &Heap, allowing a concurrent Heap::drop to free the heap while mirror() accessed it. Also guards copy_simple() against invalid descriptor kinds, rejects placed heaps whose address+size wraps u64, and checks offset+count*bytes in resolve_queries() against overflow (with a regression test). (cherry picked from commit 628b95da5e738046d00995743e07137e48936ba6) --- crates/victory-gpu/src/descriptor.rs | 34 ++++++++++++++----------- crates/victory-gpu/src/list.rs | 29 +++++++++++++++++++++- crates/victory-gpu/src/resource.rs | 37 ++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+), 16 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 3485f89..5f6ab90 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -128,23 +128,22 @@ const SHADER_VISIBLE: u32 = 1; #[cfg(windows)] static SHADER_HEAPS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); -/// The shader-visible heap holding `handle`, and the descriptor's index. -#[cfg(windows)] -fn shader_slot<'a>(handle: u64) -> Option<(&'a Heap, u32)> { - let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); - let &(_, _, at) = heaps - .iter() - .find(|&&(start, end, _)| (start..end).contains(&handle))?; - // SAFETY: registered heaps are live (removed when dropped). - let heap = unsafe { &*(at as *const Heap) }; - Some((heap, heap.index(handle)?)) -} - /// Makes the host descriptor for what the title wrote at `handle`, if it -/// is in a shader-visible heap. +/// is in a shader-visible heap. Keeps `SHADER_HEAPS` locked for the duration +/// so `Heap::drop` cannot free the heap concurrently. #[cfg(windows)] fn mirror(handle: u64) { - let Some((heap, index)) = shader_slot(handle) else { + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let Some(&(_, _, at)) = heaps + .iter() + .find(|&&(start, end, _)| (start..end).contains(&handle)) + else { + return; + }; + // SAFETY: registered heaps stay alive until `Heap::drop`, which takes + // the `SHADER_HEAPS` lock we hold here. + let heap = unsafe { &*(at as *const Heap) }; + let Some(index) = heap.index(handle) else { return; }; let mut pending = heap.pending.lock().unwrap_or_else(|e| e.into_inner()); @@ -977,7 +976,9 @@ pub(crate) extern "system" fn create_sampler_x(_: This, desc: *const [u32; 27], /// Device method: `count` descriptors of `kind` from `src` to `dst`. pub(crate) extern "system" fn copy_simple(_: This, count: u32, dst: u64, src: u64, kind: u32) { - let step = u64::from(increment(kind).unwrap_or(0)); + let Some(step) = increment(kind).map(u64::from) else { + return; + }; let len = u64::from(count) * step; if dst != 0 && src != 0 { // SAFETY: both ranges are descriptor slots the title owns. @@ -1084,6 +1085,9 @@ pub(crate) extern "system" fn create_heap( let placed = placement.address != 0 && placement.size == size; tracing::debug!(?desc, placed, "descriptor heap"); let (start, memory) = if placed { + if placement.address.checked_add(size).is_none() { + return E_INVALIDARG; + } (placement.address, None) } else { match Memory::zeroed(size, 64) { diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 1eae1dd..5a9680e 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1372,7 +1372,10 @@ extern "system" fn resolve_queries( PIPELINE_STATISTICS => (Written::Value(0), 88), _ => (Written::Value(0), 16), }; - if offset + u64::from(count) * bytes > size { + let Some(end) = offset.checked_add(u64::from(count) * bytes) else { + return; + }; + if end > size { return; } for i in 0..u64::from(count) { @@ -2257,4 +2260,28 @@ mod tests { assert_eq!(release(list), 0); assert_eq!(release(allocator), 0); } + + /// An offset near `u64::MAX` must not overflow and write outside the + /// query destination buffer. + #[test] + fn resolve_queries_rejects_overflowing_offset() { + let null = std::ptr::null(); + let mut allocator = null; + assert_eq!( + create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), + S_OK + ); + let mut list = null; + assert_eq!( + create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), + S_OK + ); + let buffer = crate::resource::test_buffer(64); + // Used to overflow `offset + count * 8` (panic in debug, wrap in release). + resolve_queries(list, null, 0, 0, 2, buffer, u64::MAX - 8); + let release = |o: This| slot:: u32>(o, 0x10)(o); + for object in [buffer, list, allocator] { + assert_eq!(release(object), 0); + } + } } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 35b7c70..db3621e 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -2856,6 +2856,43 @@ static RESOURCE_FUNCTIONS: Table<32> = { Table(f) }; +#[cfg(test)] +pub(crate) fn test_buffer(width: u64) -> This { + let heap = HeapProperties { + kind: 1, + cpu_pages: 0, + pool: 0, + creation_nodes: 0, + visible_nodes: 0, + }; + let desc = ResourceDesc { + dimension: BUFFER, + alignment: 0, + width, + height: 1, + depth_or_array_size: 1, + mip_levels: 1, + format: 0, + sample_count: 1, + sample_quality: 0, + layout: 1, + flags: 0, + }; + let mut out = std::ptr::null(); + let hr = create_committed( + std::ptr::null(), + &heap, + 0, + &desc, + 0, + std::ptr::null(), + &RESOURCE_IIDS[0], + &mut out, + ); + assert_eq!(hr, S_OK); + out +} + #[cfg(test)] mod tests { use super::*; From 32f970ca6e9a275a329c8543be4616bf6d1a56c2 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 01:26:32 +0100 Subject: [PATCH 205/445] xma: start the frame after a continuation at the next packet that has frames A frame that ends in a packet where no frame begins (the tail of a frame that crossed packets, then padding) left the next frame pointing into that padding, which ended the stream early. Now the next frame is found by following each packet's skip to the next packet with frames. (cherry picked from commit ba42db643c15c1b7fb17ba40464dddda36c1db60) --- crates/victory-formats/src/xma.rs | 47 ++++++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs index e6ca931..a8ea48c 100644 --- a/crates/victory-formats/src/xma.rs +++ b/crates/victory-formats/src/xma.rs @@ -149,10 +149,20 @@ fn next_frame(data: &[u8], start: usize, end: usize) -> Option { } let last = number + 1 >= header.frames; let mut end = end; - if end.is_multiple_of(PACKET_BITS) || (last && end / PACKET_BITS == index) { - // The next frame begins in the next packet of this stream. - let next = (end - 1) / PACKET_BITS + 1 + packet(data, (end - 1) / PACKET_BITS)?.skip as usize; - let header = packet(data, next)?; + // A frame that ends in a packet where no frame begins (the tail of a frame + // that crossed packets, then padding) is the last one before the next + // packet that has frames. + let ends_in_packet_without_frames = + end / PACKET_BITS != index && !end.is_multiple_of(PACKET_BITS) && packet(data, end / PACKET_BITS)?.frames == 0; + if end.is_multiple_of(PACKET_BITS) || (last && end / PACKET_BITS == index) || ends_in_packet_without_frames { + // The next frame begins in the next packet of this stream that has one; + // a packet with none (a frame spans all of it) holds no start. + let mut next = (end - 1) / PACKET_BITS + 1 + packet(data, (end - 1) / PACKET_BITS)?.skip as usize; + let mut header = packet(data, next)?; + while header.frames == 0 { + next += 1 + header.skip as usize; + header = packet(data, next)?; + } end = next * PACKET_BITS + HEADER_BITS + header.first_frame_bit as usize; } (end / 8 < data.len()).then_some(end) @@ -1047,6 +1057,35 @@ mod tests { assert_eq!(frame.next, None); } + /// A frame that crosses a packet where no frame begins (a full + /// continuation) and ends in another such packet, followed by padding: the + /// next frame is the first one of the next packet that has frames, not the + /// padding the frame ended in. + #[test] + fn the_frame_after_continuation_packets_starts_in_the_next_packet_with_frames() { + let mut data = vec![0u8; 4 * PACKET_BYTES]; + let header = |frames: u32, first: u32| (frames << 26) | (first << 11); + put_bits(&mut data, 0, 32, header(2, 0)); + // Packet 1 is all of one frame; packet 2 holds only its last 64 bits. + put_bits(&mut data, PACKET_BITS, 32, header(0, 0x7fff)); + put_bits(&mut data, 2 * PACKET_BITS, 32, header(0, 64)); + put_bits(&mut data, 3 * PACKET_BITS, 32, header(1, 0)); + // A first frame of 16000 bits, then one from the end of its payload + // through packets 1 and 2. + let second = HEADER_BITS + 16000; + put_bits(&mut data, HEADER_BITS, LENGTH_BITS, 16000); + let tail = PACKET_BITS - second; + let bits = tail + (PACKET_BITS - HEADER_BITS) + 64; + put_bits(&mut data, second, LENGTH_BITS, bits as u32); + put_bits(&mut data, 3 * PACKET_BITS + HEADER_BITS, LENGTH_BITS, 100); + let first = read_frame(&data, HEADER_BITS).unwrap(); + assert_eq!(first.next, Some(second)); + let frame = read_frame(&data, second).unwrap(); + assert_eq!(frame.bits, bits); + assert_eq!(frame.next, Some(3 * PACKET_BITS + HEADER_BITS)); + assert_eq!(read_frame(&data, 3 * PACKET_BITS + HEADER_BITS).unwrap().next, None); + } + /// The direct sum `imdct_half` stands for (FFmpeg's naive inverse MDCT: /// the standard formula, negated). fn imdct_reference(input: &[f32]) -> Vec { From 6b9035c375c52630eba85a5aeea052eb757d579d Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:35:58 +0100 Subject: [PATCH 206/445] XAsync: end the call that finished, not whatever call the block holds now Our own completions looked their call up again by block address: after a provider's DoWork returned, after a cancel, after a failed begin, and when queued DoWork ran. A provider usually ends its call itself (XAsyncComplete from DoWork or Cancel), and once it has, the title may begin a new call on the same block, from its completion routine or from a thread that polls the status. The lookup then found that new call: - the old call's DoWork result (S_OK, size 0) or cancel (E_ABORT) ended the new call before it had done anything, ran its cleanup and fired the completion routine a second time; - DoWork still queued for a canceled call ran the new call's DoWork. Each queued DoWork now carries the call that scheduled it and runs only while that call is still the block's, and DoWork, cancel and begin complete that call. A call that is already over ignores a second complete, so nothing reaches the next call. XAsyncComplete itself still goes by block, as providers name their call by its block. (cherry picked from commit d01b17070dbf5f181e327ee540510cec73facbe9) --- crates/victory-hle/src/modules/xasync.rs | 169 +++++++++++++++++++++-- 1 file changed, 155 insertions(+), 14 deletions(-) diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index 068d75f..ab17be9 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -501,6 +501,14 @@ fn call(block: *mut AsyncBlock) -> Option> { lock(&CALLS).get(&(block as usize)).cloned() } +/// Whether `call` is still the call in flight on `block`: once it is over, +/// the title may begin another call on the same block. +fn is_current(call: &Arc, block: *mut AsyncBlock) -> bool { + lock(&CALLS) + .get(&(block as usize)) + .is_some_and(|current| Arc::ptr_eq(current, call)) +} + /// The block's status and result-size words. fn words(block: *mut AsyncBlock) -> (&'static AtomicUsize, &'static AtomicUsize) { // SAFETY: the title's block outlives the call; its system area is ours. @@ -549,39 +557,66 @@ pub fn XAsyncBegin( // A failed begin fails the call, so the completion routine still runs. let hr = call.provider(OP_BEGIN, block, 0, std::ptr::null_mut()); if hr < 0 { - XAsyncComplete(block, hr, 0); + complete_call(&call, block, hr, 0); } S_OK } -/// Queues the provider's `DoWork` on the block's work port. +/// Queues the provider's `DoWork` on the block's work port. The work +/// belongs to the call that scheduled it: when it runs, that call may be +/// over and the block may hold another. pub fn XAsyncSchedule(block: *mut AsyncBlock, delay_ms: u32) -> HRESULT { - extern "system" fn work(block: *mut c_void, canceled: bool) { - let block = block.cast::(); - let Some(call) = call(block) else { return }; + struct Work { + call: Arc, + block: *mut AsyncBlock, + } + extern "system" fn work(context: *mut c_void, canceled: bool) { + // SAFETY: boxed in `XAsyncSchedule`; a task runs once. + let Work { call, block } = *unsafe { Box::from_raw(context.cast::()) }; + if !is_current(&call, block) { + return; + } let hr = if canceled { E_ABORT } else { call.provider(OP_DO_WORK, block, 0, std::ptr::null_mut()) }; - if hr != E_PENDING { - XAsyncComplete(block, hr, 0); - } + complete_call(&call, block, hr, 0); } - if block.is_null() || call(block).is_none() { + if block.is_null() { return E_INVALIDARG; } + let Some(call) = call(block) else { + return E_INVALIDARG; + }; // SAFETY: a block in flight is valid. let handle = unsafe { (*block).queue }; - match queue(handle) { - Some(queue) => queue.submit(WORK, delay_ms, Task::new(block.cast(), work)), - None => E_INVALIDARG, + let Some(queue) = queue(handle) else { + return E_INVALIDARG; + }; + let context = Box::into_raw(Box::new(Work { call, block })); + let hr = queue.submit(WORK, delay_ms, Task::new(context.cast(), work)); + if hr < 0 { + // Refused, so the task never runs. + // SAFETY: still ours. + drop(unsafe { Box::from_raw(context) }); } + hr } /// Records the result (the first one wins), wakes waiters and queues the /// completion routine on the block's completion port. pub fn XAsyncComplete(block: *mut AsyncBlock, result: HRESULT, required_size: usize) { + if let Some(call) = call(block) { + complete_call(&call, block, result, required_size); + } +} + +/// [`XAsyncComplete`] for `call`, which is or was in flight on `block`. Our +/// own completions name the call they belong to, not the block: if the +/// provider already completed it, the title may have begun another call on +/// the block, which a second complete by block would end. +fn complete_call(call: &Call, block: *mut AsyncBlock, result: HRESULT, required_size: usize) { extern "system" fn complete(block: *mut c_void, _canceled: bool) { let block = block.cast::(); // SAFETY: read before the status was published; see below. @@ -589,7 +624,6 @@ pub fn XAsyncComplete(block: *mut AsyncBlock, result: HRESULT, required_size: us routine(block); } } - let Some(call) = call(block) else { return }; if result == E_PENDING { return; } @@ -649,7 +683,7 @@ pub fn XAsyncGetResultSize(block: *mut AsyncBlock, out: *mut usize) -> HRESULT { pub fn XAsyncCancel(block: *mut AsyncBlock) { if let Some(call) = call(block) { call.provider(OP_CANCEL, block, 0, std::ptr::null_mut()); - XAsyncComplete(block, E_ABORT, 0); + complete_call(&call, block, E_ABORT, 0); } } @@ -1134,6 +1168,113 @@ mod tests { XTaskQueueCloseHandle(q); } + /// What a test sees of a block that a title reuses: its completion + /// routine begins the next call on the same block. + #[derive(Default)] + struct Reuse { + completions: AtomicU32, + next_begun: AtomicBool, + next_worked: AtomicBool, + } + + /// A block whose completion routine is [`begin_next`]. + fn reused_block(queue: *const Queue, reuse: &Reuse) -> AsyncBlock { + AsyncBlock { + queue, + context: std::ptr::from_ref(reuse).cast_mut().cast(), + callback: Some(begin_next), + internal: [0; 4], + } + } + + /// Begins a call without an identity. + fn begin(block: *mut AsyncBlock, context: *mut c_void, provider: Provider) -> HRESULT { + let none = std::ptr::null(); + XAsyncBegin(block, context, none, none.cast(), Some(provider)) + } + + /// Begins the next call on the block the first time a call completes, + /// as a title that keeps one block for repeated calls does. + extern "system" fn begin_next(block: *mut AsyncBlock) { + // SAFETY: the block is from `reused_block`, its `Reuse` still alive. + let context = unsafe { (*block).context }; + // SAFETY: as above. + let reuse = unsafe { &*context.cast::() }; + if reuse.completions.fetch_add(1, Ordering::SeqCst) == 0 { + let hr = begin(block, context, next_call); + reuse.next_begun.store(hr == S_OK, Ordering::SeqCst); + } + } + + /// The next call's provider: it never ends on its own, and notes being + /// asked to work. + extern "system" fn next_call(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data; its context is + // the test's `Reuse`. + let reuse = unsafe { &*(*data).context.cast::() }; + if op == OP_DO_WORK { + reuse.next_worked.store(true, Ordering::SeqCst); + return E_PENDING; + } + S_OK + } + + /// A provider that ends its call itself, in `DoWork` and on cancel, then + /// returns `S_OK`, as providers do. + extern "system" fn ends_itself(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data. + let block = unsafe { (*data).block }; + match op { + OP_DO_WORK => XAsyncComplete(block, S_OK, 0), + OP_CANCEL => XAsyncComplete(block, E_ABORT, 0), + _ => {} + } + S_OK + } + + #[test] + fn a_finished_calls_work_result_leaves_the_next_call_alone() { + let mut q = std::ptr::null(); + // Work dispatched by hand; completion routines run where the call + // completes, inside the provider's `DoWork`. + assert_eq!(XTaskQueueCreate(0, 3, &mut q), S_OK); + let reuse = Reuse::default(); + let mut block = reused_block(q, &reuse); + assert_eq!(begin(&mut block, std::ptr::null_mut(), ends_itself), S_OK); + assert_eq!(XAsyncSchedule(&mut block, 0), S_OK); + assert!(XTaskQueueDispatch(q, WORK, 0)); + assert!(reuse.next_begun.load(Ordering::SeqCst)); + assert_eq!(XAsyncGetStatus(&mut block, false), E_PENDING); + assert_eq!(reuse.completions.load(Ordering::SeqCst), 1); + + XAsyncCancel(&mut block); + assert_eq!(XAsyncGetStatus(&mut block, false), E_ABORT); + XTaskQueueCloseHandle(q); + } + + #[test] + fn a_canceled_call_leaves_the_next_call_alone() { + let mut q = std::ptr::null(); + assert_eq!(XTaskQueueCreate(0, 3, &mut q), S_OK); + let reuse = Reuse::default(); + let mut block = reused_block(q, &reuse); + assert_eq!(begin(&mut block, std::ptr::null_mut(), ends_itself), S_OK); + assert_eq!(XAsyncSchedule(&mut block, 0), S_OK); + // The provider ends the call on cancel, before its work has run. + XAsyncCancel(&mut block); + assert!(reuse.next_begun.load(Ordering::SeqCst)); + assert_eq!(XAsyncGetStatus(&mut block, false), E_PENDING); + // The canceled call's work is still queued; it runs nothing now. + assert!(XTaskQueueDispatch(q, WORK, 0)); + assert!(!reuse.next_worked.load(Ordering::SeqCst)); + assert_eq!(XAsyncGetStatus(&mut block, false), E_PENDING); + assert_eq!(reuse.completions.load(Ordering::SeqCst), 1); + + XAsyncCancel(&mut block); + assert_eq!(XAsyncGetStatus(&mut block, false), E_ABORT); + XTaskQueueCloseHandle(q); + } + #[test] fn a_nonnegative_completion_still_returns_its_payload() { const S_FALSE: HRESULT = 1; From cd6c15fe4ab48143a1467ebe3ad49ae49b6950e9 Mon Sep 17 00:00:00 2001 From: Bloxive Date: Mon, 23 Nov 2026 20:38:21 -0400 Subject: [PATCH 207/445] Census: report directory traversal failures Fail when a requested scan root cannot be opened. Report traversal errors below a readable root alongside the other skipped inputs. (cherry picked from commit b1bdd8994a456755255b1e096f641ef47ff719c9) --- apps/victory/src/census.rs | 23 +++++++++++++++-------- apps/victory/tests/census.rs | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 8 deletions(-) create mode 100644 apps/victory/tests/census.rs diff --git a/apps/victory/src/census.rs b/apps/victory/src/census.rs index 9398719..59ec2b7 100644 --- a/apps/victory/src/census.rs +++ b/apps/victory/src/census.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::io::Read; use std::path::{Path, PathBuf}; -use anyhow::Result; +use anyhow::{Context, Result}; use victory_hle::{HleResolver, HostPolicy}; use victory_loader::Provenance; use victory_pe::{ImageInfo, ImportSymbol}; @@ -32,10 +32,17 @@ pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> let mut missing: BTreeMap<(String, String), BTreeSet> = BTreeMap::new(); for root in &paths { - for entry in walkdir::WalkDir::new(root) - .into_iter() - .filter_map(Result::ok) - { + for entry in walkdir::WalkDir::new(root) { + let entry = match entry { + Ok(entry) => entry, + Err(error) if error.depth() == 0 => { + return Err(error).context("cannot scan census input"); + } + Err(error) => { + failed.push(error.to_string()); + continue; + } + }; let path = entry.path(); if !entry.file_type().is_file() || !looks_like_pe(path) { continue; @@ -46,7 +53,7 @@ pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> { Ok(info) => info, Err(e) => { - failed.push((path.to_path_buf(), e.to_string())); + failed.push(format!("{}: {e}", path.display())); continue; } }; @@ -78,8 +85,8 @@ pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> } println!("{images} images scanned, {} unreadable", failed.len()); - for (p, e) in &failed { - println!(" skipped {}: {e}", p.display()); + for error in &failed { + println!(" skipped {error}"); } println!( "\n{:<56} {:>6} {:>6} {:>6} {:>8} {:>7}", diff --git a/apps/victory/tests/census.rs b/apps/victory/tests/census.rs new file mode 100644 index 0000000..8a2bdae --- /dev/null +++ b/apps/victory/tests/census.rs @@ -0,0 +1,34 @@ +use std::path::Path; +use std::process::Command; + +#[test] +fn census_fails_when_a_requested_path_is_missing() { + let valid = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml"); + let missing = valid.with_extension("missing-census-input"); + assert!(!missing.exists()); + + let output = Command::new(env!("CARGO_BIN_EXE_victory")) + .arg("census") + .args([&valid, &missing]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + !output.status.success(), + "census succeeded: {}", + String::from_utf8_lossy(&output.stdout) + ); + assert!(stderr.contains("Cargo.missing-census-input"), "{stderr}"); +} + +#[test] +fn census_accepts_a_valid_path_with_no_pe_images() { + let valid = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml"); + let output = Command::new(env!("CARGO_BIN_EXE_victory")) + .arg("census") + .arg(valid) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + assert!(String::from_utf8_lossy(&output.stdout).contains("0 images scanned, 0 unreadable")); +} From 37e07605f81cd5d9eaa6770af912c4519efe1d04 Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:42:42 +0100 Subject: [PATCH 208/445] XTaskQueue: terminating a queue cancels its delayed callbacks too A callback submitted with a delay waited on a thread of its own and was delivered when the delay ran out, whether or not the queue had been terminated meanwhile. XTaskQueueTerminate only canceled what was already in the ports, so a pending delayed callback was not canceled: it ran later as live work (canceled = false), after the termination callback, by which time a title may have freed what the callback uses. The queue now keeps its delayed callbacks in a list until their delay runs out. Terminate cancels them along with the queued ones, before it calls the termination callback, and a delay that runs out after that finds nothing to deliver. A submit racing Terminate checks `terminated` under the list's lock, so the callback is either canceled or refused. (cherry picked from commit b9ff219826e61ba6306f6a1378b613319f70da47) --- crates/victory-hle/src/modules/xasync.rs | 63 ++++++++++++++++++++---- 1 file changed, 54 insertions(+), 9 deletions(-) diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index ab17be9..04fbe08 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -10,7 +10,7 @@ #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] -use std::collections::{HashMap, VecDeque}; +use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ffi::c_void; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard}; @@ -196,6 +196,9 @@ pub struct Queue { ports: [Arc; 2], monitors: Mutex>, terminated: AtomicBool, + /// Delayed callbacks still waiting out their delay, in submission + /// order: terminating the queue cancels them with the queued ones. + delayed: Mutex>, } impl Queue { @@ -204,10 +207,12 @@ impl Queue { ports, monitors: Mutex::default(), terminated: AtomicBool::new(false), + delayed: Mutex::default(), }) } fn submit(self: &Arc, port: u32, delay_ms: u32, task: Task) -> HRESULT { + static NEXT_DELAYED: AtomicU64 = AtomicU64::new(0); if port > COMPLETION { return E_INVALIDARG; } @@ -216,13 +221,27 @@ impl Queue { } if delay_ms == 0 { self.deliver(port, task); - } else { - let queue = self.clone(); - std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(delay_ms.into())); - queue.deliver(port, task); - }); + return S_OK; } + let id = NEXT_DELAYED.fetch_add(1, Ordering::Relaxed); + { + // Checked again under the lock termination drains: the callback + // is either canceled with the others or refused. + let mut delayed = lock(&self.delayed); + if self.terminated.load(Ordering::Acquire) { + return E_ABORT; + } + delayed.insert(id, task); + } + let queue = self.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(delay_ms.into())); + // Gone if the queue was terminated meanwhile, which canceled it. + let task = lock(&queue.delayed).remove(&id); + if let Some(task) = task { + queue.deliver(port, task); + } + }); S_OK } @@ -369,8 +388,8 @@ pub fn XTaskQueueSubmitDelayedCallback( } } -/// Cancels what is still queued (callbacks see `canceled`), refuses new -/// work, then calls `callback`. +/// Cancels what is still queued or waiting out a delay (callbacks see +/// `canceled`), refuses new work, then calls `callback`. pub fn XTaskQueueTerminate( handle: *const Queue, _wait: bool, @@ -391,6 +410,10 @@ pub fn XTaskQueueTerminate( task.run(true); } } + let delayed = std::mem::take(&mut *lock(&queue.delayed)); + for task in delayed.into_values() { + task.run(true); + } if let Some(callback) = callback { callback(context); } @@ -1475,4 +1498,26 @@ mod tests { ); XTaskQueueCloseHandle(q); } + + #[test] + fn terminate_cancels_delayed_callbacks() { + static EVENTS: Mutex> = Mutex::new(Vec::new()); + extern "system" fn delayed(_: *mut c_void, canceled: bool) { + lock(&EVENTS).push(if canceled { "canceled" } else { "ran" }); + } + extern "system" fn terminated(_: *mut c_void) { + lock(&EVENTS).push("terminated"); + } + let mut q = std::ptr::null(); + assert_eq!(XTaskQueueCreate(1, 1, &mut q), S_OK); + let none = std::ptr::null_mut(); + let hr = XTaskQueueSubmitDelayedCallback(q, WORK, 50, none, Some(delayed)); + assert_eq!(hr, S_OK); + assert_eq!(XTaskQueueTerminate(q, true, none, Some(terminated)), S_OK); + assert_eq!(*lock(&EVENTS), ["canceled", "terminated"]); + // Its delay passes without it running. + std::thread::sleep(Duration::from_millis(200)); + assert_eq!(*lock(&EVENTS), ["canceled", "terminated"]); + XTaskQueueCloseHandle(q); + } } From 9a34298a0b077a3e759001430bc47fc0f7064720 Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:43:55 +0100 Subject: [PATCH 209/445] Files: a title run by its file name alone gets its own folder as G: `victory run GTA6.exe`, run from the game folder, gives an exe path with an empty parent, and that empty folder was mounted as G:. An empty path cannot be made absolute, so the root stayed empty and G:\x64\a.rpf became \x64\a.rpf: the root of the current drive. The title then found none of its files. An empty root is now the current directory, which is what an empty folder means everywhere else (`Path::new("").join("x")` is `x` in the current directory). Passing a path with a folder in it is unaffected. (cherry picked from commit 01ae55a3ba04c39a0e8851cc00da16af7a49adbd) --- crates/victory-hle/src/modules/files.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index fa69d73..1dacc10 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -83,8 +83,15 @@ pub fn mount_at(letter: char, root: &Path) { } /// `root` as UTF-16, absolute, without trailing separators (a drive root -/// keeps its own). +/// keeps its own). An empty root is the current directory, as it is to a +/// path joined to it: it is the title's folder when the title is run by its +/// file name alone (`victory run GTA6.exe`). fn root_wide(root: &Path) -> Vec { + let root = if root.as_os_str().is_empty() { + Path::new(".") + } else { + root + }; let root = std::path::absolute(root).unwrap_or_else(|_| root.to_owned()); let mut wide: Vec = root.as_os_str().encode_wide().collect(); while wide.len() > 3 && wide.last().is_some_and(|c| SEPARATORS.contains(c)) { @@ -865,6 +872,17 @@ mod tests { ); } + /// A title run by its file name alone has an empty folder: the drive + /// over it is the current directory, not the current drive's root. + #[test] + fn an_empty_root_is_the_current_directory() { + let letter = mount(Path::new("")).unwrap(); + let path = format!(r"{letter}:\a.rpf"); + let host = translate(&w(&path)[..path.len()]).map(|v| text(&v)); + let cwd = std::env::current_dir().unwrap(); + assert_eq!(host, Some(cwd.join("a.rpf").display().to_string())); + } + #[test] fn long_title_paths_work_on_the_host() { let dir = tempfile::tempdir().unwrap(); From ade1da1129321cf2c1d0565ea51091f5b044143e Mon Sep 17 00:00:00 2001 From: TG0000 <122870448+TG0000@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:03:34 +0100 Subject: [PATCH 210/445] XMA: build the inverse transform's rotations once per subframe size imdct_half worked out every pre- and post-rotation with sin_cos on each call (n of them per subframe) and ran its FFT on two fresh Vecs. The rotations, the bit-reversed order and the butterfly rotations now come from a table built once for 128, 256 and 512 samples; the work buffers live on the stack. Every value is computed with the same expression (the butterflies with the same running product), so the output is bit for bit what it was. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 4eb0898b3cbd6d0bbbffad540aca5d7e3531ac58) --- crates/victory-formats/src/xma.rs | 336 ++++++++++++++++++++++++++---- 1 file changed, 299 insertions(+), 37 deletions(-) diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs index a8ea48c..c4164a0 100644 --- a/crates/victory-formats/src/xma.rs +++ b/crates/victory-formats/src/xma.rs @@ -293,57 +293,178 @@ fn log2(v: usize) -> u32 { /// `n` coefficients to the middle `n` samples of the 2n-sample window, /// negated and scaled by `scale`. Computed as a DCT-IV through an /// n/2-point complex FFT. +/// +/// The rotations come from [`Rotations`], built once per subframe size, so +/// a subframe costs no sines or cosines and no allocation. fn imdct_half(input: &[f32], out: &mut [f32], scale: f32) { let n = input.len(); let m = n / 2; - let mut re = vec![0f64; m]; - let mut im = vec![0f64; m]; - for k in 0..m { + let built; + let rotations = match rotations().get(log2(n).wrapping_sub(7) as usize) { + Some(r) if r.pre_re.len() == m => r, + _ => { + built = Rotations::new(n); + &built + } + }; + let mut stack = [0f64; FRAME_SAMPLES]; + let mut heap = Vec::new(); + let (re, im) = if m <= stack.len() / 2 { + stack.split_at_mut(m) + } else { + heap.resize(2 * m, 0f64); + heap.split_at_mut(m) + }; + let im = &mut im[..m]; + // Pre-rotation, each point stored at its bit-reversed place, which is + // where the FFT's input permutation would move it. + let pre = rotations + .pre_re + .iter() + .zip(&rotations.pre_im) + .zip(&rotations.reversed); + for (k, ((&c, &s), &to)) in pre.enumerate() { let (a, b) = (input[2 * k] as f64, input[n - 1 - 2 * k] as f64); - let (s, c) = (-std::f64::consts::PI * k as f64 / n as f64).sin_cos(); - (re[k], im[k]) = (a * c - b * s, a * s + b * c); + re[to as usize] = a * c - b * s; + im[to as usize] = a * s + b * c; } - fft(&mut re, &mut im); - for k in 0..m { - let (s, c) = (-std::f64::consts::PI * (4 * k + 1) as f64 / (4 * n) as f64).sin_cos(); - let (wr, wi) = (re[k] * c - im[k] * s, re[k] * s + im[k] * c); + rotations.butterflies(re, im); + let post = rotations.post_re.iter().zip(&rotations.post_im); + for (k, ((&re, &im), (&c, &s))) in re.iter().zip(im.iter()).zip(post).enumerate() { + let (wr, wi) = (re * c - im * s, re * s + im * c); // DCT-IV: c[2k] = Re, c[n-1-2k] = -Im; output j is c[n-1-j]. out[n - 1 - 2 * k] = (wr as f32) * scale; out[2 * k] = -(wi as f32) * scale; } } -/// In-place radix-2 forward DFT (`exp(-2πi nk/N)`). -fn fft(re: &mut [f64], im: &mut [f64]) { - let n = re.len(); - let mut j = 0; - for i in 1..n { - let mut bit = n >> 1; - while j & bit != 0 { - j ^= bit; - bit >>= 1; - } - j |= bit; - if i < j { - re.swap(i, j); - im.swap(i, j); - } - } - let mut len = 2; - while len <= n { - let (ws, wc) = (-2.0 * std::f64::consts::PI / len as f64).sin_cos(); - for start in (0..n).step_by(len) { - let (mut cr, mut ci) = (1.0, 0.0); - for k in 0..len / 2 { - let (a, b) = (start + k, start + k + len / 2); - let (tr, ti) = (re[b] * cr - im[b] * ci, re[b] * ci + im[b] * cr); - (re[b], im[b]) = (re[a] - tr, im[a] - ti); - (re[a], im[a]) = (re[a] + tr, im[a] + ti); - (cr, ci) = (cr * wc - ci * ws, cr * ws + ci * wc); +/// Everything [`imdct_half`] needs for one size `n` that does not depend on +/// the coefficients: the pre-rotation `exp(-iπk/n)` and post-rotation +/// `exp(-iπ(4k+1)/4n)` of each of the n/2 FFT points, the FFT's bit-reversed +/// order and its butterfly rotations. Each value is computed with the same +/// expression (for the butterflies the same running product) the transform +/// used to work out on every call, so it gives the same bits. +struct Rotations { + pre_re: Vec, + pre_im: Vec, + post_re: Vec, + post_im: Vec, + /// Where the bit-reversal permutation puts each point. + reversed: Vec, + /// The butterfly rotations of every stage, the stage of length `len` + /// starting at `len / 2 - 1`. + twiddle_re: Vec, + twiddle_im: Vec, +} + +impl Rotations { + fn new(n: usize) -> Rotations { + let m = n / 2; + let (pre_re, pre_im) = (0..m) + .map(|k| { + let (s, c) = (-std::f64::consts::PI * k as f64 / n as f64).sin_cos(); + (c, s) + }) + .unzip(); + let (post_re, post_im) = (0..m) + .map(|k| { + let (s, c) = + (-std::f64::consts::PI * (4 * k + 1) as f64 / (4 * n) as f64).sin_cos(); + (c, s) + }) + .unzip(); + // The swaps of the in-place bit-reversal, applied to the identity. + let mut reversed: Vec = (0..m as u16).collect(); + let mut j = 0; + for i in 1..m { + let mut bit = m >> 1; + while j & bit != 0 { + j ^= bit; + bit >>= 1; + } + j |= bit; + if i < j { + reversed.swap(i, j); } } - len <<= 1; + let mut twiddle_re = Vec::with_capacity(m.saturating_sub(1)); + let mut twiddle_im = Vec::with_capacity(m.saturating_sub(1)); + let mut len = 2; + while len <= m { + let (ws, wc) = (-2.0 * std::f64::consts::PI / len as f64).sin_cos(); + let (mut cr, mut ci) = (1.0, 0.0); + for _ in 0..len / 2 { + twiddle_re.push(cr); + twiddle_im.push(ci); + (cr, ci) = (cr * wc - ci * ws, cr * ws + ci * wc); + } + len <<= 1; + } + Rotations { + pre_re, + pre_im, + post_re, + post_im, + reversed, + twiddle_re, + twiddle_im, + } } + + /// The butterfly stages of an in-place radix-2 forward DFT + /// (`exp(-2πi nk/N)`) on points already in bit-reversed order. + fn butterflies(&self, re: &mut [f64], im: &mut [f64]) { + let m = re.len().min(im.len()); + let mut len = 2; + while len <= m { + let half = len / 2; + let wr = &self.twiddle_re[half - 1..][..half]; + let wi = &self.twiddle_im[half - 1..][..half]; + let blocks = re[..m] + .chunks_exact_mut(len) + .zip(im[..m].chunks_exact_mut(len)); + for (re, im) in blocks { + let (are, bre) = re.split_at_mut(half); + let (aim, bim) = im.split_at_mut(half); + butterfly_block(are, aim, bre, bim, wr, wi); + } + len <<= 1; + } + } +} + +/// One block of butterflies: `a + w·b` into `a`, `a − w·b` into `b`. +#[inline(always)] +fn butterfly_block( + are: &mut [f64], + aim: &mut [f64], + bre: &mut [f64], + bim: &mut [f64], + wr: &[f64], + wi: &[f64], +) { + let lanes = are + .iter_mut() + .zip(aim) + .zip(bre.iter_mut().zip(bim)) + .zip(wr.iter().zip(wi)); + for (((ar, ai), (br, bi)), (&cr, &ci)) in lanes { + let (tr, ti) = (*br * cr - *bi * ci, *br * ci + *bi * cr); + (*br, *bi) = (*ar - tr, *ai - ti); + (*ar, *ai) = (*ar + tr, *ai + ti); + } +} + +/// [`Rotations`] for subframes of 128, 256 and 512 samples. +fn rotations() -> &'static [Rotations; 3] { + static ROTATIONS: OnceLock<[Rotations; 3]> = OnceLock::new(); + ROTATIONS.get_or_init(|| { + [ + Rotations::new(128), + Rotations::new(256), + Rotations::new(512), + ] + }) } /// `ff_sine_windows`: the rising half of a sine window of length `n`. @@ -1115,6 +1236,147 @@ mod tests { } } + /// The transform as it was before [`Rotations`]: every rotation worked + /// out again on each call, the FFT on two fresh buffers. + fn imdct_half_untabled(input: &[f32], out: &mut [f32], scale: f32) { + let n = input.len(); + let m = n / 2; + let mut re = vec![0f64; m]; + let mut im = vec![0f64; m]; + for k in 0..m { + let (a, b) = (input[2 * k] as f64, input[n - 1 - 2 * k] as f64); + let (s, c) = (-std::f64::consts::PI * k as f64 / n as f64).sin_cos(); + (re[k], im[k]) = (a * c - b * s, a * s + b * c); + } + let mut j = 0; + for i in 1..m { + let mut bit = m >> 1; + while j & bit != 0 { + j ^= bit; + bit >>= 1; + } + j |= bit; + if i < j { + re.swap(i, j); + im.swap(i, j); + } + } + let mut len = 2; + while len <= m { + let (ws, wc) = (-2.0 * std::f64::consts::PI / len as f64).sin_cos(); + for start in (0..m).step_by(len) { + let (mut cr, mut ci) = (1.0, 0.0); + for k in 0..len / 2 { + let (a, b) = (start + k, start + k + len / 2); + let (tr, ti) = (re[b] * cr - im[b] * ci, re[b] * ci + im[b] * cr); + (re[b], im[b]) = (re[a] - tr, im[a] - ti); + (re[a], im[a]) = (re[a] + tr, im[a] + ti); + (cr, ci) = (cr * wc - ci * ws, cr * ws + ci * wc); + } + } + len <<= 1; + } + for k in 0..m { + let (s, c) = (-std::f64::consts::PI * (4 * k + 1) as f64 / (4 * n) as f64).sin_cos(); + let (wr, wi) = (re[k] * c - im[k] * s, re[k] * s + im[k] * c); + out[n - 1 - 2 * k] = (wr as f32) * scale; + out[2 * k] = -(wi as f32) * scale; + } + } + + /// Pseudo-random coefficients spread over many magnitudes, as dequantised + /// subframes are. + fn noise(n: usize, seed: u64) -> Vec { + let mut state = seed | 1; + (0..n) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + let mantissa = (state >> 40) as f32 / (1u64 << 24) as f32 - 0.5; + mantissa * 2f32.powi((state % 24) as i32 - 4) + }) + .collect() + } + + /// The tables change nothing: every subframe size (and sizes the decoder + /// never uses, which build their tables on the spot) gives the bits the + /// untabled transform gives. + #[test] + fn tabled_imdct_gives_the_same_bits() { + for n in [2usize, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048] { + for seed in 0..16 { + let input = noise(n, seed * 7919 + n as u64); + let scale = 2.0 / n as f32 / 32768.0; + let mut tabled = vec![0f32; n]; + let mut untabled = vec![0f32; n]; + imdct_half(&input, &mut tabled, scale); + imdct_half_untabled(&input, &mut untabled, scale); + let tabled: Vec = tabled.iter().map(|v| v.to_bits()).collect(); + let untabled: Vec = untabled.iter().map(|v| v.to_bits()).collect(); + assert_eq!(tabled, untabled, "n {n}, seed {seed}"); + } + } + let mut out = [0f32; 0]; + imdct_half(&[], &mut out, 1.0); + } + + /// The cached tables are the ones the sizes ask for. + #[test] + fn cached_rotations_match_their_sizes() { + for (r, n) in rotations().iter().zip([128usize, 256, 512]) { + let fresh = Rotations::new(n); + assert_eq!((&r.pre_re, &r.pre_im), (&fresh.pre_re, &fresh.pre_im)); + assert_eq!((&r.post_re, &r.post_im), (&fresh.post_re, &fresh.post_im)); + assert_eq!(r.reversed, fresh.reversed); + assert_eq!( + (&r.twiddle_re, &r.twiddle_im), + (&fresh.twiddle_re, &fresh.twiddle_im) + ); + assert_eq!(r.pre_re.len(), n / 2); + assert_eq!(r.twiddle_re.len(), n / 2 - 1); + // The order is a permutation that undoes itself. + for (i, &to) in r.reversed.iter().enumerate() { + assert_eq!(r.reversed[to as usize] as usize, i); + } + } + } + + /// Release benchmark of one inverse transform per subframe size, tabled + /// against untabled: + /// `cargo test --release -p victory-formats imdct_throughput -- --ignored --nocapture`. + #[test] + #[ignore = "benchmark"] + fn imdct_throughput() { + for n in [128usize, 256, 512] { + let inputs: Vec> = (0..64).map(|seed| noise(n, seed)).collect(); + let mut out = vec![0f32; n]; + let rounds = 20_000; + let mut time = |f: fn(&[f32], &mut [f32], f32)| { + let mut best = f64::MAX; + for _ in 0..3 { + let started = std::time::Instant::now(); + for i in 0..rounds { + f( + std::hint::black_box(&inputs[i % inputs.len()]), + &mut out, + 1.0, + ); + std::hint::black_box(&out); + } + best = best.min(started.elapsed().as_secs_f64() * 1e9 / rounds as f64); + } + best + }; + let before = time(imdct_half_untabled); + let after = time(imdct_half); + println!( + "n {n}: untabled {before:.0} ns, tabled {after:.0} ns, {:.1}x", + before / after + ); + } + } + /// Windowed MDCT blocks of a signal, put back together the way the /// decoder does (half IMDCT, then window and overlap), give the signal. #[test] From 717b3e81b29b16198f03cbf414020d45aa0b4603 Mon Sep 17 00:00:00 2001 From: AnoHunted <360473103+AnoHunted@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:13:22 +0000 Subject: [PATCH 211/445] XMA: noise tests, and end a frame at its data instead of looping forever Decoder::decode took the caller's bit count as the end of the frame. Past the data the bit reader returns zeros, and a stereo tile header reading only zeros gives the subframe to no channel, so it never moves on; with a count beyond the data it never overreads either, and looped for good. Clamp the end to the bits the data holds. A frame from read_frame always holds its bits, so its decoding does not change. Add deterministic noise tests (xorshift64, fixed seeds, as BCPack's): buffers of noise packets, streams of noise frames with clean and damaged headers, frames in mono and stereo at each sample rate, bit counts past the data, and read_frame and packet at any offset. Every walk is bounded and every decode must give one frame of samples. The bit-count test hangs without the fix; the others pass on main. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit d4d1822049fed053c6188ea0b016b0976a71bf41) --- crates/victory-formats/src/xma.rs | 239 +++++++++++++++++++++++++++++- 1 file changed, 238 insertions(+), 1 deletion(-) diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs index c4164a0..f5a5528 100644 --- a/crates/victory-formats/src/xma.rs +++ b/crates/victory-formats/src/xma.rs @@ -624,7 +624,10 @@ impl Decoder { let mut b = Bits { data, pos: 0, - end: bits, + // Past the data there are only zeros to read. A count beyond it + // would never let a stereo tile header overread, and its loop + // takes no subframe on zero bits, so it would spin for good. + end: bits.min(data.len().saturating_mul(8)), }; let len = b.read(LENGTH_BITS) as usize; let result = self.frame(&mut b, len); @@ -1454,6 +1457,240 @@ mod tests { assert_eq!(c.next, None); } + /// Deterministic noise: xorshift64, as in BCPack's noise test. + struct Noise(u64); + + impl Noise { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + /// A number below `n`. + fn below(&mut self, n: usize) -> usize { + (self.next() % n as u64) as usize + } + + /// `len` bytes of even noise, or of mostly zeros (`density` 1) or + /// mostly ones (2), which take other paths through a frame. + fn bytes(&mut self, len: usize, density: usize) -> Vec { + (0..len) + .map(|_| { + let r = self.next(); + let (a, b, c) = (r as u8, (r >> 8) as u8, (r >> 16) as u8); + match density { + 0 => a, + 1 => a & b & c, + _ => a | b | c, + } + }) + .collect() + } + } + + /// Writes `value` as `n` bits, MSB first, at bit `pos`, over what is there. + fn set_bits(data: &mut [u8], pos: usize, n: u32, value: u32) { + for i in 0..n as usize { + let (p, bit) = (pos + i, (value >> (n as usize - 1 - i)) & 1); + data[p / 8] = (data[p / 8] & !(0x80 >> (p % 8))) | ((bit as u8) << (7 - p % 8)); + } + } + + /// `packets` packets of one stream: back-to-back frames of noise after + /// their length fields, 300 to 4299 bits long (so every packet but the + /// last has a frame start, and at most 55 do), then padding of ones. + /// The headers count the frames that begin in each packet. Also gives + /// the number of frames. + fn noise_stream(noise: &mut Noise, packets: usize, density: usize) -> (Vec, usize) { + const PAYLOAD: usize = PACKET_BITS - HEADER_BITS; + let mut data = noise.bytes(packets * PACKET_BYTES, density); + // Where payload bit `q` of the stream is in the buffer. + let at = |q: usize| q / PAYLOAD * PACKET_BITS + HEADER_BITS + q % PAYLOAD; + let mut headers = vec![(0u32, 0u32); packets]; + let (mut q, mut frames) = (0, 0); + loop { + let len = 300 + noise.below(4000); + if q + len > packets * PAYLOAD { + break; + } + let header = &mut headers[q / PAYLOAD]; + if header.0 == 0 { + header.1 = (q % PAYLOAD) as u32; + } + header.0 += 1; + for i in 0..LENGTH_BITS { + let bit = (len >> (LENGTH_BITS - 1 - i)) as u32 & 1; + set_bits(&mut data, at(q + i as usize), 1, bit); + } + q += len; + frames += 1; + } + for padding in q..packets * PAYLOAD { + set_bits(&mut data, at(padding), 1, 1); + } + for (p, &(count, first)) in headers.iter().enumerate() { + set_bits(&mut data, p * PACKET_BITS, 32, count << 26 | first << 11); + } + (data, frames) + } + + /// Packets of noise, streams of frames of noise, and such streams with + /// headers and bits damaged: walking the frames from the first packet + /// and decoding each, mono and stereo, gives a frame of samples per + /// frame and ends within the frames the buffer can hold (each is over + /// 15 bits and the walk only moves on). + #[test] + fn noise_packets_walk_and_decode() { + let mut noise = Noise(0x2545_f491_4f6c_dd1d); + for round in 0..60 { + let packets = 1 + round % 4; + let density = [0, 0, 1, 2][round / 3 % 4]; + let (mut data, written) = match round % 3 { + 0 => (noise.bytes(packets * PACKET_BYTES, density), 0), + _ => noise_stream(&mut noise, packets, density), + }; + if round % 3 == 2 { + for _ in 0..1 + noise.below(3) { + let p = noise.below(packets); + set_bits(&mut data, p * PACKET_BITS, 32, noise.next() as u32); + } + for _ in 0..noise.below(16) { + let bit = noise.below(data.len() * 8); + data[bit / 8] ^= 0x80 >> (bit % 8); + } + } + let budget = data.len() * 8 / 16; + for channels in [1, 2] { + let mut decoder = Decoder::new(channels, 48_000); + let per_frame = FRAME_SAMPLES * channels; + let (mut pcm, mut frames) = (Vec::new(), 0); + let mut at = packet(&data, 0).map(|p| HEADER_BITS + p.first_frame_bit as usize); + while let Some(frame) = at.and_then(|bit| read_frame(&data, bit)) { + frames += 1; + let moves_on = frame.next.is_none_or(|next| next > frame.start); + assert!(frames <= budget && moves_on, "round {round}"); + let _ = decoder.decode(&frame.data, frame.bits, &mut pcm); + assert_eq!(pcm.len(), frames * per_frame, "round {round}"); + at = frame.next; + } + if round % 3 == 1 { + // A clean stream: every frame is walked. + assert_eq!(frames, written, "round {round}"); + } + decoder.flush(&mut pcm); + assert_eq!(pcm.len(), frames * per_frame + per_frame / 2); + } + } + } + + /// Frames of noise, mono and stereo at each sample rate, with bit + /// counts up to the end of the data: every decode gives one frame of + /// samples, whether the frame decodes or not. + #[test] + fn noise_frames_decode_to_a_frame_of_samples() { + let mut noise = Noise(0x9e37_79b9_7f4a_7c15); + for channels in [1, 2] { + for rate in [24_000, 32_000, 44_100, 48_000] { + let mut decoder = Decoder::new(channels, rate); + let mut pcm = Vec::new(); + for round in 0..48 { + let data = noise.bytes(round * 89 % 4096, [0, 0, 1, 2][round % 4]); + let bits = match round % 2 { + 0 => data.len() * 8, + _ => noise.below(data.len() * 8 + 1), + }; + pcm.clear(); + let _ = decoder.decode(&data, bits, &mut pcm); + assert_eq!( + pcm.len(), + FRAME_SAMPLES * channels, + "{channels} channels, {rate} Hz, round {round}" + ); + if round % 16 == 15 { + decoder.reset(); + } + } + pcm.clear(); + decoder.flush(&mut pcm); + assert_eq!(pcm.len(), FRAME_SAMPLES / 2 * channels); + } + } + } + + /// Bit counts past the end of a frame's data, up to `usize::MAX`: the + /// decoding ends, with a frame of samples. A stereo tile header that ran + /// out of data used to loop on the zeros past it for good (found by + /// this test). + #[test] + fn noise_frames_with_bit_counts_past_the_data() { + let mut noise = Noise(0xd1b5_4a32_d192_ed03); + for channels in [1, 2] { + let mut decoder = Decoder::new(channels, 48_000); + let mut pcm = Vec::new(); + for round in 0..48 { + let len = [0, 1, 2, 3, 5, 8, 40, 300][round % 8]; + let data = noise.bytes(len, [0, 0, 1, 2][round / 8 % 4]); + let bits = match round % 3 { + 0 => data.len() * 8 + 1 + noise.below(1 << 16), + 1 => usize::MAX / 2 + noise.below(1 << 20), + _ => usize::MAX, + }; + pcm.clear(); + let _ = decoder.decode(&data, bits, &mut pcm); + assert_eq!( + pcm.len(), + FRAME_SAMPLES * channels, + "{channels} channels, round {round}" + ); + } + } + } + + /// `read_frame` from any bit of a buffer of noise and past it, and + /// `packet` at any index: a frame read stays inside its limits. + #[test] + fn noise_offsets_read_a_frame_or_nothing() { + let mut noise = Noise(0x6a09_e667_f3bc_c908); + for round in 0..24 { + let packets = 1 + round % 3; + let data = noise.bytes(packets * PACKET_BYTES, [0, 0, 1, 2][round % 4]); + let all = data.len() * 8; + let edges = [ + 0, + 1, + HEADER_BITS - 1, + HEADER_BITS, + PACKET_BITS - LENGTH_BITS as usize, + PACKET_BITS - 1, + PACKET_BITS, + all - 1, + all, + all + 1, + usize::MAX / 2, + usize::MAX - PACKET_BITS + 1, + usize::MAX, + ]; + let mut starts = edges.to_vec(); + starts.extend((0..32).map(|_| noise.below(all))); + for start in starts { + if let Some(frame) = read_frame(&data, start) { + let lengths = LENGTH_BITS as usize + 1..0x7fff; + assert!(lengths.contains(&frame.bits), "start {start}"); + assert_eq!(frame.data.len(), frame.bits.div_ceil(8)); + if let Some(next) = frame.next { + assert!(next > start && next / 8 < data.len(), "start {start}"); + } + } + } + let far = usize::MAX / PACKET_BYTES; + for index in [0, packets - 1, packets, far, usize::MAX] { + assert_eq!(packet(&data, index).is_some(), index < packets, "{index}"); + } + } + } + /// Walks and decodes saved input buffers (`VICTORY_XMA_STREAMS=` of /// `*.xma` files with their `*.ctx` context words, made outside the /// repository): the frames walked from the first packet must be the From 8b5f54b23529759a0f640fc4f8b952b29c8e1011 Mon Sep 17 00:00:00 2001 From: Maraco91 <43787609+Maraco91@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:17:47 +0100 Subject: [PATCH 212/445] Audio: an XMA loop's skip is of its first frame, not of its last When a frame ended a loop, decode cut it at the loop's end subframe, set the loop's skip (the subframes of the loop's first frame that lie before the loop) and then took that skip out of the frame in hand: the loop's last. So the head of the last frame was dropped instead, and the first frame played from its start, with the audio before the loop in it. The number of samples came out the same; the seam did not. The pending skip is still applied to the frame in hand, and the loop's skip is set after it, for the frame decoded next. Co-Authored-By: Claude Fable 5.2 (cherry picked from commit 985d8d4b025384b5f13a3177ef906c8b6cce6840) --- crates/victory-hle/src/modules/audio.rs | 74 ++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 2 deletions(-) diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index 5ce7551..42f8746 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -608,18 +608,25 @@ fn decode(context: Context, voice: &mut Voice) -> bool { let ends_loop = loop_end != 0 && (frame.start == loop_end || (frame.start < loop_end && frame.next.is_none_or(|n| loop_end < n))); - if loops > 0 && ends_loop { + let looping = loops > 0 && ends_loop; + if looping { let keep = (context.field(1, 12, 2) as usize + 1) * xma::SUBFRAME_SAMPLES * channels; pcm.truncate(keep); next = context.field(3, 0, 26) as usize; - voice.skip = context.field(1, 17, 3) as usize * xma::SUBFRAME_SAMPLES; if loops != 255 { context.set_field(0, 12, 8, loops - 1); } } + // What is still to skip is this frame's (the stream's first, or a + // loop's first when it is its last too). let skip = (voice.skip * channels).min(pcm.len()); voice.skip -= skip / channels; voice.pcm.extend(&pcm[skip..]); + if looping { + // The loop's own skip is of its first frame, decoded next: not of + // this one, its last. + voice.skip = context.field(1, 17, 3) as usize * xma::SUBFRAME_SAMPLES; + } if next == 0 { context.set_field(0, 20 + current, 1, 0); } @@ -1083,6 +1090,69 @@ mod tests { assert_eq!(AcpHalReleaseShapeContexts(), S_OK); } + /// A loop over the first two frames, which ends after the second + /// frame's second subframe and starts two subframes into the first. + /// Each end of the loop is cut in its own frame. + #[test] + fn a_loop_skips_subframes_of_its_first_frame() { + let _serial = lock(&CONTEXT_TESTS); + let (mut input, mut input_apu) = (std::ptr::null_mut(), 0); + assert_eq!(ApuAlloc(&mut input, &mut input_apu, 0x1000, 0x800, 1), S_OK); + let stream = silent_stream(); + // SAFETY: two packets were allocated. + unsafe { std::ptr::copy_nonoverlapping(stream.as_ptr(), input.cast(), stream.len()) }; + + // Frames start at bits 32, 63 and 94 of each packet. + let (first, second, third) = (32, 63, 94); + let (end_subframe, skip_subframes) = (1, 2); + let mut words = [0u32; 16]; + let context = Context(words.as_mut_ptr()); + // Two packets, one loop, input 0 valid; 48 kHz mono. + context.set(0, 2 | 1 << 12 | 1 << 20 | 4 << 22); + context.set( + 1, + 1 << 31 | 3 << 27 | end_subframe << 12 | skip_subframes << 17, + ); + context.set(2, first); + context.set(3, first); + context.set(4, second); + context.set(5, input_apu); + let mut voice = Voice { + decoder: None, + pcm: VecDeque::new(), + skip: 0, + ended: false, + trace: Trace { + since: Instant::now(), + produced: 0, + taken: 0, + takes: 0, + partial_takes: 0, + frames: 0, + bad_frames: 0, + peak: 0, + ended_ms: None, + }, + }; + let mut step = |expect_next: u32| { + let before = voice.pcm.len(); + assert!(decode(context, &mut voice)); + assert_eq!(context.field(2, 0, 26), expect_next); + voice.pcm.len() - before + }; + let subframe = xma::SUBFRAME_SAMPLES; + // Before the loop: the first frame whole. + assert_eq!(step(second), 4 * subframe); + // The loop's last frame: its first two subframes, then back. + assert_eq!(step(first), 2 * subframe, "the loop's last frame"); + assert_eq!(context.field(0, 12, 8), 0, "one loop, taken"); + // The loop's first frame again: without its first two subframes. + assert_eq!(step(second), 2 * subframe, "the loop's first frame"); + // No loops left: both frames whole, and on to the third. + assert_eq!(step(third), 4 * subframe); + ApuFree(input); + } + #[test] fn full_message_queues_count_drops() { let mut acp = std::ptr::null_mut(); From fc0d5e7795952417b4d4177148b45ff942cc3b78 Mon Sep 17 00:00:00 2001 From: Maraco91 <43787609+Maraco91@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:25:27 +0100 Subject: [PATCH 213/445] Media: a share is refused however it is spelled The source resolver's rule (local files only) knew a share as `\..`, `//..` or `file://server/..`. The host knows more spellings: any two leading separators (`/\server\share`), the object manager's prefix (`\??\UNC\server\share`), and a `file:` URL with no host whose path starts with two separators (`file:////server/share`, `file:\server\share`, also percent-encoded). Those fell through as relative paths or drive-less local files and went to the host's resolver unchanged. They are refused now, naming the server. Paths with one leading separator, a drive after the slashes or the prefix, and the path of a URL that names this machine pass as before. Co-Authored-By: Claude Fable 5.2 (cherry picked from commit 11ca3ce4928cf9ac2f77fcdc1c095d41c62fcbce) --- crates/victory-hle/src/modules/media.rs | 108 ++++++++++++++++++++++-- 1 file changed, 103 insertions(+), 5 deletions(-) diff --git a/crates/victory-hle/src/modules/media.rs b/crates/victory-hle/src/modules/media.rs index aa6e91c..867d978 100644 --- a/crates/victory-hle/src/modules/media.rs +++ b/crates/victory-hle/src/modules/media.rs @@ -48,13 +48,25 @@ fn local(url: &[u16]) -> Result, (String, String)> { b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' }; let host_of = |rest: &str| rest.split(['/', '\\']).next().unwrap_or("").to_string(); + // Two leading separators, of either kind: to the host, a share. + let share = |s: &str| { + let b = s.as_bytes(); + b.len() >= 2 && b[..2].iter().all(|c| b"/\\".contains(c)) + }; let path = if let Some(rest) = text.strip_prefix(r"\\?\") { if !drive(rest) { return Err(("unc".into(), host_of(rest.trim_start_matches("UNC\\")))); } text.clone() - } else if let Some(rest) = text.strip_prefix(r"\\").or_else(|| text.strip_prefix("//")) { - return Err(("unc".into(), host_of(rest))); + } else if let Some(rest) = text.strip_prefix(r"\??\") { + // The same prefix as the object manager spells it; the host's file + // calls take it too. + if !drive(rest) { + return Err(("unc".into(), host_of(rest.trim_start_matches("UNC\\")))); + } + return Ok(with_nul(url)); + } else if share(&text) { + return Err(("unc".into(), host_of(&text[2..]))); } else if drive(&text) { text.clone() } else if let Some((scheme, rest)) = text.split_once(':').filter(|(s, _)| { @@ -67,18 +79,24 @@ fn local(url: &[u16]) -> Result, (String, String)> { if scheme != "file" { return Err((scheme, authority.map(host_of).unwrap_or_default())); } - let path = match authority { + let (path, this_machine) = match authority { Some(rest) => { let host = host_of(rest); if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") { return Err((scheme, host)); } - &rest[host.len()..] + (&rest[host.len()..], !host.is_empty()) } - None => rest, + None => (rest, false), }; + let whole = percent_decode(path); let path = percent_decode(path.trim_start_matches(['/', '\\'])).replace('/', "\\"); if !drive(&path) { + // With no host named, a path that starts with two separators + // names one: `file:////server/share` is `\\server\share`. + if !this_machine && share(&whole) { + return Err((scheme, host_of(whole.trim_start_matches(['/', '\\'])))); + } // A local file without a drive: the host resolves it as is. return Ok(with_nul(url)); } @@ -523,6 +541,86 @@ mod tests { assert_eq!(text(&local(&wide("clip.mp4")).unwrap()), "clip.mp4"); } + /// Other spellings of `\\server\share\a.mp4`, as paths and as `file:` + /// URLs without a host. + const SHARE_PATHS: [&str; 3] = [ + r"/\server\share\a.mp4", + r"\/server/share/a.mp4", + r"\??\UNC\server\share\a.mp4", + ]; + const SHARE_URLS: [&str; 5] = [ + "file:////server/share/a.mp4", + "file://///server/share/a.mp4", + r"file:\\server\share\a.mp4", + "file:/%5Cserver/share/a.mp4", + "file:///%5C%5Cserver/share/a.mp4", + ]; + + #[test] + fn shares_are_refused_however_they_are_spelled() { + let asked = |url: &str| local(&wide(url)).map(|v| text(&v)); + for path in SHARE_PATHS { + assert_eq!(asked(path), Err(("unc".into(), "server".into())), "{path}"); + } + for url in SHARE_URLS { + assert_eq!(asked(url), Err(("file".into(), "server".into())), "{url}"); + } + // Local files that look alike still pass: one leading separator, a + // drive after the slashes, a drive after the object prefix, and the + // path of a URL that names this machine. + for local_file in [ + r"\movies\a.mp4", + "file:///movies/a.mp4", + r"\??\C:\Windows\a.wav", + "file://localhost//server/share/a.mp4", + ] { + assert_eq!(asked(local_file), Ok(local_file.into()), "{local_file}"); + } + assert_eq!( + asked("file:////C:/Windows/a.wav"), + Ok(r"C:\Windows\a.wav".into()) + ); + } + + /// What the host makes of those spellings: the share, for each. + #[cfg(windows)] + #[test] + fn the_host_reads_those_spellings_as_shares() { + for path in &SHARE_PATHS[..2] { + assert_eq!( + std::path::absolute(path).unwrap().to_str(), + Some(r"\\server\share\a.mp4"), + "{path}" + ); + } + // The object prefix reaches the host's file calls as it is. + let windows = std::env::var("SystemRoot").unwrap(); + assert!(std::fs::metadata(format!(r"\??\{windows}")).is_ok()); + + let from_url = files::host!("shlwapi.dll", "PathCreateFromUrlW": + extern "system" fn(*const u16, *mut u16, *mut u32, u32) -> HRESULT); + let host_path = |url: &str| { + let url: Vec = url.encode_utf16().chain([0]).collect(); + let (mut path, mut n) = ([0u16; 260], 260); + assert_eq!(from_url(url.as_ptr(), path.as_mut_ptr(), &mut n, 0), S_OK); + String::from_utf16_lossy(&path[..n as usize]) + }; + for url in SHARE_URLS { + let path = host_path(url); + assert!( + path.starts_with(r"\\") && path.ends_with(r"server\share\a.mp4"), + "{url}: {path}" + ); + } + // And of the ones that pass: local paths. + assert_eq!( + host_path("file://localhost//server/share/a.mp4"), + r"\server\share\a.mp4" + ); + assert_eq!(host_path("file:////C:/Windows/a.wav"), r"C:\Windows\a.wav"); + assert_eq!(host_path("file:///movies/a.mp4"), r"\movies\a.mp4"); + } + #[test] fn interface_ids_are_the_resolvers() { assert_eq!(&IID_IUNKNOWN[8..], &[0xC0, 0, 0, 0, 0, 0, 0, 0x46]); From 1466eb61a2339559ecae83e335c548fabab5628a Mon Sep 17 00:00:00 2001 From: Maledetto <20729264+Makto94@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:29:01 +0100 Subject: [PATCH 214/445] Loader: clzero loops in one exception; rdpru Based on #34 by ka1qux (commit faa0a9a), rebased over #45, which added the same flag and register helpers for clwb loops; the duplicates are merged into gpr/cmp_flags/CMP_FLAGS. clzero: the two loops compilers build around it are done whole in one exception, leaving registers and flags as the last pass would. Anything else around it is one line and the next instruction. rdpru: returns the time-stamp counter for MPERF and APERF, 0 for other counters, and leaves the flags as they are: a Ryzen 7 5800X3D running it natively in user mode changes none, for known counters or not. Added over #34: - loop 1 rejects cmp rax, rax (it fell into the loop and left wrong flags); - tests that go through the emulation on any CPU (both loop shapes, the rax-rax and wrong-neighbour fallbacks, rdpru with both flag states), since on an AMD host the native tests never enter the handler. (cherry picked from commit 0de9efced179dfb523748f21cf4bdbe0d3aa7533) --- crates/victory-loader/src/crash.rs | 280 ++++++++++++++++++++++++++++- 1 file changed, 277 insertions(+), 3 deletions(-) diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index 3f77a88..62388ad 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -136,8 +136,12 @@ const FATAL: [i32; 6] = [ /// Console CPUs are Zen 2: titles use AMD-only instructions Intel CPUs /// lack. Does their job instead: `clzero` (`0f 01 fc`) zeroes the 64-byte -/// line at `rax`; `monitorx`/`mwaitx` (`0f 01 fa`/`fb`) are wait hints, so -/// a spin loop around them works with mwaitx as a yield. +/// line at `rax` (see [`clzero`] for the loops around it); +/// `monitorx`/`mwaitx` (`0f 01 fa`/`fb`) are wait hints, so a spin loop +/// around them works with mwaitx as a yield; `rdpru` (`0f 01 fd`) reads +/// MPERF (`ecx` 0) or APERF (1), cycles at the nominal and the actual +/// frequency, and gets the time-stamp counter for both: a core that never +/// changes frequency. unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { // SAFETY: the system passes valid exception pointers; the faulting // instruction's bytes are readable, as the CPU just fetched them. @@ -149,9 +153,17 @@ unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { } let code = context.Rip as *const u8; match code.cast::<[u8; 3]>().read_unaligned() { - [0x0f, 0x01, 0xfc] => ((context.Rax & !63) as *mut u8).write_bytes(0, 64), + [0x0f, 0x01, 0xfc] => return clzero(context), [0x0f, 0x01, 0xfa] => {} [0x0f, 0x01, 0xfb] => std::thread::yield_now(), + [0x0f, 0x01, 0xfd] => { + // Flags are left as they are: a Zen 3 changes none, for + // known counters or not (measured in user mode). + let known = context.Rcx as u32 <= 1; + let cycles = if known { std::arch::x86_64::_rdtsc() } else { 0 }; + context.Rax = cycles & 0xffff_ffff; + context.Rdx = cycles >> 32; + } _ => { // Only bytes inside the faulting instruction's page are read: the next page may // not be mapped. @@ -277,6 +289,95 @@ fn clwb_loop(code: &[u8]) -> Option { (limit != base).then_some(ClwbLoop { base, limit, len }) } +/// `clzero` at `context.Rip`. An exception costs about a microsecond and +/// titles clear tens of kilobytes at a time, a line per pass, so the two +/// loops compilers build around the instruction are done whole in one +/// exception, leaving registers and flags as their last pass would (`a` +/// and `b` any registers but `rax`): +/// +/// ```text +/// top: clzero top: mov rax, a +/// add rax, 0x40 add a, 0x40 +/// cmp rax, b clzero +/// jb top cmp a, b +/// jb top +/// ``` +/// +/// Anything else around it is one line and the next instruction. +/// +/// # Safety +/// `context` is the state of a thread that faulted at a `clzero`; the +/// lines its registers name are the title's to zero. +unsafe fn clzero(context: &mut CONTEXT) -> bool { + // SAFETY: (every use) a line the title asked to zero. + let zero = |rax: u64| unsafe { ((rax & !63) as *mut u8).write_bytes(0, 64) }; + let at = context.Rip as usize; + // The loops' other instructions are read only where that stays inside + // the faulting instruction's page (the next one may not be mapped). + let page = at & 0xfff; + if page + 12 <= 0x1000 { + // SAFETY: inside the page the CPU fetched the instruction from. + let after = unsafe { &*((at + 3) as *const [u8; 9]) }; + if let [0x48, 0x83, 0xc0, 0x40, cmp @ .., 0x72, 0xf4] = after + && let Some((0, limit)) = compare_registers(cmp) + && limit != 0 + { + let limit = *gpr(context, limit); + loop { + zero(context.Rax); + context.Rax = context.Rax.wrapping_add(0x40); + if context.Rax >= limit { + break; + } + } + context.EFlags = context.EFlags & !CMP_FLAGS | cmp_flags(context.Rax, limit); + context.Rip += 12; + return true; + } + } + if (7..=0x1000 - 8).contains(&page) { + // SAFETY: inside the page the CPU fetched the instruction from. + let (before, after) = + unsafe { (&*((at - 7) as *const [u8; 7]), &*((at + 3) as *const [u8; 5])) }; + if let [rex @ (0x48 | 0x4c), 0x89, load, add_rex @ (0x48 | 0x49), 0x83, add, 0x40] = *before + && let [cmp @ .., 0x72, 0xf1] = after + && let Some((a, b)) = compare_registers(cmp) + && load & 0xc7 == 0xc0 + && a == (load >> 3) & 7 | (rex & 4) << 1 + && add & 0xf8 == 0xc0 + && a == add & 7 | (add_rex & 1) << 3 + && a != 0 + && b != 0 + { + let limit = *gpr(context, b); + loop { + zero(context.Rax); + let next = *gpr(context, a); + if next >= limit { + break; + } + context.Rax = next; + *gpr(context, a) = next.wrapping_add(0x40); + } + context.EFlags = + context.EFlags & !CMP_FLAGS | cmp_flags(*gpr(context, a), limit); + context.Rip += 8; + return true; + } + } + zero(context.Rax); + context.Rip += 3; + true +} + +/// `cmp rm, reg` between 64-bit registers (`REX.W 39 /r`): (`rm`, `reg`). +fn compare_registers(code: &[u8]) -> Option<(u8, u8)> { + let &[rex @ 0x48..=0x4f, 0x39, modrm] = code else { + return None; + }; + (modrm >> 6 == 3).then_some((modrm & 7 | (rex & 1) << 3, (modrm >> 3) & 7 | (rex & 4) << 1)) +} + /// The general register numbered `n` as instructions encode it. fn gpr(context: &mut CONTEXT, n: u8) -> &mut u64 { match n & 15 { @@ -812,6 +913,74 @@ mod tests { std::arch::asm!(".byte 0x0f, 0x01, 0xfa", ".byte 0x0f, 0x01, 0xfb", in("rax") at, in("ecx") 0, in("edx") 0) }; + // rdpru of MPERF: a count in edx:eax, their high halves clear. + let (low, high): (u64, u64); + // SAFETY: touches only the named registers. + unsafe { + std::arch::asm!(".byte 0x0f, 0x01, 0xfd", + out("rax") low, inout("rcx") 0u64 => _, out("rdx") high) + }; + assert_ne!(high << 32 | low, 0); + assert!(high >> 32 == 0 && low >> 32 == 0); + } + + /// The flags a native `cmp a, b` leaves. + fn native_compare(a: u64, b: u64) -> u32 { + let flags: u64; + // SAFETY: compares two registers and reads the flags. + unsafe { + std::arch::asm!("cmp {a}, {b}", "pushfq", "pop {f}", + a = in(reg) a, b = in(reg) b, f = out(reg) flags) + }; + flags as u32 & CMP_FLAGS + } + + #[test] + fn compare_sets_flags_like_the_cpu() { + let values = [0, 1, 0x40, 0x7f, 0x80, 0xff, 1 << 63, (1 << 63) - 1, !0, !0 - 0x40]; + for a in values { + for b in values { + assert_eq!(cmp_flags(a, b), native_compare(a, b), "cmp {a:#x}, {b:#x}"); + } + } + } + + #[test] + fn clzero_loops_end_like_their_last_pass() { + report_crashes(); + #[repr(align(64))] + struct Lines([u8; 192]); + let zeroed = |l: &Lines| [l.0[0] == 0, l.0[64] == 0, l.0[128] == 0]; + // clzero; add rax, 0x40; cmp rax, r10; jb + let mut mem = Lines([0xff; 192]); + let start = mem.0.as_mut_ptr() as u64; + let (end, flags): (u64, u64); + // SAFETY: zeroes the first two lines of `mem`. + unsafe { + std::arch::asm!( + ".byte 0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x40, 0x4c, 0x39, 0xd0, 0x72, 0xf4", + "pushfq", "pop {f}", + inout("rax") start => end, in("r10") start + 100, f = out(reg) flags) + }; + assert_eq!(end, start + 128); + assert_eq!(flags as u32 & CMP_FLAGS, native_compare(end, start + 100)); + assert_eq!(zeroed(&mem), [true, true, false]); + // mov rax, rdx; add rdx, 0x40; clzero; cmp rdx, r8; jb + let mut mem = Lines([0xff; 192]); + let start = mem.0.as_mut_ptr() as u64; + let (last, next, flags): (u64, u64, u64); + // SAFETY: zeroes the last two lines of `mem`. + unsafe { + std::arch::asm!( + ".byte 0x48, 0x89, 0xd0, 0x48, 0x83, 0xc2, 0x40, 0x0f, 0x01, 0xfc", + ".byte 0x4c, 0x39, 0xc2, 0x72, 0xf1", + "pushfq", "pop {f}", + out("rax") last, inout("rdx") start + 64 => next, in("r8") start + 192, + f = out(reg) flags) + }; + assert_eq!((last, next), (start + 128, start + 192)); + assert_eq!(flags as u32 & CMP_FLAGS, native_compare(next, start + 192)); + assert_eq!(zeroed(&mem), [false, true, true]); } fn reg(low: u64, high: u64) -> M128A { @@ -872,6 +1041,111 @@ mod tests { assert!(line.0[64..].iter().all(|&b| b == 0xff)); } + /// Gives `code` to the emulation as if it faulted at `code[at]` with + /// `context` as the saved state, on any CPU; returns whether it + /// emulated and leaves the state after in `context`. + fn emulate_in(code: &[u8], at: usize, context: &mut CONTEXT) -> bool { + // At a fixed place in a page, so the loops' neighbours are always + // read (they are not near a page's edges). + #[repr(align(4096))] + struct Page([u8; 4096]); + let mut page = Box::new(Page([0xcc; 4096])); + let bytes = &mut page.0[0x800..]; + bytes[..code.len()].copy_from_slice(code); + context.Rip = bytes.as_ptr() as u64 + at as u64; + // SAFETY: a zeroed record is valid; the emulation reads only + // `bytes` and writes `context` and the lines the caller owns. + unsafe { + let mut record: EXCEPTION_RECORD = std::mem::zeroed(); + record.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION; + let mut pointers = EXCEPTION_POINTERS { + ExceptionRecord: &mut record, + ContextRecord: context, + }; + let emulated = emulate_amd_only(&mut pointers); + context.Rip -= bytes.as_ptr() as u64; + emulated + } + } + + #[test] + fn emulated_clzero_loops_end_like_their_last_pass() { + #[repr(align(64))] + struct Lines([u8; 192]); + let zeroed = |l: &Lines| [l.0[0] == 0, l.0[64] == 0, l.0[128] == 0]; + // clzero; add rax, 0x40; cmp rax, r10; jb + let mut mem = Lines([0xff; 192]); + let start = mem.0.as_mut_ptr() as u64; + // SAFETY: an all-zero context is valid. + let mut context: CONTEXT = unsafe { std::mem::zeroed() }; + context.Rax = start; + context.R10 = start + 100; + context.EFlags = 0x202 | CMP_FLAGS; + let code = [0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x40, 0x4c, 0x39, 0xd0, 0x72, 0xf4]; + assert!(emulate_in(&code, 0, &mut context)); + assert_eq!((context.Rip, context.Rax), (12, start + 128)); + assert_eq!(context.EFlags, 0x202 | native_compare(start + 128, start + 100)); + assert_eq!(zeroed(&mem), [true, true, false]); + // mov rax, rdx; add rdx, 0x40; clzero; cmp rdx, r8; jb (faults at clzero, + // after the first pass's mov and add) + let mut mem = Lines([0xff; 192]); + let start = mem.0.as_mut_ptr() as u64; + // SAFETY: an all-zero context is valid. + let mut context: CONTEXT = unsafe { std::mem::zeroed() }; + context.Rax = start + 64; + context.Rdx = start + 128; + context.R8 = start + 192; + let code = [ + 0x48, 0x89, 0xd0, 0x48, 0x83, 0xc2, 0x40, 0x0f, 0x01, 0xfc, 0x4c, 0x39, 0xc2, 0x72, + 0xf1, + ]; + assert!(emulate_in(&code, 7, &mut context)); + assert_eq!((context.Rip, context.Rax, context.Rdx), (15, start + 128, start + 192)); + assert_eq!(context.EFlags, native_compare(start + 192, start + 192)); + assert_eq!(zeroed(&mem), [false, true, true]); + // cmp rax, rax is not the loop (the limit would move with rax): one + // line, flags untouched. + let mut mem = Lines([0xff; 192]); + // SAFETY: an all-zero context is valid. + let mut context: CONTEXT = unsafe { std::mem::zeroed() }; + context.Rax = mem.0.as_mut_ptr() as u64; + context.EFlags = 0x202; + let code = [0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x40, 0x48, 0x39, 0xc0, 0x72, 0xf4]; + assert!(emulate_in(&code, 0, &mut context)); + assert_eq!((context.Rip, context.EFlags), (3, 0x202)); + assert_eq!(zeroed(&mem), [true, false, false]); + // Any other neighbours: one line, then the next instruction. + let mut mem = Lines([0xff; 192]); + // SAFETY: an all-zero context is valid. + let mut context: CONTEXT = unsafe { std::mem::zeroed() }; + context.Rax = mem.0.as_mut_ptr() as u64 + 70; + context.R10 = !0; + let code = [0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x20, 0x4c, 0x39, 0xd0, 0x72, 0xf4]; + assert!(emulate_in(&code, 0, &mut context)); + assert_eq!(context.Rip, 3); + assert_eq!(zeroed(&mem), [false, true, false]); + } + + #[test] + fn emulated_rdpru_reads_known_counters_and_keeps_flags() { + let cases = [(0, true), (1, true), (2, false), (0x1_0000_0000, true)]; + let starts = [0x202, 0x202 | CMP_FLAGS]; + for ((ecx, known), flags) in cases.into_iter().flat_map(|c| starts.map(|f| (c, f))) { + // SAFETY: an all-zero context is valid. + let mut context: CONTEXT = unsafe { std::mem::zeroed() }; + context.Rcx = ecx; + context.Rax = !0; + context.Rdx = !0; + context.EFlags = flags; + assert!(emulate_in(&[0x0f, 0x01, 0xfd], 0, &mut context)); + assert_eq!(context.Rip, 3); + assert_eq!(context.EFlags, flags, "ecx {ecx:#x}"); + let count = context.Rdx << 32 | context.Rax; + assert!(context.Rax >> 32 == 0 && context.Rdx >> 32 == 0); + assert_eq!(count != 0, known, "ecx {ecx:#x}"); + } + } + #[test] fn emulated_monitorx_and_mwaitx_are_skipped() { let mut xmm = [reg(1, 2); 16]; From 8b4f50f2e1bd8c44a0ec713416ce4dc5672d5ac7 Mon Sep 17 00:00:00 2001 From: Diego Date: Mon, 23 Nov 2026 22:31:59 -0300 Subject: [PATCH 215/445] fix(pe): validate section raw data bounds (cherry picked from commit e57e76a7b4058e50d665ddcc9a11eb3cd4de4e7d) --- crates/victory-pe/src/image.rs | 95 +++++++++++++++++++++++++++++++++- 1 file changed, 94 insertions(+), 1 deletion(-) diff --git a/crates/victory-pe/src/image.rs b/crates/victory-pe/src/image.rs index fc8f0f6..aaf0009 100644 --- a/crates/victory-pe/src/image.rs +++ b/crates/victory-pe/src/image.rs @@ -143,7 +143,7 @@ impl ImageInfo { ))); } - let sections = file + let sections: Vec = file .section_table() .iter() .map(|s| SectionInfo { @@ -156,6 +156,31 @@ impl ImageInfo { }) .collect(); + // Validate section raw-data boundaries before accepting + // the PE image. + for section in §ions { + if section.file_size == 0 { + continue; + } + + let start = u64::from(section.file_offset); + let size = u64::from(section.file_size); + + let Some(end) = start.checked_add(size) else { + return Err(PeError::Malformed(format!( + "section '{}' has invalid raw-data bounds", + section.name + ))); + }; + + if end > data.len() as u64 { + return Err(PeError::Malformed(format!( + "section '{}' extends beyond file bounds", + section.name + ))); + } + } + let dir_present = |index: usize| { file.data_directory(index) .is_some_and(|d| d.virtual_address.get(LE) != 0 && d.size.get(LE) != 0) @@ -505,6 +530,74 @@ mod tests { d } + #[test] + fn rejects_section_extending_beyond_file() { + // Create a synthetic PE image. + let mut data = synthetic_image(&vec![0u8; 0x200]); + + // Remove the export directory to isolate section validation. + let opt = 0x58; + data[opt + 112..opt + 120].fill(0); + + // Verify the baseline PE is accepted. + assert!( + ImageInfo::parse(&data).is_ok(), + "baseline synthetic image must be valid" + ); + + // The section header starts after the 240-byte optional header. + let sec = opt + 240; + + // Declare 4096 bytes of raw section data. + // The actual file contains only 1024 bytes. + data[sec + 16..sec + 20].copy_from_slice(&0x1000u32.to_le_bytes()); + + // Investigate whether the parser rejects this malformed image. + assert!( + ImageInfo::parse(&data).is_err(), + "section extends beyond physical file bounds" + ); + } + + #[test] + fn accepts_section_ending_at_file_boundary() { + let mut data = synthetic_image(&vec![0u8; 0x200]); + + // Disable the export directory to isolate section validation. + let opt = 0x58; + data[opt + 112..opt + 120].fill(0); + + // Raw section: offset 0x200 + size 0x200 = file length 0x400. + let info = ImageInfo::parse(&data); + + assert!( + info.is_ok(), + "section ending exactly at EOF should be accepted" + ); + } + + #[test] + fn accepts_section_with_zero_raw_size() { + let mut data = synthetic_image(&vec![0u8; 0x200]); + + // Disable the export directory. + let opt = 0x58; + data[opt + 112..opt + 120].fill(0); + + // Section header begins after the optional header. + let sec = opt + 240; + + // A section may occupy virtual memory without having raw data. + data[sec + 16..sec + 20].copy_from_slice(&0u32.to_le_bytes()); + + let info = ImageInfo::parse(&data); + + assert!( + info.is_ok(), + "section with zero raw size should be accepted" + ); + } + #[test] fn unused_export_slots_are_not_exports() { // Ordinal base 1; three address slots: "alpha", an unused hole (0), From 91d41b2c9017821fc92ad3c1c606f87b7ed172a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9rez?= Date: Tue, 24 Nov 2026 02:34:58 +0100 Subject: [PATCH 216/445] Loader: suspend a thread before reading its TEB; skip bad dump times Stack dumps (VICTORY_STACKS, diagnostics builds) read another thread's TEB right after NtQueryInformationThread and suspended it only later: a thread exiting in between frees its TEB, and the read faults. The thread is now suspended first and resumed on every way out. The dump times went through Duration::from_secs_f64, which panics on `inf` or `1e20`, killing the dump thread (the crash hook logs it as a crash). They are parsed by `schedule` now, which leaves out NaN and times no Duration holds. 1 new test. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit acdcc41687be2ecd2bf2efc43ab7449329483382) --- crates/victory-loader/src/stacks.rs | 58 +++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 15 deletions(-) diff --git a/crates/victory-loader/src/stacks.rs b/crates/victory-loader/src/stacks.rs index 1d30910..214dda9 100644 --- a/crates/victory-loader/src/stacks.rs +++ b/crates/victory-loader/src/stacks.rs @@ -27,21 +27,30 @@ pub fn dump_stacks_on_schedule() { let Ok(list) = std::env::var("VICTORY_STACKS") else { return; }; - let mut times: Vec = list - .split(',') - .filter_map(|t| t.trim().parse().ok()) - .collect(); - times.sort_by(f64::total_cmp); + let times = schedule(&list); let start = std::time::Instant::now(); std::thread::spawn(move || { - for t in times { - let at = std::time::Duration::from_secs_f64(t.max(0.0)); + for at in times { std::thread::sleep(at.saturating_sub(start.elapsed())); dump_stacks(); } }); } +/// The times in a `VICTORY_STACKS` list (seconds, comma-separated), in +/// order. Negative times are now; times no `Duration` holds (`inf`, `NaN`, +/// `1e20`) are left out instead of panicking the dump thread. +fn schedule(list: &str) -> Vec { + let mut times: Vec<_> = list + .split(',') + .filter_map(|t| t.trim().parse::().ok()) + .filter(|t| !t.is_nan()) + .filter_map(|t| std::time::Duration::try_from_secs_f64(t.max(0.0)).ok()) + .collect(); + times.sort(); + times +} + /// `THREAD_BASIC_INFORMATION` (ntddk). #[repr(C)] struct BasicInfo { @@ -125,6 +134,12 @@ fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { priority: 0, base_priority: 0, }; + // Suspended first: a running thread may exit and free its TEB between + // the query and the read below. + // SAFETY: a thread of this process that is not this one. + if unsafe { SuspendThread(thread) } == u32::MAX { + return (frames, (0, 0)); + } // SAFETY: writes `info`, whose layout and size are the system's. let status = unsafe { NtQueryInformationThread( @@ -136,21 +151,20 @@ fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { ) }; if status != 0 || info.teb.is_null() { + // SAFETY: suspended above. + unsafe { ResumeThread(thread) }; return (frames, (0, 0)); } - // SAFETY: the TEB of a live thread of this process: its NT_TIB holds - // the stack base at +8 and the stack limit at +0x10. + // SAFETY: the TEB of a suspended thread of this process: its NT_TIB + // holds the stack base at +8 and the stack limit at +0x10. let (high, low) = unsafe { (info.teb.add(1).read(), info.teb.add(2).read()) }; // SAFETY: zeroed is a valid CONTEXT. let mut context = Aligned(unsafe { std::mem::zeroed() }); context.0.ContextFlags = CONTEXT_FULL_AMD64; - // SAFETY: suspends, reads and resumes a thread that is not this one; - // nothing between suspend and resume allocates or takes a lock the - // thread could hold besides the unwinder's own. + // SAFETY: reads and resumes the thread suspended above; nothing until + // the resume allocates or takes a lock the thread could hold besides + // the unwinder's own. unsafe { - if SuspendThread(thread) == u32::MAX { - return (frames, (info.priority, info.base_priority)); - } if GetThreadContext(thread, &mut context.0) != 0 { unwind_into(context.0, low, high, &mut frames); } @@ -221,4 +235,18 @@ mod tests { stop_tx.send(()).unwrap(); parked.join().unwrap(); } + + /// Times no `Duration` holds are left out instead of panicking the dump + /// thread (`from_secs_f64` panicked on `inf`); the rest come in order. + #[test] + fn schedules_skip_times_out_of_range() { + let secs = |list| { + schedule(list) + .iter() + .map(|d| d.as_secs_f64()) + .collect::>() + }; + assert_eq!(secs("30, 5,x,-2,inf,NaN,1e20"), [0.0, 5.0, 30.0]); + assert!(schedule("").is_empty()); + } } From 3d567d4bb32d04823e5a4f6a6db19f80adc99a06 Mon Sep 17 00:00:00 2001 From: Maraco91 <43787609+Maraco91@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:45:47 +0100 Subject: [PATCH 217/445] XAsync: a new block where a result was left behind begins a call Calls are filed by their block's address, and a call that succeeded with a result stays filed until XAsyncGetResult takes it. XAsyncBegin refused any block whose address had a call filed. So when a title never took a result and freed the block, the next block it was given at that address could not begin a call: E_INVALIDARG, every time, with the old call's provider never cleaned up. A zeroed block is a new one: the block of a result left behind holds the result's size, so it never reads zero. XAsyncBegin now ends a finished call filed under the address of a zeroed block (its provider gets its cleanup) and begins the new one. A call still in flight keeps its address, and a block still holding a result is refused as before. Co-Authored-By: Claude Fable 5.2 (cherry picked from commit 5cff0007a525b83f5c69912d7a38f53c6dafcfef) --- crates/victory-hle/src/modules/xasync.rs | 78 +++++++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index 04fbe08..dc7b2ed 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -545,6 +545,12 @@ fn status(block: *mut AsyncBlock) -> HRESULT { words(block).0.load(Ordering::Acquire) as u32 as i32 } +/// Whether the block's system area is all zero, as in a block not yet used. +fn zeroed(block: *mut AsyncBlock) -> bool { + // SAFETY: the title's block, whose system area is ours to read. + unsafe { std::ptr::addr_of!((*block).internal).read_volatile() == [0; 4] } +} + fn release(block: *mut AsyncBlock) { // Unlocked before the provider runs: it may call back into us. let removed = lock(&CALLS).remove(&(block as usize)); @@ -563,9 +569,23 @@ pub fn XAsyncBegin( let Some(provider) = provider else { return E_INVALIDARG; }; - if block.is_null() || call(block).is_some() { + if block.is_null() { return E_INVALIDARG; } + if let Some(left) = call(block) { + // Calls are filed by block address, and one that succeeded stays + // filed until its result is taken. A title that never takes it and + // frees the block may get the same address for its next one, which + // it zeroes as every new block must be; the block of a result left + // behind never reads zero (it holds the result's size). So this is + // a new block, and the call left behind ends here. A call in flight + // keeps its address, and a block still holding a result is in use. + let over = *lock(&left.done); + if !(over && zeroed(block)) { + return E_INVALIDARG; + } + release(block); + } let (status, size) = words(block); status.store(E_PENDING as u32 as usize, Ordering::Release); size.store(0, Ordering::Release); @@ -1143,6 +1163,62 @@ mod tests { COMPLETED.fetch_add(1, Ordering::SeqCst); } + /// A title that never takes a call's result and frees its block: the + /// next block allocated at that address (zeroed, as a new block must + /// be) begins a call like any other. + #[test] + fn a_new_block_where_a_result_was_left_begins_a_call() { + static CLEANED: AtomicU32 = AtomicU32::new(0); + /// Completes at once with one byte to fetch; counts its cleanups. + extern "system" fn left(op: u32, data: *const ProviderData) -> HRESULT { + match op { + // SAFETY: the runtime passes valid provider data. + OP_BEGIN => XAsyncComplete(unsafe { (*data).block }, S_OK, 1), + OP_CLEANUP => drop(CLEANED.fetch_add(1, Ordering::SeqCst)), + _ => {} + } + S_OK + } + /// Never completes by itself. + extern "system" fn idle(_: u32, _: *const ProviderData) -> HRESULT { + S_OK + } + let fresh = || AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + let (none, identity) = (std::ptr::null_mut(), 0x1e as *const c_void); + let begin = |block: &mut AsyncBlock, provider: Provider| { + XAsyncBegin(block, none, identity, std::ptr::null(), Some(provider)) + }; + + let mut block = fresh(); + assert_eq!(begin(&mut block, left), S_OK); + assert_eq!(XAsyncGetStatus(&mut block, false), S_OK); + // The block as the call left it is still that call's. + assert_eq!(begin(&mut block, left), E_INVALIDARG); + assert_eq!(CLEANED.load(Ordering::SeqCst), 0); + + // Freed with its result never taken, and a new block in its place. + block = fresh(); + assert_eq!(finished_with(&mut block, identity, Ok(vec![9])), S_OK); + assert_eq!(CLEANED.load(Ordering::SeqCst), 1, "the call left behind"); + let mut value = 0u8; + assert_eq!(result(&mut block, identity, &mut value), S_OK); + assert_eq!(value, 9); + assert!(call(&mut block).is_none()); + + // A call still in flight keeps its address, whatever the block holds. + let mut block = fresh(); + assert_eq!(begin(&mut block, idle), S_OK); + block = fresh(); + assert_eq!(begin(&mut block, left), E_INVALIDARG); + XAsyncComplete(&mut block, E_ABORT, 0); + assert!(call(&mut block).is_none()); + } + #[test] fn async_calls_complete_and_return_results() { let mut q = std::ptr::null(); From 7e4bb28d04f42ff13c5a2c85ee79fea502439946 Mon Sep 17 00:00:00 2001 From: AnoHunted <360473103+AnoHunted@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:47:57 +0000 Subject: [PATCH 218/445] Audio: an XMA read block past the ring's end wraps instead of filling forever The decoder fills an XMA voice's output ring until the write block (word 0, bits 27-31) comes round to the title's read block (word 9, bits 0-4). The write block wraps modulo the ring size (word 0, bits 22-26), and so does a read block moved on by command 18, but a read block the title set up at or past the ring's end was compared as it was: no write block ever equalled it. With a stream that loops forever the pass never ended, holding that voice's lock, so the title's next command on the voice (advance, disable) waited for good, and releasing the context arrays did too. Take the read block modulo the ring size as well, as the write side already does. A test sets up read block 6 on a ring of four with an endless loop and requires the pass to end within seconds, with blocks 0 and 1 filled. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 1054fe87de08038e887d6f7c6f44e5b07ac7a9f9) --- crates/victory-hle/src/modules/audio.rs | 86 ++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index 42f8746..644e032 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -533,7 +533,11 @@ fn pump(context: Context, voice: &mut Voice) { voice.trace.produced += SAMPLES_PER_BLOCK / context.channels(); let write = (write + 1) % size; context.set_field(0, 27, 5, write); - if write == context.field(9, 0, 5) { + // The read block is the title's: taken modulo the ring like the + // write block and `advance_read`'s. Compared as it is, one at or + // past the end would never be met, and a stream that loops would + // keep this voice (and its lock) filling forever. + if write == context.field(9, 0, 5) % size { // Full: nothing more until the title advances its read block. context.set_field(1, 31, 1, 0); } @@ -1007,6 +1011,86 @@ mod tests { data } + /// A read block past the end of the ring (6 on a ring of four) is block + /// 2 of it: a stream that loops forever fills blocks 0 and 1 and the + /// pass ends. It used to fill the ring for good, holding the voice. + #[test] + fn xma_read_blocks_past_the_ring_end_wrap() { + let _serial = lock(&CONTEXT_TESTS); + let mut request = ShapeContexts { + counts: [0, 0, 0, 0, 4, 0], + arrays: [std::ptr::null_mut(); 6], + apu: [0; 6], + }; + assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK); + let context = Context(request.arrays[4].cast::().wrapping_add(16)); + let (mut input, mut input_apu) = (std::ptr::null_mut(), 0); + assert_eq!(ApuAlloc(&mut input, &mut input_apu, 0x1000, 0x800, 1), S_OK); + let stream = silent_stream(); + // SAFETY: two packets were allocated. + unsafe { std::ptr::copy_nonoverlapping(stream.as_ptr(), input.cast(), stream.len()) }; + let (mut output, mut output_apu) = (std::ptr::null_mut(), 0); + assert_eq!( + ApuAlloc(&mut output, &mut output_apu, 0x400, 0x100, 2), + S_OK + ); + // SAFETY: the ring was just allocated. + unsafe { output.cast::().write_bytes(0x55, 0x400) }; + + // As in `xma_contexts_decode_into_their_output_rings`, but looping + // forever from the first frame to the last, and read block 6. + context.set(0, 2 | 255 << 12 | 1 << 20 | 4 << 22); + context.set(1, 1 << 31 | 3 << 27); + context.set(2, 32); + context.set(3, 32); + context.set(4, (xma::PACKET_BYTES * 8 + 32 + 2 * 31) as u32); + context.set(5, input_apu); + context.set(7, output_apu); + context.set(9, 6); + + let mut acp = std::ptr::null_mut(); + assert_eq!(AcpHalCreate(&mut acp), S_OK); + // SAFETY: just created. + let m = unsafe { (*acp).vtable }; + assert_eq!((m.connect)(acp, 0x1000, 0x1000), S_OK); + let submit = |command: u32, words: &[u32]| { + assert_eq!( + (m.submit)(acp, command, 0xf1, u32::MAX, words.as_ptr().cast(), 0), + S_OK + ); + }; + submit(ENABLE_XMA, &[1]); + // A pass on a thread of its own (the decoding thread runs them too), + // so that one that never ends fails this test instead of hanging it. + let (done, passed) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + xma().pump(); + let _ = done.send(()); + }); + let five = std::time::Duration::from_secs(5); + let wait = || passed.recv_timeout(five).is_ok(); + let ended = wait(); + if !ended { + // End it as a full ring would, to release the contexts below. + context.set_field(1, 31, 1, 0); + assert!(wait(), "the XMA pass did not end on a full ring either"); + } + let (write, writable) = (context.field(0, 27, 5), context.field(1, 31, 1)); + // SAFETY: the ring. + let ring = unsafe { std::slice::from_raw_parts(output.cast::(), 0x400) }.to_vec(); + + submit(DISABLE_XMA, &[1]); + (m.release)(acp); + ApuFree(input); + ApuFree(output); + assert_eq!(AcpHalReleaseShapeContexts(), S_OK); + assert!(ended, "the XMA pass never ended"); + // Blocks 0 and 1 written (silence), 2 and 3 left for the title. + assert_eq!((write, writable), (2, 0)); + assert!(ring[..0x200].iter().all(|&b| b == 0)); + assert!(ring[0x200..].iter().all(|&b| b == 0x55)); + } + #[test] fn xma_contexts_decode_into_their_output_rings() { let _serial = lock(&CONTEXT_TESTS); From 89fb38b8cd64ecc4a5461ff8e5445c7d08cd0190 Mon Sep 17 00:00:00 2001 From: Maraco91 <43787609+Maraco91@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:55:47 +0100 Subject: [PATCH 219/445] GPU: every object answers for IUnknown No graphics object's interface list holds IUnknown, so QueryInterface for it (and every call that hands out an object by interface id) said E_NOINTERFACE and returned null. COM code asks for it to compare two pointers for identity, to keep an object as a plain reference, or to pass it on to an API that takes any object. object::is, which all of those go through, now also matches IUnknown. The DXGI device answers with the D3D12 device, which it already stands for: one pointer whichever of the object's interfaces is asked. Co-Authored-By: Claude Fable 5.2 (cherry picked from commit 92f2c60c8159e34a47570aa81f3d25624cc6db5c) --- crates/victory-gpu/src/object.rs | 39 ++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/object.rs b/crates/victory-gpu/src/object.rs index 156c92d..fd7d506 100644 --- a/crates/victory-gpu/src/object.rs +++ b/crates/victory-gpu/src/object.rs @@ -101,10 +101,13 @@ pub(crate) fn answer(kind: usize, iid: *const Iid, found: Option, out: *mu hr } -/// Whether `iid` is one of `known`. +/// `IUnknown`, which every COM object answers for. +pub(crate) const IUNKNOWN: Iid = guid(0, 0, 0, [0xc0, 0, 0, 0, 0, 0, 0, 0x46]); + +/// Whether `iid` is one of `known`, or `IUnknown`. pub(crate) fn is(iid: *const Iid, known: &[Iid]) -> bool { // SAFETY: the title passes an interface id (null is tolerated). - unsafe { iid.as_ref() }.is_some_and(|i| known.contains(i)) + unsafe { iid.as_ref() }.is_some_and(|i| *i == IUNKNOWN || known.contains(i)) } /// Hands a new object to the title as one of `known`, or drops it. `T` @@ -381,4 +384,36 @@ mod tests { assert_eq!(g[..4], [0xf1, 0x19, 0x98, 0x18]); assert_eq!(guid_text(&g), "189819f1-1db6-4b57-be54-1821339b85f7"); } + + /// Every COM object answers for `IUnknown`, and with one pointer + /// whichever of its interfaces is asked: the object's identity. + #[test] + fn every_object_answers_for_iunknown() { + type Query = extern "system" fn(This, *const Iid, *mut This) -> HRESULT; + let unknown = |object: This| { + let mut found = std::ptr::null(); + let hr = slot::(object, 0)(object, &IUNKNOWN, &mut found); + (hr, found) + }; + let device = crate::device::device(); + let mut fence = std::ptr::null(); + let fence_iid = &crate::fence::FENCE_IIDS[0]; + assert_eq!( + crate::fence::create(std::ptr::null(), 0, 0, fence_iid, &mut fence), + S_OK + ); + assert_eq!(unknown(device), (S_OK, device)); + assert_eq!(unknown(fence), (S_OK, fence)); + // The DXGI device is the same object as the device it answers for. + assert_eq!(unknown(crate::dxgi::device()), (S_OK, device)); + // An id nobody has is still nobody's. + let mut found = fence; + let nobodys = guid(0x189819f1, 0x1db6, 0x4b57, [0xbe; 8]); + assert_eq!( + slot::(fence, 0)(fence, &nobodys, &mut found), + E_NOINTERFACE + ); + assert!(found.is_null()); + slot:: u32>(fence, 0x10)(fence); + } } From 410001269c087f1d464707d918dc4c5d727b6b96 Mon Sep 17 00:00:00 2001 From: marquezini Date: Mon, 23 Nov 2026 23:22:06 -0300 Subject: [PATCH 220/445] XStore: a store id without an installed package is an invalid argument XStoreQueryPackageIdentifier documents E_INVALIDARG for a store id that has no installed package. We returned XPackage's 0x89245208 instead. (cherry picked from commit e3bef089855cc4b463a0ce7e1a70f6abf7c859e5) --- crates/victory-hle/src/modules/xstore.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/victory-hle/src/modules/xstore.rs b/crates/victory-hle/src/modules/xstore.rs index 9e2b74b..3936b6c 100644 --- a/crates/victory-hle/src/modules/xstore.rs +++ b/crates/victory-hle/src/modules/xstore.rs @@ -7,7 +7,7 @@ use std::ffi::{c_char, c_void}; -use super::xasync::{self, AsyncBlock, E_ILLEGAL_METHOD_CALL}; +use super::xasync::{self, AsyncBlock, E_ILLEGAL_METHOD_CALL, E_INVALIDARG}; use super::xgameruntime::{ Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token, }; @@ -301,7 +301,8 @@ extern "system" fn install_async( } /// The game's own store id maps to its installation; nothing else is -/// installed. +/// installed, and any other id gets the documented E_INVALIDARG (not +/// XPackage's "could not resolve" error). extern "system" fn package_identifier( _: This, store_id: *const c_char, @@ -313,7 +314,7 @@ extern "system" fn package_identifier( Some(id) if !title.store_id.is_empty() && id == title.store_id => { put_string(&xpackage::identifier(), size, buffer, std::ptr::null_mut()) } - _ => xpackage::NO_PACKAGE, + _ => E_INVALIDARG, } } @@ -476,4 +477,15 @@ mod tests { &OBJECT, 0xb0 )(this, l)); } + + #[test] + fn a_store_id_without_a_package_is_an_invalid_argument() { + type Query = extern "system" fn(This, *const c_char, usize, *mut u8) -> HRESULT; + let query = method::(&OBJECT, 0x208); + let mut id = [0u8; 33]; + assert_eq!( + query(&OBJECT, c"9NOTINSTALLED".as_ptr(), 33, id.as_mut_ptr()), + E_INVALIDARG + ); + } } From c719d0cf2be52cbcd81ea42b124b7a422f833eed Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:27:24 +0100 Subject: [PATCH 221/445] HLE: load a host DLL outside the module cache's lock host::module held the module cache's lock while it called LoadLibraryExA. Loading a DLL that is not loaded yet takes the OS loader lock, and title code runs under that lock too (a title DLL's thread attach, TLS callbacks run as threads start), where it can need the cache: any first use of a host! function, or a late-bound title DLL. One thread holding the cache and waiting for the loader lock, another holding the loader lock and waiting for the cache: the process hangs, and cannot even exit, as ExitProcess needs the loader lock too. The cache is now looked up, then unlocked for the load, then locked again to keep the handle; a thread that loaded the same DLL meanwhile got the same module, which stays loaded. (cherry picked from commit c6959acba38304852c185bcd7bc2ba1478d6e0b2) --- crates/victory-hle/src/host.rs | 100 +++++++++++++++++++++++++++++++-- 1 file changed, 96 insertions(+), 4 deletions(-) diff --git a/crates/victory-hle/src/host.rs b/crates/victory-hle/src/host.rs index 8a2a875..7300687 100644 --- a/crates/victory-hle/src/host.rs +++ b/crates/victory-hle/src/host.rs @@ -122,11 +122,15 @@ mod imp { fn module(dll: &str) -> Option { let key = dll.to_ascii_lowercase(); - let mut cache = MODULES.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(&m) = cache.get(&key) { - return Some(m); + let cache = || MODULES.lock().unwrap_or_else(|e| e.into_inner()); + let cached = cache().get(&key).copied(); + if cached.is_some() { + return cached; } let name = CString::new(key.as_str()).ok()?; + // Not under the cache's lock: loading takes the OS loader lock, and + // title code that runs under that one (a DLL's thread attach, a TLS + // callback) may look a function up here. // System32 only: never pick up a same-named DLL from the current folder or PATH. // SAFETY: NUL-terminated DLL name; only allow-listed system DLLs get here. let handle = unsafe { @@ -136,7 +140,95 @@ mod imp { LOAD_LIBRARY_SEARCH_SYSTEM32, ) } as usize; - (handle != 0).then(|| *cache.entry(key).or_insert(handle)) + // A thread that loaded it meanwhile got the same module, which stays loaded. + (handle != 0).then(|| *cache().entry(key).or_insert(handle)) + } + + #[cfg(test)] + mod tests { + use std::ffi::c_void; + use std::ptr::{null, null_mut}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::{Duration, Instant}; + + use windows_sys::Win32::System::Threading::{ + CreateThread, INFINITE, Sleep, WaitForSingleObject, + }; + + const CHILD: &str = "VICTORY_HOST_LOCK_CHILD"; + static ARMED: AtomicBool = AtomicBool::new(false); + static IN_ATTACH: AtomicBool = AtomicBool::new(false); + static STARTED: AtomicBool = AtomicBool::new(false); + + /// Runs as title TLS callbacks do: under the loader lock, as a new + /// thread starts. + #[used] + #[unsafe(link_section = ".CRT$XLY")] + static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = attach; + + unsafe extern "system" fn attach(_: *mut c_void, reason: u32, _: *mut c_void) { + const DLL_THREAD_ATTACH: u32 = 2; + if reason == DLL_THREAD_ATTACH && ARMED.swap(false, Ordering::SeqCst) { + IN_ATTACH.store(true, Ordering::SeqCst); + // SAFETY: a plain sleep, for the other thread to start a load. + unsafe { Sleep(500) }; + let found = super::super::function("kernel32.dll", "GetTickCount"); + assert!(found.is_some()); + } + } + + unsafe extern "system" fn idle(_: *mut c_void) -> u32 { + 0 + } + + /// One thread loads a DLL nothing has loaded yet, which needs the + /// loader lock, while another thread's attach holds that lock and + /// looks a function up. Run in a child process: a deadlock inside the + /// loader keeps a process from exiting, so the parent kills it. + #[test] + fn loading_a_host_dll_does_not_block_thread_attach() { + if std::env::var_os(CHILD).is_none() { + let name = "host::imp::tests::loading_a_host_dll_does_not_block_thread_attach"; + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", name]) + .env(CHILD, "1") + .spawn() + .unwrap(); + let start = Instant::now(); + loop { + if let Some(status) = child.try_wait().unwrap() { + assert!(status.success()); + return; + } + if start.elapsed() > Duration::from_secs(30) { + child.kill().unwrap(); + panic!("deadlock: a host DLL loads under the module cache's lock"); + } + std::thread::sleep(Duration::from_millis(50)); + } + } + // The attach below only needs the cache, no load of its own. + assert!(super::super::function("kernel32.dll", "GetTickCount").is_some()); + let loader = std::thread::spawn(|| { + STARTED.store(true, Ordering::SeqCst); + while !IN_ATTACH.load(Ordering::SeqCst) { + std::hint::spin_loop(); + } + super::super::function("cabinet.dll", "FDICreate") + }); + // Its own attach is over: the next is the thread below. + while !STARTED.load(Ordering::SeqCst) { + std::hint::spin_loop(); + } + ARMED.store(true, Ordering::SeqCst); + let (security, start) = (std::ptr::null(), Some(idle as _)); + // SAFETY: a thread that returns at once. + let thread = unsafe { CreateThread(security, 0, start, null(), 0, null_mut()) }; + assert!(!thread.is_null()); + assert!(loader.join().unwrap().is_some()); + // SAFETY: our own thread's handle. + unsafe { WaitForSingleObject(thread, INFINITE) }; + } } } From f4a7ae21ad011940d2ad4aab1497010c2f997aed Mon Sep 17 00:00:00 2001 From: Pedro Fortunato Date: Mon, 23 Nov 2026 23:29:52 -0300 Subject: [PATCH 222/445] fix(formats): reject overlapping texture depth slices (cherry picked from commit 93a24b7cdaeb0e7f132f711e9cbd9ba405b0f639) --- crates/victory-formats/src/texture.rs | 89 ++++++++++++++++++++++++++- 1 file changed, 86 insertions(+), 3 deletions(-) diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index fa719c9..450360c 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -639,11 +639,19 @@ impl Layout { } let n = self.desc.element_bytes as usize; let bytes = m.width as usize * n; + let slice_bytes = (m.height as usize - 1) + .checked_mul(row_pitch) + .and_then(|offset| offset.checked_add(bytes)) + .ok_or(Error::TooSmall)?; + + // Multiple depth slices must not overwrite each other. + if depth > 1 && depth_pitch < slice_bytes { + return Err(Error::TooSmall); + } + let need = (depth as usize - 1) .checked_mul(depth_pitch) - .zip((m.height as usize - 1).checked_mul(row_pitch)) - .and_then(|(depth_offset, row_offset)| depth_offset.checked_add(row_offset)) - .and_then(|offset| offset.checked_add(bytes)) + .and_then(|offset| offset.checked_add(slice_bytes)) .ok_or(Error::TooSmall)?; let (tiled_len, linear_len) = if DETILE { (src.len(), dst.len()) @@ -1138,6 +1146,81 @@ mod tests { ); } + fn volume_pitch_layout(swizzle: Swizzle) -> Layout { + Layout::new(&Desc { + dimension: Dimension::Tex3d, + depth: 2, + ..desc(4, 2, 1, 4, swizzle) + }) + .unwrap() + } + + #[test] + fn depth_pitch_rejects_overlapping_detile() { + for swizzle in [Swizzle::LINEAR, Swizzle::SW_4KB_S] { + let l = volume_pitch_layout(swizzle); + let tiled = vec![0x42; l.size as usize]; + let mut linear = [0xcc; 72]; + + for pitch in [0, 16, 35] { + assert_eq!( + l.detile(&tiled, 0, 0, &mut linear, 20, pitch), + Err(Error::TooSmall), + "{swizzle:?}, pitch {pitch}" + ); + + assert_eq!(linear, [0xcc; 72]); + } + } + } + + #[test] + fn depth_pitch_rejects_overlapping_tile() { + for swizzle in [Swizzle::LINEAR, Swizzle::SW_4KB_S] { + let l = volume_pitch_layout(swizzle); + let mut tiled = vec![0xcc; l.size as usize]; + let linear = [0x42; 72]; + + for pitch in [0, 16, 35] { + assert_eq!( + l.tile(&mut tiled, 0, 0, &linear, 20, pitch), + Err(Error::TooSmall), + "{swizzle:?}, pitch {pitch}" + ); + + assert!(tiled.iter().all(|&b| b == 0xcc)); + } + } + } + + #[test] + fn depth_pitch_accepts_exact_and_padded_slices() { + for swizzle in [Swizzle::LINEAR, Swizzle::SW_4KB_S] { + let l = volume_pitch_layout(swizzle); + + for pitch in [36usize, 40, 64] { + let len = pitch + 36; + let mut tiled = vec![0; l.size as usize]; + + let linear: Vec = (0..len).map(|i| i as u8).collect(); + + let mut back = vec![0xcc; len]; + + l.tile(&mut tiled, 0, 0, &linear, 20, pitch).unwrap(); + + l.detile(&tiled, 0, 0, &mut back, 20, pitch).unwrap(); + + for z in 0..2 { + for y in 0..2 { + let start = z * pitch + y * 20; + + assert_eq!(back[start..start + 16], linear[start..start + 16]); + } + } + } + } + } + #[test] fn volume_copy_rejects_overflowing_depth_pitch() { let layout = Layout::new(&Desc { From 803ada016200711bc9fffc0e5f195266be328eae Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:30:15 +0100 Subject: [PATCH 223/445] HLE: a '>' in a quoted manifest attribute does not end its tag The MicrosoftGame.config reader ended a tag at its first '>', but XML allows '>' unescaped inside an attribute value. A value with one (DefaultDisplayName="A > B") cut the tag short: its '/>' was never seen, so the element stayed open and every element after it was read as its child. Game/TitleId and the storage quota were then not found, and the title ran as id 00000000 with no storage quota, its saves and temporary files in that folder, without a warning. A tag now ends at the first '>' outside quotes. (cherry picked from commit d549b6397e3f40e77f9da670344aa15f12b26abb) --- crates/victory-hle/src/runtime.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index de8817d..e90aa58 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -140,7 +140,7 @@ fn elements(text: &str) -> Vec<(String, String)> { } else if rest.starts_with("").map(|e| e + 3) } else { - rest.find('>').map(|e| e + 1) + tag_end(rest) }; let Some(end) = end else { break }; let tag = &rest[1..end - 1]; @@ -173,6 +173,21 @@ fn elements(text: &str) -> Vec<(String, String)> { out } +/// Where the tag that starts `text` ends, past its `>`; a `>` in a quoted +/// attribute value is part of the value (XML allows it there unescaped). +fn tag_end(text: &str) -> Option { + let mut quote = None; + for (at, c) in text.char_indices() { + match (quote, c) { + (None, '"' | '\'') => quote = Some(c), + (Some(open), _) if c == open => quote = None, + (None, '>') => return Some(at + 1), + _ => {} + } + } + None +} + static TITLE: Mutex> = Mutex::new(None); pub fn set_title(title: Title) { @@ -223,6 +238,15 @@ pub fn use_console_timers() { mod tests { use super::*; + #[test] + fn a_quoted_angle_bracket_does_not_end_its_tag() { + let text = " B\" Description='x>y'/>\ + 639AA8DD\ + 64"; + let t = Title::from_manifest(text); + assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 64 << 20)); + } + #[test] fn reads_title_id_store_id_and_storage_quota() { let text = "\u{feff}\n\ From d02932f322d944ee00ad25e6e4a73889d3d21eb4 Mon Sep 17 00:00:00 2001 From: FIocker <4461558+FIocker@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:32:00 +0100 Subject: [PATCH 224/445] Shader info: show stage I/O even when instruction decoding fails Co-authored-by: Claude Opus 5.5 (cherry picked from commit e6ebec9ccf0bc27cfe0b5509ec3d07a0969eb25f) --- apps/victory/src/shader.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/apps/victory/src/shader.rs b/apps/victory/src/shader.rs index 779f61c..1c20285 100644 --- a/apps/victory/src/shader.rs +++ b/apps/victory/src/shader.rs @@ -113,6 +113,11 @@ pub fn run(paths: Vec, verbose: bool, disasm: bool) -> Result<()> { for n in &programs { *t.native_stages.entry(n.stage).or_default() += 1; list.push(format!("{:?} {} B", n.stage, n.code.len())); + if disasm { + listing.push(format!(" {:?} stage I/O: {:?}", n.stage, n.io)); + listing.extend(n.layout.iter().map(|p| format!(" {p:?}"))); + listing.extend(n.used.iter().map(|u| format!(" {u:?}"))); + } match gfx10::decode(&n.code) { Ok(insts) => { t.decoded += 1; @@ -122,9 +127,6 @@ pub fn run(paths: Vec, verbose: bool, disasm: bool) -> Result<()> { *t.unnamed.entry(key).or_default() += 1; } if disasm { - listing - .extend(n.layout.iter().map(|p| format!(" {p:?}"))); - listing.extend(n.used.iter().map(|u| format!(" {u:?}"))); listing.extend( insts.iter().map(|i| format_instruction(i, n.wave64)), ); From 2ea5f0f6f46ab5bb6fbc2e282ecc1068ddc50d9e Mon Sep 17 00:00:00 2001 From: marquezini Date: Mon, 23 Nov 2026 23:35:14 -0300 Subject: [PATCH 225/445] XGameUi: a text entry's limit is the console's XGameUiShowTextEntryAsync documents a 1024-character maximum on console, 1024 for a maxTextLength of 0, and 1024 for the Password scope whatever the title asks. 0 meant no limit here, larger limits were kept and the scope was ignored. (cherry picked from commit 936e5e51c91c7b380a4729aeaa2255824ce8085a) --- crates/victory-hle/src/modules/xgameui.rs | 69 ++++++++++++++++++++--- 1 file changed, 62 insertions(+), 7 deletions(-) diff --git a/crates/victory-hle/src/modules/xgameui.rs b/crates/victory-hle/src/modules/xgameui.rs index 9882b2e..663341b 100644 --- a/crates/victory-hle/src/modules/xgameui.rs +++ b/crates/victory-hle/src/modules/xgameui.rs @@ -1,6 +1,6 @@ //! System dialogs a title opens (XGameUi). A profile card has nothing to //! show and closes at once. Text entry opens a small host dialog (title, -//! description, default text, the length limit) on a thread of its own and +//! description, default text, the console's length limit) on a thread of its own and //! completes the call with what the user typed, or as cancelled (`E_ABORT`) //! when the dialog is dismissed or cannot open. #![allow(clippy::not_unsafe_ptr_arg_deref)] @@ -57,10 +57,11 @@ extern "system" fn text_entry_async( title: *const c_char, description: *const c_char, default: *const c_char, - _scope: u32, + scope: u32, max_length: u32, ) -> HRESULT { let [title, description, default] = [title, description, default].map(|t| text(t).unwrap_or_default()); + let max_length = max_length_for(scope, max_length); tracing::info!(title, description, max_length, "text entry"); xasync::pending_with(block, (&raw const TEXT).cast(), move || { match ask(&title, &description, &default, max_length) { @@ -102,14 +103,26 @@ extern "system" fn text_entry_result( put(used, written as u32) } -/// At most `max` characters (0: no limit). -fn limit(typed: &str, max: u32) -> String { - match max { - 0 => typed.to_owned(), - max => typed.chars().take(max as usize).collect(), +/// The console's most characters for a text entry. +const MAX_LENGTH: u32 = 1024; +/// `XGameUiTextEntryInputScope::Password`. +const PASSWORD: u32 = 31; + +/// The limit the console applies, as documented: the title's, at most +/// 1024; 1024 for 0 and for a password, whatever the title asks. +fn max_length_for(scope: u32, max: u32) -> u32 { + if max == 0 || scope == PASSWORD { + MAX_LENGTH + } else { + max.min(MAX_LENGTH) } } +/// At most `max` characters. +fn limit(typed: &str, max: u32) -> String { + typed.chars().take(max as usize).collect() +} + /// Asks the user in a modal host dialog; `None` if dismissed. #[cfg(not(test))] fn ask(title: &str, description: &str, default: &str, max: u32) -> Option { @@ -318,4 +331,46 @@ mod tests { assert_eq!((text(out.as_ptr()).as_deref(), used), (Some("abctyp"), 7)); assert_eq!(limit("\u{e9}t\u{e9}s", 3), "\u{e9}t\u{e9}"); } + + /// 0 and limits over 1024 mean 1024; a password ignores the title's. + #[test] + fn text_entry_limits_follow_the_console() { + assert_eq!(max_length_for(0, 0), 1024); + assert_eq!(max_length_for(0, 5000), 1024); + assert_eq!(max_length_for(0, 16), 16); + assert_eq!(max_length_for(PASSWORD, 8), 1024); + + type Entry = extern "system" fn( + This, + *mut AsyncBlock, + *const c_char, + *const c_char, + *const c_char, + u32, + u32, + ) -> HRESULT; + type Size = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT; + type Result_ = + extern "system" fn(This, *mut AsyncBlock, u32, *mut c_char, *mut u32) -> HRESULT; + let this: This = &OBJECT; + let entry = method::(&OBJECT, 0x88); + let null = std::ptr::null(); + let long = std::ffi::CString::new("a".repeat(2000)).unwrap(); + for (scope, max, default, expect) in [ + (0, 0, long.as_ptr(), 1025), + (PASSWORD, 8, c"abc".as_ptr(), 9), + ] { + let mut b = block(); + let title = c"Type".as_ptr(); + assert_eq!(entry(this, &mut b, title, null, default, scope, max), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + let mut size = 0; + assert_eq!(method::(&OBJECT, 0x90)(this, &mut b, &mut size), S_OK); + assert_eq!(size, expect, "scope {scope}, max {max}"); + let mut out = vec![0 as c_char; size as usize]; + let result = method::(&OBJECT, 0x98); + let used = std::ptr::null_mut(); + assert_eq!(result(this, &mut b, size, out.as_mut_ptr(), used), S_OK); + } + } } From 2e11203dfd0f613dcd164cf05491e4bcc6b60c76 Mon Sep 17 00:00:00 2001 From: marquezini Date: Mon, 23 Nov 2026 23:39:38 -0300 Subject: [PATCH 226/445] Kernel: GetModuleFileName of a title image into a null buffer A slice may not start at null, even an empty one, so asking for a title image's name with (NULL, 0) was undefined behaviour; a debug build aborted the process. A null buffer is now no buffer: nothing is written, 0 is returned and the last error is ERROR_INSUFFICIENT_BUFFER. (cherry picked from commit c000581df2cf12aaadfe49025f9abba8b5993c8e) --- crates/victory-hle/src/modules/kernel.rs | 37 +++++++++++++++++++----- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index d1604cc..83ce323 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -52,10 +52,7 @@ pub extern "system" fn GetModuleFileNameW(module: *mut c_void, out: *mut u16, si return host::get_module_file_name_w(module, out, size); }; let wide: Vec = path.encode_utf16().collect(); - // SAFETY: the title passes a buffer of `size` characters. - copy_truncated(&wide, unsafe { - std::slice::from_raw_parts_mut(out, size as usize) - }) + copy_truncated(&wide, title_buffer(out, size)) } /// See [`GetModuleFileNameW`]. @@ -63,10 +60,18 @@ pub extern "system" fn GetModuleFileNameA(module: *mut c_void, out: *mut u8, siz let Some(path) = title_path(module) else { return host::get_module_file_name_a(module, out, size); }; - // SAFETY: the title passes a buffer of `size` bytes. - copy_truncated(path.as_bytes(), unsafe { - std::slice::from_raw_parts_mut(out, size as usize) - }) + copy_truncated(path.as_bytes(), title_buffer(out, size)) +} + +/// The title's buffer of `size` elements; none for a null pointer (a slice +/// may not start at null, even an empty one, so `(NULL, 0)` would be +/// undefined behaviour). +fn title_buffer<'a, T>(out: *mut T, size: u32) -> &'a mut [T] { + if out.is_null() { + return &mut []; + } + // SAFETY: the title passes a buffer of `size` elements. + unsafe { std::slice::from_raw_parts_mut(out, size as usize) } } fn title_path(module: *mut c_void) -> Option { @@ -760,4 +765,20 @@ mod tests { assert!(!runtime.is_null()); assert_eq!(GetModuleHandleW(w("XGameRuntime.dll").as_ptr()), runtime); } + + /// No buffer: nothing written, the error says it was too small. + #[test] + fn a_title_image_name_into_no_buffer() { + let base = 0x7300_0000_0000; + runtime::set_image_path(base, std::path::Path::new(r"C:\title\game.exe")); + let module = base as *mut c_void; + assert_eq!(GetModuleFileNameW(module, std::ptr::null_mut(), 0), 0); + assert_eq!(GetModuleFileNameA(module, std::ptr::null_mut(), 0), 0); + #[cfg(windows)] + { + // SAFETY: reads this thread's last error. + let last = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + assert_eq!(last, ERROR_INSUFFICIENT_BUFFER); + } + } } From 5dcfa24dd5dab6169a76d16e9cd994742a8f0941 Mon Sep 17 00:00:00 2001 From: nathanbzrr Date: Tue, 24 Nov 2026 00:48:40 -0300 Subject: [PATCH 227/445] XStore: wire offline *Result slots and fix OOB XStoreShowProductPageUIResult slot (cherry picked from commit 2c22e2b2d23ef2c6e79e67d5cff51d5c8ec3475d) --- crates/victory-hle/src/modules/xstore.rs | 138 ++++++++++++++++++++++- 1 file changed, 133 insertions(+), 5 deletions(-) diff --git a/crates/victory-hle/src/modules/xstore.rs b/crates/victory-hle/src/modules/xstore.rs index 3936b6c..4cb6eb5 100644 --- a/crates/victory-hle/src/modules/xstore.rs +++ b/crates/victory-hle/src/modules/xstore.rs @@ -333,7 +333,7 @@ extern "system" fn unregister(_: This, _: Handle, _token: u64, _wait: bool) -> b true } -static VTABLE: Methods<76> = Methods([ +static VTABLE: Methods<77> = Methods([ missing::<0> as *const (), add_ref as *const (), add_ref as *const (), @@ -368,9 +368,9 @@ static VTABLE: Methods<76> = Methods([ missing::<31> as *const (), // 0xf8 missing::<32> as *const (), // 0x100 consumable_balance_async as *const (), // 0x108 - status as *const (), // 0x110 + count_status as *const (), // 0x110 report_fulfillment_async as *const (), // 0x118 - missing::<36> as *const (), // 0x120 + count_status as *const (), // 0x120 user_id_async as *const (), // 0x128 collections id size_status as *const (), // 0x130 string_status as *const (), // 0x138 @@ -384,11 +384,11 @@ static VTABLE: Methods<76> = Methods([ missing::<47> as *const (), // 0x178 missing::<48> as *const (), // 0x180 purchase_ui_async as *const (), // 0x188 - missing::<50> as *const (), // 0x190 + status as *const (), // 0x190 missing::<51> as *const (), // 0x198 rate and review missing::<52> as *const (), // 0x1a0 redeem_ui_async as *const (), // 0x1a8 - missing::<54> as *const (), // 0x1b0 + status as *const (), // 0x1b0 updates_async as *const (), // 0x1b8 count_status as *const (), // 0x1c0 array_status as *const (), // 0x1c8 @@ -410,6 +410,7 @@ static VTABLE: Methods<76> = Methods([ missing::<73> as *const (), // 0x248 associated products page missing::<74> as *const (), // 0x250 product_page_ui_async as *const (), // 0x258 + status as *const (), // 0x260 ]); #[cfg(test)] @@ -426,6 +427,133 @@ mod tests { } } + #[test] + fn offline_async_calls_report_network_error_from_their_result_slots() { + assert!(VTABLE.0.len() > 0x260 / 8); + + let this: This = &OBJECT; + type StoreIdAsync = + extern "system" fn(This, Handle, *const c_char, *mut AsyncBlock) -> HRESULT; + type ReportFulfillmentAsync = extern "system" fn( + This, + Handle, + *const c_char, + u32, + *const c_void, + *mut AsyncBlock, + ) -> HRESULT; + type PurchaseUiAsync = extern "system" fn( + This, + Handle, + *const c_char, + *const c_char, + *const c_char, + *mut AsyncBlock, + ) -> HRESULT; + type RedeemUiAsync = extern "system" fn( + This, + Handle, + *const c_char, + *const *const c_char, + usize, + bool, + *mut AsyncBlock, + ) -> HRESULT; + type StatusResult = extern "system" fn(This, *mut AsyncBlock) -> HRESULT; + type CountResult = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT; + + let mut b = block(); + assert_eq!( + method::(&OBJECT, 0x258)( + this, + handle(&CONTEXT), + c"9DUMMY".as_ptr(), + &mut b, + ), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR); + assert_eq!( + method::(&OBJECT, 0x260)(this, &mut b), + NETWORK_ERROR + ); + + let mut b = block(); + let mut remaining = 7u32; + assert_eq!( + method::(&OBJECT, 0x118)( + this, + handle(&CONTEXT), + c"9DUMMY".as_ptr(), + 1, + std::ptr::null(), + &mut b, + ), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR); + assert_eq!( + method::(&OBJECT, 0x120)(this, &mut b, &mut remaining), + NETWORK_ERROR + ); + assert_eq!(remaining, 7); + + let mut b = block(); + assert_eq!( + method::(&OBJECT, 0x188)( + this, + handle(&CONTEXT), + c"9DUMMY".as_ptr(), + std::ptr::null(), + std::ptr::null(), + &mut b, + ), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR); + assert_eq!( + method::(&OBJECT, 0x190)(this, &mut b), + NETWORK_ERROR + ); + + let mut b = block(); + assert_eq!( + method::(&OBJECT, 0x1a8)( + this, + handle(&CONTEXT), + c"DUMMY-TOKEN".as_ptr(), + std::ptr::null(), + 0, + false, + &mut b, + ), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR); + assert_eq!( + method::(&OBJECT, 0x1b0)(this, &mut b), + NETWORK_ERROR + ); + + let mut b = block(); + let mut balance = 3u32; + assert_eq!( + method::(&OBJECT, 0x108)( + this, + handle(&CONTEXT), + c"9DUMMY".as_ptr(), + &mut b, + ), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR); + assert_eq!( + method::(&OBJECT, 0x110)(this, &mut b, &mut balance), + NETWORK_ERROR + ); + assert_eq!(balance, 3); + } + #[test] fn the_game_is_licensed_and_the_store_is_offline() { let this: This = &OBJECT; From 67d1d0222bb49393438a25c47349ef401d4103be Mon Sep 17 00:00:00 2001 From: nathanbzrr Date: Tue, 24 Nov 2026 00:48:55 -0300 Subject: [PATCH 228/445] Census: deduplicate PE imports without hint (cherry picked from commit a3f89eda547690efa8542b8b993b9de894f05bb1) --- apps/victory/src/census.rs | 245 +++++++++++++++++++++++++++++++++---- 1 file changed, 221 insertions(+), 24 deletions(-) diff --git a/apps/victory/src/census.rs b/apps/victory/src/census.rs index 59ec2b7..1314efb 100644 --- a/apps/victory/src/census.rs +++ b/apps/victory/src/census.rs @@ -9,9 +9,24 @@ use victory_hle::{HleResolver, HostPolicy}; use victory_loader::Provenance; use victory_pe::{ImageInfo, ImportSymbol}; +#[derive(PartialEq, Eq, PartialOrd, Ord)] +enum FunctionKey { + Name(String), + Ordinal(u16), +} + +impl From<&ImportSymbol> for FunctionKey { + fn from(symbol: &ImportSymbol) -> Self { + match symbol { + ImportSymbol::Name { name, .. } => Self::Name(name.clone()), + ImportSymbol::Ordinal(ordinal) => Self::Ordinal(*ordinal), + } + } +} + #[derive(Default)] struct DllStats { - functions: BTreeSet, + functions: BTreeSet, hle: usize, host: usize, missing: usize, @@ -58,29 +73,7 @@ pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> } }; images += 1; - for module in info.imports.iter().chain(&info.delay_imports) { - let key = module.dll.to_ascii_lowercase(); - let stats = dlls.entry(key.clone()).or_default(); - stats.images.insert(path.to_path_buf()); - for e in &module.entries { - let class = resolver.classify(&module.dll, &e.symbol); - if class.is_none() { - missing - .entry((key.clone(), e.symbol.to_string())) - .or_default() - .insert(path.to_path_buf()); - } - // Count each dll!function once across all images. - if stats.functions.insert(e.symbol.clone()) { - match class { - Some(Provenance::Hle) => stats.hle += 1, - Some(Provenance::Host) => stats.host += 1, - Some(Provenance::Title) => unreachable!("census maps no title DLLs"), - None => stats.missing += 1, - } - } - } - } + tally_image(path, &info, &resolver, &mut dlls, &mut missing); } } @@ -129,3 +122,207 @@ fn looks_like_pe(path: &Path) -> bool { .is_ok() && &magic == b"MZ" } + +fn tally_image( + path: &Path, + info: &ImageInfo, + resolver: &HleResolver, + dlls: &mut BTreeMap, + missing: &mut BTreeMap<(String, String), BTreeSet>, +) { + for module in info.imports.iter().chain(&info.delay_imports) { + let key = module.dll.to_ascii_lowercase(); + let stats = dlls.entry(key.clone()).or_default(); + stats.images.insert(path.to_path_buf()); + for e in &module.entries { + let class = resolver.classify(&module.dll, &e.symbol); + if class.is_none() { + missing + .entry((key.clone(), e.symbol.to_string())) + .or_default() + .insert(path.to_path_buf()); + } + // Count each dll!function once across all images. + if stats.functions.insert(FunctionKey::from(&e.symbol)) { + match class { + Some(Provenance::Hle) => stats.hle += 1, + Some(Provenance::Host) => stats.host += 1, + Some(Provenance::Title) => unreachable!("census maps no title DLLs"), + None => stats.missing += 1, + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use victory_pe::{ImportEntry, ImportModule}; + + fn entry(symbol: ImportSymbol) -> ImportEntry { + ImportEntry { + symbol, + iat_slot_rva: 0, + } + } + + fn named(hint: u16, name: &str) -> ImportEntry { + entry(ImportSymbol::Name { + hint, + name: name.into(), + }) + } + + fn ordinal(ord: u16) -> ImportEntry { + entry(ImportSymbol::Ordinal(ord)) + } + + fn synthetic_image(imports: Vec, delay_imports: Vec) -> ImageInfo { + ImageInfo { + machine: 0, + characteristics: 0, + timestamp: 0, + subsystem: 0, + dll_characteristics: 0, + image_base: 0, + size_of_image: 0, + entry_rva: 0, + stack_reserve: 0, + stack_commit: 0, + sections: Vec::new(), + imports, + delay_imports, + exports: Vec::new(), + tls: None, + has_relocations: false, + has_exception_table: false, + has_load_config: false, + codeview: None, + } + } + + #[test] + fn deduplicates_imports_ignoring_hint_across_images_and_delay_imports() { + let resolver = HleResolver::new(HostPolicy::none()); + let mut dlls: BTreeMap = BTreeMap::new(); + let mut missing: BTreeMap<(String, String), BTreeSet> = BTreeMap::new(); + + let image_a = synthetic_image( + vec![ImportModule { + dll: "XGameRuntime.dll".into(), + entries: vec![ + named(1, "XGameRuntimeInitialize"), + named(10, "SyntheticMissingApi"), + ordinal(42), + ], + }], + vec![ImportModule { + dll: "XGameRuntime.dll".into(), + entries: vec![ + named(2, "XGameRuntimeInitialize"), + named(20, "SyntheticMissingApi"), + ], + }], + ); + let image_b = synthetic_image( + vec![ImportModule { + dll: "xgameruntime.dll".into(), + entries: vec![ + named(99, "XGameRuntimeInitialize"), + named(200, "SyntheticMissingApi"), + ordinal(42), + ], + }], + vec![ImportModule { + dll: "XGameRuntime.dll".into(), + entries: vec![named(300, "SyntheticMissingApi"), ordinal(42)], + }], + ); + + tally_image( + Path::new("image_a.exe"), + &image_a, + &resolver, + &mut dlls, + &mut missing, + ); + tally_image( + Path::new("image_b.dll"), + &image_b, + &resolver, + &mut dlls, + &mut missing, + ); + + assert_eq!(dlls.len(), 1); + let stats = &dlls["xgameruntime.dll"]; + assert_eq!(stats.functions.len(), 3); + assert_eq!(stats.hle, 1); + assert_eq!(stats.host, 0); + assert_eq!(stats.missing, 2); + assert_eq!(stats.images.len(), 2); + assert_eq!( + dlls.values().map(|s| s.missing).sum::(), + missing.len() + ); + assert_eq!( + missing[&("xgameruntime.dll".into(), "SyntheticMissingApi".into())].len(), + 2 + ); + assert_eq!(missing[&("xgameruntime.dll".into(), "#42".into())].len(), 2); + } + + #[test] + fn counts_distinct_symbols_and_dlls_separately() { + let resolver = HleResolver::new(HostPolicy::none()); + let mut dlls: BTreeMap = BTreeMap::new(); + let mut missing: BTreeMap<(String, String), BTreeSet> = BTreeMap::new(); + + let image = synthetic_image( + vec![ + ImportModule { + dll: "XGameRuntime.dll".into(), + entries: vec![ + named(0, "XGameRuntimeInitialize"), + named(0, "SyntheticMissingA"), + named(0, "SyntheticMissingB"), + ordinal(7), + ordinal(8), + ], + }, + ImportModule { + dll: "SyntheticExtra.dll".into(), + entries: vec![named(0, "SyntheticMissingA"), ordinal(7)], + }, + ], + Vec::new(), + ); + + tally_image( + Path::new("single.exe"), + &image, + &resolver, + &mut dlls, + &mut missing, + ); + + assert_eq!(dlls.len(), 2); + let xgr = &dlls["xgameruntime.dll"]; + assert_eq!(xgr.functions.len(), 5); + assert_eq!(xgr.hle, 1); + assert_eq!(xgr.missing, 4); + assert_eq!(xgr.images.len(), 1); + + let extra = &dlls["syntheticextra.dll"]; + assert_eq!(extra.functions.len(), 2); + assert_eq!(extra.hle, 0); + assert_eq!(extra.missing, 2); + assert_eq!(extra.images.len(), 1); + + assert_eq!( + dlls.values().map(|s| s.missing).sum::(), + missing.len() + ); + } +} From 45f9f49dacd87e40f44da13de27abcc7a029c1c4 Mon Sep 17 00:00:00 2001 From: Enzo Souza Duarte Date: Tue, 24 Nov 2026 00:53:16 -0300 Subject: [PATCH 229/445] HLE: require two hex digits in percent escapes (cherry picked from commit 75fe6c02b278f18eab33ad893bda1dd68d176287) --- crates/victory-hle/src/modules/media.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/victory-hle/src/modules/media.rs b/crates/victory-hle/src/modules/media.rs index 867d978..9e63092 100644 --- a/crates/victory-hle/src/modules/media.rs +++ b/crates/victory-hle/src/modules/media.rs @@ -118,8 +118,11 @@ fn percent_decode(s: &str) -> String { let mut out = Vec::with_capacity(b.len()); let mut i = 0; while i < b.len() { + // `from_str_radix` accepts a leading sign, so `%+1` would decode as + // a control byte. A percent escape is exactly two hex digits. let hex = b .get(i + 1..i + 3) + .filter(|h| h.iter().all(|c| c.is_ascii_hexdigit())) .and_then(|h| std::str::from_utf8(h).ok()); match (b[i], hex.and_then(|h| u8::from_str_radix(h, 16).ok())) { (b'%', Some(v)) => { @@ -493,6 +496,15 @@ mod tests { String::from_utf16_lossy(v.strip_suffix(&[0]).unwrap_or(v)) } + #[test] + fn percent_decode_requires_two_hex_digits() { + assert_eq!(percent_decode("%20"), " "); + assert_eq!(percent_decode("%+1"), "%+1"); + assert_eq!(percent_decode("%2"), "%2"); + assert_eq!(percent_decode("%%20"), "% "); + assert_eq!(percent_decode("a%2Gb"), "a%2Gb"); + } + #[test] fn only_local_files_reach_the_host() { // Network schemes and shares are refused, naming scheme and host. From ee054d47326958ecd805f6bea1ce3b18cd529ddc Mon Sep 17 00:00:00 2001 From: LF2000 Builder Date: Mon, 23 Nov 2026 23:18:02 -0500 Subject: [PATCH 230/445] xmem: report allocations the host refuses A refused XMemVirtualAlloc or XMemAllocDefault handed the title a null in silence, and the title then writes at null plus an offset, which reads like a title bug. In #289 the faulting write is at 0x217800, the request's length 0x2173a0 rounded up to 2 KiB, so the base it built on was most likely such a null. At the commit limit, XMemVirtualAlloc now writes the same crashes.log report the physical-page commit writes since #51 (the shared part is `commit_refused`); other refusals, and a host heap out of memory, are warnings. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 65062e133c75c3b6e984ac51e904512d41f71f93) --- crates/victory-hle/src/modules/xmem.rs | 44 +++++++++++++++++++++----- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 900b46f..02ba024 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -153,6 +153,20 @@ pub extern "system" fn XMemVirtualAlloc( constrained.into(), ) }; + if at.is_null() { + let error = std::io::Error::last_os_error(); + if kind & MEM_COMMIT != 0 { + commit_refused(size, "virtual memory", error); + } else { + tracing::warn!( + size, + kind = format_args!("{kind:#x}"), + flags = format_args!("{flags:#x}"), + %error, + "XMemVirtualAlloc refused" + ); + } + } if base.is_null() { tracing::debug!( size, @@ -299,6 +313,7 @@ pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_ // SAFETY: the layout has a non-zero size. let block = unsafe { alloc(layout) }; if block.is_null() { + tracing::warn!(size, "XMemAllocDefault: the host heap is out of memory"); return block.cast(); } // SAFETY: the block holds the alignment (at least the header) and then @@ -1051,7 +1066,14 @@ fn commit(base: usize, len: usize) -> bool { if !unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null() { return true; } - let error = std::io::Error::last_os_error(); + commit_refused(len, "physical pages", std::io::Error::last_os_error()); + false +} + +/// Reports memory the host would not give: at the Windows commit limit to +/// `crashes.log`, since the title usually faults soon after on the null it +/// gets; otherwise as a warning. +fn commit_refused(len: usize, what: &str, error: std::io::Error) { if error.raw_os_error() == Some(ERROR_COMMITMENT_LIMIT as i32) { let mut info = PERFORMANCE_INFORMATION { cb: size_of::() as u32, @@ -1059,20 +1081,25 @@ fn commit(base: usize, len: usize) -> bool { }; // SAFETY: the buffer and size describe a writable PERFORMANCE_INFORMATION. let queried = unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0; - victory_loader::log_crash(&commit_limit_message(len, &error, queried.then_some(&info))); + victory_loader::log_crash(&commit_limit_message( + len, + what, + &error, + queried.then_some(&info), + )); } else { - tracing::warn!(len, %error, "committing physical pages failed"); + tracing::warn!(len, %error, "committing {what} failed"); } - false } fn commit_limit_message( len: usize, + what: &str, error: &std::io::Error, info: Option<&PERFORMANCE_INFORMATION>, ) -> String { let mut message = format!( - "VIctory: Windows commit limit reached while committing {len} bytes of physical pages: {error}.\n" + "VIctory: Windows commit limit reached while committing {len} bytes of {what}: {error}.\n" ); if let Some(info) = info { use std::fmt::Write; @@ -1371,10 +1398,11 @@ mod tests { PageSize: 4096, ..Default::default() }; - let report = commit_limit_message(4 * MIB, &error, Some(&info)); - assert!(report.contains("4194304 bytes")); + let report = commit_limit_message(4 * MIB, "physical pages", &error, Some(&info)); + assert!(report.contains("4194304 bytes of physical pages")); assert!(report.contains("2 MiB of 3 MiB in use")); - let fallback = commit_limit_message(4 * MIB, &error, None); + let fallback = commit_limit_message(4 * MIB, "virtual memory", &error, None); + assert!(fallback.contains("4194304 bytes of virtual memory")); for report in [&report, &fallback] { assert!(report.contains("os error 1455")); assert!(report.contains("Windows paging file size")); From bda8238b80b26a05a0baa8bfa5ac860516adf152 Mon Sep 17 00:00:00 2001 From: broccolize <203913429+broccolize@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:48:48 +0800 Subject: [PATCH 231/445] GPU: clear DXGI outputs on out-of-range enumeration (cherry picked from commit b796c8b8b80cfa4506f254474ab9fd7260bfd8e6) --- crates/victory-gpu/src/dxgi.rs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/dxgi.rs b/crates/victory-gpu/src/dxgi.rs index af10227..5dfb218 100644 --- a/crates/victory-gpu/src/dxgi.rs +++ b/crates/victory-gpu/src/dxgi.rs @@ -90,6 +90,14 @@ fn query(kind: usize, iid: *const Iid, known: &[Iid], found: This, out: *mut Thi object::answer(kind, iid, object::is(iid, known).then_some(found), out) } +fn enumeration_not_found(out: *mut This) -> HRESULT { + if !out.is_null() { + // SAFETY: the caller supplies a writable output slot when non-null. + unsafe { out.write(std::ptr::null()) }; + } + NOT_FOUND +} + /// The DXGI device also answers for the D3D12 device. extern "system" fn device_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { if crate::device::is_device(iid) { @@ -112,7 +120,7 @@ extern "system" fn adapter_parent(_: This, iid: *const Iid, out: *mut This) -> H } extern "system" fn adapter_outputs(_: This, index: u32, out: *mut This) -> HRESULT { if index != 0 { - return NOT_FOUND; + return enumeration_not_found(out); } object::answer(ADAPTER, &OUTPUT_IIDS[0], Some(&OUTPUT_OBJECT), out) } @@ -165,7 +173,7 @@ extern "system" fn factory_query(this: This, iid: *const Iid, out: *mut This) -> } extern "system" fn factory_adapters(_: This, index: u32, out: *mut This) -> HRESULT { if index != 0 { - return NOT_FOUND; + return enumeration_not_found(out); } object::answer(FACTORY, &ADAPTER_IIDS[0], Some(&ADAPTER_OBJECT), out) } @@ -338,4 +346,18 @@ mod tests { assert!(!output.is_null()); assert_eq!(outputs(adapter, 1, &mut output), NOT_FOUND); } + + #[test] + fn out_of_range_enumeration_clears_output() { + for (object, offset, method) in [ + (&FACTORY_OBJECT, 0x38, "EnumAdapters"), + (&FACTORY_OBJECT, 0x60, "EnumAdapters1"), + (&ADAPTER_OBJECT, 0x38, "EnumOutputs"), + ] { + let enumerate = slot::(object, offset); + let mut out = object as This; + assert_eq!(enumerate(object, 1, &mut out), NOT_FOUND, "{method}"); + assert!(out.is_null(), "{method} left a stale output pointer"); + } + } } From ea357d42107b89a65b519bd50c73371137453850 Mon Sep 17 00:00:00 2001 From: Devin Date: Tue, 24 Nov 2026 13:36:46 +0800 Subject: [PATCH 232/445] Shaders: reuse lane guards for unchanged EXEC within a block An instruction guard depends on its EXEC and the reachability of its block. Keep the most recent result, including an elided guard, rather than repeating the same BDD queries for consecutive vector instructions. Scalar instructions still bypass guard selection. Cover EXEC changes across and within a branch with a synthetic shader. Add a CPU-only guard_runs benchmark for unmasked, short, and long masked runs. (cherry picked from commit 81b81df351437c50f4321286c725de51664c7b1b) --- crates/victory-shader/Cargo.toml | 4 ++ crates/victory-shader/benches/guard_runs.rs | 48 +++++++++++++++++++++ crates/victory-shader/src/structure.rs | 46 +++++++++++++++++++- 3 files changed, 96 insertions(+), 2 deletions(-) create mode 100644 crates/victory-shader/benches/guard_runs.rs diff --git a/crates/victory-shader/Cargo.toml b/crates/victory-shader/Cargo.toml index 3d0caf1..0c03ffa 100644 --- a/crates/victory-shader/Cargo.toml +++ b/crates/victory-shader/Cargo.toml @@ -17,6 +17,10 @@ host = ["dep:windows"] # Debugging switches (emitted-module dumps and the like). diagnostics = [] +[[bench]] +name = "guard_runs" +harness = false + [target.'cfg(windows)'.dependencies] windows-sys = { workspace = true, features = ["Win32_System_LibraryLoader"] } windows = { workspace = true, optional = true, features = [ diff --git a/crates/victory-shader/benches/guard_runs.rs b/crates/victory-shader/benches/guard_runs.rs new file mode 100644 index 0000000..ae01492 --- /dev/null +++ b/crates/victory-shader/benches/guard_runs.rs @@ -0,0 +1,48 @@ +//! Time structurisation only; the synthetic programs need no title files or GPU. + +use std::hint::black_box; +use std::time::Instant; + +use victory_shader::{ir, structure::structure}; + +fn program(masks: u32, run: usize) -> ir::Program { + let mut words = Vec::new(); + for i in 0..masks.max(1) { + if masks != 0 { + // v_cmpx_eq_u32 exec, 0, v[i]: each comparison narrows EXEC. + words.push(0x7DA4_0080 | (i << 9)); + } + words.extend(std::iter::repeat_n(0x4A00_0081, run)); // v_add_nc_u32 v0, 1, v0 + } + words.push(0xBF81_0000); // s_endpgm + let code = words + .into_iter() + .flat_map(u32::to_le_bytes) + .collect::>(); + ir::build(&code, true, 256).unwrap() +} + +fn main() { + const BATCH: u32 = 64; + for (label, masks, run) in [ + ("unmasked", 0, 512), + ("short runs", 8, 1), + ("long runs", 8, 64), + ] { + let p = program(masks, run); + black_box(structure(&p).unwrap()); + let mut samples = [std::time::Duration::ZERO; 9]; + for sample in &mut samples { + let start = Instant::now(); + for _ in 0..BATCH { + black_box(structure(black_box(&p)).unwrap()); + } + *sample = start.elapsed() / BATCH; + } + samples.sort_unstable(); + println!( + "{label}: {:?} per program (median)", + samples[samples.len() / 2] + ); + } +} diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index a913176..719805d 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -792,6 +792,9 @@ impl<'a> Lanes<'a> { .iter() .enumerate() .map(|(n, block)| { + // Reachability is fixed within the block. Vector instructions + // with the same EXEC therefore need the same guard. + let mut last_guard = None; block .insts .iter() @@ -801,8 +804,16 @@ impl<'a> Lanes<'a> { | (_, Fields::Sop { .. } | Fields::Sopp { .. } | Fields::Smem { .. }) => { None } - (&Some(e), _) if b.implies(cond[n], e) => None, - (&Some(e), _) => Some(b.given(e, cond[n])), + (&Some(e), _) => { + if let Some((prev, guard)) = last_guard + && prev == e + { + return guard; + } + let guard = (!b.implies(cond[n], e)).then(|| b.given(e, cond[n])); + last_guard = Some((e, guard)); + guard + } }) .collect() }) @@ -1577,6 +1588,37 @@ mod tests { assert!(matches!(s.bools.support(g)[..], [Atom::Lane(_)])); } + #[test] + fn guards_follow_exec_and_block_reachability() { + let p = build( + &[ + 0x7DA4_0080, // v_cmpx_eq_u32 exec, 0, v0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x7E04_0280, // v_mov_b32 v2, 0 + 0xBF88_0005, // s_cbranch_execz -> end + 0x7E06_0280, // v_mov_b32 v3, 0 + 0x7DA4_0880, // v_cmpx_eq_u32 exec, 0, v4 + 0x7E06_0280, // v_mov_b32 v3, 0 + 0xBE82_0480, // s_mov_b64 s[2:3], 0 + 0x7E0A_0280, // v_mov_b32 v5, 0 + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + let lane = |block: usize, i: usize| { + Atom::Lane(p.blocks[block].insts[i].write(Reg::S(EXEC)).unwrap()) + }; + let a = s.guards[0][1].unwrap(); + let b = s.guards[1][2].unwrap(); + assert_eq!(s.bools.node(a), Some((lane(0, 0), Bool::FALSE, Bool::TRUE))); + assert_eq!(s.guards[0], [None, Some(a), Some(a), None]); + // The fallthrough already implies the first compare. Only the second + // compare needs testing, and the scalar move never needs a guard. + assert_eq!(s.bools.node(b), Some((lane(1, 1), Bool::FALSE, Bool::TRUE))); + assert_eq!(s.guards[1], [None, None, Some(b), None, Some(b)]); + } + #[test] fn divergent_loop_exits_per_lane() { let p = build( From 20d9d1ebfee3b0f52739de8ab49f538d4d7b1743 Mon Sep 17 00:00:00 2001 From: LF2000 Builder Date: Tue, 24 Nov 2026 00:37:48 -0500 Subject: [PATCH 233/445] xtask: count \x escapes and 0x hex arrays as encoded runs in the policy check The run check split on every byte that is not alphanumeric or +/=, so b"\x4d\x5a..." broke into 3-character pieces and an xxd -i style [0x4d, 0x5a, ...] array into 4-character pieces. Either form of up to about 100 KB of copied bytes passed the check and the pre-commit hook. Also count the hex digits of \x escapes and 0x literals that have only commas, whitespace or backslashes between them, and flag the file when that passes the same 512 limit. The largest such run in the tree is 36 digits. Decimal arrays are still not caught. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit e950e81756340b10c3ef87d9c1789ae482f1a262) --- xtask/src/policy.rs | 76 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/xtask/src/policy.rs b/xtask/src/policy.rs index 9bcf24c..056053b 100644 --- a/xtask/src/policy.rs +++ b/xtask/src/policy.rs @@ -171,6 +171,13 @@ pub fn check(path: &str, content: &[u8]) -> Vec { && run > MAX_ENCODED_RUN { problems.push(format!("{run}-character hex/base64 run (embedded data?)")); + } else { + let digits = longest_hex_literal_run(content); + if digits > MAX_ENCODED_RUN { + problems.push(format!( + "{digits} hex digits in one run of \\x/0x literals (embedded data?)" + )); + } } problems } @@ -181,6 +188,38 @@ fn longest_encoded_run(content: &[u8]) -> Option { content.split(|b| !is_payload(b)).map(<[u8]>::len).max() } +/// Most hex digits in `\xNN` escapes or `0x` literals with only commas, +/// whitespace or backslashes between them: a byte string or `xxd -i` array, +/// which `longest_encoded_run` sees as many 3- or 4-character runs. +/// shortcut: decimal arrays (`[77, 90, ...]`) still pass, add a literal count if one shows up. +fn longest_hex_literal_run(content: &[u8]) -> usize { + let (mut i, mut run, mut longest) = (0, 0, 0); + while i < content.len() { + match &content[i..] { + [b'\\' | b'0', b'x' | b'X', rest @ ..] => { + let len = rest + .iter() + .take_while(|b| b.is_ascii_hexdigit() || **b == b'_') + .count(); + run += rest[..len].iter().filter(|b| b.is_ascii_hexdigit()).count(); + longest = longest.max(run); + // Skip a type suffix such as `u8` or `u32`. + let suffix = rest[len..] + .iter() + .take_while(|b| b.is_ascii_alphanumeric()) + .count(); + i += 2 + len + suffix; + } + [b, ..] if matches!(b, b',' | b'\\') || b.is_ascii_whitespace() => i += 1, + _ => { + run = 0; + i += 1; + } + } + } + longest +} + #[cfg(test)] mod tests { use super::check; @@ -220,4 +259,41 @@ mod tests { let blob = format!("const DATA: &str = \"{}\";", "A1".repeat(400)); assert!(!check("src/blob.rs", blob.as_bytes()).is_empty()); } + + /// Synthetic bytes, never game data. + fn synthetic(n: u32) -> impl Iterator { + (0..n).map(|i| (i * 37 + 11) % 256) + } + + #[test] + fn rejects_data_smuggled_as_an_escaped_byte_string() { + // 4096 bytes as one unbroken `\xNN` hex run, the shape a byte-string + // literal of copied data takes. + let esc: String = synthetic(4096).map(|b| format!("\\x{b:02x}")).collect(); + let src = format!("pub const DATA: &[u8] = b\"{esc}\";\n"); + assert!( + !check("src/data.rs", src.as_bytes()).is_empty(), + "{} bytes of \\x-escaped hex passed", + src.len() + ); + } + + #[test] + fn rejects_data_smuggled_as_a_hex_byte_array() { + // `xxd -i` style: 4096 bytes as hex literals. + let lits: Vec = synthetic(4096).map(|b| format!("0x{b:02x}")).collect(); + let src = format!("pub const DATA: [u8; 4096] = [{}];\n", lits.join(", ")); + assert!( + !check("src/data.rs", src.as_bytes()).is_empty(), + "{} bytes of hex array passed", + src.len() + ); + // A short constant table, like the 16-entry ones in the tree, stays legal. + let table: Vec = synthetic(16).map(|w| format!("0x{w:08x}_u32")).collect(); + let src = format!( + "const T: [u32; 16] = [\n {},\n];\n", + table.join(",\n ") + ); + assert!(check("src/table.rs", src.as_bytes()).is_empty()); + } } From 77582c3af40a099535f740d31f61ccda0df53034 Mon Sep 17 00:00:00 2001 From: KoLolX3 <94136289+KoLolX3@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:39:19 -0800 Subject: [PATCH 234/445] GPU: VICTORY_* switches set to 0 are off Six diagnostic switches (VICTORY_D3D12_DEBUG, _GBV, _DRED, _WARP, VICTORY_GPU_TIMING and VICTORY_DUMP_TARGETS) were on whenever their variable existed, so VICTORY_D3D12_WARP=0 still selected the software adapter. They now go through one helper that reads a value other than 0 as on and an unset variable or 0 as off; every other value keeps the meaning it had. The README says so above its switch table. (cherry picked from commit a4974e4c21c16e2305942e37a868647d42eefe37) --- README.md | 2 ++ crates/victory-gpu/src/capture.rs | 2 +- crates/victory-gpu/src/host.rs | 13 ++++----- crates/victory-gpu/src/lib.rs | 1 + crates/victory-gpu/src/switch.rs | 45 +++++++++++++++++++++++++++++++ 5 files changed, 54 insertions(+), 9 deletions(-) create mode 100644 crates/victory-gpu/src/switch.rs diff --git a/README.md b/README.md index 4672921..49c4f92 100644 --- a/README.md +++ b/README.md @@ -267,6 +267,8 @@ A release build has no debugging aids. Build them in with cargo build --profile diag -p victory --features diagnostics # target\diag\victory.exe ``` +The on/off switches below (`...=1`) are off when unset or set to `0`. + | Variable | Effect | |----------|--------| | `VICTORY_LOG==debug,...` | debug and trace output | diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index b4010f8..937f560 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -358,7 +358,7 @@ static TARGETS: std::sync::Mutex bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| folder().is_some() && std::env::var_os("VICTORY_DUMP_TARGETS").is_some()) + *ON.get_or_init(|| folder().is_some() && crate::switch::on("VICTORY_DUMP_TARGETS")) } /// Notes a title texture the frame being built renders to or writes. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 9c70c3f..edca8d4 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -553,8 +553,7 @@ fn create() -> windows::core::Result { // SAFETY: plain D3D12 object creation with valid descriptions. unsafe { // The debug layer only in builds with diagnostics. - let debug = - cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DEBUG").is_some(); + let debug = cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DEBUG"); if debug { let mut layer: Option = None; match D3D12GetDebugInterface(&mut layer) { @@ -565,7 +564,7 @@ fn create() -> windows::core::Result { // descriptor heap indices and the like become messages naming // the command instead of page faults. Without state tracking // (directly indexed textures are not transitioned). - if std::env::var_os("VICTORY_D3D12_GBV").is_some() + if crate::switch::on("VICTORY_D3D12_GBV") && let Some(l) = &layer { if let Ok(d1) = l.cast::() { @@ -594,7 +593,7 @@ fn create() -> windows::core::Result { // Diagnostics: the software adapter, on which a shader's wild access // is an access violation in this process (a crash report with the // address and instruction) instead of a GPU fault and driver reset. - if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() { + if cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_WARP") { let adapter = warp_adapter()?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; tracing::info!("host device on the software adapter (WARP)"); @@ -1326,9 +1325,7 @@ fn record_twin_copy( /// builds). pub(crate) fn dred_on() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| { - cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some() - }) + *ON.get_or_init(|| cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DRED")) } /// Indirect mesh dispatches since the last frame line: the largest group @@ -1352,7 +1349,7 @@ fn card_budget() -> bool { #[cfg(feature = "diagnostics")] fn timing() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some()) + *ON.get_or_init(|| crate::switch::on("VICTORY_GPU_TIMING")) } /// Names a host object for the device-removed report, which names the diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 420682d..e9a0cb2 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -63,6 +63,7 @@ mod shadow; #[cfg(windows)] mod tiles; pub mod signature; +mod switch; #[cfg(windows)] mod texture; #[cfg(windows)] diff --git a/crates/victory-gpu/src/switch.rs b/crates/victory-gpu/src/switch.rs new file mode 100644 index 0000000..f3ea9b9 --- /dev/null +++ b/crates/victory-gpu/src/switch.rs @@ -0,0 +1,45 @@ +//! The `VICTORY_*` on/off switches (`VICTORY_D3D12_DEBUG=1` and its siblings). + +use std::ffi::OsStr; + +/// Whether a switch's value turns it on: it is set, and is not `0`. +/// +/// A switch used to be on whenever its variable existed, so `VICTORY_D3D12_WARP=0` (typed to switch it off, or left +/// over from comparing two runs) still selected the software adapter. Any other value keeps the old meaning. +fn value_is_on(value: Option<&OsStr>) -> bool { + value.is_some_and(|v| v != "0") +} + +/// Whether the environment variable `name` switches something on. +pub(crate) fn on(name: &str) -> bool { + value_is_on(std::env::var_os(name).as_deref()) +} + +#[cfg(test)] +mod tests { + use super::value_is_on; + use std::ffi::OsStr; + + #[test] + fn unset_is_off() { + assert!(!value_is_on(None)); + } + + #[test] + fn zero_is_off() { + assert!(!value_is_on(Some(OsStr::new("0")))); + } + + #[test] + fn one_is_on() { + assert!(value_is_on(Some(OsStr::new("1")))); + } + + #[test] + fn other_values_keep_their_old_meaning() { + // Documented as `=1`; anything else that was on before stays on: only `0` is new. + for value in ["", "true", "yes", "2", "00", " 0", "0 "] { + assert!(value_is_on(Some(OsStr::new(value))), "{value:?}"); + } + } +} From 939ba8292282da2f0f871c53db7157be4153beee Mon Sep 17 00:00:00 2001 From: LF2000 Builder Date: Tue, 24 Nov 2026 00:37:37 -0500 Subject: [PATCH 235/445] Shaders: print only the operands an instruction has in SP3 text The disassembly text showed operands that some instructions lack, and dropped VOP3P negation that applies to one half only: - s_memtime, s_memrealtime and s_get_waveid_in_workgroup printed the unused SMEM base and offset. - A global or scratch access with no SGPR base printed `null`, not `off`. - A MUBUF load with lds printed the unused vdata as a destination. - VOP1 SDWA printed src1_sel, though VOP1 has no second source. - VOP3P ops other than v_fma_mix with only neg_lo or only neg_hi set on a source printed as if the source were not negated. These now get LLVM's neg_lo:[..] and neg_hi:[..] suffixes; a source negated in both halves keeps `-src`. Expected operands come from llvm-mc -mcpu=gfx1030 (gfx1010 for s_get_waveid_in_workgroup). Only the text changes; translation reads Fields and is unaffected. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 6325df752c5638365c3e5a2b2f827ba0f3f145cb) --- crates/victory-shader/src/gfx10/sp3.rs | 76 ++++++++++++++++++++++++-- 1 file changed, 72 insertions(+), 4 deletions(-) diff --git a/crates/victory-shader/src/gfx10/sp3.rs b/crates/victory-shader/src/gfx10/sp3.rs index baf0e82..6f0795f 100644 --- a/crates/victory-shader/src/gfx10/sp3.rs +++ b/crates/victory-shader/src/gfx10/sp3.rs @@ -151,7 +151,11 @@ fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { (_, 0) => soffset.to_string(), _ => format!("{soffset} offset:0x{:06x}", offset & 0x1F_FFFF), }; - out = format!("{data}, {base}, {off}"); + out = match name { + // The data is a counter or the wave ID; these have no address. + "s_memtime" | "s_memrealtime" | "s_get_waveid_in_workgroup" => data.to_string(), + _ => format!("{data}, {base}, {off}"), + }; } flags(&mut out, cache, false); } @@ -205,7 +209,12 @@ fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { cache, } => { if let Some(data) = data { - out = format!("{data}, {addr}, {rsrc}, {soffset}"); + // An LDS load returns its data to LDS, so vdata is unused. + out = if *lds && name.contains("_load_") { + format!("{addr}, {rsrc}, {soffset}") + } else { + format!("{data}, {addr}, {rsrc}, {soffset}") + }; if *idxen { out.push_str(" idxen"); } @@ -299,7 +308,11 @@ fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { dst.iter() .map(|o| o.to_string()) .chain([addr]) - .chain(data.iter().chain(saddr).map(|o| o.to_string())), + .chain(data.iter().map(|o| o.to_string())) + .chain(saddr.map(|o| match o { + Operand::Scalar { code: NULL, .. } => "off".into(), + o => o.to_string(), + })), ); if *offset != 0 { let _ = write!(out, " inst_offset:{offset}"); @@ -590,6 +603,18 @@ fn valu(name: &str, v: &Valu, encoding: Encoding) -> String { suffix("bound_ctrl:1"); } } + if encoding == Encoding::Vop3p && !mix { + // `-src` above covers a source negated in both halves; LLVM syntax + // for the one-sided rest. + let n = v.src.len(); + for (field, only) in [("neg_lo", v.neg & !v.neg_hi), ("neg_hi", v.neg_hi & !v.neg)] { + if (0..n).any(|i| bit(only, i)) { + let bits: Vec = + (0..n).map(|i| u8::from(bit(only, i)).to_string()).collect(); + suffix(&format!("{field}:[{}]", bits.join(","))); + } + } + } if let Some(sdwa) = v.sdwa { if v.clamp { suffix("clamp"); @@ -610,7 +635,7 @@ fn valu(name: &str, v: &Valu, encoding: Encoding) -> String { unused[usize::from(sdwa.dst_unused & 3)] )); } - for (i, s) in sdwa.src_sel.iter().enumerate() { + for (i, s) in sdwa.src_sel.iter().take(v.src.len()).enumerate() { if *s != 6 { suffix(&format!("src{i}_sel:{}", sel[usize::from(s & 7)])); } @@ -840,6 +865,49 @@ mod tests { ); } + #[test] + fn one_sided_packed_negation_is_printed() { + // Encodings from llvm-mc -mcpu=gfx1030. A source negated in both + // halves keeps the `-` prefix; one-sided bits get LLVM's suffixes. + let got = [ + one(&[0xCC0F_4001, 0x1A02_0702], true), + one(&[0xCC0F_4001, 0x3A02_0702], true), + one(&[0xCC0F_4201, 0x1A02_0702], true), + one(&[0xCC0F_4101, 0x7A02_0702], true), + ]; + assert_eq!( + got, + [ + "v_pk_add_f16 v1, v2, v3", + "v_pk_add_f16 v1, v2, v3 neg_lo:[1,0]", + "v_pk_add_f16 v1, v2, v3 neg_hi:[0,1]", + "v_pk_add_f16 v1, -v2, v3 neg_lo:[0,1]", + ] + ); + } + + #[test] + fn fields_the_instruction_lacks_are_not_printed() { + // Encodings from llvm-mc -mcpu=gfx1030; s_get_waveid_in_workgroup is gfx1010 only. + let got = [ + one(&[0xF490_0500, 0], true), + one(&[0xF4A8_0140, 0], true), + one(&[0xDC30_8000, 0x007D_0002], true), + one(&[0xE031_1000, 0x0001_0001], true), + one(&[0x7E02_02F9, 0x0005_0602], true), + ]; + assert_eq!( + got, + [ + "s_memtime s[20:21]", + "s_get_waveid_in_workgroup s5", + "global_load_dword v0, v[2:3], off", + "buffer_load_dword v1, s[4:7], s0 offen lds", + "v_mov_b32 v1, v2 src0_sel:WORD_1", + ] + ); + } + #[test] fn image_d16_data_is_packed() { // Three f16 channels occupy two VGPRs; NSA lists the addresses. From 886afce1e3a88da2673b0e466ad844e55b783937 Mon Sep 17 00:00:00 2001 From: LF2000 Builder Date: Tue, 24 Nov 2026 00:37:04 -0500 Subject: [PATCH 236/445] translate: refuse a VICTORY_EMIT_DUMP directory inside the repo translate writes emitted DXIL and validator reports to the VICTORY_EMIT_DUMP directory. Both are derived from the game's shaders, but the directory was never checked against the source tree. With VICTORY_EMIT_DUMP=. run from the checkout, the .txt reports land in the repo, and git and cargo xtask policy both let them through. Check the directory once at the start of translate::run, as Config already does for the cache and data directories. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 988fd9a64718ee9a235cff3b60192b6b86006c4d) --- apps/victory/src/translate.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 37df3ec..caaa7da 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -240,6 +240,10 @@ pub fn run( list: bool, jobs: Option, ) -> Result<()> { + // Dumped shaders and validator reports are game-derived (rule #1). + if let Some(dir) = std::env::var_os("VICTORY_EMIT_DUMP") { + victory_core::ensure_outside_repo(Path::new(&dir))?; + } let paths = crate::default_paths(paths)?; // `VICTORY_HOST_MAX_WAVE=32`: translate as for a host whose waves have // at most 32 lanes (as the runtime does on such a card). @@ -931,3 +935,24 @@ fn tally_structured(program: &ir::Program, s: &structure::Structured, t: &mut Ta fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { m.lock().unwrap_or_else(|e| e.into_inner()) } + +#[cfg(test)] +mod tests { + /// Shader dumps are game-derived, so a dump directory in the repo is refused. + #[test] + fn emit_dump_inside_repo_is_refused() { + // SAFETY: no other test in this binary touches the environment. + unsafe { std::env::set_var("VICTORY_EMIT_DUMP", env!("CARGO_MANIFEST_DIR")) }; + let missing = std::env::temp_dir().join("victory-translate-no-such-dir"); + let err = super::run(vec![missing], false, false, false, Some(1)).unwrap_err(); + // SAFETY: as above; unset so a later test's `run` is not refused. + unsafe { std::env::remove_var("VICTORY_EMIT_DUMP") }; + assert!( + matches!( + err.downcast_ref(), + Some(victory_core::PolicyError::InsideRepo { .. }) + ), + "{err}" + ); + } +} From 379f4e733d2cf01061c6c906a8754efcc2d8e21a Mon Sep 17 00:00:00 2001 From: AlanQiang0418 Date: Tue, 24 Nov 2026 00:54:23 -0500 Subject: [PATCH 237/445] Formats: reject multisampled linear texture layouts (cherry picked from commit 350f91c23a9402b2a556a84c208a80030910ae3f) --- crates/victory-formats/src/texture.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 450360c..469c174 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -274,7 +274,8 @@ impl Layout { && matches!(d.block, 1 | 4) && d.samples.is_power_of_two() && d.samples <= 8 - && (d.samples == 1 || (d.dimension == Dimension::Tex2d && d.mips == 1)) + && (d.samples == 1 + || (d.dimension == Dimension::Tex2d && d.mips == 1 && d.swizzle != Swizzle::LINEAR)) && (d.dimension != Dimension::Tex1d || d.height == 1) && (d.dimension != Dimension::Tex3d || matches!(d.swizzle.0, 0 | 5 | 9 | 17 | 21 | 24..=27)); @@ -902,6 +903,26 @@ mod tests { } } + #[test] + fn linear_layouts_require_one_sample() { + let linear = desc(256, 256, 1, 4, Swizzle::LINEAR); + let single = Layout::new(&linear).unwrap(); + assert!(single.addressable()); + assert_eq!(single.size, 256 * 256 * 4); + + for samples in [2, 4, 8] { + let multisampled = Desc { samples, ..linear }; + assert_eq!(Layout::new(&multisampled), Err(Error::Invalid)); + + let tiled = Layout::new(&Desc { + swizzle: Swizzle::SW_64KB_R_X, + ..multisampled + }) + .unwrap(); + assert_eq!(tiled.size, single.size * u64::from(samples)); + } + } + /// Sizes past the hardware's 16384 texels per side are refused instead /// of overflowing the size arithmetic (found by random-input testing). #[test] From e8eb93a2bdd19ffb6ada8f67ef89573e143a31f8 Mon Sep 17 00:00:00 2001 From: Thomas Askharoun <151990913+askharoun@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:10:33 -0500 Subject: [PATCH 238/445] Show on-disk file size in victory inspect (cherry picked from commit 43e2ca9de29f5833941970e82ed89872c9f86a81) --- apps/victory/src/inspect.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/victory/src/inspect.rs b/apps/victory/src/inspect.rs index 3991d70..15a7ff7 100644 --- a/apps/victory/src/inspect.rs +++ b/apps/victory/src/inspect.rs @@ -10,6 +10,7 @@ pub fn run(file: &Path, list_imports: bool, list_exports: bool) -> Result<()> { let info = ImageInfo::parse(&data).with_context(|| format!("parsing {}", file.display()))?; println!("file {}", file.display()); + println!("file size {} bytes", data.len()); println!("blake3 {}", blake3::hash(&data).to_hex()); if let Some(cv) = &info.codeview { println!("pdb {} (key {})", cv.pdb_path, cv.symbol_key()); From 3f497dafc1b49401280c49cdee3fa5176d8cc1e6 Mon Sep 17 00:00:00 2001 From: EatCodeSleep2 <52021568+EatCodeSleep2@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:30:24 -0800 Subject: [PATCH 239/445] Handle unsupported display deferrals in the HLE test (cherry picked from commit efe102edac86f365a9951f3c92228413cbee8e46) --- crates/victory-hle/src/modules/display.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/victory-hle/src/modules/display.rs b/crates/victory-hle/src/modules/display.rs index fd13187..527b7dc 100644 --- a/crates/victory-hle/src/modules/display.rs +++ b/crates/victory-hle/src/modules/display.rs @@ -185,11 +185,14 @@ mod tests { type Acquire = extern "system" fn(This, *mut *mut c_void) -> HRESULT; type Close = extern "system" fn(This, *mut c_void); let mut handle = std::ptr::null_mut(); - assert_eq!( - method::(&SHELL_OBJECT, 0x20)(&SHELL_OBJECT, &mut handle), - S_OK - ); - assert!(!handle.is_null()); - method::(&SHELL_OBJECT, 0x28)(&SHELL_OBJECT, handle); + match method::(&SHELL_OBJECT, 0x20)(&SHELL_OBJECT, &mut handle) { + S_OK => { + assert!(!handle.is_null()); + method::(&SHELL_OBJECT, 0x28)(&SHELL_OBJECT, handle); + } + // Windows can reject display power requests on some hosts. + NOT_SUPPORTED => assert!(handle.is_null()), + hr => panic!("unexpected display deferral HRESULT {:#010x}", hr as u32), + } } } From efbf10765a1e29efb938a3bfc8c7045dd9c0805f Mon Sep 17 00:00:00 2001 From: Nixitov <125388985+Nixitov@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:34:18 +0100 Subject: [PATCH 240/445] HLE: implement the RPC runtime's GUID calls (cherry picked from commit 7216ab7113115ea1accfabc6e3a00ee700c7c846) --- crates/victory-hle/Cargo.toml | 1 + crates/victory-hle/src/lib.rs | 26 ++ crates/victory-hle/src/modules/mod.rs | 2 + crates/victory-hle/src/modules/rpcrt4.rs | 413 +++++++++++++++++++++++ 4 files changed, 442 insertions(+) create mode 100644 crates/victory-hle/src/modules/rpcrt4.rs diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index 3522b74..d91f14f 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -22,6 +22,7 @@ windows-sys = { workspace = true, features = [ "Win32_Globalization", "Win32_Media", "Win32_Security", + "Win32_Security_Cryptography", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_Debug", "Win32_System_IO", diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs index 447de82..f9b9a86 100644 --- a/crates/victory-hle/src/lib.rs +++ b/crates/victory-hle/src/lib.rs @@ -123,4 +123,30 @@ mod tests { Some(Provenance::Hle) ); } + + // #510: the RPC runtime's GUID calls are ours, so the DLL itself stays + // outside the host policy (its own `ws2_32` imports would be a network + // path `modules::net` never sees). + #[test] + fn the_rpc_runtime_is_implemented_here() { + let r = HleResolver::new(HostPolicy::none()); + for call in [ + "UuidCreate", + "UuidCreateSequential", + "UuidFromStringA", + "UuidFromStringW", + "UuidToStringA", + "UuidToStringW", + "RpcStringFreeA", + "RpcStringFreeW", + ] { + assert_eq!( + r.classify("rpcrt4.dll", &name(call)), + Some(Provenance::Hle), + "{call}" + ); + } + // A call we do not implement is not passed to the host either. + assert_eq!(r.classify("rpcrt4.dll", &name("RpcServerRegisterIf")), None); + } } diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs index 51e3590..7f8a931 100644 --- a/crates/victory-hle/src/modules/mod.rs +++ b/crates/victory-hle/src/modules/mod.rs @@ -26,6 +26,7 @@ pub mod lifecycle; pub mod media; #[cfg(windows)] pub mod net; +pub mod rpcrt4; pub mod speech; pub mod storage; pub mod xasync; @@ -66,6 +67,7 @@ pub(crate) fn all() -> Vec { all.push(lifecycle::module()); #[cfg(windows)] all.push(net::module()); + all.push(rpcrt4::module()); #[cfg(windows)] all.push(xmem::module()); #[cfg(windows)] diff --git a/crates/victory-hle/src/modules/rpcrt4.rs b/crates/victory-hle/src/modules/rpcrt4.rs new file mode 100644 index 0000000..ca9eac0 --- /dev/null +++ b/crates/victory-hle/src/modules/rpcrt4.rs @@ -0,0 +1,413 @@ +//! `rpcrt4.dll`: the GUID calls a title loads the RPC runtime for. +//! +//! The runtime itself is not passed through (its own `ws2_32` imports would +//! give a title a network path outside `modules::net`): the handful of calls +//! titles use are implemented here, and everything else stays refused as +//! before. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xgameruntime::Guid; + +/// `RPC_S_OK`. +const OK: i32 = 0; +/// `RPC_S_INVALID_STRING_UUID`. +const INVALID_STRING_UUID: i32 = 1705; +/// `RPC_S_OUT_OF_MEMORY`. +const OUT_OF_MEMORY: i32 = 14; + +/// A version 4 GUID: 16 random bytes, the version nibble and the variant +/// bits set. +extern "system" fn UuidCreate(uuid: *mut Guid) -> i32 { + create(uuid, false) +} + +/// As [`UuidCreate`]: sequential UUIDs carry a MAC address and a clock on +/// Windows, which a title must not learn about this machine. +extern "system" fn UuidCreateSequential(uuid: *mut Guid) -> i32 { + create(uuid, true) +} + +fn create(uuid: *mut Guid, _sequential: bool) -> i32 { + if uuid.is_null() { + return INVALID_STRING_UUID; + } + let mut bytes = [0u8; 16]; + if !random(&mut bytes) { + return OUT_OF_MEMORY; + } + // The third group's high nibble is the version, the fourth the variant. + bytes[7] = (bytes[7] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + // SAFETY: the caller passes a GUID to fill. + unsafe { uuid.write(from_bytes(bytes)) }; + OK +} + +/// 16 bytes from the host's CSPRNG. +fn random(bytes: &mut [u8; 16]) -> bool { + #[cfg(windows)] + { + use windows_sys::Win32::Security::Cryptography::{ + BCRYPT_USE_SYSTEM_PREFERRED_RNG, BCryptGenRandom, + }; + // SAFETY: our own buffer, the system's preferred generator. + let status = unsafe { + BCryptGenRandom( + std::ptr::null_mut(), + bytes.as_mut_ptr(), + bytes.len() as u32, + BCRYPT_USE_SYSTEM_PREFERRED_RNG, + ) + }; + status >= 0 + } + #[cfg(not(windows))] + { + // A counter mixed with the time: enough for identifiers in tests. + use std::sync::atomic::{AtomicU64, Ordering}; + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + ^ std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos() as u64); + for (i, b) in bytes.iter_mut().enumerate() { + *b = (n >> (8 * (i % 8))) as u8 ^ (i as u8).wrapping_mul(31); + } + true + } +} + +extern "system" fn UuidFromStringA(text: *const c_char, uuid: *mut Guid) -> i32 { + if text.is_null() || uuid.is_null() { + return INVALID_STRING_UUID; + } + // SAFETY: a NUL-terminated string from the caller. + let bytes = unsafe { std::ffi::CStr::from_ptr(text.cast()) }.to_bytes(); + match parse(bytes.iter().copied()) { + // SAFETY: the caller passes a GUID to fill. + Some(g) => unsafe { + uuid.write(g); + OK + }, + None => INVALID_STRING_UUID, + } +} + +extern "system" fn UuidFromStringW(text: *const u16, uuid: *mut Guid) -> i32 { + if text.is_null() || uuid.is_null() { + return INVALID_STRING_UUID; + } + let mut units = Vec::new(); + // SAFETY: a NUL-terminated wide string from the caller. + unsafe { + let mut at = text; + while *at != 0 { + units.push(*at); + at = at.add(1); + } + } + match parse(units.into_iter().map(|u| u as u32)) { + // SAFETY: the caller passes a GUID to fill. + Some(g) => unsafe { + uuid.write(g); + OK + }, + None => INVALID_STRING_UUID, + } +} + +extern "system" fn UuidToStringA(uuid: *const Guid, out: *mut *mut c_char) -> i32 { + // SAFETY: the caller passes a GUID to read, as the import declares. + let Some(g) = (unsafe { uuid.as_ref() }) else { + return INVALID_STRING_UUID; + }; + if out.is_null() { + return INVALID_STRING_UUID; + } + let text = format(g); + let mut bytes = Vec::with_capacity(37); + bytes.extend_from_slice(&text); + bytes.push(0); + // SAFETY: `out` is the caller's pointer variable. + unsafe { out.write(allocate(&bytes).cast()) }; + OK +} + +extern "system" fn UuidToStringW(uuid: *const Guid, out: *mut *mut u16) -> i32 { + // SAFETY: the caller passes a GUID to read, as the import declares. + let Some(g) = (unsafe { uuid.as_ref() }) else { + return INVALID_STRING_UUID; + }; + if out.is_null() { + return INVALID_STRING_UUID; + } + let text = format(g); + let mut units: Vec = text.iter().map(|&b| u16::from(b)).collect(); + units.push(0); + let bytes: Vec = units.iter().flat_map(|u| u.to_le_bytes()).collect(); + // SAFETY: `out` is the caller's pointer variable. + unsafe { out.write(allocate(&bytes).cast()) }; + OK +} + +extern "system" fn RpcStringFreeA(string: *mut *mut c_char) -> i32 { + free(string.cast()); + OK +} + +extern "system" fn RpcStringFreeW(string: *mut *mut u16) -> i32 { + free(string.cast()); + OK +} + +/// `[data1, data2, data3, data4]` as the console lays a GUID out. +fn from_bytes(b: [u8; 16]) -> Guid { + Guid { + data1: u32::from_le_bytes([b[0], b[1], b[2], b[3]]), + data2: u16::from_le_bytes([b[4], b[5]]), + data3: u16::from_le_bytes([b[6], b[7]]), + data4: [b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]], + } +} + +/// `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` in lower case. +fn format(g: &Guid) -> [u8; 36] { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut text = [b'-'; 36]; + let pairs = [ + (0, g.data1 as u64, 8), + (9, g.data2 as u64, 4), + (14, g.data3 as u64, 4), + (19, g.data4[0] as u64, 2), + (21, g.data4[1] as u64, 2), + (24, g.data4[2] as u64, 2), + (26, g.data4[3] as u64, 2), + (28, g.data4[4] as u64, 2), + (30, g.data4[5] as u64, 2), + (32, g.data4[6] as u64, 2), + (34, g.data4[7] as u64, 2), + ]; + for (at, value, digits) in pairs { + for i in 0..digits { + let shift = 4 * (digits - 1 - i); + text[at + i] = HEX[((value >> shift) & 0xf) as usize]; + } + } + text +} + +/// A GUID from its text, with or without braces and the dashes in place. +fn parse(mut chars: impl Iterator>) -> Option { + let mut digits = [0u8; 32]; + let mut n = 0; + for c in &mut chars { + let c = c.into(); + if n == 32 { + // Only the closing brace may follow the last digit. + return (c == u32::from(b'}')).then(|| assemble(&digits)); + } + if c == u32::from(b'-') || (n == 0 && c == u32::from(b'{')) { + continue; + } + let digit = match c { + 0x30..=0x39 => c - 0x30, + 0x61..=0x66 => c - 0x61 + 10, + 0x41..=0x46 => c - 0x41 + 10, + _ => return None, + }; + digits[n] = digit as u8; + n += 1; + } + (n == 32).then(|| assemble(&digits)) +} + +fn assemble(digits: &[u8; 32]) -> Guid { + let byte = |i: usize| (digits[2 * i] << 4) | digits[2 * i + 1]; + // The text is the number's big-endian form; the fields are words. + Guid { + data1: u32::from_be_bytes([byte(0), byte(1), byte(2), byte(3)]), + data2: u16::from_be_bytes([byte(4), byte(5)]), + data3: u16::from_be_bytes([byte(6), byte(7)]), + data4: [ + byte(8), + byte(9), + byte(10), + byte(11), + byte(12), + byte(13), + byte(14), + byte(15), + ], + } +} + +/// An allocation only [`RpcStringFreeA`] and [`RpcStringFreeW`] give back. +/// +/// The length is kept in a word before the bytes, so a title that hands the +/// pointer back through either free (A or W) releases the whole thing. +fn allocate(bytes: &[u8]) -> *mut u8 { + let len = 8 + bytes.len(); + let layout = std::alloc::Layout::from_size_align(len, 8).expect("a small allocation"); + // SAFETY: a fresh allocation of `len` bytes. + unsafe { + let base = std::alloc::alloc(layout); + if base.is_null() { + return std::ptr::null_mut(); + } + base.cast::().write_unaligned(bytes.len() as u64); + std::ptr::copy_nonoverlapping(bytes.as_ptr(), base.add(8), bytes.len()); + base.add(8) + } +} + +fn free(pointer: *mut *mut c_void) { + if pointer.is_null() { + return; + } + // SAFETY: the caller's pointer variable, holding what `allocate` made + // (or null, which is a no-op). + unsafe { + let at = pointer.read(); + if at.is_null() { + return; + } + let base = at.cast::().sub(8); + let len = base.cast::().read_unaligned() as usize; + let layout = std::alloc::Layout::from_size_align(8 + len, 8).expect("a small allocation"); + std::alloc::dealloc(base, layout); + pointer.write(std::ptr::null_mut()); + } +} + +pub(crate) fn module() -> crate::HleModule { + crate::HleModule { + name: "rpcrt4", + dlls: &["rpcrt4.dll"], + exports: vec![ + crate::hle_export!(UuidCreate), + crate::hle_export!(UuidCreateSequential), + crate::hle_export!(UuidFromStringA), + crate::hle_export!(UuidFromStringW), + crate::hle_export!(UuidToStringA), + crate::hle_export!(UuidToStringW), + crate::hle_export!(RpcStringFreeA), + crate::hle_export!(RpcStringFreeW), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_guid_formats_and_parses_back() { + let g = Guid::new( + 0x1234_abcd, + 0x00ef, + 0x4a5b, + [0x80, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde], + ); + let text = format(&g); + assert_eq!( + std::str::from_utf8(&text).unwrap(), + "1234abcd-00ef-4a5b-8012-3456789abcde" + ); + assert_eq!(parse(text.iter().copied()), Some(g)); + // Upper case and braces are what `UuidFromString` also takes. + let upper: Vec = std::iter::once(b'{') + .chain(text.iter().map(|b| b.to_ascii_uppercase())) + .chain(std::iter::once(b'}')) + .collect(); + assert_eq!(parse(upper.iter().copied()), Some(g)); + } + + #[test] + fn garbage_is_refused() { + assert_eq!(parse(b"1234".iter().copied()), None); + assert_eq!( + parse(b"1234abcd-00ef-4a5b-8012-3456789abcde-".iter().copied()), + None + ); + assert_eq!( + parse(b"1234abcd-00ef-4a5b-8012-3456789abcdeZ".iter().copied()), + None + ); + } + + #[test] + fn a_created_guid_is_version_four() { + for _ in 0..64 { + let mut g = Guid::new(0, 0, 0, [0; 8]); + assert_eq!(UuidCreate(&mut g), OK); + assert_eq!((g.data3 >> 12) & 0xf, 4, "{g}"); + assert_eq!(g.data4[0] >> 6, 0b10, "{g}"); + assert_ne!((g.data1, g.data2, g.data3, g.data4), (0, 0, 0, [0; 8])); + } + } + + #[test] + fn a_string_is_freed_once_through_either_call() { + let g = Guid::new(1, 2, 3, [4, 5, 6, 7, 8, 9, 10, 11]); + let mut text: *mut c_char = std::ptr::null_mut(); + assert_eq!(UuidToStringA(&g, &mut text), OK); + assert_eq!( + // SAFETY: the string we just made, NUL-terminated. + unsafe { std::ffi::CStr::from_ptr(text) }.to_str().unwrap(), + "00000001-0002-0003-0405-060708090a0b" + ); + assert_eq!(RpcStringFreeA(&mut text), OK); + assert!(text.is_null()); + + let mut wide: *mut u16 = std::ptr::null_mut(); + assert_eq!(UuidToStringW(&g, &mut wide), OK); + // SAFETY: the wide string we just made, NUL-terminated. + let units = unsafe { + let mut n = 0; + while *wide.add(n) != 0 { + n += 1; + } + std::slice::from_raw_parts(wide, n) + }; + let text: String = units.iter().map(|&u| u as u8 as char).collect(); + assert_eq!(text, "00000001-0002-0003-0405-060708090a0b"); + assert_eq!(RpcStringFreeW(&mut wide), OK); + assert!(wide.is_null()); + + // Freeing nothing is fine, as the runtime's does. + let mut none: *mut c_char = std::ptr::null_mut(); + assert_eq!(RpcStringFreeA(&mut none), OK); + assert_eq!(RpcStringFreeA(std::ptr::null_mut()), OK); + } + + #[test] + fn uuid_from_string_writes_what_it_reads() { + let text = c"1234abcd-00ef-4a5b-8012-3456789abcde"; + let mut g = Guid::new(0, 0, 0, [0; 8]); + assert_eq!(UuidFromStringA(text.as_ptr().cast(), &mut g), OK); + assert_eq!( + g, + Guid::new( + 0x1234_abcd, + 0x00ef, + 0x4a5b, + [0x80, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde] + ) + ); + // The wide call takes the same text. + let wide: Vec = "1234abcd-00ef-4a5b-8012-3456789abcde\0" + .chars() + .map(|c| c as u16) + .collect(); + let mut w = Guid::new(0, 0, 0, [0; 8]); + assert_eq!(UuidFromStringW(wide.as_ptr(), &mut w), OK); + assert_eq!(w, g); + assert_eq!( + UuidFromStringA(c"nope".as_ptr().cast(), &mut w), + INVALID_STRING_UUID + ); + } +} From 0aa61efd221cddc8135a46322f0e9e7292c9e2d1 Mon Sep 17 00:00:00 2001 From: DocBlack89 <22809438+DocBlack89@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:55:35 +0100 Subject: [PATCH 241/445] fix(pipeline): retry collisions when creating cache staging files Preserve stale staging files left by interrupted writers and retry a bounded number of atomic create_new attempts. Propagate unrelated I/O errors immediately. Add deterministic CPU regressions. AI-assisted. (cherry picked from commit a32eacdd5e0f2e55b5c0cddeb0d44d5fa93f9bb9) --- crates/victory-pipeline/src/cache.rs | 97 +++++++++++++++++++++++++--- 1 file changed, 87 insertions(+), 10 deletions(-) diff --git a/crates/victory-pipeline/src/cache.rs b/crates/victory-pipeline/src/cache.rs index 81e57de..9692d29 100644 --- a/crates/victory-pipeline/src/cache.rs +++ b/crates/victory-pipeline/src/cache.rs @@ -1,5 +1,7 @@ -use std::io::Write; +use std::fs::File; +use std::io::{self, Write}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; use anyhow::{Context, Result}; @@ -58,11 +60,7 @@ impl Cache { let dir = path.parent().expect("hashed path has a parent"); std::fs::create_dir_all(dir)?; // Write-then-rename so readers never see partial output. - let tmp = tempfile_in(dir); - let mut file = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&tmp)?; + let (tmp, mut file) = tempfile_in(dir)?; let written = file.write_all(&output); drop(file); let published = written.and_then(|()| std::fs::rename(&tmp, &path)); @@ -74,11 +72,31 @@ impl Cache { } } -fn tempfile_in(dir: &Path) -> PathBuf { - use std::sync::atomic::{AtomicU64, Ordering}; +fn tempfile_in(dir: &Path) -> io::Result<(PathBuf, File)> { static COUNTER: AtomicU64 = AtomicU64::new(0); - let n = COUNTER.fetch_add(1, Ordering::Relaxed); - dir.join(format!(".tmp-{}-{n}", std::process::id())) + create_tempfile_in(dir, &COUNTER) +} + +fn create_tempfile_in(dir: &Path, counter: &AtomicU64) -> io::Result<(PathBuf, File)> { + // An interrupted writer can leave a file behind, and process IDs are + // reused. Keep it intact and try a new name rather than failing a miss. + for _ in 0..128 { + let n = counter.fetch_add(1, Ordering::Relaxed); + let path = dir.join(format!(".tmp-{}-{n}", std::process::id())); + match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + { + Ok(file) => return Ok((path, file)), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + } + Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "could not create a unique cache staging file after 128 attempts", + )) } #[cfg(test)] @@ -138,6 +156,65 @@ mod tests { ); } + #[test] + fn staging_retries_collisions_without_changing_existing_files() { + let dir = tempfile::tempdir().unwrap(); + let counter = AtomicU64::new(0); + for n in 0..2 { + std::fs::write( + dir.path().join(format!(".tmp-{}-{n}", std::process::id())), + b"stale", + ) + .unwrap(); + } + + let (path, mut file) = create_tempfile_in(dir.path(), &counter).unwrap(); + file.write_all(b"fresh").unwrap(); + drop(file); + assert_eq!( + path.file_name().unwrap(), + format!(".tmp-{}-2", std::process::id()).as_str() + ); + assert_eq!(std::fs::read(&path).unwrap(), b"fresh"); + for n in 0..2 { + assert_eq!( + std::fs::read(dir.path().join(format!(".tmp-{}-{n}", std::process::id()))).unwrap(), + b"stale" + ); + } + assert_eq!(counter.load(Ordering::Relaxed), 3); + } + + #[test] + fn staging_collision_retries_are_bounded() { + let dir = tempfile::tempdir().unwrap(); + let counter = AtomicU64::new(0); + for n in 0..128 { + std::fs::write( + dir.path().join(format!(".tmp-{}-{n}", std::process::id())), + b"stale", + ) + .unwrap(); + } + + let error = create_tempfile_in(dir.path(), &counter).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::AlreadyExists); + assert_eq!(counter.load(Ordering::Relaxed), 128); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 128); + } + + #[test] + fn staging_does_not_retry_other_io_errors() { + let dir = tempfile::tempdir().unwrap(); + let counter = AtomicU64::new(0); + let missing = dir.path().join("missing"); + + let error = create_tempfile_in(&missing, &counter).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::NotFound); + assert_eq!(counter.load(Ordering::Relaxed), 1); + assert!(!missing.exists()); + } + #[test] fn version_bump_invalidates() { let v1 = Upper { From eabb82601c9b6243a2415853536d4dface1f9e98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:11:09 +0800 Subject: [PATCH 242/445] docs(architecture): list BCPack as implemented in victory-formats (cherry picked from commit aaacc2dcfe09afc10d0893b0259ef20afd326280) --- docs/architecture.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/architecture.md b/docs/architecture.md index 5e3e6b6..90baaf9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -35,7 +35,7 @@ Converting them ahead of time from files is only a warm-up. | `victory-hle` | console API implementations, host pass-through policy | | `victory-gpu` | D3D12.X objects, command lists and GPU memory → host D3D12 | | `victory-shader` | Xbox shader containers → host shaders | -| `victory-formats` | the GPU's texture layouts (sizes, tiling, detiling), audio codecs; planned: BCPack | +| `victory-formats` | the GPU's texture layouts (sizes, tiling, detiling), BCPack, audio codecs | | `victory-pipeline` | converter trait, content-addressed cache | | `victory-game` | the title-specific formats, build identities, hooks | | `apps/victory` | command-line front end | From 8961e15fc77100203e464716a298ba1e2dc532f1 Mon Sep 17 00:00:00 2001 From: TG0000 <122870448+TG0000@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:22:38 +0100 Subject: [PATCH 243/445] Formats: share immutable texture swizzle tables Co-Authored-By: GPT 6.2 Sol (cherry picked from commit 64b80c310941c8c105c9ac78fe4c29004f5e88a4) --- .../examples/texture_layout_bench.rs | 89 +++++++++++++++++++ crates/victory-formats/src/texture.rs | 64 +++++++++++-- 2 files changed, 147 insertions(+), 6 deletions(-) create mode 100644 crates/victory-formats/examples/texture_layout_bench.rs diff --git a/crates/victory-formats/examples/texture_layout_bench.rs b/crates/victory-formats/examples/texture_layout_bench.rs new file mode 100644 index 0000000..53c3936 --- /dev/null +++ b/crates/victory-formats/examples/texture_layout_bench.rs @@ -0,0 +1,89 @@ +//! Run with `cargo run --release -p victory-formats --example texture_layout_bench`. + +use std::hint::black_box; +use std::time::Instant; + +use victory_formats::texture::{Dimension, Swizzle, Texture, TextureDesc}; + +fn main() { + const CALLS: u64 = 50_000; + let base = TextureDesc { + dimension: Dimension::Tex2d, + width: 512, + height: 512, + depth_or_array: 1, + mips: 0, + format: 98, // BC7 + samples: 1, + swizzle: Swizzle::SW_64KB_D, + }; + let cases = [ + ("BC7 64KB_D", base), + ( + "BC1 64KB_S", + TextureDesc { + format: 71, + swizzle: Swizzle::SW_64KB_S, + ..base + }, + ), + ( + "RGBA8 4KB_D", + TextureDesc { + format: 28, + swizzle: Swizzle::SW_4KB_D, + ..base + }, + ), + ( + "R8 64KB_S", + TextureDesc { + format: 61, + swizzle: Swizzle::SW_64KB_S, + ..base + }, + ), + ( + "RGBA8 volume 64KB_S", + TextureDesc { + dimension: Dimension::Tex3d, + width: 128, + height: 128, + depth_or_array: 64, + format: 28, + swizzle: Swizzle::SW_64KB_S, + ..base + }, + ), + ( + "RGBA8 linear", + TextureDesc { + format: 28, + swizzle: Swizzle::LINEAR, + ..base + }, + ), + ]; + + for (name, desc) in cases { + let mut samples = [0.0; 7]; + black_box(Texture::new(black_box(&desc)).unwrap()); + let mut checksum = 0u64; + for sample in &mut samples { + let start = Instant::now(); + for i in 0..CALLS { + let desc = TextureDesc { + width: desc.width + (i % 32) as u32, + ..desc + }; + let texture = black_box(Texture::new(black_box(&desc)).unwrap()); + let layout = &texture.planes[0].layout; + checksum = + checksum.wrapping_add(texture.size + layout.offset(0, 7, 11, 0).unwrap()); + } + *sample = start.elapsed().as_secs_f64() * 1e9 / CALLS as f64; + } + samples.sort_by(f64::total_cmp); + println!("{name:22} {:8.1} ns/layout {checksum}", samples[3]); + } +} diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 469c174..2f4c25d 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -30,6 +30,8 @@ //! Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, //! EXPRESS OR IMPLIED. +use std::sync::OnceLock; + /// A swizzle mode, by its hardware number (addrlib's `ADDR_SW_*` order). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Swizzle(pub u32); @@ -174,11 +176,14 @@ pub struct Layout { /// The first mip in the tail; `mips.len()` without one. pub first_tail_mip: u32, pub mips: Vec, - /// Byte offsets inside a block of each element coordinate bit, per - /// axis; empty for linear and unsupported modes. - pattern: [Vec; 3], + /// Byte offsets inside a block for each coordinate, per axis. + /// Empty for linear and unsupported modes. + pattern: &'static SwizzlePattern, } +type SwizzlePattern = [Vec; 3]; +static EMPTY_PATTERN: SwizzlePattern = [const { Vec::new() }; 3]; + /// Micro tile (256 bytes) patterns by log2 of the element size: for each /// address bit, the element coordinate bit it takes (`x0`, `y1`, `z0`...), /// `--` for the bits inside an element. Thin `S`, thin `D`, thick `S` @@ -247,6 +252,18 @@ fn spread(bits: &[u32]) -> Vec { .collect() } +/// Tables depend only on the micro-tile kind, block size and element size. +/// Texture extents, mip placement and array slices only affect the base +/// address, so layouts with the same key can share these immutable tables. +fn shared_pattern(kind: usize, element_log2: u32, block_log2: u32) -> &'static SwizzlePattern { + // Indexed by MICRO kind, block size (256 B, 4 KiB, 64 KiB), then element size. + static PATTERNS: [[[OnceLock; 5]; 3]; 3] = + [const { [const { [const { OnceLock::new() }; 5] }; 3] }; 3]; + let block_index = ((block_log2 - 8) / 4) as usize; + PATTERNS[kind][block_index][element_log2 as usize] + .get_or_init(|| pattern(kind, element_log2, block_log2).map(|bits| spread(&bits))) +} + const MAX_MIPS: u32 = 16; /// The largest width, height and depth (or array size) accepted, in texels. @@ -323,7 +340,7 @@ impl Layout { alignment: 256, first_tail_mip: d.mips, mips, - pattern: Default::default(), + pattern: &EMPTY_PATTERN, } } @@ -491,9 +508,9 @@ impl Layout { } else { usize::from(d.swizzle.display()) }; - pattern(kind, element_log2, block_log2).map(|bits| spread(&bits)) + shared_pattern(kind, element_log2, block_log2) } else { - Default::default() + &EMPTY_PATTERN }; Layout { desc: d, @@ -1106,6 +1123,41 @@ mod tests { assert_eq!(l.offset(0, 0, 16, 0), Ok(8192)); } + #[test] + fn layouts_share_identical_swizzle_tables() { + for (swizzle, kind, dimension, block_log2) in [ + (Swizzle::SW_256B_S, 0, Dimension::Tex2d, 8), + (Swizzle::SW_256B_D, 1, Dimension::Tex2d, 8), + (Swizzle::SW_4KB_S, 0, Dimension::Tex2d, 12), + (Swizzle::SW_4KB_D, 1, Dimension::Tex2d, 12), + (Swizzle::SW_64KB_S, 0, Dimension::Tex2d, 16), + (Swizzle::SW_64KB_D, 1, Dimension::Tex2d, 16), + (Swizzle::SW_4KB_S, 2, Dimension::Tex3d, 12), + (Swizzle::SW_64KB_S, 2, Dimension::Tex3d, 16), + ] { + for element_log2 in 0..5 { + let d = Desc { + dimension, + depth: 8, + ..desc(128, 96, 7, 1 << element_log2, swizzle) + }; + let first = Layout::new(&d).unwrap(); + let second = Layout::new(&Desc { + width: 32, + height: 24, + mips: 3, + depth: 1, + ..d + }) + .unwrap(); + let expected = pattern(kind, element_log2, block_log2).map(|bits| spread(&bits)); + assert_eq!(first.pattern, &expected); + assert!(std::ptr::eq(first.pattern, second.pattern)); + assert!(std::ptr::eq(first.pattern, first.clone().pattern)); + } + } + } + /// A 256x256 BC7 chain in 64 KiB `D`: one tail block holding mips 1-8, /// then mip 0; mip 1 sits at x = 32 elements, 32 KiB into the tail. #[test] From 6aa6fc1cbb680fc390849896f3f4ae81198ef604 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:23:05 +0800 Subject: [PATCH 244/445] loader(crash): verify unwind against known caller frames when RtlCaptureStackBackTrace returns empty (cherry picked from commit 121412bec21b0790d04d56399f49e2d140652864) --- crates/victory-loader/src/crash.rs | 117 +++++++++++++++++++++++++---- 1 file changed, 103 insertions(+), 14 deletions(-) diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index 62388ad..7062bbd 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -766,26 +766,115 @@ mod tests { EXCEPTION_RECORD, RtlCaptureContext, RtlCaptureStackBackTrace, }; + /// What [`capture_frames`] saw: our [`unwind`], then the system's walk. + type Captured = (Vec, Vec); + + /// A frame we expect [`unwind`] to report: the helper it is in, and the + /// helper's name for the message. + type Expected = (&'static str, fn() -> Captured); + + /// The runtime function entry start covering `at`: the image base the + /// lookup writes, plus the entry's `BeginAddress`. Asking the system for + /// both sides of the comparison means a thunk or an incremental-link jump + /// is not mistaken for a different function. + fn entry_start_at(at: u64) -> Option { + let mut image = 0; + // SAFETY: looks up the function table entry covering `at`; nothing + // keeps a reference to the entry past this call. + let entry = unsafe { RtlLookupFunctionEntry(at, &mut image, null_mut()) }; + if entry.is_null() { + return None; + } + // SAFETY: a non-null entry belongs to `image`, which the lookup wrote, + // and `BeginAddress` is an offset into that image. + Some(image + u64::from(unsafe { (*entry).BeginAddress })) + } + #[test] - #[inline(never)] fn unwinds_like_the_system_walk() { - // SAFETY: zeroed CONTEXT is valid; both calls write our buffers. - let (frames, walked) = unsafe { - // `RtlCaptureContext` wants it 16-byte aligned too. + // Asking the system's own walk whether the stack looks right is not + // reliable: on Windows 10 x64 debug builds `RtlCaptureStackBackTrace` + // returns no frames about half the time. The frames above us are + // known instead (see `level_a`), so check those first. + let (frames, walked) = level_a(); + // Frame 0 is in `capture_frames`, which took the context; then its + // callers in call order, each named by its runtime function entry. + let helpers: [Expected; 4] = [ + ("capture_frames", capture_frames), + ("level_c", level_c), + ("level_b", level_b), + ("level_a", level_a), + ]; + assert!(frames.len() >= helpers.len(), "{frames:?}"); + for (i, (name, helper)) in helpers.iter().enumerate() { + let want = entry_start_at(*helper as usize as u64) + .unwrap_or_else(|| panic!("no unwind data for {name}")); + let got = entry_start_at(frames[i]) + .unwrap_or_else(|| panic!("no unwind data for frame {i} at {:#x}", frames[i])); + assert_eq!(got, want, "frame {i} should be {name}: {frames:?}"); + } + // A walk that repeats an address is not a walk. + let mut distinct = frames[..helpers.len()].to_vec(); + distinct.sort_unstable(); + distinct.dedup(); + assert_eq!(distinct.len(), helpers.len(), "repeated: {frames:?}"); + // Where the system's walk does return frames, it must still agree with + // ours: frame 0 differs (both are in `capture_frames`, at different + // call sites), and the callers above are the same. + if walked.len() >= helpers.len() { + assert!(frames.len() >= walked.len(), "{frames:?} vs {walked:?}"); + let ours: Vec = frames[1..walked.len()] + .iter() + .map(|&f| f as usize) + .collect(); + assert_eq!(ours.as_slice(), &walked[1..]); + } + } + + /// The frames of this call, both ways: our [`unwind`], and the system's + /// walk, which Windows 10 can come up empty on. + #[inline(never)] + fn capture_frames() -> Captured { + // SAFETY: a zeroed CONTEXT is valid and both calls write buffers of + // ours; `RtlCaptureContext` wants the context 16-byte aligned too. + unsafe { let mut context = Aligned16(std::mem::zeroed()); RtlCaptureContext(&mut context.0); let mut walked = [null_mut(); 8]; let n = RtlCaptureStackBackTrace(0, 8, walked.as_mut_ptr(), null_mut()); - (unwind(context.0), walked[..usize::from(n)].to_vec()) - }; - // Frame 0 differs (two call sites in this function); callers agree. - assert!(walked.len() >= 4, "{walked:?}"); - let ours: Vec<_> = frames[1..walked.len()] - .iter() - .map(|&f| f as usize) - .collect(); - let system: Vec<_> = walked[1..].iter().map(|&f| f as usize).collect(); - assert_eq!(ours, system); + let frames = unwind(context.0); + let walked = walked[..usize::from(n)] + .iter() + .map(|&f| f as usize) + .collect(); + (frames, walked) + } + } + + /// `level_a` → `level_b` → `level_c` → [`capture_frames`]: three known + /// callers above the capture. `black_box` after each call keeps it from + /// becoming a tail call, which would erase the caller's frame. + #[inline(never)] + fn level_a() -> Captured { + let captured = level_b(); + std::hint::black_box(&captured); + captured + } + + /// See [`level_a`]. + #[inline(never)] + fn level_b() -> Captured { + let captured = level_c(); + std::hint::black_box(&captured); + captured + } + + /// See [`level_a`]. + #[inline(never)] + fn level_c() -> Captured { + let captured = capture_frames(); + std::hint::black_box(&captured); + captured } #[test] From 62d1b8139ead055d55987a5ada8f59a2584a0c63 Mon Sep 17 00:00:00 2001 From: TG0000 <122870448+TG0000@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:59:51 +0100 Subject: [PATCH 245/445] GPU: seek directly to private data on final release Co-Authored-By: GPT 6.2 Sol (cherry picked from commit 3e98bd7e0ce79762162ac958e3ab67cc85de00c9) --- crates/victory-gpu/src/object.rs | 147 ++++++++++++++++++++++++++++++- 1 file changed, 146 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/object.rs b/crates/victory-gpu/src/object.rs index fd7d506..6671d4b 100644 --- a/crates/victory-gpu/src/object.rs +++ b/crates/victory-gpu/src/object.rs @@ -136,7 +136,16 @@ pub(crate) fn release_boxed(this: This) -> u32 { let refs = &unsafe { &*this }.refs; match refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1)) { Ok(1) => { - private_data().retain(|&(object, _), _| object != this as usize); + let address = this as usize; + let keys = (address, [u8::MIN; 16])..=(address, [u8::MAX; 16]); + { + let mut data = private_data(); + // An object's IDs are contiguous in key order. Seek directly to + // them so releases don't visit private data held by other objects. + while let Some((&key, _)) = data.range(keys.clone()).next() { + data.remove(&key); + } + } // SAFETY: that was the last reference to a `Box`. drop(unsafe { Box::from_raw(this.cast_mut().cast::()) }); 0 @@ -373,6 +382,142 @@ pub(crate) fn slot(object: This, offset: usize) -> F { mod tests { use super::*; + const TAG: Iid = [1; 16]; + const OTHER_TAG: Iid = [2; 16]; + + extern "system" fn release_test_object(this: This) -> u32 { + release_boxed::(this) + } + + fn new_test_object() -> This { + static TABLE: Table<7> = { + let mut functions = d3d12_object(missing_table::()); + functions[2] = release_test_object as *const (); + Table(functions) + }; + let mut this = std::ptr::null(); + assert_eq!( + hand_out( + DEVICE, + Box::new(Object::new(&TABLE)), + &TAG, + &[TAG], + &mut this + ), + S_OK + ); + this + } + + #[test] + fn private_data_is_scoped_to_object_and_id() { + let first = new_test_object(); + let second = new_test_object(); + let set = + slot:: HRESULT>(first, 0x20); + let get = + slot:: HRESULT>(first, 0x18); + let release = slot:: u32>(first, 0x10); + + assert_eq!(set(first, &TAG, 1, b"a".as_ptr()), S_OK); + assert_eq!(set(first, &OTHER_TAG, 0, b"".as_ptr()), S_OK); + assert_eq!(set(second, &TAG, 2, b"bc".as_ptr()), S_OK); + assert_eq!(set(first, &TAG, 3, b"def".as_ptr()), S_OK); + assert_eq!(add_ref(first), 2); + assert_eq!(release(first), 1); + + let mut size = 0; + let mut data = [0; 3]; + assert_eq!(get(first, &TAG, &mut size, std::ptr::null_mut()), S_OK); + assert_eq!(size, 3); + size = 1; + assert_eq!(get(first, &TAG, &mut size, data.as_mut_ptr()), MORE_DATA); + assert_eq!(size, 3); + assert_eq!(data, [0; 3]); + assert_eq!(get(first, &TAG, &mut size, data.as_mut_ptr()), S_OK); + assert_eq!(&data, b"def"); + + assert_eq!(set(first, &TAG, 99, std::ptr::null()), S_OK); + assert_eq!(get(first, &TAG, &mut size, data.as_mut_ptr()), NOT_FOUND); + assert_eq!(size, 0); + assert_eq!(get(first, &OTHER_TAG, &mut size, data.as_mut_ptr()), S_OK); + assert_eq!(size, 0); + assert_eq!(release(first), 0); + size = 3; + assert_eq!(get(second, &TAG, &mut size, data.as_mut_ptr()), S_OK); + assert_eq!(&data[..size as usize], b"bc"); + assert_eq!(release(second), 0); + } + + #[test] + #[ignore = "synthetic release benchmark; run with --release --ignored --nocapture"] + fn benchmark_private_data_release() { + use std::hint::black_box; + use std::time::Instant; + + const RELEASES: usize = 50_000; + for count in [128, 512, 1024] { + let live: Vec<_> = (0..count).map(|_| new_test_object()).collect(); + let set = slot:: HRESULT>( + live[0], 0x20, + ); + let release = slot:: u32>(live[0], 0x10); + for &object in &live { + assert_eq!(set(object, &TAG, 1, b"a".as_ptr()), S_OK); + } + let mut samples = [0.0; 5]; + for sample in &mut samples { + let mut retiring: Vec<_> = (0..256).map(|_| new_test_object()).collect(); + let retiring_count = retiring.len(); + let start = Instant::now(); + for index in 0..RELEASES { + let object = new_test_object(); + if index % 4 == 0 { + assert_eq!(set(object, &TAG, 1, b"b".as_ptr()), S_OK); + } + let old = std::mem::replace(&mut retiring[index % retiring_count], object); + black_box(release(black_box(old))); + } + *sample = start.elapsed().as_secs_f64() * 1e9 / RELEASES as f64; + for object in retiring { + assert_eq!(release(object), 0); + } + } + samples.sort_by(f64::total_cmp); + println!( + "{count:4} live entries: {:8.1} ns/object (median)", + samples[2] + ); + for object in live { + assert_eq!(release(object), 0); + } + } + } + + #[test] + fn final_release_clears_private_data_before_drop() { + #[repr(C)] + struct OwnedObject(Object); + + impl Drop for OwnedObject { + fn drop(&mut self) { + let address = std::ptr::from_ref(&self.0) as usize; + let data = private_data(); + assert!(!data.contains_key(&(address, [u8::MIN; 16]))); + assert!(!data.contains_key(&(address, TAG))); + assert!(!data.contains_key(&(address, [u8::MAX; 16]))); + } + } + + static TABLE: Table<0> = Table([]); + let this: This = Box::into_raw(Box::new(OwnedObject(Object::new(&TABLE)))).cast(); + assert_eq!(add_ref(this), 1); + for id in [[u8::MIN; 16], TAG, [u8::MAX; 16]] { + assert_eq!(set_private_data(this, &id, 1, b"a".as_ptr()), S_OK); + } + assert_eq!(release_boxed::(this), 0); + } + #[test] fn guids_round_trip_through_text() { let g = guid( From c7541110d491a3c74eb2c8ab9605c3547d4ffbcc Mon Sep 17 00:00:00 2001 From: Aws Date: Tue, 24 Nov 2026 06:24:18 -0500 Subject: [PATCH 246/445] List successfully emitted shaders in offline translation scans (cherry picked from commit 6d174aeeeb93669ab9f43ff01b24963933433af8) --- apps/victory/src/translate.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index caaa7da..35492e3 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -720,6 +720,9 @@ fn check( } } let Some(v) = checks.validator.as_mut() else { + if t.list && checks.host.is_none() { + t.lines.push(format!("{} emitted", label())); + } return; }; match v.validate(&mut shader.dxil) { From ed07828ce2faadf0e5dd56a609979e16e1d87969 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:37:34 +0800 Subject: [PATCH 247/445] PE: add synthetic unit tests for implib.rs and layout.rs (cherry picked from commit 131944d02dc0b37469f85f907234c664eb8027af) --- crates/victory-pe/src/implib.rs | 568 ++++++++++++++++++++++++++++++++ crates/victory-pe/src/layout.rs | 161 +++++++++ 2 files changed, 729 insertions(+) diff --git a/crates/victory-pe/src/implib.rs b/crates/victory-pe/src/implib.rs index 234c1ec..9378a7b 100644 --- a/crates/victory-pe/src/implib.rs +++ b/crates/victory-pe/src/implib.rs @@ -64,3 +64,571 @@ impl ImportLibrary { Ok(lib) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::MACHINE_AMD64; + + /// `Sig1`, which must be `IMAGE_FILE_MACHINE_UNKNOWN` (not a machine). + const SIG1: u16 = 0; + /// `Sig2` of a short-format import object (`IMPORT_OBJECT_HDR_SIG2`). + const SIG2: u16 = 0xFFFF; + + /// `Type` field of the header, a 2-bit value at bit 0. + mod import_type { + pub const CODE: u16 = 0; + pub const DATA: u16 = 1; + pub const CONST: u16 = 2; + } + + /// `NameType` field of the header, a 3-bit value at bit 2. + mod name_type { + pub const ORDINAL: u16 = 0; + pub const NAME: u16 = 1; + pub const NAME_NO_PREFIX: u16 = 2; + pub const NAME_UNDECORATE: u16 = 3; + pub const NAME_EXPORTAS: u16 = 4; + } + + /// One short-format import object: the 20-byte header followed by the + /// NUL-terminated symbol, DLL and (for `NAME_EXPORTAS`) export names. + fn import_object( + import_type: u16, + name_type: u16, + ordinal_or_hint: u16, + symbol: &str, + dll: &str, + export_as: Option<&str>, + ) -> Vec { + let mut strings = Vec::new(); + for s in [Some(symbol), Some(dll), export_as].into_iter().flatten() { + strings.extend_from_slice(s.as_bytes()); + strings.push(0); + } + let mut out = Vec::new(); + out.extend_from_slice(&SIG1.to_le_bytes()); + out.extend_from_slice(&SIG2.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); // Version + out.extend_from_slice(&MACHINE_AMD64.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); // TimeDateStamp + out.extend_from_slice(&(strings.len() as u32).to_le_bytes()); + out.extend_from_slice(&ordinal_or_hint.to_le_bytes()); + out.extend_from_slice(&(import_type | name_type << 2).to_le_bytes()); + out.extend_from_slice(&strings); + out + } + + /// One archive member: the 60-byte header, the data, and the pad byte the + /// format adds so the next header starts even. + fn archive_member(name: &str, data: &[u8]) -> Vec { + assert!(name.len() <= 16, "an archive member name is 16 bytes"); + let mut out = vec![b' '; 60]; + out[..name.len()].copy_from_slice(name.as_bytes()); + let size = data.len().to_string(); + out[48..48 + size.len()].copy_from_slice(size.as_bytes()); + out[58] = b'`'; + out[59] = b'\n'; + out.extend_from_slice(data); + if data.len() % 2 == 1 { + out.push(b'\n'); + } + out + } + + fn archive(members: Vec<(&str, Vec)>) -> Vec { + let mut out = b"!\n".to_vec(); + for (name, data) in members { + out.extend_from_slice(&archive_member(name, &data)); + } + out + } + + #[test] + fn parses_named_code_imports() { + // Deliberately out of order, to show that the result is sorted. + let lib = archive(vec![ + ( + "version.dll/", + import_object( + import_type::CODE, + name_type::NAME, + 0, + "GetFileVersionInfoSizeW", + "version.dll", + None, + ), + ), + ( + "kernel32.dll/", + import_object( + import_type::CODE, + name_type::NAME, + 7, + "ExitProcess", + "kernel32.dll", + None, + ), + ), + ]); + let parsed = ImportLibrary::parse(&lib).unwrap(); + assert_eq!(parsed.other_members, 0); + assert_eq!( + parsed.imports, + [ + LibImport { + dll: "kernel32.dll".into(), + // `object` does not expose the hint of a short-format + // import, so it is always 0 here. + export: ImportSymbol::Name { + hint: 0, + name: "ExitProcess".into() + }, + kind: LibImportKind::Code, + }, + LibImport { + dll: "version.dll".into(), + export: ImportSymbol::Name { + hint: 0, + name: "GetFileVersionInfoSizeW".into() + }, + kind: LibImportKind::Code, + }, + ] + ); + } + + #[test] + fn parses_imports_by_ordinal() { + let lib = archive(vec![( + "d3d12.dll/", + import_object( + import_type::CODE, + name_type::ORDINAL, + 42, + "Alpha", + "d3d12.dll", + None, + ), + )]); + let parsed = ImportLibrary::parse(&lib).unwrap(); + assert_eq!(parsed.other_members, 0); + assert_eq!(parsed.imports.len(), 1); + assert_eq!(parsed.imports[0].dll, "d3d12.dll"); + assert_eq!(parsed.imports[0].export, ImportSymbol::Ordinal(42)); + assert_eq!(parsed.imports[0].kind, LibImportKind::Code); + } + + #[test] + fn maps_the_import_kinds() { + let lib = archive(vec![ + ( + "a.dll/", + import_object( + import_type::DATA, + name_type::NAME, + 0, + "tls_index", + "a.dll", + None, + ), + ), + ( + "b.dll/", + import_object( + import_type::CONST, + name_type::NAME, + 0, + "limit", + "b.dll", + None, + ), + ), + ]); + let parsed = ImportLibrary::parse(&lib).unwrap(); + let kinds: Vec<_> = parsed.imports.iter().map(|i| i.kind).collect(); + assert_eq!(parsed.other_members, 0); + assert_eq!(parsed.imports.len(), 2); + assert!(kinds.contains(&LibImportKind::Data)); + assert!(kinds.contains(&LibImportKind::Const)); + assert!(!kinds.contains(&LibImportKind::Code)); + } + + #[test] + fn a_name_exported_under_another_name_uses_the_export() { + let lib = archive(vec![( + "a.dll/", + import_object( + import_type::CODE, + name_type::NAME_EXPORTAS, + 0, + "__imp_local", + "a.dll", + Some("Remote"), + ), + )]); + let parsed = ImportLibrary::parse(&lib).unwrap(); + assert_eq!(parsed.other_members, 0); + assert_eq!( + parsed.imports[0].export, + ImportSymbol::Name { + hint: 0, + name: "Remote".into() + } + ); + } + + #[test] + fn prefixed_and_decorated_symbols_are_cleaned_up() { + // `NAME_NO_PREFIX` drops a leading `?`, `@` or `_`; `NAME_UNDECORATE` + // also stops at the first `@`. Both are what a linker writes for C + // symbols, so the map holds the plain export name. + let lib = archive(vec![ + ( + "a.dll/", + import_object( + import_type::CODE, + name_type::NAME_NO_PREFIX, + 0, + "_Remap", + "a.dll", + None, + ), + ), + ( + "b.dll/", + import_object( + import_type::CODE, + name_type::NAME_UNDECORATE, + 0, + "?Thing@@YAHXZ", + "b.dll", + None, + ), + ), + ( + "c.dll/", + import_object( + import_type::CODE, + name_type::NAME_NO_PREFIX, + 0, + "plain", + "c.dll", + None, + ), + ), + ]); + let parsed = ImportLibrary::parse(&lib).unwrap(); + let names: Vec<_> = parsed + .imports + .iter() + .map(|i| i.export.to_string()) + .collect(); + assert_eq!(parsed.other_members, 0); + assert_eq!(names, ["Remap", "Thing", "plain"]); + } + + #[test] + fn the_same_import_twice_is_listed_once() { + let exit_process = || { + import_object( + import_type::CODE, + name_type::NAME, + 0, + "ExitProcess", + "kernel32.dll", + None, + ) + }; + let lib = archive(vec![ + ("kernel32.dll/", exit_process()), + ("kernel32.dll/", exit_process()), + ]); + let parsed = ImportLibrary::parse(&lib).unwrap(); + assert_eq!(parsed.imports.len(), 1); + assert_eq!(parsed.other_members, 0); + } + + #[test] + fn the_same_symbol_of_a_different_kind_is_kept() { + // A data import (`__imp_`) and a code import of one name differ. + let lib = archive(vec![ + ( + "a.dll/", + import_object( + import_type::CODE, + name_type::NAME, + 0, + "table", + "a.dll", + None, + ), + ), + ( + "a.dll/", + import_object( + import_type::DATA, + name_type::NAME, + 0, + "table", + "a.dll", + None, + ), + ), + ]); + let parsed = ImportLibrary::parse(&lib).unwrap(); + assert_eq!(parsed.imports.len(), 2); + assert_ne!(parsed.imports[0].kind, parsed.imports[1].kind); + } + + #[test] + fn sorted_ordinal_and_named_exports_order_by_dll_then_name() { + let lib = archive(vec![ + ( + "b.dll/", + import_object( + import_type::CODE, + name_type::ORDINAL, + 1, + "second", + "b.dll", + None, + ), + ), + ( + "a.dll/", + import_object(import_type::CODE, name_type::NAME, 0, "zeta", "a.dll", None), + ), + ( + "a.dll/", + import_object( + import_type::CODE, + name_type::NAME, + 0, + "alpha", + "a.dll", + None, + ), + ), + ( + "a.dll/", + import_object( + import_type::CODE, + name_type::ORDINAL, + 9, + "first", + "a.dll", + None, + ), + ), + ]); + let parsed = ImportLibrary::parse(&lib).unwrap(); + let pairs: Vec<_> = parsed + .imports + .iter() + .map(|i| (i.dll.as_str(), i.export.clone())) + .collect(); + assert_eq!( + pairs, + [ + ( + "a.dll", + ImportSymbol::Name { + hint: 0, + name: "alpha".into() + } + ), + ( + "a.dll", + ImportSymbol::Name { + hint: 0, + name: "zeta".into() + } + ), + ("a.dll", ImportSymbol::Ordinal(9)), + ("b.dll", ImportSymbol::Ordinal(1)), + ] + ); + } + + #[test] + fn an_empty_archive_has_no_imports() { + let parsed = ImportLibrary::parse(b"!\n").unwrap(); + assert!(parsed.imports.is_empty()); + assert_eq!(parsed.other_members, 0); + } + + #[test] + fn linker_and_names_members_are_skipped_not_counted() { + // What a COFF archive looks like: two linker members, an optional + // names table, then the import objects. + let lib = archive(vec![ + ("/", vec![0; 8]), + ("/", vec![0; 8]), + ("//", b"a_long_member_name/\n".to_vec()), + ( + "kernel32.dll/", + import_object( + import_type::CODE, + name_type::NAME, + 0, + "ExitProcess", + "kernel32.dll", + None, + ), + ), + ( + "user32.dll/", + import_object( + import_type::CODE, + name_type::NAME, + 0, + "MessageBoxW", + "user32.dll", + None, + ), + ), + ]); + let parsed = ImportLibrary::parse(&lib).unwrap(); + assert_eq!(parsed.imports.len(), 2); + assert_eq!(parsed.other_members, 0); + } + + #[test] + fn members_that_are_not_import_objects_are_counted() { + let lib = archive(vec![ + // A regular COFF object starts with a machine, not a zero `Sig1`. + ("object.obj/", { + let mut object = Vec::new(); + object.extend_from_slice(&MACHINE_AMD64.to_le_bytes()); + object.extend_from_slice(&1u16.to_le_bytes()); // NumberOfSections + object.extend_from_slice(&0u32.to_le_bytes()); // TimeDateStamp + object.resize(60, 0); + object + }), + // A long-format descriptor: no short-format `Sig2`. + ("long.lib/", { + let mut long = import_object( + import_type::CODE, + name_type::NAME, + 0, + "Old", + "old.dll", + None, + ); + long[2..4].copy_from_slice(&0u16.to_le_bytes()); + long + }), + // An import header whose string table is cut short. + ("short.lib/", { + let mut short = import_object( + import_type::CODE, + name_type::NAME, + 0, + "Cut", + "cut.dll", + None, + ); + short.truncate(24); + short + }), + ( + "a.dll/", + import_object(import_type::CODE, name_type::NAME, 0, "Kept", "a.dll", None), + ), + ]); + let parsed = ImportLibrary::parse(&lib).unwrap(); + assert_eq!(parsed.other_members, 3); + assert_eq!(parsed.imports.len(), 1); + assert_eq!(parsed.imports[0].dll, "a.dll"); + } + + #[test] + fn odd_sized_members_are_padded_aligned() { + // 20-byte header plus 9 bytes of strings: the archive pads one byte, + // and the next member must still be found. + let odd = import_object(import_type::CODE, name_type::NAME, 0, "f", "ab", None); + assert_eq!(odd.len() % 2, 1); + let lib = archive(vec![ + ("a.dll/", odd), + ( + "b.dll/", + import_object(import_type::CODE, name_type::NAME, 0, "Next", "b.dll", None), + ), + ]); + let parsed = ImportLibrary::parse(&lib).unwrap(); + assert_eq!(parsed.imports.len(), 2); + assert_eq!(parsed.other_members, 0); + } + + #[test] + fn names_that_are_not_utf8_are_reported_lossily() { + // The symbol name "Café" is stored as UTF-8; replacing its lead byte + // leaves a stray continuation byte, so the member holds a name that + // is not valid UTF-8. + let mut lib = archive(vec![( + "x.dll/", + import_object( + import_type::CODE, + name_type::NAME, + 0, + "Caf\u{e9}", + "x.dll", + None, + ), + )]); + let at = lib + .windows(2) + .position(|w| w == [0xC3, 0xA9]) + .expect("the name is in the member"); + lib[at] = 0xFF; + let parsed = ImportLibrary::parse(&lib).unwrap(); + assert_eq!( + parsed.imports[0].export, + // One replacement character for the invalid byte, one for the + // continuation byte that is then unexpected. + ImportSymbol::Name { + hint: 0, + name: "Caf\u{fffd}\u{fffd}".into() + } + ); + } + + #[test] + fn rejects_input_that_is_not_an_archive() { + let cases: [&[u8]; 3] = [ + b"", + b"MZ a PE image, not a library", + b"!", // truncated magic + ]; + for data in cases { + assert!( + matches!(ImportLibrary::parse(data), Err(PeError::Malformed(_))), + "{data:?} must be rejected" + ); + } + } + + #[test] + fn rejects_a_truncated_member_header() { + let mut data = b"!\n".to_vec(); + data.extend_from_slice(&[b'x'; 20]); + assert!(matches!( + ImportLibrary::parse(&data), + Err(PeError::Malformed(_)) + )); + } + + #[test] + fn rejects_a_member_whose_data_is_cut_off() { + // The header promises 0x100 bytes, the archive holds 4. + let mut data = b"!\n".to_vec(); + let mut member = archive_member("a.dll/", &[0u8; 0x100]); + member.truncate(60 + 4); + data.extend_from_slice(&member); + assert!(matches!( + ImportLibrary::parse(&data), + Err(PeError::Malformed(_)) + )); + } +} diff --git a/crates/victory-pe/src/layout.rs b/crates/victory-pe/src/layout.rs index 888f9d2..3960fdb 100644 --- a/crates/victory-pe/src/layout.rs +++ b/crates/victory-pe/src/layout.rs @@ -101,10 +101,171 @@ pub fn read_u64(data: &[u8], at: usize) -> Option { mod tests { use super::*; + /// Length of a synthetic PE32+ prefix whose `e_lfanew` is 0x40: it ends + /// right after the 16th (last) data directory entry. + const IMAGE_LEN: usize = + 0x40 + NT_SIGNATURE_SIZE + FILE_HEADER_SIZE + OPT_DATA_DIRECTORY + 16 * DATA_DIRECTORY_SIZE; + + /// A synthetic PE32+ prefix: DOS header pointing at the NT headers, the + /// PE32+ magic, and a full data directory table of 16 entries. + fn image() -> Vec { + let mut data = vec![0u8; IMAGE_LEN]; + data[..2].copy_from_slice(b"MZ"); + data[DOS_E_LFANEW..DOS_E_LFANEW + 4].copy_from_slice(&0x40u32.to_le_bytes()); + let opt = optional_header_offset(&data).unwrap(); + data[opt..opt + 2].copy_from_slice(&0x20Bu16.to_le_bytes()); + data[opt + OPT_NUMBER_OF_RVA_AND_SIZES..opt + OPT_NUMBER_OF_RVA_AND_SIZES + 4] + .copy_from_slice(&16u32.to_le_bytes()); + data + } + #[test] fn reads_reject_overflowing_offsets() { let data = [0u8; 16]; assert_eq!(read_u32(&data, usize::MAX - 1), None); assert_eq!(read_u64(&data, usize::MAX - 2), None); } + + #[test] + fn reads_little_endian_values_at_the_edges_of_the_buffer() { + let mut data = [0u8; 8]; + data.copy_from_slice(&0x0123_4567_89AB_CDEFu64.to_le_bytes()); + assert_eq!(read_u32(&data, 0), Some(0x89AB_CDEF)); + assert_eq!(read_u32(&data, 4), Some(0x0123_4567)); + // One byte short of a field is not a field. + assert_eq!(read_u32(&data, 5), None); + assert_eq!(read_u32(&data, 8), None); + assert_eq!(read_u64(&data, 0), Some(0x0123_4567_89AB_CDEF)); + assert_eq!(read_u64(&data, 1), None); + assert_eq!(read_u64(&data, 8), None); + assert_eq!(read_u32(b"", 0), None); + assert_eq!(read_u64(b"", 0), None); + } + + #[test] + fn header_offsets_follow_e_lfanew() { + let data = image(); + assert_eq!(file_header_offset(&data), Some(0x40 + NT_SIGNATURE_SIZE)); + assert_eq!( + optional_header_offset(&data), + Some(0x40 + NT_SIGNATURE_SIZE + FILE_HEADER_SIZE) + ); + let fh = file_header_offset(&data).unwrap(); + let opt = optional_header_offset(&data).unwrap(); + assert_eq!(opt - fh, FILE_HEADER_SIZE); + } + + #[test] + fn header_offsets_need_the_dos_header() { + assert_eq!(optional_header_offset(b""), None); + assert_eq!(file_header_offset(b""), None); + // `e_lfanew` is the last field the offsets read. + assert_eq!(optional_header_offset(&[0u8; DOS_E_LFANEW]), None); + let mut data = [0u8; DOS_E_LFANEW + 4]; + data[DOS_E_LFANEW..].copy_from_slice(&0x40u32.to_le_bytes()); + assert_eq!(file_header_offset(&data), Some(0x44)); + assert_eq!(optional_header_offset(&data), Some(0x58)); + } + + #[test] + fn a_hostile_e_lfanew_is_passed_on_but_the_readers_refuse_it() { + // The offsets are pure arithmetic, so an `e_lfanew` past the end of + // the buffer is reported unchanged; every read through it is + // bounds-checked. (A value near `u32::MAX` would also overflow the + // addition on a 32-bit host, which is why it is a `checked_add`.) + let mut data = [0u8; DOS_E_LFANEW + 4]; + data[DOS_E_LFANEW..].copy_from_slice(&0x10_0000u32.to_le_bytes()); + assert_eq!(file_header_offset(&data), Some(0x10_0004)); + assert_eq!(optional_header_offset(&data), Some(0x10_0018)); + assert_eq!( + optional_header_offset(&data).and_then(|at| read_u32(&data, at)), + None + ); + assert_eq!( + file_header_offset(&data).and_then(|at| read_u32(&data, at)), + None + ); + assert_eq!(data_directory_offset(&data, dir::IMPORT), None); + } + + #[test] + fn data_directory_offsets_are_indexed_from_the_optional_header() { + let data = image(); + let opt = optional_header_offset(&data).unwrap(); + assert_eq!( + data_directory_offset(&data, 0), + Some(opt + OPT_DATA_DIRECTORY) + ); + assert_eq!( + data_directory_offset(&data, dir::IMPORT), + Some(opt + OPT_DATA_DIRECTORY + DATA_DIRECTORY_SIZE) + ); + assert_eq!( + data_directory_offset(&data, 15), + Some(opt + OPT_DATA_DIRECTORY + 15 * DATA_DIRECTORY_SIZE) + ); + // The table holds 16 entries in this image. + assert_eq!(data_directory_offset(&data, 16), None); + assert_eq!(data_directory_offset(&data, usize::MAX), None); + } + + #[test] + fn data_directory_offset_honours_a_shorter_table() { + let mut data = image(); + let opt = optional_header_offset(&data).unwrap(); + data[opt + OPT_NUMBER_OF_RVA_AND_SIZES..opt + OPT_NUMBER_OF_RVA_AND_SIZES + 4] + .copy_from_slice(&3u32.to_le_bytes()); + assert!(data_directory_offset(&data, 2).is_some()); + assert_eq!(data_directory_offset(&data, 3), None); + assert_eq!(data_directory_offset(&data, dir::IAT), None); + } + + #[test] + fn data_directory_offset_needs_the_count_and_the_header() { + let full = image(); + let opt = optional_header_offset(&full).unwrap(); + // Ends exactly where `NumberOfRvaAndSizes` starts. + let cut = &full[..opt + OPT_NUMBER_OF_RVA_AND_SIZES]; + assert_eq!( + data_directory_offset(cut, dir::IMPORT), + None, + "a header without the count field has no directories" + ); + assert_eq!(data_directory_offset(b"", dir::IMPORT), None); + assert_eq!(data_directory_offset(b"MZ", dir::IMPORT), None); + } + + #[test] + fn a_data_directory_entry_reads_back_as_the_image_wrote_it() { + let mut data = image(); + let at = data_directory_offset(&data, dir::IMPORT).unwrap(); + data[at..at + 4].copy_from_slice(&0x3000u32.to_le_bytes()); + data[at + 4..at + 8].copy_from_slice(&0x28u32.to_le_bytes()); + assert_eq!(read_u32(&data, at), Some(0x3000)); + assert_eq!(read_u32(&data, at + 4), Some(0x28)); + } + + #[test] + fn constants_match_the_pe32_layout() { + // Offsets of fields inside the structures they are named after. + assert_eq!(DOS_E_LFANEW, 0x3C); + assert_eq!(NT_SIGNATURE_SIZE, 4); + assert_eq!(FILE_HEADER_SIZE, 20); + assert_eq!(FILE_HEADER_CHARACTERISTICS, FILE_HEADER_SIZE - 2); + assert_eq!(OPT_ADDRESS_OF_ENTRY_POINT, 16); + assert_eq!(OPT_CHECKSUM, 64); + assert_eq!(OPT_DLL_CHARACTERISTICS, 70); + assert_eq!(OPT_NUMBER_OF_RVA_AND_SIZES, 108); + assert_eq!(OPT_DATA_DIRECTORY, OPT_NUMBER_OF_RVA_AND_SIZES + 4); + assert_eq!(DATA_DIRECTORY_SIZE, 8); + assert_eq!(TLS64_ADDRESS_OF_CALLBACKS, 24); + + // Data directory indices, which `prepare` patches by number. + assert_eq!(dir::IMPORT, 1); + assert_eq!(dir::EXCEPTION, 3); + assert_eq!(dir::BASERELOC, 5); + assert_eq!(dir::LOAD_CONFIG, 10); + assert_eq!(dir::BOUND_IMPORT, 11); + assert_eq!(dir::IAT, 12); + } } From 3af6d8fb0e9ca5784e60e67262b0284323988b32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:44:19 +0800 Subject: [PATCH 248/445] GPU: add synthetic unit tests for query.rs and signature.rs (cherry picked from commit 0be58e62d24181a9eb60244a7e4d878a3627d401) --- crates/victory-gpu/src/query.rs | 87 ++++++++++++ crates/victory-gpu/src/signature.rs | 202 ++++++++++++++++++++++++++++ 2 files changed, 289 insertions(+) diff --git a/crates/victory-gpu/src/query.rs b/crates/victory-gpu/src/query.rs index f3eb6b0..749859a 100644 --- a/crates/victory-gpu/src/query.rs +++ b/crates/victory-gpu/src/query.rs @@ -70,3 +70,90 @@ static FUNCTIONS: Table<24> = { f[7] = object::parent_device as *const (); // 0x38 Table(f) }; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{E_NOINTERFACE, E_POINTER, S_FALSE, S_OK, slot}; + + #[test] + fn null_descriptions_are_rejected() { + let mut heap = std::ptr::null(); + assert_eq!( + create(std::ptr::null(), std::ptr::null(), &HEAP_IIDS[0], &mut heap), + E_INVALIDARG + ); + assert!(heap.is_null()); + // The description is checked first: a probe with no room for the + // heap fails on it rather than answering S_FALSE. + assert_eq!( + create( + std::ptr::null(), + std::ptr::null(), + &HEAP_IIDS[0], + std::ptr::null_mut() + ), + E_INVALIDARG + ); + } + + #[test] + fn creation_without_an_out_pointer_only_probes() { + let desc = Desc { + kind: 1, // timestamps + count: 64, + nodes: 0, + }; + // A known interface with no out pointer asks whether creation would + // succeed; the heap is dropped instead of handed out. + assert_eq!( + create(std::ptr::null(), &desc, &HEAP_IIDS[0], std::ptr::null_mut()), + S_FALSE + ); + // A null interface id is tolerated: no interface, no heap. + let mut heap = std::ptr::null(); + assert_eq!( + create(std::ptr::null(), &desc, std::ptr::null(), &mut heap), + E_NOINTERFACE + ); + assert!(heap.is_null()); + } + + #[test] + fn heaps_answer_their_interfaces_and_count_references() { + let desc = Desc { + kind: 0, // occlusion + count: 8, + nodes: 0, + }; + let null = std::ptr::null(); + let mut heap = null; + assert_eq!(create(null, &desc, &HEAP_IIDS[0], &mut heap), S_OK); + assert!(!heap.is_null()); + let query = slot:: HRESULT>(heap, 0x0); + // Every interface the heap answers to hands out the same object. + for iid in &HEAP_IIDS { + let mut out = null; + assert_eq!(query(heap, iid, &mut out), S_OK); + assert_eq!(out as usize, heap as usize); + } + // An unknown interface writes null behind and reports it missing. + let unknown = [0u8; 16]; + let mut out = heap; + assert_eq!(query(heap, &unknown, &mut out), E_NOINTERFACE); + assert!(out.is_null()); + // A null interface id is tolerated rather than matched. + let mut out = heap; + assert_eq!(query(heap, std::ptr::null(), &mut out), E_NOINTERFACE); + assert!(out.is_null()); + // No room for the answer is a pointer error. + assert_eq!(query(heap, &unknown, std::ptr::null_mut()), E_POINTER); + // References: one from creation, four from the queries, one added; + // each release hands back what is left, the last frees the heap. + assert_eq!(slot:: u32>(heap, 0x8)(heap), 6); + let release = slot:: u32>(heap, 0x10); + for left in [5, 4, 3, 2, 1, 0] { + assert_eq!(release(heap), left); + } + } +} diff --git a/crates/victory-gpu/src/signature.rs b/crates/victory-gpu/src/signature.rs index 3c7b5d5..e8ba49b 100644 --- a/crates/victory-gpu/src/signature.rs +++ b/crates/victory-gpu/src/signature.rs @@ -92,3 +92,205 @@ static FUNCTIONS: Table<24> = { f[7] = object::parent_device as *const (); // 0x38 Table(f) }; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{E_NOINTERFACE, E_POINTER, S_FALSE, S_OK, slot}; + + #[test] + fn null_or_argument_free_descriptions_are_rejected() { + let null = std::ptr::null(); + let mut signature = null; + // No description at all. + assert_eq!( + create( + null, + std::ptr::null(), + null, + &SIGNATURE_IIDS[0], + &mut signature + ), + E_INVALIDARG + ); + assert!(signature.is_null()); + // A count of arguments with nothing behind the pointer. + let argumentless = Desc { + stride: 16, + count: 3, + arguments: std::ptr::null(), + nodes: 0, + }; + assert_eq!( + create( + null, + &argumentless, + null, + &SIGNATURE_IIDS[0], + &mut signature + ), + E_INVALIDARG + ); + assert!(signature.is_null()); + } + + #[test] + fn signatures_without_arguments_stay_empty() { + let null = std::ptr::null(); + // Zero arguments and no pointer is a valid, if useless, signature. + let empty = Desc { + stride: 16, + count: 0, + arguments: std::ptr::null(), + nodes: 0, + }; + let mut signature = null; + assert_eq!( + create(null, &empty, null, &SIGNATURE_IIDS[0], &mut signature), + S_OK + ); + let (stride, arguments) = layout(signature).expect("one of our signatures"); + assert_eq!(stride, 16); + assert!(arguments.is_empty()); + assert_eq!( + slot:: u32>(signature, 0x10)(signature), + 0 + ); + // The argument pointer is not read when the count is zero. + let none: [[u32; 4]; 0] = []; + let unread = Desc { + stride: 16, + count: 0, + arguments: none.as_ptr(), + nodes: 0, + }; + let mut signature = null; + assert_eq!( + create(null, &unread, null, &SIGNATURE_IIDS[1], &mut signature), + S_OK + ); + let (_, arguments) = layout(signature).expect("one of our signatures"); + assert!(arguments.is_empty()); + assert_eq!( + slot:: u32>(signature, 0x10)(signature), + 0 + ); + } + + #[test] + fn arguments_are_copied_out_of_title_memory() { + // A title reuses the memory its description lived in, while + // ExecuteIndirect reads the layout long after creation. + assert!( + layout(std::ptr::null()).is_none(), + "no signature, no layout" + ); + let draw = [0u32, 3, 1, 0]; // three vertices, one instance + let dispatch = [2u32, 4, 1, 1]; // dispatch 4x1x1 groups + let expected = [draw, dispatch]; + let mut title_memory = expected; + let desc = Desc { + stride: 20, + count: 2, + arguments: title_memory.as_ptr(), + nodes: 0, + }; + let null = std::ptr::null(); + let mut signature = null; + assert_eq!( + create(null, &desc, null, &SIGNATURE_IIDS[0], &mut signature), + S_OK + ); + title_memory.fill([9, 9, 9, 9]); + let (stride, arguments) = layout(signature).expect("one of our signatures"); + assert_eq!(stride, 20); + assert_eq!(arguments, &expected[..]); + assert_eq!( + slot:: u32>(signature, 0x10)(signature), + 0 + ); + } + + #[test] + fn signatures_answer_their_interfaces_and_count_references() { + let arguments = [[2u32, 4, 1, 1]]; // dispatch 4x1x1 groups + let desc = Desc { + stride: 12, + count: 1, + arguments: arguments.as_ptr(), + nodes: 0, + }; + let null = std::ptr::null(); + let mut signature = null; + assert_eq!( + create(null, &desc, null, &SIGNATURE_IIDS[0], &mut signature), + S_OK + ); + assert!(!signature.is_null()); + let query = + slot:: HRESULT>(signature, 0x0); + // Every interface the signature answers to hands out the same object. + for iid in &SIGNATURE_IIDS { + let mut out = null; + assert_eq!(query(signature, iid, &mut out), S_OK); + assert_eq!(out as usize, signature as usize); + } + // An unknown interface writes null behind and reports it missing. + let unknown = [0u8; 16]; + let mut out = signature; + assert_eq!(query(signature, &unknown, &mut out), E_NOINTERFACE); + assert!(out.is_null()); + // A null interface id is tolerated rather than matched. + let mut out = signature; + assert_eq!(query(signature, std::ptr::null(), &mut out), E_NOINTERFACE); + assert!(out.is_null()); + // No room for the answer is a pointer error. + assert_eq!(query(signature, &unknown, std::ptr::null_mut()), E_POINTER); + // References: one from creation, four from the queries, one added; + // each release hands back what is left, the last frees the signature. + assert_eq!( + slot:: u32>(signature, 0x8)(signature), + 6 + ); + let release = slot:: u32>(signature, 0x10); + for left in [5, 4, 3, 2, 1, 0] { + assert_eq!(release(signature), left); + } + } + + #[test] + fn creation_without_an_out_pointer_only_probes() { + let arguments = [[2u32, 4, 1, 1]]; // dispatch 4x1x1 groups + let desc = Desc { + stride: 12, + count: 1, + arguments: arguments.as_ptr(), + nodes: 0, + }; + // A known interface with no out pointer asks whether creation would + // succeed; the signature is dropped instead of handed out. + assert_eq!( + create( + std::ptr::null(), + &desc, + std::ptr::null(), + &SIGNATURE_IIDS[0], + std::ptr::null_mut() + ), + S_FALSE + ); + // A null interface id is tolerated: no interface, no signature. + let mut signature = std::ptr::null(); + assert_eq!( + create( + std::ptr::null(), + &desc, + std::ptr::null(), + std::ptr::null(), + &mut signature + ), + E_NOINTERFACE + ); + assert!(signature.is_null()); + } +} From 98b36e12a20cbd83dfb3976e6298a99856c042d2 Mon Sep 17 00:00:00 2001 From: quaternion Date: Mon, 23 Nov 2026 23:49:52 -0500 Subject: [PATCH 249/445] fix(pe): keep every name for a shared export ordinal The PE-specific export table stores one name per address-table slot, so when two names alias one ordinal the earlier name is silently dropped from ImageInfo and from victory inspect --exports. Use the generic Object::exports iterator instead, which yields every named export and then ordinal-only entries, and map its target and flags back to our representation. Add a synthetic PE regression with two names for one ordinal plus a separate export. (cherry picked from commit d0dd9fc5c01ce2e7e82047b4ab7e5b4821c82d7a) --- crates/victory-pe/src/image.rs | 107 +++++++++++++++++++++++++-------- 1 file changed, 81 insertions(+), 26 deletions(-) diff --git a/crates/victory-pe/src/image.rs b/crates/victory-pe/src/image.rs index aaf0009..b22808b 100644 --- a/crates/victory-pe/src/image.rs +++ b/crates/victory-pe/src/image.rs @@ -2,8 +2,7 @@ use object::LittleEndian as LE; use object::Object; use object::pe::{self, ImageNtHeaders64}; use object::read::pe::{ - ExportTarget, ImageNtHeaders, ImageOptionalHeader, Import, ImportTable, ImportThunkList, - PeFile64, + ImageNtHeaders, ImageOptionalHeader, Import, ImportTable, ImportThunkList, PeFile64, }; use crate::layout::{self, dir}; @@ -191,7 +190,7 @@ impl ImageInfo { None => Vec::new(), }; let delay_imports = parse_delay_imports(&file, opt.size_of_image())?; - let exports = parse_exports(&file)?; + let exports = parse_exports(&file, opt.image_base())?; let tls = parse_tls(&file, data, opt.image_base())?; let codeview = file.pdb_info()?.map(|cv| CodeViewInfo { pdb_path: String::from_utf8_lossy(cv.path()).into_owned(), @@ -350,34 +349,46 @@ fn entries<'data>( Ok(entries) } -fn parse_exports(file: &PeFile64<'_>) -> Result, PeError> { - let Some(table) = file.export_table()? else { - return Ok(Vec::new()); - }; - Ok(table - .exports()? - .into_iter() - // An address of 0 marks an unused slot in the address table (a gap - // in the ordinals), not an export at the image base. - .filter(|e| !matches!(e.target, ExportTarget::Address(0))) +fn parse_exports(file: &PeFile64<'_>, image_base: u64) -> Result, PeError> { + use object::read::{ExportFlags, ExportTarget as ReadTarget, NameOrOrdinal}; + + // The PE-specific table keeps one name per address-table slot, so two + // names sharing an ordinal lose all but the last one. The generic + // iterator yields every name, then the ordinal-only entries. + file.exports() + .map_err(|e| PeError::Malformed(format!("export table: {e}")))? .map(|e| { - let (rva, forward) = match e.target { - ExportTarget::Address(rva) => (Some(rva), None), - ExportTarget::ForwardByName(d, n) => { - (None, Some(format!("{}.{}", utf8(d), utf8(n)))) - } - ExportTarget::ForwardByOrdinal(d, o) => { - (None, Some(format!("{}.#{}", utf8(d), o.0))) - } + let e = e.map_err(|e| PeError::Malformed(format!("export: {e}")))?; + let ordinal = match e.flags() { + ExportFlags::Pe { ordinal } => ordinal.0, + _ => 0, }; - ExportInfo { - name: e.name.map(utf8), - ordinal: e.ordinal.0, + let name = match e.name() { + NameOrOrdinal::Name(name) => Some(utf8(name)), + NameOrOrdinal::Ordinal(_) => None, + }; + let (rva, forward) = match e.target() { + // The generic iterator adds the image base to an address. + ReadTarget::Address { address } => { + (Some(address.wrapping_sub(image_base) as u32), None) + } + ReadTarget::Reexport { library, name } => { + let symbol = match name { + NameOrOrdinal::Name(name) => utf8(name), + NameOrOrdinal::Ordinal(ordinal) => format!("#{ordinal}"), + }; + (None, Some(format!("{}.{}", utf8(library), symbol))) + } + _ => (None, None), + }; + Ok(ExportInfo { + name, + ordinal, rva, forward, - } + }) }) - .collect()) + .collect() } fn parse_tls( @@ -637,4 +648,48 @@ mod tests { ] ); } + + #[test] + fn every_name_of_a_shared_ordinal_survives() { + // Two names for address slot 0, one for slot 1. The PE-specific + // export table keeps only one name per slot, so "alpha" would be + // lost; the generic iterator keeps both. + let mut body = vec![0u8; 0x100]; + let put32 = + |b: &mut Vec, at: usize, v: u32| b[at..at + 4].copy_from_slice(&v.to_le_bytes()); + put32(&mut body, 12, 0x1040); // name of the DLL + put32(&mut body, 16, 1); // ordinal base + put32(&mut body, 20, 2); // number of functions + put32(&mut body, 24, 3); // number of names + put32(&mut body, 28, 0x1028); // address table + put32(&mut body, 32, 0x1034); // name pointer table + put32(&mut body, 36, 0x1044); // name ordinal table + put32(&mut body, 0x28, 0x1200); + put32(&mut body, 0x2C, 0x1204); + put32(&mut body, 0x34, 0x1050); + put32(&mut body, 0x38, 0x1056); + put32(&mut body, 0x3C, 0x105C); + body[0x40..0x46].copy_from_slice(b"t.dll\0"); + body[0x44..0x46].copy_from_slice(&0u16.to_le_bytes()); + body[0x46..0x48].copy_from_slice(&0u16.to_le_bytes()); + body[0x48..0x4A].copy_from_slice(&1u16.to_le_bytes()); + body[0x50..0x56].copy_from_slice(b"alpha\0"); + body[0x56..0x5B].copy_from_slice(b"beta\0"); + body[0x5C..0x62].copy_from_slice(b"gamma\0"); + + let info = ImageInfo::parse(&synthetic_image(&body)).unwrap(); + let exports: Vec<_> = info + .exports + .iter() + .map(|e| (e.name.as_deref(), e.ordinal, e.rva)) + .collect(); + assert_eq!( + exports, + [ + (Some("alpha"), 1, Some(0x1200)), + (Some("beta"), 1, Some(0x1200)), + (Some("gamma"), 2, Some(0x1204)), + ] + ); + } } From 7a4f0018b5bfd1180dbd66b1c0af759c3f398367 Mon Sep 17 00:00:00 2001 From: quaternion Date: Mon, 23 Nov 2026 23:55:49 -0500 Subject: [PATCH 250/445] fix(loader): stage prepared images in per-writer files write_if_changed used a shared .tmp file, so two concurrent cold launches of the same image could truncate each other's staging bytes or fail the rename after the other had published. Move publication into a portable module that stages under a unique pid/sequence name and removes it on failure. Two hermetic tests cover concurrent publishers and a failed rename. (cherry picked from commit 1aac20aa8fd97237053c985b942225d54c0194a7) --- crates/victory-loader/src/lib.rs | 1 + crates/victory-loader/src/publish.rs | 76 ++++++++++++++++++++++++++++ crates/victory-loader/src/windows.rs | 9 +--- 3 files changed, 79 insertions(+), 7 deletions(-) create mode 100644 crates/victory-loader/src/publish.rs diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 28cabd6..5a65fa6 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -25,6 +25,7 @@ mod console_insn; mod crash; pub mod prepare; +pub(crate) mod publish; pub mod resolve; #[cfg(all(windows, feature = "diagnostics"))] mod stacks; diff --git a/crates/victory-loader/src/publish.rs b/crates/victory-loader/src/publish.rs new file mode 100644 index 0000000..b1f7896 --- /dev/null +++ b/crates/victory-loader/src/publish.rs @@ -0,0 +1,76 @@ +//! Portable publication of derived files into a shared cache directory. +//! +//! Several copies of the runner can prepare the same title at once. Each +//! writer stages into its own file, so two of them cannot truncate each +//! other's bytes or rename a file the other already published. The final +//! rename is atomic within the directory, and the staging file is removed +//! if publication fails. + +use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; + +static NEXT_STAGING: AtomicU64 = AtomicU64::new(0); + +/// Writes `bytes` to `path` unless it is already there, using a staging file +/// unique to this process and call. +pub fn write_if_changed(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + if std::fs::read(path).is_ok_and(|existing| existing == bytes) { + return Ok(()); + } + let name = path + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("image"); + let sequence = NEXT_STAGING.fetch_add(1, Ordering::Relaxed); + let staging = path.with_file_name(format!( + ".{name}.{}.{sequence}.tmp", + std::process::id() + )); + std::fs::write(&staging, bytes)?; + if let Err(error) = std::fs::rename(&staging, path) { + let _ = std::fs::remove_file(&staging); + return Err(error); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Two publishers staging the same destination at once both succeed, + /// and neither leaves a staging file behind. + #[test] + fn concurrent_publishers_do_not_share_a_staging_file() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("image.bin"); + let bytes = b"a prepared image".to_vec(); + let (first, second) = (path.clone(), path.clone()); + let (first_bytes, second_bytes) = (bytes.clone(), bytes.clone()); + let (one, two) = ( + std::thread::spawn(move || write_if_changed(&first, &first_bytes)), + std::thread::spawn(move || write_if_changed(&second, &second_bytes)), + ); + one.join().unwrap().unwrap(); + two.join().unwrap().unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), bytes); + let leftovers: Vec<_> = std::fs::read_dir(dir.path()) + .unwrap() + .filter_map(|entry| entry.ok()) + .filter(|entry| entry.path() != path) + .collect(); + assert!(leftovers.is_empty(), "staging files were removed: {leftovers:?}"); + } + + #[test] + fn a_failed_publication_removes_its_staging_file() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("missing-parent").join("image.bin"); + assert!(write_if_changed(&path, b"bytes").is_err()); + let leftovers: Vec<_> = std::fs::read_dir(dir.path()) + .unwrap() + .filter_map(|entry| entry.ok()) + .collect(); + assert!(leftovers.is_empty(), "no staging file survives an error"); + } +} diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs index e709d11..a0375ef 100644 --- a/crates/victory-loader/src/windows.rs +++ b/crates/victory-loader/src/windows.rs @@ -183,13 +183,8 @@ impl ImportResolver for WithTitleDlls<'_> { } fn write_if_changed(path: &Path, bytes: &[u8]) -> Result<()> { - if std::fs::read(path).is_ok_and(|existing| existing == bytes) { - return Ok(()); - } - let tmp = path.with_extension("tmp"); - std::fs::write(&tmp, bytes).with_context(|| format!("writing {}", tmp.display()))?; - std::fs::rename(&tmp, path).with_context(|| format!("renaming to {}", path.display()))?; - Ok(()) + crate::publish::write_if_changed(path, bytes) + .with_context(|| format!("publishing {}", path.display())) } impl LoadedImage { From d23f0b83e195cc47b05b7aa92ed6601ecfcbdbc3 Mon Sep 17 00:00:00 2001 From: quaternion Date: Mon, 23 Nov 2026 22:57:38 -0500 Subject: [PATCH 251/445] fix(hle): read manifest fields past inline XML comments elements() took field text up to the next '<', so a generator comment before the value made TitleId, StoreId or SizeMB empty. Skip comments while gathering the text. Add a regression with comments inside all three fields. (cherry picked from commit ca362a42473bb0f8f9a83377091287a621e94527) --- crates/victory-hle/src/runtime.rs | 43 +++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index e90aa58..f26b96f 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -125,6 +125,32 @@ impl Title { } } +/// The trimmed text of one element: comments inside it are skipped, not +/// treated as the end of its value. A manifest generator can write +/// `639AA8DD`, which must still give +/// the title's id rather than an empty field. +fn field_text(rest: &str) -> String { + let mut out = String::new(); + let mut rest = rest; + loop { + let Some(open) = rest.find('<') else { + out.push_str(rest); + break; + }; + out.push_str(&rest[..open]); + if rest[open..].starts_with("") else { + break; + }; + rest = &rest[open + end + 3..]; + } else { + // A child element, a closing tag or anything else ends the text. + break; + } + } + out.trim().to_owned() +} + /// Each element of an XML text as its path from the root (`Game/TitleId`) /// and its trimmed text up to the first child, the predefined entities /// decoded; comments, CDATA sections, declarations and attributes are @@ -161,10 +187,10 @@ fn elements(text: &str) -> Vec<(String, String)> { .next() .unwrap_or(""); path.push(name); - let body = rest[..rest.find('<').unwrap_or(rest.len())].trim(); + let body = field_text(rest); let body = [("<", "<"), (">", ">"), (""", "\""), ("'", "'"), ("&", "&")] .iter() - .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)); + .fold(body, |b, (entity, c)| b.replace(entity, c)); out.push((path.join("/"), body)); if closed { path.pop(); @@ -260,4 +286,17 @@ mod tests { assert_eq!(t.store_id, "9&C"); assert_eq!(Title::from_manifest("").storage_bytes, 0); } + + #[test] + fn inline_comments_do_not_truncate_a_field() { + let text = "\ + 639AA8DD\ + 9&C\ + 1024\ + "; + let t = Title::from_manifest(text); + assert_eq!(t.id, 0x639A_A8DD); + assert_eq!(t.store_id, "9&C"); + assert_eq!(t.storage_bytes, 1024 << 20); + } } From 6ee01b61bdd633b610fee074cb60c9e053f5dc42 Mon Sep 17 00:00:00 2001 From: quaternion Date: Mon, 23 Nov 2026 22:36:59 -0500 Subject: [PATCH 252/445] fix(hle): honor the requested executable on relaunch runtime stores an absolute image path while relaunch_args searched raw CLI arguments for exact text, so a relative launch argument made XLaunchNewGame silently rerun the old title. Normalize the argument the same way runtime does before replacing it. Also split the title's quoted config args into proper arguments instead of split_whitespace. Add a regression covering a relative startup path, a different target and quoted/empty args. (cherry picked from commit 71e88665c44f6f82370e2fb84e6d2358c1e7b180) --- crates/victory-hle/src/modules/xgame.rs | 90 ++++++++++++++++++++++--- 1 file changed, 82 insertions(+), 8 deletions(-) diff --git a/crates/victory-hle/src/modules/xgame.rs b/crates/victory-hle/src/modules/xgame.rs index edcf2ea..abb1fc4 100644 --- a/crates/victory-hle/src/modules/xgame.rs +++ b/crates/victory-hle/src/modules/xgame.rs @@ -81,13 +81,18 @@ extern "system" fn launch_new_game( .unwrap_or_default(); let ours: Vec<_> = std::env::args_os().skip(1).collect(); let command = relaunch_args(ours, current.as_os_str(), &exe, &args); - super::lifecycle::end_title( - "XLaunchNewGame", - Box::new(move || super::lifecycle::relaunch(command)), - ); - loop { - std::thread::park(); + #[cfg(windows)] + { + super::lifecycle::end_title( + "XLaunchNewGame", + Box::new(move || super::lifecycle::relaunch(command)), + ); + loop { + std::thread::park(); + } } + #[cfg(not(windows))] + let _ = command; } /// Our own arguments for the relaunch: the title's executable replaced by @@ -99,14 +104,53 @@ fn relaunch_args( args: &str, ) -> Vec { let mut out: Vec<_> = ours.into_iter().take_while(|a| a != "--").collect(); + // `runtime` makes the image path absolute when it maps the title, so a + // relative launch argument is not textually equal to it. Normalise the + // same way before matching, or a relaunch would run the old executable. if !exe.is_empty() - && let Some(slot) = out.iter_mut().find(|a| a.as_os_str() == current) + && let Some(slot) = out.iter_mut().find(|a| { + a.as_os_str() == current + || std::path::absolute(a).is_ok_and(|p| p.as_os_str() == current) + }) { *slot = exe.into(); } if !args.trim().is_empty() { out.push("--".into()); - out.extend(args.split_whitespace().map(Into::into)); + out.extend(split_args(args).into_iter().map(Into::into)); + } + out +} + +/// Splits the title's command-line tail into arguments, keeping quoted +/// strings together (including empty ones). `split_whitespace` would hand +/// the child a quoted path as several broken arguments. +fn split_args(args: &str) -> Vec { + let mut out = Vec::new(); + let mut current = String::new(); + let mut quote = None; + let mut started = false; + for c in args.chars() { + match c { + '"' | '\'' if quote == Some(c) => quote = None, + '"' | '\'' if quote.is_none() => { + quote = Some(c); + started = true; + } + c if quote.is_none() && c.is_whitespace() => { + if started { + out.push(std::mem::take(&mut current)); + started = false; + } + } + c => { + current.push(c); + started = true; + } + } + } + if started { + out.push(current); } out } @@ -209,6 +253,36 @@ mod tests { assert_eq!(other[1], "G:/other.exe"); } + #[test] + fn a_relaunch_replaces_a_relative_startup_executable() { + // `runtime::set_image_path` makes this absolute before the launch. + let current = std::path::absolute("game.exe").unwrap(); + let ours: Vec = + ["run", "game.exe", "--execute", "--console", "series-s", "--", "-old"] + .map(Into::into) + .into(); + let again = relaunch_args( + ours, + current.as_os_str(), + "other.exe", + r#"--config="C:\Program Files\game" "" -y"#, + ); + let expected: Vec = [ + "run", + "other.exe", + "--execute", + "--console", + "series-s", + "--", + r"--config=C:\Program Files\game", + "", + "-y", + ] + .map(Into::into) + .into(); + assert_eq!(again, expected, "the requested exe and quoted args survive"); + } + #[test] fn served_areas_are_available_others_not() { type Check = extern "system" fn(This, u32) -> bool; From bb0a2428fcca043f37111a3e18393ffdab1c42d6 Mon Sep 17 00:00:00 2001 From: nino-exe <173394600+nino-exe@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:20:37 +0200 Subject: [PATCH 253/445] policy: resolve a `..` in the not-yet-existing part of a path `resolve` canonicalizes the longest existing prefix and re-appends the rest, but it walks up with `Path::file_name()`, which is None for a trailing `..`. A path such as `/a/../b` (nothing exists yet) hit the `_` arm and returned PolicyError::Io, so a cache_dir or data_dir with a `..` in a directory that does not exist yet was rejected, and `normalize`'s `..` handling for the missing tail was never reached. A trailing `..` is now kept in `rest` so `normalize` resolves it lexically. Test: resolves_dot_dot_in_a_path_that_does_not_exist_yet (fails before, passes after). cargo test -p victory-core, cargo fmt --check and cargo clippy --tests are clean. (cherry picked from commit 52f0a099ede8aa4d5bde61a0c46963a77a4378ba) --- crates/victory-core/src/policy.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/victory-core/src/policy.rs b/crates/victory-core/src/policy.rs index b10e1c6..d49acc4 100644 --- a/crates/victory-core/src/policy.rs +++ b/crates/victory-core/src/policy.rs @@ -92,6 +92,11 @@ fn resolve(path: &Path) -> Result { rest.push(name.to_os_string()); existing = parent; } + // `file_name()` is None for a trailing `..`; keep it so `normalize` resolves it. + (Some(parent), None) if existing.ends_with("..") => { + rest.push("..".into()); + existing = parent; + } _ => { return Err(PolicyError::Io { path: path.to_path_buf(), @@ -156,4 +161,12 @@ mod tests { let tmp = tempfile::tempdir().unwrap(); ensure_outside_repo(&tmp.path().join("does").join("not").join("exist")).unwrap(); } + + #[test] + fn resolves_dot_dot_in_a_path_that_does_not_exist_yet() { + let base = std::env::temp_dir().join("victory-policy-no-such"); + let path = base.join("a").join("..").join("b"); + let resolved = resolve(&path).expect("a `..` in the missing tail must resolve lexically"); + assert_eq!(resolved, resolve(&base.join("b")).unwrap()); + } } From 41dc5da4c9b0b407a304406e355a4e58043d47ec Mon Sep 17 00:00:00 2001 From: Enzo Souza Duarte Date: Mon, 23 Nov 2026 23:36:36 -0300 Subject: [PATCH 254/445] Config: ignore an empty VICTORY_CONFIG (cherry picked from commit fd44561ea1180aff5380285527fb8cac8195f4e8) --- crates/victory-core/src/config.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/victory-core/src/config.rs b/crates/victory-core/src/config.rs index b65014e..eb2d85e 100644 --- a/crates/victory-core/src/config.rs +++ b/crates/victory-core/src/config.rs @@ -46,7 +46,7 @@ struct FilePaths { impl Config { /// Loads configuration from the environment and the config file. pub fn load() -> Result { - let explicit = std::env::var_os("VICTORY_CONFIG").map(PathBuf::from); + let explicit = explicit_config_path(|k| std::env::var_os(k)); let path = explicit .clone() .unwrap_or_else(|| PathBuf::from("victory.toml")); @@ -119,6 +119,14 @@ impl Config { } } +/// The config file explicitly named by the environment, if any. An empty +/// `VICTORY_CONFIG` means unset, like the other path variables. +fn explicit_config_path(env: impl Fn(&str) -> Option) -> Option { + env("VICTORY_CONFIG") + .filter(|v| !v.is_empty()) + .map(PathBuf::from) +} + fn subdir(root: &Path, sub: &str) -> Result { let dir = root.join(sub); ensure_outside_repo(&dir)?; @@ -188,6 +196,17 @@ mod tests { ); } + #[test] + fn empty_config_env_is_ignored() { + let empty = |k: &str| (k == "VICTORY_CONFIG").then(OsString::new); + assert_eq!(explicit_config_path(empty), None); + let set = |k: &str| (k == "VICTORY_CONFIG").then(|| OsString::from("custom.toml")); + assert_eq!( + explicit_config_path(set), + Some(PathBuf::from("custom.toml")) + ); + } + #[test] fn example_config_parses() { let text = include_str!("../../../victory.example.toml"); From ea78bb9483740b8273900278667ab11ba9d10056 Mon Sep 17 00:00:00 2001 From: BastienRdz <58186763+BastienRodz@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:20:53 +0000 Subject: [PATCH 255/445] Loader: a clwb in the last bytes of a page is emulated instead of faulting emulate_amd_only copies only the bytes left in the faulting page and gated clwb_len on n >= 15 because clwb_len took a fixed [u8; 15]. A 4- to 10-byte clwb starting in the last 14 bytes of a page (or falling back from a clwb_loop that straddles the page end) was therefore skipped, leaving pre-Ice Lake Intel CPUs with an unhandled STATUS_ILLEGAL_INSTRUCTION. Change clwb_len to take &[u8], bounds-checking each byte read and returning Some(len) only when len <= code.len(), and drop the n >= 15 guard in emulate_amd_only. Fixes #924. Co-Authored-By: Gemini 4 Neon Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 60d2cf9cbcf5a2abc773d5de10c3c892e77d3340) --- crates/victory-loader/src/crash.rs | 96 +++++++++++++++++++++--------- 1 file changed, 68 insertions(+), 28 deletions(-) diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index 7062bbd..84684b2 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -185,9 +185,7 @@ unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { context.Rip += pass.len as u64; return true; } - if n >= 15 - && let Some(len) = clwb_len(bytes[..15].try_into().unwrap_or([0; 15])) - { + if let Some(len) = clwb_len(&bytes[..n]) { // A write-back hint: the PC's memory is coherent, so it has nothing to do. context.Rip += len as u64; return true; @@ -206,12 +204,12 @@ unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { /// `clwb m8` (`66 [rex] 0f ae /6`, a memory operand), which Intel CPUs before /// Ice Lake lack: its length, or `None` for any other instruction. -fn clwb_len(code: [u8; 15]) -> Option { - let at = if code[1] & 0xf0 == 0x40 { 2 } else { 1 }; - if code[0] != 0x66 || code[at] != 0x0f || code[at + 1] != 0xae { +fn clwb_len(code: &[u8]) -> Option { + let at = if *code.get(1)? & 0xf0 == 0x40 { 2 } else { 1 }; + if *code.first()? != 0x66 || code.get(at..at + 2)? != [0x0f, 0xae] { return None; } - let modrm = code[at + 2]; + let modrm = *code.get(at + 2)?; let (mode, rm) = (modrm >> 6, modrm & 7); if mode == 3 || (modrm >> 3) & 7 != 6 { return None; @@ -219,7 +217,7 @@ fn clwb_len(code: [u8; 15]) -> Option { let mut len = at + 3; let mut base = rm; if rm == 4 { - base = code[len] & 7; + base = *code.get(len)? & 7; len += 1; } len += match mode { @@ -228,7 +226,7 @@ fn clwb_len(code: [u8; 15]) -> Option { 2 => 4, _ => 0, }; - Some(len) + (len <= code.len()).then_some(len) } /// A `clwb` write-back loop as the title's compilers build it, one cache line a @@ -950,26 +948,68 @@ mod tests { #[test] fn clwb_lengths() { - let pad = |b: &[u8]| { - let mut c = [0u8; 15]; - c[..b.len()].copy_from_slice(b); - c + assert_eq!(clwb_len(&[0x66, 0x41, 0x0f, 0xae, 0x31]), Some(5)); // clwb [r9] + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x30]), Some(4)); // clwb [rax] + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x70, 0x40]), Some(5)); // clwb [rax+0x40] + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0xb0, 0, 1, 0, 0]), Some(8)); // [rax+disp32] + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x34, 0x24]), Some(5)); // clwb [rsp] + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x35, 0, 0, 0, 0]), Some(8)); // [rip+disp32] + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x38]), None); // clflushopt, /7 + assert_eq!(clwb_len(&[0x0f, 0xae, 0x30]), None); // xsaveopt, no 66 + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0xf0]), None); // register form + } + + #[test] + fn a_clwb_at_the_end_of_a_page_is_decoded() { + // Exact-length slices, as at the end of a page. + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x30]), Some(4)); + assert_eq!(clwb_len(&[0x66, 0x41, 0x0f, 0xae, 0x31]), Some(5)); + // Cut short by the slice: returns None without panicking. + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0xb0, 0, 1]), None); // disp32, 6 of 8 bytes + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x70]), None); // disp8, 4 of 5 bytes + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x34]), None); // SIB missing + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x34, 0x25, 0, 0]), None); // SIB disp32 cut short + assert_eq!(clwb_len(&[0x66, 0x0f, 0xae]), None); // ModRM missing + assert_eq!(clwb_len(&[0x66]), None); + assert_eq!(clwb_len(&[]), None); + + // Emulation at the last 4 and 5 bytes of a page with an unreadable page after it. + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, + VirtualFree, VirtualProtect, }; - assert_eq!(clwb_len(pad(&[0x66, 0x41, 0x0f, 0xae, 0x31])), Some(5)); // clwb [r9] - assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x30])), Some(4)); // clwb [rax] - assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x70, 0x40])), Some(5)); // clwb [rax+0x40] - assert_eq!( - clwb_len(pad(&[0x66, 0x0f, 0xae, 0xb0, 0, 1, 0, 0])), - Some(8) - ); // [rax+disp32] - assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x34, 0x24])), Some(5)); // clwb [rsp] - assert_eq!( - clwb_len(pad(&[0x66, 0x0f, 0xae, 0x35, 0, 0, 0, 0])), - Some(8) - ); // [rip+disp32] - assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x38])), None); // clflushopt, /7 - assert_eq!(clwb_len(pad(&[0x0f, 0xae, 0x30])), None); // xsaveopt, no 66 - assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0xf0])), None); // register form + // SAFETY: two pages of ours, the second unreadable so reading past the first faults. + unsafe { + let page = VirtualAlloc( + std::ptr::null(), + 0x2000, + MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE, + ) + .cast::(); + assert!(!page.is_null()); + let mut old = 0; + let guard = page.add(0x1000).cast(); + assert_ne!(VirtualProtect(guard, 0x1000, PAGE_NOACCESS, &mut old), 0); + for insn in [ + &[0x66, 0x0f, 0xae, 0x30][..], + &[0x66, 0x41, 0x0f, 0xae, 0x31][..], + ] { + let end = page.add(0x1000 - insn.len()); + end.copy_from_nonoverlapping(insn.as_ptr(), insn.len()); + let mut record: EXCEPTION_RECORD = std::mem::zeroed(); + record.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION; + let mut context: CONTEXT = std::mem::zeroed(); + context.Rip = end as u64; + let mut pointers = EXCEPTION_POINTERS { + ExceptionRecord: &mut record, + ContextRecord: &mut context, + }; + assert!(emulate_amd_only(&mut pointers)); + assert_eq!(context.Rip, end as u64 + insn.len() as u64); + } + VirtualFree(page.cast(), 0, MEM_RELEASE); + } } #[test] From b2e23f834cec1afc35e9543bf0a1457b75dca97a Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Tue, 24 Nov 2026 11:27:21 -0300 Subject: [PATCH 256/445] HLE: test that XGSuggestSwizzleMode picks linear for a 1D texture (cherry picked from commit 246ecea9631acfe1b694421c6c600e3981a1f752) --- crates/victory-hle/src/modules/xg.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/victory-hle/src/modules/xg.rs b/crates/victory-hle/src/modules/xg.rs index 56011ec..eb78ec5 100644 --- a/crates/victory-hle/src/modules/xg.rs +++ b/crates/victory-hle/src/modules/xg.rs @@ -665,6 +665,10 @@ mod tests { d.flags = ALLOW_DEPTH_STENCIL; XGSuggestSwizzleMode(&d, 0, &mut out); assert_eq!(out, 0x118); + // A 1D texture has no tiled layout, whatever its use. + d.dimension = TEXTURE_1D; + XGSuggestSwizzleMode(&d, 0, &mut out); + assert_eq!(out, 0x100); } /// The title's calls: layout, then a copy in and out of each mip. From 467bb36711856485bfd77fbb73dd616f7bfd07d2 Mon Sep 17 00:00:00 2001 From: David Palacios <97840947+dpalacios69@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:37:25 +0100 Subject: [PATCH 257/445] CLI: add AVX2 pre-flight CPU check before executing titles (cherry picked from commit 534e1dd74c57448bef4c525e204acc123387d6f2) --- apps/victory/src/run.rs | 73 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index dc5bf71..822a92b 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -4,6 +4,37 @@ use anyhow::{Context, Result}; use crate::{Console, Unimplemented}; +#[cfg(any(windows, test))] +const SKIP_CPU_CHECK_ENV: &str = "VICTORY_SKIP_CPU_CHECK"; + +#[cfg(any(windows, test))] +fn skip_cpu_check(value: Option<&str>) -> bool { + value == Some("1") +} + +#[cfg(any(windows, test))] +fn check_cpu_features_with(has_avx2: bool, skip_env: Option<&str>) -> Result<()> { + if has_avx2 || skip_cpu_check(skip_env) { + return Ok(()); + } + anyhow::bail!( + "this CPU does not support AVX2, which Xbox Series titles require; \ + set {SKIP_CPU_CHECK_ENV}=1 to bypass this check (for example under CPU emulation such as Intel SDE)" + ); +} + +/// Pre-flight check before executing title code: Xbox Series binaries are +/// compiled for Zen 2 and require AVX2. +#[cfg(windows)] +fn check_cpu_features() -> Result<()> { + #[cfg(target_arch = "x86_64")] + let has_avx2 = std::arch::is_x86_feature_detected!("avx2"); + #[cfg(not(target_arch = "x86_64"))] + let has_avx2 = true; + let skip = std::env::var(SKIP_CPU_CHECK_ENV).ok(); + check_cpu_features_with(has_avx2, skip.as_deref()) +} + #[cfg(windows)] pub fn run( exe: &Path, @@ -16,6 +47,9 @@ pub fn run( use victory_hle::{HleResolver, HostPolicy}; use victory_loader::{BindReport, UnimplementedPolicy, WithTitleDlls}; + if execute { + check_cpu_features()?; + } // A title that relaunched itself: the old process must be gone first. victory_hle::modules::lifecycle::wait_for_previous(); let cfg = victory_core::Config::load()?; @@ -336,6 +370,45 @@ mod tests { other.join().unwrap(); assert_eq!(*order.lock().unwrap(), [1, 2]); } + + #[test] + fn cpu_feature_check_matches_host() { + let skip = std::env::var(super::SKIP_CPU_CHECK_ENV).ok(); + #[cfg(target_arch = "x86_64")] + let expected_ok = + std::arch::is_x86_feature_detected!("avx2") || skip.as_deref() == Some("1"); + #[cfg(not(target_arch = "x86_64"))] + let expected_ok = true; + assert_eq!(super::check_cpu_features().is_ok(), expected_ok); + } +} + +#[cfg(test)] +mod cpu_check_tests { + use super::{SKIP_CPU_CHECK_ENV, check_cpu_features_with}; + + #[test] + fn avx2_present_passes() { + assert!(check_cpu_features_with(true, None).is_ok()); + assert!(check_cpu_features_with(true, Some("0")).is_ok()); + assert!(check_cpu_features_with(true, Some("1")).is_ok()); + } + + #[test] + fn avx2_missing_fails_with_clear_error() { + for skip in [None, Some(""), Some("0"), Some("true")] { + let err = check_cpu_features_with(false, skip).unwrap_err(); + let msg = err.to_string(); + assert!(msg.contains("AVX2"), "unexpected error: {msg}"); + assert!(msg.contains("Xbox Series"), "unexpected error: {msg}"); + assert!(msg.contains(SKIP_CPU_CHECK_ENV), "unexpected error: {msg}"); + } + } + + #[test] + fn skip_env_var_bypasses_missing_avx2() { + assert!(check_cpu_features_with(false, Some("1")).is_ok()); + } } #[cfg(not(windows))] From ae0952d7f9a2d67c5d56ca546d4f87be8ed2cf11 Mon Sep 17 00:00:00 2001 From: heromike405-arch Date: Tue, 24 Nov 2026 22:59:35 +0800 Subject: [PATCH 258/445] XMA: gather frame payloads one byte at a time Read complete payload bytes directly inside an XMA2 packet. Keep the bit reader for packet headers, interleaved stream skips and the final partial byte. Add coverage for all eight alignments at packet boundaries and EOF. On Windows x86-64, 36,720 synthetic reads matched the previous implementation, including returned bytes and the next frame position. A release microbenchmark of read_frame measured 1009 to 168 ns for 128-byte frames and 7977 to 1062 ns for 1 KiB frames (median of nine runs). (cherry picked from commit 03a6f22906b4372ec08d003e9103997659647b0f) --- crates/victory-formats/src/xma.rs | 48 +++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 3 deletions(-) diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs index f5a5528..02c01bd 100644 --- a/crates/victory-formats/src/xma.rs +++ b/crates/victory-formats/src/xma.rs @@ -102,6 +102,25 @@ impl Cursor<'_> { fn bits(&mut self, n: u32) -> Option { (0..n).try_fold(0, |v, _| Some(v << 1 | self.bit()?)) } + + /// A payload byte, MSB first. At a packet edge the individual bits + /// may be separated by a header and other streams' packets. + fn byte(&mut self) -> Option { + let in_packet = self.pos % PACKET_BITS; + if in_packet == 0 || in_packet > PACKET_BITS - 8 { + return self.bits(8).map(|v| v as u8); + } + let at = self.pos / 8; + let shift = self.pos % 8; + let first = *self.data.get(at)?; + let byte = if shift == 0 { + first + } else { + (first << shift) | (self.data.get(at + 1)? >> (8 - shift)) + }; + self.pos += 8; + Some(byte) + } } /// Reads the frame starting at bit `start` (a frame start inside a packet's @@ -112,10 +131,14 @@ pub fn read_frame(data: &[u8], start: usize) -> Option { if bits <= LENGTH_BITS as usize || bits == 0x7fff { return None; } - let mut out = vec![0u8; bits.div_ceil(8)]; + let mut out = Vec::with_capacity(bits.div_ceil(8)); let mut cursor = Cursor { data, pos: start }; - for i in 0..bits { - out[i / 8] |= (cursor.bit()? as u8) << (7 - i % 8); + for _ in 0..bits / 8 { + out.push(cursor.byte()?); + } + let tail = (bits % 8) as u32; + if tail != 0 { + out.push((cursor.bits(tail)? << (8 - tail)) as u8); } let end = cursor.pos; let next = next_frame(data, start, end); @@ -1423,6 +1446,24 @@ mod tests { assert!(packet(&[0; 3], 0).is_none()); } + #[test] + fn payload_bytes_match_bit_reads_at_packet_edges() { + let mut data: Vec = (0..3 * PACKET_BYTES).map(|i| (i * 37 + 11) as u8).collect(); + data[..4].copy_from_slice(&1u32.to_be_bytes()); // packet 1 belongs to another stream + data[PACKET_BYTES..2 * PACKET_BYTES].fill(0xee); + for edge in [HEADER_BITS + 8, PACKET_BITS, 3 * PACKET_BITS] { + for pos in edge - 8..=edge { + let mut bytes = Cursor { data: &data, pos }; + let mut bits = Cursor { data: &data, pos }; + let expected = bits.bits(8).map(|v| v as u8); + assert_eq!(bytes.byte(), expected, "bit {pos}"); + if expected.is_some() { + assert_eq!(bytes.pos, bits.pos); + } + } + } + } + #[test] fn packet_headers_and_frame_walk() { // Two packets: frame A (100 bits) and B (16300 bits, crossing into @@ -1451,6 +1492,7 @@ mod tests { assert_eq!((b.bits, b.next), (16300, Some(c_start))); // Its last bits come from after packet 1's header. assert_eq!(b.data.len(), 16300usize.div_ceil(8)); + assert_eq!(b.data.last(), Some(&0xf0)); // unused bits stay zero let c = read_frame(&data, c_start).unwrap(); assert_eq!(c.bits, 60); // C was packet 1's only frame: the next would be in packet 2. From d8b7d66993ee124c7aae3b177551772cdfb8589a Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Tue, 24 Nov 2026 12:17:22 -0300 Subject: [PATCH 259/445] Shaders: hardware test for the integer v_min3/v_max3/v_med3 (cherry picked from commit 8610ffb85baedbc7b8c4c9de1222b0911e00e589) --- crates/victory-shader/src/emit/valu_tests.rs | 45 ++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 65c0c9d..8dd2f36 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -665,6 +665,51 @@ fn v_min3_max3_med3_integer_forms_match_rdna2() { } } +#[test] +fn v_min3_max3_med3_integer_forms_match_rdna2() { + // v_{min3,max3,med3}_{i32,u32} v0, v1, v2, v3 (VOP3 0x152..0x159). + let ops: [(&str, u16, fn([u32; 3]) -> u32); 6] = [ + ("v_min3_i32", 0x152, |t| { + t.into_iter().min_by_key(|&x| x as i32).unwrap() + }), + ("v_min3_u32", 0x153, |t| t.into_iter().min().unwrap()), + ("v_max3_i32", 0x155, |t| { + t.into_iter().max_by_key(|&x| x as i32).unwrap() + }), + ("v_max3_u32", 0x156, |t| t.into_iter().max().unwrap()), + ("v_med3_i32", 0x158, |mut t| { + t.sort_by_key(|&x| x as i32); + t[1] + }), + ("v_med3_u32", 0x159, |mut t| { + t.sort_unstable(); + t[1] + }), + ]; + // Every ordering of three values, with the sign bit set on some so that + // the signed and unsigned answers differ. + let values = [0u32, 1, 0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF]; + let mut cases = Vec::new(); + for a in values { + for b in values { + for c in values { + cases.push([a, b, c, 0]); + } + } + } + for (name, op, pick) in ops { + let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); + run_cases(&shader, &cases, |backend, _, inp, got| { + let want = pick([inp[0], inp[1], inp[2]]); + assert_eq!( + got, want, + "{backend}: {name}({:#010x}, {:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], inp[2], + ); + }); + } +} + #[test] fn v_med3_f16_matches_rdna2_with_nan() { // v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357) From c0cb57396db1ad73906c72abd7031449e8ef076e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:24:15 +0800 Subject: [PATCH 260/445] GPU: guard zero/overflowing stride in expand_rects and add primitive.rs unit tests (cherry picked from commit e3c9dd0d53d92d7a1dc7b86d75147d3ed390c61a) --- crates/victory-gpu/src/primitive.rs | 89 ++++++++++++++++++++++++++++- 1 file changed, 87 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index 180e43e..2eea1bb 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -22,9 +22,15 @@ /// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both /// triangles turn the same way. `elements` are (byte offset, format). pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: &[(u32, u32)]) { + if stride == 0 { + return; + } + let (Some(in_rect), Some(out_rect)) = (stride.checked_mul(3), stride.checked_mul(6)) else { + return; + }; for (rect, out) in src - .chunks_exact(3 * stride) - .zip(dst.chunks_exact_mut(6 * stride)) + .chunks_exact(in_rect) + .zip(dst.chunks_exact_mut(out_rect)) { let v = |i: usize| &rect[i * stride..(i + 1) * stride]; for (slot, i) in [0, 1, 2, 0, 2].into_iter().enumerate() { @@ -278,4 +284,83 @@ mod tests { assert_eq!(f32_to_half(1.5), 0x3e00); assert_eq!(half_to_f32(0x0001), 2f32.powi(-24)); } + + #[test] + fn zero_or_overflowing_stride_is_ignored_without_panicking() { + let mut dst = [0xAAu8; 16]; + expand_rects(&[1, 2, 3], &mut dst, 0, &[(0, 16)]); + assert_eq!(dst, [0xAAu8; 16]); + expand_rects(&[1, 2, 3], &mut dst, usize::MAX / 2, &[(0, 16)]); + assert_eq!(dst, [0xAAu8; 16]); + } + + #[test] + fn unorm16_unorm8_clamping_and_unknown_formats_expand_correctly() { + // Vertex layout (12 bytes): + // 0..4: R16G16_UNORM (format 35) + // 4..8: R8G8B8A8_UNORM (format 28) — tests clamping below 0 and above 1 + // 8..12: unknown format (999) — must keep v0's bytes verbatim + let v = |u0: u16, u1: u16, c: [u8; 4], raw: [u8; 4]| { + let mut b = Vec::with_capacity(12); + b.extend(u0.to_le_bytes()); + b.extend(u1.to_le_bytes()); + b.extend(c); + b.extend(raw); + b + }; + let src = [ + v( + 10_000, + 50_000, + [10, 200, 100, 255], + [0xDE, 0xAD, 0xBE, 0xEF], + ), + v(20_000, 10_000, [100, 50, 100, 255], [1, 2, 3, 4]), + v(30_000, 20_000, [20, 200, 100, 255], [5, 6, 7, 8]), + ] + .concat(); + let mut dst = vec![0u8; 6 * 12]; + expand_rects(&src, &mut dst, 12, &[(0, 35), (4, 28), (8, 999)]); + let fourth = &dst[60..72]; + // u0: 10000 + 30000 - 20000 = 20000; u1: 50000 + 20000 - 10000 = 60000 + assert_eq!(u16::from_le_bytes([fourth[0], fourth[1]]), 20_000); + assert_eq!(u16::from_le_bytes([fourth[2], fourth[3]]), 60_000); + // c0: 10 + 20 - 100 -> clamped to 0; c1: 200 + 200 - 50 -> clamped to 255 + assert_eq!(&fourth[4..8], &[0, 255, 100, 255]); + // Unknown format keeps v0 bytes + assert_eq!(&fourth[8..12], &[0xDE, 0xAD, 0xBE, 0xEF]); + } + + #[test] + fn multiple_rectangles_and_f32_f16_vector_formats_expand_in_sequence() { + // Two rectangles of R32G32B32_FLOAT (format 6, 12 bytes) + R16G16_FLOAT (format 34, 4 bytes) = 16 bytes + let v = |p: [f32; 3], uv: [f32; 2]| { + let mut b = Vec::with_capacity(16); + for x in p { + b.extend(x.to_le_bytes()); + } + for x in uv { + b.extend(f32_to_half(x).to_le_bytes()); + } + b + }; + let src = [ + // Rect 0 + v([0.0, 1.0, 0.5], [0.0, 0.0]), + v([0.0, 0.0, 0.5], [0.0, 1.0]), + v([2.0, 0.0, 0.5], [1.0, 1.0]), + // Rect 1 + v([10.0, 20.0, 1.0], [0.25, 0.5]), + v([10.0, 10.0, 1.0], [0.25, 1.0]), + v([14.0, 10.0, 1.0], [0.75, 1.0]), + ] + .concat(); + let mut dst = vec![0u8; 12 * 16]; + expand_rects(&src, &mut dst, 16, &[(0, 6), (12, 34)]); + assert_eq!(&dst[5 * 16..6 * 16], &v([2.0, 1.0, 0.5], [1.0, 0.0])[..]); + assert_eq!( + &dst[11 * 16..12 * 16], + &v([14.0, 20.0, 1.0], [0.75, 0.5])[..] + ); + } } From 74c9545debb239e9b66ef7e654491a5cb05f6fbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:30:43 +0800 Subject: [PATCH 261/445] GPU: validate null args in create_deserializer to prevent d3d12 AV and add root.rs tests (cherry picked from commit ef0c3e944916e2273457626be3d34f8dd5591eb4) --- crates/victory-gpu/src/root.rs | 262 ++++++++++++++++++++++++++++++++- 1 file changed, 260 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/root.rs b/crates/victory-gpu/src/root.rs index 5bded71..116f93b 100644 --- a/crates/victory-gpu/src/root.rs +++ b/crates/victory-gpu/src/root.rs @@ -154,7 +154,10 @@ pub extern "system" fn create_deserializer( iid: *const Iid, out: *mut *mut c_void, ) -> HRESULT { - if blob.is_null() || out.is_null() { + // The host dereferences the interface id without checking it, so a null + // one is answered here instead of crashing there; an empty blob is + // malformed and rejected the same way. + if blob.is_null() || size == 0 || iid.is_null() || out.is_null() { return E_INVALIDARG; } static FUNCTION: OnceLock> = OnceLock::new(); @@ -215,7 +218,218 @@ static FUNCTIONS: Table<24> = { #[cfg(test)] mod tests { use super::*; - use crate::object::{S_OK, slot}; + use crate::object::{E_NOINTERFACE, E_POINTER, S_FALSE, S_OK, slot}; + + /// An interface we do not implement. + const OTHER_IID: Iid = guid(0x5a5a_5a5a, 0x5a5a, 0x5a5a, [0x5a; 8]); + + /// The shim hands the blob to the host unchanged; `create` keeps it, so + /// any bytes serve. + const BLOB: [u8; 4] = [0x01, 0x02, 0x03, 0x04]; + + fn created(iid: &Iid) -> This { + let mut out = std::ptr::null(); + let hr = create( + std::ptr::null(), + 0, + BLOB.as_ptr(), + BLOB.len(), + iid, + &mut out, + ); + assert_eq!(hr, S_OK); + assert!(!out.is_null()); + out + } + + /// The host's structures, field for field (64-bit layout). + #[cfg(target_pointer_width = "64")] + #[test] + fn descriptions_keep_the_pc_layout() { + assert_eq!(std::mem::size_of::(), 40); + assert_eq!(std::mem::offset_of!(Desc, parameter_count), 0); + assert_eq!(std::mem::offset_of!(Desc, parameters), 8); + assert_eq!(std::mem::offset_of!(Desc, sampler_count), 16); + assert_eq!(std::mem::offset_of!(Desc, samplers), 24); + assert_eq!(std::mem::offset_of!(Desc, flags), 32); + assert_eq!(std::mem::size_of::(), 48); + assert_eq!(std::mem::offset_of!(VersionedDesc, version), 0); + assert_eq!(std::mem::offset_of!(VersionedDesc, desc), 8); + } + + #[test] + fn console_flags_are_dropped_and_the_rest_kept() { + assert_eq!(CONSOLE_FLAGS, 0xff00_0000); + let desc = Desc { + parameter_count: 2, + parameters: BLOB.as_ptr().cast(), + sampler_count: 1, + samplers: BLOB.as_ptr().cast(), + flags: 0xffff_ffff, + }; + let plain = without_console_flags(desc); + assert_eq!(plain.flags, 0x00ff_ffff); + assert_eq!((plain.parameter_count, plain.sampler_count), (2, 1)); + assert!(std::ptr::eq(plain.parameters, desc.parameters)); + assert!(std::ptr::eq(plain.samplers, desc.samplers)); + + let low = Desc { + flags: 0x00ab_cdef, + ..desc + }; + assert_eq!(without_console_flags(low).flags, 0x00ab_cdef); + let none = Desc { flags: 0, ..desc }; + assert_eq!(without_console_flags(none).flags, 0); + } + + #[test] + fn serializers_reject_a_null_description() { + let mut blob = std::ptr::null_mut(); + let mut error = std::ptr::null_mut(); + assert_eq!( + serialize(std::ptr::null(), 1, &mut blob, &mut error), + E_INVALIDARG + ); + assert_eq!( + serialize_versioned(std::ptr::null(), &mut blob, &mut error), + E_INVALIDARG + ); + assert!(blob.is_null() && error.is_null()); + } + + /// A null `riid` used to be forwarded to the host, which dereferences it + /// (an access violation in `d3d12.dll`); an empty blob is malformed. + #[test] + fn deserializer_creation_rejects_missing_arguments() { + let iid = ROOT_SIGNATURE_IIDS[0]; + let mut out = std::ptr::null_mut(); + assert_eq!( + create_deserializer(std::ptr::null(), BLOB.len(), &iid, &mut out), + E_INVALIDARG + ); + assert_eq!( + create_deserializer(BLOB.as_ptr(), BLOB.len(), std::ptr::null(), &mut out), + E_INVALIDARG + ); + assert_eq!( + create_deserializer(BLOB.as_ptr(), 0, &iid, &mut out), + E_INVALIDARG + ); + assert_eq!( + create_deserializer(BLOB.as_ptr(), BLOB.len(), &iid, std::ptr::null_mut()), + E_INVALIDARG + ); + assert!(out.is_null()); + } + + #[test] + fn creating_a_root_signature_checks_its_arguments() { + let iid = ROOT_SIGNATURE_IIDS[0]; + let mut out = std::ptr::null(); + assert_eq!( + create( + std::ptr::null(), + 0, + std::ptr::null(), + BLOB.len(), + &iid, + &mut out + ), + E_INVALIDARG + ); + assert_eq!( + create(std::ptr::null(), 0, BLOB.as_ptr(), 0, &iid, &mut out), + E_INVALIDARG + ); + assert!(out.is_null()); + + // An unknown interface is dropped, and the answer is null. + assert_eq!( + create( + std::ptr::null(), + 0, + BLOB.as_ptr(), + BLOB.len(), + &OTHER_IID, + &mut out + ), + E_NOINTERFACE + ); + assert!(out.is_null()); + assert_eq!( + create( + std::ptr::null(), + 0, + BLOB.as_ptr(), + BLOB.len(), + std::ptr::null(), + &mut out + ), + E_NOINTERFACE + ); + assert!(out.is_null()); + + // Nowhere to write means the title only asked whether creation works. + assert_eq!( + create( + std::ptr::null(), + 0, + BLOB.as_ptr(), + BLOB.len(), + &iid, + std::ptr::null_mut() + ), + S_FALSE + ); + } + + #[test] + fn every_known_interface_creates_a_working_object() { + let root = created(&ROOT_SIGNATURE_IIDS[0]); + let query = slot:: HRESULT>(root, 0); + for iid in &ROOT_SIGNATURE_IIDS { + let mut out = std::ptr::null(); + assert_eq!(query(root, iid, &mut out), S_OK); + assert!(std::ptr::eq(out, root)); + assert_eq!(object::release(out), 1, "the original reference remains"); + } + let mut out = std::ptr::null(); + assert_eq!(query(root, &OTHER_IID, &mut out), E_NOINTERFACE); + assert!(out.is_null()); + assert_eq!(query(root, std::ptr::null(), &mut out), E_NOINTERFACE); + assert_eq!( + query(root, &ROOT_SIGNATURE_IIDS[0], std::ptr::null_mut()), + E_POINTER + ); + assert_eq!(object::release(root), 0); + } + + #[test] + fn the_table_has_the_object_and_device_child_slots() { + let root = created(&ROOT_SIGNATURE_IIDS[1]); + // SetPrivateDataInterface is the one object method left out. + assert_eq!( + slot:: HRESULT>(root, 0x28)(), + E_NOTIMPL + ); + assert_eq!( + slot:: HRESULT>(root, 0x30)( + root, + std::ptr::null() + ), + S_OK + ); + // GetDevice: an unknown interface is answered, not dereferenced. + let mut device = std::ptr::null(); + let get_device = + slot:: HRESULT>(root, 0x38); + assert_eq!( + get_device(root, std::ptr::null(), &mut device), + E_NOINTERFACE + ); + assert!(device.is_null()); + assert_eq!(object::release(root), 0); + } /// One 32-bit constant at b0, serialized by the host, then created. #[cfg(windows)] @@ -321,4 +535,48 @@ mod tests { E_INVALIDARG ); } + + /// Truncated and nonsense blobs reach the host, which rejects them + /// without writing an object. + #[cfg(windows)] + #[test] + fn malformed_blobs_are_rejected_by_the_host() { + use windows::Win32::Graphics::Direct3D12::ID3D12RootSignatureDeserializer; + use windows::core::Interface; + let desc = VersionedDesc { + version: 1, + desc: Desc { + parameter_count: 0, + parameters: std::ptr::null(), + sampler_count: 0, + samplers: std::ptr::null(), + flags: 1, + }, + }; + let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut()); + assert_eq!(serialize_versioned(&desc, &mut blob, &mut error), S_OK); + let blob = blob.cast_const().cast::(); + let data = slot:: *const u8>(blob, 0x18)(blob); + let size = slot:: usize>(blob, 0x20)(blob); + let iid: Iid = ID3D12RootSignatureDeserializer::IID.to_u128().to_be_bytes(); + let iid = guid( + u32::from_be_bytes(iid[0..4].try_into().unwrap()), + u16::from_be_bytes(iid[4..6].try_into().unwrap()), + u16::from_be_bytes(iid[6..8].try_into().unwrap()), + iid[8..16].try_into().unwrap(), + ); + let mut out = std::ptr::null_mut(); + assert_eq!( + create_deserializer(data, size - 1, &iid, &mut out), + E_INVALIDARG + ); + assert!(out.is_null()); + let garbage = [0xffu8; 64]; + assert_eq!( + create_deserializer(garbage.as_ptr(), garbage.len(), &iid, &mut out), + E_INVALIDARG + ); + assert!(out.is_null()); + slot:: u32>(blob, 0x10)(blob); + } } From 3e3c49165fa2760ab5bfe5e228dc99db4738e043 Mon Sep 17 00:00:00 2001 From: bvtterbroot <157503259+bvtterbroot@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:33:46 +0100 Subject: [PATCH 262/445] GPU: log the TDR settings, and warn when a GPU hang would freeze the PC With TdrLevel 0 Windows never resets a hung GPU: a slow or hung world frame freezes the whole desktop, and the runtime never sees a device removal it could report (#1054). With 1 the timeout is a blue screen. Both are set by hand, often to keep slow frames from being reset, and reports of "the PC froze" do not say so. When the host device is made on a hardware adapter, read TdrLevel, TdrDelay and TdrDdiDelay from HKLM\SYSTEM\CurrentControlSet\Control\ GraphicsDrivers, log them ("default" where a value is not set), and warn for TdrLevel 0 or 1 with what to set instead. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 42961e8e577e5f195db0982e34bb59e800998c77) --- crates/victory-gpu/Cargo.toml | 2 +- crates/victory-gpu/src/host.rs | 2 + crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/tdr.rs | 145 +++++++++++++++++++++++++++++++++ 4 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 crates/victory-gpu/src/tdr.rs diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index 5857ae1..cba972b 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_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "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 = { workspace = true, features = [ "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D_Fxc", diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index edca8d4..78cef03 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -599,6 +599,8 @@ fn create() -> windows::core::Result { tracing::info!("host device on the software adapter (WARP)"); } else { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; + // Whether a GPU hang ends the run or freezes the PC (#1054). + crate::tdr::log(); } let device = device.ok_or_else(windows::core::Error::empty)?; // Before anything is made with it (`VICTORY_RECORD`). diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index e9a0cb2..532cf78 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -65,6 +65,8 @@ mod tiles; pub mod signature; mod switch; #[cfg(windows)] +mod tdr; +#[cfg(windows)] mod texture; #[cfg(windows)] mod watch; diff --git a/crates/victory-gpu/src/tdr.rs b/crates/victory-gpu/src/tdr.rs new file mode 100644 index 0000000..de0509b --- /dev/null +++ b/crates/victory-gpu/src/tdr.rs @@ -0,0 +1,145 @@ +//! Windows' timeout detection and recovery (TDR) for the host GPU, read once +//! when the host device is made (#1054). +//! +//! With `TdrLevel` 0 a GPU that stops answering is never reset: a slow or +//! hung world frame freezes the whole desktop, and the runtime never sees a +//! device removal it could report. With 1 the timeout is a blue screen. Both +//! are set by hand (often to keep slow frames from being reset), so the log +//! names them; raising `TdrDelay` is what gives slow frames room. + +use windows_sys::Win32::Foundation::ERROR_SUCCESS; +use windows_sys::Win32::System::Registry::{HKEY_LOCAL_MACHINE, RRF_RT_REG_DWORD, RegGetValueW}; + +/// Where Windows keeps the values. +const KEY: &str = r"SYSTEM\CurrentControlSet\Control\GraphicsDrivers"; + +/// The TDR values in the registry; `None` where one is not set and Windows +/// uses its default. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Tdr { + /// 0 off, 1 bugcheck, 2 recover to VGA, 3 recover (the default). + pub(crate) level: Option, + /// Seconds the GPU may take before it counts as hung (default 2). + pub(crate) delay: Option, + /// Seconds a driver call may take (default 5). + pub(crate) ddi_delay: Option, +} + +impl Tdr { + pub(crate) fn read() -> Self { + Tdr { + level: dword("TdrLevel"), + delay: dword("TdrDelay"), + ddi_delay: dword("TdrDdiDelay"), + } + } + + /// What a hung GPU would do to the PC with these values, when that is + /// worse than a device removal the runtime reports. + pub(crate) fn warning(&self) -> Option<&'static str> { + match self.level { + Some(0) => Some( + "TdrLevel is 0: Windows never resets a hung GPU, so a GPU hang freezes \ + the whole PC instead of ending the run with a device removal; delete \ + TdrLevel (or set it to 3) and raise TdrDelay to give slow frames room", + ), + Some(1) => Some( + "TdrLevel is 1: a GPU timeout stops Windows with a blue screen instead \ + of ending the run with a device removal; delete TdrLevel (or set it \ + to 3) and raise TdrDelay to give slow frames room", + ), + _ => None, + } + } +} + +/// A DWORD value under [`KEY`]; `None` when it is missing or not a DWORD. +fn dword(name: &str) -> Option { + let key = wide(KEY); + let name = wide(name); + let mut value = 0u32; + let mut size = size_of::() as u32; + // SAFETY: `key` and `name` are NUL-terminated UTF-16 strings that outlive + // the call, and `value` has room for the `size` bytes a DWORD takes. + let status = unsafe { + RegGetValueW( + HKEY_LOCAL_MACHINE, + key.as_ptr(), + name.as_ptr(), + RRF_RT_REG_DWORD, + std::ptr::null_mut(), + (&raw mut value).cast(), + &mut size, + ) + }; + (status == ERROR_SUCCESS).then_some(value) +} + +fn wide(s: &str) -> Vec { + s.encode_utf16().chain(std::iter::once(0)).collect() +} + +fn shown(value: Option) -> String { + value.map_or_else(|| "default".to_owned(), |v| v.to_string()) +} + +/// Logs the values, and warns when a GPU hang would freeze the PC or stop +/// it with a blue screen. +pub(crate) fn log() { + let tdr = Tdr::read(); + tracing::info!( + level = %shown(tdr.level), + delay = %shown(tdr.delay), + ddi_delay = %shown(tdr.ddi_delay), + "GPU timeout detection (TdrLevel, TdrDelay, TdrDdiDelay)" + ); + if let Some(warning) = tdr.warning() { + tracing::warn!("{warning}"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn level(level: Option) -> Tdr { + Tdr { + level, + ..Tdr::default() + } + } + + #[test] + fn off_and_bugcheck_warn() { + assert!(level(Some(0)).warning().unwrap().contains("freezes")); + assert!(level(Some(1)).warning().unwrap().contains("blue screen")); + } + + #[test] + fn recovery_and_the_default_do_not_warn() { + for l in [None, Some(2), Some(3)] { + assert_eq!(level(l).warning(), None, "TdrLevel {l:?}"); + } + } + + #[test] + fn delay_alone_does_not_warn() { + let tdr = Tdr { + level: Some(3), + delay: Some(60), + ddi_delay: Some(60), + }; + assert_eq!(tdr.warning(), None); + } + + #[test] + fn a_missing_value_reads_as_the_default() { + assert_eq!(dword("VictoryTestNoSuchValue"), None); + } + + #[test] + fn shown_names_the_default() { + assert_eq!(shown(None), "default"); + assert_eq!(shown(Some(60)), "60"); + } +} From 1c0015f062814192afd4d833d0068afb326a7d12 Mon Sep 17 00:00:00 2001 From: Giuseppe Rainone Date: Tue, 24 Nov 2026 16:34:21 +0100 Subject: [PATCH 263/445] HLE: constrain the title before suspending it Closing the window never suspended Grand Theft Auto VI: its suspend routine waits for a state that only its constrained-change routine starts, and RegisterAppConstrainedChangeNotification bound to the host's version, which never calls it. Every close ended in the one-second deadline. Register constrained-change routines here and run them (constrained) before the suspend routines (quiesced), as the console does. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit a7847a520197a45425bccf803a644e1968de67b2) --- crates/victory-hle/src/modules/lifecycle.rs | 114 +++++++++++++++++--- 1 file changed, 100 insertions(+), 14 deletions(-) diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs index f1b5777..9ddf2a4 100644 --- a/crates/victory-hle/src/modules/lifecycle.rs +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -1,8 +1,9 @@ //! The title's life cycle. A console title is never told it is closing: -//! quitting it or launching a new game first suspends it (its suspend -//! routines run, and it has a second to save) and then ends the process. -//! Closing the title's window does the same here; a new launch then starts -//! `victory` again, which waits for this process to be gone. +//! quitting it or launching a new game first constrains it (its +//! constrained-change routines run), then suspends it (its suspend routines +//! run, and it has a second to save) and then ends the process. Closing the +//! title's window does the same here; a new launch then starts `victory` +//! again, which waits for this process to be gone. #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] #![allow(clippy::too_many_arguments)] @@ -19,21 +20,35 @@ use windows_sys::core::{PCSTR, PCWSTR, w}; use crate::{HleModule, hle_export}; -type Routine = extern "system" fn(quiesced: u8, context: *mut c_void); +/// A suspend routine (`quiesced`) or a constrained-change routine +/// (`constrained`): both take a flag and the title's context. +type Routine = extern "system" fn(flag: u8, context: *mut c_void); -/// Registration id, routine and context of each suspend routine. -static ROUTINES: Mutex> = Mutex::new(Vec::new()); +/// Registration id, routine and context. +type Registration = (usize, Routine, usize); -fn routines() -> MutexGuard<'static, Vec<(usize, Routine, usize)>> { +/// Each suspend routine. +static ROUTINES: Mutex> = Mutex::new(Vec::new()); + +/// Each constrained-change routine. +static CONSTRAINED: Mutex> = Mutex::new(Vec::new()); + +fn routines() -> MutexGuard<'static, Vec> { ROUTINES.lock().unwrap_or_else(|e| e.into_inner()) } +fn constrained() -> MutexGuard<'static, Vec> { + CONSTRAINED.lock().unwrap_or_else(|e| e.into_inner()) +} + /// How long the console lets suspend routines run before it ends the title. const SUSPEND_DEADLINE: Duration = Duration::from_secs(1); const ERROR_INVALID_PARAMETER: u32 = 87; -pub extern "system" fn RegisterAppStateChangeNotification( +/// Adds `routine` to `list` and writes its registration id. +fn register( + mut list: MutexGuard<'static, Vec>, routine: Option, context: *mut c_void, registration: *mut usize, @@ -46,16 +61,38 @@ pub extern "system" fn RegisterAppStateChangeNotification( } static NEXT: AtomicUsize = AtomicUsize::new(1); let id = NEXT.fetch_add(1, Ordering::Relaxed); - routines().push((id, routine, context as usize)); + list.push((id, routine, context as usize)); // SAFETY: checked non-null; the title passes room for its registration. unsafe { registration.write(id) }; 0 } +pub extern "system" fn RegisterAppStateChangeNotification( + routine: Option, + context: *mut c_void, + registration: *mut usize, +) -> u32 { + register(routines(), routine, context, registration) +} + pub extern "system" fn UnregisterAppStateChangeNotification(registration: usize) { routines().retain(|&(id, ..)| id != registration); } +/// The host's own version never calls the routine (a desktop app is never +/// constrained), so a title waiting for it would never suspend. +pub extern "system" fn RegisterAppConstrainedChangeNotification( + routine: Option, + context: *mut c_void, + registration: *mut usize, +) -> u32 { + register(constrained(), routine, context, registration) +} + +pub extern "system" fn UnregisterAppConstrainedChangeNotification(registration: usize) { + constrained().retain(|&(id, ..)| id != registration); +} + /// The window procedure a title window had before ours. const TITLE_PROC: PCWSTR = w!("victory.wndproc"); @@ -201,8 +238,13 @@ pub(crate) fn end_title(why: &'static str, then: Box) { if ENDING.swap(true, Ordering::SeqCst) { return; } + let constrain = constrained().clone(); let suspend = routines().clone(); - tracing::info!(routines = suspend.len(), "{why}: suspending the title"); + tracing::info!( + constrained = constrain.len(), + routines = suspend.len(), + "{why}: suspending the title" + ); // Whoever comes first (the routines or the deadline) runs `then`; the // other waits for it, so the process never ends halfway through. let then = std::sync::Arc::new(Mutex::new(Some(then))); @@ -218,9 +260,7 @@ pub(crate) fn end_title(why: &'static str, then: Box) { // Not on the calling thread: titles hand the suspend to their window // thread and wait for it inside the routine. std::thread::spawn(move || { - for (_, routine, context) in suspend { - routine(1, context as *mut c_void); - } + constrain_then_suspend(&constrain, &suspend); finish("title suspended"); }); std::thread::spawn(move || { @@ -229,6 +269,16 @@ pub(crate) fn end_title(why: &'static str, then: Box) { }); } +/// Runs the constrained-change routines (constrained), then the suspend +/// routines (quiesced), as the console does when it suspends a title. +/// Grand Theft Auto VI's suspend routine waits for a state that only its +/// constrained routine brings about; called alone it never returns. +fn constrain_then_suspend(constrain: &[Registration], suspend: &[Registration]) { + for &(_, routine, context) in constrain.iter().chain(suspend) { + routine(1, context as *mut c_void); + } +} + /// Set in the environment of a relaunched `victory`: an inherited handle /// of the process it replaces. const RELAUNCHED_FROM: &str = "VICTORY_RELAUNCHED_FROM"; @@ -303,6 +353,8 @@ pub(crate) fn module() -> HleModule { exports: vec![ hle_export!(RegisterAppStateChangeNotification), hle_export!(UnregisterAppStateChangeNotification), + hle_export!(RegisterAppConstrainedChangeNotification), + hle_export!(UnregisterAppConstrainedChangeNotification), hle_export!(CreateWindowExW), hle_export!(CreateWindowExA), ], @@ -331,6 +383,40 @@ mod tests { assert_eq!(left, [b]); } + #[test] + fn constrained_registrations_come_and_go() { + let (mut a, mut b) = (0, 0); + assert_eq!( + RegisterAppConstrainedChangeNotification(Some(noop), std::ptr::null_mut(), &mut a), + 0 + ); + assert_eq!( + RegisterAppConstrainedChangeNotification(Some(noop), std::ptr::null_mut(), &mut b), + 0 + ); + assert_eq!( + RegisterAppConstrainedChangeNotification(None, std::ptr::null_mut(), &mut a), + ERROR_INVALID_PARAMETER + ); + UnregisterAppConstrainedChangeNotification(a); + let left: Vec<_> = constrained().iter().map(|r| r.0).collect(); + assert_eq!(left, [b]); + } + + /// What `recording_routine` saw: (context, flag) per call, in order. + static CALLS: Mutex> = Mutex::new(Vec::new()); + + extern "system" fn recording_routine(flag: u8, context: *mut c_void) { + CALLS.lock().unwrap().push((context as usize, flag)); + } + + #[test] + fn constrained_routines_run_before_suspend_routines() { + let r: Routine = recording_routine; + constrain_then_suspend(&[(1, r, 10), (2, r, 11)], &[(3, r, 20), (4, r, 21)]); + assert_eq!(*CALLS.lock().unwrap(), [(10, 1), (11, 1), (20, 1), (21, 1)]); + } + #[test] fn oversized_windows_shrink_to_the_screen() { let area = RECT { From 54d9c1bfa824fdfaba366c3c7f776bb312653850 Mon Sep 17 00:00:00 2001 From: Eduardo Bertozzi Date: Tue, 24 Nov 2026 12:39:07 -0300 Subject: [PATCH 264/445] README: how to install Rust on Windows (#1087) Getting started names Rust (pinned in rust-toolchain.toml) without saying how to get it. Add rustup through winget or rustup.rs, that the pinned toolchain then comes on the first cargo command, and the MSVC C++ build tools the Windows target needs. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 098a26aad5e3ef4655a9282f78cf713a2fc01a55) --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 49c4f92..683c127 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,12 @@ Requirements: Windows 10/11 x64, a CPU with AVX2, a Direct3D 12 GPU with shader model 6.6 (and mesh shaders for the world), Rust (pinned in `rust-toolchain.toml`). +To install Rust, use rustup (`winget install --id Rustlang.Rustup -e`, or +the installer from https://rustup.rs). The first `cargo` command in this +repository then fetches the pinned toolchain. Building needs the MSVC C++ +build tools: Visual Studio or its Build Tools with the "Desktop development +with C++" workload. + The title also needs several GiB of available Windows commit at startup. Check **Committed** under **Task Manager → Performance → Memory**. If `crashes.log` reports Windows error 1455, close other applications or increase From 0d2ac11430d2b3b2df09edc275a44b5280cad5d7 Mon Sep 17 00:00:00 2001 From: BastienRdz <58186763+BastienRodz@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:40:00 +0000 Subject: [PATCH 265/445] XAsync: canceling a call that already completed leaves it alone, as documented Microsoft's XAsyncCancel reference says: "If the XAsyncCancel function is invoked for an asynchronous call that has already completed, nothing happens." A call that completed successfully with a nonempty result stays in CALLS until the title reads the result via XAsyncGetResult, so XAsyncCancel still found it and invoked the provider with OP_CANCEL before XAsyncComplete returned early on call.done. Check call.done under its lock in XAsyncCancel and return immediately when the call is already complete, dropping the lock before invoking the provider. Co-Authored-By: Gemini 4 Neon Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 44ce06784b9ff8c7d9ab7ea4a9db02d72ee7804f) --- crates/victory-hle/src/modules/xasync.rs | 67 +++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index dc7b2ed..d08d4f6 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -722,9 +722,12 @@ pub fn XAsyncGetResultSize(block: *mut AsyncBlock, out: *mut usize) -> HRESULT { } /// Asks the provider to cancel; the call fails with `E_ABORT` unless the -/// provider completed it first. +/// provider completed it first. A completed call is left alone. pub fn XAsyncCancel(block: *mut AsyncBlock) { if let Some(call) = call(block) { + if *lock(&call.done) { + return; + } call.provider(OP_CANCEL, block, 0, std::ptr::null_mut()); complete_call(&call, block, E_ABORT, 0); } @@ -1423,6 +1426,68 @@ mod tests { XTaskQueueCloseHandle(q); } + #[test] + fn canceling_a_completed_call_leaves_it_alone() { + static CANCELS: AtomicU32 = AtomicU32::new(0); + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data. + let data = unsafe { &*data }; + match op { + OP_BEGIN => { + XAsyncComplete(data.block, S_OK, 1); + S_OK + } + OP_CANCEL => { + CANCELS.fetch_add(1, Ordering::SeqCst); + S_OK + } + OP_GET_RESULT => { + // SAFETY: the runtime checked one byte. + unsafe { data.buffer.cast::().write(0x5a) }; + S_OK + } + _ => S_OK, + } + } + let mut q = std::ptr::null(); + assert_eq!(XTaskQueueCreate(0, 0, &mut q), S_OK); + let mut block = AsyncBlock { + queue: q, + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + let identity = 0x78 as *const c_void; + assert_eq!( + XAsyncBegin( + &mut block, + std::ptr::null_mut(), + identity, + std::ptr::null(), + Some(provider), + ), + S_OK + ); + assert_eq!(XAsyncGetStatus(&mut block, false), S_OK); + XAsyncCancel(&mut block); + assert_eq!(CANCELS.load(Ordering::SeqCst), 0); + assert_eq!(XAsyncGetStatus(&mut block, false), S_OK); + let mut byte = 0u8; + let mut used = 0; + assert_eq!( + XAsyncGetResult( + &mut block, + identity, + 1, + (&mut byte as *mut u8).cast(), + &mut used, + ), + S_OK + ); + assert_eq!((byte, used), (0x5a, 1)); + XTaskQueueCloseHandle(q); + } + #[test] fn run_returns_the_work_result() { extern "system" fn work(_: *mut AsyncBlock) -> HRESULT { From 6d24aaa99703149559a12b9b81961032b204060d Mon Sep 17 00:00:00 2001 From: DoubleD17 <48109637+DoubleD17@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:16:15 +0000 Subject: [PATCH 266/445] Deduplicate image paths in victory census (cherry picked from commit 142ec8dd4563608b67ffabc8ba47175508f9a660) --- apps/victory/src/census.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/apps/victory/src/census.rs b/apps/victory/src/census.rs index 1314efb..6520bb6 100644 --- a/apps/victory/src/census.rs +++ b/apps/victory/src/census.rs @@ -42,6 +42,7 @@ pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> }); let mut images = 0usize; + let mut seen = BTreeSet::new(); let mut failed = Vec::new(); let mut dlls: BTreeMap = BTreeMap::new(); let mut missing: BTreeMap<(String, String), BTreeSet> = BTreeMap::new(); @@ -62,6 +63,11 @@ pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> if !entry.file_type().is_file() || !looks_like_pe(path) { continue; } + // Use the resolved path for deduplication and keep the original for output. + let identity = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); + if !seen.insert(identity) { + continue; + } let info = match std::fs::read(path) .map_err(anyhow::Error::from) .and_then(|d| ImageInfo::parse(&d).map_err(anyhow::Error::from)) From 20e295f2fc906e0d650c21bc75c9f9e7e7e35469 Mon Sep 17 00:00:00 2001 From: divyeshganta Date: Tue, 24 Nov 2026 21:53:04 +0530 Subject: [PATCH 267/445] HLE: avoid misaligned f32 output slice in XApu (cherry picked from commit 643fc6dfecffbd06de7313897b7d4bc4ffef6564) --- crates/victory-hle/src/modules/apu.rs | 176 ++++++++++++++++++++++++-- 1 file changed, 165 insertions(+), 11 deletions(-) diff --git a/crates/victory-hle/src/modules/apu.rs b/crates/victory-hle/src/modules/apu.rs index 0668f0d..9027da0 100644 --- a/crates/victory-hle/src/modules/apu.rs +++ b/crates/victory-hle/src/modules/apu.rs @@ -181,7 +181,13 @@ pub extern "system" fn XApuConnect( } let event = if input.options & RESULT_EVENT != 0 { // SAFETY: plain auto-reset event, no name. - unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) } + let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) }; + if event.is_null() { + // SAFETY: allocated above with `layout`. + unsafe { std::alloc::dealloc(memory, layout) }; + return E_OUTOFMEMORY; + } + event } else { std::ptr::null_mut() }; @@ -271,13 +277,15 @@ pub extern "system" fn XApuEnqueueCommand( tracing::debug!(stream, channels, "Opus stream activated"); result.error = if decoder.is_some() { ALREADY_ACTIVE + } else if !(1..=2).contains(&channels) { + E_INVALIDARG } else { match OpusDecoder::new(48_000, channels as usize) { - Ok(d) if (1..=2).contains(&channels) => { + Ok(d) => { *decoder = Some(d); S_OK } - _ => E_INVALIDARG, + Err(_) => E_INVALIDARG, } }; } @@ -340,17 +348,27 @@ fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: & .min(command.frame_count as usize) .min(output_length as usize / (4 * channels)); let kept = &pcm[first * channels..(first + frames) * channels]; - // SAFETY: the title's output buffer holds `output_length` bytes. - let out = unsafe { std::slice::from_raw_parts_mut(output.cast::(), frames * channels) }; - if options & DEINTERLEAVED_OUTPUT != 0 && channels == 2 { - for (i, frame) in kept.as_chunks::<2>().0.iter().enumerate() { - (out[i], out[frames + i]) = (frame[0], frame[1]); + let bytes = frames * channels * 4; + if bytes > 0 { + // SAFETY: `output` is non-null and holds at least `bytes <= output_length` bytes; + // writing raw bytes avoids requiring 4-byte alignment on the title's `*mut u8`. + let out = unsafe { std::slice::from_raw_parts_mut(output, bytes) }; + if options & DEINTERLEAVED_OUTPUT != 0 && channels == 2 { + let (left, right) = out.split_at_mut(frames * 4); + let (left, _) = left.as_chunks_mut::<4>(); + let (right, _) = right.as_chunks_mut::<4>(); + for (i, frame) in kept.as_chunks::<2>().0.iter().enumerate() { + left[i] = frame[0].to_le_bytes(); + right[i] = frame[1].to_le_bytes(); + } + } else { + for (dst, &sample) in out.as_chunks_mut::<4>().0.iter_mut().zip(kept) { + *dst = sample.to_le_bytes(); + } } - } else { - out.copy_from_slice(kept); } result.frames = frames as u32; - result.output_length = (frames * channels * 4) as u32; + result.output_length = bytes as u32; } pub extern "system" fn XApuDequeueResult(handle: *mut Connection, out: *mut ApuResult) -> HRESULT { @@ -521,4 +539,140 @@ mod tests { assert_eq!(error, INVALID_STREAM); assert_eq!(XApuDisconnect(handle), S_OK); } + + #[test] + fn decodes_into_unaligned_output_interleaved_and_deinterleaved() { + let tone: Vec = (0..960 * 2) + .map(|i| { + let phase = (i / 2) as f32 * std::f32::consts::TAU / 48_000.0; + if i % 2 == 0 { + (phase * 440.0).sin() * 0.5 + } else { + (phase * 880.0).sin() * 0.25 + } + }) + .collect(); + let mut encoder = OpusEncoder::new(48_000, 2, Application::Audio).unwrap(); + let mut packet = [0u8; 1500]; + let n = encoder.encode(&tone, 960, &mut packet).unwrap(); + + for (options, deinterleaved) in [(0u32, false), (DEINTERLEAVED_OUTPUT, true)] { + let input = ConnectInput { + process: DECODE_OPUS, + streams: 4, + commands_per_stream: 4, + memory: 0x4_0000, + frames_per_output: 0, + options, + }; + let mut output = ConnectOutput { + memory: std::ptr::null_mut(), + result_event: std::ptr::null_mut(), + }; + let mut handle = std::ptr::null_mut(); + assert_eq!(XApuConnect(&input, &mut output, &mut handle), S_OK); + let base = output.memory.cast::(); + + // Invalid channel counts fail cleanly without activating the stream. + for bad_channels in [0u32, 3, u32::MAX] { + let bad = Activate { + id: id(ACTIVATE, 0), + channels: bad_channels, + init_length: 0, + init: std::ptr::null(), + start_pitch: 1.0, + processing_length: 0, + processing: std::ptr::null_mut(), + }; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const bad).cast(), std::ptr::null_mut()), + S_OK + ); + let mut res = std::mem::MaybeUninit::::zeroed(); + assert_eq!(XApuDequeueResult(handle, res.as_mut_ptr()), S_OK); + // SAFETY: written by `XApuDequeueResult`. + let err = unsafe { res.assume_init() }.error; + assert_eq!(err, E_INVALIDARG, "channels={bad_channels}"); + } + + // Activate two identical stereo decoders so aligned and unaligned outputs match bit-for-bit. + for stream in [0u32, 1] { + let activate = Activate { + id: id(ACTIVATE, stream), + channels: 2, + init_length: 0, + init: std::ptr::null(), + start_pitch: 1.0, + processing_length: 0, + processing: std::ptr::null_mut(), + }; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const activate).cast(), std::ptr::null_mut()), + S_OK + ); + let mut res = std::mem::MaybeUninit::::zeroed(); + assert_eq!(XApuDequeueResult(handle, res.as_mut_ptr()), S_OK); + // SAFETY: written by `XApuDequeueResult`. + let err = unsafe { res.assume_init() }.error; + assert_eq!(err, S_OK); + } + + // SAFETY: inside the connection memory. + unsafe { std::ptr::copy_nonoverlapping(packet.as_ptr(), base, n) }; + let aligned_out = base.wrapping_add(0x10000); + let unaligned_out = base.wrapping_add(0x20001); // 1 mod 4: misaligned for f32 + + for (stream, out_ptr, frame_count) in [ + (0u32, aligned_out, 960u32), + (1u32, unaligned_out, 960u32), + (1u32, base.wrapping_add(0x30003), 0u32), // zero frames at misaligned ptr + ] { + let proc_cmd = Process { + id: id(PROCESS, stream), + pitch_ramp: 0.0, + target_pitch: 1.0, + first_frame: 0, + frame_count, + input_length: n as u32, + input: base, + output_length: 960 * 8, + output: out_ptr, + }; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const proc_cmd).cast(), std::ptr::null_mut()), + S_OK + ); + let mut res = std::mem::MaybeUninit::::zeroed(); + assert_eq!(XApuDequeueResult(handle, res.as_mut_ptr()), S_OK); + // SAFETY: written by `XApuDequeueResult`. + let decoded = unsafe { res.assume_init() }; + let (err, frames, len) = (decoded.error, decoded.frames, decoded.output_length); + assert_eq!((err, frames, len), (S_OK, frame_count, frame_count * 8)); + } + + // SAFETY: both output regions are inside connection memory and hold 960 * 8 bytes. + let (aligned_bytes, unaligned_bytes) = unsafe { + ( + std::slice::from_raw_parts(aligned_out, 960 * 8), + std::slice::from_raw_parts(unaligned_out, 960 * 8), + ) + }; + assert_eq!( + unaligned_bytes, aligned_bytes, + "unaligned output must match aligned output (deinterleaved={deinterleaved})" + ); + let samples: Vec = unaligned_bytes + .as_chunks::<4>() + .0 + .iter() + .map(|c| f32::from_le_bytes(*c)) + .collect(); + let energy: f32 = samples.iter().map(|s| s * s).sum::() / samples.len() as f32; + assert!( + energy > 0.01, + "expected decoded tone (deinterleaved={deinterleaved}), energy={energy}" + ); + assert_eq!(XApuDisconnect(handle), S_OK); + } + } } From 4ae3490420a337d08cd38de3a43e5bbf30d6ec4d Mon Sep 17 00:00:00 2001 From: ashrafsdrop Date: Tue, 24 Nov 2026 22:23:38 +0600 Subject: [PATCH 268/445] XNetworking: wire UDP port change callbacks and UTF-16 security queries (cherry picked from commit 64a33ec757c1da0963a6821cd59995b8efabe946) --- crates/victory-hle/src/modules/xnetworking.rs | 101 +++++++++++++++--- 1 file changed, 85 insertions(+), 16 deletions(-) diff --git a/crates/victory-hle/src/modules/xnetworking.rs b/crates/victory-hle/src/modules/xnetworking.rs index c0b21a3..01bc552 100644 --- a/crates/victory-hle/src/modules/xnetworking.rs +++ b/crates/victory-hle/src/modules/xnetworking.rs @@ -79,6 +79,14 @@ extern "system" fn udp_port_result(_: This, block: *mut AsyncBlock, out: *mut u1 static SECURITY: u8 = 0; +fn wide(text: *const u16) -> Option { + // SAFETY: the title passes a NUL-terminated UTF-16 string or null. + (!text.is_null()).then(|| unsafe { + let len = (0..).take_while(|&i| *text.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(text, len)) + }) +} + /// The allow list comes from the service: unreachable offline. extern "system" fn security_info_async( _: This, @@ -91,6 +99,17 @@ extern "system" fn security_info_async( ); xasync::finished(block, (&raw const SECURITY).cast(), UNREACHABLE) } +extern "system" fn security_info_utf16_async( + _: This, + url: *const u16, + block: *mut AsyncBlock, +) -> HRESULT { + tracing::debug!( + url = wide(url).unwrap_or_default(), + "security information (utf16): offline" + ); + xasync::finished(block, (&raw const SECURITY).cast(), UNREACHABLE) +} extern "system" fn security_info_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT { xasync::XAsyncGetResultSize(block, out) } @@ -124,7 +143,7 @@ extern "system" fn connectivity_hint(_: This, out: *mut ConnectivityHint) -> HRE put(out, OFFLINE) } -/// The hint never changes offline, so the callback never runs. +/// The hint and preferred port never change offline, so callbacks never run. extern "system" fn register( _: This, _queue: *const c_void, @@ -142,21 +161,21 @@ static VTABLE: Methods<18> = Methods([ missing::<0> as *const (), add_ref as *const (), add_ref as *const (), - udp_port as *const (), // 0x18 - udp_port_async as *const (), // 0x20 - udp_port_result as *const (), // 0x28 - missing::<6> as *const (), // 0x30 port changed - missing::<7> as *const (), // 0x38 - security_info_async as *const (), // 0x40 - security_info_size as *const (), // 0x48 - security_info_result as *const (), // 0x50 - missing::<11> as *const (), // 0x58 the same for UTF-16 URLs - missing::<12> as *const (), // 0x60 - missing::<13> as *const (), // 0x68 - verify_certificate as *const (), // 0x70 - connectivity_hint as *const (), // 0x78 - register as *const (), // 0x80 hint changed (never) - unregister as *const (), // 0x88 + udp_port as *const (), // 0x18 + udp_port_async as *const (), // 0x20 + udp_port_result as *const (), // 0x28 + register as *const (), // 0x30 port changed (never) + unregister as *const (), // 0x38 + security_info_async as *const (), // 0x40 + security_info_size as *const (), // 0x48 + security_info_result as *const (), // 0x50 + security_info_utf16_async as *const (), // 0x58 + security_info_size as *const (), // 0x60 + security_info_result as *const (), // 0x68 + verify_certificate as *const (), // 0x70 + connectivity_hint as *const (), // 0x78 + register as *const (), // 0x80 hint changed (never) + unregister as *const (), // 0x88 ]); #[cfg(test)] @@ -192,6 +211,28 @@ mod tests { assert_eq!(method::(&OBJECT, 0x28)(this, &mut b, &mut port), S_OK); assert_eq!(port, 3074); + type Register = extern "system" fn( + This, + *const c_void, + *mut c_void, + *const c_void, + *mut u64, + ) -> HRESULT; + type Unregister = extern "system" fn(This, u64, bool) -> bool; + let mut token = 0; + assert_eq!( + method::(&OBJECT, 0x30)( + this, + std::ptr::null(), + std::ptr::null_mut(), + std::ptr::null(), + &mut token, + ), + S_OK + ); + assert_ne!(token, 0); + assert!(method::(&OBJECT, 0x38)(this, token, false)); + type Url = extern "system" fn(This, *const c_char, *mut AsyncBlock) -> HRESULT; type Size = extern "system" fn(This, *mut AsyncBlock, *mut usize) -> HRESULT; let mut b = block(); @@ -206,5 +247,33 @@ mod tests { method::(&OBJECT, 0x48)(this, &mut b, &mut size), UNREACHABLE ); + + type UrlUtf16 = extern "system" fn(This, *const u16, *mut AsyncBlock) -> HRESULT; + let mut b = block(); + let url_utf16: Vec = "https://example.invalid/\0".encode_utf16().collect(); + assert_eq!( + method::(&OBJECT, 0x58)(this, url_utf16.as_ptr(), &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), UNREACHABLE); + let mut size = 0; + assert_eq!( + method::(&OBJECT, 0x60)(this, &mut b, &mut size), + UNREACHABLE + ); + + token = 0; + assert_eq!( + method::(&OBJECT, 0x80)( + this, + std::ptr::null(), + std::ptr::null_mut(), + std::ptr::null(), + &mut token, + ), + S_OK + ); + assert_ne!(token, 0); + assert!(method::(&OBJECT, 0x88)(this, token, false)); } } From 6bd18afffa0892e9a77bdef89d07e6bf6036dc91 Mon Sep 17 00:00:00 2001 From: EatCodeSleep2 <52021568+EatCodeSleep2@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:00:56 -0800 Subject: [PATCH 269/445] HLE: complete XPackage progress callback unregistration (cherry picked from commit 4f54c4775574e78ea7a869eae6605a401b107db3) --- crates/victory-hle/src/modules/xpackage.rs | 40 +++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/crates/victory-hle/src/modules/xpackage.rs b/crates/victory-hle/src/modules/xpackage.rs index 315faac..9fad9a3 100644 --- a/crates/victory-hle/src/modules/xpackage.rs +++ b/crates/victory-hle/src/modules/xpackage.rs @@ -136,6 +136,16 @@ extern "system" fn register_progress( put(out, token()) } +/// The completed installation has no pending progress callbacks to wait for. +extern "system" fn unregister_progress( + _: This, + _monitor: *const c_void, + _token: u64, + _wait: bool, +) -> bool { + true +} + /// 0: ready. // shortcut: every selector counts as installed, including ones the // package's layout does not have (the console answers those with an @@ -279,7 +289,7 @@ static VTABLE: Methods<40> = Methods([ progress as *const (), // 0x38 missing::<8> as *const (), // 0x40 update a monitor register_progress as *const (), // 0x48 - missing::<10> as *const (), // 0x50 unregister it + unregister_progress as *const (), // 0x50 missing::<11> as *const (), // 0x58 user locale find_availability as *const (), // 0x60 missing::<13> as *const (), // 0x68 enumerate chunk availability @@ -316,6 +326,34 @@ mod tests { use super::*; use crate::modules::xgameruntime::method; + #[test] + fn completed_installation_unregisters_progress_immediately() { + type Register = + extern "system" fn(This, *const c_void, *mut c_void, *const c_void, *mut u64) -> HRESULT; + type Unregister = extern "system" fn(This, *const c_void, u64, bool) -> bool; + extern "system" fn callback(_: *mut c_void, _: *const c_void) {} + + let this: This = &OBJECT; + let register = method::(&OBJECT, 0x48); + assert_eq!(VTABLE.0[0x50 / 8], unregister_progress as *const ()); + let unregister = method::(&OBJECT, 0x50); + for wait in [false, true] { + let mut token = 0; + assert_eq!( + register( + this, + monitor(), + std::ptr::null_mut(), + callback as *const c_void, + &mut token + ), + S_OK + ); + assert_ne!(token, 0); + assert!(unregister(this, monitor(), token, wait)); + } + } + #[test] fn the_installation_is_complete_and_alone() { let this: This = &OBJECT; From 635360da208895bb943b2b0637b4e21807d8af90 Mon Sep 17 00:00:00 2001 From: EatCodeSleep2 <52021568+EatCodeSleep2@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:07:35 -0800 Subject: [PATCH 270/445] Shaders: fold conditional branches to their fallthrough (cherry picked from commit 1ed26e50d860f328cd42c640bc12486f65603995) --- crates/victory-shader/src/emit/valu_tests.rs | 20 ++++++++++++++++++++ crates/victory-shader/src/ir.rs | 12 +++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 8dd2f36..a140708 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -299,6 +299,26 @@ fn is_f16_nan(bits: u16) -> bool { (bits & 0x7FFF) > 0x7C00 } +#[test] +fn a_branch_to_fallthrough_keeps_both_values_at_a_join() { + let shader = build_valu_cs(&[ + 0xBF06_0100, // s_cmp_eq_u32 s0, s1 + 0xBF85_0002, // s_cbranch_scc1 -> the s2 = 1 path + s_mov_b32(2, 128), // s2 = 0 + 0xBF82_0002, // s_branch -> the join + s_mov_b32(2, 129), // s2 = 1 + 0xBF85_0000, // s_cbranch_scc1 -> the following instruction + vop1(0x001, 0, sgpr(2)), // join: v0 = s2 + ]); + run_cases( + &shader, + &[[7, 7, 0, 0], [7, 5, 0, 0]], + |backend, _, inputs, actual| { + assert_eq!(actual, u32::from(inputs[0] == inputs[1]), "{backend}"); + }, + ); +} + fn f16_to_f32(bits: u16) -> f32 { let sign = u32::from(bits >> 15) << 31; let exp = (bits >> 10) & 0x1F; diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 577fbc1..518e72e 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -1,7 +1,8 @@ //! One-to-one SSA form of a native program (decision 0003, step 1). //! //! Every machine instruction becomes one [`Inst`], except scheduling-only -//! ones (`s_nop`, `s_waitcnt*`, `s_inst_prefetch`...), which are dropped. +//! ones (`s_nop`, `s_waitcnt*`, `s_inst_prefetch`...) and redundant conditional +//! branches. //! Each register dword is a variable: a read names the [`Value`] it sees, a //! write defines a new one, and [`Phi`]s merge values where control flow //! joins. Nothing is raised: an instruction keeps its opcode and decoded @@ -187,6 +188,15 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result Date: Tue, 24 Nov 2026 22:45:02 +0530 Subject: [PATCH 271/445] docs: explain Windows shader-test validator prerequisite (cherry picked from commit 32eb93495919655651e6b64be31e68b71af70422) --- README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/README.md b/README.md index 683c127..eb3da65 100644 --- a/README.md +++ b/README.md @@ -265,6 +265,24 @@ victory config Logging: `VICTORY_LOG=victory_loader=trace,info` (a release build logs info and above). +### Windows shader-test validator + +The shader tests use `dxil.dll` to validate Shader Model 6.6 containers. +An older Windows SDK validator can load successfully but reject them with +`Unknown shader model 'ps_6_6'`. If this happens, use a current x64 validator +from [Microsoft's DirectX Shader Compiler releases](https://github.com/microsoft/DirectXShaderCompiler/releases) +or a current Windows SDK. Set its path for the test session: + +```powershell +$env:VICTORY_DXIL = 'C:\tools\dxc\bin\x64\dxil.dll' +cargo test -p victory-shader --lib --locked -- --test-threads=1 +``` + +Without this override, the validator loader selects the newest installed +Windows SDK's `bin//x64/dxil.dll`, then falls back to the DLL search +path when no SDK copy is found. This is a test/offline-validation dependency; +the translated shaders do not require it at runtime. + ## Debugging A release build has no debugging aids. Build them in with From c339306eff8d7af5a3613c71d656ff01a034dfa5 Mon Sep 17 00:00:00 2001 From: fuzeofficial Date: Wed, 25 Nov 2026 02:21:44 +0900 Subject: [PATCH 272/445] Shaders: compress replaced phi chains in remove_trivial_phis (cherry picked from commit 5c44562868df4c33cce60488132d83cf5ff02f30) --- crates/victory-shader/src/ir.rs | 234 ++++++++++++++++++++++++++++++-- 1 file changed, 225 insertions(+), 9 deletions(-) diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 518e72e..0e8a4ed 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -1240,13 +1240,28 @@ fn liveness(blocks: &[Block], order: &[usize]) -> (Vec, Vec) { /// Phis are placed for every live register at every join; those whose /// arguments are all one value (or the phi itself) are replaced by it. fn remove_trivial_phis(blocks: &mut [Block], values: u32) { - let mut replaced: Vec = (0..values).map(Value).collect(); - let find = |replaced: &[Value], mut v: Value| { - while replaced[v.0 as usize] != v { - v = replaced[v.0 as usize]; + remove_trivial_phis_steps(blocks, values); +} + +fn remove_trivial_phis_steps(blocks: &mut [Block], values: u32) -> usize { + fn find(replaced: &mut [Value], v: Value, steps: &mut usize) -> Value { + let mut root = v; + while replaced[root.0 as usize] != root { + *steps += 1; + root = replaced[root.0 as usize]; } - v - }; + let mut cur = v; + while replaced[cur.0 as usize] != root { + *steps += 1; + let next = replaced[cur.0 as usize]; + replaced[cur.0 as usize] = root; + cur = next; + } + root + } + + let mut replaced: Vec = (0..values).map(Value).collect(); + let mut steps = 0usize; let mut changed = true; while changed { changed = false; @@ -1254,7 +1269,7 @@ fn remove_trivial_phis(blocks: &mut [Block], values: u32) { block.phis.retain(|phi| { let mut only = None; for &a in &phi.args { - let a = find(&replaced, a); + let a = find(&mut replaced, a, &mut steps); if a == phi.value || Some(a) == only { continue; } @@ -1273,15 +1288,16 @@ fn remove_trivial_phis(blocks: &mut [Block], values: u32) { for block in blocks { for phi in &mut block.phis { for a in &mut phi.args { - *a = find(&replaced, *a); + *a = find(&mut replaced, *a, &mut steps); } } for inst in &mut block.insts { for (_, v) in &mut inst.reads { - *v = find(&replaced, *v); + *v = find(&mut replaced, *v, &mut steps); } } } + steps } /// Scheduling hints, performance counters and tracing: no effect on results. @@ -1934,4 +1950,204 @@ mod tests { assert_eq!(movrels.read(Reg::V(4)), movreld.write(Reg::V(4))); assert!(build(&code, false, 4).is_err(), "v4 is past 4 VGPRs"); } + + const fn s_branch(simm16: i16) -> u32 { + 0xBF82_0000 | simm16 as u16 as u32 + } + + const fn s_cbranch_scc1(simm16: i16) -> u32 { + 0xBF85_0000 | simm16 as u16 as u32 + } + + #[test] + fn reverse_order_diamond_chain_eliminates_trivial_phis() { + const LAYERS: usize = 4096; + let mut reverse = vec![ + 0xBE81_0381, // s_mov_b32 s1, 1 + 0xBE82_0382, // s_mov_b32 s2, 2 + s_branch(((LAYERS - 1) * 4) as i16), + ]; + for k in 0..LAYERS { + reverse.extend([ + 0xBF06_0201, // s_cmp_eq_u32 s1, s2 + s_cbranch_scc1(1), + 0xBF80_0000, // s_nop 0 + if k == 0 { + s_branch((LAYERS * 4 - 4) as i16) + } else { + s_branch(-8) + }, + ]); + } + reverse.extend([0x8000_0201, S_ENDPGM]); // s_add_u32 s0, s1, s2 + + let mut forward = vec![ + 0xBE81_0381, // s_mov_b32 s1, 1 + 0xBE82_0382, // s_mov_b32 s2, 2 + s_branch(0), + ]; + for _ in 0..LAYERS { + forward.extend([ + 0xBF06_0201, // s_cmp_eq_u32 s1, s2 + s_cbranch_scc1(1), + 0xBF80_0000, // s_nop 0 + s_branch(0), + ]); + } + forward.extend([0x8000_0201, S_ENDPGM]); // s_add_u32 s0, s1, s2 + + let rev = build_words(&reverse, false); + let fwd = build_words(&forward, false); + assert!(rev.inputs.is_empty(), "{:?}", rev.inputs); + assert!(fwd.inputs.is_empty(), "{:?}", fwd.inputs); + assert!(rev.blocks.iter().all(|b| b.phis.is_empty())); + assert!(fwd.blocks.iter().all(|b| b.phis.is_empty())); + assert_eq!(rev.blocks.len(), fwd.blocks.len()); + + let rev_s1 = rev.blocks[0].insts[0].write(Reg::S(1)).unwrap(); + let rev_s2 = rev.blocks[0].insts[1].write(Reg::S(2)).unwrap(); + let rev_exit = rev.blocks.last().unwrap(); + assert_eq!(rev_exit.insts[0].name(), "s_add_u32"); + assert_eq!(rev_exit.insts[0].read(Reg::S(1)), Some(rev_s1)); + assert_eq!(rev_exit.insts[0].read(Reg::S(2)), Some(rev_s2)); + + let fwd_s1 = fwd.blocks[0].insts[0].write(Reg::S(1)).unwrap(); + let fwd_s2 = fwd.blocks[0].insts[1].write(Reg::S(2)).unwrap(); + let fwd_exit = fwd.blocks.last().unwrap(); + assert_eq!(fwd_exit.insts[0].name(), "s_add_u32"); + assert_eq!(fwd_exit.insts[0].read(Reg::S(1)), Some(fwd_s1)); + assert_eq!(fwd_exit.insts[0].read(Reg::S(2)), Some(fwd_s2)); + } + + #[test] + fn remove_trivial_phis_compresses_reverse_chain_in_bounded_steps() { + const CHAIN: usize = 4096; + let mut template = build_words(&[0xBE80_0380, S_ENDPGM], false).blocks[0].insts[0].clone(); + template.writes.clear(); + let mut blocks = Vec::with_capacity(CHAIN); + for k in 0..CHAIN { + let v1 = Value(2 + 2 * k as u32); + let v2 = Value(3 + 2 * k as u32); + let (n1, n2) = if k + 1 < CHAIN { + (Value(2 + 2 * (k + 1) as u32), Value(3 + 2 * (k + 1) as u32)) + } else { + (Value(0), Value(1)) + }; + let mut inst = template.clone(); + inst.reads = vec![(Reg::S(1), v1), (Reg::S(2), v2)]; + blocks.push(Block { + offset: k * 4, + preds: vec![], + phis: vec![ + Phi { + reg: Reg::S(1), + value: v1, + args: vec![n1, n1], + }, + Phi { + reg: Reg::S(2), + value: v2, + args: vec![n2, n2], + }, + ], + insts: vec![inst], + exit: Exit::End, + }); + } + let steps = remove_trivial_phis_steps(&mut blocks, 2 + 2 * CHAIN as u32); + assert!(blocks.iter().all(|b| b.phis.is_empty())); + assert!( + blocks + .iter() + .all(|b| b.insts[0].reads == [(Reg::S(1), Value(0)), (Reg::S(2), Value(1))]) + ); + assert!(steps < 100_000, "steps = {steps}"); + } + + #[test] + fn non_trivial_phis_preserve_compressed_representatives() { + const LAYERS: usize = 4; + let mut code = vec![ + 0xBE81_0381, // s_mov_b32 s1, 1 + 0xBE82_0382, // s_mov_b32 s2, 2 + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + s_cbranch_scc1((2 + (LAYERS - 1) * 4) as i16), + 0xBE81_0383, // s_mov_b32 s1, 3 + s_branch((LAYERS * 4) as i16), + ]; + for k in 0..LAYERS { + code.extend([ + 0xBF06_0201, // s_cmp_eq_u32 s1, s2 + s_cbranch_scc1(1), + 0xBF80_0000, // s_nop 0 + if k == 0 { + s_branch((LAYERS * 4 - 4) as i16) + } else { + s_branch(-8) + }, + ]); + } + code.extend([0x8000_0201, S_ENDPGM]); // s_add_u32 s0, s1, s2 + + let p = build_words(&code, false); + let entry_s1 = p.blocks[0].insts[0].write(Reg::S(1)).unwrap(); + let entry_s2 = p.blocks[0].insts[1].write(Reg::S(2)).unwrap(); + let arm_s1 = p.blocks[1].insts[0].write(Reg::S(1)).unwrap(); + let merge = p.blocks.last().unwrap(); + for b in &p.blocks[..p.blocks.len() - 1] { + assert!(b.phis.is_empty(), "{:?}", b.phis); + } + let [phi] = &merge.phis[..] else { + panic!("{:?}", merge.phis) + }; + assert_eq!(phi.reg, Reg::S(1)); + assert_eq!(phi.args, [arm_s1, entry_s1]); + assert_eq!(merge.insts[0].read(Reg::S(1)), Some(phi.value)); + assert_eq!(merge.insts[0].read(Reg::S(2)), Some(entry_s2)); + + let mut loop_code = vec![ + 0xBE81_0381, // s_mov_b32 s1, 1 + 0xBE82_0382, // s_mov_b32 s2, 2 + s_branch(((LAYERS - 1) * 4) as i16), + ]; + for k in 0..LAYERS { + loop_code.extend([ + 0xBF06_0201, // s_cmp_eq_u32 s1, s2 + s_cbranch_scc1(1), + 0xBF80_0000, // s_nop 0 + if k == 0 { + s_branch((LAYERS * 4 - 4) as i16) + } else { + s_branch(-8) + }, + ]); + } + loop_code.extend([ + 0x8001_0201, // s_add_u32 s1, s1, s2 + 0xBF07_8401, // s_cmp_lg_u32 s1, 4 + s_cbranch_scc1(-3), + 0x8000_0201, // s_add_u32 s0, s1, s2 + S_ENDPGM, + ]); + + let lp = build_words(&loop_code, false); + let lp_s1 = lp.blocks[0].insts[0].write(Reg::S(1)).unwrap(); + let lp_s2 = lp.blocks[0].insts[1].write(Reg::S(2)).unwrap(); + let header = &lp.blocks[lp.blocks.len() - 2]; + let exit = lp.blocks.last().unwrap(); + for b in &lp.blocks[..lp.blocks.len() - 2] { + assert!(b.phis.is_empty(), "{:?}", b.phis); + } + assert!(exit.phis.is_empty(), "{:?}", exit.phis); + let [loop_phi] = &header.phis[..] else { + panic!("{:?}", header.phis) + }; + let next_s1 = header.insts[0].write(Reg::S(1)).unwrap(); + assert_eq!(loop_phi.reg, Reg::S(1)); + assert_eq!(loop_phi.args, [lp_s1, next_s1]); + assert_eq!(header.insts[0].read(Reg::S(1)), Some(loop_phi.value)); + assert_eq!(header.insts[0].read(Reg::S(2)), Some(lp_s2)); + assert_eq!(exit.insts[0].read(Reg::S(1)), Some(next_s1)); + assert_eq!(exit.insts[0].read(Reg::S(2)), Some(lp_s2)); + } } From b6ca1191b7b505b3a40910b0e4f6dda095113dc6 Mon Sep 17 00:00:00 2001 From: mgunes1311-lab Date: Tue, 24 Nov 2026 20:36:35 +0300 Subject: [PATCH 273/445] Shaders: do not parse VS inputs when reading mesh shader stage I/O (cherry picked from commit 4e155a36ad728e1a21e7253ff4097af06582a45f) --- crates/victory-shader/src/native.rs | 42 ++++++++++++++++++----------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index 192f355..0dee361 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -799,6 +799,21 @@ fn ps_io(data: &[u8], code_len: usize) -> Result { }) } +fn vs_outputs(data: &[u8]) -> Result, ShaderError> { + Ok(semantics(data, VS_OUTPUTS, 6, VS_OUTPUT_COUNT)? + .as_chunks::<6>() + .0 + .iter() + .map(|e| VsOutput { + usage: Usage::from_raw(e[0]), + row: e[1], + param: e[2], + fp16: e[5] & 1 != 0, + pack2: e[5] & 2 != 0, + }) + .collect()) +} + fn vs_io(data: &[u8]) -> Result { let inputs = semantics(data, VS_INPUTS, 5, VS_INPUT_COUNT)? .as_chunks::<5>() @@ -811,25 +826,12 @@ fn vs_io(data: &[u8]) -> Result { vgpr: e[3], }) .collect(); - let outputs = semantics(data, VS_OUTPUTS, 6, VS_OUTPUT_COUNT)? - .as_chunks::<6>() - .0 - .iter() - .map(|e| VsOutput { - usage: Usage::from_raw(e[0]), - row: e[1], - param: e[2], - fp16: e[5] & 1 != 0, - pack2: e[5] & 2 != 0, - }) - .collect(); + let outputs = vs_outputs(data)?; Ok(StageIo::Vs { inputs, outputs }) } fn ms_io(data: &[u8], lds_bytes: u32) -> Result { - let StageIo::Vs { outputs, .. } = vs_io(data)? else { - unreachable!() - }; + let outputs = vs_outputs(data)?; let info = data .get(MS_INFO..MS_INFO + 8) .ok_or(Malformed("stage data out of bounds"))?; @@ -1129,6 +1131,16 @@ mod tests { ); } + #[test] + fn mesh_stage_io_ignores_unused_vs_input_count() { + let mut blob = fssm(&[(HwStage::Ms, &VS_CODE)]); + let e = stage_data_at(&blob, HwStage::Ms); + // Mesh stage data has no vertex inputs; E+0xc4 is unused by MS. + blob[e + VS_INPUT_COUNT..][..4].copy_from_slice(&u32::MAX.to_le_bytes()); + let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0]; + assert!(matches!(p.io, StageIo::Ms(_))); + } + #[test] fn compute_dispatch_settings() { // 5 user SGPRs, group id x and y, thread ids in v0-v1, 1 KiB LDS. From 2d34e466b32910bd1111a49aecad45744c5b3b2b Mon Sep 17 00:00:00 2001 From: BaggyALPHA <257889696+BaggyALPHA@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:49:36 -0500 Subject: [PATCH 274/445] HLE clears the result of blocked address lookups (cherry picked from commit 2b13ae41920296be79dc9642913a7807ecc98d57) --- crates/victory-hle/src/modules/net.rs | 61 +++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 4 deletions(-) diff --git a/crates/victory-hle/src/modules/net.rs b/crates/victory-hle/src/modules/net.rs index 857b351..d7360c5 100644 --- a/crates/victory-hle/src/modules/net.rs +++ b/crates/victory-hle/src/modules/net.rs @@ -537,6 +537,14 @@ pub extern "system" fn bind(s: Socket, name: *const u8, len: i32) -> i32 { // Forward lookups. +fn blocked_lookup(result: *mut *mut c_void) -> i32 { + if !result.is_null() { + // SAFETY: a non-null result points to the caller's output slot. + unsafe { result.write(std::ptr::null_mut()) }; + } + WSAHOST_NOT_FOUND +} + pub extern "system" fn getaddrinfo( node: *const c_char, service: *const c_char, @@ -544,7 +552,7 @@ pub extern "system" fn getaddrinfo( result: *mut *mut c_void, ) -> i32 { if !resolvable(narrow(node)) { - return WSAHOST_NOT_FOUND; + return blocked_lookup(result); } host!("ws2_32.dll", "getaddrinfo": extern "system" fn(*const c_char, *const c_char, *const c_void, *mut *mut c_void) -> i32)( node, service, hints, result, @@ -558,7 +566,7 @@ pub extern "system" fn GetAddrInfoW( result: *mut *mut c_void, ) -> i32 { if !resolvable(wide(node)) { - return WSAHOST_NOT_FOUND; + return blocked_lookup(result); } host!("ws2_32.dll", "GetAddrInfoW": extern "system" fn(*const u16, *const u16, *const c_void, *mut *mut c_void) -> i32)( node, service, hints, result, @@ -578,7 +586,7 @@ pub extern "system" fn GetAddrInfoExA( handle: *mut Handle, ) -> i32 { if !resolvable(narrow(name)) { - return WSAHOST_NOT_FOUND; + return blocked_lookup(result); } host!("ws2_32.dll", "GetAddrInfoExA": extern "system" fn(*const c_char, *const c_char, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)( name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle, @@ -598,7 +606,7 @@ pub extern "system" fn GetAddrInfoExW( handle: *mut Handle, ) -> i32 { if !resolvable(wide(name)) { - return WSAHOST_NOT_FOUND; + return blocked_lookup(result); } host!("ws2_32.dll", "GetAddrInfoExW": extern "system" fn(*const u16, *const u16, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)( name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle, @@ -895,6 +903,51 @@ mod tests { const AWAY: [u8; 4] = [192, 0, 2, 1]; const HOME: [u8; 4] = [127, 0, 0, 1]; + #[test] + fn blocked_name_lookups_clear_the_result() { + let ansi = c"blocked.invalid".as_ptr(); + let wide: Vec = "blocked.invalid\0".encode_utf16().collect(); + let wide = wide.as_ptr(); + let null = std::ptr::null(); + let null_mut = std::ptr::null_mut(); + let check = |lookup: &dyn Fn(*mut *mut c_void) -> i32| { + let mut result = std::ptr::dangling_mut::(); + assert_eq!(lookup(&mut result), WSAHOST_NOT_FOUND); + assert!(result.is_null()); + assert_eq!(lookup(std::ptr::null_mut()), WSAHOST_NOT_FOUND); + }; + check(&|result| getaddrinfo(ansi, std::ptr::null(), null, result)); + check(&|result| GetAddrInfoW(wide, std::ptr::null(), null, result)); + check(&|result| { + GetAddrInfoExA( + ansi, + std::ptr::null(), + 0, + null, + null, + result, + null, + null_mut, + null, + std::ptr::null_mut(), + ) + }); + check(&|result| { + GetAddrInfoExW( + wide, + std::ptr::null(), + 0, + null, + null, + result, + null, + null_mut, + null, + std::ptr::null_mut(), + ) + }); + } + #[test] fn only_loopback_is_reachable() { // Also starts Winsock for the raw calls below. From eb84fc3db7cc4aacde547fac4872a7b2dafb310b Mon Sep 17 00:00:00 2001 From: Luiz Otavio Mello de Campos Date: Tue, 24 Nov 2026 15:01:49 -0300 Subject: [PATCH 275/445] Test scalar quadmask lowering on D3D12 Check both mask widths, the condition code and the zeroed upper destination. (cherry picked from commit e3fe5bf94f848c2a6ca36900c2dfa70342083109) --- crates/victory-shader/src/emit/valu_tests.rs | 33 ++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index a140708..b8275e0 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -295,6 +295,39 @@ fn scalar_quad_masks_pack_nibbles_and_set_scc() { }); } +#[test] +fn scalar_quad_masks_pack_nibbles_and_set_scc() { + let pack_words = |opcode: u32| { + [ + 0xBE90_0000 | opcode << 8, // s_quadmask s16, s0 (pairs for b64) + sop2(0x0a, 18, 129, 128), // s_cselect_b32 s18, 1, 0 + sop2(0x1e, 18, 18, 144), // s_lshl_b32 s18, s18, 16 + sop2(0x10, 16, 16, 18), // s_or_b32 s16, s16, s18 + vop1(1, 0, sgpr(16)), // v_mov_b32 v0, s16 + ] + }; + let cases = [ + ([0, 0, 0, 0], [0, 0]), + ([0x8000_0420, 0x0100_0001, 0, 0], [0x1_0086, 0x1_4186]), + ([0, 0x8000_0000, 0, 0], [0, 0x1_8000]), + ([u32::MAX, u32::MAX, 0, 0], [0x1_00ff, 0x1_ffff]), + ]; + let inputs = cases.map(|(input, _)| input); + for (wide, opcode) in [0x2c, 0x2d].into_iter().enumerate() { + let shader = build_valu_cs(&pack_words(opcode)); + run_cases(&shader, &inputs, |backend, i, _, got| { + assert_eq!(got, cases[i].1[wide], "{backend}, opcode {opcode:#x}"); + }); + } + let high = build_valu_cs(&[ + 0xBE90_2D00, // s_quadmask_b64 s[16:17], s[0:1] + vop1(1, 0, sgpr(17)), + ]); + run_cases(&high, &inputs, |backend, _, _, got| { + assert_eq!(got, 0, "{backend}: high dword"); + }); +} + fn is_f16_nan(bits: u16) -> bool { (bits & 0x7FFF) > 0x7C00 } From 482ee84e2ce3e967808c734b30bd2a83a0841e0c Mon Sep 17 00:00:00 2001 From: fluffyflattershy-afk Date: Tue, 24 Nov 2026 21:03:29 +0300 Subject: [PATCH 276/445] HLE: allow an explicit maximum title window size (cherry picked from commit a7636dd7b1a4a76eaa4f1cf211d2ff31faacc3f5) --- README.md | 7 ++ crates/victory-hle/src/modules/lifecycle.rs | 104 +++++++++++++++++++- 2 files changed, 108 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index eb3da65..2fe02b7 100644 --- a/README.md +++ b/README.md @@ -237,6 +237,13 @@ The window caption shows the framerate. Saves, settings and `crashes.log` are kept under the data folder (default `%LOCALAPPDATA%\victory\data`), derived data under the cache folder. +Set `VICTORY_WINDOW_MAX=1920x1080` before launching to limit the title's +top-level window to that bounding box. Smaller windows keep their size, +larger windows keep their proportions, and the monitor's work area still +limits them. This scales the displayed image; it does not change the +console render resolution or the swap-chain buffers. With the variable +unset, window sizing is unchanged. + Input: XInput pads. With none connected the keyboard is a pad while the title's window has focus: diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs index 9ddf2a4..09c6baa 100644 --- a/crates/victory-hle/src/modules/lifecycle.rs +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -151,23 +151,64 @@ pub extern "system" fn CreateWindowExA( /// the title: 3840x2160 on a Series X), which can exceed the host's screen. /// A top-level window larger than the work area is shrunk to fit, keeping /// its proportions, and centred; what it shows is scaled to it (the swap -/// chain stretches). +/// chain stretches). `VICTORY_WINDOW_MAX=WIDTHxHEIGHT` applies a smaller +/// limit without changing the title's render targets. fn fit(parent: HWND, x: i32, y: i32, width: i32, height: i32) -> (i32, i32, i32, i32) { let mut area = RECT::default(); // SAFETY: `area` receives the primary monitor's work area. let known = unsafe { wm::SystemParametersInfoW(wm::SPI_GETWORKAREA, 0, (&raw mut area).cast(), 0) }; - let fitted = fit_into(&area, width, height); + let limit = window_limit(); + let fitted = fit_with_limit(&area, width, height, limit); if !parent.is_null() || known == 0 || fitted == (width, height) { return (x, y, width, height); } - tracing::info!(width, height, to = ?fitted, "title window fitted to the screen"); + tracing::info!(width, height, to = ?fitted, ?limit, "title window fitted to the screen"); let (w, h) = fitted; let left = area.left + (area.right - area.left - w) / 2; let top = area.top + (area.bottom - area.top - h) / 2; (left, top, w, h) } +fn parse_window_limit(value: &str) -> Option<(i32, i32)> { + let (width, height) = value.trim().split_once(['x', 'X'])?; + let (width, height) = (width.trim().parse().ok()?, height.trim().parse().ok()?); + (width > 0 && height > 0).then_some((width, height)) +} + +fn window_limit() -> Option<(i32, i32)> { + static LIMIT: std::sync::OnceLock> = std::sync::OnceLock::new(); + *LIMIT.get_or_init(|| { + let value = std::env::var_os("VICTORY_WINDOW_MAX")?; + let parsed = value.to_str().and_then(parse_window_limit); + if parsed.is_none() { + tracing::warn!( + ?value, + "ignoring invalid VICTORY_WINDOW_MAX; expected positive WIDTHxHEIGHT" + ); + } + parsed + }) +} + +fn fit_with_limit( + area: &RECT, + width: i32, + height: i32, + limit: Option<(i32, i32)>, +) -> (i32, i32) { + let Some((max_width, max_height)) = limit else { + return fit_into(area, width, height); + }; + let bounded = RECT { + left: 0, + top: 0, + right: (area.right - area.left).min(max_width), + bottom: (area.bottom - area.top).min(max_height), + }; + fit_into(&bounded, width, height) +} + /// `width` x `height` scaled down to fit `area`, or unchanged if it fits /// (or is `CW_USEDEFAULT`). fn fit_into(area: &RECT, width: i32, height: i32) -> (i32, i32) { @@ -433,6 +474,63 @@ mod tests { ); } + #[test] + fn configured_window_limit_fits_4k_into_1080p() { + let area = RECT { + left: 100, + top: 50, + right: 2660, + bottom: 1490, + }; + assert_eq!(fit_with_limit(&area, 3840, 2160, Some((1920, 1080))), (1920, 1080)); + assert_eq!(fit_with_limit(&area, 640, 480, Some((1920, 1080))), (640, 480)); + assert_eq!(fit_with_limit(&area, 3840, 2160, None), (2560, 1440)); + } + + #[test] + fn configured_window_limit_still_respects_the_work_area() { + let area = RECT { + left: 0, + top: 0, + right: 1920, + bottom: 1040, + }; + assert_eq!(fit_with_limit(&area, 3840, 2160, Some((2560, 1440))), (1848, 1040)); + assert_eq!( + fit_with_limit(&area, wm::CW_USEDEFAULT, 0, Some((1920, 1080))), + (wm::CW_USEDEFAULT, 0) + ); + } + + #[test] + fn configured_window_limit_preserves_non_widescreen_proportions() { + let area = RECT { + left: 0, + top: 0, + right: 2560, + bottom: 1440, + }; + assert_eq!(fit_with_limit(&area, 1600, 1200, Some((1920, 1080))), (1440, 1080)); + } + + #[test] + fn window_limit_requires_two_positive_dimensions() { + assert_eq!(parse_window_limit("1920x1080"), Some((1920, 1080))); + assert_eq!(parse_window_limit(" 1920 X 1080 "), Some((1920, 1080))); + for bad in [ + "", + "1920", + "0x1080", + "1920x0", + "-1x1080", + "1920x-1", + "1920x1080x2", + "2147483648x1080", + ] { + assert_eq!(parse_window_limit(bad), None, "{bad}"); + } + } + #[test] fn hooked_windows_still_reach_the_title_procedure() { let null = std::ptr::null_mut(); From dc155d2fb9f0789ebd49245ed1979bf921153ce9 Mon Sep 17 00:00:00 2001 From: Tex Date: Tue, 24 Nov 2026 19:13:33 +0100 Subject: [PATCH 277/445] Shaders: fold empty loop latches containing only dead phis (cherry picked from commit be3202de393b71c9385f74b587256b01b48f7f63) --- crates/victory-shader/src/emit/bitcode.rs | 41 ++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index eff0ac0..18e0a31 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -727,7 +727,7 @@ impl Module { let blk = &self.blocks[b]; if let (Some(Term::Br(h)), true, [p]) = ( blk.term, - blk.phis.is_empty() && blk.body.is_empty(), + blk.phis.iter().all(|&i| !live[i as usize]) && blk.body.is_empty(), &preds[b][..], ) && pos[h] < pos[b] && !succs(*p).contains(&h) @@ -1196,6 +1196,45 @@ mod tests { assert_eq!(live, live_by_passes(&m)); } + #[test] + fn empty_latch_with_dead_phis_is_folded() { + // Two identical loops except one has an unread phi in its empty latch; + // both must fold the latch and emit identical bitcode. + let build = |with_dead_phi: bool| { + let mut m = Module::default(); + let i32t = m.int(32); + let void = m.void(); + let fty = m.func_ty(void, vec![i32t]); + let f = m.function("sink", fty, Some(Attr::NoUnwind), false); + let main_ty = m.func_ty(void, vec![]); + m.function("main", main_ty, None, true); + let (entry, head, body, latch, exit) = ( + m.new_block(), + m.new_block(), + m.new_block(), + m.new_block(), + m.new_block(), + ); + let (z, one, ten) = (m.i32(0), m.i32(1), m.i32(10)); + m.terminate(entry, Term::Br(head)); + let i = m.phi(head, i32t); + m.terminate(head, Term::Br(body)); + let next = m.bin(body, Bin::Add, i, one); + let cond = m.cmp(body, pred::IULT, next, ten); + m.terminate(body, Term::CondBr(cond, latch, exit)); + if with_dead_phi { + let dead = m.phi(latch, i32t); + m.set_phi(dead, vec![(next, body)]); + } + m.terminate(latch, Term::Br(head)); + m.set_phi(i, vec![(z, entry), (next, latch)]); + let _ = m.call(exit, f, vec![next]); + m.terminate(exit, Term::Ret); + m.write() + }; + assert_eq!(build(false), build(true)); + } + #[test] fn successors_of_each_terminator() { assert!(successors(None).is_empty()); From 200bde46a6a6405504b0fb65c16a725e0ea476e7 Mon Sep 17 00:00:00 2001 From: Tex Date: Tue, 24 Nov 2026 19:13:33 +0100 Subject: [PATCH 278/445] Shaders: precompute MD5 round constants and avoid per-block Vec in md5_block (cherry picked from commit 711d651ccab7673e5ab4365bd692294e954c845f) --- crates/victory-shader/src/emit/container.rs | 35 ++++++++++++++++----- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index 3c346d9..a244076 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -369,21 +369,40 @@ pub(crate) fn hash(data: &[u8]) -> [u8; 16] { fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) { const S: [u32; 16] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21]; - let x: Vec = block - .as_chunks::<4>() - .0 - .iter() - .map(|c| u32::from_le_bytes(*c)) - .collect(); + const K: [u32; 64] = [ + 0xd76a_a478, 0xe8c7_b756, 0x2420_70db, 0xc1bd_ceee, + 0xf57c_0faf, 0x4787_c62a, 0xa830_4613, 0xfd46_9501, + 0x6980_98d8, 0x8b44_f7af, 0xffff_5bb1, 0x895c_d7be, + 0x6b90_1122, 0xfd98_7193, 0xa679_438e, 0x49b4_0821, + 0xf61e_2562, 0xc040_b340, 0x265e_5a51, 0xe9b6_c7aa, + 0xd62f_105d, 0x0244_1453, 0xd8a1_e681, 0xe7d3_fbc8, + 0x21e1_cde6, 0xc337_07d6, 0xf4d5_0d87, 0x455a_14ed, + 0xa9e3_e905, 0xfcef_a3f8, 0x676f_02d9, 0x8d2a_4c8a, + 0xfffa_3942, 0x8771_f681, 0x6d9d_6122, 0xfde5_380c, + 0xa4be_ea44, 0x4bde_cfa9, 0xf6bb_4b60, 0xbebf_bc70, + 0x289b_7ec6, 0xeaa1_27fa, 0xd4ef_3085, 0x0488_1d05, + 0xd9d4_d039, 0xe6db_99e5, 0x1fa2_7cf8, 0xc4ac_5665, + 0xf429_2244, 0x432a_ff97, 0xab94_23a7, 0xfc93_a039, + 0x655b_59c3, 0x8f0c_cc92, 0xffef_f47d, 0x8584_5dd1, + 0x6fa8_7e4f, 0xfe2c_e6e0, 0xa301_4314, 0x4e08_11a1, + 0xf753_7e82, 0xbd3a_f235, 0x2ad7_d2bb, 0xeb86_d391, + ]; + let x: [u32; 16] = std::array::from_fn(|i| { + u32::from_le_bytes([ + block[4 * i], + block[4 * i + 1], + block[4 * i + 2], + block[4 * i + 3], + ]) + }); let [mut a, mut b, mut c, mut d] = *state; - for i in 0..64 { + for (i, &k) in K.iter().enumerate() { let (f, g) = match i / 16 { 0 => ((b & c) | (!b & d), i), 1 => ((d & b) | (!d & c), (5 * i + 1) % 16), 2 => (b ^ c ^ d, (3 * i + 5) % 16), _ => (c ^ (b | !d), (7 * i) % 16), }; - let k = ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32; let rotated = a .wrapping_add(f) .wrapping_add(k) From 241a70924a4e82a1155f6e49698397b97cbdfa3f Mon Sep 17 00:00:00 2001 From: Calvix2k Date: Tue, 24 Nov 2026 19:39:54 +0100 Subject: [PATCH 279/445] HLE: guard dialog commands before initialization (cherry picked from commit 9ccb83c00a9b0ee5121e4a9b2f6c0ee223630c84) --- crates/victory-hle/src/modules/xgameui.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/victory-hle/src/modules/xgameui.rs b/crates/victory-hle/src/modules/xgameui.rs index 663341b..f93fa1b 100644 --- a/crates/victory-hle/src/modules/xgameui.rs +++ b/crates/victory-hle/src/modules/xgameui.rs @@ -227,7 +227,11 @@ mod dialog { 0 // focus set here } wm::WM_COMMAND => { - let entry = &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) as *mut Entry); + let user_data = wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA); + if user_data == 0 { + return 0; + } + let entry = &mut *(user_data as *mut Entry); match (wparam & 0xffff) as i32 { wm::IDOK => { let mut buffer = vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1]; @@ -246,6 +250,19 @@ mod dialog { } } } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn command_before_init_is_ignored() { + assert_eq!( + procedure(std::ptr::null_mut(), wm::WM_COMMAND, wm::IDOK as WPARAM, 0,), + 0 + ); + } + } } static VTABLE: Methods<20> = Methods([ From 32676e3f79ad1a26cf84291560e851800d870d89 Mon Sep 17 00:00:00 2001 From: Tex Date: Tue, 24 Nov 2026 19:51:08 +0100 Subject: [PATCH 280/445] Loader: guard clwb_loop shortcut against u64 overflow and wraparound (cherry picked from commit 274f6988c9779b0612186c3448123e5e157d56e4) --- crates/victory-loader/src/crash.rs | 67 ++++++++++++++++++++++++++---- 1 file changed, 59 insertions(+), 8 deletions(-) diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index 84684b2..e880300 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -171,16 +171,14 @@ unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { let mut bytes = [0u8; 32]; let n = room.min(bytes.len()); std::ptr::copy_nonoverlapping(code, bytes.as_mut_ptr(), n); - if let Some(pass) = clwb_loop(&bytes[..n]) { + if let Some(pass) = clwb_loop(&bytes[..n]) + && let Some(end) = + clwb_loop_end(*gpr(context, pass.base), *gpr(context, pass.limit)) + { // A whole write-back loop in one exception (see `clwb_loop`). let limit = *gpr(context, pass.limit); - let base = gpr(context, pass.base); - *base = if *base <= limit { - base.wrapping_add(((limit - *base) / 64 + 1) * 64) - } else { - base.wrapping_add(64) - }; - let flags = cmp_flags(*base, limit); + *gpr(context, pass.base) = end; + let flags = cmp_flags(end, limit); context.EFlags = context.EFlags & !CMP_FLAGS | flags; context.Rip += pass.len as u64; return true; @@ -249,6 +247,19 @@ struct ClwbLoop { len: usize, } +/// The `base` value left after a `clwb_loop` finishes without wrapping past +/// `u64::MAX`, or `None` if `add base, 0x40` would overflow or wrap (in which +/// case we fall through to single-instruction `clwb` emulation). +fn clwb_loop_end(base: u64, limit: u64) -> Option { + let step = if base <= limit { + ((limit - base) / 64 + 1).checked_mul(64)? + } else { + 64 + }; + let end = base.checked_add(step)?; + (end > limit).then_some(end) +} + fn clwb_loop(code: &[u8]) -> Option { // clwb [base]: 66 [40|41] 0f ae, ModRM mod 00, reg 6, no SIB or displacement. let (rex, at) = match code.get(1)? { @@ -946,6 +957,46 @@ mod tests { assert_eq!(cmp_flags(0x1000, 0x1000) & 0x40, 0x40); } + #[test] + fn clwb_loop_wrapping_ranges_do_not_overflow_and_fall_back_to_single_clwb() { + assert_eq!(clwb_loop_end(0x1000, 0x1080), Some(0x10c0)); + assert_eq!(clwb_loop_end(0x10c0, 0x1080), Some(0x1100)); + assert_eq!(clwb_loop_end(0, u64::MAX - 10), None); + assert_eq!(clwb_loop_end(u64::MAX - 16, 0x100), None); + assert_eq!(clwb_loop_end(u64::MAX - 63, u64::MAX), None); + + // clwb [rcx]; add rcx, 0x40; cmp rcx, rax; jbe top (13 bytes, clwb is 4 bytes). + let mut bytes = [0xcc_u8; 16]; + bytes[..13].copy_from_slice(&[ + 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40, 0x48, 0x39, 0xc1, 0x76, 0xf3, + ]); + let run = |base: u64, limit: u64| -> (u64, u64) { + let start = bytes.as_ptr() as u64; + // SAFETY: zeroed record/context are valid; `emulate_amd_only` only + // reads `bytes` and updates `context`. + unsafe { + let mut record: EXCEPTION_RECORD = std::mem::zeroed(); + record.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION; + let mut context: CONTEXT = std::mem::zeroed(); + context.Rip = start; + context.Rcx = base; + context.Rax = limit; + let mut pointers = EXCEPTION_POINTERS { + ExceptionRecord: &mut record, + ContextRecord: &mut context, + }; + assert!(emulate_amd_only(&mut pointers)); + (context.Rip - start, context.Rcx) + } + }; + // Normal range completes the whole 13-byte loop in one exception. + assert_eq!(run(0x1000, 0x1080), (13, 0x10c0)); + // Overflowing/wrapping ranges must not panic or skip the loop: emulate + // just the 4-byte `clwb` instruction and let the CPU run add/cmp/jbe. + assert_eq!(run(0, u64::MAX - 10), (4, 0)); + assert_eq!(run(u64::MAX - 16, 0x100), (4, u64::MAX - 16)); + } + #[test] fn clwb_lengths() { assert_eq!(clwb_len(&[0x66, 0x41, 0x0f, 0xae, 0x31]), Some(5)); // clwb [r9] From 8f081313649f5b9fe9db1f267ad0632c5e25c430 Mon Sep 17 00:00:00 2001 From: Vyacheslav Venglovsky Date: Tue, 24 Nov 2026 19:59:26 +0100 Subject: [PATCH 281/445] Formats: test texture layouts against addrlib's own sizes and addresses The layouts follow AMD's addrlib, but the tests only checked them against themselves (every element on its own address) and a few hand-worked offsets. Two tests now pin them to addrlib itself (Mesa src/amd/addrlib at ed09d38, Navi 21 settings): - layouts_match_addrlib: 21 descriptions over every mode Layout::offset addresses (linear, 256 B, 4 KiB and 64 KiB S and D; 1-16 byte elements, block compression, arrays, mip tails, 2D and 3D), each with addrlib's surface size, first tail mip and a hash of the address of every element. - deep_volumes_keep_their_chain_in_each_slabs_tail: a 16x16x64 volume whose chain is all in the tail (addrlib's mipChainInTail), with explicit addresses: each 16-slice slab has its own tail block, and mip 1's 32 slices span two of them. Over a wider sweep (about 20,000 descriptions, every mip count for volumes up to 256 deep) main matches addrlib exactly in size, tail and every address compared. A tail-entry rule that also requires a mip's depth to fit one slab changes 5,456 of 14,780 volume layouts (5,087 grow, by up to 5x) and moves their addresses; both tests fail with it. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit f078008b112343b6e68c8ca72b884073064320c1) --- crates/victory-formats/src/texture.rs | 122 ++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 2f4c25d..dbcf277 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -1183,6 +1183,128 @@ mod tests { assert_eq!(l.mips[0].offset, 8192 + 16384); } + /// A volume deeper than its block keeps its whole chain in the tail when + /// every mip's width and height fit it (addrlib's `mipChainInTail`): each + /// depth slab has its own tail block, holding that slab's slices of + /// every mip. 16x16x64 in 64 KiB `S` blocks of 32x32x16 is four slabs + /// of one block; mip 1's 32 slices span the first two. Addresses from + /// addrlib, as in [`layouts_match_addrlib`]. + #[test] + fn deep_volumes_keep_their_chain_in_each_slabs_tail() { + let l = Layout::new(&Desc { + dimension: Dimension::Tex3d, + depth: 64, + ..desc(16, 16, 4, 4, Swizzle::SW_64KB_S) + }) + .unwrap(); + assert_eq!(l.block, [32, 32, 16]); + assert_eq!((l.first_tail_mip, l.size), (0, 4 * 65536)); + for (mip, x, y, z, address) in [ + (0, 0, 0, 0, 32768), + (0, 0, 0, 15, 42128), + (0, 0, 0, 16, 65536 + 32768), + (0, 15, 15, 63, 3 * 65536 + 49148), + (1, 0, 0, 0, 16384), + (1, 0, 0, 16, 65536 + 16384), + (1, 0, 0, 31, 65536 + 25744), + (2, 0, 0, 0, 4096), + (3, 1, 1, 7, 3740), + ] { + let at = l.offset(mip, x, y, z); + assert_eq!(at, Ok(address), "mip {mip} ({x},{y},{z})"); + } + } + + /// Layouts as AMD's addrlib computes them (Mesa `src/amd/addrlib` at ed09d38, + /// `Addr2ComputeSurfaceInfo` and `Addr2ComputeSurfaceAddrFromCoord`, + /// Navi 21 settings, no pipe-bank XOR): its surface size, its first mip + /// in the tail (`mipChainInTail` is 0; linear has no tail) and an + /// FNV-1a hash of the address of every element (mips in order, then + /// slices, rows and columns; 8 little-endian bytes each). Element sizes + /// 1-16 bytes, block compression, arrays, mip tails and deep volumes, in + /// every mode [`Layout::offset`] addresses. + #[test] + fn layouts_match_addrlib() { + use Dimension::{Tex1d, Tex2d, Tex3d}; + #[rustfmt::skip] + let cases = [ + // mode, dimension, element bytes, texels per element side, + // [width, height, depth or array], mips, + // (size, first tail mip, hash) + (Swizzle::SW_256B_S, Tex2d, 1, 1, [83, 31, 1], 6, + (5120, 6, 0x435e_9cad_96ff_dd81)), + (Swizzle::SW_256B_D, Tex2d, 16, 4, [109, 71, 1], 6, + (13824, 6, 0xbc2b_b84f_c528_7cb3)), + (Swizzle::SW_4KB_S, Tex2d, 8, 1, [250, 175, 1], 8, + (495616, 4, 0x1e87_7240_4dcd_c56e)), + (Swizzle::SW_4KB_S, Tex2d, 16, 1, [70, 70, 3], 4, + (479232, 4, 0xf948_6d1d_511c_d75c)), + (Swizzle::SW_4KB_D, Tex2d, 1, 1, [33, 17, 1], 6, + (8192, 1, 0xaae1_0e3f_15a1_892e)), + (Swizzle::SW_64KB_S, Tex2d, 2, 1, [40, 9, 1], 3, + (65536, 0, 0xf7a3_7fe6_41c2_d565)), + (Swizzle::SW_64KB_S, Tex2d, 4, 1, [100, 60, 6], 7, + (786432, 1, 0xe6b7_50a0_b65e_09a3)), + (Swizzle::SW_64KB_S, Tex2d, 8, 1, [65, 33, 1], 7, + (131072, 1, 0xdf0a_7ddb_9b93_41ee)), + (Swizzle::SW_64KB_D, Tex2d, 16, 4, [256, 256, 1], 9, + (131072, 1, 0xe569_7630_03d8_3e28)), + (Swizzle::SW_64KB_D, Tex2d, 4, 1, [100, 60, 1], 7, + (131072, 1, 0xb1db_1641_adaf_77a6)), + (Swizzle::SW_64KB_D, Tex2d, 1, 1, [255, 129, 2], 8, + (262144, 1, 0xd706_42f5_9a01_5115)), + (Swizzle::LINEAR, Tex2d, 4, 1, [30, 20, 1], 5, + (10240, 5, 0x819a_9c12_81e6_40f2)), + (Swizzle::LINEAR, Tex2d, 2, 1, [17, 9, 3], 5, + (15360, 5, 0xbf1a_74f1_7803_df62)), + (Swizzle::LINEAR, Tex1d, 4, 1, [1000, 1, 1], 10, + (9216, 10, 0xd37e_f9ac_a5de_cab4)), + (Swizzle::SW_4KB_S, Tex3d, 4, 1, [64, 32, 16], 7, + (188416, 3, 0xf06b_d42a_7183_90e6)), + (Swizzle::SW_4KB_S, Tex3d, 4, 1, [4, 4, 16], 5, + (8192, 0, 0xbf87_001b_ad72_d375)), + (Swizzle::SW_4KB_S, Tex3d, 1, 1, [1, 1, 17], 2, + (8192, 0, 0xcdf4_4ee3_33e5_e03d)), + (Swizzle::SW_64KB_S, Tex3d, 4, 1, [16, 16, 64], 4, + (262144, 0, 0x5d1a_a7af_c371_e8e5)), + (Swizzle::SW_64KB_S, Tex3d, 1, 1, [8, 8, 128], 4, + (262144, 0, 0x8fec_f010_6542_6225)), + (Swizzle::SW_64KB_S, Tex3d, 16, 1, [33, 17, 40], 6, + (1966080, 3, 0xec9c_fd44_b89c_2fd5)), + (Swizzle::LINEAR, Tex3d, 4, 1, [9, 7, 5], 3, + (16640, 3, 0x6d5b_351d_4a3d_7b5a)), + ]; + for (swizzle, dimension, element_bytes, block, extent, mips, expected) in cases { + let [width, height, depth] = extent; + let d = Desc { + dimension, + width, + height, + depth, + mips, + element_bytes, + block, + samples: 1, + swizzle, + }; + let l = Layout::new(&d).unwrap(); + let mut h = 0xcbf2_9ce4_8422_2325u64; + for (mip, m) in (0..).zip(&l.mips) { + let slices = if dimension == Tex3d { m.depth } else { depth }; + for z in 0..slices { + for y in 0..m.height { + for x in 0..m.width { + for byte in l.offset(mip, x, y, z).unwrap().to_le_bytes() { + h = (h ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3); + } + } + } + } + } + assert_eq!((l.size, l.first_tail_mip, h), expected, "{d:?}"); + } + } + #[test] fn depth_stencil_is_two_planes() { let t = Texture::new(&TextureDesc { From 903b568edc8586a81092a746b4a535a2d4cd440c Mon Sep 17 00:00:00 2001 From: BastienRdz <58186763+BastienRodz@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:08:51 +0000 Subject: [PATCH 282/445] GPU: fences answer for ID3D12Fence1 as documented fence.rs already implements ID3D12Fence1::GetCreationFlags at slot 11 (0x58), but FENCE_IIDS only listed ID3D12Fence and PAGEABLE_IIDS, so CreateFence and QueryInterface rejected ID3D12Fence1 with E_NOINTERFACE. Add ID3D12Fence1 (433685fe-e22b-4ca0-a8db-b5b4f4dd0e4a) to FENCE_IIDS and add a unit test covering creation, QueryInterface, and GetCreationFlags. Co-Authored-By: Gemini 4 Neon Co-Authored-By: Claude Opus 5.5 (cherry picked from commit bbdc3ca7249948b7624ba65f4282615caef895b8) --- crates/victory-gpu/src/fence.rs | 42 ++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 98daa89..b066fd6 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -9,13 +9,20 @@ use std::sync::atomic::{AtomicU64, Ordering}; use crate::object::{self, E_NOTIMPL, FENCE, HRESULT, Iid, Object, S_OK, Table, This, guid}; use crate::resource::PAGEABLE_IIDS; -pub(crate) const FENCE_IIDS: [Iid; 4] = [ +pub(crate) const FENCE_IIDS: [Iid; 5] = [ guid( 0x0a753dcf, 0xc4d8, 0x4b91, [0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76], ), + // ID3D12Fence1. + guid( + 0x433685fe, + 0xe22b, + 0x4ca0, + [0xa8, 0xdb, 0xb5, 0xb4, 0xf4, 0xdd, 0x0e, 0x4a], + ), PAGEABLE_IIDS[0], PAGEABLE_IIDS[1], PAGEABLE_IIDS[2], @@ -190,4 +197,37 @@ mod tests { unsafe { CloseHandle(event) }; assert_eq!(slot:: u32>(f, 0x10)(f), 0); } + + #[test] + fn fence1_interface_is_created_and_queried() { + const FENCE1_IID: Iid = guid( + 0x433685fe, + 0xe22b, + 0x4ca0, + [0xa8, 0xdb, 0xb5, 0xb4, 0xf4, 0xdd, 0x0e, 0x4a], + ); + type Query = extern "system" fn(This, *const Iid, *mut This) -> HRESULT; + type Flags = extern "system" fn(This) -> u32; + type Release = extern "system" fn(This) -> u32; + + // Direct creation as ID3D12Fence1, and GetCreationFlags at slot 0x58. + let mut f1 = std::ptr::null(); + assert_eq!(create(std::ptr::null(), 3, 0x5, &FENCE1_IID, &mut f1), S_OK); + assert!(!f1.is_null()); + assert_eq!(slot::(f1, 0x58)(f1), 0x5); + assert_eq!(slot::(f1, 0x10)(f1), 0); + + // QueryInterface from ID3D12Fence to ID3D12Fence1 returns the same object. + let mut f = std::ptr::null(); + assert_eq!( + create(std::ptr::null(), 0, 0x2, &FENCE_IIDS[0], &mut f), + S_OK + ); + let mut queried = std::ptr::null(); + assert_eq!(slot::(f, 0x00)(f, &FENCE1_IID, &mut queried), S_OK); + assert_eq!(queried, f); + assert_eq!(slot::(queried, 0x58)(queried), 0x2); + assert_eq!(slot::(queried, 0x10)(queried), 1); + assert_eq!(slot::(f, 0x10)(f), 0); + } } From 9c63a43431cdcc7cc537c7df7eaf6cff879830c2 Mon Sep 17 00:00:00 2001 From: AgneyaK <82705373+AgneyaK@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:44:39 -0800 Subject: [PATCH 283/445] run: stop with a clear message when the title's own DLLs are missing A package copied without the DLLs that ship beside the executable leaves every import from them unbound, and the title stops at its first call into one: Grand Theft Auto VI 1.0.2.1 at +0x2237178 during System Init (#930, #1553, #8), with nothing saying why. After mapping the title DLLs, name the main image's static imports that must come from the title's folder (neither the host nor our runtime serves them) but were not mapped from it. Print them; when executing with the default trap policy, stop before running title code. With `--unimplemented zero` the title still runs (stubs were asked for). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit e9cb14ad3ea2f7a3ec051d9f9691684d7e9037ae) --- apps/victory/src/run.rs | 81 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 822a92b..454bdab 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -110,6 +110,32 @@ pub fn run( println!("title dll {name} at {:#x}", dll.base()); victory_hle::runtime::set_image_path(dll.base(), &title_dir.join(name)); } + let imported: Vec<&str> = image + .info() + .imports + .iter() + .map(|m| m.dll.as_str()) + .collect(); + let mapped: Vec<&str> = dlls.iter().map(|(name, _)| name.as_str()).collect(); + let absent = absent_title_dlls(&imported, &mapped, &wanted); + if !absent.is_empty() { + let message = format!( + "{} not in {}, and neither the host nor VIctory provides {}: the package is \ + incomplete; copy every file of the package next to the executable", + absent.join(", "), + title_dir.display(), + if absent.len() == 1 { "it" } else { "them" }, + ); + println!("missing dlls {message}"); + // None of their imports can be bound, so the title stops at its first + // call into one (Grand Theft Auto VI 1.0.2.1 at +0x2237178 during + // System Init, #930) with nothing saying why. Stubs only if asked for. + if execute && matches!(unimplemented, Unimplemented::Trap) { + anyhow::bail!( + "the title's own DLLs are missing: {message} (`--unimplemented zero` runs it anyway)" + ); + } + } let policy = match unimplemented { Unimplemented::Trap => UnimplementedPolicy::Trap, @@ -225,6 +251,25 @@ fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool { !host.allows(dll) && !victory_hle::registry().iter().any(|m| m.serves(dll)) } +/// The DLLs among `imported` (the main image's static imports) that must +/// come from the title's folder (`wanted`) but were not mapped from it: +/// none of their imports can be bound. Each named once, case ignored. +#[cfg(any(windows, test))] +fn absent_title_dlls( + imported: &[&str], + mapped: &[&str], + wanted: &dyn Fn(&str) -> bool, +) -> Vec { + let mut absent: Vec = Vec::new(); + for &dll in imported { + let known = |list: &[&str]| list.iter().any(|m| m.eq_ignore_ascii_case(dll)); + if wanted(dll) && !known(mapped) && !absent.iter().any(|a| a.eq_ignore_ascii_case(dll)) { + absent.push(dll.to_owned()); + } + } + absent +} + /// Title DLLs the title loads itself (`LoadLibrary`) that nothing imports, /// e.g. The title's upscaler behind its FidelityFX loader. #[cfg(windows)] @@ -349,6 +394,42 @@ impl LoaderLock { } } +#[cfg(test)] +mod absent_tests { + use super::absent_title_dlls; + + #[test] + fn title_dlls_missing_from_the_folder_are_named_once() { + // The host provides kernel32, our runtime d3d12_xs; the rest are the + // title's own (#930: the four DLLs beside the executable missing). + let wanted = |dll: &str| { + !["KERNEL32.dll", "d3d12_xs.dll"] + .iter() + .any(|h| h.eq_ignore_ascii_case(dll)) + }; + let imported = [ + "KERNEL32.dll", + "d3d12_xs.dll", + "XboxBvhBuilder.dll", + "MSVCP140.dll", + "Bink2Scarlett.dll", + "xboxbvhbuilder.dll", + ]; + let mapped = ["msvcp140.dll"]; + assert_eq!( + absent_title_dlls(&imported, &mapped, &wanted), + ["XboxBvhBuilder.dll", "Bink2Scarlett.dll"] + ); + } + + #[test] + fn a_complete_package_has_nothing_absent() { + let wanted = |dll: &str| dll.starts_with("Title"); + assert!(absent_title_dlls(&["Title.dll", "Host.dll"], &["TITLE.DLL"], &wanted).is_empty()); + assert!(absent_title_dlls(&[], &[], &wanted).is_empty()); + } +} + #[cfg(all(test, windows))] mod tests { use std::sync::{Arc, Mutex}; From a5c98fe0725f6fc292b41c519ca8941f77092d48 Mon Sep 17 00:00:00 2001 From: HailLucifer666 Date: Wed, 25 Nov 2026 02:04:30 +0530 Subject: [PATCH 284/445] GPU: serialize pipeline library atomic writes with unique temp files save() releases LAST and library locks before calling write_atomically(), which always wrote to the same fixed host-pipelines.tmp path. Concurrent worker saves and shutdown save(true) can truncate or unlink each other's temp file on Windows. - Serialize write_atomically() with a mutex and unique per-call temp filename (.tmp--), cleaning up the temp file on rename failure. - Add a 4-thread concurrent write_atomically stress test. (cherry picked from commit be824d9d218320c71f2623ed4b14045210785db5) --- crates/victory-gpu/src/pipeline/library.rs | 42 +++++++++++++++++++--- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 9452537..1c04848 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -673,11 +673,22 @@ fn replace_library(dir: &std::path::Path, tmp: &std::path::Path) -> std::io::Res } /// Writes `bytes` to a temporary file beside `path`, then renames it over -/// `path`: a reader never sees a part. +/// `path`: a reader never sees a part. Serialised so concurrent worker and +/// shutdown saves do not race on the same staging file or target rename. fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { - let tmp = path.with_extension("tmp"); - std::fs::write(&tmp, bytes)?; - std::fs::rename(&tmp, path) + use std::sync::atomic::AtomicU64; + static WRITING: Mutex<()> = Mutex::new(()); + static NEXT: AtomicU64 = AtomicU64::new(0); + let _guard = WRITING.lock().unwrap_or_else(|e| e.into_inner()); + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let mut name = path.file_name().unwrap_or_default().to_os_string(); + name.push(format!(".tmp-{}-{n}", std::process::id())); + let tmp = path.with_file_name(name); + let res = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)); + if res.is_err() { + let _ = std::fs::remove_file(&tmp); + } + res } /// Title pipeline keys requested by draws or dispatches (this run and the last). @@ -848,4 +859,27 @@ mod tests { assert!(bytes == &expected[..], "page {page} of the replaced library no longer reads as the old file"); } } + + #[test] + fn concurrent_write_atomically_never_fails_or_truncates() { + let dir = tempfile::tempdir().unwrap(); + let target = dir.path().join("host-pipelines.bin"); + let threads: Vec<_> = (0..4) + .map(|t| { + let target = target.clone(); + std::thread::spawn(move || { + let payload = vec![b'a' + t as u8; 4096]; + for _ in 0..30 { + write_atomically(&target, &payload).unwrap(); + } + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + let final_bytes = std::fs::read(&target).unwrap(); + assert_eq!(final_bytes.len(), 4096); + assert!(final_bytes.iter().all(|&b| b == final_bytes[0])); + } } From 5f1a45bdc2fba3ed59f73b027c034c009a75c8ed Mon Sep 17 00:00:00 2001 From: imjustprism <69634294+imjustprism@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:15:51 +0100 Subject: [PATCH 285/445] flush a kept save blob that had to be copied (cherry picked from commit eb7cc2d43711e806bbd8578d4ef75bde30326c20) --- crates/victory-hle/src/modules/xgamesave.rs | 36 +++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs index 560b6a6..f7310c5 100644 --- a/crates/victory-hle/src/modules/xgamesave.rs +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -256,8 +256,9 @@ fn commit( match source { Source::Data(data) => write(path, data)?, // Files are never changed in place, so sharing one is safe. - Source::Kept(from) => std::fs::hard_link(from, &path) - .or_else(|_| std::fs::copy(from, &path).map(drop))?, + Source::Kept(from) => { + std::fs::hard_link(from, &path).or_else(|_| write(path, &std::fs::read(from)?))? + } } step(); } @@ -1069,6 +1070,37 @@ mod tests { } } + /// A kept blob that cannot be hard-linked (NTFS allows 1024 links to a + /// file) is copied into the new version with its exact bytes. + #[cfg(windows)] + #[test] + fn a_kept_blob_past_the_link_limit_is_copied() { + let dir = tempfile::tempdir().unwrap(); + let links = tempfile::tempdir().unwrap(); + let root = dir.path(); + assert_eq!( + update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), + S_OK + ); + const NTFS: &str = "the temp folder must be on NTFS, which allows 1024 links to a file"; + let old_b = container_dir(root, "Slot").join("v1").join("1"); + for i in 0..1023 { + std::fs::hard_link(&old_b, links.path().join(i.to_string())).expect(NTFS); + } + let full = std::fs::hard_link(&old_b, links.path().join("full")).expect_err(NTFS); + assert_eq!(full.kind(), std::io::ErrorKind::TooManyLinks, "{NTFS}"); + + assert_eq!(update(root, "two", &[("a", Some("new a"))]), S_OK); + + let new = ( + "two".into(), + vec![("a".into(), "new a".into()), ("b".into(), "old b".into())], + ); + assert_eq!(state(root), Some(new)); + assert!(!old_b.exists()); + assert_eq!(std::fs::read(links.path().join("0")).unwrap(), b"old b"); + } + #[test] fn names_are_exact() { for name in ["Save_1", "slot/2", "a.b c%", "\u{e9}t\u{e9}"] { From 9820bdc45e9eb1d50f8a1f7419850953d8fa54e4 Mon Sep 17 00:00:00 2001 From: Vax Date: Tue, 24 Nov 2026 08:55:13 -0500 Subject: [PATCH 286/445] HLE: show title windows through a stand-in that always reads its messages A title makes its window on one of its own threads and reads its messages only when that thread reaches its PeekMessage loop. In slow frames and loads that is seconds apart, so the system shows the busy cursor over the window and a click turns it into a "Not responding" ghost. A top-level title window is now made message-only (it can never be shown), and a stand-in window with the title's text, style, icon and fitted size is made on a thread of ours that does nothing but pump its messages. The title's ShowWindow shows the stand-in, its window text follows, closing the stand-in suspends and ends the title as before, the keyboard window menu is still refused, and the stand-in goes when the title's window does. Frames are presented to the process's visible window, now the stand-in; input is unaffected, since titles read it through GameInput, not window messages. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 9145d9d3dabb0d5f8263b4203a82586710929d90) --- crates/victory-hle/Cargo.toml | 1 + crates/victory-hle/src/modules/lifecycle.rs | 328 +++++++++++++++++++- 2 files changed, 322 insertions(+), 7 deletions(-) diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index d91f14f..6d86b03 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -20,6 +20,7 @@ tracing.workspace = true windows-sys = { workspace = true, features = [ "Win32_Foundation", "Win32_Globalization", + "Win32_Graphics_Gdi", "Win32_Media", "Win32_Security", "Win32_Security_Cryptography", diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs index 09c6baa..448c421 100644 --- a/crates/victory-hle/src/modules/lifecycle.rs +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -96,6 +96,20 @@ pub extern "system" fn UnregisterAppConstrainedChangeNotification(registration: /// The window procedure a title window had before ours. const TITLE_PROC: PCWSTR = w!("victory.wndproc"); +/// The stand-in window shown for a title window (a property of the title's). +const STAND_IN: PCWSTR = w!("victory.standin"); + +// The window the player sees is never the title's. A title makes its window +// on one of its own threads and reads its messages only when that thread +// gets round to it, which in a slow frame or a load is seconds apart; the +// system then shows the busy cursor over the window, and a click turns it +// into a "Not responding" ghost. So a top-level title window is made +// message-only (never shown), and a stand-in with the title's text, style +// and (fitted) size is shown in its place, owned by a thread of ours that +// does nothing but read its messages. The title loses nothing: its input +// comes from GameInput (polled, not window messages), and frames are +// presented to the visible window of the process, the stand-in. + pub extern "system" fn CreateWindowExW( ex_style: u32, class: PCWSTR, @@ -110,14 +124,29 @@ pub extern "system" fn CreateWindowExW( instance: HINSTANCE, param: *const c_void, ) -> HWND { - let (x, y, width, height) = fit(parent, x, y, width, height); - // SAFETY: the title's own arguments, forwarded (the size fitted). + let top = parent.is_null(); + // SAFETY: the title's own arguments, forwarded (a top-level window + // made message-only). let hwnd = unsafe { wm::CreateWindowExW( - ex_style, class, name, style, x, y, width, height, parent, menu, instance, param, + ex_style, + class, + name, + style, + x, + y, + width, + height, + if top { wm::HWND_MESSAGE } else { parent }, + menu, + instance, + param, ) }; hook(hwnd); + if top { + stand_in(hwnd, ex_style, style, x, y, width, height); + } hwnd } @@ -136,14 +165,29 @@ pub extern "system" fn CreateWindowExA( instance: HINSTANCE, param: *const c_void, ) -> HWND { - let (x, y, width, height) = fit(parent, x, y, width, height); - // SAFETY: the title's own arguments, forwarded (the size fitted). + let top = parent.is_null(); + // SAFETY: the title's own arguments, forwarded (a top-level window + // made message-only). let hwnd = unsafe { wm::CreateWindowExA( - ex_style, class, name, style, x, y, width, height, parent, menu, instance, param, + ex_style, + class, + name, + style, + x, + y, + width, + height, + if top { wm::HWND_MESSAGE } else { parent }, + menu, + instance, + param, ) }; hook(hwnd); + if top { + stand_in(hwnd, ex_style, style, x, y, width, height); + } hwnd } @@ -226,6 +270,149 @@ fn fit_into(area: &RECT, width: i32, height: i32) -> (i32, i32) { ) } +/// Shows a stand-in for the top-level title window `title` (see +/// [`STAND_IN`]); `ShowWindow` on `title` then shows or hides the stand-in. +fn stand_in(title: HWND, ex_style: u32, style: u32, x: i32, y: i32, width: i32, height: i32) { + if title.is_null() { + return; + } + let (x, y, width, height) = fit(std::ptr::null_mut(), x, y, width, height); + let mut text = vec![0u16; 512]; + // SAFETY: a window this thread just created; the buffer holds 512 + // characters. Its icon, if its class has one. + let (icon, text) = unsafe { + let n = wm::GetWindowTextW(title, text.as_mut_ptr(), text.len() as i32); + text.truncate(n.max(0) as usize); + text.push(0); + (wm::GetClassLongPtrW(title, wm::GCLP_HICON), text) + }; + let (sender, receiver) = std::sync::mpsc::channel(); + let spawned = std::thread::Builder::new() + .name("victory-window".into()) + .spawn(move || { + let window = make_stand_in(&text, ex_style, style, (x, y, width, height), icon); + let _ = sender.send(window as usize); + if !window.is_null() { + pump(); + } + }); + let window = match spawned { + Ok(_) => receiver.recv().unwrap_or(0) as HWND, + Err(_) => std::ptr::null_mut(), + }; + if window.is_null() { + tracing::warn!("no stand-in window; the title's own window is not shown"); + return; + } + // SAFETY: the title's window, on the thread that made it. + unsafe { wm::SetPropW(title, STAND_IN, window) }; +} + +/// The stand-in window for `stand_in`, on the calling thread. +fn make_stand_in( + text: &[u16], + ex_style: u32, + style: u32, + (x, y, width, height): (i32, i32, i32, i32), + icon: usize, +) -> HWND { + use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; + const CLASS: PCWSTR = w!("VIctory.title"); + // SAFETY: registers our class (again is harmless) and creates a window + // of it; `text` is NUL-terminated. + unsafe { + let instance = GetModuleHandleW(std::ptr::null()); + let class = wm::WNDCLASSEXW { + cbSize: size_of::() as u32, + lpfnWndProc: Some(stand_in_proc), + hInstance: instance, + hCursor: wm::LoadCursorW(std::ptr::null_mut(), wm::IDC_ARROW), + lpszClassName: CLASS, + ..std::mem::zeroed() + }; + wm::RegisterClassExW(&class); + let window = wm::CreateWindowExW( + ex_style, + CLASS, + text.as_ptr(), + style, + x, + y, + width, + height, + std::ptr::null_mut(), + std::ptr::null_mut(), + instance, + std::ptr::null(), + ); + if !window.is_null() && icon != 0 { + for kind in [wm::ICON_BIG, wm::ICON_SMALL] { + wm::SendMessageW(window, wm::WM_SETICON, kind as usize, icon as isize); + } + } + window + } +} + +/// Destroys a stand-in (posted when the title's window goes). +const DESTROY_STAND_IN: u32 = wm::WM_APP + 0x7649; + +extern "system" fn stand_in_proc( + hwnd: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, +) -> LRESULT { + match message { + // A user close (close button, Alt+F4, window or taskbar menu). + wm::WM_CLOSE => { + end_title("window closed", Box::new(|| {})); + return 0; + } + // No window menu from the keyboard (see `window_proc`): here it + // would stop only this thread, but it takes keys the title wants. + wm::WM_SYSCOMMAND if wparam & 0xFFF0 == wm::SC_KEYMENU as usize => return 0, + DESTROY_STAND_IN => { + // SAFETY: our window, on its thread. + unsafe { wm::DestroyWindow(hwnd) }; + return 0; + } + // SAFETY: ends `pump`, the loop of this window's thread. + wm::WM_DESTROY => unsafe { wm::PostQuitMessage(0) }, + _ => {} + } + // SAFETY: the default handling for our window. + unsafe { wm::DefWindowProcW(hwnd, message, wparam, lparam) } +} + +/// The message loop of a stand-in's thread, until its window is destroyed. +fn pump() { + // SAFETY: the standard message loop of this thread's window. + unsafe { + let mut message: wm::MSG = std::mem::zeroed(); + while wm::GetMessageW(&mut message, std::ptr::null_mut(), 0, 0) > 0 { + wm::TranslateMessage(&message); + wm::DispatchMessageW(&message); + } + } +} + +/// The stand-in shown for `hwnd`, or null. +fn stand_in_of(hwnd: HWND) -> HWND { + // SAFETY: a plain query; another window gives null. + unsafe { wm::GetPropW(hwnd, STAND_IN) } +} + +/// A title shows its window: shows the stand-in instead. Returns whether it +/// was visible before, as `ShowWindow` does. +pub extern "system" fn ShowWindow(hwnd: HWND, command: i32) -> i32 { + let window = stand_in_of(hwnd); + let target = if window.is_null() { hwnd } else { window }; + // SAFETY: the title's window, or our stand-in for it, whose thread + // always reads its messages, so this never waits long. + unsafe { wm::ShowWindow(target, command) } +} + /// Puts our procedure in front of the title's. fn hook(hwnd: HWND) { if hwnd.is_null() { @@ -264,11 +451,30 @@ extern "system" fn window_proc( // SAFETY: the procedure `hook` stored, called the way the system would. unsafe { let title = wm::GetPropW(hwnd, TITLE_PROC); + let window = stand_in_of(hwnd); if message == wm::WM_NCDESTROY { wm::RemovePropW(hwnd, TITLE_PROC); + if !window.is_null() { + wm::RemovePropW(hwnd, STAND_IN); + wm::PostMessageW(window, DESTROY_STAND_IN, 0, 0); + } } let title = std::mem::transmute::<*mut c_void, wm::WNDPROC>(title); - wm::CallWindowProcW(title, hwnd, message, wparam, lparam) + let result = wm::CallWindowProcW(title, hwnd, message, wparam, lparam); + // The stand-in shows the title's text. Its thread never waits for + // the title's, so this cannot deadlock. + if message == wm::WM_SETTEXT && !window.is_null() { + wm::SendMessageTimeoutW( + window, + wm::WM_SETTEXT, + 0, + lparam, + wm::SMTO_ABORTIFHUNG, + 1000, + std::ptr::null_mut(), + ); + } + result } } @@ -398,6 +604,7 @@ pub(crate) fn module() -> HleModule { hle_export!(UnregisterAppConstrainedChangeNotification), hle_export!(CreateWindowExW), hle_export!(CreateWindowExA), + hle_export!(ShowWindow), ], } } @@ -560,6 +767,113 @@ mod tests { } } + /// Whether `hwnd`'s thread answers a message within `ms`. + fn answers(hwnd: HWND, ms: u32) -> bool { + let mut result = 0; + // SAFETY: a plain message with a timeout. + unsafe { + wm::SendMessageTimeoutW(hwnd, wm::WM_NULL, 0, 0, wm::SMTO_NORMAL, ms, &mut result) != 0 + } + } + + fn thread_of(hwnd: HWND) -> u32 { + // SAFETY: a plain query. + unsafe { wm::GetWindowThreadProcessId(hwnd, std::ptr::null_mut()) } + } + + #[test] + fn a_title_window_is_shown_through_a_stand_in_that_always_answers() { + // A "title thread" makes its window and then stops reading messages + // for a while, as a title does in a slow frame or a load. + let (made, window) = std::sync::mpsc::channel(); + let (done, finish) = std::sync::mpsc::channel::<()>(); + let title = std::thread::spawn(move || { + let null = std::ptr::null_mut(); + let hwnd = CreateWindowExW( + 0, + w!("STATIC"), + w!("stand-in"), + 0, + 0, + 0, + 10, + 10, + null, + null, + null, + std::ptr::null(), + ); + made.send(hwnd as usize).unwrap(); + let _ = finish.recv(); + // SAFETY: this thread's window. + unsafe { wm::DestroyWindow(hwnd) }; + }); + let hwnd = window.recv().unwrap() as HWND; + assert!(!hwnd.is_null()); + let stand_in = stand_in_of(hwnd); + assert!(!stand_in.is_null()); + // SAFETY: plain queries of the two windows. + unsafe { + // The title's window is message-only: it can never be shown. + assert_ne!(wm::GetAncestor(hwnd, wm::GA_PARENT), wm::GetDesktopWindow()); + assert_eq!( + wm::GetAncestor(stand_in, wm::GA_PARENT), + wm::GetDesktopWindow() + ); + assert_eq!(wm::IsWindowVisible(hwnd), 0); + let mut text = [0u16; 16]; + let n = wm::GetWindowTextW(stand_in, text.as_mut_ptr(), 16); + assert_eq!(String::from_utf16_lossy(&text[..n as usize]), "stand-in"); + } + assert_ne!(thread_of(stand_in), thread_of(hwnd)); + assert!(!answers(hwnd, 200), "the title's thread is not reading"); + assert!(answers(stand_in, 1000), "the stand-in's thread always is"); + done.send(()).unwrap(); + title.join().unwrap(); + // The stand-in goes with the title's window. + let gone = (0..100).any(|_| { + std::thread::sleep(Duration::from_millis(10)); + // SAFETY: a plain query; a destroyed handle gives false. + unsafe { wm::IsWindow(stand_in) == 0 } + }); + assert!(gone); + } + + #[test] + fn showing_a_title_window_shows_its_stand_in() { + let null = std::ptr::null_mut(); + let hwnd = CreateWindowExW( + 0, + w!("STATIC"), + w!("show"), + wm::WS_OVERLAPPEDWINDOW, + 0, + 0, + 10, + 10, + null, + null, + null, + std::ptr::null(), + ); + let stand_in = stand_in_of(hwnd); + assert!(!stand_in.is_null()); + // SAFETY: our windows. Minimised and not activated, so the test + // takes no focus from anything. + unsafe { + assert_eq!(ShowWindow(hwnd, wm::SW_SHOWMINNOACTIVE), 0); + assert_ne!(wm::IsWindowVisible(stand_in), 0); + assert_ne!(wm::IsIconic(stand_in), 0); + assert_eq!(wm::IsWindowVisible(hwnd), 0); + // The title's text follows it to the stand-in. + wm::SetWindowTextW(hwnd, w!("renamed")); + let mut text = [0u16; 16]; + let n = wm::GetWindowTextW(stand_in, text.as_mut_ptr(), 16); + assert_eq!(String::from_utf16_lossy(&text[..n as usize]), "renamed"); + wm::DestroyWindow(hwnd); + } + } + thread_local! { /// The system commands `recording` received, low four bits cleared. static COMMANDS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; From f4d1863f255f3e91470fb691715e901b208ba460 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=99=E4=BC=8A=E8=8E=89=E9=9B=85=E8=A1=A5=E9=AD=94?= <98532177+geiyiliyabumo@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:06:44 +0800 Subject: [PATCH 287/445] gpu(list): log initial pipeline bound on reset/reset_x for parity with create_list (cherry picked from commit 8d3a025df199e6e26ccb404d4cf0f172fdde8b1c) --- crates/victory-gpu/src/list.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 5a9680e..5b04f54 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -652,8 +652,9 @@ extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT host.reset(); state.reset(pipeline); }); + crate::pipeline::bound(pipeline); #[cfg(not(windows))] - let _ = (this, pipeline); + let _ = this; S_OK } From 3f0055e213e031eaf6f99d9aeb504f6b3928040a Mon Sep 17 00:00:00 2001 From: Marvis Date: Tue, 24 Nov 2026 22:36:16 +0100 Subject: [PATCH 288/445] Diagnostics: VICTORY_POKE writes title bytes twice a second A title that ends itself when its main loop has not ticked for a while runs on through slower frames. Co-Authored-By: Claude Fable 5.2 (cherry picked from commit 532cb7cdfee02e6139a683f79ee4c9b4a92828a4) --- README.md | 1 + apps/victory/src/run.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/README.md b/README.md index 2fe02b7..e60fb02 100644 --- a/README.md +++ b/README.md @@ -305,6 +305,7 @@ The on/off switches below (`...=1`) are off when unset or set to `0`. | `VICTORY_LOG==debug,...` | debug and trace output | | `VICTORY_STACKS=20,60` | every thread's stack at those seconds | | `VICTORY_WATCH=,...` | logs a title u32 when it changes | +| `VICTORY_POKE=:,...` | writes a title byte twice a second (a hang watchdog's tick, say) | | `VICTORY_KEYS=30:Enter,35:X` | presses keys at those seconds, focus or not | | `VICTORY_CRASH_SAVE=:,...` | saves title memory to the cache folder on a crash | | `VICTORY_CAPTURE=` | saves presented frames (powers of two, or `VICTORY_CAPTURE_FRAMES=`) | diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 454bdab..3cc3b12 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -198,6 +198,7 @@ fn diagnostics(image: &victory_loader::LoadedImage, cfg: &victory_core::Config) victory_loader::dump_stacks_on_schedule(); victory_hle::modules::audio::capture::start(); watch(image.base(), image.info().size_of_image as usize); + poke(image.base(), image.info().size_of_image as usize); // Debugging aid: `VICTORY_CRASH_SAVE=:,...` (hex) writes those // title ranges to `crash-.bin` in the cache dir on a crash. let size = image.info().size_of_image as usize; @@ -245,6 +246,34 @@ fn watch(base: usize, size: usize) { }); } +/// Debugging aid: `VICTORY_POKE=:,...` (hex) writes the byte at +/// each title+rva twice a second. A title that ends itself when its main +/// loop has not ticked for a while (Grand Theft Auto VI: 30 s) runs on +/// through slower frames with its tick flag poked. The address must be +/// writable title data. +#[cfg(all(windows, feature = "diagnostics"))] +fn poke(base: usize, size: usize) { + let Ok(list) = std::env::var("VICTORY_POKE") else { + return; + }; + let hex = |s: &str| usize::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok(); + let pokes: Vec<(usize, u8)> = list + .split(',') + .filter_map(|p| p.split_once(':')) + .filter_map(|(rva, byte)| Some((hex(rva)?, u8::try_from(hex(byte)?).ok()?))) + .filter(|&(rva, _)| rva < size) + .collect(); + std::thread::spawn(move || { + loop { + for &(rva, byte) in &pokes { + // SAFETY: a byte inside the mapped image, checked above. + unsafe { ((base + rva) as *mut u8).write_volatile(byte) }; + } + std::thread::sleep(std::time::Duration::from_millis(500)); + } + }); +} + /// DLLs the host or our runtime provide are never taken from the title. #[cfg(windows)] fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool { From 137bdb5567efaaa640283349e2297ba2ec67e95b Mon Sep 17 00:00:00 2001 From: Marvis Date: Tue, 24 Nov 2026 22:36:23 +0100 Subject: [PATCH 289/445] README: status of 2026-11-24 Co-Authored-By: Claude Fable 5.2 (cherry picked from commit 70564ae08c82d43df5fad97b08d34628b07b1d9d) --- README.md | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index e60fb02..fc6022e 100644 --- a/README.md +++ b/README.md @@ -163,13 +163,13 @@ the user supplies. The title's x86-64 code runs unchanged inside our process; VIctory supplies the platform underneath it and converts the title's data, ahead of time where -it can and on first use where it must (shaders). See -[docs/architecture.md](docs/architecture.md). +it can (shaders and pipelines too, see Getting started) and on first use +otherwise. See [docs/architecture.md](docs/architecture.md). -## Status (2026-11-23) +## Status (2026-11-24) -**Not playable yet.** The title boots, runs its menus at its own 30 fps and -loads the world, where rendering fails. +**Not playable yet.** The title boots, runs its menus at its own 30 fps, +loads the world and shows it: slowly, and with rendering defects. | Stage | State | |-------|-------| @@ -177,14 +177,16 @@ loads the world, where rendering fails. | Intro video with sound | works | | Start screen, profile and saves | works | | Loading into the world (about 50 s) | works | -| The world (first mission's intro) | reached and runs with indirect draws; its title card renders, the scene after it is still dark; 0.5-1.8 s per frame | +| The world (first mission's intro) | drawn and shown: streets, buildings, vehicles, characters, the title card and credits; 1-2 s per frame. Surfaces are unlit, a band of distant geometry is missing, characters come out broken in some shots | Tested on one machine: Windows 11, AMD RX 6700 XT. -> **Warning.** Entering the world on a real GPU can currently hang it, and -> Windows then resets the display driver (every monitor goes black for a -> moment). To look further, use a diagnostics build with -> `VICTORY_D3D12_WARP=1`, which renders on the software adapter. +> **Warning.** Entering the world on a real GPU has hung it in earlier +> builds, and Windows then resets the display driver (every monitor goes +> black for a moment). The latest runs did not, but it is not ruled out; a +> run can also end on a GPU fault (`crashes.log`). A diagnostics build with +> `VICTORY_D3D12_WARP=1` renders on the software adapter instead (too slow +> to reach the world in minutes). What each part does today and what it still needs: @@ -197,8 +199,8 @@ What each part does today and what it still needs: | Input | XInput pads, keyboard, keyboard stand-in pad | Trigger rumble | | Audio | Menu, video and loading sound; XMA voices and Opus streams decode | Reverb is silent; Opus results unverified against the title | | GPU: menus | Draws, compute and presentation on host D3D12; only changed title memory is copied | Frame pacing drifts on one screen in release builds | -| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped), pipelines made by worker threads and kept on disk | Most of the scene is still missing (untranslated shaders drop draws); frames take seconds; real queries, depth bounds, HDR and scaling are missing | -| Shaders | Console GPU code recompiled to DXIL at first use, cached on disk. Menus: all. World: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539 | 64-bit image atomics, merged geometry stages, the ray-tracing builder's shaders; some compute programs need a GPU with 64-lane waves | +| GPU: world | The scene is drawn and presented: mesh pipelines, indirect execution, views the shaders pick from the heap themselves, title memory read by address (ray-tracing structures), depth written from compute, pipelines pre-built or made by worker threads and kept on disk | Lighting (surfaces are unlit) and some missing geometry; frames take 1-2 s; draws of untranslated shaders are dropped; real queries, depth bounds, HDR and scaling are missing | +| Shaders | Console GPU code recompiled to DXIL, ahead of time (`translate --cache`) or at first use, cached on disk. Menus: all. World: mesh 8,765 of 8,765, vertex/pixel 12,550 of 12,592, compute 2,579 of 2,637 | Merged geometry stages (195 programs) and about 100 others; fused multiply-adds follow the host GPU; some compute programs need a GPU with 64-lane waves | | Textures | Console tiled layouts and detiling for the modes the title uses | Render-target metadata planes | | Series S mode | Runs through the menus to the loading screen | The world, as above | From 3729ba04d55d98858d9b7310a853d825f0b60b39 Mon Sep 17 00:00:00 2001 From: pes7 Date: Tue, 24 Nov 2026 20:20:03 +0400 Subject: [PATCH 290/445] gfx10: resolve the opcode name once, at decode time `Instruction::name()` binary-searches the opcode table, and the pipeline asks about every instruction eight times per translation: `ir::build`, `structure`, `resource` (which has the most call sites), `io` and `lower`. The answer cannot change - the encoding and opcode are decoded from the words and never rewritten - so resolve it once when the instruction is built and read the field after that. Measured with the synthetic bench from #1002 (no game data), sixteen interleaved rounds per arm, best of each, nanoseconds per instruction, at 256/1k/4k/16k instructions: resource 17 -> 9, 15 -> 7, 24 -> 16, 23 -> 15 (0.47-0.67) lower 511 -> 479, 428 -> 411, 440 -> 401, 477 -> 428 (0.90-0.96) io 27 -> 23, 26 -> 21, 26 -> 22, 30 -> 22 (0.73-0.85) whole 926 -> 881, 920 -> 874, 958 -> 921, 1019 -> 939 (0.92-0.96) `decode` pays the one search it used to be spared (112 -> 115 at 16k, inside the run-to-run spread); every stage after it reads a field. The emitted DXIL is byte-identical at all four sizes. cargo test --workspace --locked: 342 passed, 0 failed, 7 ignored. Both clippy configurations clean; cargo xtask policy ok. (cherry picked from commit 146dfef67a3ecd2c4fd8f9cff8de149c65dfe6f0) --- crates/victory-shader/src/gfx10/mod.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/gfx10/mod.rs b/crates/victory-shader/src/gfx10/mod.rs index 57e6ea2..f89a382 100644 --- a/crates/victory-shader/src/gfx10/mod.rs +++ b/crates/victory-shader/src/gfx10/mod.rs @@ -56,12 +56,16 @@ pub struct Instruction { pub opcode: u16, /// Every dword of the instruction, including literals and extra dwords. pub words: Vec, + /// [`name`] of `encoding` and `opcode`, resolved once at decode time. + /// The translator asks about every instruction eight times; the table is + /// a binary search. + name: Option<&'static str>, } impl Instruction { /// AMD's name for the opcode, if it is in our table. pub fn name(&self) -> Option<&'static str> { - name(self.encoding, self.opcode) + self.name } } @@ -282,11 +286,13 @@ fn instruction(code: &[u8], offset: usize) -> Result { _ => return Err(isa(offset, "unknown encoding")), } }; + let opcode = opcode as u16; Ok(Instruction { offset, encoding, - opcode: opcode as u16, + opcode, words: (0..len).map(word).collect::>()?, + name: name(encoding, opcode), }) } From 70868f8c88b5a7ef1b3e40eeb3256553ab37aa51 Mon Sep 17 00:00:00 2001 From: moe-miau Date: Wed, 25 Nov 2026 01:23:11 +0400 Subject: [PATCH 291/445] XGameSave: a stray or unreadable version folder never costs the save Recovery took any name `v` as a version, so a leftover `v01` next to a committed `v1` parsed as version 1, and the cleanup rebuilt the name as `v1` and deleted the committed save (#870). A correctly named but unreadable newer entry (an empty `v2`, a file, a broken manifest) did the same: `v1` was pruned as older, the read failed, and the next update committed a fresh `v1` holding only the changed blobs, which the following read pruned again. Now only `v` exactly as `commit` writes it is a version. `current` takes the newest version whose manifest reads, removes only versions below it, and leaves unreadable newer entries alone. An update goes above the highest version name present, so a stray entry neither hides the save nor blocks writes. With no readable version at all, reads and updates still fail and nothing is removed. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit b8dbcba260d1012dca8f06ee572e5244bffba1ac) --- crates/victory-hle/src/modules/xgamesave.rs | 153 +++++++++++++++++--- 1 file changed, 129 insertions(+), 24 deletions(-) diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs index f7310c5..29db201 100644 --- a/crates/victory-hle/src/modules/xgamesave.rs +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -135,7 +135,9 @@ fn valid_container(name: &str) -> bool { /// A committed version of a container. struct Version { dir: PathBuf, - number: u64, + /// The highest version number any entry in the container's folder + /// carries, readable or not; the next commit goes above it. + highest: u64, name: String, display: String, /// Blob names; blob `i` is the file `i`. @@ -177,38 +179,73 @@ fn parse_manifest(bytes: &[u8]) -> Option> { (out.len() >= 2).then_some(out) } -/// The container's newest committed version, if any. Removes what a crash -/// left: unfinished versions and older ones. +/// The number of a version folder exactly as [`commit`] names it (`v1`, +/// `v2`, ...); `None` for anything else, such as `v01`, `v+1` or `v0`. +fn version_number(file: &str) -> Option { + let n = file.strip_prefix('v')?.parse::().ok()?; + (n > 0 && format!("v{n}") == file).then_some(n) +} + +/// The names in version folder `dir`: container, display, blobs; `None` if +/// its manifest is missing or does not parse. +fn load(dir: &Path) -> std::io::Result)>> { + let bytes = match std::fs::read(dir.join(MANIFEST)) { + Ok(bytes) => bytes, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e), + }; + let Some(mut names) = parse_manifest(&bytes) else { + return Ok(None); + }; + let blobs = names.split_off(2); + let [name, display] = <[String; 2]>::try_from(names).expect("two names, checked by the parser"); + Ok(Some((name, display, blobs))) +} + +/// The container's newest readable committed version, if any. Removes what +/// a crash left: unfinished versions, and versions older than that one. +/// An unreadable newer folder (a stray, or a broken manifest) is neither +/// taken nor removed, and never costs the version below it. fn current(dir: &Path) -> std::io::Result> { let mut committed = Vec::new(); + let mut highest = 0; for entry in std::fs::read_dir(dir)?.flatten() { let file = entry.file_name(); let file = file.to_string_lossy(); if file.ends_with(".new") { std::fs::remove_dir_all(entry.path())?; - } else if let Some(n) = file.strip_prefix('v').and_then(|n| n.parse::().ok()) { - committed.push(n); + } else if let Some(n) = version_number(&file) { + highest = highest.max(n); + if entry.file_type().is_ok_and(|t| t.is_dir()) { + committed.push(n); + } } } - committed.sort_unstable(); - let Some(&number) = committed.last() else { + committed.sort_unstable_by(|a, b| b.cmp(a)); + if committed.is_empty() { return Ok(None); - }; - for old in &committed[..committed.len() - 1] { - std::fs::remove_dir_all(dir.join(format!("v{old}")))?; } - let version = dir.join(format!("v{number}")); - let bad = || std::io::Error::new(std::io::ErrorKind::InvalidData, "bad save manifest"); - let mut names = parse_manifest(&std::fs::read(version.join(MANIFEST))?).ok_or_else(bad)?; - let blobs = names.split_off(2); - let [name, display] = <[String; 2]>::try_from(names).map_err(|_| bad())?; - Ok(Some(Version { - dir: version, - number, - name, - display, - blobs, - })) + for (at, &number) in committed.iter().enumerate() { + let version = dir.join(format!("v{number}")); + let Some((name, display, blobs)) = load(&version)? else { + continue; + }; + for old in &committed[at + 1..] { + std::fs::remove_dir_all(dir.join(format!("v{old}")))?; + } + return Ok(Some(Version { + dir: version, + highest, + name, + display, + blobs, + })); + } + // Versions exist but none reads: keep them all, and refuse. + Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "no save version has a readable manifest", + )) } /// The version of container `name` in `dir`; none for a missing container @@ -471,7 +508,7 @@ impl Update { } let display = self.display.as_deref(); let display = display.or(current.as_ref().map(|v| v.display.as_str())); - let number = current.as_ref().map_or(1, |v| v.number + 1); + let number = current.as_ref().map_or(1, |v| v.highest + 1); if let Err(e) = commit(&self.dir, number, &self.name, display.unwrap_or(""), &blobs) { return io_error(&self.dir, &e); } @@ -1172,7 +1209,7 @@ mod tests { ] ); let v = current_named(&c.dir, "Player").unwrap().unwrap(); - assert_eq!((v.number, v.display.as_str()), (1, "Chapter 1")); + assert_eq!((v.dir.file_name(), v.display.as_str()), (Some("v1".as_ref()), "Chapter 1")); } /// An empty configuration id names none. As a folder name it would be @@ -1384,4 +1421,72 @@ mod tests { close_container(this, container); close_provider(this, provider); } + + /// Only `v` as `commit` writes it is a version: `v01` and the like + /// are neither read, counted nor removed (#870). + #[test] + fn a_noncanonical_folder_does_not_remove_a_committed_save() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + assert_eq!(update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), S_OK); + let slot = container_dir(root, "Slot"); + for stray in ["v01", "v001", "v+1", "v0", "v02"] { + std::fs::create_dir(slot.join(stray)).unwrap(); + } + assert_eq!(state(root), old_state()); + assert!(slot.join("v1").is_dir()); + for stray in ["v01", "v001", "v+1", "v0", "v02"] { + assert!(slot.join(stray).exists(), "{stray} was removed"); + } + } + + /// A newer version folder that does not read (an empty folder, a file, + /// a broken manifest) neither hides the committed save, nor removes it, + /// nor blocks the next update, which goes above it. + #[test] + fn an_unreadable_newer_version_does_not_cost_the_save() { + type Make = fn(&Path); + let strays: [(&str, Make); 3] = [ + ("empty folder", |p| std::fs::create_dir(p).unwrap()), + ("file", |p| std::fs::write(p, b"not a version").unwrap()), + ("broken manifest", |p| { + std::fs::create_dir(p).unwrap(); + std::fs::write(p.join(MANIFEST), [9, 0, 0, 0, b'x']).unwrap(); + }), + ]; + for (what, make) in strays { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + assert_eq!(update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), S_OK); + let slot = container_dir(root, "Slot"); + make(&slot.join("v2")); + + assert_eq!(state(root), old_state(), "{what}: read"); + assert!(slot.join("v1").is_dir(), "{what}: v1 was removed"); + + assert_eq!(update(root, "two", &[("a", Some("new a"))]), S_OK, "{what}: update"); + let blobs = vec![("a".into(), "new a".into()), ("b".into(), "old b".into())]; + let after = Some(("two".into(), blobs)); + assert_eq!(state(root), after, "{what}: after the update"); + assert!(slot.join("v3").is_dir(), "{what}: the update did not go above v2"); + // Read again: the new version stays the container. + assert_eq!(state(root), after, "{what}: second read"); + } + } + + /// With no readable version at all, reads and updates fail and nothing + /// is removed. + #[test] + fn no_readable_version_is_refused_and_kept() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + assert_eq!(update(root, "one", &[("a", Some("old a"))]), S_OK); + let slot = container_dir(root, "Slot"); + std::fs::write(slot.join("v1").join(MANIFEST), [1, 2, 3]).unwrap(); + let c = Provider { root: root.into() }.container("Slot"); + assert_eq!(read(&c, None).err(), Some(NO_ACCESS)); + assert_eq!(update(root, "two", &[("a", Some("new a"))]), NO_ACCESS); + assert!(slot.join("v1").join("0").is_file()); + assert!(!slot.join("v2").exists()); + } } From daeeb28c1e8f69edd6767b6bff85c632b5429b0a Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 01:06:46 -0600 Subject: [PATCH 292/445] VIctory's 88 commits fitted in; clzero loops end as the console's do The fork's emulation of a clzero loop zeroed from the start to the end and left rax at the end: the instruction zeroes whole lines and the test comes after it (VIctory's own test of it failed here). The title's descriptor heaps are held shared while their slots are written (VIctory 628b95d held them alone, for every thread that writes descriptors). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 26 +++++-- crates/victory-loader/src/console_insn.rs | 52 +++++++------ crates/victory-loader/src/crash.rs | 4 +- crates/victory-shader/src/emit/valu_tests.rs | 78 -------------------- crates/victory-shader/src/gfx10/mod.rs | 5 ++ crates/victory-shader/src/ir.rs | 7 +- 6 files changed, 56 insertions(+), 116 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 5f6ab90..069c82f 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -126,14 +126,17 @@ const SHADER_VISIBLE: u32 = 1; /// Shader-visible heaps by address range, for mirroring descriptor writes: /// start, end, heap. #[cfg(windows)] -static SHADER_HEAPS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +/// +/// Held shared while a heap found here is used (by every thread that writes +/// descriptors, and by [`sync_heaps`]), alone only where heaps come and go. +static SHADER_HEAPS: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); /// Makes the host descriptor for what the title wrote at `handle`, if it /// is in a shader-visible heap. Keeps `SHADER_HEAPS` locked for the duration /// so `Heap::drop` cannot free the heap concurrently. #[cfg(windows)] fn mirror(handle: u64) { - let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); let Some(&(_, _, at)) = heaps .iter() .find(|&&(start, end, _)| (start..end).contains(&handle)) @@ -177,7 +180,7 @@ pub(crate) fn sync_heaps() { let started = std::time::Instant::now(); let (mut pages, mut looked, mut mirrored) = (0u64, 0u64, 0u64); let mut page_bytes: Vec = Vec::new(); - let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); for &(start, end, at) in heaps.iter() { // SAFETY: registered heaps are live (removed when dropped). let heap = unsafe { &*(at as *const Heap) }; @@ -275,7 +278,7 @@ fn changed_slots( /// `heap`, if that heap still exists. #[cfg(windows)] pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { - let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); if heaps.iter().any(|&(_, _, h)| h == heap) // SAFETY: registered heaps are live (removed when dropped). && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get() @@ -289,7 +292,7 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { /// bytes at `gpu`. #[cfg(windows)] pub(crate) fn constant_slot(heap: usize, index: u32, gpu: u64, size: u32) { - let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); if heaps.iter().any(|&(_, _, h)| h == heap) // SAFETY: registered heaps are live (removed when dropped). && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get() @@ -302,7 +305,7 @@ pub(crate) fn constant_slot(heap: usize, index: u32, gpu: u64, size: u32) { impl Drop for Heap { fn drop(&mut self) { let at = std::ptr::from_ref::(self) as usize; - let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let mut heaps = SHADER_HEAPS.write().unwrap_or_else(|e| e.into_inner()); heaps.retain(|&(_, _, h)| h != at); } } @@ -819,7 +822,14 @@ pub(crate) fn make_waiting() { // texture without a host copy must go on waiting). // (Looked up first: the handle is read only while its heap is // there.) - let Some((heap, index)) = shader_slot(handle) else { + // (The heap stays while the lock is held: `mirror`.) + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); + let Some(&(_, _, at)) = heaps.iter().find(|&&(start, end, _)| (start..end).contains(&handle)) else { + continue; + }; + // SAFETY: a registered heap, live while the lock is held. + let heap = unsafe { &*(at as *const Heap) }; + let Some(index) = heap.index(handle) else { continue; }; let same = match view(handle) { @@ -1113,7 +1123,7 @@ pub(crate) extern "system" fn create_heap( #[cfg(windows)] if visible { let at = std::ptr::from_ref::(&heap) as usize; - let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let mut heaps = SHADER_HEAPS.write().unwrap_or_else(|e| e.into_inner()); heaps.push((start, start + size, at)); } #[cfg(not(windows))] diff --git a/crates/victory-loader/src/console_insn.rs b/crates/victory-loader/src/console_insn.rs index ca1eb8c..946230d 100644 --- a/crates/victory-loader/src/console_insn.rs +++ b/crates/victory-loader/src/console_insn.rs @@ -168,29 +168,37 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { ]; let end = regs[end_reg as usize & 15] as usize; let start = ctx.Rax as usize; - if end > start && end - start < 2 << 30 { - // Region by region: a block may lie across several (the title's pages are - // mapped one view each), and one answer for all of it was a refusal, after - // which every 64-byte line took an exception of its own. - let mut at = start; - while at < end { - let Some(to) = writable_to(at, end) else { break }; - // SAFETY: committed and writable from `at` to `to`. - unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) }; - at = to; - } - if at == start { - return 0; - } - ZEROED.fetch_add((at - start) as u64, Relaxed); - if at < end { - // What follows is not writable: the loop goes on there (the same - // instruction again), where the real one faults too. - ctx.Rax = at as u64; - return CONTINUE_EXECUTION; - } + // A pass zeroes the whole line `rax` is in, wherever in it, and the test comes + // after it: lines are zeroed past an `end` inside one, and one is for an `end` + // not above the start. (The bytes from `start` to `end` were, `rax` came out as + // `end`, and the flags stayed what they were.) + const MOST: usize = (2 << 30) / 64; + let wanted = if end > start { (end - start).div_ceil(64) } else { 1 }; + let passes = wanted.min(MOST); + let first = start & !63; + let Some(stop) = first.checked_add(passes * 64) else { return 0 }; + // Region by region: a block may lie across several (the title's pages are + // mapped one view each), and one answer for all of it was a refusal, after + // which every 64-byte line took an exception of its own. + let mut at = first; + while at < stop { + let Some(to) = writable_to(at, stop) else { break }; + // SAFETY: committed and writable from `at` to `to`. + unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) }; + at = to; } - ctx.Rax = end as u64; + let done = (at - first) / 64; + if done == 0 { + return 0; + } + ZEROED.fetch_add((done * 64) as u64, Relaxed); + ctx.Rax = ctx.Rax.wrapping_add((done * 64) as u64); + if done < wanted { + // What follows is not writable (or the block is huge): the loop goes on + // there (the same instruction again), where the real one faults too. + return CONTINUE_EXECUTION; + } + ctx.EFlags = ctx.EFlags & !crate::crash::CMP_FLAGS | crate::crash::cmp_flags(ctx.Rax, end as u64); } ConsoleOnly::Rdpru => { let mut v = 0i64; diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index e880300..f22dbab 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -410,7 +410,7 @@ fn gpr(context: &mut CONTEXT, n: u8) -> &mut u64 { } /// The status flags `cmp a, b` leaves (CF, PF, AF, ZF, SF, OF) as `EFLAGS` bits. -fn cmp_flags(a: u64, b: u64) -> u32 { +pub(crate) fn cmp_flags(a: u64, b: u64) -> u32 { let r = a.wrapping_sub(b); u32::from(a < b) | u32::from((r as u8).count_ones().is_multiple_of(2)) << 2 @@ -419,7 +419,7 @@ fn cmp_flags(a: u64, b: u64) -> u32 { | ((r >> 63) as u32) << 7 | ((((a ^ b) & (a ^ r)) >> 63) as u32) << 11 } -const CMP_FLAGS: u32 = 0x8d5; +pub(crate) const CMP_FLAGS: u32 = 0x8d5; /// SSE4a's `extrq`/`insertq` (register forms, the only ones there are) on /// the saved XMM registers; returns the instruction's length. diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index b8275e0..cd2806f 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -295,39 +295,6 @@ fn scalar_quad_masks_pack_nibbles_and_set_scc() { }); } -#[test] -fn scalar_quad_masks_pack_nibbles_and_set_scc() { - let pack_words = |opcode: u32| { - [ - 0xBE90_0000 | opcode << 8, // s_quadmask s16, s0 (pairs for b64) - sop2(0x0a, 18, 129, 128), // s_cselect_b32 s18, 1, 0 - sop2(0x1e, 18, 18, 144), // s_lshl_b32 s18, s18, 16 - sop2(0x10, 16, 16, 18), // s_or_b32 s16, s16, s18 - vop1(1, 0, sgpr(16)), // v_mov_b32 v0, s16 - ] - }; - let cases = [ - ([0, 0, 0, 0], [0, 0]), - ([0x8000_0420, 0x0100_0001, 0, 0], [0x1_0086, 0x1_4186]), - ([0, 0x8000_0000, 0, 0], [0, 0x1_8000]), - ([u32::MAX, u32::MAX, 0, 0], [0x1_00ff, 0x1_ffff]), - ]; - let inputs = cases.map(|(input, _)| input); - for (wide, opcode) in [0x2c, 0x2d].into_iter().enumerate() { - let shader = build_valu_cs(&pack_words(opcode)); - run_cases(&shader, &inputs, |backend, i, _, got| { - assert_eq!(got, cases[i].1[wide], "{backend}, opcode {opcode:#x}"); - }); - } - let high = build_valu_cs(&[ - 0xBE90_2D00, // s_quadmask_b64 s[16:17], s[0:1] - vop1(1, 0, sgpr(17)), - ]); - run_cases(&high, &inputs, |backend, _, _, got| { - assert_eq!(got, 0, "{backend}: high dword"); - }); -} - fn is_f16_nan(bits: u16) -> bool { (bits & 0x7FFF) > 0x7C00 } @@ -718,51 +685,6 @@ fn v_min3_max3_med3_integer_forms_match_rdna2() { } } -#[test] -fn v_min3_max3_med3_integer_forms_match_rdna2() { - // v_{min3,max3,med3}_{i32,u32} v0, v1, v2, v3 (VOP3 0x152..0x159). - let ops: [(&str, u16, fn([u32; 3]) -> u32); 6] = [ - ("v_min3_i32", 0x152, |t| { - t.into_iter().min_by_key(|&x| x as i32).unwrap() - }), - ("v_min3_u32", 0x153, |t| t.into_iter().min().unwrap()), - ("v_max3_i32", 0x155, |t| { - t.into_iter().max_by_key(|&x| x as i32).unwrap() - }), - ("v_max3_u32", 0x156, |t| t.into_iter().max().unwrap()), - ("v_med3_i32", 0x158, |mut t| { - t.sort_by_key(|&x| x as i32); - t[1] - }), - ("v_med3_u32", 0x159, |mut t| { - t.sort_unstable(); - t[1] - }), - ]; - // Every ordering of three values, with the sign bit set on some so that - // the signed and unsigned answers differ. - let values = [0u32, 1, 0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF]; - let mut cases = Vec::new(); - for a in values { - for b in values { - for c in values { - cases.push([a, b, c, 0]); - } - } - } - for (name, op, pick) in ops { - let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); - run_cases(&shader, &cases, |backend, _, inp, got| { - let want = pick([inp[0], inp[1], inp[2]]); - assert_eq!( - got, want, - "{backend}: {name}({:#010x}, {:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}", - inp[0], inp[1], inp[2], - ); - }); - } -} - #[test] fn v_med3_f16_matches_rdna2_with_nan() { // v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357) diff --git a/crates/victory-shader/src/gfx10/mod.rs b/crates/victory-shader/src/gfx10/mod.rs index f89a382..719b346 100644 --- a/crates/victory-shader/src/gfx10/mod.rs +++ b/crates/victory-shader/src/gfx10/mod.rs @@ -63,6 +63,11 @@ pub struct Instruction { } impl Instruction { + /// An instruction of these words, its name resolved. + pub fn new(offset: usize, encoding: Encoding, opcode: u16, words: Vec) -> Self { + Self { offset, encoding, opcode, words, name: name(encoding, opcode) } + } + /// AMD's name for the opcode, if it is in our table. pub fn name(&self) -> Option<&'static str> { self.name diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 0e8a4ed..cb79fb6 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -578,12 +578,7 @@ fn unspill( } let (store, pairs, codes) = chosen; let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| { - list[i] = gfx10::Instruction { - offset: list[i].offset, - encoding, - opcode, - words: vec![word], - }; + list[i] = gfx10::Instruction::new(list[i].offset, encoding, opcode, vec![word]); }; // `s_mov_b32` / `s_mov_b64 dst, src` (SOP1, opcodes 3 and 4); `s_nop`. A code // from `PARKED` up does not fit the word: s0 stands in for it there. From 913d4f0c5d68cf0fd6f165886b93037d231f32ed Mon Sep 17 00:00:00 2001 From: quaternion Date: Tue, 24 Nov 2026 02:17:32 -0500 Subject: [PATCH 293/445] fix(hle): keep apostrophes intact when splitting relaunch args Windows command lines quote only with double quotes. split_args treated an apostrophe as a quote too, so -name=O'Brien swallowed the following argument. Only toggle on ", and add the apostrophe case to the relaunch test (review note on #455). (cherry picked from commit eb8067f2eae84cb64081af357cd03a48944a42b2) --- crates/victory-hle/src/modules/xgame.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/victory-hle/src/modules/xgame.rs b/crates/victory-hle/src/modules/xgame.rs index abb1fc4..e1bc885 100644 --- a/crates/victory-hle/src/modules/xgame.rs +++ b/crates/victory-hle/src/modules/xgame.rs @@ -122,22 +122,21 @@ fn relaunch_args( out } -/// Splits the title's command-line tail into arguments, keeping quoted -/// strings together (including empty ones). `split_whitespace` would hand -/// the child a quoted path as several broken arguments. +/// Splits the title's command-line tail into arguments, keeping double-quoted +/// strings together (including empty ones). Windows command lines quote only +/// with `"`: an apostrophe is ordinary text, as in `O'Brien`. fn split_args(args: &str) -> Vec { let mut out = Vec::new(); let mut current = String::new(); - let mut quote = None; + let mut quoted = false; let mut started = false; for c in args.chars() { match c { - '"' | '\'' if quote == Some(c) => quote = None, - '"' | '\'' if quote.is_none() => { - quote = Some(c); + '"' => { + quoted = !quoted; started = true; } - c if quote.is_none() && c.is_whitespace() => { + c if !quoted && c.is_whitespace() => { if started { out.push(std::mem::take(&mut current)); started = false; @@ -265,7 +264,7 @@ mod tests { ours, current.as_os_str(), "other.exe", - r#"--config="C:\Program Files\game" "" -y"#, + r#"--config="C:\Program Files\game" "" -name=O'Brien -y"#, ); let expected: Vec = [ "run", @@ -276,6 +275,7 @@ mod tests { "--", r"--config=C:\Program Files\game", "", + "-name=O'Brien", "-y", ] .map(Into::into) From 64c3178097e8b730ef4b6c3c3e82e3b90987f058 Mon Sep 17 00:00:00 2001 From: AnoHunted <360473103+AnoHunted@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:38:44 +0000 Subject: [PATCH 294/445] Audio: an XMA write block past the ring's end wraps before the first write The write block (context word 0, bits 27-31) was used as it is for the first block of a pass, so one at or past the ring size (bits 22-26) was written past the ring's end, possibly into another APU allocation, before it wrapped with (write + 1) % size. Take it modulo the ring first, as the read block is taken, and as advance_read does. (cherry picked from commit 7a5d85e6a2867081ed54515ce7f33bae3fcb643d) --- crates/victory-hle/src/modules/audio.rs | 88 ++++++++++++++++++++++++- 1 file changed, 87 insertions(+), 1 deletion(-) diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index 644e032..8da3346 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -520,7 +520,9 @@ fn pump(context: Context, voice: &mut Voice) { if voice.pcm.len() < SAMPLES_PER_BLOCK && !decode(context, voice) { return; } - let write = context.field(0, 27, 5); + // The write block is the title's too: taken modulo the ring before + // the first write, which would otherwise land past the ring's end. + let write = context.field(0, 27, 5) % size; let address = context.get(7) as usize + write as usize * BLOCK_BYTES; let Some(out) = heap_bytes(address as u32, BLOCK_BYTES) else { return; @@ -1091,6 +1093,90 @@ mod tests { assert!(ring[0x200..].iter().all(|&b| b == 0x55)); } + /// A write block past the end of the ring (6 on a ring of four) is block + /// 2 of it: blocks 2, 3 and 0 are filled, up to the read block (1). It + /// used to write block 6 first, past the ring's end. + #[test] + fn xma_write_blocks_past_the_ring_end_wrap() { + let _serial = lock(&CONTEXT_TESTS); + let mut request = ShapeContexts { + counts: [0, 0, 0, 0, 4, 0], + arrays: [std::ptr::null_mut(); 6], + apu: [0; 6], + }; + assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK); + let context = Context(request.arrays[4].cast::().wrapping_add(16)); + let (mut input, mut input_apu) = (std::ptr::null_mut(), 0); + assert_eq!(ApuAlloc(&mut input, &mut input_apu, 0x1000, 0x800, 1), S_OK); + let stream = silent_stream(); + // SAFETY: two packets were allocated. + unsafe { std::ptr::copy_nonoverlapping(stream.as_ptr(), input.cast(), stream.len()) }; + let (mut output, mut output_apu) = (std::ptr::null_mut(), 0); + assert_eq!( + ApuAlloc(&mut output, &mut output_apu, 0x800, 0x100, 2), + S_OK + ); + // SAFETY: the allocation was just made: the ring (four blocks) and a guard + // area after it, which the pass must not touch. + unsafe { output.cast::().write_bytes(0x55, 0x800) }; + + // As in `xma_contexts_decode_into_their_output_rings`, but looping + // forever from the first frame to the last; write block 6, read block 1. + context.set(0, 2 | 255 << 12 | 1 << 20 | 4 << 22 | 6 << 27); + context.set(1, 1 << 31 | 3 << 27); + context.set(2, 32); + context.set(3, 32); + context.set(4, (xma::PACKET_BYTES * 8 + 32 + 2 * 31) as u32); + context.set(5, input_apu); + context.set(7, output_apu); + context.set(9, 1); + + let mut acp = std::ptr::null_mut(); + assert_eq!(AcpHalCreate(&mut acp), S_OK); + // SAFETY: just created. + let m = unsafe { (*acp).vtable }; + assert_eq!((m.connect)(acp, 0x1000, 0x1000), S_OK); + let submit = |command: u32, words: &[u32]| { + assert_eq!( + (m.submit)(acp, command, 0xf1, u32::MAX, words.as_ptr().cast(), 0), + S_OK + ); + }; + submit(ENABLE_XMA, &[1]); + // A pass on a thread of its own (the decoding thread runs them too), + // so that one that never ends fails this test instead of hanging it. + let (done, passed) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + xma().pump(); + let _ = done.send(()); + }); + let five = std::time::Duration::from_secs(5); + let wait = || passed.recv_timeout(five).is_ok(); + let ended = wait(); + if !ended { + // End it as a full ring would, to release the contexts below. + context.set_field(1, 31, 1, 0); + assert!(wait(), "the XMA pass did not end on a full ring either"); + } + let (write, writable) = (context.field(0, 27, 5), context.field(1, 31, 1)); + // SAFETY: the ring. + let ring = unsafe { std::slice::from_raw_parts(output.cast::(), 0x800) }.to_vec(); + + submit(DISABLE_XMA, &[1]); + (m.release)(acp); + ApuFree(input); + ApuFree(output); + assert_eq!(AcpHalReleaseShapeContexts(), S_OK); + assert!(ended, "the XMA pass never ended"); + // Blocks 2, 3 and 0 written (silence), 1 left for the title, and + // nothing past the ring. + assert_eq!((write, writable), (1, 0)); + assert!(ring[0x400..].iter().all(|&b| b == 0x55), "written past the ring"); + let block = |n: usize| &ring[n * 0x100..(n + 1) * 0x100]; + assert!([0, 2, 3].iter().all(|&n| block(n).iter().all(|&b| b == 0))); + assert!(block(1).iter().all(|&b| b == 0x55)); + } + #[test] fn xma_contexts_decode_into_their_output_rings() { let _serial = lock(&CONTEXT_TESTS); From b9c18b0685e16315781dd489487d3796443ea64a Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 01:12:28 -0600 Subject: [PATCH 295/445] VIctory e29391f, 13185f5 and 4fc9d70, by hand 16-bit interpolations write the half op_sel picks, with omod and clamp; the device says whether it was removed; detiling ends with its staging buffer. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/device.rs | 14 +++ crates/victory-gpu/src/texture.rs | 6 +- crates/victory-shader/src/emit/lower.rs | 18 +++- crates/victory-shader/src/emit/mod.rs | 121 ++++++++++++++++++++++++ 4 files changed, 157 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index dfbf2b2..569bafd 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -399,6 +399,19 @@ extern "system" fn unknown_pipeline( E_NOTIMPL } +/// The host device's state: the console's device is removed when the host's is +/// (VIctory 13185f5: the default answer, E_NOTIMPL, reads as a lost device). +extern "system" fn removed_reason(_: This) -> HRESULT { + #[cfg(windows)] + if let Some(host) = crate::host::host() { + // SAFETY: a plain query. + if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } { + return e.code().0; + } + } + S_OK +} + /// IUnknown 3, object methods 4, device methods 76 (0x18-0x290), then the /// methods `ID3D12Device1` to `ID3D12Device8` add, in order: 3, 1, 3, 6, 9, /// 1, 2, 9 (0x298-0x3a0, the console's own among them), then those of @@ -431,6 +444,7 @@ static FUNCTIONS: Table<160> = { f[28] = resource::create_heap as *const (); // 0xe0 f[29] = resource::create_placed as *const (); // 0xe8 f[36] = fence::create as *const (); // 0x120 + f[37] = removed_reason as *const (); // 0x128 f[38] = resource::copyable_footprints as *const (); // 0x130 f[39] = query::create as *const (); // 0x138 f[41] = signature::create as *const (); // 0x148 diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 56f2726..f3c2a8d 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -1243,7 +1243,11 @@ impl Staging { let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); let f = footprint.Footprint; let pitch = f.RowPitch as usize; - let len = pitch * rows as usize * f.Depth as usize; + // The last row of the last subresource is not padded to its pitch + // (VIctory 4fc9d70): to the end of the buffer at most, where a + // block of the pool goes on with another texture's. + let len = (pitch * rows as usize * f.Depth as usize) + .min(self.bytes.saturating_sub(footprint.Offset) as usize); // SAFETY: the subresource's part of the mapped staging buffer. let linear = unsafe { std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 4672121..d4b0163 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -9927,7 +9927,23 @@ impl<'a> Lower<'a> { let f = half(self, h)?.ok_or("a packed input half no element holds")?; self.as_int(f) } else if f16 { - let f = half(self, h)?.ok_or("a packed input half no element holds")?; + let mut f = half(self, h)?.ok_or("a packed input half no element holds")?; + if let Fields::Valu(v) = &inst.fields { + // omod, then clamp, before the one rounding to 16 bits; op_sel[3] + // picks the destination half (VIctory e29391f: the low half was + // always written, the high one's value never arrived). + let (omod, clamp) = (v.omod, v.clamp); + if omod != 0 { + let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(omod)]; + let k = self.s.m.f32(factor.to_bits()); + f = self.s.m.bin(c, Bin::Mul, f, k); + } + if clamp { + f = self.unary(7, f); + } + let lo = to_f16(self, f); + return self.write_half(inst, lo, None); + } let lo = to_f16(self, f); self.low_half(inst, reg, lo) } else if matches!(eval, Eval::Mode(1)) { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 454689e..b9f52c4 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -816,6 +816,127 @@ mod tests { use super::lower::LOOP_LIMIT; use super::parse_loop_limit; + /// The LLVM text `dxc -dumpbin` prints for a DXIL container, when dxc + /// is installed. + #[cfg(windows)] + fn dump_dxil(container: &[u8]) -> Option { + let dxc = match std::env::var_os("VICTORY_PC_DXC") { + Some(p) => std::path::PathBuf::from(p), + None => super::validator::Validator::default_path()?.with_file_name("dxc.exe"), + }; + if !dxc.exists() { + return None; + } + let file = std::env::temp_dir().join(format!("victory-interp-{}.dxil", std::process::id())); + std::fs::write(&file, container).ok()?; + let out = std::process::Command::new(dxc) + .arg("-dumpbin") + .arg(&file) + .output() + .ok()?; + let _ = std::fs::remove_file(&file); + assert!( + out.status.success(), + "dxc -dumpbin failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + Some(String::from_utf8_lossy(&out.stdout).into_owned()) + } + + #[cfg(windows)] + #[test] + fn interpolated_f16_writes_the_op_sel_half_with_modifiers() { + // p1_f32 v2, v0, attr0.x; then a p2_f16 completing it into v3, which holds a value + // (v2's own is no number here: a first half is evaluated with its second). + let p2 = |dst_high: bool, omod: u32, clamp: bool| { + let vgpr = |n: u32| 256 + n; + let mut w0 = 0x35u32 << 26 | 0x35au32 << 16 | 3; + if dst_high { + w0 |= 1 << 14; // op_sel[3]: the high destination half. + } + if clamp { + w0 |= 1 << 15; + } + let w1 = vgpr(1) << 9 | vgpr(2) << 18; + [w0, w1 | omod << 27] + }; + let dump = |dst_high: bool, omod: u32, clamp: bool| { + let [w0, w1] = p2(dst_high, omod, clamp); + let words = [ + 0x7E06_0301u32, // v_mov_b32 v3, v1 + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + w0, + w1, // v_interp_p2_f16 v3, attr0, v1, v2 + 0xF800_180F, + 0x0303_0303, // exp mrt0, v3, v3, v3, v3 done vm + 0xBF81_0000, + ]; + let native = super::NativeProgram { + stage: super::HwStage::Ps, + wave64: false, + vgprs: 4, + layout: vec![], + used: vec![], + io: crate::native::StageIo::Ps { + inputs: vec![crate::native::PsInput { + usage: crate::native::Usage::Generic, + row: 0, + mask: 0b1111, + attr: 0, + flat: false, + fp16: true, + pack2: false, + row2: 0, + }], + input_addr: 2, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let el = |name: &str, kind, usage, half| SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage, + half, + }; + let isg1 = super::container::signature(&[el("TEXCOORD", 0, 0, true)], true); + let osg1 = super::container::signature(&[el("SV_Target", 16, 15, false)], false); + let bytes = + crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]); + let c = super::Container::parse(&bytes).unwrap(); + let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + super::emit(&c, &native, &p, &st, &io, &res).unwrap().dxil + }; + let (Some(low), Some(high)) = ( + dump_dxil(&dump(false, 0, false)), + dump_dxil(&dump(true, 1, true)), + ) else { + eprintln!("no dxc.exe; DXIL check skipped"); + return; + }; + // The low-half write keeps the destination's high half. + assert!(low.contains("-65536"), "low write keeps the high half"); + // The high-half write shifts the result up by 16. + assert!(high.contains("shl i32"), "op_sel[3] writes the high half"); + // omod mul:2 and clamp (dx.op.unary.f32, opcode 7) are applied. + assert!(high.contains("2.000000e+00"), "omod multiplies by two"); + assert!( + high.contains("dx.op.unary.f32(i32 7"), + "clamp saturates the result" + ); + assert!(!low.contains("dx.op.unary.f32(i32 7")); + } + #[test] fn the_clean_up_switch_parses_or_runs_every_pass() { let all = super::bitcode::opt::ALL; From d1c8acd5275b3c7d800176bf2650bad884755964 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 01:14:23 -0600 Subject: [PATCH 296/445] Revert "HLE: show title windows through a stand-in that always reads its messages" This reverts commit 9820bdc45e9eb1d50f8a1f7419850953d8fa54e4. --- crates/victory-hle/Cargo.toml | 1 - crates/victory-hle/src/modules/lifecycle.rs | 328 +------------------- 2 files changed, 7 insertions(+), 322 deletions(-) diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index 6d86b03..d91f14f 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -20,7 +20,6 @@ tracing.workspace = true windows-sys = { workspace = true, features = [ "Win32_Foundation", "Win32_Globalization", - "Win32_Graphics_Gdi", "Win32_Media", "Win32_Security", "Win32_Security_Cryptography", diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs index 448c421..09c6baa 100644 --- a/crates/victory-hle/src/modules/lifecycle.rs +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -96,20 +96,6 @@ pub extern "system" fn UnregisterAppConstrainedChangeNotification(registration: /// The window procedure a title window had before ours. const TITLE_PROC: PCWSTR = w!("victory.wndproc"); -/// The stand-in window shown for a title window (a property of the title's). -const STAND_IN: PCWSTR = w!("victory.standin"); - -// The window the player sees is never the title's. A title makes its window -// on one of its own threads and reads its messages only when that thread -// gets round to it, which in a slow frame or a load is seconds apart; the -// system then shows the busy cursor over the window, and a click turns it -// into a "Not responding" ghost. So a top-level title window is made -// message-only (never shown), and a stand-in with the title's text, style -// and (fitted) size is shown in its place, owned by a thread of ours that -// does nothing but read its messages. The title loses nothing: its input -// comes from GameInput (polled, not window messages), and frames are -// presented to the visible window of the process, the stand-in. - pub extern "system" fn CreateWindowExW( ex_style: u32, class: PCWSTR, @@ -124,29 +110,14 @@ pub extern "system" fn CreateWindowExW( instance: HINSTANCE, param: *const c_void, ) -> HWND { - let top = parent.is_null(); - // SAFETY: the title's own arguments, forwarded (a top-level window - // made message-only). + let (x, y, width, height) = fit(parent, x, y, width, height); + // SAFETY: the title's own arguments, forwarded (the size fitted). let hwnd = unsafe { wm::CreateWindowExW( - ex_style, - class, - name, - style, - x, - y, - width, - height, - if top { wm::HWND_MESSAGE } else { parent }, - menu, - instance, - param, + ex_style, class, name, style, x, y, width, height, parent, menu, instance, param, ) }; hook(hwnd); - if top { - stand_in(hwnd, ex_style, style, x, y, width, height); - } hwnd } @@ -165,29 +136,14 @@ pub extern "system" fn CreateWindowExA( instance: HINSTANCE, param: *const c_void, ) -> HWND { - let top = parent.is_null(); - // SAFETY: the title's own arguments, forwarded (a top-level window - // made message-only). + let (x, y, width, height) = fit(parent, x, y, width, height); + // SAFETY: the title's own arguments, forwarded (the size fitted). let hwnd = unsafe { wm::CreateWindowExA( - ex_style, - class, - name, - style, - x, - y, - width, - height, - if top { wm::HWND_MESSAGE } else { parent }, - menu, - instance, - param, + ex_style, class, name, style, x, y, width, height, parent, menu, instance, param, ) }; hook(hwnd); - if top { - stand_in(hwnd, ex_style, style, x, y, width, height); - } hwnd } @@ -270,149 +226,6 @@ fn fit_into(area: &RECT, width: i32, height: i32) -> (i32, i32) { ) } -/// Shows a stand-in for the top-level title window `title` (see -/// [`STAND_IN`]); `ShowWindow` on `title` then shows or hides the stand-in. -fn stand_in(title: HWND, ex_style: u32, style: u32, x: i32, y: i32, width: i32, height: i32) { - if title.is_null() { - return; - } - let (x, y, width, height) = fit(std::ptr::null_mut(), x, y, width, height); - let mut text = vec![0u16; 512]; - // SAFETY: a window this thread just created; the buffer holds 512 - // characters. Its icon, if its class has one. - let (icon, text) = unsafe { - let n = wm::GetWindowTextW(title, text.as_mut_ptr(), text.len() as i32); - text.truncate(n.max(0) as usize); - text.push(0); - (wm::GetClassLongPtrW(title, wm::GCLP_HICON), text) - }; - let (sender, receiver) = std::sync::mpsc::channel(); - let spawned = std::thread::Builder::new() - .name("victory-window".into()) - .spawn(move || { - let window = make_stand_in(&text, ex_style, style, (x, y, width, height), icon); - let _ = sender.send(window as usize); - if !window.is_null() { - pump(); - } - }); - let window = match spawned { - Ok(_) => receiver.recv().unwrap_or(0) as HWND, - Err(_) => std::ptr::null_mut(), - }; - if window.is_null() { - tracing::warn!("no stand-in window; the title's own window is not shown"); - return; - } - // SAFETY: the title's window, on the thread that made it. - unsafe { wm::SetPropW(title, STAND_IN, window) }; -} - -/// The stand-in window for `stand_in`, on the calling thread. -fn make_stand_in( - text: &[u16], - ex_style: u32, - style: u32, - (x, y, width, height): (i32, i32, i32, i32), - icon: usize, -) -> HWND { - use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; - const CLASS: PCWSTR = w!("VIctory.title"); - // SAFETY: registers our class (again is harmless) and creates a window - // of it; `text` is NUL-terminated. - unsafe { - let instance = GetModuleHandleW(std::ptr::null()); - let class = wm::WNDCLASSEXW { - cbSize: size_of::() as u32, - lpfnWndProc: Some(stand_in_proc), - hInstance: instance, - hCursor: wm::LoadCursorW(std::ptr::null_mut(), wm::IDC_ARROW), - lpszClassName: CLASS, - ..std::mem::zeroed() - }; - wm::RegisterClassExW(&class); - let window = wm::CreateWindowExW( - ex_style, - CLASS, - text.as_ptr(), - style, - x, - y, - width, - height, - std::ptr::null_mut(), - std::ptr::null_mut(), - instance, - std::ptr::null(), - ); - if !window.is_null() && icon != 0 { - for kind in [wm::ICON_BIG, wm::ICON_SMALL] { - wm::SendMessageW(window, wm::WM_SETICON, kind as usize, icon as isize); - } - } - window - } -} - -/// Destroys a stand-in (posted when the title's window goes). -const DESTROY_STAND_IN: u32 = wm::WM_APP + 0x7649; - -extern "system" fn stand_in_proc( - hwnd: HWND, - message: u32, - wparam: WPARAM, - lparam: LPARAM, -) -> LRESULT { - match message { - // A user close (close button, Alt+F4, window or taskbar menu). - wm::WM_CLOSE => { - end_title("window closed", Box::new(|| {})); - return 0; - } - // No window menu from the keyboard (see `window_proc`): here it - // would stop only this thread, but it takes keys the title wants. - wm::WM_SYSCOMMAND if wparam & 0xFFF0 == wm::SC_KEYMENU as usize => return 0, - DESTROY_STAND_IN => { - // SAFETY: our window, on its thread. - unsafe { wm::DestroyWindow(hwnd) }; - return 0; - } - // SAFETY: ends `pump`, the loop of this window's thread. - wm::WM_DESTROY => unsafe { wm::PostQuitMessage(0) }, - _ => {} - } - // SAFETY: the default handling for our window. - unsafe { wm::DefWindowProcW(hwnd, message, wparam, lparam) } -} - -/// The message loop of a stand-in's thread, until its window is destroyed. -fn pump() { - // SAFETY: the standard message loop of this thread's window. - unsafe { - let mut message: wm::MSG = std::mem::zeroed(); - while wm::GetMessageW(&mut message, std::ptr::null_mut(), 0, 0) > 0 { - wm::TranslateMessage(&message); - wm::DispatchMessageW(&message); - } - } -} - -/// The stand-in shown for `hwnd`, or null. -fn stand_in_of(hwnd: HWND) -> HWND { - // SAFETY: a plain query; another window gives null. - unsafe { wm::GetPropW(hwnd, STAND_IN) } -} - -/// A title shows its window: shows the stand-in instead. Returns whether it -/// was visible before, as `ShowWindow` does. -pub extern "system" fn ShowWindow(hwnd: HWND, command: i32) -> i32 { - let window = stand_in_of(hwnd); - let target = if window.is_null() { hwnd } else { window }; - // SAFETY: the title's window, or our stand-in for it, whose thread - // always reads its messages, so this never waits long. - unsafe { wm::ShowWindow(target, command) } -} - /// Puts our procedure in front of the title's. fn hook(hwnd: HWND) { if hwnd.is_null() { @@ -451,30 +264,11 @@ extern "system" fn window_proc( // SAFETY: the procedure `hook` stored, called the way the system would. unsafe { let title = wm::GetPropW(hwnd, TITLE_PROC); - let window = stand_in_of(hwnd); if message == wm::WM_NCDESTROY { wm::RemovePropW(hwnd, TITLE_PROC); - if !window.is_null() { - wm::RemovePropW(hwnd, STAND_IN); - wm::PostMessageW(window, DESTROY_STAND_IN, 0, 0); - } } let title = std::mem::transmute::<*mut c_void, wm::WNDPROC>(title); - let result = wm::CallWindowProcW(title, hwnd, message, wparam, lparam); - // The stand-in shows the title's text. Its thread never waits for - // the title's, so this cannot deadlock. - if message == wm::WM_SETTEXT && !window.is_null() { - wm::SendMessageTimeoutW( - window, - wm::WM_SETTEXT, - 0, - lparam, - wm::SMTO_ABORTIFHUNG, - 1000, - std::ptr::null_mut(), - ); - } - result + wm::CallWindowProcW(title, hwnd, message, wparam, lparam) } } @@ -604,7 +398,6 @@ pub(crate) fn module() -> HleModule { hle_export!(UnregisterAppConstrainedChangeNotification), hle_export!(CreateWindowExW), hle_export!(CreateWindowExA), - hle_export!(ShowWindow), ], } } @@ -767,113 +560,6 @@ mod tests { } } - /// Whether `hwnd`'s thread answers a message within `ms`. - fn answers(hwnd: HWND, ms: u32) -> bool { - let mut result = 0; - // SAFETY: a plain message with a timeout. - unsafe { - wm::SendMessageTimeoutW(hwnd, wm::WM_NULL, 0, 0, wm::SMTO_NORMAL, ms, &mut result) != 0 - } - } - - fn thread_of(hwnd: HWND) -> u32 { - // SAFETY: a plain query. - unsafe { wm::GetWindowThreadProcessId(hwnd, std::ptr::null_mut()) } - } - - #[test] - fn a_title_window_is_shown_through_a_stand_in_that_always_answers() { - // A "title thread" makes its window and then stops reading messages - // for a while, as a title does in a slow frame or a load. - let (made, window) = std::sync::mpsc::channel(); - let (done, finish) = std::sync::mpsc::channel::<()>(); - let title = std::thread::spawn(move || { - let null = std::ptr::null_mut(); - let hwnd = CreateWindowExW( - 0, - w!("STATIC"), - w!("stand-in"), - 0, - 0, - 0, - 10, - 10, - null, - null, - null, - std::ptr::null(), - ); - made.send(hwnd as usize).unwrap(); - let _ = finish.recv(); - // SAFETY: this thread's window. - unsafe { wm::DestroyWindow(hwnd) }; - }); - let hwnd = window.recv().unwrap() as HWND; - assert!(!hwnd.is_null()); - let stand_in = stand_in_of(hwnd); - assert!(!stand_in.is_null()); - // SAFETY: plain queries of the two windows. - unsafe { - // The title's window is message-only: it can never be shown. - assert_ne!(wm::GetAncestor(hwnd, wm::GA_PARENT), wm::GetDesktopWindow()); - assert_eq!( - wm::GetAncestor(stand_in, wm::GA_PARENT), - wm::GetDesktopWindow() - ); - assert_eq!(wm::IsWindowVisible(hwnd), 0); - let mut text = [0u16; 16]; - let n = wm::GetWindowTextW(stand_in, text.as_mut_ptr(), 16); - assert_eq!(String::from_utf16_lossy(&text[..n as usize]), "stand-in"); - } - assert_ne!(thread_of(stand_in), thread_of(hwnd)); - assert!(!answers(hwnd, 200), "the title's thread is not reading"); - assert!(answers(stand_in, 1000), "the stand-in's thread always is"); - done.send(()).unwrap(); - title.join().unwrap(); - // The stand-in goes with the title's window. - let gone = (0..100).any(|_| { - std::thread::sleep(Duration::from_millis(10)); - // SAFETY: a plain query; a destroyed handle gives false. - unsafe { wm::IsWindow(stand_in) == 0 } - }); - assert!(gone); - } - - #[test] - fn showing_a_title_window_shows_its_stand_in() { - let null = std::ptr::null_mut(); - let hwnd = CreateWindowExW( - 0, - w!("STATIC"), - w!("show"), - wm::WS_OVERLAPPEDWINDOW, - 0, - 0, - 10, - 10, - null, - null, - null, - std::ptr::null(), - ); - let stand_in = stand_in_of(hwnd); - assert!(!stand_in.is_null()); - // SAFETY: our windows. Minimised and not activated, so the test - // takes no focus from anything. - unsafe { - assert_eq!(ShowWindow(hwnd, wm::SW_SHOWMINNOACTIVE), 0); - assert_ne!(wm::IsWindowVisible(stand_in), 0); - assert_ne!(wm::IsIconic(stand_in), 0); - assert_eq!(wm::IsWindowVisible(hwnd), 0); - // The title's text follows it to the stand-in. - wm::SetWindowTextW(hwnd, w!("renamed")); - let mut text = [0u16; 16]; - let n = wm::GetWindowTextW(stand_in, text.as_mut_ptr(), 16); - assert_eq!(String::from_utf16_lossy(&text[..n as usize]), "renamed"); - wm::DestroyWindow(hwnd); - } - } - thread_local! { /// The system commands `recording` received, low four bits cleared. static COMMANDS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; From 8a8ad353d4d02b09e0116d1d17ef8a7a408d9d16 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 01:15:58 -0600 Subject: [PATCH 297/445] Crash tracing that can stay on: VICTORY_D3D12_DRED=light and =faults; lost texture writes named A removed device is reported by whoever finds it first, and the list it stopped in by its name. The window stand-in of VIctory 9145d9d is left out until it has been tried. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 17 ++- crates/victory-gpu/src/host.rs | 130 +++++++++++++++++++--- 2 files changed, 132 insertions(+), 15 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 397b984..991e8af 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -2815,7 +2815,22 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { // shortcut: unordered access to a texture the title placed // itself is not mirrored; give it a resource as shader // views of such textures get when a dispatch writes one. - once!(dimension = resource[0], "placed unordered texture view not mirrored"); + // Each texture is said once (the first 64), with how many times + // such a view was asked for so far: what shaders write through + // them is lost. + static SAID: Mutex> = Mutex::new(std::collections::BTreeSet::new()); + static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let at = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); + if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() { + tracing::warn!( + address = format_args!("{at:#x}"), + times, + "placed unordered texture view not mirrored (null: writes through it are lost): resource {resource:?}, view {:?}", + &desc[..10] + ); + } return None; } // The resource description's width, after the alignment. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index ebc1264..cd0d229 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -330,10 +330,14 @@ pub(crate) fn removal_context() -> String { /// host device removed. pub(crate) fn log_removal_context() { static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - if !trail_on() || SAID.swap(true, Ordering::Relaxed) { + if !(trail_on() || dred_any()) || SAID.swap(true, Ordering::Relaxed) { return; } tracing::error!("when the host device went: {}", removal_context()); + if dred_any() { + let data = host().map(|h| h.removal_data(&[])).unwrap_or_default(); + tracing::error!("device-removed data{}", if data.is_empty() { "; none" } else { &data }); + } } /// Time spent in submissions since the last frame-rate line, in @@ -580,12 +584,14 @@ fn create() -> windows::core::Result { } // Diagnostics: device-removed data (the command that faulted, the // faulting address), read when the device is removed. - if dred_on() { + if dred_any() { let mut dred: Option = None; if D3D12GetDebugInterface(&mut dred).is_ok() && let Some(dred) = dred { - dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + if dred_on() || dred_light() { + dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + } dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); } } @@ -705,6 +711,18 @@ pub(crate) fn warp_adapter() -> windows::core::Result { #[cfg(test)] mod tests { + /// A list of ours is found by its name, with the debug layer's note or not. + #[cfg(feature = "diagnostics")] + #[test] + fn a_list_is_found_by_the_number_in_its_name() { + assert_eq!(super::list_number("victory host list 7"), Some(7)); + assert_eq!(super::list_number("victory host list 158 (debug layer indirect)"), Some(158)); + assert_eq!(super::list_number("victory host list 7x"), None); + assert_eq!(super::list_number("victory host list 7 x"), None); + assert_eq!(super::list_number("another list 7"), None); + assert_eq!(super::list_number(""), None); + } + /// What is there of a range some of whose pages are not: those bytes, /// counted, and zeros for the rest, whatever the buffer held. #[test] @@ -846,7 +864,7 @@ pub(crate) struct HostList { /// when the list first has such transitions ([`lazy_prelude`]). prelude: OnceLock>, /// The pipelines the list binds, for reports of slow submissions. - pipelines: Mutex>, + pipelines: std::sync::Arc>>, /// The work its indirect executions may still do (`indirect`): a /// shader-writable word, zeroed when the list is submitted, and after /// it what the clamp notes about mesh records. In memory the CPU maps. @@ -866,7 +884,7 @@ pub(crate) struct HostList { /// The texts of the markers `note_op` set, in order (for device-removed /// data without marker texts), with the host GPU range a copy reads. #[cfg(feature = "diagnostics")] - notes: Mutex>, + notes: std::sync::Arc>>, /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command /// and at the end, and where they are read back. #[cfg(feature = "diagnostics")] @@ -1327,7 +1345,51 @@ fn record_twin_copy( /// builds). pub(crate) fn dred_on() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DRED")) + *ON.get_or_init(|| cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DRED") && !dred_faults() && !dred_light()) +} + +/// Breadcrumbs and the faulting address, but no markers and no texts +/// (`VICTORY_D3D12_DRED=light`): which list a removed device stopped in, at +/// which of its commands, and the pipelines the list binds; formatting a text +/// for every command is what makes the whole of it slow. +pub(crate) fn dred_light() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "light") + }) +} + +/// Any of the three. +pub(crate) fn dred_any() -> bool { + dred_on() || dred_light() || dred_faults() +} + +/// Whether only the faulting address of a removed device is kept +/// (`VICTORY_D3D12_DRED=faults`): no breadcrumbs, no markers and no texts, so +/// it costs next to nothing and can stay on while the title is played. +pub(crate) fn dred_faults() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "faults") + }) +} + +/// The lists alive while device-removed data is on, by the number their name +/// ends in, with their marker texts and the pipelines they bind: a report made +/// on another thread than the one that submits has no lists of its own. +#[cfg(feature = "diagnostics")] +#[allow(clippy::type_complexity)] +static LIST_NOTES: Mutex< + std::collections::BTreeMap>>, std::sync::Weak>>)>, +> = Mutex::new(std::collections::BTreeMap::new()); + +/// The number in the name of a list of ours ("victory host list 7", which the +/// debug layer ends with a note of its own in brackets). +#[cfg(feature = "diagnostics")] +fn list_number(name: &str) -> Option { + let rest = name.strip_prefix("victory host list ")?; + let digits = rest.split(' ').next()?; + (rest.len() == digits.len() || rest[digits.len()..].starts_with(" (")).then(|| digits.parse().ok()).flatten() } /// Indirect mesh dispatches since the last frame line: the largest group @@ -1362,7 +1424,7 @@ pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) { if crate::replay::record::on() { let text = text(); crate::replay::record::name(object, &text); - if dred_on() + if dred_any() && let Ok(object) = object.cast::() { // SAFETY: a plain call on a live object. @@ -1370,7 +1432,7 @@ pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) { } return; } - if dred_on() + if dred_any() && let Ok(object) = object.cast::() { // SAFETY: a plain call on a live object. @@ -3432,6 +3494,20 @@ impl Host { if !lazy_prelude() { let _ = prelude.set(self.make_prelude()); } + #[cfg(feature = "diagnostics")] + let notes = std::sync::Arc::>>::default(); + let pipelines = std::sync::Arc::>>::default(); + #[cfg(feature = "diagnostics")] + if dred_on() || dred_light() { + static NUMBER: AtomicU32 = AtomicU32::new(0); + let number = NUMBER.fetch_add(1, Ordering::Relaxed); + name(&list, || format!("victory host list {number}")); + let mut all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()); + if number.is_multiple_of(256) { + all.retain(|_, l| l.0.strong_count() > 0); + } + all.insert(number, (std::sync::Arc::downgrade(¬es), std::sync::Arc::downgrade(&pipelines))); + } Ok(HostList { allocator, list, @@ -3440,14 +3516,14 @@ impl Host { states: Mutex::default(), twins: Mutex::default(), prelude, - pipelines: Mutex::default(), + pipelines, budget: OnceLock::new(), card_budget: OnceLock::new(), indirect_args: Mutex::default(), batch_args: Mutex::default(), _alive: Counted::new(), #[cfg(feature = "diagnostics")] - notes: Mutex::default(), + notes, #[cfg(feature = "diagnostics")] stamps: OnceLock::new(), }) @@ -5123,6 +5199,9 @@ impl Host { } // The plain output: the extended one (with marker texts) came // back without stopped lists on this host. + if dred_faults() { + return text; + } let crumbs = match dred.GetAutoBreadcrumbsOutput() { Ok(crumbs) => crumbs, Err(e) => { @@ -5153,10 +5232,33 @@ impl Host { )); let list = p.pCommandList.as_ref().map(|l| l.as_raw()); let run = runs.iter().find(|r| Some(r.list.as_raw()) == list); + let named = [ + (!p.pCommandListDebugNameW.is_null()).then(|| p.pCommandListDebugNameW.to_string().unwrap_or_default()), + (!p.pCommandListDebugNameA.is_null()).then(|| { + std::ffi::CStr::from_ptr(p.pCommandListDebugNameA.cast()).to_string_lossy().into_owned() + }), + ] + .into_iter() + .flatten() + .next() + .unwrap_or_default(); + text.push_str(&format!(" of \"{named}\"")); + // Not one of the caller's: by the name. + #[cfg(feature = "diagnostics")] + let by_name = list_number(&named).and_then(|n| { + let all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()); + all.get(&n).map(|(notes, pipelines)| (notes.upgrade(), pipelines.upgrade())) + }); + #[cfg(not(feature = "diagnostics"))] + #[allow(clippy::type_complexity)] + let by_name: Option<(Option<()>, Option>>>)> = None; + #[cfg(feature = "diagnostics")] + let noted = run.map(|r| r.notes.clone()).or_else(|| by_name.as_ref().and_then(|b| b.0.clone())); + let bound = run.map(|r| r.pipelines.clone()).or_else(|| by_name.as_ref().and_then(|b| b.1.clone())); // The k-th marker command is the k-th note. #[cfg(feature = "diagnostics")] - let markers: Vec<(u32, String)> = run.map_or_else(Vec::new, |r| { - let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); + let markers: Vec<(u32, String)> = noted.map_or_else(Vec::new, |notes| { + let notes = notes.lock().unwrap_or_else(|e| e.into_inner()); history .iter() .enumerate() @@ -5174,8 +5276,8 @@ impl Host { let _ = fault_va; if done > 0 { text.push_str(&in_flight(history, &markers, done as usize)); - } else if let Some(r) = run { - let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner()); + } else if let Some(bound) = bound { + let pipelines = bound.lock().unwrap_or_else(|e| e.into_inner()); text.push_str(&format!(", its pipelines {pipelines:?}")); } } From 1c8dd3156d3a43b07fdf07f9d09aa5d3b15a2514 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 01:52:09 -0600 Subject: [PATCH 298/445] Pixel programs read their quad's neighbours with quad operations: helper lanes take no part in wave reads The lamps' shadow maps write depth plus a slope bias, and the main pass takes the normal's derivatives, from the quad's other lanes; a wave read of a helper lane is undefined (0 on AMD): holes in shadows, dashed triangle edges. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 76 ++++++++++++ crates/victory-shader/src/emit/mod.rs | 149 +++++++++++++++++++++++- 2 files changed, 223 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index d4b0163..6a86f71 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4507,6 +4507,71 @@ impl<'a> Lower<'a> { r } + /// Whether a quad-local read takes its lane with the host's quad + /// operations: in a pixel program always. Lanes of a quad the primitive + /// does not cover, or that were discarded, are helpers on the host; + /// wave reads leave those out (AMD gives 0 from them), quad reads are + /// what reaches them. + fn helpers_read(&self, quad: bool) -> bool { + quad && self.s.pixel + } + + /// `x` of the lane of this lane's quad that `lanes` names for each of + /// the quad's four, by the host's quad operations. + fn quad_read(&mut self, x: V, lanes: [u8; 4]) -> V { + self.s.flags |= flags::WAVE_OPS; + let c = self.cur; + let i32t = self.s.t.i32; + if lanes == [0, 1, 2, 3] { + return x; + } + // One lane for all. + if lanes.iter().all(|&l| l == lanes[0]) { + let n = self.s.m.i32(lanes[0].into()); + return self.s.op( + c, + "quadReadLaneAt.i32", + Attr::NoUnwind, + i32t, + 122, + &[x, n], + ); + } + // Else each lane's own, its neighbour across in x (1) or y (2), or + // the diagonal one (3). + let across = |i: usize| i as u8 ^ lanes[i]; + let mut r = None; + for by in 0..4u8 { + if !(0..4).any(|i| across(i) == by) { + continue; + } + let read = if by == 0 { + x + } else { + // QuadReadAcrossX, Y, Diagonal. + let kind = self.s.m.i8(by - 1); + self.s + .op(c, "quadOp.i32", Attr::NoUnwind, i32t, 123, &[x, kind]) + }; + r = Some(match r { + None => read, + Some(r) => { + let mut here = self.s.m.bool(false); + let lane = self.lane_index(); + let three = self.s.m.i32(3); + let at = self.s.m.bin(c, Bin::And, lane, three); + for i in (0..4).filter(|&i| across(i) == by) { + let k = self.s.m.i32(i as u32); + let is = self.s.m.cmp(c, pred::EQ, at, k); + here = self.s.m.bin(c, Bin::Or, here, is); + } + self.s.m.select(c, here, read, r) + } + }); + } + r.unwrap_or(x) + } + /// `x` in the first lane of this host wave where `guard` holds, and whether it has such a /// lane: the console reads the first lane of EXEC, and a lane that got here with EXEC clear /// (a guard, not a branch) is not one. With none, `x` of the wave's first lane here. @@ -4652,6 +4717,13 @@ impl<'a> Lower<'a> { }; let r = if mesh_quad { self.quad_pick(x, src) + } else if self.helpers_read(quad) { + let lanes = if offset & 0x8000 != 0 { + [0, 1, 2, 3].map(|i| (offset >> (2 * i) & 3) as u8) + } else { + [0, 1, 2, 3].map(|i| ((i & offset | offset >> 5 & 3) ^ offset >> 10 & 3) as u8 & 3) + }; + self.quad_read(x, lanes) } else { self.read_lane(x, src) }; @@ -7234,6 +7306,10 @@ impl<'a> Lower<'a> { }; let mut r = if mesh_quad { self.quad_pick(x, src) + } else if let Dpp::Row { ctrl, .. } = dpp + && self.helpers_read(quad) + { + self.quad_read(x, [0, 1, 2, 3].map(|i| (ctrl >> (2 * i) & 3) as u8)) } else { self.read_lane(x, src) }; diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index b9f52c4..c9c727e 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -1485,6 +1485,142 @@ mod tests { assert_eq!(c[4..20], ours[..], "our hash differs from the validator's"); } + /// A pixel program of `words` with no user data. + fn emit_native(words: &[u32], input_addr: u32) -> NativeProgram { + NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 4, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } + } + + /// A pixel program that takes its neighbour's position across its quad + /// (`ds_swizzle_b32`, as the console's compiler makes derivatives) and + /// exports the differences in x and y: 1 and -1 in every pixel of a + /// triangle, those at its edges too, whose neighbours are helpers. + #[test] + #[cfg(windows)] + fn quad_neighbours_at_a_triangles_edge_are_read() { + use super::host::{Draw, Host, Root}; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_SHADER_VISIBILITY_MESH, D3D12_SHADER_VISIBILITY_PIXEL, + }; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + // v2, v3: position x, y (input address: POS_X and POS_Y after the + // two perspective barycentrics). + let swizzle = |dst: u32, src: u32, pattern: u32| { + [ + 0xD800_0000 | 0x35 << 18 | 0x8000 | pattern, + dst << 24 | src, + ] + }; + let mut words = vec![0xBEFC_0380u32]; // s_mov_b32 m0, 0 + words.extend(swizzle(4, 2, 0xB1)); // lanes 1 0 3 2 + words.extend(swizzle(5, 3, 0x4E)); // lanes 2 3 0 1 + words.extend(swizzle(6, 2, 0xA0)); // lanes 0 0 2 2 + words.extend([ + 0x0808_0504, // v_sub_f32 v4, v4, v2 + 0x080A_0705, // v_sub_f32 v5, v5, v3 + 0x080C_0506, // v_sub_f32 v6, v6, v2 + 0xF800_180F, + 0x0302_0504, // exp mrt0 v4, v5, v2, v3 done vm + 0xBF81_0000, + ]); + let _ = 6; + let mut native = emit_native(&words, 1 << 1 | 1 << 8 | 1 << 9); + native.vgprs = 8; + let out = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }; + let position = SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 4, + row: Some(0), + col: 0, + cols: 4, + usage: 3, + half: false, + }; + let isg1 = container::signature(&[position], true); + let osg1 = container::signature(&[out], false); + let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let ps = emit(&c, &native, &p, &st, &io, &res).unwrap(); + if let Some(path) = super::validator::Validator::default_path() { + let mut v = super::validator::Validator::load(Some(&path)).unwrap(); + v.validate(&mut ps.dxil.clone()).unwrap(); + } + let ms = triangle_mesh_to(TRIANGLE, 1.3).unwrap(); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + continue; + }; + let Ok(root) = host.root_signature_for(&[ + (&ms, D3D12_SHADER_VISIBILITY_MESH), + (&ps, D3D12_SHADER_VISIBILITY_PIXEL), + ]) else { + continue; + }; + let Ok(pso) = host.mesh_pipeline_with(&root, &ms.dxil, &ps.dxil) else { + eprintln!("no mesh pipeline on {label}; skipped"); + continue; + }; + let texels = host + .draw( + &root, + &pso, + &Draw { + roots: vec![(0, Root::Constants(vec![0])), (1, Root::Constants(vec![0]))], + textures: &[], + samplers: &[], + vertices: &[], + stride: 0, + size: (16, 16), + mesh_groups: 1, + }, + ) + .unwrap_or_else(|e| panic!("{label}: draw: {e}")); + let lit: Vec<(usize, &[f32; 4])> = texels.iter().enumerate().filter(|t| t.1[2] != 0.0).collect(); + assert!((20..240).contains(&lit.len()), "{label}: {} texels lit", lit.len()); + let bad: Vec<_> = lit + .iter() + .filter(|(n, t)| { + let x = if n % 2 == 0 { 1.0 } else { -1.0 }; + let y = if n / 16 % 2 == 0 { 1.0 } else { -1.0 }; + (t[0], t[1]) != (x, y) + }) + .collect(); + assert!(bad.is_empty(), "{label}: {} of {} texels: {:?}", bad.len(), lit.len(), bad[0]); + } + } + /// Triangle (0, 1, 2), each corner's 9-bit index in its 10-bit field. const TRIANGLE: u32 = 1 << 10 | 2 << 20; /// The edge flags of the three corners (bits 9, 19 and 29). @@ -1497,6 +1633,13 @@ mod tests { /// (lane & 1 ? 3 : -1, lane & 2 ? 3 : -1, 0.5, 1): triangle (0, 1, 2) /// covers the whole target. fn triangle_mesh(prim: u32) -> Result { + triangle_mesh_to(prim, 4.0) + } + + /// The triangle with its far corners at `reach` - 1. + fn triangle_mesh_to(prim: u32, reach: f32) -> Result { + // (the second corner's y comes out as 2 x its lane bit: half of it) + let [x, y] = [reach.to_bits(), (reach / 2.0).to_bits()]; let words = [ 0xD765_0001u32, // v_mbcnt_lo_u32_b32 v1, -1, 0 0x0001_00C1, @@ -1504,9 +1647,11 @@ mod tests { 0x3606_0282, // v_and_b32 v3, 2, v1 0x7E04_0D02, // v_cvt_f32_u32 v2, v2 0x7E06_0D03, // v_cvt_f32_u32 v3, v3 - 0x1008_04F6, // v_mul_f32 v4, 4.0, v2 + 0x1008_04FF, // v_mul_f32 v4, reach, v2 + x, 0x0608_08F3, // v_add_f32 v4, -1.0, v4 - 0x100A_06F4, // v_mul_f32 v5, 2.0, v3 + 0x100A_06FF, // v_mul_f32 v5, reach / 2, v3 + y, 0x060A_0AF3, // v_add_f32 v5, -1.0, v5 0x7E0C_02F0, // v_mov_b32 v6, 0.5 0x7E0E_02F2, // v_mov_b32 v7, 1.0 From 1f1a43367687dc5f45734a2beffa39b8473012b0 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 01:52:09 -0600 Subject: [PATCH 299/445] Speed and room: draws' own records left to the draws in the heap sync, 2^20 table slots, textures kept while the card has room - VICTORY_HEAP_SYNC=all mirrors every copied record at once, as before. - VICTORY_DYNAMIC_SLOTS sets the table slots past the title's. - Room kept for card copies of buffers is 1 GiB at most (was 5 GiB on 24 GB). - VICTORY_TEXTURE_KEEP=0 lets idle textures go after 5 s, as before. - VICTORY_TEXTURE_AWAY_MS: a texture whose memory went is shown 3 s longer. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 86 +++++++--- crates/victory-gpu/src/descriptor/host.rs | 190 ++++++++++++++++++---- crates/victory-gpu/src/draw.rs | 15 ++ crates/victory-gpu/src/host.rs | 27 ++- crates/victory-gpu/src/shadow.rs | 8 +- 5 files changed, 270 insertions(+), 56 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 069c82f..39e8b68 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -178,8 +178,11 @@ pub(crate) fn sync_heaps() { return; } let started = std::time::Instant::now(); - let (mut pages, mut looked, mut mirrored) = (0u64, 0u64, 0u64); + let (mut pages, mut looked, mut mirrored, mut tabled, mut later) = (0u64, 0u64, 0u64, 0u64, 0u64); let mut page_bytes: Vec = Vec::new(); + let mut changed: Vec = Vec::new(); + let mut wait: Vec = Vec::new(); + let frame = crate::frame::current(); let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); for &(start, end, at) in heaps.iter() { // SAFETY: registered heaps are live (removed when dropped). @@ -193,6 +196,16 @@ pub(crate) fn sync_heaps() { // Capped host heaps have no counterparts for the title slots reserved // for per-draw tables; raw writes there must not be mirrored. 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; + } + } 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 { @@ -205,54 +218,87 @@ pub(crate) fn sync_heaps() { if crate::host::read_into(from as *const u8, &mut page_bytes) { pages += 1; let slots = changed_slots(from, to, start as usize, step, mirrored_count); - for index in slots { - let handle = start + index * step; - // A record that straddles the range's ends is left - // to the range that holds its first byte. - let Some(at) = (handle as usize).checked_sub(from) else { - continue; + // A record that straddles the range's ends is left + // to the range that holds its first byte. + let first = ((from - start as usize) as u64).div_ceil(step).max(slots.start); + let Some(records) = page_bytes.get((start + first * step) as usize - from..) else { + page += crate::watch::PAGE; + continue; + }; + let count = (records.len() as u64 / step).min(slots.end.saturating_sub(first)); + looked += count; + // Only the records that are not the ones last seen + // there (`HostHeap::copied_changes`). + changed.clear(); + host.copied_changes(first as u32, &records[..(count * step) as usize], step as usize, &mut changed); + for &index in &changed { + let at = (u64::from(index) - first) as usize * step as usize; + let word = |n: usize| { + records + .get(at + 4 * n..at + 4 * n + 4) + .and_then(|b| b.try_into().ok()) + .map_or(0, u32::from_le_bytes) }; - let Some(record) = page_bytes.get(at..at + step as usize) else { - continue; - }; - looked += 1; - // Only a record that is not the one last seen there - // (`HostHeap::mirror_copied`). - if host.mirror_copied(index as u32, handle, record) { - mirrored += 1; + if !heap.samplers() && word(0) == VIEW_TAG { + // A draw's own table: the draw makes what it + // reads of it (`draw.rs` `tables`). + if host.copied_tabled(index, frame) { + tabled += 1; + continue; + } + // Buffer views and placed textures get no host + // slot from this anyway, they wait for a draw + // or a pass: noted some frames on, unless a + // draw's table turns out to hold them. + if matches!(word(2) >> KIND_SHIFT, CONSTANT | PLACED) && host.copied_waits() { + wait.push(index); + later += 1; + continue; + } } + host.mirror(index, start + u64::from(index) * step, false); + mirrored += 1; } } page += crate::watch::PAGE; } } + if !wait.is_empty() { + host.copied_wait(frame, std::mem::take(&mut wait)); + } } drop(heaps); - for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, started.elapsed().as_micros() as u64]) { + let micros = started.elapsed().as_micros() as u64; + for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, micros, tabled, later]) { count.fetch_add(n, Relaxed); } } /// 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 (mirrored), and the microseconds it took. +/// not the one last seen and was mirrored, the microseconds it took; then +/// new records left to the draws that read them through a table, and new +/// records that waited for one ([`host::HostHeap::copied_wait`]). #[cfg(windows)] -pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; +pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; /// With the frame line: what [`sync_heaps`] did per frame over `frames`. /// Nothing while no heap page changed. #[cfg(windows)] pub(crate) fn sync_line(frames: f64) { - let [pages, looked, mirrored, micros] = [0, 1, 2, 3].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + let [pages, looked, mirrored, micros, tabled, later] = [0, 1, 2, 3, 4, 5].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); 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, {:.2} ms", + {:.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", 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 ); } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 991e8af..5aac724 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -26,10 +26,17 @@ pub(crate) struct HostHeap { sampler: bool, /// The record (view index and generation) each slot was last made from. made: Mutex>, - /// A fingerprint of the record each slot held when the pass over - /// records copied in as bytes last looked at it - /// ([`HostHeap::mirror_copied`]; 0: never looked at). Made on first use. - copied: Mutex>, + /// The records of the title's heap as the pass over records copied in + /// as bytes last saw them ([`HostHeap::copied_changes`]). Made on first + /// use. + copied: Mutex>, + /// New ones of them that wait for a draw ([`HostHeap::copied_wait`]), + /// by the frame they were found in. + waiting: Mutex)>>, + /// The slots made from a texture whose memory was found away, with what + /// they were made from and when that was + /// ([`HostHeap::texture_slot_gone`]). + away: Mutex>, /// The host resource each slot views, held while the slot does: shaders /// index heaps directly, so a slot the title has not rewritten since it /// released the resource may still be read, and a freed host resource @@ -513,6 +520,14 @@ const TABLED_FRAMES: u64 = 240; /// (435 begun in the 353 s of run 52's, for some 140 presented). const TABLED_GRACE: u64 = 8; +/// Frames for which a record copied into a slot a draw read through a +/// table is left to such a draw ([`HostHeap::copied_tabled`]). +const COPIED_FRAMES: u32 = 8; + +/// Frames a record copied into any other slot waits for one, before it is +/// taken for one shaders pick by index ([`HostHeap::copied_wait`]). +const COPIED_GRACE: u64 = 4; + /// In [`HostHeap::tabled`]: a draw read the slot in that frame. const TABLED_READ: u32 = 1 << 31; @@ -940,6 +955,26 @@ pub(crate) fn probe_view_limit() { /// table past them is made afresh in these slots like any other. pub(crate) const DYNAMIC: u32 = 1 << 18; +/// [`DYNAMIC`] for a heap of `count` title slots whose null slot is `null` +/// (0: none): up to four times as many where the host heap has the room (a +/// host that takes more than [`PORTABLE_VIEWS`]; `VICTORY_DYNAMIC_SLOTS` +/// sets the most). 2^18 ran out in the title's bigger places (session +/// play-1125-0127: 27,000 to 35,000 tables a frame, up to 3,285 of them +/// refused, with 2,639 indirect draws and dispatches). +fn dynamic_slots(count: u32, null: u32) -> u32 { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + let most = *MOST.get_or_init(|| { + std::env::var("VICTORY_DYNAMIC_SLOTS") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(DYNAMIC << 2) + }); + if null < PORTABLE_VIEWS { + return DYNAMIC; + } + null.saturating_sub(count).min(most).max(DYNAMIC) +} + impl HostHeap { pub(crate) fn new(sampler: bool, count: u32) -> Option { let host = host()?; @@ -960,7 +995,6 @@ impl HostHeap { }) } }; - let extra = if sampler { 0 } else { DYNAMIC }; // A view heap ends at the null slot shaders clamp view indices to // (`probe_view_limit`), whatever the title's own count: the title's // slots, then the dynamic ones, then null up to and with that slot. @@ -972,6 +1006,7 @@ impl HostHeap { } else { victory_shader::emit::view_heap_limit() }; + let extra = if sampler { 0 } else { dynamic_slots(count, null) }; let (heap, count, size) = if null == 0 { match make(count + extra) { Ok(heap) => (heap, count, count + extra), @@ -1036,9 +1071,11 @@ impl HostHeap { sampler, made: Mutex::new(vec![0; count as usize]), copied: Mutex::new(Vec::new()), + waiting: Mutex::default(), + away: Mutex::default(), kept: Mutex::new(vec![None; (count + extra) as usize]), - next: Mutex::new((0, vec![false; DYNAMIC as usize])), - free: std::sync::atomic::AtomicU32::new(DYNAMIC), + next: Mutex::new((0, vec![false; extra as usize])), + free: std::sync::atomic::AtomicU32::new(extra), too_long: std::sync::atomic::AtomicU32::new(u32::MAX), strides, buffers: Mutex::default(), @@ -1186,7 +1223,7 @@ impl HostHeap { crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64); taken[first..first + n].fill(true); self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed); - *next = ((first + n) % DYNAMIC as usize) as u32; + *next = ((first + n) % end) as u32; Some(self.count + first as u32) } @@ -1520,16 +1557,52 @@ impl HostHeap { /// (any more): a host slot made from it becomes null again, so that /// the host copy can be let go (`crate::resource::let_go_idle`; a slot /// keeps what it views). True if the slot was made. + /// + /// Not at the first look: a title that moves a texture in its streaming + /// memory unmaps it before it maps it again, and what was shown went + /// black for the pictures in between (session play-1125-0127: faces, + /// books, posters and sleeves for 0.3 to 2 s). Only when it is still + /// away `AWAY_MS` after it was first found away + /// (`VICTORY_TEXTURE_AWAY_MS`; 0: at once, as before). pub(crate) fn texture_slot_gone(&self, index: u32) -> bool { + const AWAY_MS: u64 = 3000; + static WAIT: std::sync::OnceLock = std::sync::OnceLock::new(); + 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()); - if made.get(index as usize).is_none_or(|&key| key == 0) { + let Some(key) = made.get(index as usize).copied().filter(|&key| key != 0) else { return false; + }; + let now = crate::host::now_ms(); + { + let mut away = self.away.lock().unwrap_or_else(|e| e.into_inner()); + match away.get(&index) { + Some(&(was, since)) if was == key && now.saturating_sub(since) < wait => return false, + Some(&(was, _)) if was == key => { + away.remove(&index); + } + _ if wait == 0 => {} + _ => { + away.insert(index, (key, now)); + return false; + } + } } self.unmake(&mut made, index); STALE[4].fetch_add(1, std::sync::atomic::Ordering::Relaxed); true } + /// The memory of the texture title slot `index` views is there (again): + /// see [`HostHeap::texture_slot_gone`]. + pub(crate) fn texture_slot_here(&self, index: u32) { + let mut away = self.away.lock().unwrap_or_else(|e| e.into_inner()); + if !away.is_empty() { + away.remove(&index); + } + } + /// 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) { @@ -1623,6 +1696,12 @@ impl HostHeap { } } + /// Title slot `index` lies in a table a draw reads or had made afresh: + /// what it holds is the draw's to make ([`HostHeap::copied_tabled`]). + pub(crate) fn slot_tabled(&self, index: u32) { + self.tabled_in(index, false, crate::frame::current()); + } + /// 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()); @@ -1913,10 +1992,10 @@ impl HostHeap { } } - /// For a slot on a page of the title's heap that changed with no call + /// For a run of records of the title's heap from slot `first`, `step` + /// bytes each, on a page that changed with no call /// (`super::sync_heaps`: the title copies records into its heap as - /// bytes): [`HostHeap::mirror`], if the `bytes` bytes of the record at - /// `handle` are not the ones this last saw there. True if it did. + /// bytes): the slots whose record is not the one this last saw there. /// /// The page says only that something on it was written, and `mirror` /// by itself would take every buffer or placed-texture record on it for @@ -1924,32 +2003,77 @@ impl HostHeap { /// or a pass uses it): the texture queue's entry for the slot would /// start again, and the buffer pass would look at 2,048 slots for one /// that changed. - /// `record`: the record's bytes as the caller read them (through the + /// `records`: their bytes as the caller read them (through the /// kernel, which fails on a page the title unmapped meanwhile where a /// read in place would fault: the title unmaps heap pages too). - pub(crate) fn mirror_copied(&self, index: u32, handle: u64, record: &[u8]) -> bool { - if index >= self.count { + pub(crate) fn copied_changes(&self, first: u32, records: &[u8], step: usize, out: &mut Vec) { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if copied.is_empty() { + // Nothing there: a slot never looked at that holds nothing is + // as it was. + copied.resize(self.count as usize * step, 0); + } + let at = first as usize * step; + let end = (at + records.len()).min(copied.len()); + let Some(last) = copied.get_mut(at..end) else { + return; + }; + let records = &records[..last.len()]; + if last == records { + return; + } + for (n, (old, new)) in last.chunks_exact_mut(step).zip(records.chunks_exact(step)).enumerate() { + if old != new { + old.copy_from_slice(new); + out.push(first + n as u32); + } + } + } + + /// Whether new records of draws' tables are left to the draws + /// (`VICTORY_HEAP_SYNC=all`: every new record is mirrored at once, as + /// it first was). + /// + /// The title builds each draw's tables in its heap by copying records + /// there as bytes: 60,000 to 210,000 a frame in its world (session + /// play-1125-0127), 0.9 microseconds each on the submitting thread and + /// 1.4 more in the buffer pass they were all handed to, 120 to 600 ms + /// of every frame, and the draws make what they read of them anyway. + pub(crate) fn copied_waits(&self) -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC").is_none_or(|v| v != "all")) + } + + /// Whether a draw read title slot `index` through a table within the + /// last few frames before `frame` ([`HostHeap::tabled`]): what it holds + /// is such a draw's to make. + pub(crate) fn copied_tabled(&self, index: u32, frame: u64) -> bool { + if !self.copied_waits() { return false; } - let n = record.len(); - // Never 0, which is "never looked at". - let print = u64::from_le_bytes(blake3::hash(record).as_bytes()[..8].try_into().unwrap_or([1; 8])) | 1; - { - let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - if copied.is_empty() { - copied.resize(self.count as usize, 0); - } - let Some(last) = copied.get_mut(index as usize) else { - return false; - }; - // A slot never looked at that holds nothing: as it was. - if *last == print || (*last == 0 && record[..n].iter().all(|&b| b == 0)) { - return false; - } - *last = print; + let stamp = self.tabled_stamp(index) & !TABLED_READ; + let now = (frame as u32).wrapping_add(1) & !TABLED_READ; + stamp != 0 && now.wrapping_sub(stamp) & !TABLED_READ <= COPIED_FRAMES + } + + /// 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) { + self.waiting.lock().unwrap_or_else(|e| e.into_inner()).push_back((frame, slots)); + } + + /// The slots that have waited long enough at `frame` + /// ([`HostHeap::copied_wait`]), each once. + pub(crate) fn copied_before(&self, frame: u64) -> Vec { + let mut waiting = self.waiting.lock().unwrap_or_else(|e| e.into_inner()); + let mut out = Vec::new(); + while waiting.front().is_some_and(|(written, _)| written + COPIED_GRACE <= frame) { + out.extend(waiting.pop_front().into_iter().flat_map(|(_, slots)| slots)); } - self.mirror(index, handle, false); - true + drop(waiting); + out.sort_unstable(); + out.dedup(); + out } /// Makes host slot `index` from the record the title has at `handle` diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 6c02828..2b6f8a0 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1646,6 +1646,10 @@ impl State { let mut unordered = Vec::new(); for (n, &index) in slots.iter().enumerate() { ranges.set(index, None); + // 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; }; @@ -2087,6 +2091,7 @@ impl State { host.texture_slot_later(index, write, frame, most); continue; } + host.texture_slot_here(index); if mapped < len { if mapped <= host.texture_slot_mapped(index) { HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed); @@ -2697,6 +2702,8 @@ impl State { // Up to date by this draw: not the texture pass's to make. if crate::descriptor::host::is_texture_view(&view) { host.texture_slot_tabled(index, true); + } else { + host.slot_tabled(index); } } } @@ -2847,6 +2854,14 @@ impl State { // The title's own slots of this table: what the draw reads of // them it brings up to date here, in the dynamic slots. let title_first = heap.index(table).filter(|first| first + n <= host.count()); + // They are such a table's, whatever they hold. (Of a big one, + // which may lie over slots shaders pick by index, only the ones + // the shader names.) + if let Some(title) = title_first { + for k in (0..n).filter(|&k| n <= 64 || entries.iter().any(|u| u.table_offset_dwords / 8 == k)) { + host.slot_tabled(title + k); + } + } // The whole range: a shader may index past the entries its // used-resource list names (descriptor arrays). for k in 0..n { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index cd0d229..21f0ba5 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -120,7 +120,20 @@ pub(crate) fn available_physical_ram() -> Option { /// Effective idle timeout (in milliseconds) for VRAM-backed host textures, /// scaled down under VRAM pressure. Never returns less than 1,000 ms so /// handles not yet recorded into a list or slot remain protected. +/// +/// With room on the card nothing has to go: in session play-1125-0127 88,000 +/// of them (31 GB) went after 5 s with 7 GB of the card free, and 24,700 +/// (12 GB) had to be made and uploaded again. +/// `VICTORY_TEXTURE_KEEP=0`: 5 s there too, as before. pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 { + static KEEP: OnceLock = OnceLock::new(); + let keep = *KEEP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_KEEP").is_none_or(|v| v != "0")); + vram_idle_for(video_memory, keep) +} + +fn vram_idle_for(video_memory: Option<[u64; 4]>, keep: bool) -> u64 { + const KEPT_MS: u64 = 600_000; + const LONG_MS: u64 = 30_000; const NORMAL_MS: u64 = 5_000; const MODERATE_MS: u64 = 2_500; const HIGH_MS: u64 = 1_000; @@ -135,8 +148,12 @@ pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 { HIGH_MS } else if used_pct >= 75 { MODERATE_MS - } else { + } else if !keep { NORMAL_MS + } else if used_pct >= 68 { + LONG_MS + } else { + KEPT_MS } } @@ -8852,8 +8869,14 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at #[test] fn vram_idle_ms_scales_with_pressure() { - use super::vram_idle_ms; + let vram_idle_ms = |memory| super::vram_idle_for(memory, false); + let keeps = |memory| super::vram_idle_for(memory, true); let gib = 1024 * 1024 * 1024; + assert_eq!(keeps(Some([100, 67, 0, 0])), 600_000); + assert_eq!(keeps(Some([100, 68, 0, 0])), 30_000); + assert_eq!(keeps(Some([100, 75, 0, 0])), 2_500); + assert_eq!(keeps(Some([100, 85, 0, 0])), 1_000); + assert_eq!(keeps(None), 5_000); // Normal (< 75%) assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000); assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index fdba9ed..ec17b9e 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -274,7 +274,13 @@ pub(crate) fn card_room_kept() -> u64 { if !card_room_kept_on() || !cards() { return 0; } - card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed)) + // Not more than such copies came to in any session, whatever they may + // come to: on a card of 24 GB a quarter of its budget was kept for them, + // 5 GB that never came (941 MB in 97 copies after fifteen minutes), and + // no texture was made any more with 5 GB of the card free (session + // play-1125-0127: 1,453 passes refused, the ground and people black). + const SEEN: u64 = 1 << 30; + card_limits().1.min(SEEN).saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed)) } /// The copies in the card's memory. From ad30f2cb1f90acb159a981feea9aa1263a9c83d2 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 01:59:21 -0600 Subject: [PATCH 300/445] Shared locks for buffer and window lookups; early pipeline list without a small cap; crash report names what a list binds Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 14 +++- crates/victory-gpu/src/pipeline/library.rs | 2 +- crates/victory-gpu/src/shadow.rs | 79 +++++++++++++++------- 3 files changed, 67 insertions(+), 28 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 21f0ba5..e24be3b 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -610,6 +610,13 @@ fn create() -> windows::core::Result { dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); } dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + tracing::info!( + breadcrumbs = dred_on() || dred_light(), + markers = dred_on(), + "crash tracing on (device-removed data)" + ); + } else { + tracing::warn!("crash tracing asked for and not there: no device-removed data settings"); } } let mut device: Option = None; @@ -5293,7 +5300,12 @@ impl Host { let _ = fault_va; if done > 0 { text.push_str(&in_flight(history, &markers, done as usize)); - } else if let Some(bound) = bound { + } + // (Without markers a list that stopped midway says what + // it may have been at only by what it binds.) + if (done == 0 || markers.is_empty()) + && let Some(bound) = bound + { let pipelines = bound.lock().unwrap_or_else(|e| e.into_inner()); text.push_str(&format!(", its pipelines {pipelines:?}")); } diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 1c04848..fa22cf8 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -435,7 +435,7 @@ const LIBRARY_FILE: &str = "host-pipelines.bin"; const NEXT_FILE: &str = "host-pipelines.next"; const EARLY_FILE: &str = "early-pipelines.txt"; /// Title pipelines listed for an early start, at most. -const EARLY_MAX: usize = 8192; +const EARLY_MAX: usize = 100_000; fn library() -> Option<&'static Library> { static LIBRARY: OnceLock> = OnceLock::new(); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index ec17b9e..8b127df 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -573,8 +573,8 @@ pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc, Vec<(usize, usize)>) /// memory's). Returns the bytes compared. pub(crate) fn stale_pages(most: usize, say: &mut dyn FnMut(&Shadow, usize, usize, (usize, u32, u32))) -> usize { static NEXT: AtomicU64 = AtomicU64::new(0); - let mut all: Vec> = buffers().values().filter_map(|e| e.shadow.clone()).collect(); - all.extend(LOOSE.lock().unwrap_or_else(|e| e.into_inner()).values().cloned()); + let mut all: Vec> = buffers_read().values().filter_map(|e| e.shadow.clone()).collect(); + all.extend(LOOSE.write().unwrap_or_else(|e| e.into_inner()).values().cloned()); all.retain(|s| s.place.is_none() && s.watched.load(Ordering::Relaxed) == 1); all.sort_by_key(|s| s.id); let next = NEXT.load(Ordering::Relaxed); @@ -2397,7 +2397,7 @@ static LET_GO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; #[cfg(feature = "diagnostics")] pub(crate) fn windows() -> [u64; 3] { let asked: u64 = { - let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner()); loose .values() .map(|s| { @@ -2421,7 +2421,7 @@ pub(crate) fn windows() -> [u64; 3] { #[cfg(feature = "diagnostics")] pub(crate) fn window_use() -> [u64; 8] { let mut out = [0u64; 8]; - let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner()); for s in loose.values() { let copied = s.copied.lock().unwrap_or_else(|e| e.into_inner()); let pages = copied.iter().filter(|&&at| at != 0).count() as u64; @@ -2462,7 +2462,7 @@ pub(crate) fn let_go_idle() { let gone: Vec> = { // Held from the look to the removal: `loose` hands a copy out // under the same lock, so none is handed out in between. - let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let mut map = LOOSE.write().unwrap_or_else(|e| e.into_inner()); if map.is_empty() { return; } @@ -2499,7 +2499,7 @@ pub(crate) fn let_go_idle() { #[cfg(feature = "diagnostics")] pub(crate) fn memory() -> [u64; 6] { let (windows, window_bytes) = { - let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner()); // Each copy once: a window may stand under several keys. let mut seen = std::collections::HashSet::new(); let bytes: u64 = loose @@ -4211,10 +4211,17 @@ struct Entry { } /// Title buffers by (start address, resource), with their copy once made. -static BUFFERS: Mutex> = Mutex::new(BTreeMap::new()); +/// +/// Read by every view a draw names, on all recording threads at once, and +/// written when a buffer comes, goes or gets its copy: readers share it. +static BUFFERS: std::sync::RwLock> = std::sync::RwLock::new(BTreeMap::new()); -fn buffers() -> std::sync::MutexGuard<'static, BTreeMap<(u64, usize), Entry>> { - BUFFERS.lock().unwrap_or_else(|e| e.into_inner()) +fn buffers() -> std::sync::RwLockWriteGuard<'static, BTreeMap<(u64, usize), Entry>> { + BUFFERS.write().unwrap_or_else(|e| e.into_inner()) +} + +fn buffers_read() -> std::sync::RwLockReadGuard<'static, BTreeMap<(u64, usize), Entry>> { + BUFFERS.read().unwrap_or_else(|e| e.into_inner()) } /// A title buffer exists at `start` (`len` bytes). @@ -4253,7 +4260,7 @@ pub(crate) fn in_place_let_go(at: u64, len: u64) -> u64 { let end = at.saturating_add(len); let mut gone: Vec> = Vec::new(); { - let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let mut map = LOOSE.write().unwrap_or_else(|e| e.into_inner()); let keys: Vec<(u64, u64)> = map .range((at.saturating_sub(WINDOW), 0)..(end, 0)) .filter(|(key, shadow)| shadow.place.is_some() && key.0 + key.1 > at) @@ -4281,8 +4288,8 @@ pub(crate) fn in_place_let_go(at: u64, len: u64) -> u64 { /// bytes, false) and the windows outside buffers that have a copy (start, /// bytes, true). pub(crate) fn spans() -> Vec<(u64, u64, bool)> { - let mut spans: Vec<(u64, u64, bool)> = buffers().iter().map(|(key, entry)| (key.0, entry.end - key.0, false)).collect(); - let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let mut spans: Vec<(u64, u64, bool)> = buffers_read().iter().map(|(key, entry)| (key.0, entry.end - key.0, false)).collect(); + let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner()); spans.extend(loose.keys().map(|&(start, len)| (start, len, true))); spans } @@ -4322,11 +4329,23 @@ pub(crate) fn find_any(address: u64, len: u64) -> Option> { /// The copy [`find`] gives for a range inside a title buffer, if it was made. pub(crate) fn peek(address: u64, len: u64) -> Option> { let end = address.checked_add(len.max(1))?; - buffers().range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end).and_then(|(_, e)| e.shadow.clone()) + buffers_read().range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end).and_then(|(_, e)| e.shadow.clone()) } fn lookup(address: u64, len: u64, any: bool) -> Option> { let end = address.checked_add(len.max(1))?; + { + let map = buffers_read(); + match map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end) { + // The copy is made already (nearly always). + Some((_, Entry { shadow: Some(shadow), .. })) => return Some(shadow.clone()), + Some(_) => {} + None => { + drop(map); + return loose(address, end, len <= 1, any); + } + } + } let mut map = buffers(); let key = map .range(..=(address, usize::MAX)) @@ -4505,7 +4524,7 @@ fn fine() -> bool { /// which is copied once for each. #[cfg(feature = "diagnostics")] pub(crate) fn window_cover() -> u64 { - let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner()); cover(loose.keys().copied()) } @@ -4536,12 +4555,29 @@ fn longest_tail(windows: impl Iterator, address: u64, end: u6 } /// Copies of title memory outside buffers, by (start, length). -static LOOSE: Mutex>> = Mutex::new(BTreeMap::new()); +static LOOSE: std::sync::RwLock>> = std::sync::RwLock::new(BTreeMap::new()); fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option> { - let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); let (cell, _) = window_of(address, end, WINDOW); let named = window_of(address, end, if unsized_ask { WINDOW } else { window() }); + // Under the lock, with the handing out: see `let_go_idle`. + let note = |shadow: &Shadow| { + shadow.used.store(crate::host::moment(), Ordering::Relaxed); + shadow.asked[0].fetch_min(address, Ordering::Relaxed); + shadow.asked[1].fetch_max(end, Ordering::Relaxed); + if unsized_ask { + shadow.unsized_asks.fetch_add(1, Ordering::Relaxed); + } + }; + // The window is there already (nearly always): readers share the lock. + if !(unsized_ask && tails()) && !(any && fine() && !unsized_ask) { + let map = LOOSE.read().unwrap_or_else(|e| e.into_inner()); + if let Some(shadow) = map.get(&named) { + note(shadow); + return Some(shadow.clone()); + } + } + let mut map = LOOSE.write().unwrap_or_else(|e| e.into_inner()); let (start, len) = if unsized_ask && tails() { let there = map.range((cell, 0)..=(address, u64::MAX)).map(|(key, _)| *key); longest_tail(there, address, end).unwrap_or_else(|| tail_of(address, end)) @@ -4554,15 +4590,6 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option String { .collect(); all.extend( LOOSE - .lock() + .read() .unwrap_or_else(|e| e.into_inner()) .values() .map(|s| (s.gpu, s.start, s.len)), From ac34b4d40901377c548bfe0ca2241fce4c143b71 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 02:34:49 -0600 Subject: [PATCH 301/445] Crash report names the indirect executions a list stopped at; constant buffer slots hold their scratch memory Both device losses of 2026-11-25 (play-1125-0203, n02) stopped at the same place, found by the run of three indirect executions between barriers in the captures: compute 0452fc2d2e2fc4c3 (meshlet culling), behind fc5e66f8f873d3bb. - With device-removed data on (DRED=light too) each list keeps, per indirect execution, the pipeline and the first 16 dwords of user data; the report says them for the stopped commands, and what the heap slots they name hold. - A dynamic slot that shows a constant buffer in a list's scratch chunk holds that chunk (n02: the fault was in the memory of three freed chunks). VICTORY_SLOT_HOLDS=0: not held, as before. - A slot's resource is let go after its descriptor is written over, not before; the same resource again is not retired. - indirect::tests::raw_loads_past_views (ignored, a measurement): on the RX 7900 XTX raw loads through typed, structured and constant buffer views have no end: they read whatever lies after the view. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 27 ++++- crates/victory-gpu/src/descriptor/host.rs | 40 ++++++- crates/victory-gpu/src/draw.rs | 15 ++- crates/victory-gpu/src/host.rs | 85 +++++++++++++- crates/victory-gpu/src/host/card_steps.rs | 2 +- crates/victory-gpu/src/host/indirects.rs | 127 +++++++++++++++++++++ crates/victory-gpu/src/indirect.rs | 130 +++++++++++++++++++++- 7 files changed, 411 insertions(+), 15 deletions(-) create mode 100644 crates/victory-gpu/src/host/indirects.rs diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 39e8b68..d4edf99 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -333,17 +333,38 @@ 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"))] +pub(crate) fn with_view_heap(f: impl FnOnce(&host::HostHeap) -> T) -> Option { + let heaps = SHADER_HEAPS.try_read().ok()?; + let host = heaps + .iter() + // SAFETY: registered heaps are live (removed when dropped). + .map(|&(_, _, at)| unsafe { &*(at as *const Heap) }) + .filter(|heap| !heap.samplers()) + .filter_map(|heap| heap.host.get()?.as_ref()) + .max_by_key(|host| host.count())?; + Some(f(host)) +} + /// Makes dynamic slot `index` of the host heap behind the title heap at /// `heap`, if that heap still exists, the constant buffer view of `size` -/// bytes at `gpu`. +/// bytes of `buffer` at `gpu`. #[cfg(windows)] -pub(crate) fn constant_slot(heap: usize, index: u32, gpu: u64, size: u32) { +pub(crate) fn constant_slot( + heap: usize, + index: u32, + buffer: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, + gpu: u64, + size: u32, +) { let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); if heaps.iter().any(|&(_, _, h)| h == heap) // SAFETY: registered heaps are live (removed when dropped). && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get() { - host.constant_at(index, gpu, size); + host.constant_at(index, buffer, gpu, size); } } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 5aac724..825a2a0 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -866,6 +866,20 @@ fn view_home( crate::shadow::exact(start, len).unwrap_or(shadow) } +/// For device-removed reports: what the slots of the title's view heap that +/// the words of user data may name hold now ([`crate::host::indirects`]). +#[cfg(feature = "diagnostics")] +pub(crate) fn describe_slots(words: &[u32]) -> Vec<(usize, u32, String)> { + super::with_view_heap(|host| { + crate::host::indirects::slots(words, host.count, 6) + .into_iter() + .take(24) + .map(|(word, slot)| (word, slot, host.describe_slot(slot).unwrap_or_default())) + .collect() + }) + .unwrap_or_default() +} + /// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for /// device-removed reports: a shader indexing a heap past its end faults. static GPU_RANGES: Mutex> = Mutex::new(Vec::new()); @@ -1859,6 +1873,11 @@ impl HostHeap { fn keep(&self, index: u32, resource: Option) { let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); if let Some(slot) = kept.get_mut(index as usize) { + use windows::core::Interface; + // The same again: nothing to retire. + if slot.as_ref().map(Interface::as_raw) == resource.as_ref().map(Interface::as_raw) { + return; + } // A running submission may still read the old resource through // this slot. if let Some(old) = std::mem::replace(slot, resource) { @@ -1937,7 +1956,6 @@ impl HostHeap { /// Makes slot `index` (a dynamic one) a raw unordered access view of /// nothing: reads give zeros, writes are dropped. pub(crate) fn null_raw_uav_at(&self, index: u32) { - self.keep(index, None); let Some(host) = host() else { return }; let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, @@ -1959,6 +1977,7 @@ impl HostHeap { self.cpu(index), ) }; + self.keep(index, None); } /// The shader-visible handle of slot `index`. @@ -1971,9 +1990,17 @@ impl HostHeap { } /// Makes slot `index` (a dynamic one) a constant buffer view of host - /// memory (the list's own, which it holds). - pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) { - self.keep(index, None); + /// memory, `size` bytes at `gpu` of `buffer`, which the slot holds. + /// + /// The list holds it too, until it is reset; the slot shows it until it + /// is made again, and a shader that picks the slot by an index it + /// computes from wrong data reads it through there. The list's scratch + /// chunks go back to the pool and are freed past its limit: session n02 + /// lost the device to a page fault in the memory of three freed ones. + /// `VICTORY_SLOT_HOLDS=0`: only the list holds it, as before. + pub(crate) fn constant_at(&self, index: u32, buffer: &ID3D12Resource, gpu: u64, size: u32) { + static HOLDS: std::sync::OnceLock = std::sync::OnceLock::new(); + let holds = *HOLDS.get_or_init(|| std::env::var_os("VICTORY_SLOT_HOLDS").is_none_or(|v| v != "0")); let Some(host) = host() else { return }; let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, @@ -1984,6 +2011,9 @@ impl HostHeap { host.device .CreateConstantBufferView(Some(&desc), self.cpu(index)) }; + // After the descriptor: what it showed is let go when nothing shows + // it any more. + self.keep(index, holds.then(|| buffer.clone())); } fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { @@ -3297,7 +3327,7 @@ mod tests { assert!(alive(), "a view of {size} bytes"); } // SAFETY: a live upload buffer. - heap.constant_at(1, unsafe { buffer.GetGPUVirtualAddress() }, 969_472); + heap.constant_at(1, &buffer, unsafe { buffer.GetGPUVirtualAddress() }, 969_472); assert!(alive(), "a view of the list's own memory"); assert_eq!(constant_bytes(480), 512); assert_eq!(constant_bytes(64 << 10), 64 << 10); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2b6f8a0..7dccb4f 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -283,6 +283,10 @@ pub(crate) struct State { /// The records clamped in a batch, if later executions may still read /// them ([`batches`]). batch: Option, + /// The user data bound last, of the last stage that has some (for the + /// report of a removed device, `crate::host::indirects`). + #[cfg(feature = "diagnostics")] + user: Vec, /// What the host list has: pipeline, root signature, heaps. host_pipeline: usize, /// Graphics, compute. @@ -1246,6 +1250,11 @@ impl State { None => self.user_value(compute, u.slot, u.root, u.dword), }; } + #[cfg(feature = "diagnostics")] + { + self.user.clear(); + self.user.extend_from_slice(&values); + } // SAFETY: an open list; `values` covers the parameter. unsafe { if compute { @@ -2869,13 +2878,13 @@ impl State { let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k); match crate::descriptor::view(table + u64::from(k) * 32) { Some(View::Constant(address, size)) => { - let Some((gpu, to)) = list.scratch(u64::from(size)) else { + let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else { host.make_null(index); continue; }; let slot = (std::ptr::from_ref(heap) as usize, index); list.defer_constants(to, address as *const u8, size as usize, slot); - host.constant_at(index, gpu, size); + host.constant_at(index, &buffer, gpu, size); } Some(view) => { host.make_at(index, &view); @@ -3383,6 +3392,8 @@ impl State { list.note_op(|| { self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) }); + #[cfg(feature = "diagnostics")] + list.ran_indirect(p.pso.as_raw() as usize, &p.name, kind, max, &self.user); if kind == MESH { self.mesh_scissor(list, true); } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index e24be3b..20c3785 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -889,6 +889,9 @@ pub(crate) struct HostList { prelude: OnceLock>, /// The pipelines the list binds, for reports of slow submissions. pipelines: std::sync::Arc>>, + /// What its indirect executions ran, for the report of a removed device. + #[cfg(feature = "diagnostics")] + indirects: indirects::Shared, /// The work its indirect executions may still do (`indirect`): a /// shader-writable word, zeroed when the list is submitted, and after /// it what the clamp notes about mesh records. In memory the CPU maps. @@ -1404,7 +1407,14 @@ pub(crate) fn dred_faults() -> bool { #[cfg(feature = "diagnostics")] #[allow(clippy::type_complexity)] static LIST_NOTES: Mutex< - std::collections::BTreeMap>>, std::sync::Weak>>)>, + std::collections::BTreeMap< + u32, + ( + std::sync::Weak>>, + std::sync::Weak>>, + std::sync::Weak>, + ), + >, > = Mutex::new(std::collections::BTreeMap::new()); /// The number in the name of a list of ours ("victory host list 7", which the @@ -3155,6 +3165,7 @@ fn late_line(frames: f64) { } mod card_steps; +pub(crate) mod indirects; mod place; mod send; mod torn; @@ -3522,6 +3533,8 @@ impl Host { let notes = std::sync::Arc::>>::default(); let pipelines = std::sync::Arc::>>::default(); #[cfg(feature = "diagnostics")] + let indirects = indirects::Shared::default(); + #[cfg(feature = "diagnostics")] if dred_on() || dred_light() { static NUMBER: AtomicU32 = AtomicU32::new(0); let number = NUMBER.fetch_add(1, Ordering::Relaxed); @@ -3530,7 +3543,14 @@ impl Host { if number.is_multiple_of(256) { all.retain(|_, l| l.0.strong_count() > 0); } - all.insert(number, (std::sync::Arc::downgrade(¬es), std::sync::Arc::downgrade(&pipelines))); + all.insert( + number, + ( + std::sync::Arc::downgrade(¬es), + std::sync::Arc::downgrade(&pipelines), + std::sync::Arc::downgrade(&indirects), + ), + ); } Ok(HostList { allocator, @@ -3541,6 +3561,8 @@ impl Host { twins: Mutex::default(), prelude, pipelines, + #[cfg(feature = "diagnostics")] + indirects, budget: OnceLock::new(), card_budget: OnceLock::new(), indirect_args: Mutex::default(), @@ -5271,7 +5293,12 @@ impl Host { #[cfg(feature = "diagnostics")] let by_name = list_number(&named).and_then(|n| { let all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()); - all.get(&n).map(|(notes, pipelines)| (notes.upgrade(), pipelines.upgrade())) + all.get(&n).map(|(notes, pipelines, _)| (notes.upgrade(), pipelines.upgrade())) + }); + #[cfg(feature = "diagnostics")] + let indirects = run.map(|r| r.indirects.clone()).or_else(|| { + let n = list_number(&named)?; + LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()).get(&n)?.2.upgrade() }); #[cfg(not(feature = "diagnostics"))] #[allow(clippy::type_complexity)] @@ -5301,6 +5328,10 @@ impl Host { if done > 0 { text.push_str(&in_flight(history, &markers, done as usize)); } + #[cfg(feature = "diagnostics")] + if let Some(indirects) = indirects { + text.push_str(&indirects_around(history, done as usize, &indirects)); + } // (Without markers a list that stopped midway says what // it may have been at only by what it binds.) if (done == 0 || markers.is_empty()) @@ -5498,6 +5529,8 @@ impl HostList { self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); #[cfg(feature = "diagnostics")] + self.indirects.lock().unwrap_or_else(|e| e.into_inner()).clear(); + #[cfg(feature = "diagnostics")] self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); { let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); @@ -5904,6 +5937,15 @@ impl HostList { && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty() } + /// Notes an indirect execution, while device-removed data is kept + /// ([`indirects`]). + #[cfg(feature = "diagnostics")] + pub(crate) fn ran_indirect(&self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) { + if dred_on() || dred_light() { + self.indirects.lock().unwrap_or_else(|e| e.into_inner()).note(pipeline, name, kind, count, user); + } + } + /// Notes a pipeline the list binds. pub(crate) fn used_pipeline(&self, name: &str) { let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner()); @@ -6025,6 +6067,15 @@ impl HostList { Some((unsafe { buffer.GetGPUVirtualAddress() } + at, data)) } + /// [`HostList::scratch`] and the buffer it lies in, for a descriptor + /// slot to hold: the slot outlives the list's use of it. + pub(crate) fn scratch_held(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> { + let (buffer, at, data) = self.scratch_at(len)?; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() } + at; + Some((buffer, gpu, data)) + } + /// [`HostList::scratch`]: the buffer, the offset in it and the CPU /// pointer. fn scratch_at(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> { @@ -7977,6 +8028,34 @@ fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String { /// barriers overlaps on the GPU), by kind, and what the markers just /// before them say (`HostList::note_op`: diagnostics builds with /// device-removed data on). +/// For a list that stopped at command `done`: what the indirect executions +/// there ran, from the one before it to the next barrier (four at most), and +/// what the heap slots their user data names hold now. +#[cfg(feature = "diagnostics")] +fn indirects_around(history: &[D3D12_AUTO_BREADCRUMB_OP], done: usize, all: &indirects::Shared) -> String { + let indirect = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_EXECUTEINDIRECT; + let all = all.lock().unwrap_or_else(|e| e.into_inner()); + let mut text = String::new(); + let mut shown = 0; + for (at, op) in history.iter().enumerate().skip(done.saturating_sub(1)) { + if shown == 4 || (at > done && *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER) { + break; + } + if !indirect(op) { + continue; + } + shown += 1; + let Some((what, words)) = all.nth(indirects::before(history, at, indirect)) else { + continue; + }; + text.push_str(&format!("; command {at} ran {what}")); + for (word, slot, what) in crate::descriptor::host::describe_slots(words) { + text.push_str(&format!(", word {word} slot {slot}: {what}")); + } + } + text +} + fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String { let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER; let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1); diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 881d1b2..84641cd 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -715,7 +715,7 @@ impl Host { To::Slot(heap, index) => { DONE[0].fetch_add(1, Ordering::Relaxed); // (A heap that is gone: nothing can read the slot.) - crate::descriptor::constant_slot(*heap, *index, gpu + op.at, op.len as u32); + crate::descriptor::constant_slot(*heap, *index, &own.between, gpu + op.at, op.len as u32); } To::Buffer(_) => { DONE[0].fetch_add(1, Ordering::Relaxed); diff --git a/crates/victory-gpu/src/host/indirects.rs b/crates/victory-gpu/src/host/indirects.rs new file mode 100644 index 0000000..cc34bff --- /dev/null +++ b/crates/victory-gpu/src/host/indirects.rs @@ -0,0 +1,127 @@ +//! What the indirect executions of a list ran, for the report of a removed +//! device: with `VICTORY_D3D12_DRED=light` the lists carry no markers, and +//! the two device losses of 2026-11-25 (sessions play-1125-0203 and n02) +//! said only that a list of 814 (954) commands stopped at an indirect +//! execution. The pipeline of each was found hours later by finding the +//! same run of commands in a capture. +//! +//! Per list, in the order recorded: the pipeline (by its host object, whose +//! name is kept once) and the first root constants (user data) it had. The +//! report finds an indirect execution by how many the breadcrumbs' history +//! has before it. Nothing is kept without device-removed data. +//! `VICTORY_D3D12_DRED=faults` and no data at all: nothing is noted. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +/// Words of user data kept of each execution. +pub(crate) const WORDS: usize = 16; + +/// One indirect execution. +#[derive(Clone, Copy)] +pub(crate) struct Ran { + pipeline: usize, + kind: u32, + count: u32, + words: [u32; WORDS], + used: u8, +} + +#[derive(Default)] +pub(crate) struct Indirects { + names: HashMap, + ran: Vec, +} + +/// A list's, shared with the report's table of lists. +pub(crate) type Shared = Arc>; + +impl Indirects { + /// An indirect execution of `kind` (the argument's type) of at most + /// `count` records with `pipeline` (a host object) and user data. + pub(crate) fn note(&mut self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) { + self.names.entry(pipeline).or_insert_with(|| name.to_owned()); + let used = user.len().min(WORDS); + let mut words = [0; WORDS]; + words[..used].copy_from_slice(&user[..used]); + self.ran.push(Ran { pipeline, kind, count, words, used: used as u8 }); + } + + pub(crate) fn clear(&mut self) { + self.ran.clear(); + if self.names.len() > 512 { + self.names.clear(); + } + } + + /// The `nth` execution (from 0): its text and its user data. + pub(crate) fn nth(&self, nth: usize) -> Option<(String, &[u32])> { + let ran = self.ran.get(nth)?; + let name = self.names.get(&ran.pipeline).map_or("a pipeline", String::as_str); + let words = &ran.words[..usize::from(ran.used)]; + Some(( + format!("{name} (indirect kind {} max {}, the list's indirect execution {nth}, user data {words:x?})", ran.kind, ran.count), + words, + )) + } +} + +/// How many indirect executions come before command `at` of a history of +/// breadcrumb operations (`is` tells them): which of a list's it is. +pub(crate) fn before(history: &[T], at: usize, is: impl Fn(&T) -> bool) -> usize { + history[..at.min(history.len())].iter().filter(|op| is(op)).count() +} + +/// The heap slots the user data may name, for the report to describe: the +/// words that are slots as they are, and the slots from where a word is a +/// table's byte offset (32 bytes a descriptor), `table` of them. +pub(crate) fn slots(words: &[u32], count: u32, table: u32) -> Vec<(usize, u32)> { + let mut out = Vec::new(); + for (i, &word) in words.iter().enumerate() { + if word > 0 && word < count && word % 32 != 0 { + out.push((i, word)); + } + if word % 32 == 0 && word / 32 > 16 && word / 32 < count { + out.extend((0..table).map(|k| (i, word / 32 + k)).filter(|s| s.1 < count)); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The execution a breadcrumb history stops at is found by the ones + /// before it, and its pipeline and user data are told. + #[test] + fn an_indirect_execution_is_found_by_its_place_in_the_history() { + let mut all = Indirects::default(); + all.note(1, "[compute a]", 2, 1, &[0x2549f40, 0x20, 0x11]); + all.note(2, "[compute b]", 2, 1, &[7; 20]); + all.note(1, "another name of the same is not taken", 10, 4, &[]); + // dispatch, indirect, barrier, indirect, indirect + let history = [6, 5, 15, 5, 5]; + let nth = before(&history, 3, |op| *op == 5); + assert_eq!(nth, 1); + let (text, words) = all.nth(nth).unwrap(); + assert!(text.starts_with("[compute b] (indirect kind 2 max 1"), "{text}"); + assert_eq!(words, [7; WORDS]); + let (text, words) = all.nth(2).unwrap(); + assert!(text.starts_with("[compute a] (indirect kind 10 max 4"), "{text}"); + assert!(words.is_empty()); + assert!(all.nth(3).is_none()); + assert_eq!(before(&history, 99, |op| *op == 5), 3); + all.clear(); + assert!(all.nth(0).is_none()); + } + + /// A table's byte offset names the slots from it on; a small word that + /// is no multiple of a descriptor's bytes names its own slot. + #[test] + fn user_data_names_slots() { + let words = [0, 0x2549f40, 0x20, 0x11, 0x26f1, 0xffff_ffff]; + let slots = slots(&words, 1_245_184, 2); + assert_eq!(slots, [(1, 0x2549f40 / 32), (1, 0x2549f40 / 32 + 1), (3, 0x11), (4, 0x26f1)]); + } +} diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 7d044ab..6d738d8 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -600,7 +600,7 @@ pub(crate) mod tests { use super::*; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; - use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; use windows::Win32::Graphics::Dxgi::*; use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; use windows::core::Interface; @@ -984,6 +984,134 @@ void main() { } } + /// What raw loads through views that are not raw give past the view's + /// end (ignored: a measurement of the card). A buffer view of 4 KiB in a + /// buffer of 1 MiB whose every dword says where it lies: zeros past the + /// view, or the bytes there (whatever the card has in that place). + #[test] + #[ignore] + fn raw_loads_past_views() { + let Some(mut gpu) = WarpHarness::on(std::env::var_os("VICTORY_BENCH_WARP").is_some()) else { + return; + }; + const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=4,b0), DescriptorTable(SRV(t0,numDescriptors=8)), UAV(u0), DescriptorTable(CBV(b1,numDescriptors=8))" +cbuffer C : register(b0) { uint which; uint first; uint step; uint at; } +ByteAddressBuffer v[8] : register(t0); +struct Block { uint4 d[4096]; }; +ConstantBuffer c[8] : register(b1); +RWByteAddressBuffer o : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID, uint g : SV_GroupIndex) { + if (step == 0) { if (id.x == 0) o.Store(at, v[which].Load(first)); } + else if (step == 1) { if (id.x == 0) o.Store(at, c[which].d[first / 16][(first / 4) & 3]); } + else { o.Store(at + id.x * 4, v[which].Load(first + id.x * step)); } +} +"#; + let pass = compile_cs(&gpu.device, SOURCE).expect("the pass must compile"); + let (buffer, data, _) = gpu.shared_buffer(1 << 20); + for i in 0..(1usize << 18) { + // SAFETY: inside the mapping. + unsafe { data.cast::().add(i).write(0xA000_0000 | i as u32) }; + } + let (_out, out_ptr, out_gpu) = gpu.shared_buffer(1 << 16); + // SAFETY: plain heap creation, views of a live buffer. + let heap: ID3D12DescriptorHeap = unsafe { + gpu.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 16, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + } + .unwrap(); + // SAFETY: as above. + let (cpu, table, step) = unsafe { + ( + heap.GetCPUDescriptorHandleForHeapStart().ptr, + heap.GetGPUDescriptorHandleForHeapStart(), + gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize, + ) + }; + let names = ["raw", "structured 24 at 24", "structured 16", "typed u32", "typed u16", "typed 4 x u32", "constant buffer", "null raw"]; + let view = |i: usize, format: i32, first: u64, count: u32, stride: u32, raw: bool, null: bool| { + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(format), + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: first, + NumElements: count, + StructureByteStride: stride, + Flags: if raw { D3D12_BUFFER_SRV_FLAG_RAW } else { D3D12_BUFFER_SRV_FLAG_NONE }, + }, + }, + }; + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu + i * step }; + // SAFETY: a slot of our heap, a live buffer. + unsafe { gpu.device.CreateShaderResourceView(if null { None } else { Some(&buffer) }, Some(&desc), at) }; + }; + for base in [0, 8] { + view(base, 39, 0, 1024, 0, true, false); + view(base + 1, 0, 1, 170, 24, false, false); + view(base + 2, 0, 0, 256, 16, false, false); + view(base + 3, 42, 0, 1024, 0, false, false); + view(base + 4, 57, 0, 2048, 0, false, false); + view(base + 5, 3, 0, 256, 0, false, false); + view(base + 7, 39, 0, 1, 0, true, true); + let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { + // SAFETY: a live buffer. + BufferLocation: unsafe { buffer.GetGPUVirtualAddress() }, + SizeInBytes: 4096, + }; + // SAFETY: a slot of our heap. + unsafe { gpu.device.CreateConstantBufferView(Some(&desc), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu + (base + 6) * step }) }; + } + let table2 = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: table.ptr + 8 * step as u64 }; + let offsets = [0u32, 4092, 4096, 4104, 8192, 65536, 524_288, (1 << 20) - 4]; + for mode in ["one load (uniform)", "a load a thread", "constant buffer load"] { + println!("{mode}:"); + for (which, name) in names.iter().enumerate() { + // SAFETY: our open list, live buffers. + unsafe { + std::ptr::write_bytes(out_ptr, 0x77, 1 << 16); + gpu.list.SetDescriptorHeaps(&[Some(heap.clone())]); + gpu.list.SetComputeRootSignature(&pass.root); + gpu.list.SetPipelineState(&pass.pso); + gpu.list.SetComputeRootDescriptorTable(1, table); + gpu.list.SetComputeRootUnorderedAccessView(2, out_gpu); + gpu.list.SetComputeRootDescriptorTable(3, table2); + for (k, &offset) in offsets.iter().enumerate() { + let step = match mode.as_bytes()[0] { + b'o' => 0u32, + b'c' => 1, + _ => 4, + }; + // (A thread's loads end at the offset.) + let first = if step == 4 { offset.saturating_sub(63 * 4) } else { offset }; + let constants = [which as u32, first, step, k as u32 * 256]; + gpu.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + gpu.list.Dispatch(1, 1, 1); + } + } + gpu.submit_and_wait(); + let found: Vec = offsets + .iter() + .enumerate() + .map(|(k, &offset)| { + let thread = if mode.as_bytes()[0] == b'a' { (offset.min(63 * 4) / 4) as usize } else { 0 }; + // SAFETY: inside the mapping. + let word = unsafe { out_ptr.cast::().add(k * 64 + thread).read_volatile() }; + format!("{offset}: {word:#x}") + }) + .collect(); + println!(" {name:20} {}", found.join(" ")); + } + } + } + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { From 7d3e17908eb774b54243dfedb80b071c523932dd Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 02:38:31 -0600 Subject: [PATCH 302/445] Memory the card was given stays with it while there is room Both losses were reads in memory given back seconds before. Empty texture blocks (up to 4 GiB) stay below 85 % of the card's budget, windows of title memory and staging buffers stay for five minutes with 12 GiB of the PC's memory free, and up to 1 GiB of scratch chunks stays. Nothing read past a view or through a wrong slot finds the hole then. VICTORY_KEEP_FREED=0: as before. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 36 +++++++++++++++++++++++++++-- crates/victory-gpu/src/pool.rs | 42 ++++++++++++++++++++++++++++++---- 2 files changed, 71 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 20c3785..3e03ac4 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -157,11 +157,37 @@ fn vram_idle_for(video_memory: Option<[u64; 4]>, keep: bool) -> u64 { } } +/// Whether memory the card was given stays with it while there is room (on +/// by default; `VICTORY_KEEP_FREED=0`: it is given back as before). A shader +/// that reads past a view (a raw load through a typed, structured or +/// constant buffer view has no end on AMD: `indirect::tests::raw_loads_past_views`) +/// or through a slot that shows wrong data reads whatever lies there, and +/// nothing happens; where memory was given back it is a page fault, and the +/// device is lost. Both losses of 2026-11-25 were reads in memory given back +/// seconds before (a block of textures; a list's scratch and a window of +/// title memory). Kept are: empty blocks of textures ([`crate::pool`]) below +/// 85 % of the card's budget, windows of title memory and staging buffers +/// for five minutes with 12 GiB of the PC's memory free, and 1 GiB of +/// scratch chunks. +pub(crate) fn keep_freed() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_FREED").is_none_or(|v| v != "0")) +} + /// Effective idle timeout (in milliseconds) for system-RAM caches (staging /// buffers, loose shadows, and the mapped pipeline library), scaled down /// when free physical RAM is low. Never returns less than 2,000 ms. +/// With plenty of it five minutes ([`keep_freed`]). pub(crate) fn ram_idle_ms(avail_phys: Option) -> u64 { + ram_idle_for(avail_phys, keep_freed()) +} + +fn ram_idle_for(avail_phys: Option, keep: bool) -> u64 { const GIB: u64 = 1024 * 1024 * 1024; + const KEPT_MS: u64 = 300_000; + if keep && avail_phys.is_some_and(|avail| avail >= 12 * GIB) { + return KEPT_MS; + } const NORMAL_MS: u64 = 10_000; const MODERATE_MS: u64 = 5_000; const HIGH_MS: u64 = 2_000; @@ -215,6 +241,7 @@ fn sweep() { { return; } + crate::pool::room(host().and_then(|h| h.video_memory())); crate::pipeline::trim_library(); crate::shadow::let_go_idle(); crate::texture::let_go_idle(); @@ -1541,6 +1568,8 @@ const SCRATCH_CHUNK: u64 = 4 << 20; const SCRATCH_FIRST: u64 = 256 << 10; /// The most bytes of chunks kept while no list holds them. const SPARE_MOST: u64 = 128 << 20; +/// The same with [`keep_freed`]. +const SPARE_KEPT: u64 = 1 << 30; /// Whether lists share their scratch chunks: a list takes a chunk when it /// first needs one, a small one first, and gives all of them back when it @@ -1621,7 +1650,7 @@ fn give_chunks(chunks: Vec<(Chunk, u64)>) { let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); for (chunk, size) in chunks { let back = if scratch_pool() { - spare.give(chunk, size, SPARE_MOST) + spare.give(chunk, size, if keep_freed() { SPARE_KEPT } else { SPARE_MOST }) } else { Some(chunk) }; @@ -8985,7 +9014,10 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at #[test] fn ram_idle_ms_scales_with_pressure() { - use super::ram_idle_ms; + let ram_idle_ms = |avail| super::ram_idle_for(avail, false); + assert_eq!(super::ram_idle_for(Some(12 << 30), true), 300_000); + assert_eq!(super::ram_idle_for(Some((12 << 30) - 1), true), 10_000); + assert_eq!(super::ram_idle_for(None, true), 10_000); let gib = 1024 * 1024 * 1024; // Normal (>= 4 GiB) assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000); diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index 32b3bfb..95ba178 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -20,7 +20,7 @@ use std::collections::{BTreeMap, VecDeque}; use std::ffi::c_void; use std::sync::Mutex; -use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; use windows::Win32::Graphics::Direct3D12::*; use windows::core::{GUID, HRESULT, IUnknown, Interface}; @@ -29,6 +29,25 @@ use windows::core::{GUID, HRESULT, IUnknown, Interface}; const BLOCK: u64 = 64 << 20; /// Blocks with nothing in them that are kept. const SPARE: usize = 2; +/// The same while the card has room ([`room`]): 4 GiB of them. +const SPARE_KEPT: usize = 64; +/// How many are kept now. +static SPARES: AtomicUsize = AtomicUsize::new(SPARE); + +/// Sets how many empty blocks stay, by the card's memory (budget and use): +/// [`SPARE_KEPT`] below 85 % ([`crate::host::keep_freed`]), else [`SPARE`]. +/// Asked once a second. +pub(crate) fn room(memory: Option<[u64; 4]>) { + SPARES.store(spares(memory, crate::host::keep_freed()), Ordering::Relaxed); +} + +fn spares(memory: Option<[u64; 4]>, keep: bool) -> usize { + match memory { + Some([budget, used, ..]) if keep && u128::from(used) * 100 < u128::from(budget) * 85 => SPARE_KEPT, + _ => SPARE, + } +} + /// Milliseconds until a piece given back is used again. (It was three /// frames, a tenth of a second while the title shows a loading screen at 30 /// a second, with up to 18 submissions in the air.) @@ -106,11 +125,13 @@ struct Pool { blocks: Vec>>, /// Pieces given back, and when each may be used again. resting: VecDeque<(u64, Piece)>, + /// The empty blocks it was last told to keep. + spare: usize, } impl Pool { const fn new() -> Pool { - Pool { blocks: Vec::new(), resting: VecDeque::new() } + Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0 } } /// A piece of `len` bytes and the memory it lies in, and whether that @@ -168,12 +189,15 @@ impl Pool { any |= block.free.whole(BLOCK); } } - if any { + // (Without a piece given back too, once there is less room.) + let most = SPARES.load(Ordering::Relaxed); + if any || most < self.spare { + self.spare = most; let mut spare = 0; for block in &mut self.blocks { if block.as_ref().is_some_and(|b| b.free.whole(BLOCK)) { spare += 1; - if spare > SPARE { + if spare > most { *block = None; } } @@ -379,6 +403,14 @@ mod tests { assert!(r.whole(1024)); } + #[test] + fn empty_blocks_stay_while_the_card_has_room() { + assert_eq!(spares(Some([100, 84, 0, 0]), true), SPARE_KEPT); + assert_eq!(spares(Some([100, 85, 0, 0]), true), SPARE); + assert_eq!(spares(Some([100, 10, 0, 0]), false), SPARE); + assert_eq!(spares(None, true), SPARE); + } + #[test] fn pieces_never_overlap_and_rest_before_they_are_used_again() { let mut pool: Pool = Pool::new(); @@ -408,7 +440,7 @@ mod tests { pool.give(p, 20); } pool.rested(20 + REST); - assert_eq!(pool.blocks(), blocks.min(SPARE)); + assert_eq!(pool.blocks(), blocks.min(SPARES.load(Ordering::Relaxed))); // Too big for a block, and a block that cannot be made. assert!(pool.take(BLOCK, 65536, 30, make).is_none()); let mut none: Pool = Pool::new(); From 1f58d913662298bdd9194b5dbcaabf014bba3ade Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 02:48:44 -0600 Subject: [PATCH 303/445] Shaders read the buffers they pick through raw twins of the heap's views A buffer a shader picks from the view heap by an index it computes is read as raw bytes, whatever view the title has there, and the index and the offset come from data. On AMD a raw load through a typed, structured or constant buffer view has no end (measured), a texture's descriptor read as a buffer's is a wild address, and an index past the title's slots (clamped to 2^21) reaches the dynamic slots of other lists. Both device losses of 2026-11-25 stopped in the meshlet culling (0452fc2d2e2fc4c3), which does such reads. View heaps now hold 2^22 views: past 2^21 a raw view of the same bytes for every buffer view of a title slot (a constant buffer's view for a constant buffer; a null raw view for everything else and every slot past the title's), and picked raw and constant buffers are read there. Texture and typed picks and tables stay as they were. A view that does not begin on 16 bytes cannot be raw; its twin is the view as it is. Idea of a guard by kind: VIctory d71c3889. VICTORY_RAW_VIEWS=0: as before. Every shader is translated again (8 min). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 211 ++++++++++++++++--- crates/victory-gpu/src/indirect.rs | 2 + crates/victory-shader/src/emit/lower.rs | 50 ++++- crates/victory-shader/src/emit/mod.rs | 3 +- crates/victory-shader/src/emit/shader.rs | 51 ++++- crates/victory-shader/src/emit/size_tests.rs | 44 ++++ 6 files changed, 328 insertions(+), 33 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 825a2a0..357ed9c 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -24,6 +24,11 @@ pub(crate) struct HostHeap { /// ours keeps 2^18 there: 2^16 and 2^17 both ran out in this title.) dynamic: u32, sampler: bool, + /// Where the raw twins of the title's slots start + /// (`victory_shader::emit::raw_views`; 0: there are none), and which of + /// them are not null. + raw: u32, + twins: Vec, /// The record (view index and generation) each slot was last made from. made: Mutex>, /// The records of the title's heap as the pass over records copied in @@ -838,6 +843,12 @@ fn off_elements(offset: u64, stride: u32, raw: bool, element: u64) -> bool { } } +/// Whether `view` has a raw twin when its host slot is made ([`raw_twins`]): +/// a buffer view or a constant buffer's. +fn twinned(view: &View) -> bool { + matches!(view, View::Constant(..)) || view_elements(view).is_some() +} + /// Whether views off their copy's elements get a copy of their own bytes. On by /// default; `VICTORY_VIEW_BYTES=0` leaves them null, as before. fn view_bytes() -> bool { @@ -913,6 +924,20 @@ const PORTABLE_VIEWS: u32 = 1_000_000; /// the last slot is the null slot every view index at or past it reads. const UNCAPPED_VIEWS: u32 = 1 << 21; +/// Where the raw twins of the title's slots start in a heap that has them +/// ([`raw_twins`]): past every slot a title's heap and the dynamic ones take. +const RAW_TWINS: u32 = 1 << 21; + +/// Whether view heaps keep a raw twin of every buffer view of the title's +/// slots, which shaders read that pick buffers by an index they compute +/// (`victory_shader::emit::raw_views` says why; `VICTORY_RAW_VIEWS=0`: they +/// read the title's slots themselves, as before). Needs a host that takes +/// heaps of 2^22 views. +fn raw_twins() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_RAW_VIEWS").is_none_or(|v| v != "0")) +} + /// Picks, once, the null slot at the end of every host view heap and tells /// the translator now (`set_view_heap_limit`) instead of when the title's /// heap is made: a shader keeps the limit it was translated with, and the @@ -943,13 +968,21 @@ pub(crate) fn probe_view_limit() { }; made.is_ok() }; - let views = if fits(UNCAPPED_VIEWS) { + let twins = raw_twins() && fits(2 * RAW_TWINS); + if twins { + victory_shader::emit::set_raw_views(RAW_TWINS); + } + // (The twins lie past the null slot.) + let views = if twins { + RAW_TWINS + } else if fits(UNCAPPED_VIEWS) { UNCAPPED_VIEWS } else { PORTABLE_VIEWS }; tracing::info!( views, + raw_twins = twins, "host view heaps hold {views} views; view indices are clamped to the null slot at the end from the first shader on" ); victory_shader::emit::set_view_heap_limit(views - 1); @@ -1020,6 +1053,7 @@ impl HostHeap { } else { victory_shader::emit::view_heap_limit() }; + let raw = if sampler { 0 } else { victory_shader::emit::raw_views() }; let extra = if sampler { 0 } else { dynamic_slots(count, null) }; let (heap, count, size) = if null == 0 { match make(count + extra) { @@ -1030,7 +1064,7 @@ impl HostHeap { } } } else { - let size = null + 1; + let size = if raw == 0 { null + 1 } else { 2 * raw }; let fitted = if count + extra <= null { count } else { @@ -1083,6 +1117,8 @@ impl HostHeap { count, dynamic: extra, sampler, + raw, + twins: (0..if raw == 0 { 0 } else { count }).map(|_| std::sync::atomic::AtomicBool::new(false)).collect(), made: Mutex::new(vec![0; count as usize]), copied: Mutex::new(Vec::new()), waiting: Mutex::default(), @@ -1138,22 +1174,31 @@ impl HostHeap { let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + (i * self.step) as usize, }; - if self.sampler { - null_sampler(start); - } else { - null_view(start); - } - let mut filled = 1; - while filled < BLOCK { - let n = filled.min(BLOCK - filled); - host.device.CopyDescriptorsSimple(n, at(filled), start, kind); - filled += n; - } + // (The twins are null buffer views.) + let ends = if self.raw == 0 { [total, total] } else { [self.raw.min(total), total] }; let mut done = 0; - while done < total { - let n = BLOCK.min(total - done); - host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind); - done += n; + for (twin, end) in ends.into_iter().enumerate() { + if done == end { + continue; + } + if self.sampler { + null_sampler(start); + } else if twin == 1 { + null_buffer_view(start); + } else { + null_view(start); + } + let mut filled = 1; + while filled < BLOCK { + let n = filled.min(BLOCK - filled); + host.device.CopyDescriptorsSimple(n, at(filled), start, kind); + filled += n; + } + while done < end { + let n = BLOCK.min(end - done); + host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind); + done += n; + } } } Ok(()) @@ -1630,6 +1675,7 @@ impl HostHeap { Some(view) => null_for(&view, self.cpu(index)), None => null_view(self.cpu(index)), } + self.clear_twin(index); self.keep(index, None); } @@ -1869,6 +1915,20 @@ impl HostHeap { self.keep(index, None); } + /// Where the raw twin of title slot `index` is. + fn twin(&self, index: u32) -> Option { + (index < self.twins.len() as u32).then(|| self.cpu(self.raw + index)) + } + + /// The raw twin of title slot `index` is a null view again. + fn clear_twin(&self, index: u32) { + if let Some(made) = self.twins.get(index as usize) + && made.swap(false, std::sync::atomic::Ordering::Relaxed) + { + null_buffer_view(self.cpu(self.raw + index)); + } + } + /// Slot `index` now views `resource` (or nothing of the host's). fn keep(&self, index: u32, resource: Option) { let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); @@ -2136,6 +2196,7 @@ impl HostHeap { // title released): nothing to read. if made[index as usize] != 0 { made[index as usize] = 0; + self.clear_twin(index); self.make_null(index); let _ = self.note_buffer(index, None, false); } else if for_draw { @@ -2181,11 +2242,18 @@ impl HostHeap { let kept = if later { None } else { - make(&view, self.cpu(index)) + make_twinned(&view, self.cpu(index), self.twin(index)) }; if kept.is_none() && !self.sampler { null_for(&view, self.cpu(index)); } + if kept.is_some() && twinned(&view) { + if let Some(made) = self.twins.get(index as usize) { + made.store(true, std::sync::atomic::Ordering::Relaxed); + } + } else { + self.clear_twin(index); + } self.keep(index, kept.flatten()); } Some(view) @@ -2474,11 +2542,40 @@ fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: .is_some_and(|end| end <= width) } +/// Raw twins ([`raw_twins`]) made since the start, and those of them that had +/// to be views as the title's slot has them (a raw view begins on 16 bytes). +pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The bytes a buffer view the host takes ([`buffer_view_ok`]) shows as a raw +/// view (first dword, dwords), if it begins where one can; of a buffer of +/// `width` bytes. +fn twin_window(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> Option<(u64, u32)> { + use std::sync::atomic::Ordering::Relaxed; + TWINS[0].fetch_add(1, Relaxed); + let element = if raw { + 4 + } else if stride > 0 { + u64::from(stride) + } else { + crate::resource::element(format.0 as u32).map_or(0, |(bytes, _)| bytes) + }; + let start = first * element; + let dwords = (u64::from(count) * element).div_ceil(4).min((width - start.min(width)) / 4); + let window = (start % 16 == 0 && dwords > 0) + .then(|| u32::try_from(dwords).ok().map(|dwords| (start / 4, dwords))) + .flatten(); + if window.is_none() { + TWINS[1].fetch_add(1, Relaxed); + } + window +} + fn buffer_srv( address: u64, len: u64, mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE, + twin: Option, ) -> Option { let mut shadow = crate::shadow::find(address, len)?; let mut offset = shadow.offset(address); @@ -2549,6 +2646,22 @@ fn buffer_srv( host.device .CreateShaderResourceView(&shadow.buffer, Some(&desc), at) }; + if let Some(twin) = twin { + if let Some((first, count)) = twin_window(desc.Format, first, count, stride, raw, width) { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Anonymous.Buffer = D3D12_BUFFER_SRV { + FirstElement: first, + NumElements: count, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }; + } + // SAFETY: a live buffer and a slot of our heap. + unsafe { + host.device + .CreateShaderResourceView(&shadow.buffer, Some(&desc), twin) + }; + } Some(Some(shadow.buffer.clone())) } @@ -2562,6 +2675,7 @@ fn buffer_uav( len: u64, mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE, + twin: Option, ) -> Option { let mut shadow = crate::shadow::find(address, len)?; let unit = { @@ -2647,6 +2761,23 @@ fn buffer_uav( host.device .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) }; + if let Some(twin) = twin { + if let Some((first, count)) = twin_window(desc.Format, first, count, stride, raw, width) { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Anonymous.Buffer = D3D12_BUFFER_UAV { + FirstElement: first, + NumElements: count, + StructureByteStride: 0, + CounterOffsetInBytes: 0, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + }; + } + // SAFETY: a live buffer and a slot of our heap. + unsafe { + host.device + .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), twin) + }; + } Some(Some(shadow.buffer.clone())) } @@ -2793,6 +2924,17 @@ fn constant_bytes(size: u32) -> u32 { /// Makes the host descriptor for `view` at `at`: the host resource it /// views, or `None` if it cannot. fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { + make_twinned(view, at, None) +} + +/// [`make`]; `twin`: where the raw twin of a buffer view goes +/// ([`raw_twins`]; a constant buffer's is the same view again, other views +/// have none). +fn make_twinned( + view: &View, + at: D3D12_CPU_DESCRIPTOR_HANDLE, + twin: Option, +) -> Option { let host = host()?; let device = &host.device; match view { @@ -2810,8 +2952,13 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { BufferLocation: gpu, SizeInBytes: constant_bytes(size), }; - // SAFETY: a slot of our heap; the range lies in the host copy. - unsafe { device.CreateConstantBufferView(Some(&desc), at) }; + // SAFETY: slots of our heap; the range lies in the host copy. + unsafe { + device.CreateConstantBufferView(Some(&desc), at); + if let Some(twin) = twin { + device.CreateConstantBufferView(Some(&desc), twin); + } + } Some(Some(shadow.buffer.clone())) } View::Shader(resource, desc) => { @@ -2883,7 +3030,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { } else if let (Some((data, len)), Some(desc)) = (crate::resource::buffer_bytes(resource), desc) { - buffer_srv(data as u64, len, srv_desc(desc), at) + buffer_srv(data as u64, len, srv_desc(desc), at, twin) } else { None } @@ -2893,7 +3040,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { let Some(texture) = crate::resource::host_resource(resource) else { return match (crate::resource::buffer_bytes(resource), desc) { (Some((data, len)), Some(desc)) => { - buffer_uav(data as u64, len, uav_desc(desc), at) + buffer_uav(data as u64, len, uav_desc(desc), at, twin) } _ => None, }; @@ -2997,9 +3144,9 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { return None; } if *unordered { - buffer_uav(address, len, uav_desc(words), at) + buffer_uav(address, len, uav_desc(words), at, twin) } else { - buffer_srv(address, len, srv_desc(words), at) + buffer_srv(address, len, srv_desc(words), at, twin) } } } @@ -3367,6 +3514,22 @@ mod tests { assert!(buffer_view_ok(DXGI_FORMAT_UNKNOWN, 1, 10, 12, false, 4096)); } + /// The raw twin of a view shows the same bytes: typed and structured ones + /// that begin on 16 bytes, whole dwords, none past the buffer. + #[test] + fn raw_twins_show_the_views_bytes() { + let (u16s, u32s, none) = (DXGI_FORMAT(57), DXGI_FORMAT(42), DXGI_FORMAT_UNKNOWN); + assert_eq!(twin_window(u32s, 4, 10, 0, false, 4096), Some((4, 10))); + assert_eq!(twin_window(u16s, 8, 7, 0, false, 4096), Some((4, 4))); + // the last dword would reach past the buffer + assert_eq!(twin_window(u16s, 8, 7, 0, false, 30), Some((4, 3))); + assert_eq!(twin_window(none, 2, 3, 24, false, 4096), Some((12, 18))); + assert_eq!(twin_window(DXGI_FORMAT_R32_TYPELESS, 8, 5, 0, true, 4096), Some((8, 5))); + // where no raw view begins: the view as it is + assert_eq!(twin_window(none, 1, 3, 24, false, 4096), None); + assert_eq!(twin_window(u32s, 1, 10, 0, false, 4096), None); + } + /// Views that begin where no host view can: raw ones off 16 bytes, /// structured ones off their elements (and off 16 bytes, where they are /// made raw), typed ones off theirs. diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 6d738d8..86e68fb 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -1110,6 +1110,8 @@ void main(uint3 id : SV_DispatchThreadID, uint g : SV_GroupIndex) { println!(" {name:20} {}", found.join(" ")); } } + // SAFETY: a plain query. + println!("device: {:?}", unsafe { gpu.device.GetDeviceRemovedReason() }); } /// The clamp compiles with the system's compiler and the host takes it. diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 6a86f71..86ceff9 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1082,9 +1082,9 @@ fn own_bits_on() -> bool { } /// What the translator was told of the host, for a cache's key: the widest -/// wave and the view heap's limit. -pub fn host_settings() -> [u32; 2] { - [host_max_wave(), super::shader::view_heap_limit()] +/// wave, the view heap's limit and where the raw twins of its views start. +pub fn host_settings() -> [u32; 3] { + [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views()] } /// The refusal of a first half of an interpolation whose result is read @@ -6724,12 +6724,13 @@ impl<'a> Lower<'a> { return Ok(h); } let index = self.heap_index(*load, *first, sampler)?; + let (index, bounded) = self.raw_twin(src, index, sampler, props); // A waterfall loop's load at the first lane's offset reads // each lane's own entry (see `resource::Waterfall`). let per_lane = self.x.res.waterfall.loads.contains(load); let h = self .s - .heap_handle(self.cur, index, sampler, per_lane, props); + .heap_handle_at(self.cur, index, sampler, per_lane, props, bounded); self.handles.insert(key, h); Ok(h) } @@ -6775,7 +6776,8 @@ impl<'a> Lower<'a> { Source::Phi { block, args } => { let _ = site; let phi = self.descriptor_phi(*block, args, sampler, 8)?; - Ok(self.s.heap_handle(self.cur, phi, sampler, false, props)) + let (index, bounded) = self.raw_twin(src, phi, sampler, props); + Ok(self.s.heap_handle_at(self.cur, index, sampler, false, props, bounded)) } Source::Select { scc, args } => { // The heap index of each choice, picked by SCC (uniform). @@ -6793,18 +6795,52 @@ impl<'a> Lower<'a> { let set = self.heap_index(a, fa, sampler)?; let clear = self.heap_index(b, fb, sampler)?; let index = self.s.m.select(self.cur, cond, set, clear); - Ok(self.s.heap_handle(self.cur, index, sampler, false, props)) + let (index, bounded) = self.raw_twin(src, index, sampler, props); + Ok(self.s.heap_handle_at(self.cur, index, sampler, false, props, bounded)) } Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => { // A descriptor each lane has its own of (a waterfall loop // reads it from the first active lane): each lane's heap // index, non-uniform. let index = self.lane_heap_index(src, sampler)?; - Ok(self.s.heap_handle(self.cur, index, sampler, true, props)) + let (index, bounded) = self.raw_twin(src, index, sampler, props); + Ok(self.s.heap_handle_at(self.cur, index, sampler, true, props, bounded)) } } } + /// The heap index to read descriptor `src` at, `index` being the title's: + /// for a buffer picked from the heap itself and read as raw bytes (or as + /// a constant buffer), the host's raw twin of that slot + /// ([`super::shader::raw_views`]), whose reads end where the view does. + /// Everything else (tables, textures, typed buffers) stays in place. + /// And whether it is a twin's (inside the host's heap). + fn raw_twin(&mut self, src: &Source, index: V, sampler: bool, props: (u32, u32)) -> (V, bool) { + // Raw and constant buffers (DXIL resource kinds 11 and 13). + const RAW: u32 = 11; + const CONSTANT: u32 = 13; + let first = super::shader::raw_views(); + let picked = |leaf: &&Source| { + let (Source::Loaded { load, .. } | Source::Fetched { load, .. }) = leaf else { + return false; + }; + self.scalar + .get(load) + .and_then(|a| self.x.native.layout.get(a.param)) + .is_some_and(|p| p.root == RootType::ResourceHeap) + }; + if first == 0 || sampler || !matches!(props.0 & 0xFF, RAW | CONSTANT) || !src.leaves().iter().all(picked) { + return (index, false); + } + let c = self.cur; + let (last, first) = (self.s.m.i32(first - 1), self.s.m.i32(first)); + let i32t = self.s.t.i32; + // (As `dx.op.binary` UMin, see `heap_handle`.) + let index = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]); + self.s.m.tag(index, Tag::Clamp); + (self.s.m.bin(c, Bin::Or, index, first), true) + } + /// The heap index a descriptor phi picks. Each predecessor computes its /// heap index at its end and the join picks one with a phi; a /// predecessor whose descriptor is itself chosen by control flow (a diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index c9c727e..46de147 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -119,7 +119,7 @@ pub use rect::rect_list_gs; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, - set_view_heap_limit, view_heap_limit, + raw_views, set_raw_views, set_view_heap_limit, view_heap_limit, }; /// The loop limit without an override: 2^20. @@ -221,6 +221,7 @@ pub fn translation_fingerprint() -> Vec { } out.extend_from_slice(&lower::host_max_wave().to_le_bytes()); out.extend_from_slice(&shader::view_heap_limit().to_le_bytes()); + out.extend_from_slice(&shader::raw_views().to_le_bytes()); out.extend_from_slice(&loop_limit().to_le_bytes()); out.push(group_sync()); out.extend_from_slice(&shader_opt().to_le_bytes()); diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index eb6d589..c545294 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -131,6 +131,40 @@ pub fn view_heap_limit() -> u32 { VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed) } +/// Where the host's raw twins of its buffer views start in its view heaps (0: there are none). +/// +/// A buffer a shader picks from the heap by an index it computes is read as raw bytes whatever +/// view the title has there, and the index comes from data: a record of a mesh long gone, a list +/// entry nothing wrote. On AMD a raw load through a view that is not raw (typed, structured, a +/// constant buffer's) has no end: it reads whatever lies there, up to 4 GiB on, and loses the +/// device where nothing does; and a texture's descriptor read as a buffer's is a wild address. +/// So the host keeps, for title slot `i`, a raw view of the same bytes at this place + `i` +/// (a constant buffer view of a constant buffer, a null raw view of everything else and of every +/// slot past the title's), and shaders translated while this is set read picked buffers there. +/// A power of two above every slot index. +static RAW_VIEWS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +#[cfg(test)] +thread_local! { + /// For a test's thread alone. + pub(crate) static RAW_VIEWS_HERE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// See [`RAW_VIEWS`]. +pub fn set_raw_views(first: u32) { + debug_assert!(first == 0 || first.is_power_of_two()); + RAW_VIEWS.store(first, std::sync::atomic::Ordering::Relaxed); +} + +/// See [`RAW_VIEWS`]: where shaders translated now read the buffers they pick (0: in place). +pub fn raw_views() -> u32 { + #[cfg(test)] + if let Some(first) = RAW_VIEWS_HERE.get() { + return first; + } + RAW_VIEWS.load(std::sync::atomic::Ordering::Relaxed) +} + pub(crate) struct Shader { pub m: Module, pub t: Types, @@ -402,9 +436,24 @@ impl Shader { sampler: bool, nonuniform: bool, props: (u32, u32), + ) -> V { + self.heap_handle_at(block, index, sampler, nonuniform, props, false) + } + + /// [`Shader::heap_handle`]; `bounded`: the index is inside the host's heap already + /// ([`raw_views`]). + pub fn heap_handle_at( + &mut self, + block: usize, + index: V, + sampler: bool, + nonuniform: bool, + props: (u32, u32), + bounded: bool, ) -> V { // a view index past the host heap (`set_view_heap_limit`) reads its null slot instead - let limit = VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed); + // (the raw twins of buffer views lie past it: such an index comes bounded) + let limit = if bounded { 0 } else { VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed) }; // (as `dx.op.binary` UMin: a compare and select emitted here made the bitcode invalid) let index = if !sampler && limit != 0 { let null = self.m.i32(limit); diff --git a/crates/victory-shader/src/emit/size_tests.rs b/crates/victory-shader/src/emit/size_tests.rs index 086587b..0cb8696 100644 --- a/crates/victory-shader/src/emit/size_tests.rs +++ b/crates/victory-shader/src/emit/size_tests.rs @@ -299,3 +299,47 @@ fn a_buffer_loaded_past_the_cache_is_coherent() { } } } + +/// A buffer picked from the view heap and read as raw bytes is read at the +/// host's raw twin of its slot, when the host keeps some; an index past the +/// title's slots reads the last twin, not a slot of something else. +#[test] +fn a_picked_buffer_is_read_at_its_raw_twin() { + let program = |at: u32| { + let words = [ + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xBE8C_03FF, // s_mov_b32 s12, at + at, + 0xF408_0203, // s_load_dwordx4 s[8:11], s[6:7], s12 + 0x1800_0000, + 0xE030_0004, // buffer_load_dword v5, off, s[8:11], 0 offset:4 + 0x8002_0500, + 0x7E0A_0505, // v_readfirstlane_b32 s5, v5 + 0xBE84_0380, // s_mov_b32 s4, 0 + ]; + [TABLE, &words, STORE].concat() + }; + let (title, twin, last, texel) = ([1u32, 2, 3, 4], [5u32, 6, 7, 8], [9u32, 10, 11, 12], [[0.0; 4]; 1]); + let raw = |data| View::Buffer { data, stride: Stride::Raw }; + let views = || { + [ + View::Texture(1, 1, &texel), + raw(&title), + View::RawUav(2), + View::Texture(1, 1, &texel), + View::Texture(1, 1, &texel), + raw(&twin), + View::Texture(1, 1, &texel), + raw(&last), + ] + }; + for (first, at, expected) in [(0, 32, 2), (4, 32, 6), (4, 32 * 1000, 10)] { + super::shader::RAW_VIEWS_HERE.set(Some(first)); + let shader = build(&program(at), (8, 0)).expect("translates"); + super::shader::RAW_VIEWS_HERE.set(None); + for (label, got) in run(&shader, &views()) { + assert_eq!(got[..2], [0, expected], "{label}: twins from {first}, byte {at}"); + } + } +} From 9526cb28cc909ed37b761b382f1ebcc217d8c45c Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 02:56:28 -0600 Subject: [PATCH 304/445] Formats: a texture of which only the smaller mips are there detiles from its start After victory-amd bddfb4a5 (myokex). Co-Authored-By: Claude Opus 5.5 --- crates/victory-formats/src/texture.rs | 60 ++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index dbcf277..e52d639 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -599,8 +599,35 @@ impl Layout { self.mips.get(mip as usize).map_or(0, |m| m.depth) } + /// The bytes from the texture's start that mip `first` and the smaller + /// ones take: the smaller a mip, the nearer the start it lies, so a + /// title that streams textures has memory for the smaller mips only and + /// another texture right behind them. All of the layout where slices + /// follow each other (each holds its whole chain). + pub fn bytes_from(&self, first: u32) -> u64 { + let whole = first == 0 + || self.slices != 1 + || self.thick + || self.desc.dimension == Dimension::Tex3d + || self.desc.samples != 1 + || first >= self.desc.mips; + if whole { + return self.size; + } + self.mips[first as usize..] + .iter() + .map(|m| match m.tail { + Some(_) => self.alignment, + None => m.offset + u64::from(m.pitch) * u64::from(m.rows) * u64::from(self.desc.element_bytes), + }) + .max() + .unwrap_or(self.size) + .min(self.size) + } + /// Copies one subresource out of tiled memory (the whole texture, - /// [`Layout::size`] bytes) into linear rows: mip `mip` of array slice + /// [`Layout::size`] bytes, or the [`Layout::bytes_from`] of the mip) + /// into linear rows: mip `mip` of array slice /// `slice` (3D: every depth slice of the mip, `slice` 0). Rows are /// `row_pitch` bytes apart, depth slices `depth_pitch`. pub fn detile( @@ -676,7 +703,8 @@ impl Layout { } else { (dst.len(), src.len()) }; - if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes { + let tiled_need = if DETILE { self.bytes_from(mip) } else { self.size }; + if tiled_len < tiled_need as usize || linear_len < need || row_pitch < bytes { return Err(Error::TooSmall); } let linear = self.desc.swizzle == Swizzle::LINEAR; @@ -1305,6 +1333,34 @@ mod tests { } } + /// The smaller mips lie first: they are read from the memory that holds + /// them alone, as from the whole texture's. + #[test] + fn smaller_mips_need_only_the_start_of_the_texture() { + for swizzle in [Swizzle::SW_4KB_S, Swizzle(9)] { + let l = Layout::new(&Desc { block: 4, ..desc(1024, 1024, 9, 8, swizzle) }).unwrap(); + assert_eq!(l.bytes_from(0), l.size); + let needs: Vec = (0..9).map(|mip| l.bytes_from(mip)).collect(); + assert!(needs.windows(2).all(|w| w[0] >= w[1]), "{needs:?}"); + assert!(needs[3] * 4 < l.size, "{needs:?}"); + let tiled: Vec = (0..l.size).map(|i| (i * 7 >> 3) as u8).collect(); + for mip in 1..9 { + let m = l.mips[mip as usize]; + let pitch = m.width as usize * 8; + let read = |tiled: &[u8]| { + let mut linear = vec![0; pitch * m.height as usize]; + l.detile(tiled, mip, 0, &mut linear, pitch, pitch * m.height as usize).map(|()| linear) + }; + let len = l.bytes_from(mip) as usize; + assert_eq!(read(&tiled[..len]), read(&tiled)); + assert_eq!(read(&tiled[..len - 1]), Err(Error::TooSmall)); + } + } + // Slices each hold their chain: the whole texture. + let l = Layout::new(&Desc { depth: 2, block: 4, ..desc(1024, 1024, 9, 8, Swizzle::SW_4KB_S) }).unwrap(); + assert_eq!(l.bytes_from(4), l.size); + } + #[test] fn depth_stencil_is_two_planes() { let t = Texture::new(&TextureDesc { From 8d79927a80c4686b6a7da0509d91f2961b3b7f82 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 02:56:28 -0600 Subject: [PATCH 305/445] Textures from the first level viewed; equal uploads left out; bakes take textures as they are; kept by the card's real room Placed textures are read, kept on the card and uploaded from the first level their views show (VICTORY_HELD_LEVELS=0: whole; after victory-amd 4436f8f1's spans). An upload of the bytes a host copy holds is left out (VICTORY_TEXTURE_SAME=0). A slot shows its new view once that view's upload has run. A decoration bake takes slots due a few frames later too and waits for memory being remapped (VICTORY_BAKE_EXACT=0). Host copies go only past 88 % of the budget, the longest idle first (VICTORY_TEXTURE_KEEP=1: the rule before). A slot rewritten with other filler words keeps its view. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 220 ++++++++++++++-- crates/victory-gpu/src/draw.rs | 91 ++++++- crates/victory-gpu/src/host.rs | 64 ++++- crates/victory-gpu/src/pool.rs | 13 +- crates/victory-gpu/src/resource.rs | 296 +++++++++++++++++++++- crates/victory-gpu/src/texture.rs | 227 +++++++++++++++-- 6 files changed, 866 insertions(+), 45 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 5aac724..24d0ac3 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -140,6 +140,42 @@ pub(crate) fn levels_changed(start: u64) { RESHOWN.lock().unwrap_or_else(|e| e.into_inner()).push(start); } +/// [`levels_changed`] once the submissions begun so far (that of the list +/// whose step calls this among them) have run. +pub(crate) fn levels_changed_after(start: u64) { + let after = crate::host::submissions().0; + RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner()).push((after, start)); +} + +static RESHOWN_AFTER: Mutex> = Mutex::new(Vec::new()); + +/// Slots that show a placed texture from another level than the title's view +/// in them says now, and are made from that view when the upload it needs +/// has run ([`HostHeap::texture_slot_flip`]). +struct Flip { + /// The submission to wait for. + after: u64, + /// The heap (its address), the slot, where its record is and which + /// record it was. + heap: usize, + index: u32, + handle: u64, + key: u64, +} + +static FLIPS: Mutex> = Mutex::new(Vec::new()); + +/// 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]; + +/// The key of the record at `handle`, a view's descriptor slot; 0: none. +fn record_key(handle: u64) -> u64 { + // SAFETY: the handle is a descriptor slot in title memory. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + if tag == VIEW_TAG { u64::from(generation) << 32 | u64::from(i) } else { 0 } +} + /// Levels on demand (`crate::tiles`): where the placed textures start /// whose last upload left a held level without tiles (the card had no /// room, or no heap could be had), and when (`crate::host::moment`). A @@ -210,8 +246,9 @@ pub(crate) struct Spans { rule: Rule, by_start: std::collections::BTreeMap)>, by_slot: std::collections::HashMap, - /// The level each slot's view starts at ([`Spans::shows`]). - first: std::collections::HashMap, + /// The level each slot's view starts at, and where what it is read from + /// ends ([`Spans::shows`]). + first: std::collections::HashMap, /// The bytes a placed texture takes, by resource description: worked /// out once for each (a title writes the views of a few thousand /// descriptions, thousands of times a frame). @@ -329,14 +366,20 @@ impl Spans { stale } - /// The view in slot `index` starts at level `first` of its texture. - fn shows(&mut self, index: u32, first: u32) { - self.first.insert(index, first); + /// The view in slot `index` starts at level `first` of its texture; the + /// memory of that and the smaller levels ends at `end`. + fn shows(&mut self, index: u32, first: u32, end: u64) { + self.first.insert(index, (first, end)); + } + + /// Whether slot `index`'s view is read from memory at or past `start`. + fn reaches(&self, index: u32, start: u64) -> bool { + self.first.get(&index).is_none_or(|&(_, end)| end > start) } /// The lowest level a view of the texture at `start` starts at. fn first_viewed(&self, start: u64) -> Option { - self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).min().copied() + self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).map(|&(first, _)| first).min() } /// The first span that starts inside `[start, end)` past the first @@ -370,6 +413,7 @@ impl Spans { .iter() .filter_map(|at| self.by_start.get(at)) .flat_map(|span| span.1.iter().copied()) + .filter(|&slot| self.reaches(slot, start)) .collect() } @@ -391,6 +435,7 @@ impl Spans { .into_iter() .chain(self.by_start.range(start..end).map(|(_, span)| span)) .flat_map(|span| span.1.iter().copied()) + .filter(|&slot| self.reaches(slot, start)) .collect() } } @@ -1525,6 +1570,19 @@ impl HostHeap { if self.sampler { return 0; } + { + let mut after = RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner()); + if !after.is_empty() { + let finished = crate::host::submissions().1; + let mut now = RESHOWN.lock().unwrap_or_else(|e| e.into_inner()); + after.retain(|&(at, start)| { + if at <= finished { + now.push(start); + } + at > finished + }); + } + } let starts = std::mem::take(&mut *RESHOWN.lock().unwrap_or_else(|e| e.into_inner())); if starts.is_empty() { return 0; @@ -1594,6 +1652,75 @@ impl HostHeap { true } + /// Whether host slot `index` shows the placed texture the title's record + /// 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 { + return false; + }; + if key == 0 || shown == 0 || shown == key { + return false; + } + let view = |key: u64| view_at(key as u32, (key >> 32) as u32); + matches!((view(shown), view(key)), (Some(a), Some(b)) if same_placed_texture(&a, &b)) + } + + /// Slot `index` is made from the record at `handle` (what it is now) + /// when `list`, which holds the upload of what that view shows, has run: + /// until then it shows what it showed. (Made at once, the frames on the + /// card read the new view before its levels were filled.) + pub(crate) fn texture_slot_flip(&self, list: &crate::host::HostList, index: u32, handle: u64) { + let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle)); + list.defer_host(move || { + let after = crate::host::submissions().0; + let flip = Flip { after, heap, index, handle, key }; + FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip); + }); + } + + /// Makes the slots whose new view's upload has run + /// ([`HostHeap::texture_slot_flip`]); returns how many. + pub(crate) fn texture_slots_flip(&self) -> usize { + use std::sync::atomic::Ordering::Relaxed; + let finished = crate::host::submissions().1; + let ready: Vec = { + let mut flips = FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + if flips.is_empty() { + return 0; + } + let own = std::ptr::from_ref(self) as usize; + let (ready, wait): (Vec, Vec) = + flips.drain(..).partition(|f| f.after <= finished && f.heap == own); + *flips = wait; + 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 { + continue; + }; + if *shown == f.key { + continue; + } + // Written again since, or made null: that write is in the queue. + let view = view_at(f.key as u32, (f.key >> 32) as u32); + let (true, true, Some(view)) = (f.key != 0 && record_key(f.handle) == f.key, *shown != 0, view) else { + FLIPPED[1].fetch_add(1, Relaxed); + continue; + }; + if let Some(kept) = make(&view, self.cpu(f.index)) { + *shown = f.key; + self.keep(f.index, kept); + flipped += 1; + } + } + FLIPPED[0].fetch_add(flipped as u64, Relaxed); + flipped + } + /// The memory of the texture title slot `index` views is there (again): /// see [`HostHeap::texture_slot_gone`]. pub(crate) fn texture_slot_here(&self, index: u32) { @@ -1761,23 +1888,25 @@ impl HostHeap { // (And the level the view starts at: word 4 of a texture // view's description, after format, dimension, mapping // and a pad.) - Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32, desc[4])) + let at = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let held = crate::resource::placed_bytes_from(resource, crate::resource::first_mip(desc)); + Some((resource, at, desc[4], held.map_or(u64::MAX, |held| at.saturating_add(held)))) } _ => None, }; let stale = { use std::sync::atomic::Ordering::Relaxed; let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); - let span = placed_view.and_then(|(resource, start, first)| { - Some((start, start.saturating_add(placed.bytes(resource)?), first)) + let span = placed_view.and_then(|(resource, start, first, held)| { + Some((start, start.saturating_add(placed.bytes(resource)?), first, held)) }); match span { - Some((start, end, first)) => { + Some((start, end, first, held)) => { SPANNED[0].fetch_min(start, Relaxed); SPANNED[1].fetch_max(end, Relaxed); placed.rule = stale_rule(); let stale = placed.note(index, start, end, !seen); - placed.shows(index, first); + placed.shows(index, first, held); stale } None => { @@ -2786,7 +2915,8 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { } View::Shader(resource, desc) => { let resource = *resource as crate::object::This; - if let Some(texture) = crate::resource::host_resource(resource) { + if let Some(copy) = crate::resource::host_copy(resource) { + let texture = ©.texture; // The title's views of textures with a stencil plane, as it // describes them (format, dimension, component mapping, a // pad, then first level, levels, plane): each distinct one @@ -2841,6 +2971,11 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { }; crate::tiles::show_from(desc.get_or_insert(whole), first, u32::from(own.MipLevels)); } + if copy.base > 0 + && let Some(desc) = &mut desc + { + from_base(desc, copy.base); + } // SAFETY: a live texture and a slot of our heap. unsafe { device.CreateShaderResourceView( @@ -2975,6 +3110,23 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { } } +/// The view `desc` of a texture, of a host copy of its levels from `base` +/// on (`crate::resource::held_only`). What it shows of larger ones, if any, +/// is left out. +fn from_base(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, base: u32) { + if desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D { + return; + } + // SAFETY: the member its dimension says. + let t = unsafe { &mut desc.Anonymous.Texture2D }; + let lost = base.saturating_sub(t.MostDetailedMip); + t.MostDetailedMip = t.MostDetailedMip.saturating_sub(base); + if t.MipLevels != u32::MAX { + t.MipLevels = t.MipLevels.saturating_sub(lost).max(1); + } + t.ResourceMinLODClamp = (t.ResourceMinLODClamp - base as f32).max(0.0); +} + /// Writes of a slot with another view of the placed texture it showed, /// since the start: the slot kept showing the old view. pub(crate) static KEPT_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -2993,7 +3145,10 @@ fn keep_views() -> bool { fn same_placed_texture(a: &View, b: &View) -> bool { match (a, b) { (View::Placed(false, resource, desc), View::Placed(false, other, other_desc)) => { - resource[0] != 1 && resource == other && desc[10..12] == other_desc[10..12] + // (Words 1 and 13 are the filler of the description's layout, not + // part of what a texture is: `crate::resource::texture_at`.) + let same = |from: usize, to: usize| resource[from..to] == other[from..to]; + resource[0] != 1 && resource[0] == other[0] && same(2, 13) && desc[10..12] == other_desc[10..12] } _ => false, } @@ -3011,6 +3166,7 @@ pub(crate) fn placed_texture(view: &View) -> Option { } let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let texture = crate::resource::texture_at(address, resource)?; + crate::resource::want_level(texture, crate::resource::first_mip(desc)); Some(View::Shader(texture as usize, desc[..10].try_into().ok())) } @@ -3186,6 +3342,40 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { mod tests { use super::*; + /// A view of a host copy that begins at a later level shows the same + /// levels of it. + #[test] + fn views_count_from_the_first_level_of_the_host_copy() { + let view = |first, levels, clamp| { + let mut desc = srv_desc(&[98, 4, 5768, 0, first, levels, 0, 0, 0, 0]); + desc.Anonymous.Texture2D.ResourceMinLODClamp = clamp; + from_base(&mut desc, 3); + // SAFETY: the member its dimension says. + let t = unsafe { desc.Anonymous.Texture2D }; + (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) + }; + assert_eq!(view(3, 4, 0.0), (0, 4, 0.0)); + assert_eq!(view(5, u32::MAX, 5.5), (2, u32::MAX, 2.5)); + // (Two levels the copy has not.) + assert_eq!(view(1, 4, 0.0), (0, 2, 0.0)); + } + + /// Memory past the levels a slot's view shows is not its texture's. + #[test] + fn a_view_of_smaller_levels_is_not_told_of_memory_past_them() { + let mut spans = Spans::default(); + spans.note(1, 0x10000, 0x50000, true); + spans.shows(1, 3, 0x12000); + spans.note(2, 0x10000, 0x50000, true); + spans.shows(2, 0, 0x50000); + assert_eq!(spans.slots_holding(0x11000, 0x11800), vec![1, 2]); + assert_eq!(spans.slots_holding(0x20000, 0x21000), vec![2]); + assert_eq!(spans.slots_in(0x20000, 0x21000), vec![2]); + spans.forget(2); + assert!(spans.slots_in(0x20000, 0x21000).is_empty()); + assert_eq!(spans.slots_in(0x0, 0x10001), vec![1]); + } + /// A texture filled with less than was mapped is looked at again, but /// not for ever: memory that is shown and cannot be read ends it, and a /// filling that got everything starts the count anew. @@ -3235,9 +3425,9 @@ mod tests { // A 512x512 texture of 0x56000 bytes viewed from levels 3 and 1, // and the next one 0x6000 after it (run 188). spans.note(1, 0x1_0000, 0x1_0000 + 0x5_6000, true); - spans.shows(1, 3); + spans.shows(1, 3, u64::MAX); spans.note(2, 0x1_0000, 0x1_0000 + 0x5_6000, true); - spans.shows(2, 1); + spans.shows(2, 1, u64::MAX); spans.note(3, 0x1_6000, 0x1_6000 + 0x5_6000, true); assert_eq!(spans.next_start(0x1_0000, 0x1_0000 + 0x5_6000), Some(0x1_6000)); assert_eq!(spans.next_start(0x1_6000, 0x1_6000 + 0x5_6000), None); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2b6f8a0..e7a474a 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -95,6 +95,26 @@ fn early_budgets() -> (u64, u64) { }) } +/// Whether a draw of the title's bake finds the textures it picks by index +/// as title memory has them at that moment (`VICTORY_BAKE_EXACT=0`: as the +/// pass leaves them, as before). The pass looks at a slot whose memory was +/// written or mapped a frame or two later, by when the rest of it has +/// landed, and at one uploaded whole a few frames later again, for a title +/// that fills memory unnoticed: a bake in between took the bytes from before +/// (another texture's), and what it bakes stays: coloured specks all over +/// the waitress's face for the whole diner scene (run n01), none in other +/// runs. So the pass ahead of a bake takes those slots too, and its uploads +/// wait for title memory that is being remapped (`crate::texture` `BAKING`). +fn bake_exact() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BAKE_EXACT").is_none_or(|v| v != "0")) +} + +/// Frames ahead the pass before a bake takes slots from that are due only +/// then ([`bake_exact`]): those of notices (1 and 2), and the first looks +/// again ([`RECHECK_FRAMES`]). +const BAKE_AHEAD: u64 = 12; + /// The pixel shaders of the title's decoration bake (the title: /// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the /// frame listings print it. They draw into a 256x256 corner of 2048x2048 @@ -601,6 +621,7 @@ fn heap_recheck() -> bool { } /// Times a placed texture's slot was passed over because its memory is not /// mapped. +pub(crate) static HEAP_TEXTURES_SAME: AtomicU64 = AtomicU64::new(0); pub(crate) static HEAP_TEXTURES_AWAY: AtomicU64 = AtomicU64::new(0); /// Slots the pass found up to date already: their texture is uploaded by /// the draws that read it through a table (it has a staging buffer). @@ -1820,7 +1841,9 @@ impl State { } let began = std::time::Instant::now(); PASS_BUDGET.set(Some(budget)); + crate::texture::BAKING.set(bake && bake_exact()); self.heap_textures(list, heap, host); + crate::texture::BAKING.set(false); PASS_BUDGET.set(None); if bake { BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); @@ -1970,15 +1993,23 @@ impl State { // wrote since the last pass are due again. host.texture_slots_remapped(frame); host.texture_slots_short(frame); - // Levels on demand: the slots of textures whose first level with - // memory changed since the last pass are made again from it. + // The slots of textures whose first level with memory (levels on + // demand), or whose host copy for one with more levels, changed since + // the last pass are made again from it; those whose new view's upload + // has run are made from that. host.texture_views_remade(); + host.texture_slots_flip(); // And with room, the textures whose upload left a held level // without the card's memory are uploaded again. if room { host.texture_slots_waiting(frame); } - let (due, census) = host.texture_slots_due(frame, 4096); + let baking = crate::texture::BAKING.get(); + let (due, census) = if baking { + host.texture_slots_due(frame + BAKE_AHEAD, 1 << 16) + } else { + host.texture_slots_due(frame, 4096) + }; HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed); for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) { count.store(now, Ordering::Relaxed); @@ -2068,7 +2099,16 @@ impl State { } let n = HEAP_TEXTURES_RECHECKED[1].fetch_add(1, Ordering::Relaxed); if n < 200 || n.is_multiple_of(1000) { + // Whether its pages are the title's at other addresses + // too: what is written there is told of there alone. + let elsewhere = crate::inplace::shown_elsewhere(at as usize & !0xffff, (at + len) as usize); + let first = heap.handle(index).and_then(crate::descriptor::view).map_or(0, |view| match view { + View::Placed(false, _, desc) => crate::resource::first_mip(&desc), + _ => 0, + }); tracing::warn!( + first_level = first, + blocks_shown_elsewhere = elsewhere.len(), slot = index, address = format_args!("{at:#x}"), bytes = len, @@ -2082,7 +2122,8 @@ impl State { let mut partly = None; if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) { let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; - let len = crate::resource::placed_bytes(&resource).unwrap_or(1); + let first = crate::resource::first_mip(&desc); + let len = crate::resource::placed_bytes_from(&resource, first).unwrap_or(1); let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize); if mapped == 0 { HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed); @@ -2155,7 +2196,15 @@ impl State { ); } } - let view = heap.handle(index).and_then(|handle| host.mirror(index, handle, true)); + // A slot that shows the texture by an earlier view of it (one + // from another level) goes on doing so until the upload of what + // the new one shows has run. + let shows_other = !baking + && crate::resource::held_only() + && heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle)); + let view = heap.handle(index).and_then(|handle| { + if shows_other { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) } + }); let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); let resource = match placed.as_ref().or(view.as_ref()) { Some(&View::Shader(resource, _)) => resource as This, @@ -2174,9 +2223,34 @@ impl State { // through a table: they upload it, and check it at every // submission that samples it. let tabled = crate::texture::is_staged(resource); + // The host copy holds these very bytes: nothing to upload. + let first = match (&placed, &view) { + (Some(_), Some(View::Placed(_, _, desc))) => crate::resource::first_mip(desc), + _ => 0, + }; + let same = !tabled && crate::texture::unchanged(resource, first); + if same { + HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed); + if shows_other && let Some(handle) = heap.handle(index) { + let _ = host.mirror(index, handle, true); + } + let again = partly.map(|mapped| (frame + 1, mapped)); + let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None }; + match memory { + Some((at, len)) => { + let print = crate::texture::fingerprint(at, len); + host.texture_slot_recheck(index, write, frame + RECHECK_FRAMES[0], (at, len), print, 0, frame); + } + None => host.texture_slot_done(index, write, again), + } + continue; + } if let Some(view) = &view { readable(list, sampled.kind, view); } + if shows_other && let Some(handle) = heap.handle(index) { + host.texture_slot_flip(list, index, handle); + } // A texture view the host refuses removes the device: name it. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if !GONE.load(Ordering::Relaxed) @@ -3529,7 +3603,12 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) { && let Some(t) = crate::resource::host_resource(*resource as This) && crate::texture::title_written(t) { - crate::texture::upload(list, *resource as This, t); + // Of a texture the title placed, the levels the view shows. + let first = match (&placed, view) { + (Some(_), View::Shader(_, Some(desc))) => crate::resource::first_mip(desc), + _ => 0, + }; + crate::texture::upload_from(list, *resource as This, first); } // A depth texture shaders also write: what they wrote, first. list.twin_use(*resource as This, false, false); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index e24be3b..d1f2c5e 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -117,6 +117,34 @@ pub(crate) fn available_physical_ram() -> Option { ok.then_some(m.ullAvailPhys) } +/// How long host copies of textures the title fills must have been idle to +/// be let go, in milliseconds, and how many bytes of them go at most (the +/// longest idle first): none but those of ten minutes while what is in use +/// of the card (`used`: without what our own blocks have free, with what is +/// kept free for others) is under 88 % of its budget, else enough to come +/// down to 85 %. `VICTORY_TEXTURE_KEEP=0`: [`vram_idle_ms`]' older rule, +/// all that are idle; `=1`: that rule with its two longer times. +/// +/// (By those times everything idle for 2.5 s went from 75 % of the budget +/// on: 61,000 of them in the first 300 s of session play-1125-0203, at 78 to +/// 80 %, of which 13,000 were made and uploaded again.) +pub(crate) fn vram_keep(budget: u64, used: u64) -> (u64, u64) { + const KEPT_MS: u64 = 600_000; + const IDLE_MS: u64 = 5_000; + const SHORT_MS: u64 = 1_500; + if budget == 0 { + return (IDLE_MS, u64::MAX); + } + let share = |percent: u64| budget / 100 * percent; + if used < share(88) { + (KEPT_MS, u64::MAX) + } else if used < share(95) { + (IDLE_MS, used - share(85)) + } else { + (SHORT_MS, used - share(85)) + } +} + /// Effective idle timeout (in milliseconds) for VRAM-backed host textures, /// scaled down under VRAM pressure. Never returns less than 1,000 ms so /// handles not yet recorded into a list or slot remain protected. @@ -221,6 +249,12 @@ fn sweep() { crate::resource::let_go_idle(); } +/// The number of the newest submission begun, and of the newest of which all +/// before it have finished too. +pub(crate) fn submissions() -> (u64, u64) { + (STARTED.load(Ordering::Acquire), FINISHED.load(Ordering::Acquire)) +} + /// Drops `object` once every submission running now has finished: at once /// if none is. pub(crate) fn retire(object: T) { @@ -5530,8 +5564,10 @@ impl HostList { resource: crate::object::This, wanted: u32, ) -> Option<(&'static ID3D12Resource, u32)> { - let texture = crate::resource::host_resource(resource)?; let copy = crate::resource::host_copy(resource)?; + // SAFETY: as in `crate::resource::host_resource`; the list's states + // hold the copy from here on. + let texture: &'static ID3D12Resource = unsafe { &*std::ptr::from_ref(©.texture) }; let wanted = legal_state(texture, wanted); let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); match states.entry(std::sync::Arc::as_ptr(©) as usize) { @@ -7408,6 +7444,20 @@ impl Meter { crate::descriptor::host::STALE[4].load(Ordering::Relaxed) ); } + if crate::resource::held_only() { + let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed)); + let [flipped, missed] = [0, 1].map(|i| crate::descriptor::host::FLIPPED[i].load(Ordering::Relaxed)); + tracing::info!( + "textures from the first level viewed (VICTORY_HELD_LEVELS=0: whole), since the start: {copies} host copies of the \ + levels viewed alone ({} MB on the card, {} MB of title memory whole), {grown} replaced by one with more levels, \ + {flipped} slots made from their new view after its upload had run ({missed} written again first); {} uploads left \ + out as the host copy held those bytes (VICTORY_TEXTURE_SAME=0: made); {} MB of texture blocks free", + bytes >> 20, + whole >> 20, + crate::draw::HEAP_TEXTURES_SAME.load(Ordering::Relaxed), + crate::pool::texture_room() >> 20 + ); + } { let mode = crate::watch::page_writes(); let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed)); @@ -8904,6 +8954,18 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000); } + #[test] + fn textures_are_kept_while_the_card_has_room() { + use super::vram_keep; + let gib = 1 << 30; + assert_eq!(vram_keep(100 * gib, 87 * gib).0, 600_000); + // Past it: the longest idle ones, enough to come down to 85 %. + let (ms, bytes) = vram_keep(100 * gib, 90 * gib); + assert_eq!((ms, bytes), (5_000, 5 * gib)); + assert_eq!(vram_keep(100 * gib, 120 * gib), (1_500, 35 * gib)); + assert_eq!(vram_keep(0, 7).0, 5_000); + } + #[test] fn ram_idle_ms_scales_with_pressure() { use super::ram_idle_ms; diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index 32b3bfb..f05d963 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -20,7 +20,7 @@ use std::collections::{BTreeMap, VecDeque}; use std::ffi::c_void; use std::sync::Mutex; -use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use windows::Win32::Graphics::Direct3D12::*; use windows::core::{GUID, HRESULT, IUnknown, Interface}; @@ -199,6 +199,15 @@ fn lock(m: &'static Mutex) -> std::sync::MutexGuard<'static, T> { m.lock().unwrap_or_else(|e| e.into_inner()) } +/// Bytes of the pieces textures hold now. +static HELD: AtomicU64 = AtomicU64::new(0); + +/// Bytes of the texture blocks no texture holds: the card's memory in use +/// by us that new textures take first. +pub(crate) fn texture_room() -> u64 { + (lock(&TEXTURES).blocks() as u64 * BLOCK).saturating_sub(HELD.load(Ordering::Relaxed)) +} + /// For the memory line: blocks of textures and of staging buffers, in MiB. #[cfg(feature = "diagnostics")] pub(crate) fn memory() -> [u64; 2] { @@ -282,6 +291,7 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { let left = (*this.cast::()).references.fetch_sub(1, Ordering::AcqRel) - 1; if left == 0 { let gone = Box::from_raw(this.cast::()); + HELD.fetch_sub(gone.piece.len, Ordering::Relaxed); lock(&TEXTURES).give(gone.piece, now()); } left @@ -351,6 +361,7 @@ pub(crate) unsafe fn texture( let result = unsafe { device.CreatePlacedResource(&heap, piece.start, &d, state, None, &mut made) }; match (result, made) { (Ok(()), Some(made)) => { + HELD.fetch_add(piece.len, Ordering::Relaxed); give_back_with(&made, piece); Some(made) } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index db3621e..dc3de0d 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -98,6 +98,20 @@ pub(crate) struct ResourceDesc { flags: u32, } +#[cfg(windows)] +impl ResourceDesc { + /// The texture of this one's levels from `base` on. + fn from_level(&self, base: u32) -> ResourceDesc { + let mut d = *self; + if base > 0 { + d.width = (d.width >> base).max(1); + d.height = (d.height >> base).max(1); + d.mip_levels -= base as u16; + } + d + } +} + #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct AllocationInfo { @@ -1137,8 +1151,27 @@ pub(crate) struct HostTexture { /// levels have been given. Its `bytes` are 0: what it holds of the card /// is counted there. pub(crate) tiled: Option, + /// The title's level its level 0 is ([`held_only`]): larger levels have + /// no place in it. + pub(crate) base: u32, + /// Tells host copies apart that one texture had one after the other. + pub(crate) serial: u64, + /// Made in place of one with fewer levels: the slots that show that one + /// are made again once this one was filled whole. + pub(crate) grown: std::sync::atomic::AtomicBool, + /// What the last submitted upload put in it. + pub(crate) holds: std::sync::Arc, } +/// What a host copy was filled with last: the first level of it and the +/// hash of the title memory it was read from. +#[cfg(windows)] +pub(crate) type Holds = std::sync::Mutex>; + +/// [`HostTexture::serial`] of the last one made. +#[cfg(windows)] +static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + /// What a title texture has on the host: its host copy and, for a depth /// texture shaders also write, the colour twin. #[cfg(windows)] @@ -1167,6 +1200,149 @@ struct Hosted { gone: std::sync::atomic::AtomicBool, /// A texture of [`PLACED_TEXTURES`]. placed: std::sync::atomic::AtomicBool, + /// The lowest level a view asked for since it had no host copy + /// ([`want_level`]; `u32::MAX`: none said). + wanted: std::sync::atomic::AtomicU32, + /// The next host copy takes the place of one with fewer levels. + grown: std::sync::atomic::AtomicBool, +} + +/// Whether a texture the title places in memory is read, kept and uploaded +/// from the first level its views show on (`VICTORY_HELD_LEVELS=0`: whole, +/// as before). Such a title describes every level of a texture and views it +/// from the first one it holds; the memory of the larger ones is the next +/// texture's, or nothing. Of two recorded world frames the levels some slot +/// shows are 1.2 and 1.6 GB of the 6.3 and 6.7 GB of such host copies, and +/// most of what was found "changed" and uploaded again was other textures' +/// bytes. +#[cfg(windows)] +pub(crate) fn held_only() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + std::env::var_os("VICTORY_HELD_LEVELS").is_none_or(|v| v != "0") && !crate::tiles::wanted() + }) +} + +/// The first level a placed texture's view shows: of views of one 2D +/// texture (the others show whole textures). After victory-amd 4436f8f1. +pub(crate) fn first_mip(view: &[u32]) -> u32 { + const TEXTURE_2D_VIEW: u32 = 4; + match *view { + [_, TEXTURE_2D_VIEW, _, _, first, ..] => first.min(15), + _ => 0, + } +} + +/// The level from which on a texture of layout `layout` is read for a view +/// that starts at `first`: the smallest levels share a block and are read +/// together; 0 where the larger ones lie between the smaller ones. +pub(crate) fn read_from(layout: &victory_formats::texture::Layout, first: u32) -> u32 { + if layout.slices != 1 || layout.mips.is_empty() { + return 0; + } + let first = first.min(layout.first_tail_mip).min(layout.mips.len() as u32 - 1); + if layout.bytes_from(first) < layout.size { first } else { 0 } +} + +/// The level a host copy begins at for views that start at `first`: one the +/// host can have as a texture's level 0 ([`read_from`]; block-compressed +/// formats in whole blocks). +#[cfg(windows)] +fn base_level(desc: &ResourceDesc, first: u32) -> u32 { + const TEXTURE_2D: u32 = 3; + if first == 0 + || !fills(desc) + || desc.dimension != TEXTURE_2D + || desc.depth_or_array_size != 1 + || desc.mip_levels <= 1 + || desc.sample_count > 1 + { + return 0; + } + let Some(t) = texture_layout(desc).filter(|t| t.planes.len() == 1) else { + return 0; + }; + let layout = &t.planes[0].layout; + if layout.desc.swizzle.xor() { + return 0; + } + let block = u64::from(layout.desc.block.max(1)); + let mut base = read_from(layout, first).min(u32::from(desc.mip_levels) - 1); + let whole = |side: u64| side != 0 && side.is_multiple_of(block); + while base > 0 && !(whole(desc.width >> base) && whole(u64::from(desc.height) >> base)) { + base -= 1; + } + base +} + +/// The bytes of title memory a placed texture with the resource description +/// `desc` is read from for a view that starts at level `first`; `None` as +/// [`placed_bytes`]. Remembered: asked for every slot that is looked at. +#[cfg(windows)] +pub(crate) fn placed_bytes_from(desc: &[u32; 14], first: u32) -> Option { + if first == 0 || !held_only() { + return placed_bytes(desc); + } + type Known = std::collections::HashMap<([u32; 14], u32), Option>; + thread_local! { + static KNOWN: std::cell::RefCell = std::cell::RefCell::default(); + } + KNOWN.with(|known| { + *known.borrow_mut().entry((*desc, first)).or_insert_with(|| { + let whole = placed_bytes(desc)?; + // SAFETY: 56 bytes in the description's layout. + let d = unsafe { desc.as_ptr().cast::().read_unaligned() }; + let Some(t) = texture_layout(&d).filter(|t| t.planes.len() == 1) else { + return Some(whole); + }; + let layout = &t.planes[0].layout; + Some(layout.bytes_from(read_from(layout, first)).min(whole)) + }) + }) +} + +/// Host copies replaced by ones with more levels, for as long as a thread +/// that asked for one may still be about to record its use +/// ([`host_resource`]): when, and the copy. +#[cfg(windows)] +static REPLACED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Since the start: host copies made with a first level other than the +/// title's, and their bytes; host copies replaced by one with more levels; +/// bytes of title memory such copies' textures take whole. +#[cfg(windows)] +pub(crate) static HELD: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// A view of the placed texture `this` that starts at level `first` is made +/// or brought up to date: a host copy without that level is replaced by one +/// with it (made and filled at the next use; the slots that show the old +/// one go on showing it until that is done). +#[cfg(windows)] +pub(crate) fn want_level(this: This, first: u32) { + use std::sync::atomic::Ordering::Relaxed; + if this.is_null() || !held_only() { + return; + } + let r = resource(this); + if r.desc.dimension == BUFFER || !r.host.placed.load(Relaxed) { + return; + } + let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + let Some((host, _)) = made.as_ref() else { + r.host.wanted.fetch_min(first, Relaxed); + return; + }; + if host.base == 0 || host.base <= base_level(&r.desc, first) { + return; + } + r.host.wanted.store(first, Relaxed); + // Under the lock, as in `let_go_idle`. + crate::texture::unstage(this); + r.host.grown.store(true, Relaxed); + HELD[2].fetch_add(1, Relaxed); + if let Some(old) = made.take() { + REPLACED.lock().unwrap_or_else(|e| e.into_inner()).push((crate::host::moment(), old)); + } } /// Counts for the memory line: host copies of textures the title fills @@ -1353,9 +1529,20 @@ fn hosted(this: This, make: bool) -> Option { texture = reserved; } } + // The levels views show ([`held_only`]), those of the slots shaders + // pick by index among them. + let mut base = 0; + if shape_fits && r.host.placed.load(Relaxed) && held_only() && alias_of(this).is_none() { + let wanted = r.host.wanted.load(Relaxed); + let viewed = crate::descriptor::host::first_viewed(r.data() as u64).unwrap_or(u32::MAX); + let first = wanted.min(viewed); + if first != u32::MAX { + base = base_level(&r.desc, first); + } + } let texture = match texture { Some(texture) => Some(texture), - None => host_texture(&r.desc, r.host.state, clear), + None => host_texture(&r.desc.from_level(base), r.host.state, clear), }; let Some(texture) = texture else { r.host.refused.store(true, Relaxed); @@ -1378,6 +1565,13 @@ fn hosted(this: This, make: bool) -> Option { Some(tiled) => HostTexture::new_tiled(texture, state, tiled), None => HostTexture::new(texture, state), }; + host.base = base; + host.grown.store(r.host.grown.swap(false, Relaxed), Relaxed); + if base > 0 { + HELD[0].fetch_add(1, Relaxed); + HELD[1].fetch_add(host.bytes, Relaxed); + HELD[3].fetch_add(footprint(&r.desc).map_or(0, |f| f.size), Relaxed); + } host.filled = fills(&r.desc); if host.filled { KINDS[0].fetch_add(1, Relaxed); @@ -1455,7 +1649,8 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { // world makes in its first frame ([`targets_room_kept`]) counts as // used. Some([budget, used, ..]) => { - used + crate::shadow::card_room_kept() + targets_room_kept() < budget / 100 * room_percent() + used.saturating_sub(crate::pool::texture_room()) + crate::shadow::card_room_kept() + targets_room_kept() + < budget / 100 * room_percent() } None => filled < WITHOUT_BUDGET, } @@ -1777,12 +1972,52 @@ pub(crate) fn let_go_idle() { if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_none_or(|v| v != "0")) { return; } - let idle_ms = crate::host::vram_idle_ms(crate::host::host().and_then(|h| h.video_memory())); + // Copies replaced by ones with more levels, as any let go. + { + let mut replaced = REPLACED.lock().unwrap_or_else(|e| e.into_inner()); + let (gone, keep): (Vec<_>, Vec<_>) = + replaced.drain(..).partition(|(at, _)| crate::host::long_ago(*at, 1000, IDLE_FRAMES)); + *replaced = keep; + drop(replaced); + for (_, made) in gone { + crate::host::retire(made); + } + } + let memory = crate::host::host().and_then(|h| h.video_memory()); + static KEEP: std::sync::OnceLock = std::sync::OnceLock::new(); + let keep = *KEEP + .get_or_init(|| !matches!(std::env::var("VICTORY_TEXTURE_KEEP").as_deref(), Ok("0") | Ok("1"))); + let (idle_ms, most) = match memory { + Some([budget, used, ..]) if keep => { + let used = used.saturating_sub(crate::pool::texture_room()) + + crate::shadow::card_room_kept() + + targets_room_kept(); + crate::host::vram_keep(budget, used) + } + _ => (crate::host::vram_idle_ms(memory), u64::MAX), + }; // For the trail (`crate::host::trail`): how many went, their bytes, // and the first one. let (mut went, mut bytes, mut first) = (0u64, 0u64, None); let all = textures(); - for &at in all.iter() { + // With a limit, the longest idle first. + let mut by_age: Vec<(u64, usize)> = Vec::new(); + if most != u64::MAX { + for &at in all.iter() { + // SAFETY: as below. + let r = unsafe { &*(at as *const Resource) }; + let used = r.host.used.load(Relaxed); + if used != 0 && fills(&r.desc) && crate::host::long_ago(used, idle_ms, IDLE_FRAMES) { + by_age.push((used & 0xffff_ffff, at)); + } + } + by_age.sort_unstable(); + } + let every = all.iter().copied().filter(|_| most == u64::MAX); + for at in every.chain(by_age.iter().map(|&(_, at)| at)) { + if bytes >= most { + break; + } // SAFETY: a texture leaves the table before it is freed, under the // lock held here (`Drop for Resource`). let r = unsafe { &*(at as *const Resource) }; @@ -1800,6 +2035,7 @@ pub(crate) fn let_go_idle() { // Under the lock: the next use must not find the staging // state of the texture let go (it says "uploaded"). crate::texture::unstage(at as This); + r.host.wanted.store(u32::MAX, Relaxed); made.take() } else { None @@ -1973,6 +2209,10 @@ impl HostTexture { bytes, filled: false, tiled: None, + base: 0, + serial: SERIAL.fetch_add(1, Relaxed) + 1, + grown: Default::default(), + holds: Default::default(), } } @@ -1990,6 +2230,10 @@ impl HostTexture { bytes: 0, filled: false, tiled: Some(tiled), + base: 0, + serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1, + grown: Default::default(), + holds: Default::default(), } } } @@ -2054,6 +2298,15 @@ pub(crate) fn host_copy(this: This) -> Option> { hosted(this, true).map(|made| made.0) } +/// A title texture's host copy if it is made; not made here. +#[cfg(windows)] +pub(crate) fn made_copy(this: This) -> Option> { + if this.is_null() { + return None; + } + hosted(this, false).map(|made| made.0) +} + /// A host texture like the title's: same description, in GPU memory, /// without the console's layout and flags. #[cfg(windows)] @@ -2330,6 +2583,8 @@ fn hand_out_resource( refused: std::sync::atomic::AtomicBool::new(false), gone: std::sync::atomic::AtomicBool::new(false), placed: std::sync::atomic::AtomicBool::new(false), + wanted: std::sync::atomic::AtomicU32::new(u32::MAX), + grown: std::sync::atomic::AtomicBool::new(false), }, }); // The host copy waits for the texture's first use ([`Hosted`]). @@ -4140,4 +4395,37 @@ float4 lit() : SV_Target { return 1.0; } assert_eq!(texture_floor_bytes(Some(24 * GIB)), 2 * GIB); assert_eq!(texture_floor_bytes(Some(32 * GIB)), 2 * GIB); } + + /// A placed texture viewed from a later level has a host copy of that + /// and the smaller levels; a view from an earlier one gets another. + #[cfg(windows)] + #[test] + fn a_placed_texture_is_kept_from_the_level_viewed() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + if crate::host::host().is_none() || !held_only() { + return; + } + // 256x256 BC7, nine levels, 4 KiB blocks. + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = placed_bytes(&desc).unwrap(); + let part = placed_bytes_from(&desc, 2).unwrap(); + assert!(part * 8 < whole, "{part} of {whole}"); + assert_eq!(placed_bytes_from(&desc, 0), Some(whole)); + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole as usize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; + let texture = texture_at(at as u64, &desc).unwrap(); + want_level(texture, 2); + let copy = host_copy(texture).unwrap(); + // SAFETY: a live texture. + let d = unsafe { copy.texture.GetDesc() }; + assert_eq!((copy.base, d.Width, d.Height, d.MipLevels), (2, 64, 64, 7)); + want_level(texture, 5); + assert_eq!(host_copy(texture).unwrap().serial, copy.serial); + want_level(texture, 0); + let more = host_copy(texture).unwrap(); + // SAFETY: as above. + let d = unsafe { more.texture.GetDesc() }; + assert_eq!((more.base, d.Width, d.MipLevels), (0, 256, 9)); + assert!(more.serial != copy.serial && more.grown.load(std::sync::atomic::Ordering::Relaxed)); + } } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index f3c2a8d..f970f70 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -46,8 +46,20 @@ pub(crate) struct Staging { footprints: Vec, rows: Vec, layout: victory_formats::texture::Layout, - /// Mips per array slice. + /// Mips per array slice, of the title's texture. mips: u32, + /// The first of them that is read and uploaded + /// (`crate::resource::held_only`), the one the host copy begins at, and + /// the bytes of title memory read. + first: u32, + level0: u32, + read: usize, + /// Which host copy it uploads into, and what that is told to hold. + serial: u64, + holds: Arc, + /// Title memory being remapped is waited for whatever [`no_wait`] says: + /// a list that bakes from the texture now recorded the upload. + waits: std::sync::atomic::AtomicBool, /// The staging buffer's bytes (counted in `STAGED` while it lives). bytes: u64, memory: *const u8, @@ -160,6 +172,8 @@ pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool { const TARGET_OR_UNORDERED: u32 = 0x4 | 0x8; const COPY_DEST: u32 = 0x400; const COPY_SOURCE: u32 = 0x800; + // (All of its levels: the copy is level by level.) + crate::resource::want_level(placed, 0); let (Some(to), Some(from)) = ( crate::resource::host_resource(placed), crate::resource::host_resource(source), @@ -629,7 +643,21 @@ pub(crate) fn title_written(texture: &ID3D12Resource) -> bool { /// its host copy, and the detiling that refreshes the staging buffer at /// submission if the memory changed. Leaves the texture in the copy /// destination state. -pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { +pub(crate) fn upload(list: &HostList, resource: This, _texture: &ID3D12Resource) { + upload_from(list, resource, 0); +} + +thread_local! { + /// The thread records uploads for a draw that bakes from them + /// ([`Staging::waits`]). + pub(crate) static BAKING: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// [`upload`] of the levels from `first` on, the ones a view shows: of a +/// texture the title placed there may be no memory of the larger ones, and +/// what lies there is another texture's. (After victory-amd 4436f8f1.) +pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { + let first = if crate::resource::held_only() { first } else { 0 }; let host_written = HOST_WRITTEN .lock() .unwrap_or_else(|e| e.into_inner()) @@ -637,13 +665,28 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) .is_some_and(|set| set.contains(&(resource as usize))); // shortcut: a texture the host copied into keeps the host's contents // even if the title later writes its memory too. - if host_written || !list.first_use(resource as usize) { + if host_written { return; } - let Some(staging) = staging(resource, texture) else { + // Once a list for each first level; not again for one that the list's + // upload of larger ones held too. + if !list.first_use(1 << 63 | (resource as usize) << 4 | first as usize & 15) { + return; + } + if !list.first_use(resource as usize) && staged_from(resource) <= first { + return; + } + let Some(copy) = crate::resource::host_copy(resource) else { + return; + }; + let texture = ©.texture; + let Some(staging) = staging(resource, ©, first) else { return; }; use std::sync::atomic::Ordering::Relaxed; + if BAKING.get() { + staging.waits.store(true, Relaxed); + } staging.used.store(crate::host::moment(), Relaxed); // Levels on demand: a view of the texture now starts at another // level, or another texture now starts inside its span, with no byte @@ -684,7 +727,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexUploads, 1); if no_wait() && fill_unlocked() { - let there = mapped_bytes(staging.memory, staging.layout.size as usize); + let there = mapped_bytes(staging.memory, staging.read); staging.expected.store(there, Relaxed); } const COPY_DEST: u32 = 0x400; @@ -741,7 +784,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) pResource: unsafe { std::mem::transmute_copy(texture) }, Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: i as u32, + SubresourceIndex: staging.first - staging.level0 + i as u32, }, }; let from = D3D12_TEXTURE_COPY_LOCATION { @@ -768,6 +811,13 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) staging.dirty.store(false, Relaxed); }); } + // A host copy that took the place of one with fewer levels: the slots + // that show that one are made again once this upload has run. + if staging.first == staging.level0 && copy.grown.swap(false, Relaxed) { + let start = staging.memory as u64; + list.defer_host(move || crate::descriptor::host::levels_changed_after(start)); + } + let noted = staging.clone(); // Levels on demand (`crate::tiles`): after the check below, in the // order of this list's steps, and before the list is executed, the // levels the staging buffer holds as the title's are given the card's @@ -778,6 +828,8 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) let Some(on_demand) = on_demand else { // Once per submission however many of its lists sample the texture. list.defer_texture(staging); + // Then what the list's copy puts in the host copy is known. + list.defer_host(move || noted.note_held()); return; }; list.defer_texture(staging.clone()); @@ -971,7 +1023,21 @@ impl Staging { /// The title memory the texture is read from: address and bytes. pub(crate) fn memory(&self) -> (usize, usize) { - (self.memory as usize, self.layout.size as usize) + (self.memory as usize, self.read) + } + + /// The title's level and the array slice of the staging buffer's part + /// `i`. + fn part(&self, i: usize) -> (u32, u32) { + let mips = self.mips - self.first; + (self.first + i as u32 % mips, i as u32 / mips) + } + + /// The host copy holds what the staging buffer was filled from + /// ([`unchanged`]). + fn note_held(&self) { + let hash = self.last.lock().unwrap_or_else(|e| e.into_inner()).hash; + *self.holds.lock().unwrap_or_else(|e| e.into_inner()) = hash.map(|hash| (self.first, hash)); } /// Detiles the texture memory into the staging buffer if it changed @@ -994,7 +1060,7 @@ impl Staging { } fn refresh_timed(&self) -> usize { - let size = self.layout.size as usize; + let size = self.read; let start = self.memory as usize; let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); let last = &mut *last; @@ -1061,7 +1127,7 @@ impl Staging { // stays mapped (see `crate::watch::title_memory_reading`; without // it a page went between the asking and the read in runs 71 and // 74). - let _mapped = if no_wait() { + let _mapped = if no_wait() && !self.waits.load(std::sync::atomic::Ordering::Relaxed) { // Not waited for: while the runtime remaps title memory the // texture is read through the kernel instead, whole or not at // all (`no_wait`). @@ -1240,7 +1306,7 @@ impl Staging { ); } for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() { - let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); + let (mip, slice) = self.part(i); let f = footprint.Footprint; let pitch = f.RowPitch as usize; // The last row of the last subresource is not padded to its pitch @@ -1330,6 +1396,59 @@ pub(crate) fn staged_state(resource: This) -> Option<(bool, bool)> { Some((staging.uploaded.load(Relaxed), staging.dirty.load(Relaxed))) } +/// The first level a title texture's staging buffer holds; `u32::MAX` +/// without one. +fn staged_from(resource: This) -> u32 { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + map.as_ref() + .and_then(|map| map.get(&(resource as usize))) + .map_or(u32::MAX, |s| s.first) +} + +/// Whether the levels from `first` on of `resource`'s host copy were filled +/// from the bytes title memory holds now: an upload would bring nothing new. +/// (Of 787 repeated uploads of a frame that streams 398 were equal in every +/// byte, and a texture uploaded again costs a staging buffer, a detiling and +/// a copy more than this look.) `VICTORY_TEXTURE_SAME=0`: not asked. +pub(crate) fn unchanged(resource: This, first: u32) -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SAME").is_none_or(|v| v != "0")) { + return false; + } + let Some(copy) = crate::resource::made_copy(resource) else { + return false; + }; + let Some((from, held)) = *copy.holds.lock().unwrap_or_else(|e| e.into_inner()) else { + return false; + }; + let Some((memory, desc)) = crate::resource::texture_memory(resource) else { + return false; + }; + let Some(layout) = crate::resource::texture_layout(&desc) else { + return false; + }; + let layout = &layout.planes[0].layout; + if from > crate::resource::read_from(layout, first).max(copy.base) { + return false; + } + let size = layout.bytes_from(from) as usize; + with_read(size, |read| { + if crate::host::read_there(memory, read) == 0 { + return false; + } + blake3::hash(read) == held + }) +} + +/// Where the levels from `first` on of a title texture are: address and +/// bytes. +pub(crate) fn title_span(resource: This, first: u32) -> Option<(u64, u64)> { + let (memory, desc) = crate::resource::texture_memory(resource)?; + let layout = crate::resource::texture_layout(&desc)?; + let layout = &layout.planes[0].layout; + Some((memory as u64, layout.bytes_from(crate::resource::read_from(layout, first)))) +} + pub(crate) fn is_staged(resource: This) -> bool { let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); map.as_ref().is_some_and(|map| map.contains_key(&(resource as usize))) @@ -1342,8 +1461,7 @@ pub(crate) fn staged(resource: This) -> Option<(u64, bool)> { let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); map.as_ref()?.get(&(resource as usize))?.clone() }; - let size = s.layout.size as usize; - Some((size as u64, committed(s.memory, size))) + Some((s.read as u64, committed(s.memory, s.read))) } /// Whether `[at, at + len)` is committed memory (streamed textures may be @@ -1509,13 +1627,17 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 { } /// The staging state of a title texture, made on first use. -fn staging(resource: This, texture: &ID3D12Resource) -> Option> { +fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> Option> { + let texture = ©.texture; // Asked before the table is locked: the sweep lets go of a staging // buffer with its texture's host side locked, in that order. let on_demand = crate::resource::host_tiled(resource).is_some(); let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); let map = map.get_or_insert_with(HashMap::new); - if let Some(s) = map.get(&(resource as usize)) { + if let Some(s) = map.get(&(resource as usize)) + && s.first <= first.max(copy.base) + && s.serial == copy.serial + { return Some(s.clone()); } let (memory, desc) = crate::resource::texture_memory(resource)?; @@ -1534,10 +1656,14 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { let host = host()?; // SAFETY: a live resource. let d = unsafe { texture.GetDesc() }; + let level0 = copy.base; + let mips = level0 + u32::from(d.MipLevels); + let first = crate::resource::read_from(&layout, first).max(level0).min(mips - 1); + let read = layout.bytes_from(first) as usize; let count = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { - u32::from(d.MipLevels) + mips - first } else { - u32::from(d.MipLevels) * u32::from(d.DepthOrArraySize) + (mips - first) * u32::from(d.DepthOrArraySize) }; let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize]; let mut rows = vec![0u32; count as usize]; @@ -1546,7 +1672,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { unsafe { host.device.GetCopyableFootprints( &d, - 0, + first - level0, count, 0, Some(footprints.as_mut_ptr()), @@ -1581,7 +1707,13 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { footprints, rows, layout, - mips: u32::from(d.MipLevels), + mips, + first, + level0, + read, + serial: copy.serial, + holds: copy.holds.clone(), + waits: std::sync::atomic::AtomicBool::new(false), bytes: total, memory, last: Mutex::default(), @@ -1800,6 +1932,65 @@ mod allocation_costs { } } + /// What a texture met for the first time costs, by step, in + /// milliseconds a megabyte on one thread: for whether a store of + /// detiled copies on disk could be worth it (its key is a hash of the + /// title's bytes, so reading and hashing them stay; `VICTORY_BENCH_FILE` + /// is a big file to read past the system's cache). + #[test] + #[ignore = "a measurement, not a check"] + fn cold_texture_costs() { + let Some(host) = crate::host::host() else { return }; + let desc = [3u32, 0, 0, 0, 1024, 0, 1024, 0xb_0001, 98, 1, 0, 0x105, 0, 0]; + // SAFETY: 56 bytes in the description's layout. + let desc = unsafe { desc.as_ptr().cast::().read_unaligned() }; + let layout = crate::resource::texture_layout(&desc).unwrap().planes[0].layout.clone(); + let size = layout.size as usize; + let title: Vec = (0..size).map(|i| (i.wrapping_mul(2654435761) >> 13) as u8).collect(); + let (_buffer, up) = host.upload_buffer(2 * layout.size).unwrap(); + // SAFETY: the mapping. + let up = unsafe { std::slice::from_raw_parts_mut(up, 2 * size) }; + let mut read = vec![0u8; size]; + const N: u32 = 200; + let per_mb = |t: std::time::Duration| t.as_secs_f64() * 1e3 / (f64::from(N) * size as f64 / 1e6); + let timed = |what: &str, f: &mut dyn FnMut()| { + f(); + let started = std::time::Instant::now(); + (0..N).for_each(|_| f()); + println!("{what}: {:.3} ms/MB", per_mb(started.elapsed())); + }; + timed("read through the kernel or a safe copy", &mut || { + std::hint::black_box(crate::host::read_into(title.as_ptr(), &mut read)); + }); + timed("blake3", &mut || { + std::hint::black_box(blake3::hash(&title)); + }); + timed("detiled into upload memory", &mut || { + let mut at = 0; + for (mip, m) in layout.mips.iter().enumerate() { + let pitch = (m.width as usize * 16).next_multiple_of(256); + let len = pitch * m.height as usize; + layout.detile(&title, mip as u32, 0, &mut up[at..at + len], pitch, len).unwrap(); + at += len.next_multiple_of(512); + } + }); + timed("copied into upload memory", &mut || up[..size].copy_from_slice(&title)); + if let Some(file) = std::env::var_os("VICTORY_BENCH_FILE") { + use std::os::windows::fs::{FileExt, OpenOptionsExt}; + const NO_BUFFERING: u32 = 0x2000_0000; + let file = std::fs::OpenOptions::new().read(true).custom_flags(NO_BUFFERING).open(file).unwrap(); + let len = file.metadata().unwrap().len(); + let mut block = vec![0u8; size + 4096]; + let skew = block.as_ptr().align_offset(4096); + let n = size / 4096 * 4096; + let mut at = 0u64; + timed("read from the disk, one request at a time", &mut || { + at = (at + 7919 * 4096 * 64) % (len - n as u64) / 4096 * 4096; + file.seek_read(&mut block[skew..skew + n], at).unwrap(); + }); + } + } + #[test] #[ignore = "a measurement, not a check"] fn allocation_costs() { From 6ff1e14aadf4c2d4a9ec4bd9eb60bcc23342db31 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 02:58:07 -0600 Subject: [PATCH 306/445] Diagnostics: a sampling profiler (VICTORY_PROFILE=,,,[;...]) Samples the 28 busiest threads, whole stacks, with what the frame is at. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/run.rs | 1 + crates/victory-gpu/src/copystat.rs | 18 +++ crates/victory-gpu/src/lib.rs | 6 + crates/victory-hle/src/lib.rs | 3 + crates/victory-loader/src/lib.rs | 4 + crates/victory-loader/src/profile.rs | 195 +++++++++++++++++++++++++++ crates/victory-loader/src/stacks.rs | 22 +-- 7 files changed, 241 insertions(+), 8 deletions(-) create mode 100644 crates/victory-loader/src/profile.rs diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 3cc3b12..0d05390 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -196,6 +196,7 @@ pub fn run( #[cfg(all(windows, feature = "diagnostics"))] fn diagnostics(image: &victory_loader::LoadedImage, cfg: &victory_core::Config) { victory_loader::dump_stacks_on_schedule(); + victory_loader::profile_on_schedule(victory_hle::frame_phase); victory_hle::modules::audio::capture::start(); watch(image.base(), image.info().size_of_image as usize); poke(image.base(), image.info().size_of_image as usize); diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 1fdd273..c43d1af 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -1009,6 +1009,7 @@ pub(crate) fn recorded(started: std::time::Instant) { /// submission lock). pub(crate) fn submission_begins() { let now = now_us(); + INSIDE.fetch_add(1, Relaxed); if !SUBMITTED_SINCE.load(Relaxed) && !SUBMITTED_SINCE.swap(true, Relaxed) { add(C::UntilSubmitUs, now.saturating_sub(PRESENTED_AT.load(Relaxed))); } @@ -1029,6 +1030,7 @@ pub(crate) fn submission_begins() { /// submission lock. pub(crate) fn submission_ends(lock: u64) { let now = now_us(); + INSIDE.fetch_sub(1, Relaxed); SUBMITTED_AT.store(now, Relaxed); let (user, kernel) = thread_times(); let (u, k) = ENTERED.with(|e| e.get()); @@ -1042,6 +1044,22 @@ pub(crate) fn submission_ends(lock: u64) { s.inside_kernel += kernel.saturating_sub(k); } +/// The submissions being prepared now. +static INSIDE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// What the frame is at, for the sampling profiler (`VICTORY_PROFILE`): 3 +/// in a submission, else 0 after a present until the first list call, 1 until +/// the first submission, 2 behind it. +pub(crate) fn phase() -> u32 { + if INSIDE.load(Relaxed) > 0 { + 3 + } else if SUBMITTED_SINCE.load(Relaxed) { + 2 + } else { + u32::from(RECORDED_SINCE.load(Relaxed)) + } +} + /// The title calls its present (before our own copy to the window runs). pub(crate) fn present_begins() { add(C::TailUs, now_us().saturating_sub(SUBMITTED_AT.load(Relaxed))); diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 532cf78..a0199ae 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -73,6 +73,12 @@ mod watch; #[cfg(windows)] pub use host::on_failure; + +/// What the frame is at (`copystat::phase`), for the sampling profiler. +#[cfg(all(windows, feature = "diagnostics"))] +pub fn frame_phase() -> u32 { + copystat::phase() +} #[cfg(windows)] pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view}; #[cfg(windows)] diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs index f9b9a86..0ad25ff 100644 --- a/crates/victory-hle/src/lib.rs +++ b/crates/victory-hle/src/lib.rs @@ -13,6 +13,9 @@ mod host; mod image_watch; +#[cfg(all(windows, feature = "diagnostics"))] +pub use victory_gpu::frame_phase; + pub mod modules; mod registry; pub mod runtime; diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 5a65fa6..9ae6730 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -28,6 +28,8 @@ pub mod prepare; pub(crate) mod publish; pub mod resolve; #[cfg(all(windows, feature = "diagnostics"))] +mod profile; +#[cfg(all(windows, feature = "diagnostics"))] mod stacks; #[cfg(windows)] mod threads; @@ -48,6 +50,8 @@ pub use prepare::{PrepareError, PreparedImage, prepare}; pub use resolve::{ImportResolver, Provenance, Resolution}; #[cfg(all(windows, feature = "diagnostics"))] pub use stacks::{dump_stacks, dump_stacks_on_schedule}; +#[cfg(all(windows, feature = "diagnostics"))] +pub use profile::profile_on_schedule; #[cfg(windows)] pub use threads::disable_thread_calls; #[cfg(windows)] diff --git a/crates/victory-loader/src/profile.rs b/crates/victory-loader/src/profile.rs new file mode 100644 index 0000000..d9142db --- /dev/null +++ b/crates/victory-loader/src/profile.rs @@ -0,0 +1,195 @@ +//! Where the process's time goes: `VICTORY_PROFILE=,,,` +//! samples the stacks of the busiest threads every `` milliseconds +//! between two times (seconds, as `VICTORY_STACKS`), and writes them counted +//! to `` at the end (several of them, one after another, with `;` +//! between). A thread that waits is sampled like one that +//! runs: its top frame says which (`ntdll`'s system calls). +//! +//! The file: `thread `, then +//! `stack ;;...` (innermost first, as +//! `module+rva`), where the phase is what the caller's function says of the +//! frame at that moment. + +use std::collections::HashMap; +use std::io::Write; +use std::time::{Duration, Instant}; + +use windows_sys::Win32::Foundation::{CloseHandle, FILETIME, HANDLE}; +use windows_sys::Win32::System::Threading::{ + GetThreadTimes, OpenThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME, +}; + +use crate::crash::locate; +use crate::stacks::{frames_of, name_of, other_threads, start_of}; + +/// The threads sampled: those that ran most since they were last chosen. +const BUSIEST: usize = 28; +/// How often they are chosen anew. +const CHOOSE: Duration = Duration::from_secs(1); + +/// What `VICTORY_PROFILE` says: from, to, every, the file. +fn asked(list: &str) -> Option<(Duration, Duration, Duration, String)> { + let mut parts = list.splitn(4, ','); + let mut seconds = || parts.next()?.trim().parse::().ok(); + let (from, to, ms) = (seconds()?, seconds()?, seconds()?); + let of = |s: f64| Duration::try_from_secs_f64(s).ok(); + let file = parts.next()?.trim().to_string(); + Some((of(from)?, of(to)?, of(ms / 1000.0)?, file)).filter(|(a, b, ms, f)| a < b && !ms.is_zero() && !f.is_empty()) +} + +struct Thread { + handle: HANDLE, + start: String, + name: String, + /// Its processor time, 100 ns: at first, when last chosen, now. + first: u64, + last: u64, + now: u64, + samples: u64, +} + +fn cpu(thread: HANDLE) -> u64 { + // SAFETY: zeroed is a valid FILETIME, and the calls write them. + let mut t: [FILETIME; 4] = unsafe { std::mem::zeroed() }; + let [a, b, c, d] = &mut t; + // SAFETY: an open thread; the pointers are to the structures above. + unsafe { GetThreadTimes(thread, a, b, c, d) }; + let of = |f: &FILETIME| u64::from(f.dwHighDateTime) << 32 | u64::from(f.dwLowDateTime); + of(&t[2]) + of(&t[3]) +} + +/// Reads `VICTORY_PROFILE` and, if set, starts the thread that samples. +/// `phase` is asked at each round. +pub fn profile_on_schedule(phase: fn() -> u32) { + let Ok(list) = std::env::var("VICTORY_PROFILE") else { + return; + }; + let start = Instant::now(); + let all: Vec<_> = list.split(';').filter_map(asked).collect(); + std::thread::spawn(move || { + for one in all { + profile(one, start, phase); + } + }); +} + +fn profile((from, to, every, file): (Duration, Duration, Duration, String), start: Instant, phase: fn() -> u32) { + std::thread::sleep(from.saturating_sub(start.elapsed())); + eprintln!("VIctory: the profile begins"); + let mut threads: HashMap = HashMap::new(); + let mut chosen: Vec = Vec::new(); + let mut counts: HashMap<(u32, u32, Vec), u64> = HashMap::new(); + let mut phases: HashMap = HashMap::new(); + let mut choose_at = Instant::now(); + let mut rounds = 0u64; + while start.elapsed() < to { + let round = Instant::now(); + if round >= choose_at { + choose_at = round + CHOOSE; + choose(&mut threads, &mut chosen); + } + let phase = phase(); + *phases.entry(phase).or_default() += 1; + for id in &chosen { + if let Some(t) = threads.get_mut(id) { + let (frames, _) = frames_of(t.handle); + t.samples += 1; + if !frames.is_empty() { + *counts.entry((*id, phase, frames)).or_default() += 1; + } + } + } + rounds += 1; + std::thread::sleep(every.saturating_sub(round.elapsed())); + } + choose(&mut threads, &mut chosen); + if let Err(e) = write(&file, &threads, &counts, &phases, rounds) { + eprintln!("VIctory: the profile was not written: {e}"); + } else { + eprintln!("VIctory: the profile is in {file}"); + } +} + +/// Opens the threads that are new, and chooses the ones to sample. +fn choose(threads: &mut HashMap, chosen: &mut Vec) { + for id in other_threads() { + threads.entry(id).or_insert_with(|| { + // SAFETY: opens a thread of our own process; kept open for the + // profile's life, so the id stays its own. + let handle = + unsafe { OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 0, id) }; + let first = if handle.is_null() { 0 } else { cpu(handle) }; + Thread { + handle, + start: if handle.is_null() { String::new() } else { locate(start_of(handle)) }, + name: if handle.is_null() { String::new() } else { name_of(handle) }, + first, + last: first, + now: first, + samples: 0, + } + }); + } + let mut ran: Vec<(u64, u32)> = Vec::new(); + for (&id, t) in threads.iter_mut().filter(|(_, t)| !t.handle.is_null()) { + t.now = cpu(t.handle); + ran.push((t.now - t.last, id)); + t.last = t.now; + } + ran.sort_unstable_by(|a, b| b.cmp(a)); + *chosen = ran.into_iter().take(BUSIEST).map(|(_, id)| id).collect(); +} + +fn write( + file: &str, + threads: &HashMap, + counts: &HashMap<(u32, u32, Vec), u64>, + phases: &HashMap, + rounds: u64, +) -> std::io::Result<()> { + let mut out = std::io::BufWriter::new(std::fs::File::create(file)?); + writeln!(out, "rounds {rounds}")?; + for (phase, n) in phases { + writeln!(out, "phase {phase} {n}")?; + } + let mut names: HashMap = HashMap::new(); + for (id, t) in threads { + writeln!(out, "thread {id} {} {} {} {}", t.start, (t.now - t.first) / 10_000, t.samples, t.name)?; + if !t.handle.is_null() { + // SAFETY: opened by `choose`. + unsafe { CloseHandle(t.handle) }; + } + } + for ((id, phase, frames), n) in counts { + write!(out, "stack {id} {phase} {n} ")?; + for f in frames { + let name = names.entry(*f).or_insert_with(|| locate(*f as usize)); + write!(out, "{name};")?; + } + writeln!(out)?; + } + out.flush() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn what_is_asked_is_read_whole_or_not_at_all() { + assert_eq!( + asked("150, 160.5,5,D:\\a b,c.txt"), + Some(( + Duration::from_secs(150), + Duration::from_millis(160_500), + Duration::from_millis(5), + "D:\\a b,c.txt".to_string() + )) + ); + assert_eq!(asked("150,160,5"), None); + assert_eq!(asked("160,150,5,x"), None); + assert_eq!(asked("a,160,5,x"), None); + assert_eq!(asked("-1,160,5,x"), None); + assert_eq!(asked("1,160,0,x"), None); + } +} diff --git a/crates/victory-loader/src/stacks.rs b/crates/victory-loader/src/stacks.rs index 214dda9..85c8132 100644 --- a/crates/victory-loader/src/stacks.rs +++ b/crates/victory-loader/src/stacks.rs @@ -66,10 +66,8 @@ struct BasicInfo { #[repr(C, align(16))] struct Aligned(CONTEXT); -/// Prints every other thread's stack to stderr. Each thread is suspended -/// only while its context is read and unwound into a buffer allocated -/// beforehand (it may hold the heap lock). -pub fn dump_stacks() { +/// The ids of this process's threads but the caller's. +pub(crate) fn other_threads() -> Vec { // SAFETY: plain queries and a snapshot of this process's threads. let (me, process, snapshot) = unsafe { ( @@ -79,7 +77,7 @@ pub fn dump_stacks() { ) }; if snapshot == INVALID_HANDLE_VALUE { - return; + return Vec::new(); } let mut ids = Vec::new(); // SAFETY: zeroed is a valid THREADENTRY32; its size is set before use. @@ -96,6 +94,14 @@ pub fn dump_stacks() { } // SAFETY: we opened it. unsafe { CloseHandle(snapshot) }; + ids +} + +/// Prints every other thread's stack to stderr. Each thread is suspended +/// only while its context is read and unwound into a buffer allocated +/// beforehand (it may hold the heap lock). +pub fn dump_stacks() { + let ids = other_threads(); eprintln!("VIctory: stacks of {} threads", ids.len()); for id in ids { // SAFETY: opens a thread of our own process. @@ -124,7 +130,7 @@ pub fn dump_stacks() { } /// The thread's frames and its current and base scheduling priority (0-31). -fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { +pub(crate) fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { let mut frames = Vec::with_capacity(MAX_FRAMES); let mut info: BasicInfo = BasicInfo { exit_status: 0, @@ -173,7 +179,7 @@ fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { (frames, (info.priority, info.base_priority)) } -fn start_of(thread: HANDLE) -> usize { +pub(crate) fn start_of(thread: HANDLE) -> usize { let mut start = 0usize; // SAFETY: writes one pointer-sized start address. unsafe { @@ -188,7 +194,7 @@ fn start_of(thread: HANDLE) -> usize { start } -fn name_of(thread: HANDLE) -> String { +pub(crate) fn name_of(thread: HANDLE) -> String { let mut name = std::ptr::null_mut(); // SAFETY: the system allocates the string; we free it with LocalFree. unsafe { From 49d71266b25f8d432cfc86ec3d27c304a5191e66 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:06:38 -0600 Subject: [PATCH 307/445] Streaming: mapping calls ask only for what they need; the thread that loads runs ahead; a streaming log All of the title's loading goes through one thread of its own, which maps the pages of a batch and then submits it. Each page took up to four system calls (unmap, split, map, commit), each waiting for the address-space lock: 200-400 us a page in the world. No split of a placeholder that is the view's own, no commit of section pages that are committed (VICTORY_MAP_LEAN=0: as before); the thread, below normal priority as the title sets it, is lifted above it where it maps (VICTORY_STREAM_PRIORITY=0: not). VICTORY_DSTORAGE_LOG=: every request, status entry and the cost of the mapping calls; VICTORY_STACKS names each thread's affinity. Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/dstorage.rs | 119 +++++++++- crates/victory-hle/src/modules/xmem.rs | 248 +++++++++++++++++++-- crates/victory-loader/src/stacks.rs | 12 +- 3 files changed, 345 insertions(+), 34 deletions(-) diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index f74ddfc..5d0a5f2 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -151,6 +151,9 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out let file = unsafe { std::fs::File::from_raw_handle(handle) }; let files = Files::new(file, Io::chosen()); let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { files }); + if stream_log::on() { + stream_log::line(format_args!("F\t{:x}\t{kept}", file as usize)); + } WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept)); put(out, file) } @@ -170,9 +173,10 @@ extern "system" fn create_status_array( "dstorage: status array" ); let entries = (0..capacity).map(|_| AtomicI32::new(S_OK)).collect(); + let written = (0..capacity).map(|_| AtomicU64::new(0)).collect(); let array = Instance::create( Object::new("dstorage status array", &STATUS_VTABLE), - StatusArray { entries }, + StatusArray { entries, written }, ); put(out, array) } @@ -459,6 +463,9 @@ static FILE_VTABLE: Methods<8> = Methods([ struct StatusArray { entries: Box<[AtomicI32]>, + /// For the log: when each entry was written ([`stream_log::now`]); 0 + /// once the title has seen it. + written: Box<[AtomicU64]>, } type Array = *mut Instance; @@ -476,7 +483,15 @@ extern "system" fn status_result(this: Array, index: u32) -> HRESULT { /// The title polls this (entry 0, a `Sleep(1)` loop) and never /// reads the result itself. extern "system" fn is_complete(this: Array, index: u32) -> bool { - status_result(this, index) != E_PENDING + let done = status_result(this, index) != E_PENDING; + if done && stream_log::on() { + // SAFETY: as above. + let written = &unsafe { &*this }.state.written; + if let Some(at) = written.get(index as usize).map(|w| w.swap(0, Ordering::Relaxed)).filter(|&at| at != 0) { + stream_log::line(format_args!("P\t{:x}\t{at}\t{}", this as usize, stream_log::now())); + } + } + done } static STATUS_VTABLE: Methods<5> = Methods([ @@ -671,6 +686,83 @@ fn walls_request(request: &Request, result: &Result<(), HRESULT>, started: std:: ); } +/// The streaming log (`VICTORY_DSTORAGE_LOG=`): a line for every +/// request (`R`: queue, number, file, offset, source bytes, destination +/// bytes, options, when enqueued, submitted, started, done, result), every +/// status entry written (`S`: array, number, when enqueued, when written), +/// the title's first look at it after (`P`: array, when written, when +/// seen), every file opened (`F`), and each second what the title's mapping +/// calls cost (`M`, `xmem::map_costs`). Times are milliseconds since the +/// Unix epoch. +pub(crate) mod stream_log { + use super::*; + use std::io::Write; + + type Log = Mutex>; + + fn log() -> Option<&'static Log> { + static LOG: OnceLock> = OnceLock::new(); + LOG.get_or_init(|| { + let path = std::env::var_os("VICTORY_DSTORAGE_LOG")?; + let file = std::fs::File::create(&path).ok()?; + std::thread::spawn(|| { + loop { + std::thread::sleep(std::time::Duration::from_secs(1)); + if let Some(costs) = super::super::xmem::map_costs() { + line(format_args!("M\t{}\t{costs}", now())); + } + if let Some(log) = log() { + let _ = log.lock().unwrap_or_else(|e| e.into_inner()).flush(); + } + } + }); + Some(Mutex::new(std::io::BufWriter::with_capacity(1 << 20, file))) + }) + .as_ref() + } + + pub(crate) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_DSTORAGE_LOG").is_some()) + } + + /// Milliseconds since the Unix epoch. + pub(super) fn now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |t| t.as_millis() as u64) + } + + pub(super) fn line(text: std::fmt::Arguments) { + if let Some(log) = log() { + let _ = writeln!(log.lock().unwrap_or_else(|e| e.into_inner()), "{text}"); + } + } + + pub(super) fn request(job: &Job, started: std::time::Instant, result: &Result<(), HRESULT>) { + if !on() { + return; + } + let now = now(); + let ago = |t: Option| now - t.map_or(0, |t| t.elapsed().as_millis() as u64); + let r = &job.request; + line(format_args!( + "R\t{}\t{}\t{:x}\t{}\t{}\t{}\t{:x}\t{}\t{}\t{}\t{now}\t{:x}", + job.lane, + job.seq, + r.source as usize, + r.offset, + r.source_size, + r.destination_size, + r.options, + ago(job.note.enqueued), + ago(job.note.submitted), + ago(Some(started)), + result.err().unwrap_or(0) + )); + } +} + /// A worker: runs the next read of the most deserving queue. fn work(scheduler: &'static Scheduler) { let mut lanes = scheduler.lock(); @@ -684,6 +776,7 @@ fn work(scheduler: &'static Scheduler) { let traced = Traced::start(&job); let result = execute(&job.request); walls_request(&job.request, &result, started); + stream_log::request(&job, started, &result); if let Some(traced) = traced { traced.end(&job, &result); } @@ -848,6 +941,11 @@ impl Lane { let first = std::mem::replace(&mut self.failures, later) .into_values() .next(); + if stream_log::on() { + let at = stream_log::now(); + stream_log::line(format_args!("S\t{:x}\t{seq}\t{}\t{at}", status.array as usize, status.enqueued)); + status.written().store(at, Ordering::Relaxed); + } status .entry() .store(first.unwrap_or(S_OK), Ordering::Release); @@ -965,6 +1063,7 @@ struct Note { impl Note { fn enqueued(request: &Request) -> Note { match trace() { + 0 if stream_log::on() => Note { enqueued: Some(std::time::Instant::now()), ..Note::default() }, 0 => Note::default(), _ => Note { enqueued: Some(std::time::Instant::now()), @@ -976,8 +1075,10 @@ impl Note { fn submitted(&mut self, request: &Request, early: bool) { self.early = early; - if trace() > 0 { + if trace() > 0 || stream_log::on() { self.submitted = Some(std::time::Instant::now()); + } + if trace() > 0 { self.at_submit = list_hash(request); } } @@ -1131,6 +1232,8 @@ impl Traced { struct Status { array: Array, index: u32, + /// For the log. + enqueued: u64, } impl Drop for Status { @@ -1144,6 +1247,11 @@ impl Status { // SAFETY: we hold a reference; the index was checked when enqueued. &unsafe { &*self.array }.state.entries[self.index as usize] } + + fn written(&self) -> &AtomicU64 { + // SAFETY: as above. + &unsafe { &*self.array }.state.written[self.index as usize] + } } extern "system" fn enqueue_request(this: QueueRef, request: *const Request) { @@ -1166,7 +1274,8 @@ extern "system" fn enqueue_status(this: QueueRef, array: Array, index: u32) { }; entry.store(E_PENDING, Ordering::Release); add_ref_instance(array); - queue(this, Command::Status(Status { array, index })); + let enqueued = stream_log::now(); + queue(this, Command::Status(Status { array, index, enqueued })); } /// Whether a queue submits itself once half of it is enqueued @@ -2162,7 +2271,7 @@ mod tests { let array = status_array(2).cast::>(); let status = |index| { add_ref_instance(array); - Command::Status(Status { array, index }) + Command::Status(Status { array, index, enqueued: 0 }) }; read(&mut l, 0, 0, 16); read(&mut l, 0, 0, 16); diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 02ba024..5d01c55 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -419,6 +419,33 @@ impl Section { } } +impl Section { + /// Commits the pages from `index` on that a view at `base` shows, unless + /// all of them are ([`lean`]): committed for one view is for all. + fn commit_shown(&self, index: usize, base: usize, len: usize) -> bool { + use std::sync::atomic::Ordering; + let pages = index..(index + len / PAGE).min(self.pages); + let bit = |p: usize| (&self.committed[p / 64], 1 << (p % 64)); + let done = || { + pages.clone().all(|p| { + let (word, bit) = bit(p); + word.load(Ordering::Acquire) & bit != 0 + }) + }; + if lean() && done() { + return true; + } + if !counted(Call::Commit, || commit(base, len)) { + return false; + } + for p in pages { + let (word, bit) = bit(p); + word.fetch_or(bit, Ordering::AcqRel); + } + true + } +} + // SAFETY: a section handle may be used from any thread. unsafe impl Send for Section {} // SAFETY: as above. @@ -455,6 +482,9 @@ struct Slice { struct Physical { /// Mapped views by address: their length and what they show. views: BTreeMap, + /// Placeholders that are some view's own, left by its unmapping: address + /// and length. The title may have joined one with others since. + holes: HashMap, } /// The title's pages by number. @@ -893,6 +923,121 @@ pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) { } } +/// What the title's mapping calls cost since the last asking, for the +/// streaming log, counted only while that log is on: calls, pages, +/// milliseconds in all, the longest one's and waiting for the lock; the same +/// of the GPU's page-mapping copies ([`map_alias`]; calls and milliseconds); +/// and by system call (unmap, split, map, commit) how many and their +/// milliseconds. +static MAPPING: [std::sync::atomic::AtomicU64; 15] = [const { std::sync::atomic::AtomicU64::new(0) }; 15]; + +pub(crate) fn map_costs() -> Option { + let n: [u64; 15] = std::array::from_fn(|i| MAPPING[i].swap(0, Ordering::Relaxed)); + let time = |i: usize| matches!(i, 2 | 3 | 4 | 6 | 8 | 10 | 12 | 14); + (n[0] + n[5] > 0).then(|| { + let all: Vec = n + .iter() + .enumerate() + .map(|(i, &n)| if time(i) { n / 1_000_000 } else { n }) + .map(|n| n.to_string()) + .collect(); + all.join("\t") + }) +} + +/// The system calls that change a mapping, as [`MAPPING`] counts them. +#[derive(Clone, Copy)] +enum Call { + Unmap = 7, + Split = 9, + Map = 11, + Commit = 13, +} + +/// Runs `f`, a system call, and counts it while the streaming log is on. +fn counted(call: Call, f: impl FnOnce() -> T) -> T { + if !super::dstorage::stream_log::on() { + return f(); + } + let started = std::time::Instant::now(); + let done = f(); + MAPPING[call as usize].fetch_add(1, Ordering::Relaxed); + MAPPING[call as usize + 1].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + done +} + +/// Counts a mapping call when dropped. +struct Costed { + started: std::time::Instant, + /// `None`: a copy of mappings. + pages: Option, + waited: u64, +} + +impl Costed { + fn begin(pages: Option) -> Option { + super::dstorage::stream_log::on().then(|| Costed { started: std::time::Instant::now(), pages, waited: 0 }) + } +} + +impl Drop for Costed { + fn drop(&mut self) { + let ns = self.started.elapsed().as_nanos() as u64; + let Some(pages) = self.pages else { + MAPPING[5].fetch_add(1, Ordering::Relaxed); + MAPPING[6].fetch_add(ns, Ordering::Relaxed); + return; + }; + for (i, n) in [1, pages as u64, ns].into_iter().enumerate() { + MAPPING[i].fetch_add(n, Ordering::Relaxed); + } + MAPPING[3].fetch_max(ns, Ordering::Relaxed); + MAPPING[4].fetch_add(self.waited, Ordering::Relaxed); + } +} + +/// Whether a mapping change asks the host only for what it needs: no split +/// of a placeholder that is already the view's own, no commit of section +/// pages that are committed (`VICTORY_MAP_LEAN=0`: both every time, as +/// before). +/// +/// All of the title's streaming goes through one thread, which maps the +/// pages of a batch and then submits it. Each call waits for the process's +/// one address-space lock, behind the guards' and the driver's: 200 to 400 +/// us a page in the world against 10 in a menu, 2 to 4 s of every 5 s of +/// that thread (runs stream-1 and -2; all six stacks taken of it in the +/// opening were in these calls), so that models came as fast as their pages +/// could be mapped. A page took up to four calls (unmap, split, map, +/// commit), twice: the title maps a page into its pool and then has the GPU +/// map it into its tiled heap. +fn lean() -> bool { + static ON: LazyLock = LazyLock::new(|| std::env::var_os("VICTORY_MAP_LEAN").is_none_or(|v| v != "0")); + *ON +} + +/// The title's streaming thread runs below normal priority, as do sixteen +/// workers of ours when pipelines are made; on the console nothing else +/// wants its core. Called where that thread maps and submits: lifts a +/// thread that is below normal to above it (`VICTORY_STREAM_PRIORITY=0`: +/// left as the title set it). +pub(crate) fn lift_thread() { + use windows_sys::Win32::System::Threading::{ + GetCurrentThread, GetThreadPriority, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL, + }; + static ON: LazyLock = + LazyLock::new(|| std::env::var_os("VICTORY_STREAM_PRIORITY").is_none_or(|v| v != "0")); + if !*ON { + return; + } + // SAFETY: plain calls on this thread. + unsafe { + let thread = GetCurrentThread(); + if matches!(GetThreadPriority(thread), -2..0) { + SetThreadPriority(thread, THREAD_PRIORITY_ABOVE_NORMAL); + } + } +} + /// Maps `n` pages at `address`, in place of what is mapped there; null /// `pages` unmaps. Returns `address`, or null if a page or the host fails. pub extern "system" fn XMemMapPhysicalPages( @@ -905,7 +1050,11 @@ pub extern "system" fn XMemMapPhysicalPages( // the mapping call that holds them. // SAFETY: the title passes `n` page numbers, or null. let pages = (!pages.is_null()).then(|| unsafe { std::slice::from_raw_parts(pages, n) }.to_vec()); + let mut costed = Costed::begin(Some(n)); let mut physical = physical(); + if let Some(costed) = &mut costed { + costed.waited = costed.started.elapsed().as_nanos() as u64; + } // Until the pages are mapped again: `unmap` takes whole views away and // maps what stays of them again, and a mapped view is a reservation // until it is committed. A read of title memory in place must not fall @@ -953,6 +1102,7 @@ pub extern "system" fn XMemMapPhysicalPagesScatter( if addresses.is_null() { return 0; } + lift_thread(); for i in 0..n { // SAFETY: the title passes `n` addresses and, unless null, `n` pages. let (address, page) = unsafe { @@ -979,6 +1129,7 @@ pub extern "system" fn XMemMapPhysicalPagesScatter( /// heap. Page by page; false if a source page is not mapped physical memory. 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 mut physical = physical(); // As in `XMemMapPhysicalPages`: no read in place meets the gap. let _changing = victory_gpu::title_memory_remapping(); @@ -1010,27 +1161,36 @@ pub fn map_alias(to: u64, from: u64, len: u64) -> bool { /// Maps `slice` and the slices after it over `[base, base + len)`, which /// must lie in one placeholder. fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { - // SAFETY: splits the placeholder around the range (failing harmlessly - // when the range is the whole placeholder), then maps the section - // there; both act only on placeholders. - let view = unsafe { - VirtualFree( - base as *mut c_void, - len, - MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, - ); - MapViewOfFile3( - slice.section.handle, - GetCurrentProcess(), - base as *const c_void, - (slice.index * PAGE) as u64, - len, - MEM_REPLACE_PLACEHOLDER, - PAGE_READWRITE, - std::ptr::null_mut(), - 0, - ) + let map_view = || { + // SAFETY: maps the section over a placeholder; acts only on one. + counted(Call::Map, || unsafe { + MapViewOfFile3( + slice.section.handle, + GetCurrentProcess(), + base as *const c_void, + (slice.index * PAGE) as u64, + len, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }) }; + let own = physical.holes.remove(&base) == Some(len) && lean(); + let mut view = if own { map_view() } else { MEMORY_MAPPED_VIEW_ADDRESS { Value: std::ptr::null_mut() } }; + if view.Value as usize != base { + // SAFETY: splits the placeholder around the range (failing + // harmlessly when the range is the whole placeholder). + counted(Call::Split, || unsafe { + VirtualFree( + base as *mut c_void, + len, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ) + }); + view = map_view(); + } if view.Value as usize != base { tracing::warn!( address = format_args!("{base:#x}"), @@ -1040,7 +1200,7 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { ); return false; } - if !commit(base, len) { + if !slice.section.commit_shown(slice.index, base, len) { // SAFETY: the view just mapped, back to a placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }; return false; @@ -1150,7 +1310,7 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { } victory_gpu::title_memory_unmapping(at, size); // SAFETY: a view we mapped; it becomes a placeholder again. - unsafe { + let gone = counted(Call::Unmap, || unsafe { UnmapViewOfFile2( GetCurrentProcess(), MEMORY_MAPPED_VIEW_ADDRESS { @@ -1158,7 +1318,10 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { }, MEM_PRESERVE_PLACEHOLDER, ) - }; + }); + if gone != 0 && at >= base && at + size <= end { + physical.holes.insert(at, size); + } if at < base { map(physical, at, base - at, slice.clone()); } @@ -1591,6 +1754,45 @@ mod tests { assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1); } + /// Pages keep what they hold however often they are mapped, moved and + /// unmapped without a commit or a split of their own. + #[test] + fn pages_mapped_again_hold_what_they_held() { + let pages = allocate(3); + let a = XMemVirtualAlloc(std::ptr::null_mut(), 8 * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + assert!(!a.is_null()); + let at = |k: usize| a.wrapping_byte_add(k * PAGE); + for round in 0..6_usize { + for (k, page) in pages.iter().enumerate() { + let to = at((round + 2 * k) % 8); + assert_eq!(XMemMapPhysicalPages(to, 1, page), to); + let first = to.cast::(); + // SAFETY: mapped read-write; the far end of the page too. + unsafe { + if round > 0 { + assert_eq!(first.read(), (round * 16 + k - 16) as u64); + assert_eq!(first.add(PAGE / 8 - 1).read(), k as u64); + } + first.write((round * 16 + k) as u64); + first.add(PAGE / 8 - 1).write(k as u64); + } + } + for k in 0..pages.len() { + let to = at((round + 2 * k) % 8); + assert_eq!(XMemMapPhysicalPages(to, 1, std::ptr::null()), to); + assert_eq!(query(to).host.State, MEM_RESERVE); + } + // The title joins what it unmapped: the next view splits it anew. + if round == 3 { + // SAFETY: placeholders of ours, nothing mapped in them. + unsafe { + VirtualFree(a, 8 * PAGE, MEM_RELEASE | 1 /* MEM_COALESCE_PLACEHOLDERS */) + }; + } + } + assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); + } + #[test] fn mapping_no_pages_changes_nothing() { let pages = allocate(2); diff --git a/crates/victory-loader/src/stacks.rs b/crates/victory-loader/src/stacks.rs index 214dda9..73ae3c6 100644 --- a/crates/victory-loader/src/stacks.rs +++ b/crates/victory-loader/src/stacks.rs @@ -109,9 +109,9 @@ pub fn dump_stacks() { if thread.is_null() { continue; } - let (frames, (priority, base)) = frames_of(thread); + let (frames, (priority, base, affinity)) = frames_of(thread); eprintln!( - " thread {id} \"{}\" start {} priority {priority} (base {base})", + " thread {id} \"{}\" start {} priority {priority} (base {base}) affinity {affinity:#x}", name_of(thread), locate(start_of(thread)) ); @@ -124,7 +124,7 @@ pub fn dump_stacks() { } /// The thread's frames and its current and base scheduling priority (0-31). -fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { +fn frames_of(thread: HANDLE) -> (Vec, (i32, i32, usize)) { let mut frames = Vec::with_capacity(MAX_FRAMES); let mut info: BasicInfo = BasicInfo { exit_status: 0, @@ -138,7 +138,7 @@ fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { // the query and the read below. // SAFETY: a thread of this process that is not this one. if unsafe { SuspendThread(thread) } == u32::MAX { - return (frames, (0, 0)); + return (frames, (0, 0, 0)); } // SAFETY: writes `info`, whose layout and size are the system's. let status = unsafe { @@ -153,7 +153,7 @@ fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { if status != 0 || info.teb.is_null() { // SAFETY: suspended above. unsafe { ResumeThread(thread) }; - return (frames, (0, 0)); + return (frames, (0, 0, 0)); } // SAFETY: the TEB of a suspended thread of this process: its NT_TIB // holds the stack base at +8 and the stack limit at +0x10. @@ -170,7 +170,7 @@ fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { } ResumeThread(thread); } - (frames, (info.priority, info.base_priority)) + (frames, (info.priority, info.base_priority, info.affinity)) } fn start_of(thread: HANDLE) -> usize { From c278c67796d48e7a93f4c75631a442888cc6b6d1 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:06:38 -0600 Subject: [PATCH 308/445] The process runs above normal priority, pipeline workers below the title's loading VICTORY_PROCESS_PRIORITY=normal and VICTORY_PIPELINE_LOWEST=0 for the old ways. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/pipeline/make.rs | 8 ++++++-- crates/victory-hle/src/runtime.rs | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 138fb2b..02bb959 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -318,11 +318,15 @@ fn workers() -> bool { let spawned = std::thread::Builder::new() .name(format!("victory-pipelines-{i}")) .spawn(|| { - // Below the title's own threads (loading, recording). + // 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"); // SAFETY: a plain call on our own thread. unsafe { use windows::Win32::System::Threading::*; - let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + let priority = if lowest { THREAD_PRIORITY_LOWEST } else { THREAD_PRIORITY_BELOW_NORMAL }; + let _ = SetThreadPriority(GetCurrentThread(), priority); } loop { next().make(); diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index f26b96f..a42c89f 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -258,6 +258,25 @@ pub fn use_console_timers() { ); timeBeginPeriod(1); } + ahead_of_other_programs(); +} + +/// The title's streaming thread runs below normal priority (on the console +/// nobody else wants its core) and does all of the title's loading: a +/// program that keeps the processors busy at normal priority (a build, a +/// virus scan) starved it, loading took 40 to 60 s instead of 28 to 33, and +/// the opening ran without the models that were to be there (runs cpu-1, +/// play-1125-0203). The process runs above normal, as long as it runs. +/// `VICTORY_PROCESS_PRIORITY=normal`: as it was started. +#[cfg(windows)] +fn ahead_of_other_programs() { + use windows_sys::Win32::System::Threading::{ABOVE_NORMAL_PRIORITY_CLASS, GetCurrentProcess, SetPriorityClass}; + if std::env::var_os("VICTORY_PROCESS_PRIORITY").is_some_and(|v| v == "normal" || v == "0") { + return; + } + // SAFETY: a plain process setting. + let set = unsafe { SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS) } != 0; + tracing::info!(set, "the process runs above normal priority (VICTORY_PROCESS_PRIORITY=normal: not)"); } #[cfg(test)] From b558934d7b3c02f03e7dd393a62ea701413c2c63 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:11:24 -0600 Subject: [PATCH 309/445] Structure builder: root views as memory by address, windows of its own on the card, upload memory below 2^37 The ray-tracing structure builder's 52 programs translate, validate and make host pipelines on the 7900 XTX (its waves have 32-64 lanes). What kept it from working, from a first run (light-1, VICTORY_BVH_QUARANTINE=1) and the code: - a root view ends with the host copy (a 4 MiB window); structures of megabytes cross it. Programs with a spilled user-data table now reach what their root views name by address (USER_ROOT_ADDRESS), as upstream VIctory 0f637570 does. - the list's upload memory (instance descriptions) came from the process heap, above 2^40, where shaders' addresses do not reach (upstream 0f637570, 6d021fe3). - the 1,023 numbered copies of 4 MiB ran out in the first frame: pages come in windows of 256 KiB (4 MiB around what a dispatch names), 16,383 at most. - what the builder stores came back to title memory; now only what it stores in small title buffers it names (sizes the title reads). - the directory lay in the PC's memory and every access stored a fault note. - a list without a view heap gets the title's; a dropped stage rests the builder for a frame, not for the run. Off unless VICTORY_BVH_BUILDER=1, as before. VICTORY_UPLOAD_LOW=0, VICTORY_LENT_HEAP=0, VICTORY_MEMORY_WINDOW_KB, VICTORY_MEMORY_CARD_MB. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 21 ++ crates/victory-gpu/src/draw.rs | 39 +- crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/list.rs | 28 +- crates/victory-gpu/src/memory.rs | 389 +++++++++++++------- crates/victory-gpu/src/pipeline.rs | 40 +- crates/victory-gpu/src/pipeline/make.rs | 6 + crates/victory-gpu/src/shadow.rs | 71 +++- crates/victory-gpu/src/upload.rs | 168 +++++++++ crates/victory-shader/src/emit/intersect.rs | 6 +- crates/victory-shader/src/emit/lower.rs | 121 +++++- crates/victory-shader/src/emit/mod.rs | 2 +- crates/victory-shader/src/emit/shader.rs | 11 +- 13 files changed, 727 insertions(+), 177 deletions(-) create mode 100644 crates/victory-gpu/src/upload.rs diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 39e8b68..8d0a6fe 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -320,6 +320,27 @@ fn changed_slots( first.min(last)..last } +/// The title's view heap that shaders of a list without one get their views +/// from (`draw.rs`, `bind`): the title's structure builder binds root views +/// only, and the host shows those, and memory by address, through heap slots. +/// The biggest there is. `VICTORY_LENT_HEAP=0`: none, such a dispatch is +/// dropped, as before. +#[cfg(windows)] +pub(crate) fn lent_heap() -> Option { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_LENT_HEAP").is_none_or(|v| v != "0")) { + return None; + } + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); + heaps + .iter() + // SAFETY: registered heaps are live (removed when dropped). + .map(|&(_, _, h)| (h, unsafe { &*(h as *const Heap) })) + .filter(|(_, heap)| !heap.samplers() && matches!(heap.host.get(), Some(Some(_)))) + .max_by_key(|(_, heap)| heap.desc.count) + .map(|(h, _)| h) +} + /// Gives back dynamic slots of the host heap behind the title heap at /// `heap`, if that heap still exists. #[cfg(windows)] diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2b6f8a0..b4174c9 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -953,10 +953,17 @@ impl State { dword: u32, memory: Option<&crate::memory::Ready>, ) -> u32 { - use victory_shader::emit::{USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS}; + use victory_shader::emit::{USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS}; if kind == USER_MEMORY_BASE { return memory.map_or(0, |m| m.base); } + if kind == USER_ROOT_ADDRESS || kind == USER_ROOT_ADDRESS + 1 { + return match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::View(address)) if kind == USER_ROOT_ADDRESS => address as u32, + Some(&Root::View(address)) => (address >> 32) as u32, + _ => 0, + }; + } if kind == USER_VIEW_BIAS { // The view begins on 16 bytes of the copy the address finds // (`root_uav`, `root_srv_table`). @@ -1014,7 +1021,7 @@ impl State { list: &HostList, t: &crate::pipeline::Translated, compute: bool, - writes: bool, + use_: crate::memory::Use, ) -> Option { let heap = match self.heaps[0] { 0 => None, @@ -1033,7 +1040,7 @@ impl State { addresses.push(self.view_address(compute, u.slot, u.dword)); } } - crate::memory::ready(list, heap, &addresses, &constants, writes) + crate::memory::ready(list, heap, &addresses, &constants, use_) } /// The bound heap holding `handle`. @@ -1154,6 +1161,15 @@ impl State { if crate::host::walls_trace() { self.walls_census(p, compute); } + // A list without a view heap: one of the title's for the views the + // host itself puts into heap slots. + if self.heaps[0] == 0 + && p.stages.iter().any(|s| !s.root_uavs.is_empty() || !s.root_srvs.is_empty()) + && let Some(heap) = crate::descriptor::lent_heap() + { + once!("a dispatch without a view heap that needs one gets the title's"); + self.heaps[0] = heap; + } // Heaps first: a root signature with directly indexed heaps must be // set after them. if self.host_heaps != self.heaps { @@ -1221,8 +1237,14 @@ impl State { let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) { // Only through a store by address: what it stores through // views is declared with them. - let writes = writes && t.stores_by_address; - let Some(ready) = self.memory_ready(list, &t, compute, writes) else { + let use_ = if crate::pipeline::is_builder(self.pipeline as This) { + crate::memory::Use::Builder { back: writes } + } else if writes && t.stores_by_address { + crate::memory::Use::Writes + } else { + crate::memory::Use::Reads + }; + let Some(ready) = self.memory_ready(list, &t, compute, use_) else { once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped"); return false; }; @@ -2317,12 +2339,17 @@ impl State { // A stage of the structure builder that cannot be bound is a // dropped stage: the others stop too. if crate::pipeline::is_builder(self.pipeline as This) { - crate::pipeline::builder_off("one of its dispatches could not be bound"); + crate::pipeline::builder_rests("one of its dispatches could not be bound"); } return; } #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); + #[cfg(feature = "diagnostics")] + if crate::pipeline::is_builder(self.pipeline as This) { + crate::capture::op(list as *const _ as usize, || format!("builder {}", p.name)); + self.list_dropped_roots([x, y, z]); + } // SAFETY: an open list with everything set. unsafe { list.list.Dispatch(x, y, z) }; self.buffers_written(); diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 532cf78..a54b4fb 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -69,6 +69,8 @@ mod tdr; #[cfg(windows)] mod texture; #[cfg(windows)] +mod upload; +#[cfg(windows)] mod watch; #[cfg(windows)] diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 140b755..e58f019 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -114,7 +114,7 @@ struct List { /// Ours, after the console layout: memory handed out by /// [`allocate_upload`], kept until the list is reset; the host list the /// calls record into (decision 0007), and the draw state the title set. - uploads: std::sync::Mutex>>, + uploads: std::sync::Mutex>, #[cfg(windows)] host: Option, #[cfg(windows)] @@ -187,7 +187,7 @@ pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> { #[cfg(windows)] pub(crate) struct Detached { host: crate::host::HostList, - _uploads: Vec>, + _uploads: Vec, _state: crate::draw::State, } @@ -1481,6 +1481,23 @@ extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: reset(this, allocator, pipeline) } +#[cfg(windows)] +use crate::upload::Upload; + +/// The memory of [`allocate_upload`] where no host GPU reads it by address. +#[cfg(not(windows))] +struct Upload(Vec); + +#[cfg(not(windows))] +impl Upload { + fn new(len: usize) -> Option { + Some(Upload(vec![0; len])) + } + fn start(&mut self) -> *mut u8 { + self.0.as_mut_ptr() + } +} + /// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list /// owns until it is reset, which the CPU writes and the GPU reads at the /// same address; null on failure. The title's BVH builder puts @@ -1494,13 +1511,14 @@ extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mu if this.is_null() || !align.is_power_of_two() { return std::ptr::null_mut(); } - let mut block = vec![0u8; len]; - let start = block.as_mut_ptr(); + let Some(mut block) = Upload::new(len) else { + return std::ptr::null_mut(); + }; + let start = block.start(); // SAFETY: the offset is below `align`, so `size` bytes fit after it. let at = unsafe { start.add(start.align_offset(align)) }; // SAFETY: the title passes one of our lists. let uploads = unsafe { &(*this.cast::()).uploads }; - // Moving the vector keeps its heap block where it is. uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block); at } diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index a85ee02..da67877 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -4,15 +4,22 @@ //! structures; the structures themselves lie in plain title memory, in no //! buffer object). //! -//! The copies are the ones every other access uses ([`crate::shadow`]: a -//! title buffer's copy, or the 4 MiB window of memory outside buffers), so -//! a root view and a raw address reach the same host bytes. This module -//! keeps what a shader needs to find them: +//! A page in a title buffer that holds all of it is in that buffer's copy +//! ([`crate::shadow`]), which every other access uses. A page outside +//! buffers is in a window of this module's own, on the card +//! ([`crate::shadow::by_address`]): 4 MiB around what a dispatch names (the +//! title's pool of dynamic structures), 256 KiB around a page a shader came +//! to by a pointer (the streamed structures lie anywhere between other +//! data; `VICTORY_MEMORY_WINDOW_KB`). +//! +//! This module keeps what a shader needs to find the copies: //! //! - the **directory**: per 64 KiB page of title address space the number //! of the copy that holds the page (0: none) and the page's byte offset -//! in it; one buffer for all lists, entries only ever go from empty to -//! filled; +//! in it; one for all lists, entries only ever go from empty to filled. +//! The CPU writes it in memory of its own and shaders read a copy of that +//! on the card, brought up to date as title memory is (over the bus, every +//! step of every ray waited for it); //! - per view heap a run of slots with a raw unordered access view of each //! numbered copy (slot 0 of the run: a null view, for pages without a //! copy); @@ -25,27 +32,26 @@ //! the read gives 0, the store is dropped, and the fault note only helps //! the next frame. For the structure builder that is the same as a dropped //! stage, so before a dispatch the host makes ready everything it can see -//! the dispatch name: the whole copy around each root view, around each +//! the dispatch name: the window around each root view, around each //! pair of root constants that is a title address and around each root //! constant that is one in 256-byte units (the builder passes structures -//! all three ways), and the 4 MiB after each (a structure may cross a +//! all three ways), and the one after each (a structure may cross a //! window's end). //! shortcut: what a stage reaches only through pointers it reads out of -//! memory (InitHeaders' table of structure addresses, LoadInstances' -//! instance records) is not made ready unless something else named it; -//! the fault count in the log says whether that happens. The whole answer -//! is the extent of the title's allocation around an address, which the -//! memory module of the layer knows and this one does not ask yet. +//! memory (the structures a top-level build's instances name) is there from +//! the second frame on; the fault count in the log says how often that +//! happens. The top level is built anew every frame. +//! +//! **What comes back to title memory**: what the builder stores in title +//! buffers of at most [`BACK`] bytes it names (the sizes the title reads to +//! make a structure smaller). Structures and scratch memory stay on the card. +//! Other programs that store by address declare the copies they name. //! //! shortcut: a copy that is numbered is kept for the rest of the run, and -//! there are at most [`COPIES`] of them (4 MiB windows mostly: 4 GiB at -//! most). Every list with such a shader brings all numbered copies up to -//! date. A dispatch that can store through raw addresses declares the -//! copies it names as written (the bytes are compared afterwards, as for -//! any unordered access view); what a stage stores through pointers it -//! reads out of memory is declared if a stage of the same list names the -//! copy, and otherwise stays in the host's copy until one does. A -//! dirty-page mask written by the shader would bound both. +//! there are at most [`COPIES`] of them. +//! shortcut: the windows a list does not name are brought up to date once a +//! frame, by the first list that reads by address: bytes the title writes +//! there later in the frame are seen a frame late. use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -58,29 +64,54 @@ use crate::host::{HostList, host}; use crate::shadow::Shadow; /// Copies that can be numbered (the run of heap slots is one longer). A -/// listed frame of the opening cutscene names about 50 windows. -const COPIES: u32 = 1023; -/// A window of memory outside buffers (`shadow.rs`). +/// frame of the dorm names 1,100 pages outside the named windows. +const COPIES: u32 = (1 << 14) - 1; +/// A window around memory a dispatch names. const CELL: u64 = 4 << 20; /// A directory page. const PAGE: u64 = 1 << 16; +/// The biggest title buffer whose builder results come back. +const BACK: u64 = 256 << 10; + +/// What a draw or dispatch does with title memory by address. +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum Use { + Reads, + Writes, + /// A stage of the structure builder; `back`: its results come back. + Builder { back: bool }, +} struct Memory { - /// Buffer, its mapping, its GPU address. - directory: (ID3D12Resource, *mut u32, u64), + /// The CPU's entries (number, offset), and the copy shaders read. + directory: (*mut u32, Arc), faults: (ID3D12Resource, *mut u32, u64), - /// Copy `n` is `copies[n - 1]`. - copies: Vec>, + /// Copy `n` is `copies[n - 1]`; whether it is a window of ours. + copies: Vec<(Arc, bool)>, + /// Places of title buffers' copies among `copies`. + numbers: HashMap, /// Per host view heap (by address): the first slot of its run, and how /// many copies have their view there. heaps: HashMap, /// The frame the faults were last read in. frame: u64, + /// The frame our windows were last brought up to date in. + swept: u64, /// Pages asked for this frame that are not the title's memory. refused: std::collections::HashSet, + stats: Stats, } -// SAFETY: the mappings are of buffers the struct owns; all access is under +/// Since the last report (diagnostics). +#[derive(Default)] +struct Stats { + from: Option<(std::time::Instant, u64)>, + uses: [u64; 3], + faults: u64, + back: u64, +} + +// SAFETY: the mappings are of memory the struct owns; all access is under // the mutex. unsafe impl Send for Memory {} @@ -94,54 +125,70 @@ pub(crate) struct Ready { pub(crate) base: u32, } +/// A window around a page a shader came to by a pointer. +fn far_window() -> u64 { + static BYTES: std::sync::OnceLock = std::sync::OnceLock::new(); + *BYTES.get_or_init(|| { + let kb = std::env::var("VICTORY_MEMORY_WINDOW_KB").ok().and_then(|v| v.trim().parse::().ok()); + kb.map(|kb| kb << 10).filter(|b| b.is_power_of_two() && (PAGE..=CELL).contains(b)).unwrap_or(256 << 10) + }) +} + impl Memory { fn new() -> Option { let host = host()?; - let make = |dwords: u64, what: &str| { - let (buffer, data) = host.shared_buffer(dwords * 4)?; - crate::host::name(&buffer, || format!("title memory by address: {what}")); - // SAFETY: a fresh mapping of at least that many bytes. - unsafe { std::ptr::write_bytes(data, 0, (dwords * 4) as usize) }; - // SAFETY: a live buffer. - let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - Some((buffer, data.cast::(), gpu)) - }; + let bytes = u64::from(MEMORY_PAGES) * 8; + // Zeroed, and watched for writes as the title's memory is. + let entries = crate::upload::reserve(bytes as usize)?; + let directory = crate::shadow::by_address(entries as u64, bytes)?; + crate::host::name(&directory.buffer, || "title memory by address: directory".into()); + let (faults, data) = host.shared_buffer(u64::from(MEMORY_FAULTS) * 4)?; + crate::host::name(&faults, || "title memory by address: faults".into()); + // SAFETY: a fresh mapping of at least that many bytes. + unsafe { std::ptr::write_bytes(data, 0, MEMORY_FAULTS as usize * 4) }; + // SAFETY: a live buffer. + let gpu = unsafe { faults.GetGPUVirtualAddress() }; tracing::info!("title memory by address: a shader reads or writes through raw addresses"); Some(Memory { - directory: make(u64::from(MEMORY_PAGES) * 2, "directory")?, - faults: make(u64::from(MEMORY_FAULTS), "faults")?, + directory: (entries as *mut u32, directory), + faults: (faults, data.cast::(), gpu), copies: Vec::new(), + numbers: HashMap::new(), heaps: HashMap::new(), frame: u64::MAX, + swept: u64::MAX, refused: Default::default(), + stats: Stats::default(), }) } - /// Gives the page of `address` its copy, if it has none and the memory - /// is the title's; the place of its copy in `copies`. - fn map(&mut self, address: u64) -> Option { - self.make(address); - let page = address / PAGE; - if page >= u64::from(MEMORY_PAGES) - 1 { - return None; - } - // SAFETY: inside the directory's mapping. - let number = unsafe { self.directory.1.add(page as usize * 2).read() }; - (number as usize).checked_sub(1) + /// The directory's entry of `page`. + fn entry(&self, page: u64) -> *mut u32 { + debug_assert!(page < u64::from(MEMORY_PAGES)); + // SAFETY: inside the directory. + unsafe { self.directory.0.add(page as usize * 2) } } - fn make(&mut self, address: u64) { + /// Gives the page of `address` its copy, if it has none and the memory + /// is the title's (a window of `window` bytes outside buffers); the place + /// of its copy in `copies`. + fn map(&mut self, address: u64, window: u64) -> Option { let page = address / PAGE; // The last entry stays empty: addresses past the directory read it. if page >= u64::from(MEMORY_PAGES) - 1 { - return; + return None; } - // SAFETY: inside the directory's mapping. - let entry = unsafe { self.directory.1.add(page as usize * 2) }; - // SAFETY: as above. - if unsafe { entry.read() } != 0 { - return; + // SAFETY: an entry of the directory. + let mut number = unsafe { self.entry(page).read() }; + if number == 0 { + self.make(page, window); + // SAFETY: as above. + number = unsafe { self.entry(page).read() }; } + (number as usize).checked_sub(1) + } + + fn make(&mut self, page: u64, window: u64) { let start = page * PAGE; // A shader's pointer, or a constant taken for an address, may be // anything: only memory the title has. @@ -152,60 +199,57 @@ impl Memory { self.refused.insert(page); return; } - // The copy a root view at that address would get; a buffer that - // ends inside the page is passed over for what holds all of it. - let whole = |s: &Arc| s.offset_in(start).is_some_and(|_| s.left(start) >= PAGE); - let Some(shadow) = crate::shadow::find(start, 1) - .filter(whole) - .or_else(|| crate::shadow::find(start, PAGE).filter(whole)) - else { - return; + // The copy of a title buffer that holds all of the page, the + // innermost first; else a window of our own. + let whole = |s: &Arc| s.offset_in(start).is_some() && s.left(start) >= PAGE; + let buffer = crate::shadow::in_buffer(start, PAGE).and_then(|_| crate::shadow::find(start, PAGE)).filter(whole); + let own = buffer.is_none(); + let shadow = match buffer { + Some(s) => s, + None => { + if self.copies.len() >= COPIES as usize { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros") + }); + return; + } + let Some(s) = crate::shadow::by_address(start & !(window - 1), window) else { + return; + }; + s + } }; // SAFETY: a live buffer. let flags = unsafe { shadow.buffer.GetDesc() }.Flags; if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { return; } - let n = match self.copies.iter().position(|c| Arc::ptr_eq(c, &shadow)) { - Some(n) => n, + let key = Arc::as_ptr(&shadow) as usize; + let n = match self.numbers.get(&key) { + Some(&n) => n, None if self.copies.len() < COPIES as usize => { - self.copies.push(shadow.clone()); + self.copies.push((shadow.clone(), own)); let n = self.copies.len() - 1; + self.numbers.insert(key, n); // Every page the copy holds whole, not only the one asked - // for: a structure is more than 64 KiB. - // shortcut: a page of a title buffer inside this one that - // has a copy of its own is given this copy too. + // for: a structure is more than 64 KiB. (Not those of title + // buffers inside a window: they have copies of their own.) let (first, len) = shadow.span(); let mut at = first.next_multiple_of(PAGE); while at + PAGE <= first + len && at / PAGE < u64::from(MEMORY_PAGES) - 1 { - // SAFETY: inside the directory's mapping. - let other = unsafe { self.directory.1.add((at / PAGE) as usize * 2) }; - // SAFETY: as above; the offset first, as below. - unsafe { - if other.read() == 0 { - other.add(1).write_volatile((at - first) as u32); - other.write_volatile(n as u32 + 1); - } + let entry = self.entry(at / PAGE); + // SAFETY: an entry of the directory. + if unsafe { entry.read() } == 0 && (!own || crate::shadow::in_buffer(at, PAGE).is_none()) { + fill(entry, n, at - first); } at += PAGE; } n } - None => { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros") - }); - return; - } + None => return, }; - let offset = shadow.offset_in(start).unwrap_or(0); - // The offset first: a shader that sees the number sees it too. - // SAFETY: inside the directory's mapping. - unsafe { - entry.add(1).write_volatile(offset as u32); - entry.write_volatile(n as u32 + 1); - } + fill(self.entry(page), n, shadow.offset_in(start).unwrap_or(0)); } /// The pages shaders found empty since the last frame. @@ -223,48 +267,90 @@ impl Memory { unsafe { at.write_volatile(0) }; } } - if !pages.is_empty() { - // Each is an access that read 0 or was dropped. - static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 50 { - tracing::warn!( - pages = pages.len(), - first = format_args!("{:#x}", u64::from(pages[0]) * PAGE), - "title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); the copies are made now" - ); - } + if pages.is_empty() { + return; } - for page in pages { - self.map(u64::from(page) * PAGE); + let mut made = 0; + for &page in &pages { + made += usize::from(self.map(u64::from(page) * PAGE, far_window()).is_some()); + } + self.stats.faults += pages.len() as u64; + // Each is an access that read 0 or was dropped. + static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 100 { + pages.sort_unstable(); + let first: Vec = pages.iter().take(8).map(|&p| format!("{:#x}", u64::from(p) * PAGE)).collect(); + tracing::warn!( + frame = self.frame, + pages = pages.len(), + made, + copies = self.copies.len(), + ?first, + "title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); the copies are made now, of those that are the title's" + ); } } - /// What a dispatch names: the copy around `address` and the 4 MiB - /// after it; their places in `copies`. + /// What a dispatch names: the copy around `address` and the one after it; + /// their places in `copies`. fn name(&mut self, address: u64, named: &mut Vec) { for at in [address, (address & !(CELL - 1)) + CELL] { - if let Some(n) = self.map(at) + if let Some(n) = self.map(at, CELL) && !named.contains(&n) { named.push(n); } } } + + /// Every ten seconds or so, what was used (with the frame's line). + fn report(&mut self) { + let now = std::time::Instant::now(); + let (since, frame) = *self.stats.from.get_or_insert((now, self.frame)); + let seconds = now.duration_since(since).as_secs_f64(); + if seconds < 10.0 { + return; + } + let frames = self.frame.wrapping_sub(frame).max(1) as f64; + let (mut ours, mut bytes) = (0, 0); + for (s, own) in &self.copies { + if *own { + ours += 1; + bytes += s.span().1; + } + } + let s = std::mem::take(&mut self.stats); + tracing::info!( + "title memory by address: {ours} windows ({} MB) and {} title buffers; per frame {:.0} dispatches that read, {:.0} that write, \ + {:.0} of the structure builder, {:.1} pages that had no copy, {:.1} results brought back", + bytes >> 20, + self.copies.len() - ours, + s.uses[0] as f64 / frames, + s.uses[1] as f64 / frames, + s.uses[2] as f64 / frames, + s.faults as f64 / frames, + s.back as f64 / frames + ); + self.stats.from = Some((now, self.frame)); + } +} + +/// The offset first: a shader that sees the number sees it too. +fn fill(entry: *mut u32, n: usize, offset: u64) { + // SAFETY: an entry of the directory, under the mutex. + unsafe { + entry.add(1).write_volatile(offset as u32); + entry.write_volatile(n as u32 + 1); + } } /// Before a draw whose shader reads title memory by address: what its /// root arguments name gets its copies (`addresses`: its root views; /// `constants`: its root constants, see the module), every numbered copy /// has its view in `heap`'s run and is brought up to date when `list` is -/// submitted (and, with `writes`, the named ones copied back after). None if the host -/// cannot hold it; the draw is then dropped. -pub(crate) fn ready( - list: &HostList, - heap: &HostHeap, - addresses: &[u64], - constants: &[u32], - writes: bool, -) -> Option { +/// submitted (what `use_` writes is copied back after, see the module). +/// None if the host cannot hold it; the draw is then dropped. +pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constants: &[u32], use_: Use) -> Option { let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); if guard.is_none() { *guard = Memory::new(); @@ -275,7 +361,13 @@ pub(crate) fn ready( m.frame = frame; m.refused.clear(); m.take_faults(); + m.report(); } + m.stats.uses[match use_ { + Use::Reads => 0, + Use::Writes => 1, + Use::Builder { .. } => 2, + }] += 1; let numbered = m.copies.len(); let mut named = Vec::new(); for &address in addresses { @@ -305,7 +397,7 @@ pub(crate) fn ready( (base, 0) } }; - for (n, shadow) in m.copies.iter().enumerate().skip(made as usize) { + for (n, (shadow, _)) in m.copies.iter().enumerate().skip(made as usize) { let (_, len) = shadow.span(); heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len); } @@ -315,25 +407,68 @@ pub(crate) fn ready( // shortcut: a copy another list numbers meanwhile is brought up to date // by that list's submission, which may run after this one's. const READ: usize = usize::MAX - 0x6d; - const WRITE: usize = usize::MAX - 0x1_0000; + const NAMED: usize = usize::MAX - 0x1_0000; + const WRITE: usize = usize::MAX - 0x2_0000; + const RESULT: usize = usize::MAX / 2; let first_read = list.first_use(READ); - for (n, shadow) in m.copies.iter().enumerate() { + if first_read { + let (start, len) = m.directory.1.span(); + m.directory.1.refresh(list, start, len); + let sweep = m.swept != frame; + m.swept = frame; + for (shadow, own) in &m.copies { + if sweep || !own { + let (start, len) = shadow.span(); + shadow.refresh(list, start, len); + } + } + list.keep(&m.faults.0); + } else if m.copies.len() > numbered { + let (start, len) = m.directory.1.span(); + m.directory.1.refresh(list, start, len); + } + for (shadow, _) in &m.copies[numbered..] { let (start, len) = shadow.span(); - if first_read || n >= numbered { + shadow.refresh(list, start, len); + } + for &n in &named { + let (shadow, own) = &m.copies[n]; + let (start, len) = shadow.span(); + if *own && list.first_use(NAMED - n) { shadow.refresh(list, start, len); } - if writes && named.contains(&n) && list.first_use(WRITE - n) { + if use_ == Use::Writes && list.first_use(WRITE - n) { #[cfg(feature = "diagnostics")] crate::host::wide_write(start, len, 1); shadow.gpu_writes(list, start, len); } } - if first_read { - list.keep(&m.directory.0); - list.keep(&m.faults.0); + if use_ == (Use::Builder { back: true }) { + for &address in addresses { + let Some((start, len)) = crate::shadow::in_buffer(address, 1).filter(|b| b.1 <= BACK) else { + continue; + }; + if !list.first_use(RESULT + start as usize) { + continue; + } + // The copy or copies its pages are in (it need not fill one). + let mut at = start; + while at < start + len { + let end = (at / PAGE + 1) * PAGE; + let n = end.min(start + len) - at; + if let Some(k) = m.map(at, CELL) { + let shadow = &m.copies[k].0; + shadow.refresh(list, at, n); + shadow.gpu_writes(list, at, n); + m.stats.back += 1; + } + at = end; + } + } } + let directory = &m.directory.1; Some(Ready { - directory: m.directory.2, + directory: directory.gpu(directory.span().0), faults: m.faults.2, base, }) diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 971a351..e94d740 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -233,8 +233,11 @@ fn translate(container: &[u8]) -> Result { /// So a builder dispatch runs only while every builder pipeline the title /// has created has a host pipeline; the first builder dispatch makes them /// all on the spot instead of over the next frames (a stage "still being -/// made" would be a dropped stage). One that cannot be made turns the -/// builder off for the rest of the run. +/// made" would be a dropped stage). While one cannot be made the builder +/// is off; it is looked at again when the title creates another. A stage +/// that could not be bound stops the stages after it for the rest of that +/// frame and the next ([`builder_rests`]); it turned the builder off for the +/// rest of the run at first. /// /// shortcut: and only with `VICTORY_BVH_BUILDER=1`, until a run has shown /// the whole builder and the host side of title memory by address @@ -245,15 +248,18 @@ struct Builder { pipelines: Vec>, /// Every one of `pipelines` has a host pipeline. whole: bool, - /// One could not be made. - off: bool, + /// One could not be made, of so many (0: none). + off: usize, + /// No stage runs before this frame. + rests: u64, } #[cfg(windows)] static BUILDER: Mutex = Mutex::new(Builder { pipelines: Vec::new(), whole: false, - off: false, + off: 0, + rests: 0, }); /// Whether `shaders` are a pipeline of the structure builder. @@ -292,13 +298,15 @@ pub(crate) fn is_builder(this: This) -> bool { !this.is_null() && pipeline(this).builder } -/// A stage of the builder was dropped after all: none runs from here on. +/// A stage of the builder was dropped after all: none runs for the rest of +/// this frame and the next (what it fed is not there). #[cfg(windows)] -pub(crate) fn builder_off(why: &'static str) { +pub(crate) fn builder_rests(why: &'static str) { let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); - if !b.off { - b.off = true; - tracing::warn!(why, "the ray-tracing structure builder is turned off for the rest of the run: its stages run all or none"); + b.rests = crate::frame::current() + 2; + static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 20 { + tracing::warn!(why, "the ray-tracing structure builder rests for this frame and the next: its stages run all or none"); } } @@ -311,22 +319,24 @@ pub(crate) fn builder_runs() -> bool { return false; } let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); - if b.off { + if b.off == b.pipelines.len() || crate::frame::current() < b.rests { return false; } if b.whole { return true; } - let missing = b.pipelines.iter().filter(|p| !make::now(p)).count(); - if missing > 0 { - b.off = true; + let missing: Vec = b.pipelines.iter().filter(|p| !make::now(p)).map(|p| make::hashes(p)).collect(); + if !missing.is_empty() { + b.off = b.pipelines.len(); tracing::warn!( - missing, + missing = missing.len(), of = b.pipelines.len(), + which = ?missing, "the ray-tracing structure builder stays off: not all of its programs have a host pipeline, and its stages run all or none" ); return false; } + b.off = 0; tracing::info!( pipelines = b.pipelines.len(), "the ray-tracing structure builder runs: all of its programs have host pipelines" diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 138fb2b..39d67b5 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -91,6 +91,12 @@ pub(crate) fn missing(p: &Pending) -> Option { } } +/// The hashes of the shaders `p` is made of. +pub(crate) fn hashes(p: &Pending) -> String { + let hashes: Vec<&str> = p.shaders.iter().map(|s| s.hash.as_str()).collect(); + hashes.join("+") +} + /// Signalled whenever a worker has made a pipeline. static DONE: (Mutex<()>, Condvar) = (Mutex::new(()), Condvar::new()); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 8b127df..93242b7 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -83,6 +83,9 @@ pub(crate) struct Shadow { card: Option, /// A window of title memory outside buffers, not a title buffer's copy. window: bool, + /// Of a copy with two sides: only the dwords the title changed go up, + /// as with [`send_changed`] ([`by_address`]). + changes_only: bool, /// With `crate::inplace`: not a copy at all. `buffer` is placed in a /// heap opened on the title memory itself, so shaders read and write /// the title's own bytes and nothing is copied either way. The heap, @@ -2631,6 +2634,7 @@ impl Shadow { }, card: None, window: false, + changes_only: false, place: None, } } @@ -3515,7 +3519,7 @@ impl Shadow { /// A page of title memory, as read. static TITLE: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } - let Some(card) = self.card.as_ref().filter(|_| send_changed()) else { + let Some(card) = self.card.as_ref().filter(|_| self.changes_only || send_changed()) else { return self.copy(from, to); }; let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none(); @@ -4554,6 +4558,71 @@ fn longest_tail(windows: impl Iterator, address: u64, end: u6 .min() } +/// Whether `[address, address + len)` lies in one title buffer. +pub(crate) fn in_buffer(address: u64, len: u64) -> Option<(u64, u64)> { + let end = address.checked_add(len)?; + let map = buffers_read(); + let found = map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end); + found.map(|(k, e)| (k.0, e.end - k.0)) +} + +/// A copy of the title memory `[start, start + len)` outside buffers for the +/// programs that find memory by address ([`crate::memory`]), on the card: the +/// structures rays are traced through, read with every step of every ray. +/// +/// What shaders write there by address is not brought back to title memory +/// (nothing else reads a structure; the first whole run of the builder wrote +/// garbage over the title's objects), so the copy is the only place that has +/// it. The CPU's side holds the title's bytes as they were last taken, and +/// only dwords the title changed since go up: a page the title writes a part +/// of keeps what shaders wrote in the rest. +pub(crate) fn by_address(start: u64, len: u64) -> Option> { + let host = host()?; + if !cards() || !host.card_ready() { + return None; + } + // At most so much on the card's own memory (2 GiB unless + // `VICTORY_MEMORY_CARD_MB` says otherwise), and while it has room; past + // that the side shaders see is in the PC's memory. + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + static USED: AtomicU64 = AtomicU64::new(0); + let most = *MOST.get_or_init(|| { + let mb = std::env::var("VICTORY_MEMORY_CARD_MB").ok().and_then(|v| v.trim().parse::().ok()); + mb.unwrap_or(2048) << 20 + }); + let room = host.video_memory().is_none_or(|[budget, used, ..]| used + len < budget / 100 * 97); + let (staging, data) = host.shared_buffer(len)?; + let on_card = if room && USED.fetch_add(len, Ordering::Relaxed) + len <= most { + host.uav_buffer(len) + } else { + None + }; + let buffer = match on_card { + Some(buffer) => buffer, + None => host.shared_buffer(len)?.0, + }; + crate::host::name(&staging, || format!("title memory {start:#x}+{len:#x} by address, the CPU's side")); + crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x} by address")); + // (Counted down with the windows' on the card when it goes.) + WINDOW_CARD_BYTES.fetch_add(len, Ordering::Relaxed); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let mut shadow = Shadow::new(buffer, data, gpu, start, len); + shadow.window = true; + shadow.changes_only = true; + shadow.card = Some(Card { + staging, + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + touched: Default::default(), + size: len, + }); + let shadow = Arc::new(shadow); + CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow)); + Some(shadow) +} + /// Copies of title memory outside buffers, by (start, length). static LOOSE: std::sync::RwLock>> = std::sync::RwLock::new(BTreeMap::new()); diff --git a/crates/victory-gpu/src/upload.rs b/crates/victory-gpu/src/upload.rs new file mode 100644 index 0000000..7ea3776 --- /dev/null +++ b/crates/victory-gpu/src/upload.rs @@ -0,0 +1,168 @@ +//! Memory `allocate_upload` (`list.rs`) hands out: the title's CPU writes +//! it and its shaders read it at the same address (the structure builder's +//! instance descriptions lie there). +//! +//! The console's GPU addresses have 40 bits, and a translated shader that +//! reads by address has no more (`victory_shader`'s `Lower::memory`): memory +//! from the process heap lies above 2^40 and was read at another address, as +//! zeros. So this memory is taken in blocks of 64 KiB out of arenas in +//! [4 GiB, 2^37), as upstream VIctory 0f637570 and 6d021fe3 place it (there +//! an allocation of its own each). An arena is a title buffer to the host +//! copies ([`crate::shadow`]) and lives as long as the process: the directory +//! of memory by address ([`crate::memory`]) keeps the copy it found at an +//! address for good, so the same addresses must stay the same copy. +//! `VICTORY_UPLOAD_LOW=0`: from the process heap, as before. + +use std::sync::{Mutex, OnceLock}; + +/// What blocks are cut on: a page of the directory of memory by address. +const BLOCK: usize = 64 << 10; +/// An arena's size, if one request does not need more. +const ARENA: usize = 4 << 20; + +struct Arena { + at: usize, + /// Per block whether it is handed out. + taken: Vec, +} + +static ARENAS: Mutex> = Mutex::new(Vec::new()); + +/// Upload memory of one request, zeroed, given back when dropped. +pub(crate) struct Upload(Kind); + +enum Kind { + /// Address, bytes. + Low(usize, usize), + Heap(Vec), +} + +fn low() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_UPLOAD_LOW").is_none_or(|v| v != "0")) +} + +/// The first place of `n` free blocks side by side. +fn gap(taken: &[bool], n: usize) -> Option { + let mut free = 0; + for (i, &t) in taken.iter().enumerate() { + free = if t { 0 } else { free + 1 }; + if free == n { + return Some(i + 1 - n); + } + } + None +} + +/// Fresh zeroed memory in [4 GiB, 2^37) (where the directory of memory by +/// address reaches, `MEMORY_PAGES`), write-watched as the title's own +/// pools are (copies then take only written pages). +pub(crate) fn reserve(len: usize) -> Option { + use windows_sys::Win32::System::Memory::{ + MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, MEM_RESERVE, MemExtendedParameterAddressRequirements, + PAGE_READWRITE, VirtualAlloc2, + }; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + let mut requirements = MEM_ADDRESS_REQUIREMENTS { + LowestStartingAddress: (1usize << 32) as *mut _, + HighestEndingAddress: ((1usize << 37) - 1) as *mut _, + Alignment: 0, + }; + let mut parameter = MEM_EXTENDED_PARAMETER::default(); + parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64; + parameter.Anonymous2.Pointer = (&raw mut requirements).cast(); + // SAFETY: a fresh allocation; the parameter points at `requirements`, + // which outlives the call. + let at = unsafe { + VirtualAlloc2( + std::ptr::null_mut(), + std::ptr::null(), + len, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + &mut parameter, + 1, + ) + } as usize; + (at != 0).then_some(at) +} + +impl Upload { + pub(crate) fn new(len: usize) -> Option { + if !low() { + return Some(Upload(Kind::Heap(vec![0; len]))); + } + let n = len.max(1).div_ceil(BLOCK); + let mut arenas = ARENAS.lock().unwrap_or_else(|e| e.into_inner()); + let found = arenas.iter().enumerate().find_map(|(a, arena)| Some((a, gap(&arena.taken, n)?))); + let (a, first) = match found { + Some(place) => place, + None => { + let blocks = n.max(ARENA / BLOCK); + let at = reserve(blocks * BLOCK)?; + crate::shadow::register(at, at as u64, (blocks * BLOCK) as u64); + tracing::info!(at = format_args!("{at:#x}"), bytes = blocks * BLOCK, "memory for lists' uploads, where shaders reach it by address"); + arenas.push(Arena { at, taken: vec![false; blocks] }); + (arenas.len() - 1, 0) + } + }; + let arena = &mut arenas[a]; + arena.taken[first..first + n].fill(true); + let at = arena.at + first * BLOCK; + // SAFETY: the blocks are the arena's and nobody else's now. + unsafe { std::ptr::write_bytes(at as *mut u8, 0, len) }; + Some(Upload(Kind::Low(at, len))) + } + + pub(crate) fn start(&mut self) -> *mut u8 { + match &mut self.0 { + Kind::Low(at, _) => *at as *mut u8, + Kind::Heap(block) => block.as_mut_ptr(), + } + } +} + +impl Drop for Upload { + fn drop(&mut self) { + let Kind::Low(at, len) = self.0 else { return }; + let mut arenas = ARENAS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(arena) = arenas.iter_mut().find(|a| (a.at..a.at + a.taken.len() * BLOCK).contains(&at)) { + let first = (at - arena.at) / BLOCK; + arena.taken[first..first + len.max(1).div_ceil(BLOCK)].fill(false); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blocks_lie_below_40_bits_and_are_used_again_zeroed() { + let mut a = Upload::new(100).unwrap(); + let mut b = Upload::new(BLOCK + 1).unwrap(); + let (pa, pb) = (a.start(), b.start()); + assert!((pa as usize) >= 1 << 32 && (pb as usize) + 2 * BLOCK <= 1 << 40); + assert!((pa as usize).is_multiple_of(BLOCK) && pa != pb); + // SAFETY: 100 bytes were handed out. + unsafe { pa.write_bytes(0xab, 100) }; + drop(a); + // The lowest free place (another test may have taken it meanwhile; + // zeroed either way). + let mut c = Upload::new(100).unwrap(); + // SAFETY: as above. + assert!(unsafe { std::slice::from_raw_parts(c.start(), 100) }.iter().all(|&x| x == 0)); + // More than an arena. + let mut d = Upload::new(ARENA + 1).unwrap(); + // SAFETY: the bytes were handed out. + unsafe { d.start().add(ARENA).write(1) }; + drop(b); + } + + #[test] + fn a_gap_is_blocks_side_by_side() { + assert_eq!(gap(&[true, false, true, false, false, true], 1), Some(1)); + assert_eq!(gap(&[true, false, true, false, false, true], 2), Some(3)); + assert_eq!(gap(&[true, false, true, false, false, true], 3), None); + } +} diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs index 78a1d99..e1043f3 100644 --- a/crates/victory-shader/src/emit/intersect.rs +++ b/crates/victory-shader/src/emit/intersect.rs @@ -251,7 +251,6 @@ impl<'a> Lower<'a> { /// computed, `offset` fixed; none of the node's bytes past 127), read /// four at a time. fn bvh_node_words(&mut self, at: NodeAt, base: Option, offset: u32, count: u32) -> Vec { - let c = self.cur; let (undef, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); // The second half of a 128-byte node may lie in the next 64 KiB // page, which may be in another copy: its own look, made once. @@ -267,10 +266,11 @@ impl<'a> Lower<'a> { let (low, high) = self.address_plus(low, high, 64); // Every lane in this block runs the instruction. let (handle, byte) = self.bvh_memory(low, high, None); - let k64 = self.s.m.i32(64); + let (k64, c) = (self.s.m.i32(64), self.cur); (handle, self.s.m.bin(c, Bin::Sub, byte, k64)) }), }; + let c = self.cur; if let Some(b) = base { byte = self.s.m.bin(c, Bin::Add, byte, b); } @@ -330,6 +330,8 @@ impl<'a> Lower<'a> { let k16 = self.s.m.i32(16); let words = self.bvh_node_words(at, None, 16, 24); let floats: Vec = words.iter().map(|&w| self.as_float(w)).collect(); + // (The look for the second half goes on in another block.) + let wide_block = self.cur; self.s.m.terminate(wide_block, Term::Br(join)); // 16-bit floats: 24 halves in 12 dwords from byte 16, the low half // of a dword first. diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 6a86f71..44bee8c 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -259,6 +259,9 @@ struct Lower<'a> { /// they are globally coherent; a load in a loop that only waits would /// be made once otherwise. coherent: HashSet<(usize, u32)>, + /// In the instruction being lowered: the host copy its root view's bytes + /// are in ([`Lower::root_memory`]). + root_copy: Option, mask_phis: HashMap, pending_masks: Vec<(V, usize, usize)>, data_phis: Vec<(V, usize, usize)>, @@ -1572,6 +1575,7 @@ impl<'a> Lower<'a> { read_phis: HashSet::new(), stale: HashSet::new(), coherent: HashSet::new(), + root_copy: None, ordered: if x.native.stage == HwStage::Ps { ordered_section(p) } else { @@ -1735,6 +1739,7 @@ impl<'a> Lower<'a> { let Fields::Flat { dst, .. } = &inst.fields else { unreachable!() }; + self.root_copy = None; let name = inst.name(); if self.scalar.get(&(b, i)).is_some_and(|a| a.param == MEMORY) { return self.memory_flat(inst, b, i); @@ -1778,8 +1783,15 @@ impl<'a> Lower<'a> { if let Some(bias) = self.root_bias(a.param) { off = self.s.m.bin(c, Bin::Add, off, bias); } - Some(self.handle((b, i), &src, false, (11, 0))?) + match self.root_memory(&src, off, guard) { + Some((h, byte)) => { + off = byte; + Some(h) + } + None => Some(self.handle((b, i), &src, false, (11, 0))?), + } }; + let c = self.cur; let dword = |l: &mut Self, byte: V| -> Result { match h { None => l.code_dword(byte), @@ -2999,7 +3011,8 @@ impl<'a> Lower<'a> { /// `SLOT_MEMORY`): the handle of the raw view of the host copy holding /// it and the byte in that view. A page without a copy reads zeros /// (and drops writes) through the null view at the first slot, and its - /// number is left for the host, for lanes that run (`guard`). + /// number is left for the host, for lanes that run (`guard`). Goes on in + /// another block. fn memory(&mut self, lo: V, hi: V, guard: Option) -> (V, V) { use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE}; let c = self.cur; @@ -3031,21 +3044,23 @@ impl<'a> Lower<'a> { ); let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1)); let (copy, start) = (self.as_int(copy), self.as_int(start)); - // A page without a copy: its number, at a place by the number, or - // at the sink for lanes that do not run and pages that have one. + // A page without a copy: its number, at a place by the number. In a + // branch: the notes lie in the PC's memory, and a store there with + // every node of every ray would be most of what a trace does. let zero = k(self, 0); let mut missing = self.s.m.cmp(c, pred::EQ, copy, zero); if let Some(g) = guard { missing = self.s.m.bin(c, Bin::And, missing, g); } let places = k(self, MEMORY_FAULTS - 1); + let faults = self.s.root_uav_handle(SLOT_FAULTS); + let noting = self.begin_guarded(Some(missing)); + let c = self.cur; let place = self.s.m.bin(c, Bin::URem, page, places); let one = k(self, 1); let place = self.s.m.bin(c, Bin::Add, place, one); let k2 = k(self, 2); let place = self.s.m.bin(c, Bin::Shl, place, k2); - let place = self.s.m.select(c, missing, place, zero); - let faults = self.s.root_uav_handle(SLOT_FAULTS); let void = self.s.t.void; let mask = self.s.m.i8(1); self.s.op( @@ -3056,15 +3071,63 @@ impl<'a> Lower<'a> { 140, &[faults, place, iu, page, iu, iu, iu, mask, align], ); + self.end_guarded(noting, &[]); + let c = self.cur; let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0); let slot = self.s.m.bin(c, Bin::Add, base, copy); - let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0)); + // The builder's threads read what others of the dispatch wrote (a + // refit climbs from children to parents): globally coherent. + let coherent = if crate::spill::is_spilled(self.x.native) { 0x4000 } else { 0 }; + let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000 | coherent, 0)); let k64k = k(self, 0xFFFF); let within = self.s.m.bin(c, Bin::And, lo, k64k); let byte = self.s.m.bin(c, Bin::Add, start, within); (h, byte) } + /// The title address in the root view `src` is built around, in a program + /// with a spilled user-data table (`shader.rs` `USER_ROOT_ADDRESS`). + fn root_address(&mut self, src: &Source) -> Option<(V, V)> { + use super::shader::USER_ROOT_ADDRESS; + let Source::Built { address, .. } = src else { + return None; + }; + let rp = *self.x.native.layout.get(address.param)?; + if rp.root != RootType::Descriptor || !crate::spill::is_spilled(self.x.native) { + return None; + } + let used = self.x.native.used.iter().find(|u| u.user_data == rp.user_data)?; + if !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) { + return None; + } + let lo = self.host_word(RootType::Other(USER_ROOT_ADDRESS), rp.slot, 0); + let hi = self.host_word(RootType::Other(USER_ROOT_ADDRESS + 1), rp.slot, 0); + Some((lo, hi)) + } + + /// For an access through such a root view: the raw view of the host copy + /// and the byte in it of the view's byte `off` (signed: an offset below + /// the address stays below it). [`Lower::handle`] gives the same view for + /// the rest of the instruction. None for any other source. Goes on in + /// another block. + /// shortcut: an access of several dwords is taken not to cross the end + /// of a host copy (the builder's records lie on their size). + fn root_memory(&mut self, src: &Source, off: V, guard: Option) -> Option<(V, V)> { + let (lo, hi) = self.root_address(src)?; + let c = self.cur; + let i32t = self.s.t.i32; + let sum = self.s.m.bin(c, Bin::Add, lo, off); + let wrapped = self.s.m.cmp(c, pred::IULT, sum, lo); + let carry = self.s.m.cast(c, Cast::ZExt, wrapped, i32t); + 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 (h, byte) = self.memory(sum, hi, guard); + self.root_copy = Some(h); + Some((h, byte)) + } + /// `global_load_*`, `global_store_*` and `global_atomic_*` on title /// memory by address (`resource::MEMORY`): the address is the VGPR /// pair, each lane its own. @@ -3094,7 +3157,6 @@ impl<'a> Lower<'a> { let (lo, hi) = (word(self, 0)?, word(self, 1)?); let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset)); let guard = self.guard(b, i)?; - let c = self.cur; let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void); let iu = self.s.m.undef(i32t); let align = self.s.m.i32(4); @@ -3112,6 +3174,7 @@ impl<'a> Lower<'a> { return Err("a global load result"); }; let (h, byte) = self.memory(lo, hi, guard); + let c = self.cur; let mask = self.s.m.i8((1u8 << n) - 1); let r = self.s.op( c, @@ -3160,6 +3223,7 @@ impl<'a> Lower<'a> { None => self.s.m.i32(0), }; let (h, byte) = self.memory(lo, hi, guard); + let c = self.cur; // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8. let simple = match op { @@ -3294,6 +3358,7 @@ impl<'a> Lower<'a> { let n = (count - first).min(4); let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first)); let (h, byte) = self.memory(lo, hi, None); + let c = self.cur; let mask = self.s.m.i8((1u8 << n) - 1); let r = self.s.op( c, @@ -5830,6 +5895,7 @@ impl<'a> Lower<'a> { else { unreachable!() }; + self.root_copy = None; let name = inst.name(); if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) { return self.code_smem(inst, a); @@ -5938,7 +6004,14 @@ impl<'a> Lower<'a> { return Ok(()); } if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { - let h = self.handle(site, src, false, (11, 0))?; + let h = match self.root_memory(src, addr, None) { + Some((h, byte)) => { + addr = byte; + h + } + None => self.handle(site, src, false, (11, 0))?, + }; + let c = self.cur; for k in 0..count { let off = self.s.m.i32(4 * k); let a = self.s.m.bin(c, Bin::Add, addr, off); @@ -6645,13 +6718,14 @@ impl<'a> Lower<'a> { /// For a root view the host binds as a raw view that may begin before /// the title's address (`shader.rs` `USER_VIEW_BIAS`): the bytes to add - /// to offsets through it. Every root UAV, and the root SRVs of programs - /// with a spilled user-data table (the others keep the views they + /// to offsets through it. Every root UAV (root SRVs keep the views they /// have). fn root_bias(&mut self, param: usize) -> Option { use super::shader::USER_VIEW_BIAS; let rp = *self.x.native.layout.get(param)?; - if rp.root != RootType::Descriptor { + // (Title memory by address where the user-data table is spilled: + // [`Lower::root_memory`].) + if rp.root != RootType::Descriptor || crate::spill::is_spilled(self.x.native) { return None; } let kind = self @@ -6661,12 +6735,7 @@ impl<'a> Lower<'a> { .iter() .find(|u| u.user_data == rp.user_data) .map(|u| u.kind); - let biased = match kind { - Some(ResourceType::Uav) => true, - Some(ResourceType::Srv) => crate::spill::is_spilled(self.x.native), - _ => false, - }; - biased.then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0)) + (kind == Some(ResourceType::Uav)).then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0)) } /// The used-resource entry a descriptor loaded from a table falls in. @@ -6738,6 +6807,7 @@ impl<'a> Lower<'a> { Ok(self.s.sampler_handle(self.cur, n)) } Source::Constant(_) => Err("a constant resource descriptor"), + Source::Built { .. } if self.root_copy.is_some() => self.root_copy.ok_or("no copy"), Source::Built { address, .. } => { let rp = *self .x @@ -11001,6 +11071,7 @@ impl<'a> Lower<'a> { } fn buffer(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + self.root_copy = None; let Fields::Buffer { data, addr, @@ -11163,6 +11234,20 @@ impl<'a> Lower<'a> { } return Ok(()); } + if self.root_address(src).is_some() { + // Title memory by address: the byte in the host copy from here on. + if let Some(element) = index { + if used.is_none_or(|u| u.stride != 1) { + return Err("an indexed access through a root view by address"); + } + off = self.s.m.bin(c, Bin::Add, element, off); + index = None; + } + if let Some((_, byte)) = self.root_memory(src, off, guard) { + off = byte; + } + } + let c = self.cur; let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav); let mut u = if uav { 0x1000 } else { 0 }; if uav && !typed && self.entry(src).is_some_and(|e| self.coherent.contains(&e)) { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index c9c727e..bd453bc 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -118,7 +118,7 @@ pub use lower::{host_settings, set_host_max_wave}; pub use rect::rect_list_gs; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, - SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, + SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS, 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 eb6d589..c73baf6 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -66,9 +66,16 @@ pub const USER_VIEW_ADDRESS: u32 = 0x101; /// begins on 16 bytes of its host buffer; the console's root views begin /// anywhere (the structure builder's counters sit at addresses ending in /// 4 and c). The shader adds the dword to every byte offset through that -/// view. Asked for every root UAV, and for the root SRVs of programs with -/// a spilled user-data table. +/// view. Asked for every root UAV. pub const USER_VIEW_BIAS: u32 = 0x103; +/// `RootType::Other` code of a user-data dword the host computes: the low +/// 32 bits of the title address in the root view of root parameter `slot`; +/// [`USER_ROOT_ADDRESS`] + 1: its bits from 32 up. Programs with a spilled +/// user-data table (the ray-tracing structure builder's) reach what their +/// root views name as title memory by address ([`SLOT_MEMORY`]): a root view +/// has no size, and the host's copy of what it names may end in the middle of +/// it (a structure of megabytes crosses the 4 MiB windows). +pub const USER_ROOT_ADDRESS: u32 = 0x104; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { From d77556c791599421f7c2d57524e5d62cc939e6ca Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:23:33 -0600 Subject: [PATCH 310/445] Fewer empty staging blocks kept; the raw twins made are counted Run crash-1 held 5.2 GB of staging blocks (n02: 0.9): at most 8 empty ones stay (512 MB of the PC's memory). With the frame line: raw twins made per frame, and those that had to be views as the title's are. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 8 ++++++++ crates/victory-gpu/src/descriptor/host.rs | 2 +- crates/victory-gpu/src/pool.rs | 22 +++++++++++++--------- 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index d4edf99..256b8e5 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -286,6 +286,14 @@ pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 6] = [const { std::sync /// Nothing while no heap page changed. #[cfg(windows)] pub(crate) fn sync_line(frames: f64) { + let [twins, as_is] = [0, 1].map(|i| host::TWINS[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + if twins > 0 { + tracing::info!( + "raw twins of buffer views made per frame (VICTORY_RAW_VIEWS=0: none): {:.0}, of them {:.1} as the title's view is (it does not begin on 16 bytes)", + twins as f64 / frames, + as_is as f64 / frames + ); + } let [pages, looked, mirrored, micros, tabled, later] = [0, 1, 2, 3, 4, 5].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); if pages == 0 { return; diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 357ed9c..7bf1711 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -2542,7 +2542,7 @@ fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: .is_some_and(|end| end <= width) } -/// Raw twins ([`raw_twins`]) made since the start, and those of them that had +/// Raw twins ([`raw_twins`]) made since the last frame line, and those of them that had /// to be views as the title's slot has them (a raw view begins on 16 bytes). pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index 95ba178..f4d3b73 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -31,6 +31,9 @@ const BLOCK: u64 = 64 << 20; const SPARE: usize = 2; /// The same while the card has room ([`room`]): 4 GiB of them. const SPARE_KEPT: usize = 64; +/// The same of blocks of staging buffers, which are the PC's memory: run +/// crash-1 held 5.2 GB of them. +const STAGING_KEPT: usize = 8; /// How many are kept now. static SPARES: AtomicUsize = AtomicUsize::new(SPARE); @@ -125,13 +128,14 @@ struct Pool { blocks: Vec>>, /// Pieces given back, and when each may be used again. resting: VecDeque<(u64, Piece)>, - /// The empty blocks it was last told to keep. + /// The empty blocks it was last told to keep, and the most it keeps. spare: usize, + most: usize, } impl Pool { - const fn new() -> Pool { - Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0 } + const fn new(most: usize) -> Pool { + Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most } } /// A piece of `len` bytes and the memory it lies in, and whether that @@ -190,7 +194,7 @@ impl Pool { } } // (Without a piece given back too, once there is less room.) - let most = SPARES.load(Ordering::Relaxed); + let most = SPARES.load(Ordering::Relaxed).min(self.most); if any || most < self.spare { self.spare = most; let mut spare = 0; @@ -216,8 +220,8 @@ struct Upload(ID3D12Resource, *mut u8); // SAFETY: the mapping is written by the owners of its pieces, each its own. unsafe impl Send for Upload {} -static TEXTURES: Mutex> = Mutex::new(Pool::new()); -static STAGING: Mutex> = Mutex::new(Pool::new()); +static TEXTURES: Mutex> = Mutex::new(Pool::new(SPARE_KEPT)); +static STAGING: Mutex> = Mutex::new(Pool::new(STAGING_KEPT)); fn lock(m: &'static Mutex) -> std::sync::MutexGuard<'static, T> { m.lock().unwrap_or_else(|e| e.into_inner()) @@ -413,7 +417,7 @@ mod tests { #[test] fn pieces_never_overlap_and_rest_before_they_are_used_again() { - let mut pool: Pool = Pool::new(); + let mut pool: Pool = Pool::new(SPARE); let made = std::cell::Cell::new(0); let make = || { made.set(made.get() + 1); @@ -440,10 +444,10 @@ mod tests { pool.give(p, 20); } pool.rested(20 + REST); - assert_eq!(pool.blocks(), blocks.min(SPARES.load(Ordering::Relaxed))); + assert_eq!(pool.blocks(), blocks.min(SPARE)); // Too big for a block, and a block that cannot be made. assert!(pool.take(BLOCK, 65536, 30, make).is_none()); - let mut none: Pool = Pool::new(); + let mut none: Pool = Pool::new(SPARE); assert!(none.take(65536, 65536, 0, || None).is_none()); } From bd68f5e175e01551f5e65dab7d484fe690af346b Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:35:03 -0600 Subject: [PATCH 311/445] Card memory the CPU maps: windows, sends and scratch (VICTORY_WINDOWS_BAR_MB, VICTORY_SEND_BAR, VICTORY_SCRATCH_BAR); the card's own stamps (VICTORY_CARD_SPANS) GPU_UPLOAD heaps, all off by default. Replayed yard frame (capture play-1125-0127): 36.3 ms; windows in the card's memory 31.9, sends 32.7. Replay: --pace, --breadcrumbs, copies counted by the memory they cross. VICTORY_GPU_LOAD_MS: what the title's GPU timestamps show. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 9 + crates/victory-gpu/src/draw.rs | 4 + crates/victory-gpu/src/host.rs | 105 +++++++++++- crates/victory-gpu/src/host/send.rs | 23 ++- crates/victory-gpu/src/host/spans.rs | 232 ++++++++++++++++++++++++++ crates/victory-gpu/src/queue.rs | 38 ++++- crates/victory-gpu/src/replay/play.rs | 82 ++++++++- crates/victory-gpu/src/shadow.rs | 66 +++++++- docs/replay.md | 2 + 9 files changed, 549 insertions(+), 12 deletions(-) create mode 100644 crates/victory-gpu/src/host/spans.rs diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index e6e7860..db2f9d6 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -81,6 +81,13 @@ pub(crate) struct Replay { /// Each list sent on its own, and waited for. #[arg(long)] wait_lists: bool, + /// Milliseconds to wait after sending each submission: the card stands + /// idle between them, as it does while the title prepares the next. + #[arg(long, default_value_t = 0.0)] + pace: f64, + /// The system's breadcrumbs after every command (VICTORY_D3D12_DRED=light). + #[arg(long)] + breadcrumbs: bool, /// Run only these lists, by their place in the frame (`3..7`, or `5`); /// of the others only barriers. #[arg(long)] @@ -255,11 +262,13 @@ pub(crate) fn run(r: Replay) -> Result<()> { merge: !r.no_merge, wait_all: r.wait_all, wait_lists: r.wait_lists, + pace: r.pace, only, until, skip_shaders: r.skip_shader, compare: r.compare, debug: r.debug_layer, + breadcrumbs: r.breadcrumbs, }; if let Some(text) = &r.slots { let (list, command) = text diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2b6f8a0..8454580 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -833,6 +833,10 @@ impl State { /// Viewports, scissors, the blend factor and the stencil reference: set /// on the host list at once, and kept for [`State::replay`]. pub(crate) fn set_viewports(&mut self, list: &HostList, viewports: &[D3D12_VIEWPORT]) { + #[cfg(feature = "diagnostics")] + if let Some(v) = viewports.first() { + crate::host::spans::viewport(v.Width as u32, v.Height as u32); + } self.viewports.clear(); self.viewports.extend_from_slice(viewports); crate::draw::viewports(list, viewports); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index e24be3b..0c77c85 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1579,6 +1579,15 @@ impl Spare { /// Scratch chunks no list holds. static SPARE: Mutex> = Mutex::new(Spare::new()); +/// Whether lists' scratch memory (constants and tables, which shaders read) +/// lies in the card's memory, written by the CPU through the bus +/// (`VICTORY_SCRATCH_BAR=1`; the default is upload memory, which the card +/// reads through it). +fn scratch_on_card() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_BAR").is_some_and(|v| v == "1")) +} + /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one. fn take_chunk(host: &Host, size: u64) -> Option { if scratch_pool() @@ -1589,7 +1598,11 @@ fn take_chunk(host: &Host, size: u64) -> Option { ALIVE[5].fetch_add(1, Ordering::Relaxed); return Some(chunk); } - let (buffer, data) = host.upload_buffer(size)?; + let mapped = if scratch_on_card() { host.mapped_card_buffer(size, false) } else { None }; + let (buffer, data) = match mapped { + Some(made) => made, + None => host.upload_buffer(size)?, + }; name(&buffer, || "list scratch".into()); ALIVE[1].fetch_add(1, Ordering::Relaxed); ALIVE[2].fetch_add(size, Ordering::Relaxed); @@ -3157,6 +3170,8 @@ fn late_line(frames: f64) { mod card_steps; mod place; mod send; +#[cfg(feature = "diagnostics")] +pub(crate) mod spans; mod torn; pub(crate) mod upcheck; @@ -5005,6 +5020,11 @@ impl Host { let prepared = std::time::Instant::now(); if late { *submitted += 1; + #[cfg(feature = "diagnostics")] + if let Some([front, behind]) = self.span_lists() { + lists.insert(0, Some(front)); + lists.push(Some(behind)); + } // SAFETY: closed lists; the fence is ours. let signalled = unsafe { self.queue.ExecuteCommandLists(&lists); @@ -7318,6 +7338,8 @@ impl Meter { crate::descriptor::sync_line(frames); late_line(frames); card_clock_line(frames, ms); + #[cfg(feature = "diagnostics")] + spans::line(frames); crate::shadow::back_line(frames); #[cfg(feature = "diagnostics")] split_line(frames); @@ -7891,6 +7913,87 @@ impl Host { } } + /// Whether buffers can lie in the card's memory and be mapped by the CPU + /// (`D3D12_HEAP_TYPE_GPU_UPLOAD`: a resizable BAR, and a system and driver + /// that offer it); logged once. + pub(crate) fn mapped_card_memory(&self) -> bool { + static THERE: OnceLock = OnceLock::new(); + *THERE.get_or_init(|| { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default(); + // SAFETY: writes `options` of the given size. + let ok = unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS16, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + }; + let supported = ok && options.GPUUploadHeapSupported.as_bool(); + tracing::info!(supported, "card memory the CPU maps"); + supported + }) + } + + /// A buffer in the card's own memory that the CPU maps, shaders read and + /// (with `written`) may write. The CPU should only write it: a read of the + /// mapping crosses the bus a few bytes at a time. + pub(crate) fn mapped_card_buffer(&self, size: u64, written: bool) -> Option<(ID3D12Resource, *mut u8)> { + if !self.mapped_card_memory() { + return None; + } + MADE[4].fetch_add(1, Ordering::Relaxed); + MADE[5].fetch_add(size, Ordering::Relaxed); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_GPU_UPLOAD, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: if written { + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS + } else { + D3D12_RESOURCE_FLAG_NONE + }, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping of a CPU-visible buffer. + let made = unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .and_then(|()| { + let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + b.Map(0, None, Some(&mut data)) + }) + }; + match made { + Ok(()) => Some((buffer?, data.cast())), + Err(e) => { + tracing::warn!(error = %e, size, "no buffer in card memory the CPU maps"); + None + } + } + } + /// A device-local buffer shaders may write (unordered access) and indirect /// execution may read, starting in the common state. pub(crate) fn uav_buffer(&self, size: u64) -> Option { diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs index 9227399..669c965 100644 --- a/crates/victory-gpu/src/host/send.rs +++ b/crates/victory-gpu/src/host/send.rs @@ -88,8 +88,19 @@ unsafe impl Send for Memory {} /// What submissions that have run gave back. static SPARE: Mutex> = Mutex::new(Vec::new()); -/// At most this much is kept. -const KEPT: u64 = 768 << 20; +/// At most this much is kept (of the card's memory, with [`on_card`]). +fn kept() -> u64 { + if on_card() { 256 << 20 } else { 768 << 20 } +} + +/// Whether the memory lies in the card's memory, written by the CPU through +/// the bus (`VICTORY_SEND_BAR=1`): the copies on the card's drawing queue, which +/// nothing overlaps, then cross no bus. In a captured frame they took 5.4 ms of +/// the card's 30 (342 copies). +fn on_card() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SEND_BAR").is_some_and(|v| v == "1")) +} fn memory(host: &Host, size: u64) -> Option { { @@ -100,7 +111,11 @@ fn memory(host: &Host, size: u64) -> Option { } } let size = size.next_multiple_of(8 << 20); - let (buffer, data) = host.upload_buffer(size)?; + let mapped = if on_card() { host.mapped_card_buffer(size, false) } else { None }; + let (buffer, data) = match mapped { + Some(made) => made, + None => host.upload_buffer(size)?, + }; name(&buffer, || "bytes a submission sends up".into()); Some(Memory { buffer, @@ -114,7 +129,7 @@ pub(super) fn give_back(memory: Memory) { let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); spare.push(memory); spare.sort_by_key(|m| std::cmp::Reverse(m.size)); - while spare.iter().map(|m| m.size).sum::() > KEPT { + while spare.iter().map(|m| m.size).sum::() > kept() { spare.remove(0); } } diff --git a/crates/victory-gpu/src/host/spans.rs b/crates/victory-gpu/src/host/spans.rs new file mode 100644 index 0000000..e8bd804 --- /dev/null +++ b/crates/victory-gpu/src/host/spans.rs @@ -0,0 +1,232 @@ +//! Diagnostics: how long the card itself works on our submissions, by its own +//! timestamps (`VICTORY_CARD_SPANS=1`). The clock of the frame line +//! (`card_clock_line`) counts from the call that sends a submission to the +//! moment a thread of ours wakes behind its last signal: the time the system +//! takes to hand a submission to the card and to report it done is in it, 40 +//! times a frame. Here two lists made once, of nothing but a timestamp, stand +//! around each submission. + +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::Interface; + +use super::Host; + +/// Submissions stamped before the first stamps are read and used again. +const SPANS: usize = 512; + +/// The stamps of one queue's submissions. +pub(super) struct Spans { + _allocator: ID3D12CommandAllocator, + _heap: ID3D12QueryHeap, + _back: ID3D12Resource, + /// The mapped results, two a submission. + data: usize, + lists: Vec, + ticks_per_ms: f64, + next: usize, + sums: Sums, +} + +// SAFETY: free-threaded objects and a mapping only read behind a lock. +unsafe impl Send for Spans {} + +/// What the stamps read so far add up to. +#[derive(Debug, Default, Clone, Copy, PartialEq)] +struct Sums { + /// Submissions, ticks the card worked on them, ticks between them. + count: u64, + busy: u64, + between: u64, + /// Ticks of the longest one, and the last one's end. + longest: u64, + last: u64, +} + +impl Sums { + /// A submission that ran from `start` to `end` (card ticks), after those + /// before it. The start's stamp may be of before the last one's end: the + /// part before that end is the last one's. + fn add(&mut self, start: u64, end: u64) { + if start == 0 || end < start { + return; + } + let start = start.max(self.last); + let took = end.saturating_sub(start); + if self.last != 0 { + self.between += start - self.last; + } + self.count += 1; + self.busy += took; + self.longest = self.longest.max(took); + self.last = end.max(self.last); + } +} + +fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_SPANS").is_some_and(|v| v == "1")) +} + +static SPANS_MADE: Mutex>> = Mutex::new(None); + +impl Host { + /// The lists that go in front of and behind a submission about to be + /// sent to the drawing queue, if stamps are asked for. + pub(super) fn span_lists(&self) -> Option<[ID3D12CommandList; 2]> { + if !on() { + return None; + } + let mut made = SPANS_MADE.lock().unwrap_or_else(|e| e.into_inner()); + let spans = made + .get_or_insert_with(|| { + self.make_spans() + .inspect_err(|e| tracing::warn!(error = %e, "no stamps around submissions")) + .ok() + }) + .as_mut()?; + let i = spans.next; + spans.next = (i + 1) % SPANS; + // The stamps of the submission that had these lists, that many + // submissions ago: long done. + // SAFETY: inside the mapping; written by the card at whole words. + let (start, end) = unsafe { + let at = (spans.data as *mut u64).add(2 * i); + let read = (at.read_volatile(), at.add(1).read_volatile()); + at.write_volatile(0); + at.add(1).write_volatile(0); + read + }; + spans.sums.add(start, end); + Some([spans.lists[2 * i].clone(), spans.lists[2 * i + 1].clone()]) + } + + fn make_spans(&self) -> windows::core::Result { + let device = &self.device; + // SAFETY: plain object creation; lists of one allocator recorded one + // after the other. + unsafe { + let mut heap: Option = None; + device.CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2 * SPANS as u32, + NodeMask: 0, + }, + &mut heap, + )?; + let heap = heap.ok_or_else(windows::core::Error::empty)?; + let back = self.read_back_buffer(16 * SPANS as u64).ok_or_else(windows::core::Error::empty)?; + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data))?; + std::ptr::write_bytes(data.cast::(), 0, 16 * SPANS); + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let mut lists = Vec::with_capacity(2 * SPANS); + for i in 0..2 * SPANS as u32 { + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.EndQuery(&heap, D3D12_QUERY_TYPE_TIMESTAMP, i); + list.ResolveQueryData(&heap, D3D12_QUERY_TYPE_TIMESTAMP, i, 1, &back, u64::from(i) * 8); + list.Close()?; + lists.push(list.cast()?); + } + Ok(Spans { + _allocator: allocator, + _heap: heap, + _back: back, + data: data as usize, + lists, + ticks_per_ms: self.queue.GetTimestampFrequency()? as f64 / 1000.0, + next: 0, + sums: Sums::default(), + }) + } + } +} + +/// The GPU timestamps the title was given since the last frame-rate line: +/// how many, how often a later one was 1 ms or more after the one before +/// (written with another submission), and where the first few lie. +static STAMPED: Mutex<(u64, u64, u64, Vec)> = Mutex::new((0, 0, 0, Vec::new())); + +/// The title's GPU timestamp at `at` was given the value `now` (ticks of 10 +/// ns). +pub(crate) fn stamped(at: usize, now: u64) { + if !on() { + return; + } + let mut s = STAMPED.lock().unwrap_or_else(|e| e.into_inner()); + s.0 += 1; + s.1 += u64::from(now.saturating_sub(s.2) > 100_000); + s.2 = now; + if s.3.len() < 64 && !s.3.contains(&at) { + s.3.push(at); + tracing::info!(address = format_args!("{at:#x}"), now, "a GPU timestamp of the title"); + } +} + +/// The viewports' sizes seen (each said once): whether the title draws its +/// scene at sizes of its choice. +pub(crate) fn viewport(width: u32, height: u32) { + if !on() || width < 1024 || height < 576 { + return; + } + static SEEN: Mutex> = Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if seen.len() < 200 && !seen.contains(&(width, height)) { + seen.push((width, height)); + tracing::info!(width, height, "a viewport of the title"); + } +} + +/// For the frame-rate line: what the stamps read since the last one say, per +/// frame (they are of some [`SPANS`] submissions ago). +pub(super) fn line(frames: f64) { + { + let mut s = STAMPED.lock().unwrap_or_else(|e| e.into_inner()); + if s.0 > 0 { + tracing::info!( + "GPU timestamps the title asked for per frame: {:.1}, in {:.1} groups written at one time", + s.0 as f64 / frames, + s.1 as f64 / frames + ); + } + (s.0, s.1) = (0, 0); + } + let mut made = SPANS_MADE.lock().unwrap_or_else(|e| e.into_inner()); + let Some(Some(spans)) = made.as_mut() else { + return; + }; + let last = spans.sums.last; + let s = std::mem::replace(&mut spans.sums, Sums { last, ..Sums::default() }); + let ms = |ticks: u64| ticks as f64 / spans.ticks_per_ms / frames; + tracing::info!( + "the card's own stamps per frame: {:.1} submissions, working {:.1} ms, idle between them {:.1} ms, the longest {:.1} ms", + s.count as f64 / frames, + ms(s.busy), + ms(s.between), + s.longest as f64 / spans.ticks_per_ms + ); +} + +#[cfg(test)] +mod tests { + use super::Sums; + + #[test] + fn submissions_add_up_without_counting_anything_twice() { + let mut s = Sums::default(); + s.add(100, 150); + s.add(140, 200); // began before the last one ended + s.add(260, 270); + assert_eq!((s.count, s.busy, s.between, s.longest, s.last), (3, 110, 60, 50, 270)); + // Never written, or nonsense: nothing. + s.add(0, 0); + s.add(300, 290); + assert_eq!(s.count, 3); + // Whole inside the last one. + s.add(265, 268); + assert_eq!((s.count, s.busy, s.between), (4, 110, 60)); + } +} diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 11d3a8c..884fbf0 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -715,7 +715,10 @@ impl Written { Written::GpuTimestamp => { static START: std::sync::OnceLock = std::sync::OnceLock::new(); let elapsed = START.get_or_init(std::time::Instant::now).elapsed(); - (elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64 + let now = (elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64; + #[cfg(all(windows, feature = "diagnostics"))] + crate::host::spans::stamped(at as usize, now); + as_loaded(now, at as usize, gpu_load()) } Written::SystemTimestamp => system_timestamp(), }; @@ -730,6 +733,31 @@ impl Written { } } +/// What the title's GPU time is made to look like, in ticks +/// (`VICTORY_GPU_LOAD_MS`; unset: as it is). +/// +/// The title asks for four GPU timestamps a frame, in pairs of 16 bytes, the +/// start in the second eight and the end in the first. All of them are written +/// when the frame's last submissions land, within microseconds, so every pair +/// says the card did nothing. +fn gpu_load() -> u64 { + static LOAD: std::sync::OnceLock = std::sync::OnceLock::new(); + *LOAD.get_or_init(|| { + let ms = std::env::var("VICTORY_GPU_LOAD_MS").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0); + ms * (TIMESTAMP_FREQUENCY / 1000) + }) +} + +/// The timestamp written at `at` when the clock says `now`, if a pair's start +/// is to lie `load` ticks before its end. +fn as_loaded(now: u64, at: usize, load: u64) -> u64 { + if at & 8 != 0 { + now.saturating_sub(load).max(1) + } else { + now + } +} + fn system_timestamp() -> u64 { #[cfg(windows)] { @@ -1072,6 +1100,14 @@ mod tests { assert_eq!(new[35], execute_x as *const ()); // 0x118 } + #[test] + fn a_pair_of_timestamps_shows_the_load_it_is_given() { + let (start, end) = (0xd0419_6698, 0xd0419_6690); + assert_eq!(as_loaded(5_000_000, end, 4_000_000) - as_loaded(5_000_000, start, 4_000_000), 4_000_000); + assert_eq!(as_loaded(5_000_000, start, 0), 5_000_000); + assert_eq!(as_loaded(5, start, 100), 1); + } + #[test] fn timestamps_and_values_are_written() { let mut at = [0u64; 2]; diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index b56f6e2..e28c20c 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -84,6 +84,9 @@ pub struct Options { pub wait_all: bool, /// Each list sent on its own, and waited for. pub wait_lists: bool, + /// Milliseconds the sender waits after each submission, as a title does + /// that prepares the next one meanwhile: the card stands idle. + pub pace: f64, /// Run only these lists (by their place in the frame). pub only: Option<(u32, u32)>, /// The last command that runs (list, command); after it only barriers. @@ -95,6 +98,9 @@ pub struct Options { pub compare: bool, /// The debug layer, if it is installed. pub debug: bool, + /// The system's breadcrumbs after every command, as + /// `VICTORY_D3D12_DRED=light` has them. + pub breadcrumbs: bool, } impl Default for Options { @@ -116,11 +122,13 @@ impl Default for Options { merge: true, wait_all: false, wait_lists: false, + pace: 0.0, only: None, until: None, skip_shaders: Vec::new(), compare: false, debug: false, + breadcrumbs: false, } } } @@ -488,6 +496,10 @@ pub struct Player { /// What a command of a list is timed as. type Stamp = (usize, &'static str, u32); +/// With a stamp of a copy to a texture: this bit and the texture's number +/// stand for the pipeline's. +const COPY_TO: u32 = 1 << 31; + /// A list made from commands, with what its timestamps are of. struct Built { _allocator: ID3D12CommandAllocator, @@ -503,7 +515,7 @@ impl Player { let folder = find(folder)?; let began = Instant::now(); let frame = Frame::read(&folder.join("frame.bin"))?; - let (device, info) = make_device(&frame, options.debug)?; + let (device, info) = make_device(&frame, options.debug, options.breadcrumbs)?; // SAFETY: plain creation and queries. let (queue, frequency) = unsafe { let queue: ID3D12CommandQueue = @@ -2413,9 +2425,18 @@ impl Player { "clears" } Cmd::Resolve { .. } | Cmd::ResolveRegion { .. } => "resolves", - _ => "copies", + _ => self.copy_kind(c), + }; + let runs = match c { + c if c.runs_shaders() => bound, + // Copies to textures by what they go to. + Cmd::CopyResource { dst, .. } + | Cmd::CopyTexture { + dst: Loc::Sub { res: dst, .. }, + .. + } => COPY_TO | dst, + _ => NONE, }; - let runs = if c.runs_shaders() { bound } else { NONE }; stamps.push((**next as usize, category, runs)); **next += 1; } @@ -2423,6 +2444,34 @@ impl Player { stamps } + /// Which copies a copy is counted with: by the memory it crosses. + fn copy_kind(&self, c: &Cmd) -> &'static str { + let pc = |id: u32| { + self.objects.get(&id).is_some_and(|o| { + matches!(&self.frame.resources[o.index].place, + Place::Committed { props, .. } if gpu::seen(props) != Seen::No) + }) + }; + let res = |l: &Loc| match l { + Loc::Sub { res, .. } | Loc::Placed { res, .. } => *res, + }; + match c { + Cmd::CopyBuffer { dst, src, .. } => match (pc(*dst), pc(*src)) { + (false, true) => "copies of buffers, PC to card", + (true, false) => "copies of buffers, card to PC", + (true, true) => "copies of buffers, PC to PC", + (false, false) => "copies of buffers, card to card", + }, + Cmd::CopyTexture { dst, src, .. } => match (pc(res(dst)), pc(res(src))) { + (false, true) => "copies of textures, PC to card", + (true, _) => "copies of textures, to the PC", + (false, false) => "copies of textures, card to card", + }, + Cmd::CopyResource { .. } => "copies of whole resources", + _ => "copies", + } + } + unsafe fn command(&self, l: &ID3D12GraphicsCommandList, c: &Cmd, version: usize) { let res = |id: u32| self.resource(id); let view = |s: &Slot| self.targets.get(s).copied().unwrap_or_default(); @@ -2886,6 +2935,12 @@ impl Player { for all in &submissions { if !o.wait_lists { self.worker.queue.ExecuteCommandLists(all); + if o.pace > 0.0 { + let until = Instant::now() + std::time::Duration::from_secs_f64(o.pace / 1e3); + while Instant::now() < until { + std::thread::yield_now(); + } + } continue; } for l in all { @@ -3014,7 +3069,16 @@ impl Player { all.truncate(o.top); report.shaders = all .into_iter() - .map(|(ms, n, pso)| (ms, n, self.pipeline_name(pso))) + .map(|(ms, n, pso)| { + let name = match self.objects.get(&(pso & !COPY_TO)).filter(|_| pso & COPY_TO != 0) { + Some(o) => { + let r = &self.frame.resources[o.index]; + format!("copies to #{} {}", pso & !COPY_TO, r.name) + } + None => self.pipeline_name(pso), + }; + (ms, n, name) + }) .collect(); } @@ -3229,7 +3293,7 @@ fn read_at(file: &File, mut to: &mut [u8], mut at: u64) -> std::io::Result<()> { Ok(()) } -fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option)> { +fn make_device(frame: &Frame, debug: bool, breadcrumbs: bool) -> Result<(ID3D12Device, Option)> { // SAFETY: plain creation and queries. unsafe { if debug { @@ -3247,6 +3311,14 @@ fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option tracing::warn!("no debug layer: {e}"), } } + if breadcrumbs { + let mut dred: Option = None; + D3D12GetDebugInterface(&mut dred)?; + if let Some(dred) = dred { + dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + } + } let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; let mut adapter = None; for i in 0.. { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 8b127df..b2d9155 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -83,6 +83,8 @@ pub(crate) struct Shadow { card: Option, /// A window of title memory outside buffers, not a title buffer's copy. window: bool, + /// A window in card memory the CPU maps ([`window_mapped_for`]). + mapped: bool, /// With `crate::inplace`: not a copy at all. `buffer` is placed in a /// heap opened on the title memory itself, so shaders read and write /// the title's own bytes and nothing is copied either way. The heap, @@ -299,7 +301,9 @@ pub(crate) fn card_stats() -> [u64; 10] { out[i] = stat.swap(0, Ordering::Relaxed); } out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.strong_count() > 0).count() as u64; - out[8] = CARD_BYTES[0].load(Ordering::Relaxed) + WINDOW_CARD_BYTES.load(Ordering::Relaxed); + out[8] = CARD_BYTES[0].load(Ordering::Relaxed) + + WINDOW_CARD_BYTES.load(Ordering::Relaxed) + + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed); out[9] = CARD_BYTES[1].load(Ordering::Relaxed); out } @@ -447,6 +451,49 @@ fn window_card_for(size: u64) -> Option { Some(buffer) } +/// The most bytes of windows outside buffers that lie in the card's memory +/// and are filled by the CPU through the bus (`VICTORY_WINDOWS_BAR_MB`; 0, the +/// default, none): one buffer (`D3D12_HEAP_TYPE_GPU_UPLOAD`), no CPU's side, no +/// copy to send and no list of changes, unlike [`window_card_most`]. The CPU +/// only writes them, as no shader is declared to write a window; if one were, +/// its snapshot and compare would read through the bus, right but slow. +/// +/// Windows go there while a fifth of the card's budget is free, as with +/// [`window_room_for`], which this comes before. +fn window_mapped_most() -> u64 { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_WINDOWS_BAR_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0) << 20 + }) +} + +/// Bytes alive of windows in card memory the CPU maps. +static WINDOW_MAPPED_BYTES: AtomicU64 = AtomicU64::new(0); + +/// A buffer for a window of `size` bytes in card memory the CPU maps, if it is +/// to be there ([`window_mapped_most`]). +fn window_mapped_for(size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let most = window_mapped_most(); + if most == 0 { + return None; + } + let host = host()?; + if let Some([budget, used, ..]) = host.video_memory() + && used + size > budget / 10 * 8 + { + return None; + } + if WINDOW_MAPPED_BYTES.fetch_add(size, Ordering::Relaxed) + size > most { + WINDOW_MAPPED_BYTES.fetch_sub(size, Ordering::Relaxed); + return None; + } + let made = host.mapped_card_buffer(size, true); + if made.is_none() { + WINDOW_MAPPED_BYTES.fetch_sub(size, Ordering::Relaxed); + } + made +} + /// Whether windows outside buffers have two sides too, so that submissions /// in the air read the bytes they were prepared with (`VICTORY_WINDOWS_OWN=1`; /// off by default: it takes the windows' bytes again, 3.3 GB in capture @@ -2247,6 +2294,9 @@ impl Drop for Shadow { KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed); } let window = self.window; + if self.mapped { + WINDOW_MAPPED_BYTES.fetch_sub(self.len, Ordering::Relaxed); + } if let Some(card) = &mut self.card { if window { WINDOW_CARD_BYTES.fetch_sub(card.size, Ordering::Relaxed); @@ -2631,6 +2681,7 @@ impl Shadow { }, card: None, window: false, + mapped: false, place: None, } } @@ -4602,6 +4653,19 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) | | `--no-restore` | leaves what a loop changed | +| `--pace ` | a wait after each submission sent: the card stands idle between them, as in a game that prepares the next one | +| `--breadcrumbs` | the system's breadcrumbs (`VICTORY_D3D12_DRED=light`) | | `--debug-layer` | D3D12's debug layer; its errors in the report | Use the median of several loops; the first is slower. An experiment that From 7130d521d76830e7e2de32b23e6752e487cb6a70 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:35:14 -0600 Subject: [PATCH 312/445] Bakes take what is due now first; textures that change unnoticed are looked at each frame; placed textures over unlike targets said VICTORY_RECHECK_SOON=0: after four frames, as before. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 36 +++++++++++++++++++++++------- crates/victory-gpu/src/resource.rs | 24 ++++++++++++++++++++ 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e7a474a..3798135 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -110,6 +110,14 @@ fn bake_exact() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_BAKE_EXACT").is_none_or(|v| v != "0")) } +/// Whether a texture found changed with nothing to tell of it is looked at +/// again in the next frame (`VICTORY_RECHECK_SOON=0`: after four, as +/// before). +fn recheck_soon() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_RECHECK_SOON").is_none_or(|v| v != "0")) +} + /// Frames ahead the pass before a bake takes slots from that are due only /// then ([`bake_exact`]): those of notices (1 and 2), and the first looks /// again ([`RECHECK_FRAMES`]). @@ -2005,11 +2013,14 @@ impl State { host.texture_slots_waiting(frame); } let baking = crate::texture::BAKING.get(); - let (due, census) = if baking { - host.texture_slots_due(frame + BAKE_AHEAD, 1 << 16) - } else { - host.texture_slots_due(frame, 4096) - }; + let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 }); + // (Those that are due later after all that are due.) + let on_time = due.len(); + if baking { + let known: std::collections::HashSet = due.iter().map(|&(index, _)| index).collect(); + let (ahead, _) = host.texture_slots_due(frame + BAKE_AHEAD, 1 << 16); + due.extend(ahead.into_iter().filter(|(index, _)| !known.contains(index))); + } HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed); for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) { count.store(now, Ordering::Relaxed); @@ -2052,7 +2063,7 @@ impl State { // drains; `VICTORY_TEXTURE_CATCHUP=0` keeps the plain budget. static CATCHUP: std::sync::OnceLock = std::sync::OnceLock::new(); let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0")); - let (per_frame, span) = if catchup && due.len() >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) }; + let (per_frame, span) = if catchup && on_time >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) }; // A run made early (`State::early_textures`) has a budget of its // own: its bytes on top of what the frame has spent so far. // (Not `most`: that is the longest wait between looks, used below.) @@ -2086,6 +2097,12 @@ impl State { // first look for the rest of the run. The look reads 48 KiB; // only a changed texture is uploaded again. // `VICTORY_HEAP_RECHECK=0`: uploaded once, as before. + // One found changed by such a look is looked at in the next frame + // again: the textures left that change unnoticed are ones the + // title paints all the time through another view of their pages + // (all their blocks are shown at other addresses too), and each + // was shown four frames late, over and over. + let mut again_in = RECHECK_FRAMES[0]; if let Some((at, len, print, looks, uploaded)) = host.texture_slot_checked(index) { if crate::texture::fingerprint(at, len) == print { HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed); @@ -2097,6 +2114,9 @@ impl State { } continue; } + if recheck_soon() { + again_in = 1; + } let n = HEAP_TEXTURES_RECHECKED[1].fetch_add(1, Ordering::Relaxed); if n < 200 || n.is_multiple_of(1000) { // Whether its pages are the title's at other addresses @@ -2239,7 +2259,7 @@ impl State { match memory { Some((at, len)) => { let print = crate::texture::fingerprint(at, len); - host.texture_slot_recheck(index, write, frame + RECHECK_FRAMES[0], (at, len), print, 0, frame); + host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame); } None => host.texture_slot_done(index, write, again), } @@ -2306,7 +2326,7 @@ impl State { // Whole and uploaded: looked at again (see above). Some((at, len)) => { let print = crate::texture::fingerprint(at, len); - host.texture_slot_recheck(index, write, frame + RECHECK_FRAMES[0], (at, len), print, 0, frame); + host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame); } None => host.texture_slot_done(index, write, again), } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index dc3de0d..d207e40 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1430,6 +1430,30 @@ pub(crate) fn alias_of(this: This) -> Option { && o.desc.flags & DEPTH == 0 && target_format(o.desc.format) == o.desc.format && element(o.desc.format).is_some_and(|e| e.1 == 1 && Some(e) == element(r.desc.format)); + if !same && r.desc.sample_count <= 1 { + // What shaders wrote there is on the card in the other texture; this + // one is filled from title memory, which they never reached. Each + // kind of pair is said once. + static SAID: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); + let pair = [ + r.desc.width as u32, + r.desc.height, + r.desc.format, + o.desc.width as u32, + o.desc.height, + o.desc.format, + ]; + let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); + if said.len() < 64 && said.insert(pair) { + tracing::warn!( + view = ?this, + texture = ?other, + "a placed texture lies where a texture the host writes does, and is not like it (width, height, format of each): {pair:?}, levels {} and {}, layers {} and {}", + r.desc.mip_levels, o.desc.mip_levels, r.desc.depth_or_array_size, o.desc.depth_or_array_size + ); + } + } same.then_some(other) } From 3e64a646efe582d0a86057153649343a8423ec6e Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:50:03 -0600 Subject: [PATCH 313/445] Card steps: the plan joins its ranges once a round, each place is looked up once One by one, every fill of the 2,800 a frame sorted the ranges again: the unmeasured 16 ms before a submission's preparing (profile cpu-1). Up to 12,288 steps a submission. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host/card_steps.rs | 94 ++++++++++++++++------- 1 file changed, 67 insertions(+), 27 deletions(-) diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 881d1b2..808fa7c 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -88,7 +88,7 @@ pub(super) fn stage() -> u32 { const BETWEEN: u64 = 4 << 20; /// The most steps of a submission done this way. -const MOST: usize = 4096; +const MOST: usize = 12288; /// How a fill's bytes get where its list reads them, if the card brings /// them. @@ -247,6 +247,9 @@ fn plan(does: &[Does], stage: u32) -> Result, &'static str> { } } while !more.is_empty() { + // (Joined once for the round: one by one the 2,800 fills of a frame + // sorted the ranges each time, 16 ms of the submitting thread.) + let (mut reads, mut writes) = (Vec::new(), Vec::new()); for i in std::mem::take(&mut more) { takes(&does[i])?; taken[i] = true; @@ -254,10 +257,14 @@ fn plan(does: &[Does], stage: u32) -> Result, &'static str> { if w.0 < w.1 && meet(r, w) { return Err("a copy onto itself"); } - join_ranges(&mut read, [r]); - join_ranges(&mut written, [w]); + reads.push(r); + writes.push(w); } } + join_ranges(&mut read, reads); + if writes.iter().any(|w| w.0 < w.1) { + join_ranges(&mut written, writes); + } if taken.iter().filter(|t| **t).count() > MOST { return Err("too many steps depend on it"); } @@ -288,7 +295,9 @@ fn plan(does: &[Does], stage: u32) -> Result, &'static str> { let mut behind: Vec<(usize, usize)> = Vec::new(); for (i, d) in does.iter().enumerate() { if taken[i] { - if let Some((_, w)) = reads_writes(d) { + if let Some((_, w)) = reads_writes(d) + && w.0 < w.1 + { join_ranges(&mut behind, [w]); } continue; @@ -368,9 +377,25 @@ fn holder(writers: &[Writer], from: usize, to: usize) -> Result, &'s /// Whether every page of `[from, to)` can be read (through the kernel: /// asking Windows walks the page tables, milliseconds in the title's heap). -fn mapped(from: usize, to: usize) -> bool { - let mut bytes = vec![0u8; to - from]; - read_into(from as *const u8, &mut bytes) +/// `room`: for what is read. +fn mapped(from: usize, to: usize, room: &mut Vec) -> bool { + if room.len() < to - from { + room.resize(to - from, 0); + } + read_into(from as *const u8, &mut room[..to - from]) +} + +/// A table by addresses and numbers of ours. +type HashMap = std::collections::HashMap>; + +/// Where the bytes of the fill that is `step` (its list by address, its place +/// in it) go. +fn fill_to(runs: &[&HostList], step: (usize, usize)) -> Option { + let list = runs.iter().find(|l| std::ptr::from_ref::(l) as usize == step.0)?; + match list.deferred().copies.get(step.1)? { + Step::Fill(_, _, _, to) => to.clone(), + _ => None, + } } /// A step done on the card. @@ -475,7 +500,7 @@ static DONE: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::Ato /// list by address, their place in it). pub(super) struct Taken { own: Own, - steps: std::collections::HashSet<(usize, usize)>, + steps: std::collections::HashSet<(usize, usize), std::hash::BuildHasherDefault>, copied: Vec<(Arc, usize, usize)>, } @@ -543,8 +568,6 @@ impl Host { fn take_steps(&self, written: &[(usize, usize)], runs: &[&HostList]) -> Result, &'static str> { let mut does = Vec::new(); - // Where the fills' bytes go. - let mut fills = std::collections::HashMap::new(); // Which step each is. One list's lock at a time: a submission may // name a list twice. let mut steps = Vec::new(); @@ -561,12 +584,7 @@ impl Host { src: *src, len: *len, asked: read_blocked(written, *src, *len), - to: { - if let Some(to) = to { - fills.insert(does.len(), to.clone()); - } - to.is_some() - }, + to: to.is_some(), }, Step::Texture(staging) => { let (at, len) = staging.memory(); @@ -605,7 +623,11 @@ impl Host { let mut ops: Vec = Vec::with_capacity(chosen.len()); // The places read (host copy, address, bytes, level): where in the // buffer between their bytes are. - let mut places = std::collections::HashMap::new(); + let mut places: HashMap<(usize, usize, usize, u32), u64> = HashMap::default(); + // Some 2,800 fills a frame, of a few hundred places: what holds each + // is looked for once, as long as no copy is added to the writers. + let mut held: HashMap<(usize, usize), Arc> = HashMap::default(); + let mut room = Vec::new(); let mut end = 0u64; for &(i, level) in &chosen { let Some(((src, _), (dst, _))) = reads_writes(&does[i]) else { @@ -617,7 +639,14 @@ impl Host { if len == 0 { return Err("nothing to read"); } - let from = holder(&writers, src, src + len)?; + let from = match held.get(&(src, len)) { + Some(from) => from.clone(), + None => { + let from = holder(&writers, src, src + len)?; + held.insert((src, len), from.clone()); + from + } + }; let place = (Arc::as_ptr(&from) as usize, src, len, level); let at = match places.get(&place) { Some(&at) => at, @@ -625,7 +654,7 @@ impl Host { if end + len as u64 > BETWEEN { return Err("too much at once"); } - if !mapped(src, src + len) { + if !mapped(src, src + len, &mut room) { return Err("not all of what it reads is mapped"); } let at = end; @@ -640,7 +669,7 @@ impl Host { if elsewhere(&does, Arc::as_ptr(&to) as usize, dst, dst + len) { return Err("another host copy of what it writes is read"); } - if !mapped(dst, dst + len) { + if !mapped(dst, dst + len, &mut room) { return Err("not all of what it writes is mapped"); } // What the steps behind it read of it is in that host @@ -651,11 +680,12 @@ impl Host { to: dst + len, copy: true, }); + held.clear(); To::Copy(to, dst) } - _ => match fills.get(&i) { - Some(FillTo::Slot(heap, index)) => To::Slot(*heap, *index), - Some(FillTo::Buffer(buffer)) => To::Buffer(buffer.clone()), + _ => match fill_to(runs, steps[i]) { + Some(FillTo::Slot(heap, index)) => To::Slot(heap, index), + Some(FillTo::Buffer(buffer)) => To::Buffer(buffer), None => continue, }, }; @@ -671,13 +701,23 @@ impl Host { return Err("no host list or buffer for it"); }; // First every refresh, then the writes: the bytes compared with are - // the title's. + // the title's. (One step for each host copy, over all that is read of + // it: a flush brings a copy up to date from the first range asked for + // to the last, whatever the steps.) + let mut spans: ByCopy<(Arc, usize, usize)> = ByCopy::default(); for op in &ops { - op.from.0.refresh(&own.list, op.from.1 as u64, op.len as u64); - if let To::Copy(to, dst) = &op.to { - to.refresh(&own.list, *dst as u64, op.len as u64); + let to = match &op.to { + To::Copy(to, dst) => Some((to, *dst)), + _ => None, + }; + for (shadow, at) in std::iter::once((&op.from.0, op.from.1)).chain(to) { + let span = spans.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| (shadow.clone(), at, at + op.len)); + (span.1, span.2) = (span.1.min(at), span.2.max(at + op.len)); } } + for (shadow, from, to) in spans.into_values() { + shadow.refresh(&own.list, from as u64, (to - from) as u64); + } let mut copied = Vec::new(); for op in &ops { if let To::Copy(to, dst) = &op.to { From 40580d778ce8578bdc5eee26594afffdf31320d8 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:50:03 -0600 Subject: [PATCH 314/445] The title's bytes under flights' writes go up by whole words (VICTORY_UNDER_WORDS=0: by bytes) Words are pairs of one dispatch and are not counted against the 4,096 copies a submission sends up, at which it stood until the flights had landed. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 1 + crates/victory-gpu/src/host/send.rs | 32 ++++++++++++++++++++++++++++- crates/victory-gpu/src/shadow.rs | 10 +++++++-- 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index e24be3b..2373a17 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3161,6 +3161,7 @@ mod torn; pub(crate) mod upcheck; #[cfg(test)] +pub(crate) use send::{goes_as_words, words_under}; mod late_tests { use super::{continues, join_ranges, touches}; diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs index 9227399..1373481 100644 --- a/crates/victory-gpu/src/host/send.rs +++ b/crates/victory-gpu/src/host/send.rs @@ -30,6 +30,36 @@ pub(super) fn own() -> bool { /// Runs up to this many bytes go as pairs. const SHORT: usize = 256; +/// Whether a run of `len` bytes at offset `at` of a copy goes as pairs. +fn short(at: usize, len: usize) -> bool { + len <= SHORT && at % 4 == 0 && len % 4 == 0 +} + +/// Whether a run of `len` bytes at offset `at` of a copy in the card's memory +/// is no copy command of its own, but pairs of one dispatch. +pub(crate) fn goes_as_words(at: usize, len: usize) -> bool { + own() && short(at, len) +} + +/// Whether the title's bytes that go in under flights' writes +/// (`Shadow::merge_under_writes`) go in by whole words +/// (`VICTORY_UNDER_WORDS=0`: by the bytes that changed, as before). +/// +/// By bytes nearly every run (a float's three low bytes) was a copy command +/// of its own, and a submission with more than 4,096 of them stood until the +/// flights had landed: 4 to 14 ms of a steady frame (session play-1125-0203: +/// "more changed runs than a submission sends up"), for some 20 KB. Whole +/// words are pairs of one dispatch, and are not counted. +/// +/// A word is taken to be the title's or the shaders', not shared: where the +/// title changed a byte of a word of which a flight's shader writes another +/// byte, that byte is as it was before the flight. The landing rests on the +/// same ([`crate::shadow::exact_back`]). +pub(crate) fn words_under() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| own() && std::env::var_os("VICTORY_UNDER_WORDS").is_none_or(|v| v != "0")) +} + const SCATTER: &str = r#" #define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0)" cbuffer Part : register(b0) { uint at; uint count; }; @@ -142,7 +172,7 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc, Vec<(usize, us pass(host)?; // Runs of whole words of the copy: only those are pairs. (A byte beside // them in a word may be the card's.) - let short = |&(a, b): &(usize, usize)| b - a <= SHORT && a % 4 == 0 && b % 4 == 0; + let short = |&(a, b): &(usize, usize)| short(a, b - a); let mut at = 0u64; let mut copies = Vec::with_capacity(dirty.len()); for (_, ranges) in dirty { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 8b127df..72d4315 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -3198,8 +3198,12 @@ impl Shadow { // 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) }; - let runs = changed_runs(title, held); - if runs.len() > *runs_left { + // 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; } @@ -3229,6 +3233,8 @@ impl Shadow { // 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(runs.len() as u64, Ordering::Relaxed); + self.card_changed_runs(runs.into_iter().map(|(r, m)| (at + r, at + r + m))); MERGED[1].fetch_add(1, Ordering::Relaxed); MERGED[2].fetch_add(m as u64, Ordering::Relaxed); } From 52e0c03f56bdf1ee1c629ddb57ce4e514c52a632 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:50:04 -0600 Subject: [PATCH 315/445] Snapshot memory, host lists and send memory kept for reuse (VICTORY_SNAPSHOT_POOL=8: as before) Made anew and given back all the time: 30 % of the submitting thread in the opening (profile cpu-1: allocations of snapshots 11, preludes 12, lists dropped 5, send memory 3). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host/send.rs | 4 ++- crates/victory-gpu/src/list.rs | 7 +++-- crates/victory-gpu/src/shadow.rs | 46 ++++++++++++++++++++--------- 3 files changed, 40 insertions(+), 17 deletions(-) diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs index 1373481..1962988 100644 --- a/crates/victory-gpu/src/host/send.rs +++ b/crates/victory-gpu/src/host/send.rs @@ -129,7 +129,9 @@ fn memory(host: &Host, size: u64) -> Option { return Some(spare.swap_remove(i)); } } - let size = size.next_multiple_of(8 << 20); + // By doubles, so that the next of about this size finds it: what + // submissions send differs from frame to frame. + let size = size.max(8 << 20).next_power_of_two(); let (buffer, data) = host.upload_buffer(size)?; name(&buffer, || "bytes a submission sends up".into()); Some(Memory { diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 140b755..a919fb5 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -218,11 +218,14 @@ unsafe impl Send for Idle {} #[cfg(windows)] static IDLE: std::sync::Mutex<(Vec, u64)> = std::sync::Mutex::new((Vec::new(), 0)); -/// The most host lists kept idle, and the most upload memory they may keep +/// The most host lists kept idle (128 were too few: flights land several at +/// a time, so lists were thrown away and others made in the same frame, with +/// their preludes and buffers, 12 % of the submitting thread in the opening, +/// profile cpu-1), and the most upload memory they may keep /// between them (a list keeps scratch chunks over a reset only while lists /// do not share them, `VICTORY_SCRATCH_POOL=0`). #[cfg(windows)] -const IDLE_MOST: (usize, u64) = (128, 256 << 20); +const IDLE_MOST: (usize, u64) = (512, 256 << 20); /// Whether host lists that have run are used again (on by default; /// `VICTORY_LIST_POOL=0`: each is made new and thrown away, as before). diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 72d4315..b140a27 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1197,20 +1197,40 @@ fn pooled(n: usize) -> Vec { v } -/// Returns a snapshot buffer to the pool: at most 8 kept, the largest, and -/// of those the largest one and the next ones up to `KEPT` bytes in all. +/// How many snapshot buffers are kept (`VICTORY_SNAPSHOT_POOL`; `8`: as +/// before). +/// +/// A frame gives some 330 ranges of copies in the PC's memory to shaders, and +/// most are of copies of their own; with two or three frames in the air eight +/// buffers were the eight largest, and every other snapshot was memory fresh +/// from the kernel and given back to it: 11 % of the submitting thread in the +/// opening (profile cpu-1: `NtAllocateVirtualMemory` under +/// [`Shadow::writing`]), and the page faults of filling it. +fn snapshots_kept() -> usize { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| std::env::var("VICTORY_SNAPSHOT_POOL").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1024)) +} + +/// Returns a snapshot buffer to the pool: at most [`snapshots_kept`] kept, +/// the largest, and of those the largest one and the next ones up to `KEPT` +/// bytes in all. fn give_back(v: Vec) { const KEPT: usize = 512 << 20; let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); pool.push(v); pool.sort_by_key(|v| std::cmp::Reverse(v.capacity())); - pool.truncate(8); - let (mut seen, mut total) = (0, 0usize); - pool.retain(|v| { - seen += 1; + let (mut kept, mut total) = (0, 0usize); + for v in pool.iter().take(snapshots_kept()) { total = total.saturating_add(v.capacity()); - seen == 1 || total <= KEPT - }); + if kept > 0 && total > KEPT { + break; + } + kept += 1; + } + // (Given back to the kernel without the lock: milliseconds.) + let gone = pool.split_off(kept); + drop(pool); + drop(gone); } const NOT_WATCHED: u8 = 2; @@ -3207,14 +3227,14 @@ impl Shadow { note_stale(2); return true; } - *runs_left -= runs.len(); + *runs_left -= copies; let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec()); - for (r, m) in runs { + for &(r, m) in &runs { held[r..r + m].copy_from_slice(&title[r..r + m]); - self.card_changed(at + r, at + r + m); - MERGED[1].fetch_add(1, Ordering::Relaxed); 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); } @@ -3233,8 +3253,6 @@ impl Shadow { // 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(runs.len() as u64, Ordering::Relaxed); - self.card_changed_runs(runs.into_iter().map(|(r, m)| (at + r, at + r + m))); MERGED[1].fetch_add(1, Ordering::Relaxed); MERGED[2].fetch_add(m as u64, Ordering::Relaxed); } From 53c5256b687f02690586800273063567206298cb Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:50:04 -0600 Subject: [PATCH 316/445] The heaps' records are brought up to date beside the preparing (VICTORY_HEAP_SYNC_ASIDE=0); a made slot is told without the lock (VICTORY_QUICK_MIRROR=0) Changed pages are compared sixteen records at a time. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 114 ++++++++++++++++++++-- crates/victory-gpu/src/descriptor/host.rs | 96 ++++++++++++++++-- crates/victory-gpu/src/host.rs | 11 ++- 3 files changed, 201 insertions(+), 20 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 39e8b68..043dd26 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -161,6 +161,96 @@ fn mirror(handle: u64) { } } +/// Whether [`sync_heaps`] is done (`VICTORY_HEAP_SYNC=0`: not). +#[cfg(windows)] +fn sync_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC").is_none_or(|v| v != "0")) +} + +/// Whether a submission's [`sync_heaps`] is done by a thread of its own +/// beside the rest of the preparing (`VICTORY_HEAP_SYNC_ASIDE=0`: in front of +/// it, as before). +/// +/// It took 13 ms a frame of the submitting thread (session play-1125-0203: +/// 230 changed heap pages and 470,000 slots in 30 submissions). What it makes +/// are the host heap's descriptors, which the card reads: it has to be done +/// before the lists go to the queue, and nothing of the preparing looks at +/// them (what a draw reads through a table it made itself, when recorded). +#[cfg(windows)] +fn sync_aside() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| sync_on() && std::env::var_os("VICTORY_HEAP_SYNC_ASIDE").is_none_or(|v| v != "0")) +} + +/// The thread's work: rounds asked for, rounds done. +#[cfg(windows)] +static SYNC_ROUNDS: (std::sync::Mutex<(u64, u64)>, std::sync::Condvar) = (std::sync::Mutex::new((0, 0)), std::sync::Condvar::new()); + +/// [`sync_heaps`], begun; done when it is dropped (with [`sync_aside`]), or +/// when this returns. +#[cfg(windows)] +pub(crate) struct SyncedHeaps(Option); + +#[cfg(windows)] +pub(crate) fn begin_sync_heaps() -> SyncedHeaps { + if !sync_aside() { + sync_heaps(); + return SyncedHeaps(None); + } + static STARTED: std::sync::Once = std::sync::Once::new(); + static THREAD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + STARTED.call_once(|| { + let made = std::thread::Builder::new().name("victory-heap-sync".into()).spawn(|| { + let rounds = || SYNC_ROUNDS.0.lock().unwrap_or_else(|e| e.into_inner()); + /// A round is over, however it ends. + struct Over; + impl Drop for Over { + fn drop(&mut self) { + SYNC_ROUNDS.0.lock().unwrap_or_else(|e| e.into_inner()).1 += 1; + SYNC_ROUNDS.1.notify_all(); + } + } + loop { + let mut r = rounds(); + while r.0 == r.1 { + r = SYNC_ROUNDS.1.wait(r).unwrap_or_else(|e| e.into_inner()); + } + drop(r); + let _over = Over; + let _ = std::panic::catch_unwind(sync_heaps); + } + }); + THREAD.store(made.is_ok(), std::sync::atomic::Ordering::Release); + }); + if !THREAD.load(std::sync::atomic::Ordering::Acquire) { + sync_heaps(); + return SyncedHeaps(None); + } + let mut rounds = SYNC_ROUNDS.0.lock().unwrap_or_else(|e| e.into_inner()); + rounds.0 += 1; + let mine = rounds.0; + drop(rounds); + SYNC_ROUNDS.1.notify_all(); + SyncedHeaps(Some(mine)) +} + +#[cfg(windows)] +impl Drop for SyncedHeaps { + fn drop(&mut self) { + let Some(mine) = self.0 else { + return; + }; + let began = std::time::Instant::now(); + let mut rounds = SYNC_ROUNDS.0.lock().unwrap_or_else(|e| e.into_inner()); + while rounds.1 < mine { + rounds = SYNC_ROUNDS.1.wait(rounds).unwrap_or_else(|e| e.into_inner()); + } + drop(rounds); + SYNCED[6].fetch_add(began.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + } +} + /// Mirrors records copied directly into placed shader-visible heaps. Calls /// to `Create*View` are already mirrored by [`mirror`]; raw CPU copies leave /// only write-watch pages to reveal which slots changed. @@ -173,8 +263,7 @@ fn mirror(handle: u64) { #[cfg(windows)] pub(crate) fn sync_heaps() { use std::sync::atomic::Ordering::Relaxed; - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC").is_none_or(|v| v != "0")) { + if !sync_on() { return; } let started = std::time::Instant::now(); @@ -278,28 +367,30 @@ pub(crate) fn sync_heaps() { /// 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 /// new records left to the draws that read them through a table, and new -/// records that waited for one ([`host::HostHeap::copied_wait`]). +/// records that waited for one ([`host::HostHeap::copied_wait`]); and the +/// microseconds submissions waited for it ([`sync_aside`]). #[cfg(windows)] -pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; +pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 7] = [const { std::sync::atomic::AtomicU64::new(0) }; 7]; /// With the frame line: what [`sync_heaps`] did per frame over `frames`. /// Nothing while no heap page changed. #[cfg(windows)] pub(crate) fn sync_line(frames: f64) { - let [pages, looked, mirrored, micros, tabled, later] = [0, 1, 2, 3, 4, 5].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + 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)); 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", + draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms ({:.2} ms waited for)", 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 + micros as f64 / 1000.0 / frames, + waited as f64 / 1000.0 / frames ); } @@ -320,6 +411,15 @@ fn changed_slots( first.min(last)..last } +/// `f` of the title heap at `heap`, if that heap still exists; it stays +/// until `f` is done. +#[cfg(windows)] +pub(crate) fn with_heap(heap: usize, f: impl FnOnce(&Heap) -> T) -> Option { + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); + // SAFETY: registered heaps are live (removed when dropped). + heaps.iter().any(|&(_, _, h)| h == heap).then(|| f(unsafe { &*(heap as *const Heap) })) +} + /// Gives back dynamic slots of the host heap behind the title heap at /// `heap`, if that heap still exists. #[cfg(windows)] diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 5aac724..8418b21 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -26,6 +26,9 @@ pub(crate) struct HostHeap { sampler: bool, /// The record (view index and generation) each slot was last made from. made: Mutex>, + /// 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, /// The records of the title's heap as the pass over records copied in /// as bytes last saw them ([`HostHeap::copied_changes`]). Made on first /// use. @@ -1070,6 +1073,7 @@ impl HostHeap { dynamic: extra, sampler, made: Mutex::new(vec![0; count as usize]), + quick: (0..count).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(), copied: Mutex::new(Vec::new()), waiting: Mutex::default(), away: Mutex::default(), @@ -1606,6 +1610,7 @@ 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) { + self.quick_is(index, 0); let Some(key) = made.get_mut(index as usize).map(std::mem::take) else { return; }; @@ -2019,15 +2024,7 @@ impl HostHeap { return; }; let records = &records[..last.len()]; - if last == records { - return; - } - for (n, (old, new)) in last.chunks_exact_mut(step).zip(records.chunks_exact(step)).enumerate() { - if old != new { - old.copy_from_slice(new); - out.push(first + n as u32); - } - } + changed_records(last, records, step, first, out); } /// Whether new records of draws' tables are left to the draws @@ -2099,12 +2096,24 @@ impl HostHeap { let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; // Generations start at 1, so a made slot's key is never 0. let key = u64::from(generation) << 32 | u64::from(i); + // Made from this record, and nothing has changed it: most of the + // asks, from five recording threads, behind one lock while another + // held it to make a descriptor (15 % of a recording thread's time in + // the opening, profile cpu-1). + if tag == VIEW_TAG + && quick_mirror() + && self.quick.get(index as usize).is_some_and(|k| k.load(std::sync::atomic::Ordering::Acquire) == key) + && let Some(view) = view_at(i, generation) + { + return Some(view); + } let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); 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 { + self.quick_is(index, 0); made[index as usize] = 0; self.make_null(index); let _ = self.note_buffer(index, None, false); @@ -2147,6 +2156,7 @@ impl HostHeap { KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); return Some(view); } + self.quick_is(index, 0); made[index as usize] = if later { 0 } else { key }; let kept = if later { None @@ -2157,10 +2167,19 @@ impl HostHeap { null_for(&view, self.cpu(index)); } self.keep(index, kept.flatten()); + self.quick_is(index, made[index as usize]); } Some(view) } + /// Slot `index` is made from record `key` and stays so (0: not). Under + /// the lock of `made`. + fn quick_is(&self, index: u32, key: u64) { + if let Some(quick) = self.quick.get(index as usize) { + quick.store(key, std::sync::atomic::Ordering::Release); + } + } + /// Whether slot `index` is backed by a made host descriptor (tests). #[cfg(test)] pub(crate) fn made(&self, index: u32) -> bool { @@ -2987,6 +3006,65 @@ fn keep_views() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0")) } +/// 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 { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_QUICK_MIRROR").is_none_or(|v| v != "0")) +} + +/// The records (`step` bytes each, the first is slot `first`) that differ +/// between `last` and `records` (of one length) go into `out` and `last`. +/// Most of a changed page is as it was: it is looked at sixteen records at a +/// time. +fn changed_records(last: &mut [u8], records: &[u8], step: usize, first: u32, out: &mut Vec) { + const AT_A_TIME: usize = 16; + let block = AT_A_TIME * step; + for (b, (old, new)) in last.chunks_mut(block).zip(records.chunks(block)).enumerate() { + if old == new { + continue; + } + for (n, (old, new)) in old.chunks_exact_mut(step).zip(new.chunks_exact(step)).enumerate() { + if old != new { + old.copy_from_slice(new); + out.push(first + (b * AT_A_TIME + n) as u32); + } + } + } +} + +#[cfg(test)] +mod changed_records_tests { + use super::changed_records; + + #[test] + fn changed_records_are_those_that_differ_one_by_one() { + for (step, count) in [(32usize, 128usize), (32, 2048), (16, 77), (32, 5), (32, 17)] { + let mut seed = 7u64; + let mut random = move || { + seed = seed.wrapping_mul(0x5851_F42D_4C95_7F2D).wrapping_add(0x1405_7B7E_F767_814F); + (seed >> 33) as usize + }; + let mut last: Vec = (0..step * count).map(|_| random() as u8).collect(); + let mut now = last.clone(); + let mut differ = Vec::new(); + for slot in 0..count { + if random() % 9 == 0 { + now[slot * step + random() % step] ^= 1 + (random() % 255) as u8; + differ.push(1000 + slot as u32); + } + } + let mut out = Vec::new(); + changed_records(&mut last, &now, step, 1000, &mut out); + assert_eq!(out, differ); + assert_eq!(last, now); + out.clear(); + changed_records(&mut last, &now, step, 1000, &mut out); + assert!(out.is_empty()); + } + } +} + /// Whether both are shader views of one texture the title placed in /// memory: the same address and the same resource description, whatever /// part of it each shows. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 2373a17..4dbda49 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4852,7 +4852,7 @@ impl Host { } // Descriptors the title copied into placed heaps directly, before // command lists that index those slots are submitted. - crate::descriptor::sync_heaps(); + let heaps_synced = crate::descriptor::begin_sync_heaps(); // That list runs first, and is one of the submission's from here on. let with: Vec<&HostList>; let runs = match &own { @@ -4885,9 +4885,6 @@ impl Host { SWEPT.store(now_ms(), Ordering::Relaxed); } let behind = late && flying(); - // The slots that waited for a texture's host copy, before the - // lists that may read them run. - crate::descriptor::make_waiting(); let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1; // The ranges shaders write are counted for it (with the relay). crate::shadow::preparing(this_submission); @@ -5019,6 +5016,12 @@ impl Host { split.part(5); let back = crate::picked::with(declared_writes(runs), &picked.written); let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); + drop(heaps_synced); + // The slots that waited for a texture's host copy, before the + // lists that may read them run. + crate::descriptor::make_waiting(); + #[cfg(feature = "diagnostics")] + split.part(15); SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed); submitting(0, 0); #[cfg(feature = "diagnostics")] From 1a411ae49b1680449fc4866a2b1d1a5652ec116e Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:50:04 -0600 Subject: [PATCH 317/445] A thread asks the write watch ahead of the submissions (VICTORY_ASK_EARLY); the time ahead of the preparing is split VICTORY_ASK_EARLY=0: no such thread. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 29 ++++++++- crates/victory-gpu/src/watch.rs | 112 ++++++++++++++++++++++++++++++++ 2 files changed, 138 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4dbda49..7283546 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4835,11 +4835,17 @@ impl Host { // what they write. // Or the reads are done on the card, behind the flights. let own = if late { self.card_steps(runs) } else { None }; + #[cfg(feature = "diagnostics")] + let ahead = Split::begin(); + #[cfg(feature = "diagnostics")] + SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed); if !late { self.settle(&mut submitted, WHY_SYNC); } else if own.is_none() && let Some(why) = late_blocked(runs) { + #[cfg(feature = "diagnostics")] + ahead.part(12); if relay_exact() && why == WHY_READ { // Only until the flights that may write what is read have // landed: their copy-back's end, not the card's other work. @@ -4855,6 +4861,8 @@ impl Host { let heaps_synced = crate::descriptor::begin_sync_heaps(); // That list runs first, and is one of the submission's from here on. let with: Vec<&HostList>; + #[cfg(feature = "diagnostics")] + ahead.part(13); let runs = match &own { Some(own) => { with = std::iter::once(own.list()).chain(runs.iter().copied()).collect(); @@ -4895,6 +4903,8 @@ impl Host { crate::copystat::add(crate::copystat::C::Submissions, 1); let mut lists: Vec> = Vec::with_capacity(2 * runs.len()); // Where each run's lists start in `lists`. + ahead.part(14); + #[cfg(feature = "diagnostics")] let mut firsts = Vec::with_capacity(runs.len()); let mut batch = Batch::default(); #[cfg(feature = "diagnostics")] @@ -6489,9 +6499,12 @@ impl std::hash::Hasher for AddressHash { /// of the steps: the refreshes, and the copies and fills (those with the /// refreshes a copy of title memory flushes). Of the asking, which ranges it /// is of. Of the refreshes, those before ranges are given to shaders, one -/// copy at a time: nanoseconds, and how many. +/// copy at a time: nanoseconds, and how many. Ahead of all that: the wait for +/// the submission lock, the steps done on the card planned ([`card_steps`]), +/// the flights waited for, the heaps' records and what is swept; and, at the +/// end, the wait for the heaps' records. #[cfg(feature = "diagnostics")] -static SPLIT: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11]; +static SPLIT: [std::sync::atomic::AtomicU64; 16] = [const { std::sync::atomic::AtomicU64::new(0) }; 16]; /// Since the last frame-rate line: flushes of refreshes, their refreshes, /// those known to copy nothing, and those done on several threads. @@ -6532,7 +6545,9 @@ fn split_line(frames: f64) { "preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \ writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \ several threads, {:.1} one at a time in {:.0} before shader writes; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \ - card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})", + card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {}); ahead of these {:.1} waiting for the submission lock, {:.1} \ + planning steps done on the card, {:.1} waiting for flights, {:.1} the heaps' records and what is swept; at the end {:.1} waiting \ + for the heaps' records; asked early by a thread of its own {:.0} pieces of 2 MiB, {:.1} ms (VICTORY_ASK_EARLY)", ms[0], ms[8], ms[1], @@ -6563,6 +6578,7 @@ fn split_line(frames: f64) { a[10], a[9], a[2], + let e: Vec = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect(); a[3], a[4], a[5], @@ -6587,6 +6603,13 @@ fn split_line(frames: f64) { /// /// A submission brings some sixty copies up to date, one after the other /// on the submitting thread: for each, the pages the title wrote are asked + ms[11], + ms[12], + ms[13], + ms[14], + ms[15], + e[0], + e[1] / 1e3, /// for and read through the kernel into the copy. That is the frame line's /// "copies", 45-50 ms a frame, and the copies have nothing to do with one /// another: each refresh writes its own copy and its own notes, and reads diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 9afcd11..38cfe92 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -239,6 +239,7 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { ask_run(&pieces[i..k], &mut asked, &mut written); i = k; } + note_hot(&written); let mut j = journal_mut(); j.ahead_asked = next_asking(); j.ahead = asked; @@ -271,6 +272,116 @@ pub(crate) fn slow_asks() -> [u64; 3] { [0, 1, 2].map(|i| SLOW[i].swap(0, std::sync::atomic::Ordering::Relaxed)) } +/// Whether a thread asks, between a submission's askings, about the memory +/// they found written (`VICTORY_ASK_EARLY=` between its rounds, 2 if not +/// given; `0`: no such thread). +/// +/// An asking's cost is the pages it finds written and resets, some 1.4 +/// microseconds each, and the title writes 7,000 a frame: the first +/// submission that refreshes its 174 MB heap stood 8 to 10 ms in one call +/// (session play-1125-0203). Asked a little at a time while the title +/// records, the same pages are in the journal when the submission comes, and +/// its own asking finds those written since. +/// +/// Nothing is seen later than before: a page goes into the journal as found +/// written by an asking of its own number, as from any thread that asks, and +/// the submission still asks for itself. A page the title writes again after +/// such a round faults once more. +fn early() -> Option { + static EVERY: std::sync::OnceLock> = std::sync::OnceLock::new(); + *EVERY.get_or_init(|| { + let ms = match std::env::var("VICTORY_ASK_EARLY") { + Ok(v) => v.trim().parse::().unwrap_or(2.0), + Err(_) => 2.0, + }; + std::time::Duration::try_from_secs_f64(ms / 1000.0).ok().filter(|d| !d.is_zero()) + }) +} + +/// The pieces of memory (by [`EARLY_PIECE`] pages) that submissions' askings +/// found written lately: how many pages each, halved every round of 64. +static HOT: Mutex> = Mutex::new(BTreeMap::new()); +/// The pieces asked in a round, at most. +const EARLY_MOST: usize = 24; +/// The pages of a piece: 2 MiB. +const EARLY_PIECE: usize = (2 << 20) / PAGE; +/// Told when a submission asked. +static HOT_MOVED: Condvar = Condvar::new(); + +/// Since the last frame line: pieces asked early, the microseconds of it. +static EARLY: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// [`EARLY`], taken. +#[cfg(feature = "diagnostics")] +pub(crate) fn early_asks() -> [u64; 2] { + [0, 1].map(|i| EARLY[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// A submission's asking found `written` (pages). +fn note_hot(written: &[usize]) { + let Some(every) = early() else { + return; + }; + let mut hot = HOT.lock().unwrap_or_else(|e| e.into_inner()); + for page in written { + let n = hot.entry(page / EARLY_PIECE).or_default(); + *n = (*n + 1).min(1 << 10); + } + HOT_MOVED.notify_one(); + drop(hot); + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("victory-ask-early".into()).spawn(move || ask_early(every)); + }); +} + +fn ask_early(every: std::time::Duration) { + use std::sync::atomic::Ordering::Relaxed; + // So many rounds without a submission's asking: wait for one. + const IDLE: u32 = 100; + let mut round = 0u32; + let mut idle = 0; + let mut last = 0u64; + loop { + std::thread::sleep(every); + let pieces: Vec = { + let mut hot = HOT.lock().unwrap_or_else(|e| e.into_inner()); + let now = ASKED.load(Relaxed); + idle = if now == last { idle + 1 } else { 0 }; + while idle > IDLE { + hot = HOT_MOVED.wait(hot).unwrap_or_else(|e| e.into_inner()); + idle = 0; + } + round += 1; + if round % 64 == 0 { + hot.retain(|_, n| { + *n /= 2; + *n > 0 + }); + } + // The most written: a piece with a few pages is as dear to ask as + // one with many. + let mut most: Vec<(u32, usize)> = hot.iter().filter(|h| *h.1 >= 16).map(|(&p, &n)| (n, p)).collect(); + most.sort_unstable_by(|a, b| b.cmp(a)); + most.into_iter().take(EARLY_MOST).map(|(_, p)| p).collect() + }; + let began = std::time::Instant::now(); + let mut asked = 0; + for piece in pieces { + // (A submission's asking stands: what it holds is answered from + // the journal, and costs nothing here.) + if published(piece * EARLY_PIECE * PAGE, (piece + 1) * EARLY_PIECE * PAGE) { + continue; + } + asked += 1; + let _ = writes(piece * EARLY_PIECE * PAGE, (piece + 1) * EARLY_PIECE * PAGE, false); + } + EARLY[0].fetch_add(asked, Relaxed); + EARLY[1].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + last = ASKED.load(Relaxed); + } +} + /// The submission's refreshes are done: `writes` asks the kernel again. pub(crate) fn ask_ahead_done() { let mut j = journal_mut(); @@ -341,6 +452,7 @@ fn ask_rest(ranges: &[(usize, usize)]) { ahead.push((first, last)); } } + note_hot(&written); let mut j = journal_mut(); // A number of its own, and the one this asking stands under: between // the two parts another thread may have asked about a range of the From aff4def0fba477b50b062f2d58b3e7ddd0caab73 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:50:05 -0600 Subject: [PATCH 318/445] A submission's fills of upload memory are done together on several threads (VICTORY_WIDE_FILLS=0: one by one) 5 ms of the submitting thread. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 53 ++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 7283546..cc96adf 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4973,6 +4973,7 @@ impl Host { #[cfg(feature = "diagnostics")] split.part(2); // The snapshots of the ranges shaders may write, if they were left + batch.fill(); // for now (`crate::shadow::wide_back`): the refreshes are done, the // lists have not gone to the card. { @@ -6395,6 +6396,7 @@ impl HostList { if let Some(bytes) = p.prepare(free) { batch.placed.push((p.shadow.clone(), p.dst, bytes)); } + batch.fill(); (started, p.len) } Step::Refresh(shadow, address, len) => { @@ -6411,12 +6413,19 @@ impl HostList { let started = std::time::Instant::now(); if matches!(step, Step::Run(_)) { batch.title_written(); + if wide_fills() { + batch.fills.push((dst, src, len)); + bytes += len as u64; + continue; + } + let started = std::time::Instant::now(); } work(); // It wrote title memory, where is not known here: the // submission's one asking ends, later refreshes ask anew. if matches!(step, Step::Run(_)) { crate::watch::ask_once_end(); + batch.fill(); } #[cfg(feature = "diagnostics")] { @@ -6435,6 +6444,7 @@ impl HostList { #[cfg(feature = "diagnostics")] let snapshot = std::time::Instant::now(); shadow.writing(*address, *len); + batch.fill(); #[cfg(feature = "diagnostics")] { add(C::GpuWrites, 1); @@ -6705,6 +6715,22 @@ impl Batch { (r.1, r.2) = (r.1.min(address), r.2.max(end)); } None => { + /// Fills not done yet (destination, source, bytes): [`wide_fills`]. + fills: Vec<(usize, usize, usize)>, +} + +/// Whether the fills of a submission's upload memory are done together on +/// several threads (`VICTORY_WIDE_FILLS=0`: one after the other, where the +/// lists name them). +/// +/// They are 7,000 to 12,000 a frame, some 500 bytes each, 5 ms of the +/// submitting thread. Each reads title memory and writes memory of its own +/// that the card alone reads, when the lists run; they are done before the +/// next step that writes title memory or runs code of ours, and before the +/// submission goes on from its steps. +fn wide_fills() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_FILLS").is_none_or(|v| v != "0") && wide_refresh()) self.index.insert(key, self.refreshes.len()); self.refreshes.push((shadow.clone(), address, end)); } @@ -6790,6 +6816,33 @@ impl Batch { FLUSHES[0].fetch_add(1, Ordering::Relaxed); FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed); } + /// The fills noted are done. + fn fill(&mut self) { + // Below this many the threads cost more than they save. + const FEW: usize = 96; + const PART: usize = 64; + if self.fills.is_empty() { + return; + } + let started = std::time::Instant::now(); + if self.fills.len() < FEW { + for (dst, src, len) in self.fills.drain(..) { + copy_mapped(dst as *mut u8, src as *const u8, len, false); + } + } else { + let fills = std::mem::take(&mut self.fills); + crate::shadow::wide_each(fills.len().div_ceil(PART), move |i| { + for &(dst, src, len) in fills.iter().skip(i * PART).take(PART) { + copy_mapped(dst as *mut u8, src as *const u8, len, false); + } + }); + } + let took = started.elapsed(); + PREPARING[0].fetch_add(took.as_micros() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + SPLIT[7].fetch_add(took.as_nanos() as u64, Ordering::Relaxed); + } + } fn flush_all(&mut self) { From f672130364375541f07483fb1b6e685d94417200 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:50:05 -0600 Subject: [PATCH 319/445] The pass over the heap's buffer views is made beside the recording (VICTORY_HEAP_PASS_ASIDE=0: in it) 12 to 17 ms of one recording thread at the frame's first list that needs it. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 305 +++++++++++++++------------ crates/victory-gpu/src/host.rs | 188 ++++++++++------- crates/victory-gpu/src/host/aside.rs | 98 +++++++++ 3 files changed, 372 insertions(+), 219 deletions(-) create mode 100644 crates/victory-gpu/src/host/aside.rs diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2b6f8a0..a15156c 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -678,6 +678,161 @@ fn set(roots: &mut Vec, slot: u32, root: Root) { roots[slot] = root; } +/// The pass over the buffer views of `heap` that shaders pick by index +/// ([`State::heap_buffers`]): their host slots are made, and the host copies +/// they show are to be refreshed. +fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::host::HostHeap, frame: u64) -> Vec { + let started = std::time::Instant::now(); + // Per host heap: the host copy and range each slot's buffer view + // reads, kept from pass to pass. Only the slots written since the + // last pass are looked at again (83,000 slots a pass otherwise, 0.1 s + // at best); all of them every 16 passes, because a view of a + // released resource goes stale without a write, and a slot written + // before its memory had a host copy is only made then. + type Ranges = HeapRanges>; + static RANGES: std::sync::Mutex>> = + std::sync::Mutex::new(None); + let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); + let (passes, ranges) = kept + .get_or_insert_with(Default::default) + .entry(std::ptr::from_ref(host) as usize) + .or_insert_with(|| (0, HeapRanges(Vec::new()))); + let changed = host.buffer_changes(); + let all = *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread()); + let slots = if all { + ranges.0.clear(); + host.buffer_slots() + } else if heap_spread() { + // The written ones, and this pass's part of the others. + let (part, parts) = ((*passes % HEAP_ROUND) as u32, HEAP_ROUND as u32); + ranges.forget_part(part, parts); + let mut slots = host.buffer_slots_of(part, parts); + slots.extend(changed); + slots + } else { + changed + }; + *passes += 1; + // 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 mut unordered = Vec::new(); + for (n, &index) in slots.iter().enumerate() { + ranges.set(index, None); + // 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(); + } + // 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; + }; + #[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)); + } + ranges.set(index, Some((shadow, address, address + len))); + } + if crate::picked::on() { + crate::picked::shown(unordered, all); + } + #[cfg(feature = "diagnostics")] + let looked = std::time::Instant::now(); + // Per host copy, the span its picked views cover. + let mut spans: crate::host::ByCopy<(std::sync::Arc, u64, u64)> = Default::default(); + let mut views = 0u32; + for (shadow, from, to) in ranges.ranges() { + views += 1; + let key = std::sync::Arc::as_ptr(shadow) as usize; + let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to)); + span.1 = span.1.min(*from); + span.2 = span.2.max(*to); + } + drop(kept); + let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum(); + // Memory that is not write-watched is copied whole by every refresh. + // It was once refreshed only every 120 frames (unmapped pages read + // one by one cost 14 GB a frame in run 11, before they were + // remembered): streamed geometry then drew from stale buffers, and + // the garbage ended runs (the card stopped answering 14-90 frames + // into the opening cutscene; with every frame it ran on). The pass + // costs some 30 ms a frame this way. + static WHOLE: std::sync::Mutex>> = std::sync::Mutex::new(None); + let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); + let whole = whole.get_or_insert_with(Default::default); + let mut found = Vec::with_capacity(spans.len()); + for (shadow, from, to) in spans.values() { + if shadow.unwatched() { + // By the copy's number: a copy made where one let go was + // (`shadow::let_go_idle`) has never been refreshed. + let key = shadow.id() as usize; + // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame). + static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); + let every = *EVERY.get_or_init(|| { + std::env::var("VICTORY_UNWATCHED_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1) + }); + match whole.get(&key) { + Some(&last) if frame < last + every => continue, + _ => { + whole.insert(key, frame); + } + } + } + found.push((shadow.clone(), *from, (*to).min(*from + shadow.left(*from)))); + } + #[cfg(feature = "diagnostics")] + let refreshed = std::time::Instant::now(); + crate::watch::look_at_holes(); + #[cfg(feature = "diagnostics")] + for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked]) { + sum.fetch_add(time.as_nanos() as u64, Ordering::Relaxed); + } + static LOGGED: AtomicU64 = AtomicU64::new(0); + // The first pass and every growth of the set by half. + let seen = LOGGED.load(Ordering::Relaxed); + if u64::from(views) > seen + seen / 2 { + LOGGED.store(u64::from(views), Ordering::Relaxed); + tracing::info!( + slots = slots.len(), + views, + copies = spans.len(), + mb = bytes >> 20, + ms = started.elapsed().as_millis(), + "buffer views of the heap made ready for shaders that pick them by index" + ); + } + found +} + impl State { pub(crate) fn reset(&mut self, pipeline: This) { *self = State::default(); @@ -1609,155 +1764,25 @@ impl State { return Some(gpu); } let started = std::time::Instant::now(); - // Per host heap: the host copy and range each slot's buffer view - // reads, kept from pass to pass. Only the slots written since the - // last pass are looked at again (83,000 slots a pass otherwise, 0.1 s - // at best); all of them every 16 passes, because a view of a - // released resource goes stale without a write, and a slot written - // before its memory had a host copy is only made then. - type Ranges = HeapRanges>; - static RANGES: std::sync::Mutex>> = - std::sync::Mutex::new(None); - let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); - let (passes, ranges) = kept - .get_or_insert_with(Default::default) - .entry(std::ptr::from_ref(host) as usize) - .or_insert_with(|| (0, HeapRanges(Vec::new()))); - let changed = host.buffer_changes(); - let all = *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread()); - let slots = if all { - ranges.0.clear(); - host.buffer_slots() - } else if heap_spread() { - // The written ones, and this pass's part of the others. - let (part, parts) = ((*passes % HEAP_ROUND) as u32, HEAP_ROUND as u32); - ranges.forget_part(part, parts); - let mut slots = host.buffer_slots_of(part, parts); - slots.extend(changed); - slots + if crate::host::aside::on() { + let at = std::ptr::from_ref(heap) as usize; + list.refreshes_coming(move || { + crate::descriptor::with_heap(at, |heap| heap.host().map(|host| heap_buffer_pass(heap, host, frame))) + .flatten() + .unwrap_or_default() + }); } else { - changed - }; - *passes += 1; - // 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 mut unordered = Vec::new(); - for (n, &index) in slots.iter().enumerate() { - ranges.set(index, None); - // A draw's table's: the draw brings what it reads up to date. - if host.copied_tabled(index, frame) { - continue; + for (shadow, from, to) in heap_buffer_pass(heap, host, frame) { + shadow.refresh(list, from, to - from); } - 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(); - } - // 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; - }; - #[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)); - } - ranges.set(index, Some((shadow, address, address + len))); - } - if crate::picked::on() { - crate::picked::shown(unordered, all); - } - #[cfg(feature = "diagnostics")] - let looked = std::time::Instant::now(); - // Per host copy, the span its picked views cover. - let mut spans: crate::host::ByCopy<(std::sync::Arc, u64, u64)> = Default::default(); - let mut views = 0u32; - for (shadow, from, to) in ranges.ranges() { - views += 1; - let key = std::sync::Arc::as_ptr(shadow) as usize; - let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to)); - span.1 = span.1.min(*from); - span.2 = span.2.max(*to); - } - drop(kept); - let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum(); - // Memory that is not write-watched is copied whole by every refresh. - // It was once refreshed only every 120 frames (unmapped pages read - // one by one cost 14 GB a frame in run 11, before they were - // remembered): streamed geometry then drew from stale buffers, and - // the garbage ended runs (the card stopped answering 14-90 frames - // into the opening cutscene; with every frame it ran on). The pass - // costs some 30 ms a frame this way. - static WHOLE: std::sync::Mutex>> = std::sync::Mutex::new(None); - let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); - let whole = whole.get_or_insert_with(Default::default); - for (shadow, from, to) in spans.values() { - if shadow.unwatched() { - // By the copy's number: a copy made where one let go was - // (`shadow::let_go_idle`) has never been refreshed. - let key = shadow.id() as usize; - // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame). - static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); - let every = *EVERY.get_or_init(|| { - std::env::var("VICTORY_UNWATCHED_FRAMES") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(1) - }); - match whole.get(&key) { - Some(&last) if frame < last + every => continue, - _ => { - whole.insert(key, frame); - } - } - } - shadow.refresh(list, *from, to - from); } #[cfg(feature = "diagnostics")] let refreshed = std::time::Instant::now(); - crate::watch::look_at_holes(); self.heap_textures(list, heap, host); #[cfg(feature = "diagnostics")] - for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked, refreshed.elapsed()]) { - sum.fetch_add(time.as_nanos() as u64, Ordering::Relaxed); - } + HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed); HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); - static LOGGED: AtomicU64 = AtomicU64::new(0); - // The first pass and every growth of the set by half. - let seen = LOGGED.load(Ordering::Relaxed); - if u64::from(views) > seen + seen / 2 { - LOGGED.store(u64::from(views), Ordering::Relaxed); - tracing::info!( - slots = slots.len(), - views, - copies = spans.len(), - mb = bytes >> 20, - ms = started.elapsed().as_millis(), - "buffer views of the heap made ready for shaders that pick them by index" - ); - } Some(gpu) } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index cc96adf..b671536 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -903,6 +903,9 @@ pub(crate) struct HostList { /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and /// how many batches of this recording have a place in them. batch_args: Mutex<(Vec, u32)>, + /// Refreshes of host copies that a thread of ours is still finding, and + /// where among the list's steps they belong ([`aside`]). + coming: Mutex)>>, /// Counts the list in [`ALIVE`] while it lives. _alive: Counted, /// The texts of the markers `note_op` set, in order (for device-removed @@ -3154,14 +3157,15 @@ fn late_line(frames: f64) { } } +pub(crate) mod aside; mod card_steps; mod place; mod send; +pub(crate) use send::{goes_as_words, words_under}; mod torn; pub(crate) mod upcheck; #[cfg(test)] -pub(crate) use send::{goes_as_words, words_under}; mod late_tests { use super::{continues, join_ranges, touches}; @@ -3546,6 +3550,7 @@ impl Host { card_budget: OnceLock::new(), indirect_args: Mutex::default(), batch_args: Mutex::default(), + coming: Mutex::default(), _alive: Counted::new(), #[cfg(feature = "diagnostics")] notes, @@ -4830,22 +4835,22 @@ impl Host { let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); let was_working = working(true); submitting(1, runs.len()); + #[cfg(feature = "diagnostics")] + let ahead = Split::begin(); + #[cfg(feature = "diagnostics")] + SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed); // Flights in the air ([`late`]): a submission that is waited for // settles them first, one sent ahead only if preparing it reads // what they write. // Or the reads are done on the card, behind the flights. let own = if late { self.card_steps(runs) } else { None }; #[cfg(feature = "diagnostics")] - let ahead = Split::begin(); - #[cfg(feature = "diagnostics")] - SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed); + ahead.part(12); if !late { self.settle(&mut submitted, WHY_SYNC); } else if own.is_none() && let Some(why) = late_blocked(runs) { - #[cfg(feature = "diagnostics")] - ahead.part(12); if relay_exact() && why == WHY_READ { // Only until the flights that may write what is read have // landed: their copy-back's end, not the card's other work. @@ -4856,13 +4861,13 @@ impl Host { self.settle(&mut submitted, why); } } + #[cfg(feature = "diagnostics")] + ahead.part(13); // Descriptors the title copied into placed heaps directly, before // command lists that index those slots are submitted. let heaps_synced = crate::descriptor::begin_sync_heaps(); // That list runs first, and is one of the submission's from here on. let with: Vec<&HostList>; - #[cfg(feature = "diagnostics")] - ahead.part(13); let runs = match &own { Some(own) => { with = std::iter::once(own.list()).chain(runs.iter().copied()).collect(); @@ -4898,13 +4903,13 @@ impl Host { crate::shadow::preparing(this_submission); let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] + ahead.part(14); + #[cfg(feature = "diagnostics")] let lock = (started - called).as_micros() as u64; #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Submissions, 1); let mut lists: Vec> = Vec::with_capacity(2 * runs.len()); // Where each run's lists start in `lists`. - ahead.part(14); - #[cfg(feature = "diagnostics")] let mut firsts = Vec::with_capacity(runs.len()); let mut batch = Batch::default(); #[cfg(feature = "diagnostics")] @@ -4968,12 +4973,12 @@ impl Host { } lists.push(list.list.cast().ok()); } + batch.fill(); batch.flush(); crate::watch::ask_once_end(); #[cfg(feature = "diagnostics")] split.part(2); // The snapshots of the ranges shaders may write, if they were left - batch.fill(); // for now (`crate::shadow::wide_back`): the refreshes are done, the // lists have not gone to the card. { @@ -5011,6 +5016,12 @@ impl Host { } #[cfg(feature = "diagnostics")] split.part(4); + drop(heaps_synced); + // The slots that waited for a texture's host copy, before the + // lists that may read them run. + crate::descriptor::make_waiting(); + #[cfg(feature = "diagnostics")] + split.part(15); let prepared = std::time::Instant::now(); if late { *submitted += 1; @@ -5027,12 +5038,6 @@ impl Host { split.part(5); let back = crate::picked::with(declared_writes(runs), &picked.written); let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); - drop(heaps_synced); - // The slots that waited for a texture's host copy, before the - // lists that may read them run. - crate::descriptor::make_waiting(); - #[cfg(feature = "diagnostics")] - split.part(15); SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed); submitting(0, 0); #[cfg(feature = "diagnostics")] @@ -5485,6 +5490,7 @@ impl HostList { } self.batches_common(); self.card_budget_out(); + self.take_coming(); #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); @@ -5502,12 +5508,35 @@ impl HostList { } } + /// `work` finds, on a thread of ours, refreshes that belong at this + /// place among the list's steps; they are there when the list is closed. + pub(crate) fn refreshes_coming(&self, work: impl FnOnce() -> Vec + Send + 'static) { + self.take_coming(); + let at = self.deferred().copies.len(); + let coming = aside::begin(work); + *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = Some((at, coming)); + } + + /// The refreshes that were still to come are put among the steps. + fn take_coming(&self) { + let Some((at, coming)) = self.coming.lock().unwrap_or_else(|e| e.into_inner()).take() else { + return; + }; + let found = coming.wait(); + let mut deferred = self.deferred(); + let at = at.min(deferred.copies.len()); + deferred + .copies + .splice(at..at, found.into_iter().map(|(shadow, from, to)| Step::Refresh(shadow, from as usize, (to - from) as usize))); + } + /// Only after the list's last submission finished (every one is waited /// for). pub(crate) fn reset(&self) { #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); self._alive.used(); + *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = None; *self.deferred() = Deferred::default(); self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear(); @@ -6367,6 +6396,7 @@ impl HostList { { copies += 1; } + batch.fill(); batch.title_written(); copy_mapped(dst as *mut u8, src as *const u8, len, true); // With the submission's one asking: the journal learns it. @@ -6379,24 +6409,29 @@ impl HostList { (started, len) } &Step::Fill(dst, src, len, _) => { - let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] { copies += 1; } + if wide_fills() { + batch.fills.push((dst, src, len)); + bytes += len as u64; + continue; + } + let started = std::time::Instant::now(); copy_mapped(dst as *mut u8, src as *const u8, len, false); (started, len) } Step::Placed(p) => { let started = std::time::Instant::now(); let free = !touches(air, p.src, p.src + p.len) && !touches(air, p.dst, p.dst + p.len); + batch.fill(); if free { batch.title_written(); } if let Some(bytes) = p.prepare(free) { batch.placed.push((p.shadow.clone(), p.dst, bytes)); } - batch.fill(); (started, p.len) } Step::Refresh(shadow, address, len) => { @@ -6409,23 +6444,17 @@ impl HostList { continue; } Step::Run(work) | Step::Host(work, _) => { + batch.fill(); #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); if matches!(step, Step::Run(_)) { batch.title_written(); - if wide_fills() { - batch.fills.push((dst, src, len)); - bytes += len as u64; - continue; - } - let started = std::time::Instant::now(); } work(); // It wrote title memory, where is not known here: the // submission's one asking ends, later refreshes ask anew. if matches!(step, Step::Run(_)) { crate::watch::ask_once_end(); - batch.fill(); } #[cfg(feature = "diagnostics")] { @@ -6444,7 +6473,6 @@ impl HostList { #[cfg(feature = "diagnostics")] let snapshot = std::time::Instant::now(); shadow.writing(*address, *len); - batch.fill(); #[cfg(feature = "diagnostics")] { add(C::GpuWrites, 1); @@ -6548,6 +6576,7 @@ impl Split { fn split_line(frames: f64) { let ms: Vec = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); let f: Vec = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let e: Vec = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect(); let a: Vec = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect(); let h: Vec = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); let s: Vec = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect(); @@ -6574,6 +6603,13 @@ fn split_line(frames: f64) { ms[4], ms[5], if crate::watch::light() { "on" } else { "off" }, + ms[11], + ms[12], + ms[13], + ms[14], + ms[15], + e[0], + e[1] / 1e3, ); tracing::info!( "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \ @@ -6588,7 +6624,6 @@ fn split_line(frames: f64) { a[10], a[9], a[2], - let e: Vec = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect(); a[3], a[4], a[5], @@ -6601,10 +6636,12 @@ fn split_line(frames: f64) { s[3], ); tracing::info!( - "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures", + "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures; the \ + first two beside the recording (VICTORY_HEAP_PASS_ASIDE), {:.1} ms waited for at the lists' close", h[0], h[1], h[2], + aside::WAITED.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames, ); } @@ -6613,13 +6650,6 @@ fn split_line(frames: f64) { /// /// A submission brings some sixty copies up to date, one after the other /// on the submitting thread: for each, the pages the title wrote are asked - ms[11], - ms[12], - ms[13], - ms[14], - ms[15], - e[0], - e[1] / 1e3, /// for and read through the kernel into the copy. That is the frame line's /// "copies", 45-50 ms a frame, and the copies have nothing to do with one /// another: each refresh writes its own copy and its own notes, and reads @@ -6685,6 +6715,22 @@ struct Batch { /// What copies at their place in the submission's lists put into title /// memory ([`place`]): the host copy, the title address, the bytes. placed: Vec<(std::sync::Arc, usize, Vec)>, + /// Fills not done yet (destination, source, bytes): [`wide_fills`]. + fills: Vec<(usize, usize, usize)>, +} + +/// Whether the fills of a submission's upload memory are done together on +/// several threads (`VICTORY_WIDE_FILLS=0`: one after the other, where the +/// lists name them). +/// +/// They are 7,000 to 12,000 a frame, some 500 bytes each, 5 ms of the +/// submitting thread. Each reads title memory and writes memory of its own +/// that the card alone reads, when the lists run; they are done before the +/// next step that writes title memory or runs code of ours, and before the +/// submission goes on from its steps. +fn wide_fills() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_FILLS").is_none_or(|v| v != "0") && wide_refresh()) } /// Whether a submission's textures are brought up to date on several @@ -6715,22 +6761,6 @@ impl Batch { (r.1, r.2) = (r.1.min(address), r.2.max(end)); } None => { - /// Fills not done yet (destination, source, bytes): [`wide_fills`]. - fills: Vec<(usize, usize, usize)>, -} - -/// Whether the fills of a submission's upload memory are done together on -/// several threads (`VICTORY_WIDE_FILLS=0`: one after the other, where the -/// lists name them). -/// -/// They are 7,000 to 12,000 a frame, some 500 bytes each, 5 ms of the -/// submitting thread. Each reads title memory and writes memory of its own -/// that the card alone reads, when the lists run; they are done before the -/// next step that writes title memory or runs code of ours, and before the -/// submission goes on from its steps. -fn wide_fills() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_FILLS").is_none_or(|v| v != "0") && wide_refresh()) self.index.insert(key, self.refreshes.len()); self.refreshes.push((shadow.clone(), address, end)); } @@ -6786,6 +6816,33 @@ fn wide_fills() -> bool { self.textures.clear(); } + /// The fills noted are done. + fn fill(&mut self) { + // Below this many the threads cost more than they save. + const FEW: usize = 96; + const PART: usize = 64; + if self.fills.is_empty() { + return; + } + let started = std::time::Instant::now(); + if self.fills.len() < FEW { + for (dst, src, len) in self.fills.drain(..) { + copy_mapped(dst as *mut u8, src as *const u8, len, false); + } + } else { + let fills = std::mem::take(&mut self.fills); + crate::shadow::wide_each(fills.len().div_ceil(PART), move |i| { + for &(dst, src, len) in fills.iter().skip(i * PART).take(PART) { + copy_mapped(dst as *mut u8, src as *const u8, len, false); + } + }); + } + let took = started.elapsed(); + PREPARING[0].fetch_add(took.as_micros() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + SPLIT[7].fetch_add(took.as_nanos() as u64, Ordering::Relaxed); + } + /// The textures due are brought up to date. fn refresh_textures(&mut self) { if self.due.len() < 2 || !wide_textures() { @@ -6816,33 +6873,6 @@ fn wide_fills() -> bool { FLUSHES[0].fetch_add(1, Ordering::Relaxed); FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed); } - /// The fills noted are done. - fn fill(&mut self) { - // Below this many the threads cost more than they save. - const FEW: usize = 96; - const PART: usize = 64; - if self.fills.is_empty() { - return; - } - let started = std::time::Instant::now(); - if self.fills.len() < FEW { - for (dst, src, len) in self.fills.drain(..) { - copy_mapped(dst as *mut u8, src as *const u8, len, false); - } - } else { - let fills = std::mem::take(&mut self.fills); - crate::shadow::wide_each(fills.len().div_ceil(PART), move |i| { - for &(dst, src, len) in fills.iter().skip(i * PART).take(PART) { - copy_mapped(dst as *mut u8, src as *const u8, len, false); - } - }); - } - let took = started.elapsed(); - PREPARING[0].fetch_add(took.as_micros() as u64, Ordering::Relaxed); - #[cfg(feature = "diagnostics")] - SPLIT[7].fetch_add(took.as_nanos() as u64, Ordering::Relaxed); - } - } fn flush_all(&mut self) { diff --git a/crates/victory-gpu/src/host/aside.rs b/crates/victory-gpu/src/host/aside.rs new file mode 100644 index 0000000..051debc --- /dev/null +++ b/crates/victory-gpu/src/host/aside.rs @@ -0,0 +1,98 @@ +//! Work for a list that a thread of ours does while the title records on: +//! the pass over the heap's buffer views (`crate::draw`), which took 12 to 17 +//! ms of one recording thread at the frame's first list that needs it, with +//! the submission of that list, and of those behind it, waiting. +//! `VICTORY_HEAP_PASS_ASIDE=0`: done where it is needed, as before. +//! +//! What it finds are refreshes of host copies, which are steps of the list +//! for its submission, and what it makes are descriptors, which the card +//! reads when the list runs: both are there when the list is closed +//! (`HostList::close` waits), and the refreshes stand at the place in the +//! list's steps where the pass was begun. + +use super::*; + +/// A host copy, and the title memory of it (from, to). +pub(crate) type Refresh = (std::sync::Arc, u64, u64); + +/// What is being found, until it is. +pub(crate) struct Coming(Mutex>>, std::sync::Condvar); + +/// Since the last frame line: microseconds lists waited at their close. +pub(crate) static WAITED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +impl Coming { + /// What was found. + pub(crate) fn wait(&self) -> Vec { + let began = std::time::Instant::now(); + let mut found = self.0.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(found) = found.take() { + WAITED.fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); + return found; + } + found = self.1.wait(found).unwrap_or_else(|e| e.into_inner()); + } + } + + fn found(&self, what: Vec) { + *self.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(what); + self.1.notify_all(); + } +} + +pub(crate) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_PASS_ASIDE").is_none_or(|v| v != "0")) +} + +type Job = Box; + +/// `work` begins on the thread for it, one after another; here and now if +/// there is no such thread. +pub(crate) fn begin(work: impl FnOnce() -> Vec + Send + 'static) -> std::sync::Arc { + static THREAD: OnceLock>>> = OnceLock::new(); + let coming = std::sync::Arc::new(Coming(Mutex::new(None), std::sync::Condvar::new())); + let told = coming.clone(); + let job: Job = Box::new(move || { + // (However it ends, the list that waits goes on.) + let found = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)).unwrap_or_default(); + told.found(found); + }); + let thread = THREAD.get_or_init(|| { + let (send, jobs) = std::sync::mpsc::channel::(); + std::thread::Builder::new() + .name("victory-aside".into()) + .spawn(move || jobs.into_iter().for_each(|job| job())) + .ok() + .map(|_| Mutex::new(send)) + }); + match thread { + Some(send) => { + if let Err(job) = send.lock().unwrap_or_else(|e| e.into_inner()).send(job) { + (job.0)(); + } + } + None => job(), + } + coming +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn what_is_found_is_waited_for_and_a_panic_lets_the_list_go_on() { + let (go, wait) = std::sync::mpsc::channel::<()>(); + let coming = begin(move || { + let _ = wait.recv(); + Vec::new() + }); + assert!(coming.0.lock().unwrap().is_none()); + go.send(()).unwrap(); + assert!(coming.wait().is_empty()); + assert!(begin(|| panic!("a panic of the work")).wait().is_empty()); + assert!(begin(Vec::new).wait().is_empty()); + } +} From 5f86fa3025c4b551d34a97bd5138b8853256b3b9 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:00:22 -0600 Subject: [PATCH 320/445] VICTORY_CARD_AWAKE: the card's clocks kept up between submissions A captured frame whose lists take 28.6 ms sent in one go takes 37.8 ms with 1.2 ms between its submissions, as the game sends them; with one group of threads counting on a compute queue it takes 28.6 ms again, and nothing changes when sent in one go (36.1 against 36.3 ms with its copies). =turns: 20 s on, 20 s off, to compare in one run. Replay: --awake, --no-restore makes no copies to restore from. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 4 + crates/victory-gpu/src/host.rs | 2 + crates/victory-gpu/src/host/awake.rs | 204 ++++++++++++++++++++++++++ crates/victory-gpu/src/replay/play.rs | 14 +- docs/replay.md | 3 +- 5 files changed, 224 insertions(+), 3 deletions(-) create mode 100644 crates/victory-gpu/src/host/awake.rs diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index db2f9d6..490b523 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -85,6 +85,9 @@ pub(crate) struct Replay { /// idle between them, as it does while the title prepares the next. #[arg(long, default_value_t = 0.0)] pace: f64, + /// Keep the card's clocks up meanwhile (VICTORY_CARD_AWAKE=1). + #[arg(long)] + awake: bool, /// The system's breadcrumbs after every command (VICTORY_D3D12_DRED=light). #[arg(long)] breadcrumbs: bool, @@ -263,6 +266,7 @@ pub(crate) fn run(r: Replay) -> Result<()> { wait_all: r.wait_all, wait_lists: r.wait_lists, pace: r.pace, + awake: r.awake, only, until, skip_shaders: r.skip_shader, diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 0c77c85..296cd0f 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3167,6 +3167,7 @@ fn late_line(frames: f64) { } } +pub(crate) mod awake; mod card_steps; mod place; mod send; @@ -5030,6 +5031,7 @@ impl Host { self.queue.ExecuteCommandLists(&lists); self.queue.Signal(&self.fence, *submitted) }; + awake::sent(&self.device); self.card_sent(); if let Err(e) = signalled { fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); diff --git a/crates/victory-gpu/src/host/awake.rs b/crates/victory-gpu/src/host/awake.rs new file mode 100644 index 0000000..ceb66ea --- /dev/null +++ b/crates/victory-gpu/src/host/awake.rs @@ -0,0 +1,204 @@ +//! Keeps the card's clocks up between submissions (`VICTORY_CARD_AWAKE=1`; off +//! by default). The card stands idle half of every frame, some thirty times for +//! a millisecond or two each, while the CPU prepares the next submission. The +//! driver takes that for a light load and lowers the clocks, and what comes +//! next starts slow: a captured frame whose lists take 30 ms sent in one go +//! takes 38-40 ms with waits of 1.2-2.4 ms between its submissions +//! (`victory replay --pace`). +//! +//! One group of 64 threads counts on a compute queue, over and +//! over: it takes one or two of the card's few thousand wave slots, and the +//! card is never idle. Nothing is sent once no submission has gone out for a +//! while (a menu at 30 fps, a minimized window). + +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::Duration; + +use windows::Win32::Foundation::CloseHandle; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::core::Interface; + +/// About 2 ms at full clocks: 500 sends a second. +const COUNT: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer sum : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + uint x = id.x; + [loop] for (uint i = 0; i < 400000u; i++) x = x * 1664525u + 1013904223u; + sum.Store(id.x * 4u, x); +} +"#; + +/// Quiet this long after the last submission. +const QUIET_MS: u64 = 250; + +fn now_ms() -> u64 { + static START: OnceLock = OnceLock::new(); + START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + +/// When a submission was last sent ([`now_ms`] plus one; 0: never). +static LAST: AtomicU64 = AtomicU64::new(0); + +fn wanted() -> bool { + let (last, now) = (LAST.load(Ordering::Relaxed), now_ms()); + last != 0 && now + 1 < last + QUIET_MS && (mode() != Mode::ByTurns || now / TURN_MS % 2 == 1) +} + +/// With `VICTORY_CARD_AWAKE=turns`: this long on, this long off. +const TURN_MS: u64 = 20_000; + +#[derive(Clone, Copy, PartialEq)] +enum Mode { + Off, + On, + /// On and off by turns, to compare the two in one run (the log says when). + ByTurns, +} + +fn mode() -> Mode { + static MODE: OnceLock = OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_CARD_AWAKE").as_deref() { + Ok("1") => Mode::On, + Ok("turns") => Mode::ByTurns, + _ => Mode::Off, + }) +} + +/// A submission of the title's goes to `device`'s drawing queue. +pub(super) fn sent(device: &ID3D12Device) { + if mode() == Mode::Off { + return; + } + let now = now_ms(); + let before = LAST.swap(now + 1, Ordering::Relaxed); + if mode() == Mode::ByTurns && before.saturating_sub(1) / TURN_MS != now / TURN_MS { + tracing::info!(on = now / TURN_MS % 2 == 1, "the card is kept awake, by turns"); + } + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + // Runs as long as the process does. + std::mem::forget(start(device, wanted)); + }); +} + +/// The thread that keeps the card busy; it ends when this is dropped. +pub(crate) struct Awake { + stop: std::sync::Arc, + thread: Option>, +} + +impl Drop for Awake { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +/// Keeps the card of `device` busy while `wanted`. +pub(crate) fn start(device: &ID3D12Device, wanted: impl Fn() -> bool + Send + 'static) -> Option { + let stop = std::sync::Arc::new(AtomicBool::new(false)); + let (device, ended) = (device.clone(), stop.clone()); + let thread = std::thread::Builder::new() + .name("victory-card-awake".into()) + .spawn(move || { + if let Err(e) = run(&device, &wanted, &ended) { + tracing::warn!(error = %e, "the card is not kept awake"); + } + }) + .ok()?; + Some(Awake { + stop, + thread: Some(thread), + }) +} + +fn run(device: &ID3D12Device, wanted: &dyn Fn() -> bool, stop: &AtomicBool) -> windows::core::Result<()> { + let code = super::compile(COUNT, windows::core::s!("main"), windows::core::s!("cs_5_1"))?; + // SAFETY: plain object creation; the code lives through the calls, the + // root signature is inside it. Two closed lists, sent in turn, whose + // objects live until what was sent last has run. + unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, &code)?; + let pso: ID3D12PipelineState = device.CreateComputePipelineState(&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() + })?; + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, + Priority: D3D12_COMMAND_QUEUE_PRIORITY_NORMAL.0, + ..Default::default() + })?; + let mut sum: Option = None; + device.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut sum, + )?; + let sum = sum.ok_or_else(windows::core::Error::empty)?; + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE)?; + let mut lists = Vec::new(); + for _ in 0..2 { + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &allocator, &pso)?; + list.SetComputeRootSignature(&root); + list.SetComputeRootUnorderedAccessView(0, sum.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.Close()?; + lists.push(Some(list.cast::()?)); + } + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = CreateEventW(None, false, false, None)?; + let mut value = 0u64; + let mut result = Ok(()); + while !stop.load(Ordering::Relaxed) && result.is_ok() { + if !wanted() { + std::thread::sleep(Duration::from_millis(2)); + continue; + } + // Never more than two on the way. + if value >= 2 && fence.GetCompletedValue() + 2 <= value { + result = fence.SetEventOnCompletion(value - 1, event); + if result.is_ok() { + WaitForSingleObject(event, 1000); + result = device.GetDeviceRemovedReason(); + } + continue; + } + queue.ExecuteCommandLists(&lists[(value % 2) as usize..][..1]); + value += 1; + result = queue.Signal(&fence, value); + } + if result.is_ok() && fence.GetCompletedValue() < value && fence.SetEventOnCompletion(value, event).is_ok() { + WaitForSingleObject(event, INFINITE); + } + let _ = CloseHandle(event); + result + } +} diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index e28c20c..b823576 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -87,6 +87,8 @@ pub struct Options { /// Milliseconds the sender waits after each submission, as a title does /// that prepares the next one meanwhile: the card stands idle. pub pace: f64, + /// The card kept awake meanwhile (`crate::host::awake`). + pub awake: bool, /// Run only these lists (by their place in the frame). pub only: Option<(u32, u32)>, /// The last command that runs (list, command); after it only barriers. @@ -123,6 +125,7 @@ impl Default for Options { wait_all: false, wait_lists: false, pace: 0.0, + awake: false, only: None, until: None, skip_shaders: Vec::new(), @@ -158,6 +161,7 @@ impl Options { one_submit: false, wait_all: false, wait_lists: false, + awake: false, only: None, skip_shaders: Vec::new(), ..self.clone() @@ -582,7 +586,7 @@ impl Player { step("descriptors", &mut at); player.load_contents()?; step("contents", &mut at); - player.make_masters(options.buffers)?; + player.make_masters(options.buffers, options.restore)?; step("copies to restore from", &mut at); let steps: Vec = steps .iter() @@ -1566,7 +1570,7 @@ impl Player { } /// Copies of what the frame changes; and the states it leaves. - fn make_masters(&mut self, buffers: Buffers) -> Result<()> { + fn make_masters(&mut self, buffers: Buffers, wanted: bool) -> Result<()> { let mut states = States::default(); for r in &self.frame.resources { if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { @@ -1699,6 +1703,11 @@ impl Player { }) .collect(); ids.sort_unstable(); + // Without restoring they are of no use, and their room may be what + // the frame itself lacks. + if !wanted { + ids.clear(); + } let mut total = 0u64; let mut in_pc = 0u64; for id in ids { @@ -2962,6 +2971,7 @@ impl Player { /// Runs the frame as the options say. pub fn run(&mut self, o: &Options) -> Result { let mut made = self.prepare(o)?; + let _awake = if o.awake { crate::host::awake::start(&self.device, || true) } else { None }; let mut stamps = Vec::new(); for _ in 0..o.loops.max(1) { stamps = self.once(o, &mut made)?; diff --git a/docs/replay.md b/docs/replay.md index 7d9e050..0459d7d 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -69,8 +69,9 @@ with the presented one. | `--only 3..7` | runs these lists; of the others only barriers | | `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) | | `--skip-shader ` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) | -| `--no-restore` | leaves what a loop changed | +| `--no-restore` | leaves what a loop changed, and makes no copies to restore from (of a capture that does not fit in the card's memory with them) | | `--pace ` | a wait after each submission sent: the card stands idle between them, as in a game that prepares the next one | +| `--awake` | keeps the card's clocks up (`VICTORY_CARD_AWAKE=1`) | | `--breadcrumbs` | the system's breadcrumbs (`VICTORY_D3D12_DRED=light`) | | `--debug-layer` | D3D12's debug layer; its errors in the report | From bde604e72589022d4e6b84b3fe6c26f334f65427 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:03:24 -0600 Subject: [PATCH 321/445] Title memory by address: pages in arenas, structures' pages made ready ahead Windows of title memory around every page took 8 GB (run light-2, 0.5-1 s a frame): structures are streamed in anywhere between other data. A 64 KiB page outside title buffers now has a page of its own in an arena on the card; only the title's GPU memory is taken; what instances in a list's upload memory name is there before the top level is built, 1 MiB from each root view before the rehydration stages unpack it in place. VICTORY_MEMORY_DUMP= writes the arenas out (diagnostics). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 10 +- crates/victory-gpu/src/memory.rs | 703 +++++++++++++++++++++---------- crates/victory-gpu/src/shadow.rs | 21 +- crates/victory-gpu/src/upload.rs | 10 + 4 files changed, 516 insertions(+), 228 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index b4174c9..f286375 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1030,7 +1030,9 @@ impl State { let (mut addresses, mut constants) = (Vec::new(), Vec::new()); for root in self.roots_ref(compute) { match root { - Root::View(address) => addresses.push(*address), + // (Of a program that only walks structures, the structures' + // views below: its root views are constants and tables.) + Root::View(address) if use_ != crate::memory::Use::Reads => addresses.push(*address), Root::Constants(values) => constants.extend_from_slice(values), _ => {} } @@ -1237,10 +1239,8 @@ impl State { let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) { // Only through a store by address: what it stores through // views is declared with them. - let use_ = if crate::pipeline::is_builder(self.pipeline as This) { - crate::memory::Use::Builder { back: writes } - } else if writes && t.stores_by_address { - crate::memory::Use::Writes + let use_ = if crate::pipeline::is_builder(self.pipeline as This) || writes && t.stores_by_address { + crate::memory::Use::Builds { back: writes } } else { crate::memory::Use::Reads }; diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index da67877..034c244 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -4,15 +4,14 @@ //! structures; the structures themselves lie in plain title memory, in no //! buffer object). //! -//! A page in a title buffer that holds all of it is in that buffer's copy -//! ([`crate::shadow`]), which every other access uses. A page outside -//! buffers is in a window of this module's own, on the card -//! ([`crate::shadow::by_address`]): 4 MiB around what a dispatch names (the -//! title's pool of dynamic structures), 256 KiB around a page a shader came -//! to by a pointer (the streamed structures lie anywhere between other -//! data; `VICTORY_MEMORY_WINDOW_KB`). +//! A 64 KiB page in a title buffer that holds all of it is in that buffer's +//! copy ([`crate::shadow`]), which every other access uses. A page outside +//! buffers has a page of its own in an **arena**: memory of ours with a copy +//! on the card ([`crate::shadow::by_address`]). The streamed structures lie +//! anywhere between other data (6.6 GB of title memory in 4 MiB windows, run +//! light-1; 8 GB in windows of 256 KiB, light-2), so a page is what is kept. //! -//! This module keeps what a shader needs to find the copies: +//! This module keeps what a shader needs to find the pages: //! //! - the **directory**: per 64 KiB page of title address space the number //! of the copy that holds the page (0: none) and the page's byte offset @@ -24,34 +23,35 @@ //! numbered copy (slot 0 of the run: a null view, for pages without a //! copy); //! - the **faults**: the page numbers shaders found empty, read back here -//! once a frame, so the copies exist from the next frame on. A pointer a -//! shader takes out of memory cannot be known before it runs; the -//! addresses a dispatch is given as root views are made ready before it. +//! once a frame, so the pages are there from the next frame on. A pointer a +//! shader takes out of memory cannot be known before it runs. //! //! **A page that is not there when a shader touches it is a lost access**: //! the read gives 0, the store is dropped, and the fault note only helps //! the next frame. For the structure builder that is the same as a dropped -//! stage, so before a dispatch the host makes ready everything it can see -//! the dispatch name: the window around each root view, around each -//! pair of root constants that is a title address and around each root -//! constant that is one in 256-byte units (the builder passes structures -//! all three ways), and the one after each (a structure may cross a -//! window's end). -//! shortcut: what a stage reaches only through pointers it reads out of -//! memory (the structures a top-level build's instances name) is there from -//! the second frame on; the fault count in the log says how often that -//! happens. The top level is built anew every frame. +//! stage, so before one of its dispatches the host makes ready what it can +//! see the dispatch name: +//! +//! - 1 MiB from each root view outside buffers (structures unpacked in place: +//! the title ships them packed and the builder's rehydration stages unpack +//! each once, when it is streamed in); +//! - 4 MiB from each pair of root constants that is a title address and from +//! each root constant that is one in 256-byte units (structures built); +//! - the first page of every structure a list's upload memory names +//! (a top-level build's instances). //! //! **What comes back to title memory**: what the builder stores in title //! buffers of at most [`BACK`] bytes it names (the sizes the title reads to -//! make a structure smaller). Structures and scratch memory stay on the card. -//! Other programs that store by address declare the copies they name. +//! make a structure smaller). Structures and scratch memory stay on the card +//! (the first whole run of the builder wrote garbage over the title's +//! objects). So an arena's page is the only place a structure is whole, and +//! title memory must not go over it: of a page the title wrote only the +//! dwords that changed since they were last taken go up, unless a quarter of +//! a 4 KiB piece changed, which is other data streamed in: then all of it. //! -//! shortcut: a copy that is numbered is kept for the rest of the run, and -//! there are at most [`COPIES`] of them. -//! shortcut: the windows a list does not name are brought up to date once a -//! frame, by the first list that reads by address: bytes the title writes -//! there later in the frame are seen a frame late. +//! shortcut: a page is kept for the rest of the run. +//! shortcut: pages a list does not name are looked at again in turn, over +//! [`SWEEP`] frames. use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -63,52 +63,83 @@ use crate::descriptor::host::HostHeap; use crate::host::{HostList, host}; use crate::shadow::Shadow; -/// Copies that can be numbered (the run of heap slots is one longer). A -/// frame of the dorm names 1,100 pages outside the named windows. -const COPIES: u32 = (1 << 14) - 1; -/// A window around memory a dispatch names. -const CELL: u64 = 4 << 20; +/// Copies that can be numbered (the run of heap slots is one longer). +const COPIES: u32 = (1 << 12) - 1; /// A directory page. const PAGE: u64 = 1 << 16; +/// An arena's bytes. +const ARENA: u64 = 64 << 20; +/// The kernel's page: what is sent whole when much of it changed. +const PIECE: usize = 4096; +/// From a root view; from an address in constants. +const VIEW: u64 = 1 << 20; +const BUILT: u64 = 4 << 20; /// The biggest title buffer whose builder results come back. const BACK: u64 = 256 << 10; +/// Pages taken from the faults of one frame, at most. +const FAULTS: usize = 2048; +/// Frames over which every page is looked at once. +const SWEEP: usize = 32; /// What a draw or dispatch does with title memory by address. #[derive(Clone, Copy, PartialEq)] pub(crate) enum Use { Reads, - Writes, - /// A stage of the structure builder; `back`: its results come back. - Builder { back: bool }, + /// Stores by address, as the structure builder; `back`: its results in + /// small title buffers come back. + Builds { back: bool }, +} + +/// A page of title memory in an arena. +struct Held { + /// Where in the arena's memory, and the arena's place in `copies`. + at: usize, + copy: usize, + /// The write-watch asking after which it was last taken (0: never). + taken: u64, } struct Memory { /// The CPU's entries (number, offset), and the copy shaders read. directory: (*mut u32, Arc), faults: (ID3D12Resource, *mut u32, u64), - /// Copy `n` is `copies[n - 1]`; whether it is a window of ours. - copies: Vec<(Arc, bool)>, + /// Copy `n` is `copies[n - 1]`. + copies: Vec>, /// Places of title buffers' copies among `copies`. numbers: HashMap, + /// Arenas: place in `copies`, address; pages of the last one handed out. + arenas: Vec<(usize, usize)>, + used: u64, + /// By title page. + pages: HashMap, + /// Their numbers in the order they came, and where the sweep is. + order: Vec, + sweep: usize, /// Per host view heap (by address): the first slot of its run, and how /// many copies have their view there. heaps: HashMap, /// The frame the faults were last read in. frame: u64, - /// The frame our windows were last brought up to date in. - swept: u64, /// Pages asked for this frame that are not the title's memory. refused: std::collections::HashSet, stats: Stats, + #[cfg(feature = "diagnostics")] + dump: dump::Dump, } -/// Since the last report (diagnostics). +/// Since the last report. #[derive(Default)] struct Stats { from: Option<(std::time::Instant, u64)>, - uses: [u64; 3], + uses: [u64; 2], faults: u64, + unknown: u64, back: u64, + /// Pages looked at, bytes that changed, pieces sent whole. + looked: u64, + changed: u64, + whole: u64, + micros: u64, } // SAFETY: the mappings are of memory the struct owns; all access is under @@ -125,15 +156,6 @@ pub(crate) struct Ready { pub(crate) base: u32, } -/// A window around a page a shader came to by a pointer. -fn far_window() -> u64 { - static BYTES: std::sync::OnceLock = std::sync::OnceLock::new(); - *BYTES.get_or_init(|| { - let kb = std::env::var("VICTORY_MEMORY_WINDOW_KB").ok().and_then(|v| v.trim().parse::().ok()); - kb.map(|kb| kb << 10).filter(|b| b.is_power_of_two() && (PAGE..=CELL).contains(b)).unwrap_or(256 << 10) - }) -} - impl Memory { fn new() -> Option { let host = host()?; @@ -154,11 +176,17 @@ impl Memory { faults: (faults, data.cast::(), gpu), copies: Vec::new(), numbers: HashMap::new(), + arenas: Vec::new(), + used: ARENA / PAGE, + pages: HashMap::new(), + order: Vec::new(), + sweep: 0, heaps: HashMap::new(), frame: u64::MAX, - swept: u64::MAX, refused: Default::default(), stats: Stats::default(), + #[cfg(feature = "diagnostics")] + dump: Default::default(), }) } @@ -169,87 +197,168 @@ impl Memory { unsafe { self.directory.0.add(page as usize * 2) } } - /// Gives the page of `address` its copy, if it has none and the memory - /// is the title's (a window of `window` bytes outside buffers); the place - /// of its copy in `copies`. - fn map(&mut self, address: u64, window: u64) -> Option { - let page = address / PAGE; - // The last entry stays empty: addresses past the directory read it. - if page >= u64::from(MEMORY_PAGES) - 1 { + /// The place in `copies` of the copy that holds `page`, if one does. + fn copy_of(&self, page: u64) -> Option { + if page >= u64::from(MEMORY_PAGES) { return None; } // SAFETY: an entry of the directory. - let mut number = unsafe { self.entry(page).read() }; - if number == 0 { - self.make(page, window); - // SAFETY: as above. - number = unsafe { self.entry(page).read() }; - } - (number as usize).checked_sub(1) + (unsafe { self.entry(page).read() } as usize).checked_sub(1) } - fn make(&mut self, page: u64, window: u64) { - let start = page * PAGE; - // A shader's pointer, or a constant taken for an address, may be - // anything: only memory the title has. - if self.refused.contains(&page) { - return; + /// Whether `page` can be given a place: in the directory, not turned down + /// this frame, and the title's GPU memory. (A shader's pointer, or a + /// constant taken for an address, may be anything.) + fn possible(&mut self, page: u64) -> bool { + // Not the last entry: addresses past the directory read it, and it + // stays empty. + if page < 0x1_0000 || page >= u64::from(MEMORY_PAGES) - 1 || self.refused.contains(&page) { + return false; } - if !crate::texture::committed(start as *const u8, PAGE as usize) { + let at = (page * PAGE) as usize; + let ours = crate::texture::committed(at as *const u8, PAGE as usize) + && crate::watch::writes(at, at + PAGE as usize, true).is_some(); + if !ours { self.refused.insert(page); - return; + self.stats.unknown += 1; + } + ours + } + + /// Gives a copy a number, if one is left. + fn number(&mut self, shadow: Arc) -> Option { + let key = Arc::as_ptr(&shadow) as usize; + if let Some(&n) = self.numbers.get(&key) { + return Some(n); + } + if self.copies.len() >= COPIES as usize { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros")); + return None; } - // The copy of a title buffer that holds all of the page, the - // innermost first; else a window of our own. - let whole = |s: &Arc| s.offset_in(start).is_some() && s.left(start) >= PAGE; - let buffer = crate::shadow::in_buffer(start, PAGE).and_then(|_| crate::shadow::find(start, PAGE)).filter(whole); - let own = buffer.is_none(); - let shadow = match buffer { - Some(s) => s, - None => { - if self.copies.len() >= COPIES as usize { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros") - }); - return; - } - let Some(s) = crate::shadow::by_address(start & !(window - 1), window) else { - return; - }; - s - } - }; // SAFETY: a live buffer. let flags = unsafe { shadow.buffer.GetDesc() }.Flags; if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { - return; + return None; } - let key = Arc::as_ptr(&shadow) as usize; - let n = match self.numbers.get(&key) { - Some(&n) => n, - None if self.copies.len() < COPIES as usize => { - self.copies.push((shadow.clone(), own)); - let n = self.copies.len() - 1; - self.numbers.insert(key, n); - // Every page the copy holds whole, not only the one asked - // for: a structure is more than 64 KiB. (Not those of title - // buffers inside a window: they have copies of their own.) + self.copies.push(shadow); + let n = self.copies.len() - 1; + self.numbers.insert(key, n); + Some(n) + } + + /// Gives `page` a place, if it has none and the memory is the title's; + /// whether it has one then. + fn map(&mut self, page: u64) -> bool { + if self.copy_of(page).is_some() { + return true; + } + if !self.possible(page) { + return false; + } + let start = page * PAGE; + if crate::shadow::in_buffer(start, PAGE).is_some() { + let Some(shadow) = crate::shadow::find(start, PAGE) else { + return false; + }; + let fresh = !self.numbers.contains_key(&(Arc::as_ptr(&shadow) as usize)); + let Some(n) = self.number(shadow.clone()) else { + return false; + }; + // Every page the copy holds whole, not only the one asked for. + // shortcut: a page of a title buffer inside this one that has a + // copy of its own is given this copy too. + if fresh { let (first, len) = shadow.span(); let mut at = first.next_multiple_of(PAGE); while at + PAGE <= first + len && at / PAGE < u64::from(MEMORY_PAGES) - 1 { let entry = self.entry(at / PAGE); // SAFETY: an entry of the directory. - if unsafe { entry.read() } == 0 && (!own || crate::shadow::in_buffer(at, PAGE).is_none()) { + if unsafe { entry.read() } == 0 { fill(entry, n, at - first); } at += PAGE; } - n } - None => return, + fill(self.entry(page), n, start - shadow.span().0); + return true; + } + if self.used == ARENA / PAGE { + let Some(at) = crate::upload::reserve(ARENA as usize) else { + return false; + }; + let Some(shadow) = crate::shadow::by_address(at as u64, ARENA) else { + return false; + }; + let Some(n) = self.number(shadow) else { + return false; + }; + self.arenas.push((n, at)); + self.used = 0; + } + let Some(&(copy, arena)) = self.arenas.last() else { + return false; }; - fill(self.entry(page), n, shadow.offset_in(start).unwrap_or(0)); + let offset = self.used * PAGE; + self.used += 1; + self.pages.insert(page, Held { at: arena + offset as usize, copy, taken: 0 }); + self.order.push(page); + fill(self.entry(page), copy, offset); + true + } + + /// [`Memory::map`] of the pages of `[address, address + len)`, up to the + /// first that is not the title's, and what the title wrote there since + /// they were taken goes into the arenas. + fn ready(&mut self, address: u64, len: u64) { + let first = address / PAGE; + let mut end = first; + while end * PAGE < address + len && self.map(end) { + end += 1; + } + self.bring(first, end); + } + + /// Takes the pages `[first, end)` that are in arenas from title memory + /// where it wrote them. + fn bring(&mut self, first: u64, end: u64) { + if first >= end { + return; + } + let started = std::time::Instant::now(); + let answer = crate::watch::writes((first * PAGE) as usize, (end * PAGE) as usize, true); + for page in first..end { + let Some(held) = self.pages.get_mut(&page) else { + continue; + }; + self.stats.looked += 1; + let wrote = answer + .as_ref() + .map(|(_, w)| w.binary_search_by_key(&(page as usize), |w| w.0).map_or(0, |i| w[i].1)); + let now = answer.as_ref().map_or(1, |a| a.0); + let stale = held.taken == 0 || wrote.is_none_or(|w| w > held.taken); + if !stale { + continue; + } + let never = std::mem::replace(&mut held.taken, now.max(1)) == 0; + let shadow = &self.copies[held.copy]; + let base = held.at - shadow.span().0 as usize; + let mut title = [0u8; PIECE]; + for piece in (0..PAGE as usize).step_by(PIECE) { + let from = (page * PAGE) as usize + piece; + // (Pages that are not there read as zeros.) + crate::host::copy_mapped(title.as_mut_ptr(), from as *const u8, PIECE, false); + // SAFETY: a page of an arena of ours, under the mutex. + let ours = unsafe { std::slice::from_raw_parts_mut((held.at + piece) as *mut u8, PIECE) }; + let (changed, whole) = merge(&title, ours, never); + self.stats.changed += changed as u64 * 4; + if whole { + self.stats.whole += 1; + shadow.resend(base + piece, base + piece + PIECE); + } + } + } + self.stats.micros += started.elapsed().as_micros() as u64; } /// The pages shaders found empty since the last frame. @@ -262,7 +371,7 @@ impl Memory { // SAFETY: as above. let page = unsafe { at.read_volatile() }; if page != 0 { - pages.push(page); + pages.push(u64::from(page)); // SAFETY: as above. unsafe { at.write_volatile(0) }; } @@ -270,66 +379,105 @@ impl Memory { if pages.is_empty() { return; } + pages.sort_unstable(); let mut made = 0; for &page in &pages { - made += usize::from(self.map(u64::from(page) * PAGE, far_window()).is_some()); + if made < FAULTS && self.copy_of(page).is_none() && self.map(page) { + made += 1; + self.bring(page, page + 1); + } } self.stats.faults += pages.len() as u64; // Each is an access that read 0 or was dropped. static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 100 { - pages.sort_unstable(); - let first: Vec = pages.iter().take(8).map(|&p| format!("{:#x}", u64::from(p) * PAGE)).collect(); + let said = SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if said < 40 || said.is_multiple_of(100) { + let some: Vec = pages + .iter() + .step_by(pages.len().div_ceil(12)) + .map(|&p| format!("{:#x}", p * PAGE)) + .collect(); tracing::warn!( frame = self.frame, pages = pages.len(), made, - copies = self.copies.len(), - ?first, - "title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); the copies are made now, of those that are the title's" + held = self.pages.len(), + ?some, + "title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); those that are the title's are there now" ); } } - /// What a dispatch names: the copy around `address` and the one after it; - /// their places in `copies`. - fn name(&mut self, address: u64, named: &mut Vec) { - for at in [address, (address & !(CELL - 1)) + CELL] { - if let Some(n) = self.map(at, CELL) - && !named.contains(&n) - { - named.push(n); + /// The structures named in a list's upload memory around `address` + /// (instances of a top-level build: a structure's address is their last + /// 8 bytes): the first page of each. + fn named_in_upload(&mut self, address: u64) { + let Some((from, len)) = crate::upload::block(address as usize) else { + return; + }; + // SAFETY: the block is handed out and stays mapped; the title wrote + // it before it recorded the dispatch. + let words = unsafe { std::slice::from_raw_parts(from as *const u64, len / 8) }; + let mut seen = std::collections::HashSet::new(); + for &word in words { + if word & 0xFF == 0 && (1 << 32..1 << 37).contains(&word) && seen.insert(word / PAGE) && self.map(word / PAGE) { + let page = word / PAGE; + self.bring(page, page + 1); } } } - /// Every ten seconds or so, what was used (with the frame's line). + /// A title buffer too small to fill its pages, whose results come back: + /// windows of title memory itself around its pages, which go back. + fn small(&mut self, list: &HostList, start: u64, len: u64) { + let mut at = start; + while at < start + len { + let page = at / PAGE; + let n = ((page + 1) * PAGE).min(start + len) - at; + if self.copy_of(page).is_none() + && self.possible(page) + && let Some(shadow) = crate::shadow::by_address(page * PAGE, PAGE) + && let Some(k) = self.number(shadow) + { + fill(self.entry(page), k, 0); + } + if let Some(k) = self.copy_of(page) + && !self.pages.contains_key(&page) + { + self.copies[k].refresh(list, at, n); + self.copies[k].gpu_writes(list, at, n); + self.stats.back += 1; + } + at += n; + } + } + + /// Every ten seconds or so, what was used. fn report(&mut self) { let now = std::time::Instant::now(); let (since, frame) = *self.stats.from.get_or_insert((now, self.frame)); - let seconds = now.duration_since(since).as_secs_f64(); - if seconds < 10.0 { + if now.duration_since(since).as_secs_f64() < 10.0 { return; } let frames = self.frame.wrapping_sub(frame).max(1) as f64; - let (mut ours, mut bytes) = (0, 0); - for (s, own) in &self.copies { - if *own { - ours += 1; - bytes += s.span().1; - } - } let s = std::mem::take(&mut self.stats); tracing::info!( - "title memory by address: {ours} windows ({} MB) and {} title buffers; per frame {:.0} dispatches that read, {:.0} that write, \ - {:.0} of the structure builder, {:.1} pages that had no copy, {:.1} results brought back", - bytes >> 20, - self.copies.len() - ours, + "title memory by address: {} pages ({} MB) in {} arenas, {} copies in all; per frame {:.0} dispatches that read, {:.0} that build, \ + {:.1} pages that had no copy, {:.1} pages turned down, {:.1} results brought back; {:.0} pages looked at, {:.1} KB changed, \ + {:.1} pieces sent whole, {:.2} ms", + self.pages.len(), + (self.pages.len() as u64 * PAGE) >> 20, + self.arenas.len(), + self.copies.len(), s.uses[0] as f64 / frames, s.uses[1] as f64 / frames, - s.uses[2] as f64 / frames, s.faults as f64 / frames, - s.back as f64 / frames + s.unknown as f64 / frames, + s.back as f64 / frames, + s.looked as f64 / frames, + s.changed as f64 / 1024.0 / frames, + s.whole as f64 / frames, + s.micros as f64 / 1000.0 / frames ); self.stats.from = Some((now, self.frame)); } @@ -344,12 +492,32 @@ fn fill(entry: *mut u32, n: usize, offset: u64) { } } +/// Puts what `title` holds into `ours` (what was last taken): the dwords that +/// differ. How many, and whether the whole piece is to be sent again because +/// so many did (or it was never taken). +fn merge(title: &[u8; PIECE], ours: &mut [u8], never: bool) -> (usize, bool) { + if never { + ours.copy_from_slice(title); + return (PIECE / 4, true); + } + if ours == title { + return (0, false); + } + let mut changed = 0; + for (t, o) in title.chunks_exact(4).zip(ours.chunks_exact_mut(4)) { + if t != o { + o.copy_from_slice(t); + changed += 1; + } + } + (changed, changed > PIECE / 16) +} + /// Before a draw whose shader reads title memory by address: what its -/// root arguments name gets its copies (`addresses`: its root views; +/// root arguments name is made ready (`addresses`: its root views; /// `constants`: its root constants, see the module), every numbered copy /// has its view in `heap`'s run and is brought up to date when `list` is -/// submitted (what `use_` writes is copied back after, see the module). -/// None if the host cannot hold it; the draw is then dropped. +/// submitted. None if the host cannot hold it; the draw is then dropped. pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constants: &[u32], use_: Use) -> Option { let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); if guard.is_none() { @@ -361,30 +529,60 @@ pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constan m.frame = frame; m.refused.clear(); m.take_faults(); + let n = m.order.len().div_ceil(SWEEP); + for _ in 0..n { + m.sweep = (m.sweep + 1) % m.order.len(); + let page = m.order[m.sweep]; + m.bring(page, page + 1); + } m.report(); } - m.stats.uses[match use_ { - Use::Reads => 0, - Use::Writes => 1, - Use::Builder { .. } => 2, - }] += 1; + let builds = use_ != Use::Reads; + m.stats.uses[usize::from(builds)] += 1; let numbered = m.copies.len(); - let mut named = Vec::new(); - for &address in addresses { - m.name(address, &mut named); - } + // Once per list and page named: the builder dispatches hundreds of times + // a frame with the same arguments. + const READ: usize = usize::MAX - 0x6d; + let named = |kind: usize, at: u64| list.first_use(usize::MAX - (kind << 26) - (at / PAGE) as usize); // A title address in two constants (low dword, then bits 32 to 39), or - // in one in 256-byte units. A constant that only looks like one names - // memory nothing reads; one that is not the title's memory is refused. + // in one in 256-byte units (the builder's alone). A constant that only + // looks like one names memory nothing reads; one that is not the title's + // memory is refused. + let built = if builds { BUILT } else { PAGE }; for (i, &c) in constants.iter().enumerate() { if let Some(&high) = constants.get(i + 1) - && (1..=0xFF).contains(&high) + && (1..=0x1F).contains(&high) && c >= 0x1_0000 { - m.name(u64::from(c) | u64::from(high) << 32, &mut named); + let at = u64::from(c) | u64::from(high) << 32; + if named(1, at) { + m.ready(at, built); + } } - if c >= 0x0100_0000 { - m.name(u64::from(c) << 8, &mut named); + if builds && (0x0100_0000..0x2000_0000).contains(&c) { + let at = u64::from(c) << 8; + if named(1, at) { + m.ready(at, built); + } + } + } + for &at in addresses.iter().filter(|&&a| a >= 1 << 32) { + if !named(2, at) { + continue; + } + match crate::shadow::in_buffer(at, 1) { + Some((start, len)) if builds && len <= BACK => { + if use_ == (Use::Builds { back: true }) { + m.small(list, start, len); + } + m.ready(at, 1); + m.named_in_upload(at); + } + Some(_) => { + m.ready(at, 1); + m.named_in_upload(at); + } + None => m.ready(at, if builds { VIEW } else { PAGE }), } } let key = std::ptr::from_ref(heap) as usize; @@ -397,74 +595,31 @@ pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constan (base, 0) } }; - for (n, (shadow, _)) in m.copies.iter().enumerate().skip(made as usize) { + for (n, shadow) in m.copies.iter().enumerate().skip(made as usize) { let (_, len) = shadow.span(); heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len); } m.heaps.insert(key, (base, m.copies.len() as u32)); - // Once per list, and for copies numbered since: the builder alone - // dispatches hundreds of times a frame. // shortcut: a copy another list numbers meanwhile is brought up to date // by that list's submission, which may run after this one's. - const READ: usize = usize::MAX - 0x6d; - const NAMED: usize = usize::MAX - 0x1_0000; - const WRITE: usize = usize::MAX - 0x2_0000; - const RESULT: usize = usize::MAX / 2; let first_read = list.first_use(READ); - if first_read { - let (start, len) = m.directory.1.span(); - m.directory.1.refresh(list, start, len); - let sweep = m.swept != frame; - m.swept = frame; - for (shadow, own) in &m.copies { - if sweep || !own { - let (start, len) = shadow.span(); - shadow.refresh(list, start, len); - } - } - list.keep(&m.faults.0); - } else if m.copies.len() > numbered { + let from = if first_read { 0 } else { numbered }; + if first_read || m.copies.len() > numbered { let (start, len) = m.directory.1.span(); m.directory.1.refresh(list, start, len); } - for (shadow, _) in &m.copies[numbered..] { + for shadow in &m.copies[from..] { let (start, len) = shadow.span(); shadow.refresh(list, start, len); } - for &n in &named { - let (shadow, own) = &m.copies[n]; - let (start, len) = shadow.span(); - if *own && list.first_use(NAMED - n) { - shadow.refresh(list, start, len); - } - if use_ == Use::Writes && list.first_use(WRITE - n) { - #[cfg(feature = "diagnostics")] - crate::host::wide_write(start, len, 1); - shadow.gpu_writes(list, start, len); - } + if first_read { + list.keep(&m.faults.0); + #[cfg(feature = "diagnostics")] + m.dump(list, addresses); } - if use_ == (Use::Builder { back: true }) { - for &address in addresses { - let Some((start, len)) = crate::shadow::in_buffer(address, 1).filter(|b| b.1 <= BACK) else { - continue; - }; - if !list.first_use(RESULT + start as usize) { - continue; - } - // The copy or copies its pages are in (it need not fill one). - let mut at = start; - while at < start + len { - let end = (at / PAGE + 1) * PAGE; - let n = end.min(start + len) - at; - if let Some(k) = m.map(at, CELL) { - let shadow = &m.copies[k].0; - shadow.refresh(list, at, n); - shadow.gpu_writes(list, at, n); - m.stats.back += 1; - } - at = end; - } - } + #[cfg(feature = "diagnostics")] + if use_ == Use::Reads { + m.dump.walked(addresses); } let directory = &m.directory.1; Some(Ready { @@ -473,3 +628,123 @@ pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constan base, }) } + +/// `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 +/// programs were given: to look at the structures offline. +#[cfg(feature = "diagnostics")] +mod dump { + use super::*; + + #[derive(Default)] + pub(super) struct Dump { + walked: std::collections::BTreeSet, + /// The frame it is written at, and the copies. + due: Option<(u64, Vec<(ID3D12Resource, usize)>)>, + done: bool, + } + + impl Dump { + pub(super) fn walked(&mut self, addresses: &[u64]) { + if !self.done && self.walked.len() < 64 { + self.walked.extend(addresses); + } + } + } + + fn folder() -> Option<&'static std::path::PathBuf> { + static FOLDER: std::sync::OnceLock> = std::sync::OnceLock::new(); + FOLDER.get_or_init(|| std::env::var_os("VICTORY_MEMORY_DUMP").map(Into::into)).as_ref() + } + + fn turn(buffer: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: the same pointer, not counted; the barrier is + // used while the buffer lives. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } + } + + impl Memory { + /// At a list's first use: the copies are recorded into it. + pub(super) fn dump(&mut self, list: &HostList, _: &[u64]) { + let Some(folder) = folder() else { return }; + if let Some((due, _)) = &self.dump.due { + if self.frame < *due { + return; + } + let copies = self.dump.due.take().map(|d| d.1).unwrap_or_default(); + let mut text = String::new(); + for a in &self.dump.walked { + text += &format!("walked {a:#x}\n"); + } + for (page, held) in &self.pages { + let arena = self.arenas.iter().position(|a| a.0 == held.copy).unwrap_or(usize::MAX); + let at = held.at - self.arenas[arena].1; + text += &format!("{:#x} {arena} {at:#x}\n", page * PAGE); + } + let _ = std::fs::write(folder.join("pages.txt"), text); + for (n, (_, data)) in copies.iter().enumerate() { + // SAFETY: a mapping of an arena's bytes; the copies ran + // frames ago. + let bytes = unsafe { std::slice::from_raw_parts(*data as *const u8, ARENA as usize) }; + let _ = std::fs::write(folder.join(format!("arena-{n}.bin")), bytes); + } + tracing::info!(arenas = copies.len(), "title memory by address: the arenas are written out"); + return; + } + if self.dump.done || !folder.join("go").exists() { + return; + } + self.dump.done = true; + let Some(host) = host() else { return }; + let mut copies = Vec::new(); + for &(n, _) in &self.arenas { + let buffer = &self.copies[n].buffer; + let Some((to, data)) = host.shared_buffer(ARENA) else { break }; + // SAFETY: an open list; live buffers of those sizes. The list + // has not used the arena yet. + unsafe { + list.list.ResourceBarrier(&[turn(buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.list.CopyBufferRegion(&to, 0, buffer, 0, ARENA); + list.list.ResourceBarrier(&[turn(buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); + } + list.keep(&to); + copies.push((to, data as usize)); + } + self.dump.due = Some((self.frame + 12, copies)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_piece_takes_what_changed_and_is_sent_whole_when_much_did() { + let mut title = [7u8; PIECE]; + let mut ours = vec![0u8; PIECE]; + assert_eq!(merge(&title, &mut ours, true), (PIECE / 4, true)); + assert_eq!(ours, title); + assert_eq!(merge(&title, &mut ours, false), (0, false)); + // A dword of it. + title[41] = 8; + assert_eq!(merge(&title, &mut ours, false), (1, false)); + assert_eq!(ours, title); + // Other data. + title[..PIECE / 2].fill(9); + assert_eq!(merge(&title, &mut ours, false), (PIECE / 8, true)); + assert_eq!(ours, title); + } +} diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 93242b7..9f4a90c 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -3587,6 +3587,11 @@ impl Shadow { self.card.is_some() } + /// Offsets `[from, to)` go up again whole, as the CPU's side has them. + pub(crate) fn resend(&self, from: usize, to: usize) { + self.card_changed(from, to); + } + /// The CPU side's bytes at offsets `[from, to)` changed: they go to the /// card's side before the next submission. fn card_changed(&self, from: usize, to: usize) { @@ -4566,16 +4571,14 @@ pub(crate) fn in_buffer(address: u64, len: u64) -> Option<(u64, u64)> { found.map(|(k, e)| (k.0, e.end - k.0)) } -/// A copy of the title memory `[start, start + len)` outside buffers for the -/// programs that find memory by address ([`crate::memory`]), on the card: the -/// structures rays are traced through, read with every step of every ray. +/// A copy of the memory `[start, start + len)` (an arena of +/// [`crate::memory`]'s, its directory, title memory around a small buffer) +/// for the programs that find memory by address, on the card: the structures +/// rays are traced through, read with every step of every ray. /// -/// What shaders write there by address is not brought back to title memory -/// (nothing else reads a structure; the first whole run of the builder wrote -/// garbage over the title's objects), so the copy is the only place that has -/// it. The CPU's side holds the title's bytes as they were last taken, and -/// only dwords the title changed since go up: a page the title writes a part -/// of keeps what shaders wrote in the rest. +/// What shaders write there by address is not brought back, so the copy is +/// the only place that has it. The CPU's side holds the bytes as they were +/// last taken, and only dwords that changed since go up. pub(crate) fn by_address(start: u64, len: u64) -> Option> { let host = host()?; if !cards() || !host.card_ready() { diff --git a/crates/victory-gpu/src/upload.rs b/crates/victory-gpu/src/upload.rs index 7ea3776..d6f60e5 100644 --- a/crates/victory-gpu/src/upload.rs +++ b/crates/victory-gpu/src/upload.rs @@ -133,6 +133,16 @@ impl Drop for Upload { } } +/// The block handed out that holds `address`: its start and bytes (whole +/// [`BLOCK`]s). +pub(crate) fn block(address: usize) -> Option<(usize, usize)> { + let arenas = ARENAS.lock().unwrap_or_else(|e| e.into_inner()); + let arena = arenas.iter().find(|a| (a.at..a.at + a.taken.len() * BLOCK).contains(&address))?; + let first = (address - arena.at) / BLOCK; + let n = arena.taken[first..].iter().take_while(|t| **t).count(); + (n > 0).then_some((arena.at + first * BLOCK, n * BLOCK)) +} + #[cfg(test)] mod tests { use super::*; From f3ba71343155f65d36b7f8968ce5dba5e64d8068 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:14:51 -0600 Subject: [PATCH 322/445] The first copy into a texture the title fills goes over what title memory holds What the copy does not write was whatever the block of the pool held: the atlas of baked decorations (a 2048x2048 BC3 texture of which a bake writes 256x256 at most) drew other textures' bytes over the waitress's face. VICTORY_COPY_OVER_TITLE=0: as before. With a measurement of what a cold texture costs. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/list.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 140b755..84aa3a3 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1023,6 +1023,25 @@ extern "system" fn copy_texture_region( // A depth texture shaders also write: what they wrote, first (the // source above too). list.twin_use(dst.resource, false, true); + // The first copy into a texture of the title's: what it does not + // write is what title memory holds, as on the console. (The host + // copy is cut from a block and held whatever lay there, and no + // upload is made once a copy wrote it: the atlas the title copies + // its baked decorations into, a 2048x2048 BC3 texture of which a + // bake writes 256x256 at most, was drawn over a character's face + // with other textures' bytes wherever nothing was baked, runs n01 and + // textures-1.) + static OVER: std::sync::OnceLock = std::sync::OnceLock::new(); + if *OVER.get_or_init(|| std::env::var_os("VICTORY_COPY_OVER_TITLE").is_none_or(|v| v != "0")) + && crate::texture::title_written(to) + && !crate::texture::host_wrote(dst.resource as usize) + { + crate::texture::upload(list, dst.resource, to); + // (Done before the title's copy writes over it.) + if list.used(dst.resource as usize) { + ensure_state(list, dst.resource, COPY_SOURCE); + } + } // A destination made level by level gets the level's memory ahead // of this list (`crate::tiles`): the title's bake copies each level // of its result into a block-compressed texture of that kind, and From 773b403171e31ae96aa61651f7d92aca60f09a65 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:15:29 -0600 Subject: [PATCH 323/445] Title memory by address: packed structures go up whole when the builder unpacks them; small buffers' pages stay title memory The arenas of run light-3, read offline: 2,833 instances, valid top levels and dynamic structures, three quarters of the streamed ones unpacked right. The rest were unpacked a second time (the same bytes streamed in again do not differ from those last taken), into garbage over their neighbours. And the sizes the title reads of a structure (compaction) never came back where their small buffer lay in an arena's page. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/memory.rs | 163 +++++++++++++++++++++++-------- crates/victory-gpu/src/shadow.rs | 8 ++ 2 files changed, 131 insertions(+), 40 deletions(-) diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 034c244..1e4a952 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -32,9 +32,10 @@ //! stage, so before one of its dispatches the host makes ready what it can //! see the dispatch name: //! -//! - 1 MiB from each root view outside buffers (structures unpacked in place: -//! the title ships them packed and the builder's rehydration stages unpack -//! each once, when it is streamed in); +//! - 1 MiB from each root view outside buffers, and where title memory has a +//! packed ("dehydrated") structure there, all of it: the title ships its +//! structures packed, and the builder's rehydration stages unpack each in +//! place once it is streamed in; //! - 4 MiB from each pair of root constants that is a title address and from //! each root constant that is one in 256-byte units (structures built); //! - the first page of every structure a list's upload memory names @@ -46,8 +47,11 @@ //! (the first whole run of the builder wrote garbage over the title's //! objects). So an arena's page is the only place a structure is whole, and //! title memory must not go over it: of a page the title wrote only the -//! dwords that changed since they were last taken go up, unless a quarter of -//! a 4 KiB piece changed, which is other data streamed in: then all of it. +//! dwords that changed since they were last taken go up. A packed structure +//! goes up whole when the builder comes to it, whatever is known of it: the +//! same bytes streamed in again do not differ from those last taken, and the +//! card holds them unpacked (run light-3: a quarter of the structures +//! unpacked a second time, into garbage all over their neighbours). //! //! shortcut: a page is kept for the rest of the run. //! shortcut: pages a list does not name are looked at again in turn, over @@ -69,8 +73,16 @@ const COPIES: u32 = (1 << 12) - 1; const PAGE: u64 = 1 << 16; /// An arena's bytes. const ARENA: u64 = 64 << 20; -/// The kernel's page: what is sent whole when much of it changed. +/// What is compared at a time. const PIECE: usize = 4096; +/// Pages held, at most (2 GiB). +const MOST: usize = 1 << 15; +/// Pages of title memory with small title buffers in them, at most. +const WINDOWS: usize = 512; +/// The biggest packed structure taken for one. +const PACKED: u64 = 64 << 20; +/// A packed structure not named for so many frames is another one. +const AGAIN: u64 = 8; /// From a root view; from an address in constants. const VIEW: u64 = 1 << 20; const BUILT: u64 = 4 << 20; @@ -115,6 +127,10 @@ struct Memory { /// Their numbers in the order they came, and where the sweep is. order: Vec, sweep: usize, + /// Windows of title memory itself ([`Memory::map`]). + windows: usize, + /// Packed structures the builder came to: the frame it last did. + packed: HashMap, /// Per host view heap (by address): the first slot of its run, and how /// many copies have their view there. heaps: HashMap, @@ -135,10 +151,10 @@ struct Stats { faults: u64, unknown: u64, back: u64, - /// Pages looked at, bytes that changed, pieces sent whole. + /// Pages looked at, bytes that changed, packed structures sent. looked: u64, changed: u64, - whole: u64, + packed: u64, micros: u64, } @@ -181,6 +197,8 @@ impl Memory { pages: HashMap::new(), order: Vec::new(), sweep: 0, + windows: 0, + packed: HashMap::new(), heaps: HashMap::new(), frame: u64::MAX, refused: Default::default(), @@ -283,6 +301,23 @@ impl Memory { fill(self.entry(page), n, start - shadow.span().0); return true; } + // Small title buffers in it: what the builder stores in them comes + // back, so title memory itself. + if self.windows < WINDOWS && crate::shadow::small_buffer_in(start, PAGE, BACK) { + if let Some(shadow) = crate::shadow::by_address(start, PAGE) + && let Some(n) = self.number(shadow) + { + self.windows += 1; + fill(self.entry(page), n, 0); + return true; + } + return false; + } + if self.pages.len() >= MOST { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(MOST, "title memory by address: no more pages are taken; others read zeros")); + return false; + } if self.used == ARENA / PAGE { let Some(at) = crate::upload::reserve(ARENA as usize) else { return false; @@ -350,17 +385,49 @@ impl Memory { crate::host::copy_mapped(title.as_mut_ptr(), from as *const u8, PIECE, false); // SAFETY: a page of an arena of ours, under the mutex. let ours = unsafe { std::slice::from_raw_parts_mut((held.at + piece) as *mut u8, PIECE) }; - let (changed, whole) = merge(&title, ours, never); - self.stats.changed += changed as u64 * 4; - if whole { - self.stats.whole += 1; - shadow.resend(base + piece, base + piece + PIECE); - } + self.stats.changed += merge(&title, ours, never) as u64 * 4; + } + if never { + shadow.resend(base, base + PAGE as usize); } } self.stats.micros += started.elapsed().as_micros() as u64; } + /// If title memory has a packed structure at `address` that the builder + /// comes to anew: all of it has its pages, and goes up as it is there. + fn unpacks(&mut self, address: u64) { + if address & 0xFF != 0 || !self.possible(address / PAGE) { + return; + } + let mut header = [0u8; 8]; + crate::host::copy_mapped(header.as_mut_ptr(), address as *const u8, 8, false); + let Some(len) = packed_len(u64::from_le_bytes(header)) else { + return; + }; + let last = self.packed.insert(address, self.frame); + if last.is_some_and(|f| f + AGAIN >= self.frame) { + return; + } + self.ready(address, len); + let mut title = [0u8; PIECE]; + let mut at = address; + while at < address + len { + let n = (PAGE - at % PAGE).min(address + len - at).min(PIECE as u64) as usize; + if let Some(held) = self.pages.get(&(at / PAGE)) { + let place = held.at + (at % PAGE) as usize; + crate::host::copy_mapped(title.as_mut_ptr(), at as *const u8, n, false); + // SAFETY: a page of an arena of ours, under the mutex. + unsafe { std::slice::from_raw_parts_mut(place as *mut u8, n) }.copy_from_slice(&title[..n]); + let shadow = &self.copies[held.copy]; + let base = place - shadow.span().0 as usize; + shadow.resend(base, base + n); + } + at += n as u64; + } + self.stats.packed += 1; + } + /// The pages shaders found empty since the last frame. fn take_faults(&mut self) { let mut pages = Vec::new(); @@ -427,20 +494,14 @@ impl Memory { } } - /// A title buffer too small to fill its pages, whose results come back: - /// windows of title memory itself around its pages, which go back. + /// A small title buffer whose results come back, if its pages are + /// windows of title memory itself (or a copy of the buffer's own). fn small(&mut self, list: &HostList, start: u64, len: u64) { let mut at = start; while at < start + len { let page = at / PAGE; let n = ((page + 1) * PAGE).min(start + len) - at; - if self.copy_of(page).is_none() - && self.possible(page) - && let Some(shadow) = crate::shadow::by_address(page * PAGE, PAGE) - && let Some(k) = self.number(shadow) - { - fill(self.entry(page), k, 0); - } + self.map(page); if let Some(k) = self.copy_of(page) && !self.pages.contains_key(&page) { @@ -464,7 +525,7 @@ impl Memory { tracing::info!( "title memory by address: {} pages ({} MB) in {} arenas, {} copies in all; per frame {:.0} dispatches that read, {:.0} that build, \ {:.1} pages that had no copy, {:.1} pages turned down, {:.1} results brought back; {:.0} pages looked at, {:.1} KB changed, \ - {:.1} pieces sent whole, {:.2} ms", + {:.1} packed structures ({} seen), {:.2} ms; {} windows", self.pages.len(), (self.pages.len() as u64 * PAGE) >> 20, self.arenas.len(), @@ -476,8 +537,10 @@ impl Memory { s.back as f64 / frames, s.looked as f64 / frames, s.changed as f64 / 1024.0 / frames, - s.whole as f64 / frames, - s.micros as f64 / 1000.0 / frames + s.packed as f64 / frames, + self.packed.len(), + s.micros as f64 / 1000.0 / frames, + self.windows ); self.stats.from = Some((now, self.frame)); } @@ -492,16 +555,24 @@ fn fill(entry: *mut u32, n: usize, offset: u64) { } } +/// The bytes of a packed structure whose first two dwords these are: the +/// version (6) with the marks of a bottom level and of one that is packed, +/// and its size unpacked in 64-byte nodes. +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) +} + /// Puts what `title` holds into `ours` (what was last taken): the dwords that -/// differ. How many, and whether the whole piece is to be sent again because -/// so many did (or it was never taken). -fn merge(title: &[u8; PIECE], ours: &mut [u8], never: bool) -> (usize, bool) { +/// differ. How many. +fn merge(title: &[u8; PIECE], ours: &mut [u8], never: bool) -> usize { if never { ours.copy_from_slice(title); - return (PIECE / 4, true); + return PIECE / 4; } if ours == title { - return (0, false); + return 0; } let mut changed = 0; for (t, o) in title.chunks_exact(4).zip(ours.chunks_exact_mut(4)) { @@ -510,7 +581,7 @@ fn merge(title: &[u8; PIECE], ours: &mut [u8], never: bool) -> (usize, bool) { changed += 1; } } - (changed, changed > PIECE / 16) + changed } /// Before a draw whose shader reads title memory by address: what its @@ -567,6 +638,10 @@ pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constan } } for &at in addresses.iter().filter(|&&a| a >= 1 << 32) { + // (Several structures to a page.) + if builds && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize) { + m.unpacks(at); + } if !named(2, at) { continue; } @@ -732,19 +807,27 @@ mod tests { use super::*; #[test] - fn a_piece_takes_what_changed_and_is_sent_whole_when_much_did() { + fn a_piece_takes_what_changed() { let mut title = [7u8; PIECE]; let mut ours = vec![0u8; PIECE]; - assert_eq!(merge(&title, &mut ours, true), (PIECE / 4, true)); + assert_eq!(merge(&title, &mut ours, true), PIECE / 4); assert_eq!(ours, title); - assert_eq!(merge(&title, &mut ours, false), (0, false)); + assert_eq!(merge(&title, &mut ours, false), 0); // A dword of it. title[41] = 8; - assert_eq!(merge(&title, &mut ours, false), (1, false)); - assert_eq!(ours, title); - // Other data. - title[..PIECE / 2].fill(9); - assert_eq!(merge(&title, &mut ours, false), (PIECE / 8, true)); + assert_eq!(merge(&title, &mut ours, false), 1); assert_eq!(ours, title); } + + #[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)); + // 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); + assert_eq!(packed_len(header(0x8102_0007, 5)), None); + assert_eq!(packed_len(header(0x8102_0006, 0)), None); + assert_eq!(packed_len(header(0x8102_0006, 1 << 21)), None); + } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 9f4a90c..3f2b89d 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -4571,6 +4571,14 @@ pub(crate) fn in_buffer(address: u64, len: u64) -> Option<(u64, u64)> { found.map(|(k, e)| (k.0, e.end - k.0)) } +/// Whether a title buffer of at most `most` bytes lies in `[address, address +/// + len)`, all of it or in part. +pub(crate) fn small_buffer_in(address: u64, len: u64, most: u64) -> bool { + let map = buffers_read(); + map.range((address.saturating_sub(most), 0)..(address + len, 0)) + .any(|(key, entry)| entry.end > address && entry.end - key.0 <= most) +} + /// A copy of the memory `[start, start + len)` (an arena of /// [`crate::memory`]'s, its directory, title memory around a small buffer) /// for the programs that find memory by address, on the card: the structures From 02f36e444003d5f4e7bcb7ad15b0cda85df0771c Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:27:38 -0600 Subject: [PATCH 324/445] Views are made beside the heaps the card sees and copied in whole Measured on the RX 7900 XTX (indirect::tests::descriptors_written_under_readers): a thread that makes texture views in a slot of a shader-visible heap lets the card see a descriptor that is neither the old one nor the new one in 4 % of its reads (35 of 822 million: the driver clears it and fills it step by step). Copied from a CPU-only heap: none in 8,582 million reads, and three times as fast (51 ns against 149). Title threads and our passes rewrite slots while submissions run whose shaders pick them; three device losses of 2026-11-25 (play-1125-0203, n02, n03) were reads of memory no view names. Every slot of the host heaps (views, raw twins, null views, constant buffers, samplers) is now made in a slot of the thread's own in a heap the card does not see and copied in. VICTORY_VIEW_COPY=0: made in place, as before. A raw twin whose view begins between two multiples of 16 (35 a frame, left as the title's unbounded view) is made from the 16 bytes below and its descriptor moved on, if it is the one AMD's raw buffer descriptors are; null otherwise. indirect::tests::textures_read_in_another_dimension (a measurement): a view read in another dimension or level than its own gives zeros or its own texels: not a cause. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 7 +- crates/victory-gpu/src/descriptor/host.rs | 362 ++++++++++++++++--- crates/victory-gpu/src/indirect.rs | 407 ++++++++++++++++++++++ 3 files changed, 723 insertions(+), 53 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 256b8e5..2652ad4 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -286,12 +286,13 @@ pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 6] = [const { std::sync /// Nothing while no heap page changed. #[cfg(windows)] pub(crate) fn sync_line(frames: f64) { - let [twins, as_is] = [0, 1].map(|i| host::TWINS[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + let [twins, moved, lost] = [0, 1, 2].map(|i| host::TWINS[i].swap(0, std::sync::atomic::Ordering::Relaxed)); if twins > 0 { tracing::info!( - "raw twins of buffer views made per frame (VICTORY_RAW_VIEWS=0: none): {:.0}, of them {:.1} as the title's view is (it does not begin on 16 bytes)", + "raw twins of buffer views made per frame (VICTORY_RAW_VIEWS=0: none): {:.0}, of them {:.1} that do not begin on 16 bytes ({:.1} null)", twins as f64 / frames, - as_is as f64 / frames + moved as f64 / frames, + lost as f64 / frames ); } let [pages, looked, mirrored, micros, tabled, later] = [0, 1, 2, 3, 4, 5].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 03187e5..2a6372f 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1252,7 +1252,8 @@ impl HostHeap { /// A plain point sampler at slot `index`, for sampler slots without a /// view. fn null_sampler(&self, index: u32) { - null_sampler(self.cpu(index)); + null_sampler(self.at(index)); + self.put(index); } } @@ -1662,7 +1663,8 @@ impl HostHeap { let Some(view) = view_at(key as u32, (key >> 32) as u32) else { continue; }; - if let Some(kept) = make(&view, self.cpu(slot)) { + if let Some(kept) = make(&view, self.at(slot)) { + self.put(slot); self.keep(slot, kept); remade += 1; } @@ -1770,7 +1772,8 @@ impl HostHeap { FLIPPED[1].fetch_add(1, Relaxed); continue; }; - if let Some(kept) = make(&view, self.cpu(f.index)) { + if let Some(kept) = make(&view, self.at(f.index)) { + self.put(f.index); *shown = f.key; self.keep(f.index, kept); flipped += 1; @@ -1799,9 +1802,10 @@ impl HostHeap { return; } match view_at(key as u32, (key >> 32) as u32) { - Some(view) => null_for(&view, self.cpu(index)), - None => null_view(self.cpu(index)), + Some(view) => null_for(&view, self.at(index)), + None => null_view(self.at(index)), } + self.put(index); self.clear_twin(index); self.keep(index, None); } @@ -2027,10 +2031,11 @@ impl HostHeap { /// Makes slot `index` (a dynamic one) from `view`; a null view if the /// host cannot. pub(crate) fn make_at(&self, index: u32, view: &View) { - let kept = make(view, self.cpu(index)); + let kept = make(view, self.at(index)); if kept.is_none() { - null_for(view, self.cpu(index)); + null_for(view, self.at(index)); } + self.put(index); self.keep(index, kept.flatten()); } @@ -2039,14 +2044,15 @@ impl HostHeap { if self.sampler { self.null_sampler(index); } else { - null_view(self.cpu(index)); + null_view(self.at(index)); + self.put(index); } self.keep(index, None); } /// Where the raw twin of title slot `index` is. fn twin(&self, index: u32) -> Option { - (index < self.twins.len() as u32).then(|| self.cpu(self.raw + index)) + (index < self.twins.len() as u32).then(|| staged(self.sampler, 1).unwrap_or_else(|| self.cpu(self.raw + index))) } /// The raw twin of title slot `index` is a null view again. @@ -2054,7 +2060,8 @@ impl HostHeap { if let Some(made) = self.twins.get(index as usize) && made.swap(false, std::sync::atomic::Ordering::Relaxed) { - null_buffer_view(self.cpu(self.raw + index)); + null_buffer_view(self.at(self.raw + index)); + self.put(self.raw + index); } } @@ -2098,15 +2105,17 @@ impl HostHeap { // SAFETY: a slot of our heap and a live buffer covering the range. unsafe { host.device - .CreateShaderResourceView(buffer, Some(&desc), self.cpu(index)) + .CreateShaderResourceView(buffer, Some(&desc), self.at(index)) }; + self.put(index); self.keep(index, Some(buffer.clone())); } /// Makes slot `index` (a dynamic one) a raw buffer view that reads /// zeros. pub(crate) fn null_raw_at(&self, index: u32) { - null_buffer_view(self.cpu(index)); + null_buffer_view(self.at(index)); + self.put(index); self.keep(index, None); } @@ -2136,9 +2145,10 @@ impl HostHeap { buffer, None::<&ID3D12Resource>, Some(&desc), - self.cpu(index), + self.at(index), ) }; + self.put(index); self.keep(index, Some(buffer.clone())); } @@ -2163,9 +2173,10 @@ impl HostHeap { None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&desc), - self.cpu(index), + self.at(index), ) }; + self.put(index); self.keep(index, None); } @@ -2198,13 +2209,47 @@ impl HostHeap { // SAFETY: a slot of our heap; the memory is the caller's. unsafe { host.device - .CreateConstantBufferView(Some(&desc), self.cpu(index)) + .CreateConstantBufferView(Some(&desc), self.at(index)) }; + self.put(index); // After the descriptor: what it showed is let go when nothing shows // it any more. self.keep(index, holds.then(|| buffer.clone())); } + /// Where a descriptor for slot `index` is made, then [`HostHeap::put`]: + /// a slot of this thread's in a heap the card does not see + /// ([`staged`]), or the slot itself. + fn at(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { + staged(self.sampler, 0).unwrap_or_else(|| self.cpu(index)) + } + + /// The descriptor this thread made last ([`HostHeap::at`]) goes to slot + /// `index`. + fn put(&self, index: u32) { + self.copy_to(index, 0); + } + + /// The raw twin this thread made last goes to that of slot `index`. + fn put_twin(&self, index: u32) { + if self.twin(index).is_some() { + self.copy_to(self.raw + index, 1); + } + } + + fn copy_to(&self, to: u32, which: u32) { + let (Some(from), Some(host)) = (staged(self.sampler, which), host()) else { + return; // made in place + }; + let kind = if self.sampler { + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER + } else { + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV + }; + // SAFETY: a slot of our heap, and one of this thread's heap slots. + unsafe { host.device.CopyDescriptorsSimple(1, self.cpu(to), from, kind) }; + } + fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { D3D12_CPU_DESCRIPTOR_HANDLE { ptr: self.cpu + index as usize * self.step as usize, @@ -2371,12 +2416,16 @@ impl HostHeap { let kept = if later { None } else { - make_twinned(&view, self.cpu(index), self.twin(index)) + make_twinned(&view, self.at(index), self.twin(index)) }; if kept.is_none() && !self.sampler { - null_for(&view, self.cpu(index)); + null_for(&view, self.at(index)); + } + if kept.is_some() || !self.sampler { + self.put(index); } if kept.is_some() && twinned(&view) { + self.put_twin(index); if let Some(made) = self.twins.get(index as usize) { made.store(true, std::sync::atomic::Ordering::Relaxed); } @@ -2445,6 +2494,90 @@ impl HostHeap { } } +/// Slots of this thread's own in heaps the card does not see, two of views +/// and two of samplers (`which` 0 or 1): descriptors are made there and +/// copied whole into the heaps it does see. Made in place they are seen half +/// written: an RX 7900 XTX saw a texture of no size in 4 % of its reads of +/// slots whose views a thread made over and over (the driver clears the +/// descriptor and fills it step by step), and none in 8,500 million with the +/// same descriptors copied, three times as fast +/// (`indirect::tests::descriptors_written_under_readers`). Title threads and +/// our passes rewrite slots while submissions run whose shaders pick them; +/// three device losses of 2026-11-25 (play-1125-0203, n02, n03) were reads of +/// memory no view names. `VICTORY_VIEW_COPY=0`: made in place, as before. +fn staged(sampler: bool, which: u32) -> Option { + /// Threads at a time that have slots; more make views in place. + const THREADS: u32 = 4096; + struct Stage { + starts: [usize; 2], + steps: [usize; 2], + _heaps: [ID3D12DescriptorHeap; 2], + } + // SAFETY: descriptor heaps are free-threaded; each thread has slots of + // its own. + unsafe impl Send for Stage {} + // SAFETY: as above. + unsafe impl Sync for Stage {} + static STAGE: std::sync::OnceLock> = std::sync::OnceLock::new(); + /// Places given back, and how many were ever given out. + static PLACES: Mutex<(Vec, u32)> = Mutex::new((Vec::new(), 0)); + struct Place(Option); + impl Drop for Place { + fn drop(&mut self) { + if let Some(place) = self.0 { + PLACES.lock().unwrap_or_else(|e| e.into_inner()).0.push(place); + } + } + } + thread_local! { + static PLACE: Place = { + let mut places = PLACES.lock().unwrap_or_else(|e| e.into_inner()); + Place(places.0.pop().or_else(|| { + (places.1 < THREADS).then(|| { + places.1 += 1; + places.1 - 1 + }) + })) + }; + } + let stage = STAGE + .get_or_init(|| { + if std::env::var_os("VICTORY_VIEW_COPY").is_some_and(|v| v == "0") { + return None; + } + let host = host()?; + let make = |kind: D3D12_DESCRIPTOR_HEAP_TYPE| -> Option { + // SAFETY: plain heap creation. + unsafe { + host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: 2 * THREADS, + ..Default::default() + }) + } + .inspect_err(|e| tracing::warn!(error = %e, "no heap to make views in: they are made in place")) + .ok() + }; + let kinds = [D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER]; + let heaps = [make(kinds[0])?, make(kinds[1])?]; + // SAFETY: live heaps, plain queries. + let (starts, steps) = unsafe { + ( + [0, 1].map(|i: usize| heaps[i].GetCPUDescriptorHandleForHeapStart().ptr), + kinds.map(|kind| host.device.GetDescriptorHandleIncrementSize(kind) as usize), + ) + }; + Some(Stage { starts, steps, _heaps: heaps }) + }) + .as_ref()?; + // (A thread that is ending has none any more.) + let place = PLACE.try_with(|p| p.0).ok().flatten()?; + let kind = usize::from(sampler); + Some(D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: stage.starts[kind] + (2 * place + which) as usize * stage.steps[kind], + }) +} + /// Logs `what` the first time it happens. macro_rules! once { ($($arg:tt)*) => {{ @@ -2671,14 +2804,46 @@ fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: .is_some_and(|end| end <= width) } -/// Raw twins ([`raw_twins`]) made since the last frame line, and those of them that had -/// to be views as the title's slot has them (a raw view begins on 16 bytes). -pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +/// Raw twins ([`raw_twins`]) made since the last frame line, and those of them that +/// do not begin on 16 bytes, as a raw view must ([`move_raw`]), and those of +/// these that could not be moved there (null). +pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Moves the raw view at `at`, a slot of our heaps the card does not see, +/// which shows `bytes` from `start` on (GPU address), `by` bytes on: for a +/// twin whose view begins between two multiples of 16, where the host makes +/// no raw view. An AMD descriptor of a raw buffer is its address (48 bits), +/// its bytes and flags; only one that says just that is changed, and only +/// where what the handle points at is the descriptor. False: not moved. +fn move_raw(at: D3D12_CPU_DESCRIPTOR_HANDLE, start: u64, bytes: u32, by: u32) -> bool { + if !by.is_multiple_of(4) || by >= bytes { + return false; + } + let mut words = [0u8; 16]; + if !crate::host::read_into(at.ptr as *const u8, &mut words) { + return false; + } + let word = |i: usize| u32::from_le_bytes([words[4 * i], words[4 * i + 1], words[4 * i + 2], words[4 * i + 3]]); + let address = u64::from(word(0)) | u64::from(word(1)) << 32; + if address != start || word(2) != bytes || start >> 48 != 0 { + return false; + } + let moved = start + u64::from(by); + // SAFETY: this thread's own slot (it has slots of its own: the caller + // asks only for those), read just now. + unsafe { + let words = at.ptr as *mut u32; + words.write(moved as u32); + words.add(1).write((moved >> 32) as u32); + words.add(2).write(bytes - by); + } + true +} /// The bytes a buffer view the host takes ([`buffer_view_ok`]) shows as a raw -/// view (first dword, dwords), if it begins where one can; of a buffer of -/// `width` bytes. -fn twin_window(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> Option<(u64, u32)> { +/// view (first dword, dwords, and the bytes past that dword it begins: a raw +/// view begins on 16 bytes); of a buffer of `width` bytes. +fn twin_window(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> Option<(u64, u32, u32)> { use std::sync::atomic::Ordering::Relaxed; TWINS[0].fetch_add(1, Relaxed); let element = if raw { @@ -2688,15 +2853,17 @@ fn twin_window(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bo } else { crate::resource::element(format.0 as u32).map_or(0, |(bytes, _)| bytes) }; - let start = first * element; - let dwords = (u64::from(count) * element).div_ceil(4).min((width - start.min(width)) / 4); - let window = (start % 16 == 0 && dwords > 0) - .then(|| u32::try_from(dwords).ok().map(|dwords| (start / 4, dwords))) - .flatten(); - if window.is_none() { + let (start, end) = (first * element, ((first + u64::from(count)) * element).next_multiple_of(4)); + let end = end.min(width & !3); + let from = start & !15; + if end <= start { + return None; + } + let dwords = u32::try_from((end - from) / 4).ok()?; + if from != start { TWINS[1].fetch_add(1, Relaxed); } - window + Some((from / 4, dwords, (start - from) as u32)) } fn buffer_srv( @@ -2776,7 +2943,8 @@ fn buffer_srv( .CreateShaderResourceView(&shadow.buffer, Some(&desc), at) }; if let Some(twin) = twin { - if let Some((first, count)) = twin_window(desc.Format, first, count, stride, raw, width) { + let window = twin_window(desc.Format, first, count, stride, raw, width); + if let Some((first, count, by)) = window { desc.Format = DXGI_FORMAT_R32_TYPELESS; desc.Anonymous.Buffer = D3D12_BUFFER_SRV { FirstElement: first, @@ -2784,12 +2952,19 @@ fn buffer_srv( StructureByteStride: 0, Flags: D3D12_BUFFER_SRV_FLAG_RAW, }; + // SAFETY: a live buffer and a slot of our heap. + let start = unsafe { + host.device + .CreateShaderResourceView(&shadow.buffer, Some(&desc), twin); + shadow.buffer.GetGPUVirtualAddress() + first * 4 + }; + if by > 0 && !(staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) && move_raw(twin, start, count.saturating_mul(4), by)) { + TWINS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + null_buffer_view(twin); + } + } else { + null_buffer_view(twin); } - // SAFETY: a live buffer and a slot of our heap. - unsafe { - host.device - .CreateShaderResourceView(&shadow.buffer, Some(&desc), twin) - }; } Some(Some(shadow.buffer.clone())) } @@ -2891,7 +3066,8 @@ fn buffer_uav( .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) }; if let Some(twin) = twin { - if let Some((first, count)) = twin_window(desc.Format, first, count, stride, raw, width) { + let window = twin_window(desc.Format, first, count, stride, raw, width); + if let Some((first, count, by)) = window { desc.Format = DXGI_FORMAT_R32_TYPELESS; desc.Anonymous.Buffer = D3D12_BUFFER_UAV { FirstElement: first, @@ -2900,12 +3076,19 @@ fn buffer_uav( CounterOffsetInBytes: 0, Flags: D3D12_BUFFER_UAV_FLAG_RAW, }; + // SAFETY: a live buffer and a slot of our heap. + let start = unsafe { + host.device + .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), twin); + shadow.buffer.GetGPUVirtualAddress() + first * 4 + }; + if by > 0 && !(staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) && move_raw(twin, start, count.saturating_mul(4), by)) { + TWINS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + null_buffer_view(twin); + } + } else { + null_buffer_view(twin); } - // SAFETY: a live buffer and a slot of our heap. - unsafe { - host.device - .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), twin) - }; } Some(Some(shadow.buffer.clone())) } @@ -3709,15 +3892,94 @@ mod tests { #[test] fn raw_twins_show_the_views_bytes() { let (u16s, u32s, none) = (DXGI_FORMAT(57), DXGI_FORMAT(42), DXGI_FORMAT_UNKNOWN); - assert_eq!(twin_window(u32s, 4, 10, 0, false, 4096), Some((4, 10))); - assert_eq!(twin_window(u16s, 8, 7, 0, false, 4096), Some((4, 4))); + assert_eq!(twin_window(u32s, 4, 10, 0, false, 4096), Some((4, 10, 0))); + assert_eq!(twin_window(u16s, 8, 7, 0, false, 4096), Some((4, 4, 0))); // the last dword would reach past the buffer - assert_eq!(twin_window(u16s, 8, 7, 0, false, 30), Some((4, 3))); - assert_eq!(twin_window(none, 2, 3, 24, false, 4096), Some((12, 18))); - assert_eq!(twin_window(DXGI_FORMAT_R32_TYPELESS, 8, 5, 0, true, 4096), Some((8, 5))); - // where no raw view begins: the view as it is - assert_eq!(twin_window(none, 1, 3, 24, false, 4096), None); - assert_eq!(twin_window(u32s, 1, 10, 0, false, 4096), None); + assert_eq!(twin_window(u16s, 8, 7, 0, false, 30), Some((4, 3, 0))); + assert_eq!(twin_window(none, 2, 3, 24, false, 4096), Some((12, 18, 0))); + assert_eq!(twin_window(DXGI_FORMAT_R32_TYPELESS, 8, 5, 0, true, 4096), Some((8, 5, 0))); + // where no raw view begins: from the 16 bytes below + assert_eq!(twin_window(none, 1, 3, 24, false, 4096), Some((4, 20, 8))); + assert_eq!(twin_window(u32s, 1, 10, 0, false, 4096), Some((0, 11, 4))); + assert_eq!(twin_window(u32s, 1, 10, 0, false, 4), None); + } + + /// What a slot is made as is made beside the heap and copied in whole: the + /// slot's descriptor is the one the view has, and each thread makes its + /// own. + #[test] + fn views_are_made_beside_the_heap_and_copied_in() { + let Some(host) = host() else { + return; // no host GPU here + }; + let Some(heap) = HostHeap::new(false, 4) else { + return; + }; + let (Some(a), Some(b)) = (staged(false, 0), staged(false, 1)) else { + return; + }; + assert_ne!(a.ptr, b.ptr); + assert_ne!(Some(a.ptr), std::thread::spawn(|| staged(false, 0).map(|h| h.ptr)).join().unwrap()); + let (buffer, _) = host.shared_buffer(1 << 16).unwrap(); + let index = heap.dynamic(1).unwrap(); + let bytes = |at: D3D12_CPU_DESCRIPTOR_HANDLE| { + let mut bytes = [0u8; 32]; + crate::host::read_into(at.ptr as *const u8, &mut bytes).then_some(bytes) + }; + heap.raw_at(index, &buffer, 64, 1024); + let (slot, beside) = (bytes(heap.cpu(index)), bytes(staged(false, 0).unwrap())); + assert_eq!(slot, beside, "copied as it was made"); + heap.null_raw_at(index); + assert_ne!(bytes(heap.cpu(index)), slot, "another view since"); + // SAFETY: a plain query. + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + } + + /// A raw view moved on by some dwords says so in its descriptor, on a + /// card whose descriptors are what we take them for; on another nothing + /// is changed. + #[test] + fn a_raw_view_is_moved_only_where_its_descriptor_says_where_it_is() { + let (Some(host), Some(at)) = (host(), staged(false, 1)) else { + return; // no host GPU here + }; + let (buffer, _) = host.shared_buffer(1 << 16).unwrap(); + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: 8, + NumElements: 100, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }, + }, + }; + // SAFETY: this thread's slot, a live buffer. + let start = unsafe { + host.device.CreateShaderResourceView(&buffer, Some(&desc), at); + buffer.GetGPUVirtualAddress() + 32 + }; + let words = || { + let mut bytes = [0u8; 32]; + assert!(crate::host::read_into(at.ptr as *const u8, &mut bytes)); + bytes + }; + let before = words(); + assert!(!move_raw(at, start + 16, 400, 8), "another address"); + assert!(!move_raw(at, start, 404, 8), "another size"); + assert!(!move_raw(at, start, 400, 2), "not a dword"); + assert_eq!(words(), before); + if move_raw(at, start, 400, 8) { + let moved = words(); + assert_eq!(moved[..8], (start + 8).to_le_bytes()); + assert_eq!(moved[8..12], 392u32.to_le_bytes()); + assert_eq!(moved[12..], before[12..]); + } else { + assert_eq!(words(), before); + } } /// Views that begin where no host view can: raw ones off 16 bytes, diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 86e68fb..60b645c 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -1114,6 +1114,413 @@ void main(uint3 id : SV_DispatchThreadID, uint g : SV_GroupIndex) { println!("device: {:?}", unsafe { gpu.device.GetDeviceRemovedReason() }); } + /// Whether the card can read a texture's descriptor half written + /// (ignored: a measurement of the card, `VICTORY_BENCH_S` seconds a way, + /// 5). Two slots change between a texture of 64x64 and one of 2048x2048 + /// as fast as a thread can write them, while groups that each load the + /// descriptor anew ask its size and read its last texel: size and texel + /// of two textures are one descriptor half written. (Both lie in one heap + /// that is there as a whole: a read past the small one finds memory.) + #[test] + #[ignore] + fn descriptors_written_under_readers() { + let Some(mut gpu) = WarpHarness::on(std::env::var_os("VICTORY_BENCH_WARP").is_some()) else { + return; + }; + let seconds = std::env::var("VICTORY_BENCH_S").ok().and_then(|v| v.parse().ok()).unwrap_or(5u64); + const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=1,b0), DescriptorTable(SRV(t0,numDescriptors=2,flags=DESCRIPTORS_VOLATILE)), UAV(u0)" +cbuffer C : register(b0) { uint odd; } +Texture2D t[2] : register(t0); +RWByteAddressBuffer o : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { + uint w, h, n; + uint which = (g.x + odd) & 1; + t[which].GetDimensions(0, w, h, n); + uint r = (uint)(t[which].Load(int3(w - 1, h - 1, 0)).x * 255.0 + 0.5); + // 0: small, 1: large, 2: no size of the two, 3: small with another texel, 4: large with another + uint kind = (w == 64 && h == 64) ? (r == 17 ? 0 : 3) : (w == 2048 && h == 2048) ? (r == 34 ? 1 : 4) : 2; + if (i == 0) { + uint was; + o.InterlockedAdd(kind * 4, 1, was); + if (kind > 1) { o.Store(32, w); o.Store(36, h); o.Store(40, r); } + } +} +"#; + let pass = compile_cs(&gpu.device, SOURCE).expect("the pass must compile"); + let texture = |size: u64| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: size, + Height: size as u32, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT(28), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + // SAFETY: plain creation; each texture in its own half of the heap. + let (heap, textures) = unsafe { + let mut heap: Option = None; + gpu.device + .CreateHeap( + &D3D12_HEAP_DESC { + SizeInBytes: 64 << 20, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }, + &mut heap, + ) + .unwrap(); + let heap = heap.unwrap(); + let textures = [(0u64, 64u64), (32 << 20, 2048)].map(|(at, size)| { + let mut made: Option = None; + gpu.device + .CreatePlacedResource(&heap, at, &texture(size), D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made) + .unwrap(); + made.unwrap() + }); + (heap, textures) + }; + // Fill them: 17 and 34 in every byte. + for (texture, (size, byte)) in textures.iter().zip([(64u32, 17u8), (2048, 34)]) { + let pitch = size * 4; + let (from, data, _) = gpu.shared_buffer(u64::from(pitch) * u64::from(size)); + // SAFETY: the mapping holds the bytes; an open list, live resources. + unsafe { + std::ptr::write_bytes(data, byte, (pitch * size) as usize); + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&from), + 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: DXGI_FORMAT(28), + Width: size, + Height: size, + Depth: 1, + RowPitch: pitch, + }, + }, + }, + }; + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(texture), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + gpu.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + gpu.list.ResourceBarrier(&[crate::host::transition( + texture, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + } + gpu.submit_and_wait(); + } + let view_heap = |visible: bool| -> ID3D12DescriptorHeap { + // SAFETY: plain heap creation. + unsafe { + gpu.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 4, + Flags: if visible { D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE } else { D3D12_DESCRIPTOR_HEAP_FLAG_NONE }, + NodeMask: 0, + }) + } + .unwrap() + }; + let (shown, kept) = (view_heap(true), view_heap(false)); + // SAFETY: live heaps. + let (to, from, step) = unsafe { + ( + shown.GetCPUDescriptorHandleForHeapStart().ptr, + kept.GetCPUDescriptorHandleForHeapStart().ptr, + gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize, + ) + }; + let at = |base: usize, i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: base + i * step }; + for (i, texture) in textures.iter().enumerate() { + // SAFETY: slots of our heaps, live textures. + unsafe { + gpu.device.CreateShaderResourceView(texture, None, at(from, i)); + gpu.device.CreateShaderResourceView(texture, None, at(to, i)); + } + } + let bytes = |base: usize, i: usize| { + // SAFETY: a heap's handle; what it points at is read if it is memory. + let mut out = vec![0u8; step]; + crate::host::read_into((base + i * step) as *const u8, &mut out).then_some(out) + }; + println!("step {step}, the heaps' handles point at {:#x} and {:#x} (shown, kept)", to, from); + for i in 0..2 { + println!(" shown {i}: {:02x?}", bytes(to, i)); + println!(" kept {i}: {:02x?}", bytes(from, i)); + } + let same = bytes(to, 0).is_some() && bytes(to, 0) == bytes(from, 0) && bytes(to, 1) == bytes(from, 1); + println!("the shown heap's memory is the descriptors' own bytes: {same}"); + let images = [bytes(from, 0), bytes(from, 1)]; + // SAFETY: a live heap. + let table = unsafe { shown.GetGPUDescriptorHandleForHeapStart() }; + for way in ["view creation", "copies from a CPU heap", "one 32 byte store"] { + if way.starts_with("one") && !(same && step == 32) { + continue; + } + let (_out, out_ptr, out_gpu) = gpu.shared_buffer(1 << 12); + // SAFETY: the mapping. + unsafe { std::ptr::write_bytes(out_ptr, 0, 1 << 12) }; + let stop = std::sync::atomic::AtomicBool::new(false); + let writes = std::sync::atomic::AtomicU64::new(0); + std::thread::scope(|scope| { + let device = gpu.device.clone(); + let (stop, writes, textures, images) = (&stop, &writes, &textures, &images); + scope.spawn(move || { + let mut k = 0usize; + while !stop.load(std::sync::atomic::Ordering::Relaxed) { + for slot in 0..2 { + let which = (k + slot) & 1; + // SAFETY: slots of our heaps, live textures. + unsafe { + match way.as_bytes()[0] { + b'v' => device.CreateShaderResourceView(&textures[which], None, at(to, slot)), + b'c' => device.CopyDescriptorsSimple( + 1, + at(to, slot), + at(from, which), + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + ), + _ => store32(to + slot * step, images[which].as_deref().unwrap()), + } + } + } + k += 1; + writes.fetch_add(2, std::sync::atomic::Ordering::Relaxed); + } + }); + let started = std::time::Instant::now(); + let mut odd = 0u32; + while started.elapsed().as_secs() < seconds { + // SAFETY: our open list, live objects. + unsafe { + gpu.list.SetDescriptorHeaps(&[Some(shown.clone())]); + gpu.list.SetComputeRootSignature(&pass.root); + gpu.list.SetPipelineState(&pass.pso); + gpu.list.SetComputeRootDescriptorTable(1, table); + gpu.list.SetComputeRootUnorderedAccessView(2, out_gpu); + for _ in 0..8 { + gpu.list.SetComputeRoot32BitConstants(0, 1, (&raw const odd).cast(), 0); + gpu.list.Dispatch(65_535, 1, 1); + odd += 1; + } + } + gpu.submit_and_wait(); + } + stop.store(true, std::sync::atomic::Ordering::Relaxed); + }); + // SAFETY: the mapping, the card is done. + let found: Vec = (0..11).map(|i| unsafe { out_ptr.cast::().add(i).read_volatile() }).collect(); + println!( + "{way}: {} writes; groups that saw the small texture {}, the large {}; no size of the two {}, the small size with another texel {}, the large size with another texel {}; the last such: {}x{} texel {}", + writes.load(std::sync::atomic::Ordering::Relaxed), + found[0], + found[1], + found[2], + found[3], + found[4], + found[8], + found[9], + found[10] + ); + // SAFETY: a plain query. + println!(" device: {:?}", unsafe { gpu.device.GetDeviceRemovedReason() }); + } + drop(heap); + } + + /// 32 bytes to `to` (32 byte aligned) in one store, then a fence. + /// + /// # Safety + /// `to` is 32 bytes of memory that may be written. + unsafe fn store32(to: usize, bytes: &[u8]) { + #[target_feature(enable = "avx")] + unsafe fn store(to: usize, bytes: *const u8) { + use std::arch::x86_64::*; + // SAFETY: the caller's. + unsafe { + _mm256_stream_si256(to as *mut __m256i, _mm256_loadu_si256(bytes.cast())); + _mm_sfence(); + } + } + assert!(std::is_x86_feature_detected!("avx") && bytes.len() == 32 && to.is_multiple_of(32)); + // SAFETY: asked for above; the caller's memory. + unsafe { store(to, bytes.as_ptr()) } + } + + /// What a texture read in another dimension than its view's gives + /// (ignored: a measurement of the card): a view of a small 2D texture + /// read as an array, a volume and a cube, and a small volume read as 2D, + /// far out. The texture lies at the start of a heap whose other megabytes + /// hold other bytes: a texel of those is a read past the texture. + #[test] + #[ignore] + fn textures_read_in_another_dimension() { + let Some(mut gpu) = WarpHarness::on(std::env::var_os("VICTORY_BENCH_WARP").is_some()) else { + return; + }; + const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=2,b0), DescriptorTable(SRV(t0,numDescriptors=4,flags=DESCRIPTORS_VOLATILE)), UAV(u0), StaticSampler(s0,filter=FILTER_MIN_MAG_MIP_POINT,addressU=TEXTURE_ADDRESS_WRAP,addressV=TEXTURE_ADDRESS_WRAP,addressW=TEXTURE_ADDRESS_WRAP)" +cbuffer C : register(b0) { uint how; uint far; } +Texture2D flat_ : register(t0); +Texture2DArray layers : register(t1); +Texture3D volume : register(t2); +TextureCubeArray cube : register(t3); +SamplerState s : register(s0); +RWByteAddressBuffer o : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 t : SV_DispatchThreadID) { + uint2 at = uint2(t.x & 7, t.x >> 3); + float4 c = 0; + if (how == 0) c = flat_.Load(int3(at, 0)); + if (how == 1) c = layers.Load(int4(at, far, 0)); + if (how == 2) c = volume.Load(int4(at, far, 0)); + if (how == 3) c = layers.SampleLevel(s, float3((at + 0.5) / 64, far), 0); + if (how == 4) c = volume.SampleLevel(s, float3((at + 0.5) / 64, (far + 0.5) / 4096.0), 0); + if (how == 5) c = cube.SampleLevel(s, float4(1, (at + 0.5) / 64, far), 0); + if (how == 6) c = flat_.Load(int3(at, far)); + uint r = (uint)(c.x * 255.0 + 0.5), was; + // the texture's own bytes, zeros, anything else + o.InterlockedAdd(r == 17 ? 0 : r == 0 ? 4 : 8, 1, was); + if (r != 17 && r != 0) o.Store(12, r); +} +"#; + let pass = compile_cs(&gpu.device, SOURCE).expect("the pass must compile"); + // SAFETY: plain creation, each thing in its own part of the heap. + let (_heap, small) = unsafe { + let mut heap: Option = None; + gpu.device + .CreateHeap( + &D3D12_HEAP_DESC { + SizeInBytes: 256 << 20, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }, + &mut heap, + ) + .unwrap(); + let heap = heap.unwrap(); + let place = |at: u64, size: u64| { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: size, + Height: size as u32, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT(28), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let mut made: Option = None; + gpu.device + .CreatePlacedResource(&heap, at, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made) + .unwrap(); + made.unwrap() + }; + let small = place(0, 64); + // The rest: 34 in every byte. + let mut fill: Vec<(ID3D12Resource, u32, u8)> = vec![(small.clone(), 64, 17)]; + for k in 0..15u64 { + fill.push((place((1 + k) << 24, 2048), 2048, 34)); + } + for k in 1..16u64 { + fill.push((place(k << 20, 512), 512, 34)); + } + for (texture, size, byte) in fill { + let pitch = size * 4; + let (from, data, _) = gpu.shared_buffer(u64::from(pitch) * u64::from(size)); + std::ptr::write_bytes(data, byte, (pitch * size) as usize); + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&from), + 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: DXGI_FORMAT(28), + Width: size, + Height: size, + Depth: 1, + RowPitch: pitch, + }, + }, + }, + }; + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&texture), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + gpu.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + gpu.list.ResourceBarrier(&[crate::host::transition( + &texture, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + gpu.submit_and_wait(); + } + (heap, small) + }; + // SAFETY: plain heap creation; slots of it, a live texture. + let heap: ID3D12DescriptorHeap = unsafe { + let heap: ID3D12DescriptorHeap = gpu + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 4, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .unwrap(); + let step = gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + for i in 0..4 { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: heap.GetCPUDescriptorHandleForHeapStart().ptr + i * step }; + // A 2D view of the small texture in every slot. + gpu.device.CreateShaderResourceView(&small, None, at); + } + heap + }; + for (how, name) in + ["2D", "array, loaded", "volume, loaded", "array, sampled", "volume, sampled", "cube array", "2D, a level it has not"] + .iter() + .enumerate() + { + for far in [0u32, 1, 7, 63, 1000, 4000] { + let (_out, out_ptr, out_gpu) = gpu.shared_buffer(1 << 12); + // SAFETY: the mapping; our open list, live objects. + unsafe { + std::ptr::write_bytes(out_ptr, 0, 1 << 12); + gpu.list.SetDescriptorHeaps(&[Some(heap.clone())]); + gpu.list.SetComputeRootSignature(&pass.root); + gpu.list.SetPipelineState(&pass.pso); + gpu.list.SetComputeRoot32BitConstants(0, 2, [how as u32, far].as_ptr().cast(), 0); + gpu.list.SetComputeRootDescriptorTable(1, heap.GetGPUDescriptorHandleForHeapStart()); + gpu.list.SetComputeRootUnorderedAccessView(2, out_gpu); + gpu.list.Dispatch(1, 1, 1); + } + gpu.submit_and_wait(); + // SAFETY: the mapping, the card is done. + let found: Vec = (0..4).map(|i| unsafe { out_ptr.cast::().add(i).read_volatile() }).collect(); + println!("{name} at {far}: its own texels {}, zeros {}, others {} (the last {})", found[0], found[1], found[2], found[3]); + } + } + // SAFETY: a plain query. + println!("device: {:?}", unsafe { gpu.device.GetDeviceRemovedReason() }); + } + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { From 0d065d35210e8751f5382a2254d6cc1fbc822049 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:31:31 -0600 Subject: [PATCH 325/445] The title's idle and lowest threads run below normal: loading no longer waits for idle processors VICTORY_TITLE_PRIORITIES=0: as the title sets them. Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/kernel.rs | 47 ++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index 83ce323..5b8fb20 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -406,6 +406,34 @@ pub extern "C" fn __p___argv() -> *mut *mut *mut c_char { argv().list.get() } +/// The title's thread priorities, but for the lowest two, which become +/// "below normal". Six of the title's threads run at "idle", the streaming +/// pager's among them; on the console they have what the rest of the title +/// leaves of its cores. A PC's processors are also wanted by other programs +/// and by our own workers (sixteen when pipelines are made): with every +/// one of them busy such a thread ran once in four seconds or so, when the +/// host's scheduler took pity, and the loading that waits for it with it +/// (run stream-3: loads seen to be done 1.1 s late on average, 4.8 s at +/// worst). `VICTORY_TITLE_PRIORITIES=0`: as the title sets them. +fn title_priority(asked: i32) -> i32 { + const IDLE: i32 = -15; + const LOWEST: i32 = -2; + const BELOW_NORMAL: i32 = -1; + match asked { + IDLE..=LOWEST => BELOW_NORMAL, + other => other, + } +} + +/// [`title_priority`]. +pub extern "system" fn SetThreadPriority(thread: *mut c_void, priority: i32) -> i32 { + static AS_SET: std::sync::OnceLock = std::sync::OnceLock::new(); + let as_set = *AS_SET.get_or_init(|| std::env::var_os("VICTORY_TITLE_PRIORITIES").is_some_and(|v| v == "0")); + let priority = if as_set { priority } else { title_priority(priority) }; + // SAFETY: the title passes a thread handle. + unsafe { windows_sys::Win32::System::Threading::SetThreadPriority(thread, priority) } +} + pub(crate) fn module() -> HleModule { HleModule { name: "kernel", @@ -440,6 +468,7 @@ pub(crate) fn module() -> HleModule { hle_export!(_invalid_parameter_noinfo_noreturn), hle_export!(TerminateProcess), hle_export!(SetUnhandledExceptionFilter), + hle_export!(SetThreadPriority), ], } } @@ -654,6 +683,24 @@ mod host { mod tests { use super::*; + /// The title's idle and lowest threads run below normal; the others as + /// it sets them. + #[test] + fn no_title_thread_waits_for_idle_processors() { + let given: Vec = [-15, -2, -1, 0, 1, 2, 15].into_iter().map(title_priority).collect(); + assert_eq!(given, [-1, -1, -1, 0, 1, 2, 15]); + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadPriority}; + std::thread::spawn(|| { + // SAFETY: plain calls on this thread. + let thread = unsafe { GetCurrentThread() }; + assert_eq!(SetThreadPriority(thread, -15), 1); + // SAFETY: as above. + assert_eq!(unsafe { GetThreadPriority(thread) }, -1); + }) + .join() + .unwrap(); + } + #[test] fn title_images_report_their_original_path() { let base = 0x7000_0000_0000; From 565f4a5603011bf725e0c347b4627907773f0c1c Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:31:31 -0600 Subject: [PATCH 326/445] Pages are mapped side by side: eight threads stand in the host's queue instead of one Mapping and unmapping a view wait for what every protection change of a view takes too (about 100,000 a second, the guards'): 0.2-4 ms a page, all on the one thread the title loads with. Scatter maps and the GPU's page-mapping copies go in groups of up to 64 pages, noted before and after on the caller's thread, the system calls on up to eight (VICTORY_MAP_THREADS=1: one after the other, as before). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/queue.rs | 12 + crates/victory-gpu/src/resource.rs | 14 + crates/victory-hle/src/modules/d3d12x.rs | 1 + crates/victory-hle/src/modules/xmem.rs | 460 +++++++++++++++++++++-- 4 files changed, 458 insertions(+), 29 deletions(-) diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 11d3a8c..069a431 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -919,6 +919,15 @@ extern "system" fn copy_page_mappings( unsafe { std::slice::from_raw_parts(batches, count as usize) } }); let mut ok = true; + let many = crate::resource::many_page_mapper(); + let mut gathered: Vec<(u64, u64, u64)> = Vec::new(); + let mut map = |to: u64, from: u64, len: u64| match many { + Some(_) => { + gathered.push((to, from, len)); + true + } + None => map(to, from, len), + }; for b in batches.into_iter().flatten() { if b.ranges.is_null() { continue; @@ -940,6 +949,9 @@ extern "system" fn copy_page_mappings( at += len; } } + if let Some(many) = many { + ok &= many(&gathered); + } if !ok { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed")); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index db3621e..f567507 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -947,6 +947,20 @@ pub fn use_page_mapper(mapper: PageMapper) { let _ = PAGE_MAPPER.set(mapper); } +/// As a [`PageMapper`], many at once: `(to, from, len)` each, in order. +pub type ManyPageMapper = fn(&[(u64, u64, u64)]) -> bool; + +static MANY_PAGE_MAPPER: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// The runtime's mapper of many pages at once. +pub fn use_many_page_mapper(mapper: ManyPageMapper) { + let _ = MANY_PAGE_MAPPER.set(mapper); +} + +pub(crate) fn many_page_mapper() -> Option { + MANY_PAGE_MAPPER.get().copied() +} + pub(crate) fn page_mapper() -> Option { PAGE_MAPPER.get().copied() } diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index 4b9bd25..a5de7c4 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -19,6 +19,7 @@ extern "system" fn create_device( ) -> HRESULT { victory_gpu::resource::use_allocator(super::xmem::XMemAlloc, super::xmem::XMemFree); victory_gpu::resource::use_page_mapper(super::xmem::map_alias); + victory_gpu::resource::use_many_page_mapper(super::xmem::map_aliases); #[cfg(windows)] victory_gpu::on_failure(host_gpu_failed); device::create(adapter, parameters, iid, out) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 5d01c55..4181edb 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -487,6 +487,20 @@ struct Physical { holes: HashMap, } +impl Physical { + /// What the page at `at` shows. + fn slice_at(&self, at: usize) -> Option { + self.views + .range(..=at) + .next_back() + .filter(|(base, (size, _))| at < *base + size) + .map(|(base, (_, s))| Slice { + index: s.index + (at - base) / PAGE, + section: s.section.clone(), + }) + } +} + /// The title's pages by number. struct Pages { next_page: usize, @@ -1103,6 +1117,16 @@ pub extern "system" fn XMemMapPhysicalPagesScatter( return 0; } lift_thread(); + if side_by_side() > 1 && n > 1 { + // Read before any lock is taken, as in `XMemMapPhysicalPages`. + let wanted: Vec<(usize, usize)> = (0..n) + // SAFETY: the title passes `n` addresses and, unless null, `n` pages. + .map(|i| unsafe { (*addresses.add(i) as usize, if pages.is_null() { 0 } else { *pages.add(i) }) }) + .collect(); + if wanted.iter().all(|w| w.0 % PAGE == 0) { + return scatter(&wanted).into(); + } + } for i in 0..n { // SAFETY: the title passes `n` addresses and, unless null, `n` pages. let (address, page) = unsafe { @@ -1139,16 +1163,7 @@ pub fn map_alias(to: u64, from: u64, len: u64) -> bool { break; } let at = from + k; - let Some(slice) = physical - .views - .range(..=at) - .next_back() - .filter(|(base, (size, _))| at < *base + size) - .map(|(base, (_, s))| Slice { - index: s.index + (at - base) / PAGE, - section: s.section.clone(), - }) - else { + let Some(slice) = physical.slice_at(at) else { return false; }; if !map(&mut physical, to + k, PAGE, slice) { @@ -1158,9 +1173,353 @@ pub fn map_alias(to: u64, from: u64, len: u64) -> bool { true } +/// [`map_alias`] of many ranges, in order. +pub fn map_aliases(ranges: &[(u64, u64, u64)]) -> bool { + let _costed = Costed::begin(None); + lift_thread(); + if side_by_side() <= 1 { + return ranges.iter().all(|&(to, from, len)| map_alias(to, from, len)); + } + // By the page: the address, and the one whose page it is to show. + let pages: Vec<(usize, Option)> = ranges + .iter() + .flat_map(|&(to, from, len)| { + (0..len as usize).step_by(PAGE).map(move |k| (to as usize + k, (from != 0).then_some(from as usize + k))) + }) + .collect(); + if pages.iter().any(|p| p.0 % PAGE != 0 || p.1.is_some_and(|from| from % PAGE != 0)) { + return ranges.iter().all(|&(to, from, len)| map_alias(to, from, len)); + } + let mut ok = true; + let mut at = 0; + while at < pages.len() { + let mut physical = physical(); + let mut ops: Vec = Vec::new(); + let mut touched = std::collections::HashSet::new(); + for &(to, from) in &pages[at..] { + // A page the group changes already, or one it would be mapped + // from: after it. + if ops.len() == GROUP || touched.contains(&to) || from.is_some_and(|from| touched.contains(&from)) { + break; + } + let slice = from.map(|from| physical.slice_at(from)); + ok &= !matches!(slice, Some(None)); + touched.insert(to); + ops.push(Op::new(to, slice.flatten())); + at += 1; + } + let _changing = victory_gpu::title_memory_remapping(); + ok &= change(&mut physical, ops); + } + ok +} + +/// Maps (page number not 0) or unmaps each address; false if a page is not +/// the title's or the host refuses one. +fn scatter(wanted: &[(usize, usize)]) -> bool { + let mut ok = true; + let mut at = 0; + while at < wanted.len() { + let mut costed = Costed::begin(None); + let mut ops: Vec = Vec::new(); + let mut physical = physical(); + if let Some(costed) = &mut costed { + costed.waited = costed.started.elapsed().as_nanos() as u64; + } + { + let table = page_table(); + let mut touched = std::collections::HashSet::new(); + for &(to, page) in &wanted[at..] { + if ops.len() == GROUP || !touched.insert(to) { + break; + } + let slice = table.pages.get(&page).cloned(); + if page != 0 && slice.is_none() { + tracing::warn!(page, "XMemMapPhysicalPagesScatter: unknown page"); + ok = false; + } + ops.push(Op::new(to, slice)); + at += 1; + } + } + if let Some(costed) = &mut costed { + costed.pages = Some(ops.len()); + } + let _changing = victory_gpu::title_memory_remapping(); + ok &= change(&mut physical, ops); + } + ok +} + +/// Pages changed under the locks at once. +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). +/// +/// 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 +/// many threads, in the world: 0.2 to 4 ms a page. One thread stands in that +/// queue once at a time. In a bench (60,000 views, five threads changing +/// protections) one thread mapped 1,500 pages a second, eight 30,000. +fn side_by_side() -> usize { + 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) + }); + *THREADS +} + +/// A page of address space to unmap and, with a slice, map anew. +struct Op { + at: usize, + slice: Option, + /// A view of this page alone is there, to be unmapped. + had: bool, + /// The placeholder is the page's own (or will be, after the unmapping). + own: bool, +} + +impl Op { + fn new(at: usize, slice: Option) -> Op { + Op { at, slice, had: false, own: false } + } + + /// The system calls; whether the host did as asked. + fn run(&self) -> bool { + if self.had { + // SAFETY: a view we mapped; it becomes a placeholder again. + let gone = counted(Call::Unmap, || unsafe { + UnmapViewOfFile2( + GetCurrentProcess(), + MEMORY_MAPPED_VIEW_ADDRESS { Value: self.at as *mut c_void }, + MEM_PRESERVE_PLACEHOLDER, + ) + }); + if gone == 0 { + return false; + } + } + let Some(slice) = &self.slice else { + return true; + }; + show(self.at, PAGE, slice, self.own) + } +} + +/// Does `ops`, each of another page, side by side: first what is noted of +/// the pages goes, then the system calls, then what is there now is noted. +/// With [`PHYSICAL`] and the change of mapping (`title_memory_remapping`) +/// held. +fn change(physical: &mut Physical, mut ops: Vec) -> bool { + for op in &mut ops { + let there = physical + .views + .range(..=op.at) + .next_back() + .filter(|(base, view)| op.at < **base + view.0) + .map(|(base, view)| (*base, view.0)); + match there { + Some((base, PAGE)) if base == op.at => { + if let Some((size, slice)) = physical.views.remove(&op.at) { + shown_mut().forget(op.at, size, &slice); + } + victory_gpu::title_memory_unmapping(op.at, PAGE); + physical.holes.remove(&op.at); + (op.had, op.own) = (true, lean()); + } + // Part of a larger view. + Some(_) => { + unmap(physical, op.at, PAGE); + } + None => {} + } + if op.had { + continue; + } + op.own = physical.holes.remove(&op.at) == Some(PAGE) && lean(); + if op.slice.is_some() && !op.own { + // Cut out of a larger placeholder here, not side by side: a + // thread that maps a piece while others cut the same one can + // fail. + split(op.at, PAGE); + op.own = true; + } + } + let done = pool::all(ops); + let mut ok = true; + for (op, done) in done { + match op.slice { + Some(slice) if done => { + // As in `map`. + shown_mut().note(op.at, PAGE, &slice); + victory_gpu::title_memory_remapped(op.at, PAGE); + victory_gpu::title_memory_view(op.at, PAGE, slice.section.handle as usize, (slice.index * PAGE) as u64); + physical.views.insert(op.at, (PAGE, slice)); + } + None if op.had && done => { + physical.holes.insert(op.at, PAGE); + } + _ => ok &= done, + } + } + ok +} + +/// The threads that do the system calls of [`change`]. +mod pool { + use std::collections::VecDeque; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::{Arc, Condvar, Mutex, OnceLock}; + + use super::{Op, side_by_side}; + + struct Batch { + ops: Vec<(Op, AtomicBool)>, + next: AtomicUsize, + /// Ops not done yet. + left: AtomicUsize, + over: (Mutex, Condvar), + } + + impl Batch { + /// Does ops until none is left to begin. + fn work(&self) { + loop { + let i = self.next.fetch_add(1, Ordering::Relaxed); + let Some((op, done)) = self.ops.get(i) else { + return; + }; + done.store(op.run(), Ordering::Release); + if self.left.fetch_sub(1, Ordering::AcqRel) == 1 { + *self.over.0.lock().unwrap_or_else(|e| e.into_inner()) = true; + self.over.1.notify_all(); + } + } + } + } + + struct Pool { + batches: Mutex>>, + more: Condvar, + } + + fn pool() -> &'static Pool { + static POOL: OnceLock = OnceLock::new(); + 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()) + .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)"); + }); + pool + } + + fn serve(pool: &Pool) { + use windows_sys::Win32::System::Threading::{ + GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL, + }; + // SAFETY: a plain call on our own thread. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) }; + let mut batches = pool.batches.lock().unwrap_or_else(|e| e.into_inner()); + loop { + let Some(batch) = batches.front().cloned() else { + batches = pool.more.wait(batches).unwrap_or_else(|e| e.into_inner()); + continue; + }; + if batch.next.load(Ordering::Relaxed) >= batch.ops.len() { + // All begun: nobody needs to see it any more. + if batches.front().is_some_and(|b| Arc::ptr_eq(b, &batch)) { + batches.pop_front(); + } + continue; + } + drop(batches); + batch.work(); + batches = pool.batches.lock().unwrap_or_else(|e| e.into_inner()); + } + } + + /// Runs `ops`; each with whether the host did it. + pub(super) fn all(ops: Vec) -> Vec<(Op, bool)> { + // Waking the others takes longer than a few quick calls. + if ops.len() < 3 { + return ops + .into_iter() + .map(|op| { + let done = op.run(); + (op, done) + }) + .collect(); + } + let n = ops.len(); + let batch = Arc::new(Batch { + ops: ops.into_iter().map(|op| (op, AtomicBool::new(false))).collect(), + next: AtomicUsize::new(0), + left: AtomicUsize::new(n), + over: Default::default(), + }); + let pool = pool(); + pool.batches.lock().unwrap_or_else(|e| e.into_inner()).push_back(batch.clone()); + if n > side_by_side() { + pool.more.notify_all(); + } else { + (1..n).for_each(|_| pool.more.notify_one()); + } + batch.work(); + let mut over = batch.over.0.lock().unwrap_or_else(|e| e.into_inner()); + while !*over { + over = batch.over.1.wait(over).unwrap_or_else(|e| e.into_inner()); + } + drop(over); + // No worker changes it any more (one may still hold it for a moment). + batch + .ops + .iter() + .map(|(op, done)| { + let op = Op { at: op.at, slice: op.slice.clone(), had: op.had, own: op.own }; + (op, done.load(Ordering::Acquire)) + }) + .collect() + } +} + /// Maps `slice` and the slices after it over `[base, base + len)`, which /// must lie in one placeholder. fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { + let own = physical.holes.remove(&base) == Some(len) && lean(); + if !show(base, len, &slice, own) { + return false; + } + // Noted before the GPU side is told: bytes DirectStorage put in earlier, + // without notice at these addresses ([`pages_written`]), are there by + // the time the copies of them go. + shown_mut().note(base, len, &slice); + // New contents, read-write: the GPU side's copies no longer guard it. + victory_gpu::title_memory_remapped(base, len); + // What the range shows now, for the GPU side's in-place census. + victory_gpu::title_memory_view(base, len, slice.section.handle as usize, (slice.index * PAGE) as u64); + physical.views.insert(base, (len, slice)); + true +} + +/// Cuts `[base, base + len)` out of the placeholder it is in (which fails +/// harmlessly when the range is the whole placeholder). +fn split(base: usize, len: usize) { + // SAFETY: acts only on a placeholder. + counted(Call::Split, || unsafe { + VirtualFree( + base as *mut c_void, + len, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ) + }); +} + +/// The system calls of [`map`]; `own`: the placeholder at `base` is `len` +/// long already. +fn show(base: usize, len: usize, slice: &Slice, own: bool) -> bool { let map_view = || { // SAFETY: maps the section over a placeholder; acts only on one. counted(Call::Map, || unsafe { @@ -1177,18 +1536,9 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { ) }) }; - let own = physical.holes.remove(&base) == Some(len) && lean(); let mut view = if own { map_view() } else { MEMORY_MAPPED_VIEW_ADDRESS { Value: std::ptr::null_mut() } }; if view.Value as usize != base { - // SAFETY: splits the placeholder around the range (failing - // harmlessly when the range is the whole placeholder). - counted(Call::Split, || unsafe { - VirtualFree( - base as *mut c_void, - len, - MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, - ) - }); + split(base, len); view = map_view(); } if view.Value as usize != base { @@ -1205,15 +1555,6 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }; return false; } - // Noted before the GPU side is told: bytes DirectStorage put in earlier, - // without notice at these addresses ([`pages_written`]), are there by - // the time the copies of them go. - shown_mut().note(base, len, &slice); - // New contents, read-write: the GPU side's copies no longer guard it. - victory_gpu::title_memory_remapped(base, len); - // What the range shows now, for the GPU side's in-place census. - victory_gpu::title_memory_view(base, len, slice.section.handle as usize, (slice.index * PAGE) as u64); - physical.views.insert(base, (len, slice)); true } @@ -1754,6 +2095,67 @@ mod tests { assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1); } + /// Many pages in one call: mapped, moved over each other's addresses, + /// given twice in one list, copied by the GPU's mappings and unmapped. + #[test] + fn a_scatter_of_many_pages_is_what_one_after_the_other_is() { + const N: usize = 200; + let pages = allocate(N); + let a = XMemVirtualAlloc(std::ptr::null_mut(), 2 * N * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE) as usize; + let at = |k: usize| (a + k * PAGE) as *mut c_void; + let first = |k: usize| at(k).cast::(); + for round in 0..4_usize { + // Every address shows another page each round. + let to: Vec<*mut c_void> = (0..N).map(|i| at((i + 7 * round) % N)).collect(); + assert_eq!(XMemMapPhysicalPagesScatter(to.as_ptr(), N, pages.as_ptr()), 1); + for i in 0..N { + // SAFETY: mapped read-write. + unsafe { + if round > 0 { + assert_eq!(first((i + 7 * round) % N).read(), (1000 * (round - 1) + i) as u64); + } + first((i + 7 * round) % N).write((1000 * round + i) as u64); + } + } + } + // The GPU's copies of the mappings, in ranges and one by one; a page + // mapped from one the same call has mapped shows the same. + let half = (N / 2 * PAGE) as u64; + let (from, to) = (a as u64, at(N) as u64); + assert!(map_aliases(&[(to, from, half), (to + half, to, half)])); + for k in 0..N / 2 { + // SAFETY: mapped read-write. + unsafe { + assert_eq!(first(N + k).read(), first(k).read()); + assert_eq!(first(N + N / 2 + k).read(), first(k).read()); + first(N + k).write(5); + assert_eq!(first(k).read(), 5); + } + } + // An address twice: the last one counts; page 0 unmaps. + let to = [at(0), at(1), at(0), at(2), at(3), at(0)]; + let what = [pages[5], pages[6], 0, 0, pages[7], pages[8]]; + assert_eq!(XMemMapPhysicalPagesScatter(to.as_ptr(), 6, what.as_ptr()), 1); + assert_eq!(query(at(2)).host.State, MEM_RESERVE); + // SAFETY: mapped read-write; the same page at both. + unsafe { + first(0).write(77); + assert_eq!(XMemMapPhysicalPagesScatter([at(2), at(4), at(6)].as_ptr(), 3, [pages[8]; 3].as_ptr()), 1); + assert_eq!((first(2).read(), first(4).read(), first(6).read()), (77, 77, 77)); + } + // A page the title does not own. + assert_eq!(XMemMapPhysicalPagesScatter([at(0), at(1)].as_ptr(), 2, [pages[0], 1].as_ptr()), 0); + // All gone, also parts of a larger view. + assert_eq!(XMemMapPhysicalPages(at(0), 4, std::ptr::null()), at(0)); + // SAFETY: placeholders of ours, nothing mapped in them. + unsafe { VirtualFree(at(0), 4 * PAGE, MEM_RELEASE | 1 /* MEM_COALESCE_PLACEHOLDERS */) }; + assert_eq!(XMemMapPhysicalPages(at(0), 4, pages.as_ptr()), at(0)); + assert!(map_aliases(&[(a as u64, 0, (2 * N * PAGE) as u64)])); + assert!((0..2 * N).all(|k| query(at(k)).host.State == MEM_RESERVE)); + assert!(physical().views.range(a..a + 2 * N * PAGE).next().is_none()); + assert_eq!(XMemFreePhysicalPages(N, pages.as_ptr()), 1); + } + /// Pages keep what they hold however often they are mapped, moved and /// unmapped without a commit or a split of their own. #[test] From 3ead56e175f8601ec8ab745cd8c19c9a3c82f4ef Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:45:37 -0600 Subject: [PATCH 327/445] Refreshes copy and send the 4 KiB parts of a page that were written (VICTORY_PAGE_PARTS=0: the 64 KiB page); the early asking is off Where the kernel or a landing names them; what is checked stays a page. VICTORY_ASK_EARLY= turns the early asking on. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 3 +- crates/victory-gpu/src/shadow.rs | 66 +++++++++++++ crates/victory-gpu/src/watch.rs | 155 ++++++++++++++++++++++++++----- 3 files changed, 200 insertions(+), 24 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b671536..b3457e9 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -8756,7 +8756,8 @@ mod refresh_tests { assert_eq!(look(true, "taken"), 0); // SAFETY: the test's own memory. unsafe { ((region + 600) as *mut u8).write_volatile(1) }; - assert_eq!(look(false, "written at its end"), PAGE - 500); + // (The kernel names the 4 KiB, the guards only the block.) + assert_eq!(look(false, "written at its end"), if view { PAGE } else { 4096 } - 500); assert_eq!(look(true, "taken again"), 0); // Outside the range, on its last page. // SAFETY: as above. diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index b140a27..b1e8388 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2388,6 +2388,66 @@ fn stale_pages_in(base: usize, copied: &[u64], a: usize, e: usize, written: &[(u .collect() } +/// `runs` (from, to, whether the copy held it before), cut in those of pages +/// held before (`pages`: page number and asking, in order) to the parts of +/// each page that were written since (`parts`: a bit for each 4 KiB). +fn by_parts(runs: Vec<(usize, usize, bool)>, pages: &[(usize, u64)], parts: &[u16]) -> Vec<(usize, usize, bool)> { + const PART: usize = PAGE / 16; + if parts.iter().all(|&p| p == u16::MAX) { + return runs; + } + let mut out: Vec<(usize, usize, bool)> = Vec::with_capacity(runs.len() + pages.len()); + let mut pages = pages.iter().zip(parts).peekable(); + for (from, to, known) in runs { + if !known { + out.push((from, to, known)); + continue; + } + while let Some((&(page, _), &parts)) = pages.next_if(|((page, _), _)| page * PAGE < to) { + for k in (0..16).filter(|k| parts >> k & 1 != 0) { + let (a, b) = ((page * PAGE + k * PART).max(from), (page * PAGE + (k + 1) * PART).min(to)); + if a >= b { + continue; + } + match out.last_mut() { + Some((_, end, true)) if *end == a => *end = b, + _ => out.push((a, b, true)), + } + } + } + } + out +} + +#[cfg(test)] +mod parts_tests { + use super::{PAGE, by_parts}; + + #[test] + fn runs_are_cut_to_the_parts_written() { + const P: usize = PAGE / 16; + let at = |page: usize, part: usize| page * PAGE + part * P; + // Pages 10 and 11 again (from the middle of 10's part 1 on), 12 + // never taken, 14 again. + let runs = vec![ + (at(10, 1) + 100, at(12, 0), true), + (at(12, 0), at(13, 0), false), + (at(14, 0), at(14, 9) + 7, true), + ]; + let pages = [(10, 5), (11, 5), (14, 6)]; + assert_eq!(by_parts(runs.clone(), &pages, &[u16::MAX; 3]), runs); + assert_eq!( + by_parts(runs, &pages, &[0b1000_0000_0000_0011, 0b11, 0b10_0000_0000]), + [ + (at(10, 1) + 100, at(10, 2), true), + (at(10, 15), at(11, 2), true), + (at(12, 0), at(13, 0), false), + (at(14, 9), at(14, 9) + 7, true), + ] + ); + } +} + #[cfg(test)] mod stale_tests { use super::*; @@ -3451,6 +3511,8 @@ impl Shadow { // since, is as it was. let ranged = if crate::watch::light() { self.ranged(from, to) } else { 0 }; let (mut runs, mut run) = (Vec::new(), None::<(usize, bool)>); + // Pages taken before and written since: in the order of their runs. + let mut again_at: Vec<(usize, u64)> = Vec::new(); let last = (to - 1) / PAGE; for page in from / PAGE..=last { let write = match writes.peek() { @@ -3471,6 +3533,9 @@ impl Shadow { } // Cut where pages taken before meet pages never taken. let again = taken != 0; + if again { + again_at.push((page, taken)); + } if let Some((first, known)) = run && known != again { @@ -3486,6 +3551,7 @@ impl Shadow { if let Some((first, known)) = run { runs.push(((first * PAGE).max(from), ((last + 1) * PAGE).min(to), known)); } + let runs = by_parts(runs, &again_at, &crate::watch::parts_written(&again_at)); let bytes = self.take_all(runs); if crate::watch::light() { // All of the range is in the copy as of this asking. diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 38cfe92..94684f5 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -36,6 +36,58 @@ pub(crate) const PAGE: usize = 64 << 10; /// The kernel's page, the unit of its answers. const KERNEL_PAGE: usize = 4096; +/// The parts of a page. +const PARTS: usize = PAGE / KERNEL_PAGE; +/// All of them. +const WHOLE: u16 = u16::MAX; + +/// Whether the parts of a page that the kernel names are kept, and a refresh +/// copies those (`VICTORY_PAGE_PARTS=0`: the 64 KiB page, as before). +/// +/// The kernel says which 4 KiB pages were written, and a copy took the 64 KiB +/// around each: 29 MB a frame written so were most of 114 MB copied, and as +/// much sent up and hashed again on the card (session play-1125-0203, run +/// cpu-2). What is checked is as before, a page. +fn parts_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PAGE_PARTS").is_none_or(|v| v != "0")) +} + +impl Journal { + /// Page `page` was found written by asking `now`: the parts in `parts` + /// (a bit each). The asking that found it written before (0: none). + fn note(&mut self, page: usize, parts: u16, now: u64) -> u64 { + let before = self.written.insert(page, now).unwrap_or(0); + if parts == WHOLE || !parts_on() { + self.parts.remove(&page); + return before; + } + let all = self.parts.entry(page).or_insert([before; PARTS]); + for (k, at) in all.iter_mut().enumerate() { + if parts >> k & 1 != 0 { + *at = now; + } + } + before + } + + /// The parts of `page` written by an asking after `taken`. + fn parts_since(&self, page: usize, taken: u64) -> u16 { + match self.parts.get(&page) { + Some(all) => all.iter().enumerate().filter(|(_, at)| **at > taken).fold(0, |m, (k, _)| m | 1 << k), + None => WHOLE, + } + } +} + +/// Of the pages of a copy that were written after it took them (page number, +/// the asking it took the page at): the parts to take again, a bit for each +/// 4 KiB, in the same order. +pub(crate) fn parts_written(pages: &[(usize, u64)]) -> Vec { + let j = journal(); + pages.iter().map(|&(page, taken)| j.parts_since(page, taken)).collect() +} + /// Numbers the askings; 0 is "never". Counted up with the journal held /// (shared will do: what notes an answer holds it alone). static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -68,6 +120,10 @@ pub(crate) fn track(start: usize, len: usize, views: bool) -> Option { struct Journal { /// Page number → the asking that last found it written. written: BTreeMap, + /// The same for each of a page's sixteen parts ([`KERNEL_PAGE`]), where + /// the parts are known ([`parts_on`]); a page that is not here was + /// written whole, as far as anyone knows. + parts: std::collections::HashMap>, /// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`]) /// and the asking that did: `writes` answers for a range inside one /// from the journal, without another kernel call. @@ -87,6 +143,7 @@ struct Journal { /// it, found it waiting for that lock (run pooloff1). static JOURNAL: RwLock = RwLock::new(Journal { written: BTreeMap::new(), + parts: std::collections::HashMap::with_hasher(std::hash::BuildHasherDefault::new()), ahead: Vec::new(), ahead_asked: 0, kept: false, @@ -142,9 +199,9 @@ thread_local! { } /// The pages of `[first, last)` the kernel says were written since it was -/// last asked, in order, each once; `None` if the range is not write-watched +/// last asked, in order, each once, with their written parts; `None` if the range is not write-watched /// memory of one reservation. The caller holds the range ([`Asking`]). -fn kernel_written(first: usize, last: usize) -> Option> { +fn kernel_written(first: usize, last: usize) -> Option> { use windows_sys::Win32::System::Memory::GetWriteWatch; const WRITE_WATCH_FLAG_RESET: u32 = 1; FOUND.with(|found| { @@ -185,8 +242,14 @@ fn kernel_written(first: usize, last: usize) -> Option> { tally(0, 1); tally(1, ((last - first) * (PAGE >> 10)) as u64); } - let mut pages: Vec = found[..count].iter().map(|&at| at / PAGE).collect(); - pages.dedup(); + let mut pages: Vec<(usize, u16)> = Vec::new(); + for &at in &found[..count] { + let (page, part) = (at / PAGE, 1u16 << (at % PAGE / KERNEL_PAGE)); + match pages.last_mut() { + Some((last, parts)) if *last == page => *parts |= part, + _ => pages.push((page, part)), + } + } Some(pages) }) } @@ -244,7 +307,9 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { j.ahead_asked = next_asking(); j.ahead = asked; let now = j.ahead_asked; - j.written.extend(written.into_iter().map(|page| (page, now))); + for (page, parts) in written { + j.note(page, parts, now); + } } /// Since the last frame line: the kernel askings that took a millisecond @@ -273,8 +338,9 @@ pub(crate) fn slow_asks() -> [u64; 3] { } /// Whether a thread asks, between a submission's askings, about the memory -/// they found written (`VICTORY_ASK_EARLY=` between its rounds, 2 if not -/// given; `0`: no such thread). +/// they found written (`VICTORY_ASK_EARLY=` between its rounds; off +/// unless given: in run cpu-2 the submissions' own askings were none the +/// cheaper for its 650 a frame, 12 to 18 ms where 9 were). /// /// An asking's cost is the pages it finds written and resets, some 1.4 /// microseconds each, and the title writes 7,000 a frame: the first @@ -292,7 +358,7 @@ fn early() -> Option { *EVERY.get_or_init(|| { let ms = match std::env::var("VICTORY_ASK_EARLY") { Ok(v) => v.trim().parse::().unwrap_or(2.0), - Err(_) => 2.0, + Err(_) => 0.0, }; std::time::Duration::try_from_secs_f64(ms / 1000.0).ok().filter(|d| !d.is_zero()) }) @@ -318,12 +384,12 @@ pub(crate) fn early_asks() -> [u64; 2] { } /// A submission's asking found `written` (pages). -fn note_hot(written: &[usize]) { +fn note_hot(written: &[(usize, u16)]) { let Some(every) = early() else { return; }; let mut hot = HOT.lock().unwrap_or_else(|e| e.into_inner()); - for page in written { + for (page, _) in written { let n = hot.entry(page / EARLY_PIECE).or_default(); *n = (*n + 1).min(1 << 10); } @@ -460,7 +526,9 @@ fn ask_rest(ranges: &[(usize, usize)]) { // part's number that write was older than the copy, and never copied. let now = next_asking(); j.ahead_asked = now; - j.written.extend(written.into_iter().map(|page| (page, now))); + for (page, parts) in written { + j.note(page, parts, now); + } j.kept = !ahead.is_empty(); j.ahead = ahead; } @@ -489,10 +557,12 @@ pub(crate) fn wrote(at: usize, len: usize) { // until the next asking copy the pages again. j.ahead_asked = now; for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) { - j.written.insert(page, now); + j.note(page, WHOLE, now); } for (_, others) in elsewhere(at, len) { - j.written.extend(others.into_iter().map(|other| (other / PAGE, now))); + for other in others { + j.note(other / PAGE, WHOLE, now); + } } } @@ -509,7 +579,7 @@ fn elsewhere(at: usize, len: usize) -> Vec<(usize, Vec)> { /// fails, as a run across two reservations or into memory that is not /// write-watched does. A piece alone is left to [`writes`]. Adds what was /// asked to `asked` and the pages found written to `written`. -fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written: &mut Vec) { +fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written: &mut Vec<(usize, u16)>) { if pieces.len() < 2 { return; } @@ -575,7 +645,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve } #[cfg(feature = "diagnostics")] let guarding = std::time::Instant::now(); - let written = guard(first * PAGE, last * PAGE); + let written = guard(first * PAGE, last * PAGE).map(|pages| pages.into_iter().map(|p| (p, WHOLE)).collect::>()); #[cfg(feature = "diagnostics")] { use crate::copystat::{C, add}; @@ -598,14 +668,16 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve let answer = { let mut j = journal_mut(); let now = next_asking(); - j.written.extend(pages.iter().map(|&page| (page, now))); + for &(page, parts) in &pages { + j.note(page, parts, now); + } (now, of(&j)) }; // Noted: what the guards made clean of it is known by its bits from // now on. (The range is still held: no other asking of any of it came // between.) if guards_asked && light() { - publish(&pages); + publish(&pages.iter().map(|p| p.0).collect::>()); } Some(answer) } @@ -1098,16 +1170,21 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64, let mut j = journal_mut(); let now = next_asking(); noted = now; - let mut last = usize::MAX; + let mut blocks: Vec<(usize, u16)> = Vec::with_capacity(spans.len()); for &page in pages { - let block = page * KERNEL_PAGE / PAGE; - if block != last { - before.push((block, j.written.insert(block, now).unwrap_or(0))); - last = block; + let (block, part) = (page / PARTS, 1u16 << (page % PARTS)); + match blocks.last_mut() { + Some((last, parts)) if *last == block => *parts |= part, + _ => blocks.push((block, part)), } } + for (block, parts) in blocks { + before.push((block, j.note(block, parts, now))); + } for (_, others) in &elsewhere { - j.written.extend(others.iter().map(|other| (other / PAGE, now))); + for other in others { + j.note(other / PAGE, WHOLE, now); + } } } for &(at, len) in spans { @@ -2114,6 +2191,38 @@ fn writable(at: usize) -> bool { n != 0 && info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE } +#[cfg(test)] +mod parts_tests { + use super::*; + + #[test] + fn the_parts_of_a_page_written_since_it_was_taken() { + let mut j = Journal { + written: BTreeMap::new(), + parts: std::collections::HashMap::with_hasher(std::hash::BuildHasherDefault::new()), + ahead: Vec::new(), + ahead_asked: 0, + kept: false, + }; + assert_eq!(j.parts_since(7, 0), WHOLE); + assert_eq!(j.note(7, WHOLE, 3), 0); + // Parts 0 and 5 at 4, part 5 again at 6: at 2 the whole page is due. + assert_eq!(j.note(7, 0b10_0001, 4), 3); + assert_eq!(j.note(7, 0b10_0000, 6), 4); + assert_eq!(j.parts_since(7, 2), WHOLE); + assert_eq!(j.parts_since(7, 3), 0b10_0001); + assert_eq!(j.parts_since(7, 4), 0b10_0000); + assert_eq!(j.parts_since(7, 5), 0b10_0000); + assert_eq!(j.parts_since(7, 6), 0); + // Written whole: all of it, whoever took it before. + assert_eq!(j.note(7, WHOLE, 8), 6); + assert_eq!(j.parts_since(7, 7), WHOLE); + // A page never written before: what was not named was never written. + assert_eq!(j.note(9, 0b100, 9), 0); + assert_eq!(j.parts_since(9, 5), 0b100); + } +} + #[cfg(test)] mod tests { use super::*; From dc2a3ad49e4aa3e827c5b62902e5c08880c72c69 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:45:38 -0600 Subject: [PATCH 328/445] Copies that shaders write are brought up to date together ahead of a submission's steps (VICTORY_REFRESH_AHEAD=0: one by one) 580 a frame, 3.4 to 6.5 ms of the submitting thread. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 137 +++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b3457e9..276d1d5 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4965,6 +4965,9 @@ impl Host { split.part(1); // What flights in the air may write. let air = line().written.clone(); + if ahead_of_writes() { + batch.refresh_ahead(runs, |list, i| own.as_ref().is_some_and(|own| own.takes(list, i))); + } for list in runs { list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i))); firsts.push(lists.len()); @@ -6717,6 +6720,86 @@ struct Batch { placed: Vec<(std::sync::Arc, usize, Vec)>, /// Fills not done yet (destination, source, bytes): [`wide_fills`]. fills: Vec<(usize, usize, usize)>, + /// Copies (by address) brought up to date ahead of the steps, and the + /// range (from, to) ([`Batch::refresh_ahead`]). + ahead: ByCopy<(usize, usize)>, +} + +/// Whether the copies that a submission's shaders write are brought up to +/// date together, on several threads, ahead of its steps +/// (`VICTORY_REFRESH_AHEAD=0`: each before the step that gives it to them). +/// +/// 580 copies a frame, one after the other on the submitting thread, 3.4 to +/// 6.5 ms (session play-1125-0203). +fn ahead_of_writes() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_AHEAD").is_none_or(|v| v != "0") && wide_refresh() && crate::watch::light()) +} + +/// What a step is to the copies' refreshes, for [`written_spans`]. +enum Touch { + /// A refresh of a copy (by address), from, to. + Refresh(usize, usize, usize), + /// The copy is given to shaders. + Write(usize), + /// Title memory is written. + Title, + Nothing, +} + +/// Of `steps`, up to the first that writes title memory: the copies given to +/// shaders, each with the range its refreshes before that cover. +fn written_spans(steps: impl Iterator) -> Vec<(usize, usize, usize)> { + // (From, to, given to shaders.) + let mut spans: ByCopy<(usize, usize, bool)> = ByCopy::default(); + for step in steps { + match step { + Touch::Refresh(copy, from, to) => { + let span = spans.entry(copy).or_insert((from, to, false)); + if !span.2 { + (span.0, span.1) = (span.0.min(from), span.1.max(to)); + } + } + // (Not refreshed before: nothing of it is due.) + Touch::Write(copy) => { + if let Some(span) = spans.get_mut(©) { + span.2 = true; + } + } + Touch::Title => break, + Touch::Nothing => {} + } + } + spans.into_iter().filter(|(_, s)| s.2).map(|(copy, (from, to, _))| (copy, from, to)).collect() +} + +#[cfg(test)] +mod written_spans_tests { + use super::{Touch, written_spans}; + + #[test] + fn what_is_written_is_refreshed_ahead_up_to_its_write_and_to_title_writes() { + use Touch::{Nothing, Refresh, Title, Write}; + let mut found = written_spans( + [ + Refresh(1, 10, 20), + Refresh(2, 0, 5), + Nothing, + Refresh(1, 30, 40), + Write(1), + Refresh(1, 0, 100), + Write(3), + Refresh(3, 1, 2), + Refresh(4, 7, 9), + Write(4), + Title, + Write(2), + ] + .into_iter(), + ); + found.sort_unstable(); + assert_eq!(found, [(1, 10, 40), (4, 7, 9)]); + } } /// Whether the fills of a submission's upload memory are done together on @@ -6755,6 +6838,9 @@ impl Batch { fn add(&mut self, shadow: &std::sync::Arc, address: usize, len: usize) { let end = address + len; let key = std::sync::Arc::as_ptr(shadow) as usize; + if self.ahead.get(&key).is_some_and(|&(from, to)| from <= address && end <= to) { + return; + } match self.index.get(&key) { Some(&at) => { let r = &mut self.refreshes[at]; @@ -6770,6 +6856,8 @@ 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)); let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else { return; }; @@ -6813,9 +6901,58 @@ impl Batch { /// first, and textures are checked again after it. fn title_written(&mut self) { self.flush(); + self.ahead.clear(); self.textures.clear(); } + /// 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) { + let mut copies: ByCopy> = ByCopy::default(); + let mut touches = Vec::new(); + 'steps: for list in runs { + for (i, step) in list.deferred().copies.iter().enumerate() { + touches.push(match step { + Step::Refresh(shadow, at, len) => { + let key = std::sync::Arc::as_ptr(shadow) as usize; + copies.entry(key).or_insert_with(|| shadow.clone()); + Touch::Refresh(key, *at, *at + *len) + } + Step::GpuWrite(shadow, ..) => Touch::Write(std::sync::Arc::as_ptr(shadow) as usize), + Step::Copy(..) if taken(list, i) => Touch::Nothing, + Step::Copy(..) | Step::Run(_) | Step::Placed(_) => break 'steps, + _ => Touch::Nothing, + }); + } + } + let due: Vec<_> = written_spans(touches.into_iter()) + .into_iter() + .filter_map(|(key, from, to)| Some((copies.get(&key)?.clone(), from, to))) + .collect(); + for (shadow, from, to) in &due { + self.ahead.insert(std::sync::Arc::as_ptr(shadow) as usize, (*from, *to)); + } + #[cfg(feature = "diagnostics")] + let began = std::time::Instant::now(); + let started = std::time::Instant::now(); + let before = PREPARING[0].load(Ordering::Relaxed); + crate::shadow::wide_each(due.len(), move |i| { + let (shadow, from, to) = &due[i]; + if !shadow.nothing_new(*from, *to - *from) { + Self::update(shadow, *from, *to); + } + }); + // The time counted is the time it took, not the threads' sum. + let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before); + PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + { + let ns = began.elapsed().as_nanos() as u64; + SPLIT[6].fetch_add(ns, Ordering::Relaxed); + SPLIT[9].fetch_add(ns, Ordering::Relaxed); + } + } + /// The fills noted are done. fn fill(&mut self) { // Below this many the threads cost more than they save. From f6db4793ff65d0332c13866e5d1d55e85ec5fcbb Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:45:38 -0600 Subject: [PATCH 329/445] The heaps' records are also looked at between submissions (VICTORY_HEAP_SYNC_EARLY=0: not) Every 4 ms while submissions come, on the thread for it. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 36 +++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 043dd26..27a8c97 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -183,6 +183,20 @@ fn sync_aside() -> bool { *ON.get_or_init(|| sync_on() && std::env::var_os("VICTORY_HEAP_SYNC_ASIDE").is_none_or(|v| v != "0")) } +/// How long that thread waits for a submission before it makes a round of its +/// own (`VICTORY_HEAP_SYNC_EARLY=`, 4 if not given; `0`: none). The title +/// copies its records while it records, and the first submission of a frame +/// found all of them: 8 ms waited for (run cpu-2). A round made meanwhile +/// leaves it those written since. +#[cfg(windows)] +fn sync_early() -> Option { + static EVERY: std::sync::OnceLock> = std::sync::OnceLock::new(); + *EVERY.get_or_init(|| { + let ms = std::env::var("VICTORY_HEAP_SYNC_EARLY").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(4u64); + (ms > 0).then(|| std::time::Duration::from_millis(ms)) + }) +} + /// The thread's work: rounds asked for, rounds done. #[cfg(windows)] static SYNC_ROUNDS: (std::sync::Mutex<(u64, u64)>, std::sync::Condvar) = (std::sync::Mutex::new((0, 0)), std::sync::Condvar::new()); @@ -211,13 +225,29 @@ pub(crate) fn begin_sync_heaps() -> SyncedHeaps { SYNC_ROUNDS.1.notify_all(); } } + // Between the rounds asked for, while submissions come. + let mut last = std::time::Instant::now(); loop { let mut r = rounds(); - while r.0 == r.1 { - r = SYNC_ROUNDS.1.wait(r).unwrap_or_else(|e| e.into_inner()); + let mut asked = r.0 != r.1; + while !asked { + let Some(every) = sync_early().filter(|_| last.elapsed().as_millis() < 500) else { + r = SYNC_ROUNDS.1.wait(r).unwrap_or_else(|e| e.into_inner()); + asked = r.0 != r.1; + continue; + }; + let (back, over) = SYNC_ROUNDS.1.wait_timeout(r, every).unwrap_or_else(|e| e.into_inner()); + r = back; + asked = r.0 != r.1; + if over.timed_out() { + break; + } } drop(r); - let _over = Over; + let _over = asked.then(|| { + last = std::time::Instant::now(); + Over + }); let _ = std::panic::catch_unwind(sync_heaps); } }); From 41808180e6f362771b57ef2e78d97ddc319c8e8e Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:45:39 -0600 Subject: [PATCH 330/445] The title's page mappings are mapped in runs, and not again where they are (VICTORY_MAP_RUNS=0: page by page) 13 % of the title's main thread while walking (profile cpu-1: two kernel calls for each 64 KiB page). Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/xmem.rs | 167 ++++++++++++++++++++++++- 1 file changed, 165 insertions(+), 2 deletions(-) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 02ba024..00a5217 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -979,10 +979,142 @@ pub extern "system" fn XMemMapPhysicalPagesScatter( /// heap. Page by page; false if a source page is not mapped physical memory. 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 started = std::time::Instant::now(); let mut physical = physical(); // As in `XMemMapPhysicalPages`: no read in place meets the gap. let _changing = victory_gpu::title_memory_remapping(); - unmap(&mut physical, to, len); + let ok = if alias_runs() { alias_in_runs(&mut physical, to, from, len) } else { alias_pages(&mut physical, to, from, len) }; + alias_line([1, (len / PAGE) as u64, 0, 0, started.elapsed().as_micros() as u64]); + ok +} + +/// Whether the pages of one mapping are mapped in runs (`VICTORY_MAP_RUNS=0`: +/// each with a call of its own, as before). +/// +/// While the player walks, the title maps and unmaps thousands of pages of its +/// tiled heap a second (what it streams in), and did it on the thread its +/// frame waits for: 13 % of that thread's time in the two kernel calls for +/// each 64 KiB page (profile cpu-1: `NtUnmapViewOfSectionEx`, +/// `NtMapViewOfSectionEx`). Pages next to one another in the heap and in the +/// section are one view; a page that shows what it is to show is left alone. +fn alias_runs() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_MAP_RUNS").is_none_or(|v| v != "0")) +} + +/// Since the last line: calls of [`map_alias`], their pages, pages that +/// showed the same already, views mapped, microseconds. The line itself, at +/// most every five seconds. +fn alias_line(add: [u64; 5]) { + use std::sync::atomic::AtomicU64; + static COUNTS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + static SAID: Mutex> = Mutex::new(None); + for (count, n) in COUNTS.iter().zip(add) { + count.fetch_add(n, Ordering::Relaxed); + } + if add[0] == 0 { + return; + } + let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); + let before = said.get_or_insert_with(std::time::Instant::now); + let secs = before.elapsed().as_secs_f64(); + if secs < 5.0 { + return; + } + *before = std::time::Instant::now(); + let [calls, pages, same, views, us] = [0, 1, 2, 3, 4].map(|i| COUNTS[i].swap(0, Ordering::Relaxed) as f64 / secs); + tracing::info!( + "page mappings of the title's queues per second: {calls:.0} calls for {pages:.0} pages, {same:.0} of them as they were, {views:.0} \ + views mapped, {:.1} ms (VICTORY_MAP_RUNS)", + us / 1e3 + ); +} + +/// What title memory at `at` shows, if it shows a physical page. +fn shown_slice(physical: &Physical, at: usize) -> Option { + let (base, (_, s)) = physical.views.range(..=at).next_back().filter(|(base, (size, _))| at < **base + *size)?; + Some(Slice { + index: s.index + (at - base) / PAGE, + section: s.section.clone(), + }) +} + +fn follows(a: &Slice, b: &Slice) -> bool { + Arc::ptr_eq(&a.section, &b.section) && a.index + 1 == b.index +} + +/// [`map_alias`], in runs ([`alias_runs`]). +fn alias_in_runs(physical: &mut Physical, to: usize, from: usize, len: usize) -> bool { + if from == 0 || len == 0 { + unmap(physical, to, len); + return true; + } + let pages = len.div_ceil(PAGE); + // What is to be shown, up to the first page that has no source. + let wanted: Vec = (0..pages).map_while(|k| shown_slice(physical, from + k * PAGE)).collect(); + let same: Vec = wanted + .iter() + .enumerate() + .map(|(k, w)| shown_slice(physical, to + k * PAGE).is_some_and(|s| Arc::ptr_eq(&s.section, &w.section) && s.index == w.index)) + .collect(); + let mut k = 0; + while k < wanted.len() { + let mut end = k + 1; + while end < wanted.len() && same[end] == same[k] && (same[k] || follows(&wanted[end - 1], &wanted[end])) { + end += 1; + } + let (at, bytes) = (to + k * PAGE, (end - k) * PAGE); + if same[k] { + // The title says so because it put other bytes there. + victory_gpu::title_memory_written(at, bytes, true); + alias_line([0, 0, (end - k) as u64, 0, 0]); + } else { + unmap(physical, at, bytes); + if !map_run(physical, at, end - k, &wanted[k]) { + return false; + } + } + k = end; + } + if wanted.len() < pages { + unmap(physical, to + wanted.len() * PAGE, len - wanted.len() * PAGE); + return false; + } + true +} + +/// Maps `pages` pages of a section, from `slice` on, at `base`, where only +/// placeholders are: as one view, or page by page if that cannot be. +fn map_run(physical: &mut Physical, base: usize, pages: usize, slice: &Slice) -> bool { + const MEM_COALESCE_PLACEHOLDERS: u32 = 1; + if pages > 1 { + // Each page a placeholder of its own (harmless where it is one, or + // not at the edge of one), then all of them one. + // SAFETY: both act on placeholders only. + let one = unsafe { + for k in 0..pages { + VirtualFree((base + k * PAGE) as *mut c_void, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER); + } + VirtualFree(base as *mut c_void, pages * PAGE, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS) != 0 + }; + if one { + alias_line([0, 0, 0, 1, 0]); + return map(physical, base, pages * PAGE, slice.clone()); + } + } + alias_line([0, 0, 0, pages as u64, 0]); + (0..pages).all(|k| { + let slice = Slice { + index: slice.index + k, + section: slice.section.clone(), + }; + map(physical, base + k * PAGE, PAGE, slice) + }) +} + +/// [`map_alias`], page by page. +fn alias_pages(physical: &mut Physical, to: usize, from: usize, len: usize) -> bool { + unmap(physical, to, len); for k in (0..len).step_by(PAGE) { if from == 0 { break; @@ -1000,7 +1132,7 @@ pub fn map_alias(to: u64, from: u64, len: u64) -> bool { else { return false; }; - if !map(&mut physical, to + k, PAGE, slice) { + if !map(physical, to + k, PAGE, slice) { return false; } } @@ -1483,6 +1615,37 @@ mod tests { assert!(map_alias(b as u64, 0, PAGE as u64)); assert_eq!(query(b).host.State, MEM_RESERVE); assert!(!map_alias(b as u64, at(a, 1) as u64, PAGE as u64)); + // All three in their order again, three at once at `b`, from the + // middle on another page, and back. + let scattered = [at(a, 1)]; + assert_eq!(XMemMapPhysicalPagesScatter(scattered.as_ptr(), 1, pages[1..].as_ptr()), 1); + // SAFETY: mapped read-write, both. + let same = |k: usize, page: usize, value: u8| unsafe { + at(a, page).cast::().add(64).write(value); + assert_eq!(at(b, k).cast::().add(64).read(), value, "page {k}"); + }; + for _ in 0..2 { + assert!(map_alias(b as u64, a as u64, 3 * PAGE as u64)); + for k in 0..3 { + same(k, k, 40 + k as u8); + } + } + assert!(map_alias(at(b, 1) as u64, a as u64, PAGE as u64)); + same(0, 0, 51); + same(1, 0, 52); + same(2, 2, 53); + assert!(map_alias(b as u64, at(a, 1) as u64, 2 * PAGE as u64)); + same(0, 1, 54); + same(1, 2, 55); + same(2, 2, 56); + // A source that ends: what came before it is mapped, the rest not. + assert!(map_alias(at(a, 1) as u64, 0, PAGE as u64)); + assert!(!map_alias(b as u64, a as u64, 2 * PAGE as u64)); + same(0, 0, 57); + assert_eq!(query(at(b, 1)).host.State, MEM_RESERVE); + same(2, 2, 58); + assert!(map_alias(b as u64, 0, 3 * PAGE as u64)); + assert_eq!(query(at(b, 2)).host.State, MEM_RESERVE); assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); assert_eq!(XMemIsToolsMemAvailable(), 0); } From 2ded49e8da539c7f2a1158e89f28a0927b99ec88 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:47:23 -0600 Subject: [PATCH 331/445] Card memory the CPU maps: scratch switch gone, what the others measured; a test Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 15 +-------- crates/victory-gpu/src/host/awake.rs | 47 ++++++++++++++++++++++++++++ crates/victory-gpu/src/host/send.rs | 5 ++- crates/victory-gpu/src/shadow.rs | 4 ++- 4 files changed, 55 insertions(+), 16 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 296cd0f..4e46127 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1579,15 +1579,6 @@ impl Spare { /// Scratch chunks no list holds. static SPARE: Mutex> = Mutex::new(Spare::new()); -/// Whether lists' scratch memory (constants and tables, which shaders read) -/// lies in the card's memory, written by the CPU through the bus -/// (`VICTORY_SCRATCH_BAR=1`; the default is upload memory, which the card -/// reads through it). -fn scratch_on_card() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_BAR").is_some_and(|v| v == "1")) -} - /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one. fn take_chunk(host: &Host, size: u64) -> Option { if scratch_pool() @@ -1598,11 +1589,7 @@ fn take_chunk(host: &Host, size: u64) -> Option { ALIVE[5].fetch_add(1, Ordering::Relaxed); return Some(chunk); } - let mapped = if scratch_on_card() { host.mapped_card_buffer(size, false) } else { None }; - let (buffer, data) = match mapped { - Some(made) => made, - None => host.upload_buffer(size)?, - }; + let (buffer, data) = host.upload_buffer(size)?; name(&buffer, || "list scratch".into()); ALIVE[1].fetch_add(1, Ordering::Relaxed); ALIVE[2].fetch_add(size, Ordering::Relaxed); diff --git a/crates/victory-gpu/src/host/awake.rs b/crates/victory-gpu/src/host/awake.rs index ceb66ea..8837d15 100644 --- a/crates/victory-gpu/src/host/awake.rs +++ b/crates/victory-gpu/src/host/awake.rs @@ -202,3 +202,50 @@ fn run(device: &ID3D12Device, wanted: &dyn Fn() -> bool, stop: &AtomicBool) -> w result } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Card memory the CPU maps holds what the CPU wrote, with the card kept + /// awake meanwhile; the thread ends when it is let go. + #[test] + fn mapped_card_memory_is_written_by_the_cpu_and_read_by_the_card() { + let Some(host) = crate::host::host() else { + return; + }; + let awake = start(&host.device, || true); + assert!(awake.is_some()); + let Some((buffer, data)) = host.mapped_card_buffer(4096, true) else { + return; + }; + let (seen, back) = host.shared_buffer(4096).unwrap(); + // SAFETY: mappings of 4096 bytes; a list, a queue and a fence of the + // test's own, and nothing is read before the copy has run. + let read = unsafe { + for i in 0..4096 { + data.add(i).write((i * 7 + i / 251) as u8); + } + let device = &host.device; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .unwrap(); + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + list.CopyBufferRegion(&seen, 0, &buffer, 0, 4096); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + // No event: returns when the fence is there. + fence.SetEventOnCompletion(1, windows::Win32::Foundation::HANDLE::default()).unwrap(); + std::slice::from_raw_parts(back, 4096).to_vec() + }; + assert!(read.iter().enumerate().all(|(i, &b)| b == (i * 7 + i / 251) as u8)); + drop(awake); + } +} diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs index 669c965..ff836de 100644 --- a/crates/victory-gpu/src/host/send.rs +++ b/crates/victory-gpu/src/host/send.rs @@ -96,7 +96,10 @@ fn kept() -> u64 { /// Whether the memory lies in the card's memory, written by the CPU through /// the bus (`VICTORY_SEND_BAR=1`): the copies on the card's drawing queue, which /// nothing overlaps, then cross no bus. In a captured frame they took 5.4 ms of -/// the card's 30 (342 copies). +/// the card's 30 (342 copies), and take 0.4 this way; but filling it takes the +/// submitting thread 8-9 ms a frame instead of 3 (73-93 MB, run card-3 against +/// card-1), so it is a loss while the card waits for that thread: off by +/// default. fn on_card() -> bool { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_SEND_BAR").is_some_and(|v| v == "1")) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index b2d9155..8426552 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -456,7 +456,9 @@ fn window_card_for(size: u64) -> Option { /// default, none): one buffer (`D3D12_HEAP_TYPE_GPU_UPLOAD`), no CPU's side, no /// copy to send and no list of changes, unlike [`window_card_most`]. The CPU /// only writes them, as no shader is declared to write a window; if one were, -/// its snapshot and compare would read through the bus, right but slow. +/// its snapshot and compare would read through the bus, right but slow. In a +/// captured frame the lists take 26 ms of the card instead of 29, the frame 32 +/// instead of 36; filling them costs the CPU what it did. /// /// Windows go there while a fifth of the card's budget is free, as with /// [`window_room_for`], which this comes before. From 96bfd0ebecae7f48ad2e1e4f4a3c7c928952c005 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:53:33 -0600 Subject: [PATCH 332/445] Stores by address are bounded: title buffers take the builder's only where it was given them to write A directory entry says whether stores by address reach its page (translator and host). Faults take at most 128 pages a frame and 8,192 in all; every slot of the copies' run holds a null view until its copy is there; a page is looked at once a frame. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 12 +- crates/victory-gpu/src/memory.rs | 126 +++++++++++++++----- crates/victory-shader/src/emit/intersect.rs | 2 +- crates/victory-shader/src/emit/lower.rs | 34 ++++-- crates/victory-shader/src/emit/mod.rs | 2 +- crates/victory-shader/src/emit/shader.rs | 6 +- 6 files changed, 136 insertions(+), 46 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index b075c97..7efd5ac 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1061,6 +1061,16 @@ impl State { h => crate::descriptor::heap(h as This).host(), }?; let (mut addresses, mut constants) = (Vec::new(), Vec::new()); + // (What it may write: its root views of unordered access.) + let written: Vec = t + .used + .iter() + .filter(|u| u.kind == ResourceType::Uav && u.root == RootType::Descriptor) + .filter_map(|u| match self.roots_ref(compute).get(usize::from(u.slot)) { + Some(&Root::View(address)) => Some(address), + _ => None, + }) + .collect(); for root in self.roots_ref(compute) { match root { // (Of a program that only walks structures, the structures' @@ -1075,7 +1085,7 @@ impl State { addresses.push(self.view_address(compute, u.slot, u.dword)); } } - crate::memory::ready(list, heap, &addresses, &constants, use_) + crate::memory::ready(list, heap, &addresses, &written, &constants, use_) } /// The bound heap holding `handle`. diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 1e4a952..a1168c5 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -32,7 +32,7 @@ //! stage, so before one of its dispatches the host makes ready what it can //! see the dispatch name: //! -//! - 1 MiB from each root view outside buffers, and where title memory has a +//! - 256 KiB from each root view outside buffers, and where title memory has a //! packed ("dehydrated") structure there, all of it: the title ships its //! structures packed, and the builder's rehydration stages unpack each in //! place once it is streamed in; @@ -53,6 +53,11 @@ //! card holds them unpacked (run light-3: a quarter of the structures //! unpacked a second time, into garbage all over their neighbours). //! +//! **Stores are bounded**: a structure the builder misreads makes it store +//! anywhere. Pages of title buffers take its stores only once one of its +//! dispatches was given that buffer as an unordered access view (its scratch +//! memory, its results); what else a store reaches is an arena's. +//! //! shortcut: a page is kept for the rest of the run. //! shortcut: pages a list does not name are looked at again in turn, over //! [`SWEEP`] frames. @@ -60,7 +65,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; -use victory_shader::emit::{MEMORY_FAULTS, MEMORY_PAGES}; +use victory_shader::emit::{MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY}; use windows::Win32::Graphics::Direct3D12::*; use crate::descriptor::host::HostHeap; @@ -84,14 +89,17 @@ const PACKED: u64 = 64 << 20; /// A packed structure not named for so many frames is another one. const AGAIN: u64 = 8; /// From a root view; from an address in constants. -const VIEW: u64 = 1 << 20; +const VIEW: u64 = 256 << 10; const BUILT: u64 = 4 << 20; /// The biggest title buffer whose builder results come back. const BACK: u64 = 256 << 10; -/// Pages taken from the faults of one frame, at most. -const FAULTS: usize = 2048; +/// Pages taken from the faults, of one frame and in all, at most: a ray in a +/// structure that is not right goes anywhere, and 2,048 a frame took all the +/// pages there are in the first seconds (run light-4). +const FAULTS: usize = 128; +const FAULTS_ALL: usize = 8192; /// Frames over which every page is looked at once. -const SWEEP: usize = 32; +const SWEEP: usize = 128; /// What a draw or dispatch does with title memory by address. #[derive(Clone, Copy, PartialEq)] @@ -109,6 +117,8 @@ struct Held { copy: usize, /// The write-watch asking after which it was last taken (0: never). taken: u64, + /// The frame it was last looked at in. + looked: u64, } struct Memory { @@ -131,6 +141,10 @@ struct Memory { windows: usize, /// Packed structures the builder came to: the frame it last did. packed: HashMap, + /// Copies of title buffers the builder may store in. + open: std::collections::HashSet, + /// Pages taken from faults. + faulted: usize, /// Per host view heap (by address): the first slot of its run, and how /// many copies have their view there. heaps: HashMap, @@ -199,6 +213,8 @@ impl Memory { sweep: 0, windows: 0, packed: HashMap::new(), + open: Default::default(), + faulted: 0, heaps: HashMap::new(), frame: u64::MAX, refused: Default::default(), @@ -221,7 +237,7 @@ impl Memory { return None; } // SAFETY: an entry of the directory. - (unsafe { self.entry(page).read() } as usize).checked_sub(1) + ((unsafe { self.entry(page).read() } & !MEMORY_READ_ONLY) as usize).checked_sub(1) } /// Whether `page` can be given a place: in the directory, not turned down @@ -293,12 +309,15 @@ impl Memory { let entry = self.entry(at / PAGE); // SAFETY: an entry of the directory. if unsafe { entry.read() } == 0 { - fill(entry, n, at - first); + close(entry, n, at - first); } at += PAGE; } } - fill(self.entry(page), n, start - shadow.span().0); + // SAFETY: as above. + if unsafe { self.entry(page).read() } == 0 { + close(self.entry(page), n, start - shadow.span().0); + } return true; } // Small title buffers in it: what the builder stores in them comes @@ -336,12 +355,34 @@ impl Memory { }; let offset = self.used * PAGE; self.used += 1; - self.pages.insert(page, Held { at: arena + offset as usize, copy, taken: 0 }); + self.pages.insert(page, Held { at: arena + offset as usize, copy, taken: 0, looked: u64::MAX }); self.order.push(page); fill(self.entry(page), copy, offset); true } + /// A dispatch of the builder was given `address` to write: if it is in a + /// title buffer's copy, stores by address reach that from here on. + fn opens(&mut self, address: u64) { + let Some(n) = self.map(address / PAGE).then(|| self.copy_of(address / PAGE)).flatten() else { + return; + }; + if self.pages.contains_key(&(address / PAGE)) || !self.open.insert(n) { + return; + } + let (first, len) = self.copies[n].span(); + tracing::info!( + start = format_args!("{first:#x}"), + len, + "title memory by address: the structure builder may store in a title buffer" + ); + for page in first.div_ceil(PAGE)..(first + len) / PAGE { + if self.copy_of(page) == Some(n) { + fill(self.entry(page), n, page * PAGE - first); + } + } + } + /// [`Memory::map`] of the pages of `[address, address + len)`, up to the /// first that is not the title's, and what the title wrote there since /// they were taken goes into the arenas. @@ -357,7 +398,9 @@ impl Memory { /// Takes the pages `[first, end)` that are in arenas from title memory /// where it wrote them. fn bring(&mut self, first: u64, end: u64) { - if first >= end { + // Once a frame: the builder names the same pages list after list. + let frame = self.frame; + if !(first..end).any(|page| self.pages.get(&page).is_some_and(|h| h.looked != frame)) { return; } let started = std::time::Instant::now(); @@ -366,6 +409,10 @@ impl Memory { let Some(held) = self.pages.get_mut(&page) else { continue; }; + if held.looked == frame { + continue; + } + held.looked = frame; self.stats.looked += 1; let wrote = answer .as_ref() @@ -396,18 +443,19 @@ impl Memory { /// If title memory has a packed structure at `address` that the builder /// comes to anew: all of it has its pages, and goes up as it is there. - fn unpacks(&mut self, address: u64) { + /// Whether there is a packed structure. + fn unpacks(&mut self, address: u64) -> bool { if address & 0xFF != 0 || !self.possible(address / PAGE) { - return; + return false; } let mut header = [0u8; 8]; crate::host::copy_mapped(header.as_mut_ptr(), address as *const u8, 8, false); let Some(len) = packed_len(u64::from_le_bytes(header)) else { - return; + return false; }; let last = self.packed.insert(address, self.frame); if last.is_some_and(|f| f + AGAIN >= self.frame) { - return; + return true; } self.ready(address, len); let mut title = [0u8; PIECE]; @@ -426,6 +474,7 @@ impl Memory { at += n as u64; } self.stats.packed += 1; + true } /// The pages shaders found empty since the last frame. @@ -449,8 +498,9 @@ impl Memory { pages.sort_unstable(); let mut made = 0; for &page in &pages { - if made < FAULTS && self.copy_of(page).is_none() && self.map(page) { + if made < FAULTS && self.faulted < FAULTS_ALL && self.copy_of(page).is_none() && self.map(page) { made += 1; + self.faulted += 1; self.bring(page, page + 1); } } @@ -546,6 +596,11 @@ impl Memory { } } +/// [`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); +} + /// The offset first: a shader that sees the number sees it too. fn fill(entry: *mut u32, n: usize, offset: u64) { // SAFETY: an entry of the directory, under the mutex. @@ -585,11 +640,19 @@ fn merge(title: &[u8; PIECE], ours: &mut [u8], never: bool) -> usize { } /// Before a draw whose shader reads title memory by address: what its -/// root arguments name is made ready (`addresses`: its root views; -/// `constants`: its root constants, see the module), every numbered copy +/// root arguments name is made ready (`addresses`: its root views, of them +/// `written` those it writes; `constants`: its root constants, see the +/// module), every numbered copy /// has its view in `heap`'s run and is brought up to date when `list` is /// submitted. None if the host cannot hold it; the draw is then dropped. -pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constants: &[u32], use_: Use) -> Option { +pub(crate) fn ready( + list: &HostList, + heap: &HostHeap, + addresses: &[u64], + written: &[u64], + constants: &[u32], + use_: Use, +) -> Option { let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); if guard.is_none() { *guard = Memory::new(); @@ -639,20 +702,20 @@ pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constan } for &at in addresses.iter().filter(|&&a| a >= 1 << 32) { // (Several structures to a page.) - if builds && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize) { - m.unpacks(at); + let packed = builds && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize) && m.unpacks(at); + if builds && written.contains(&at) && named(4, at) { + if let Some((start, len)) = crate::shadow::in_buffer(at, 1) + && len <= BACK + && use_ == (Use::Builds { back: true }) + { + m.small(list, start, len); + } + m.opens(at); } - if !named(2, at) { + if packed || !named(2, at) { continue; } match crate::shadow::in_buffer(at, 1) { - Some((start, len)) if builds && len <= BACK => { - if use_ == (Use::Builds { back: true }) { - m.small(list, start, len); - } - m.ready(at, 1); - m.named_in_upload(at); - } Some(_) => { m.ready(at, 1); m.named_in_upload(at); @@ -666,7 +729,10 @@ pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constan None => { // Held for the heap's life: not given back with a list's slots. let base = heap.dynamic(COPIES + 1)?; - heap.null_raw_uav_at(base); + // Every slot of the run: a number shows no view of another kind. + for n in 0..=COPIES { + heap.null_raw_uav_at(base + n); + } (base, 0) } }; diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs index e1043f3..b5335cb 100644 --- a/crates/victory-shader/src/emit/intersect.rs +++ b/crates/victory-shader/src/emit/intersect.rs @@ -244,7 +244,7 @@ impl<'a> Lower<'a> { let at = self.s.m.select(c, inside, at, outside); return (handle, at); } - self.memory(low, high, guard) + self.memory(low, high, guard, false) } /// `count` dwords of the node from its byte `base` + `offset` (`base` diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 319b20e..38fab3b 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1783,7 +1783,7 @@ impl<'a> Lower<'a> { if let Some(bias) = self.root_bias(a.param) { off = self.s.m.bin(c, Bin::Add, off, bias); } - match self.root_memory(&src, off, guard) { + match self.root_memory(&src, off, guard, false) { Some((h, byte)) => { off = byte; Some(h) @@ -3013,8 +3013,10 @@ impl<'a> Lower<'a> { /// (and drops writes) through the null view at the first slot, and its /// number is left for the host, for lanes that run (`guard`). Goes on in /// another block. - fn memory(&mut self, lo: V, hi: V, guard: Option) -> (V, V) { - use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE}; + /// With `store`, a page that is not to be written ([`super::shader::MEMORY_READ_ONLY`]) + /// is the null view. + fn memory(&mut self, lo: V, hi: V, guard: Option, store: bool) -> (V, V) { + use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE}; let c = self.cur; let (i32t, res) = (self.s.t.i32, self.s.t.res_ret); let k = |l: &mut Self, v: u32| l.s.m.i32(v); @@ -3043,7 +3045,9 @@ impl<'a> Lower<'a> { &[directory, at, iu, both, align], ); let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1)); - let (copy, start) = (self.as_int(copy), self.as_int(start)); + let (number, start) = (self.as_int(copy), self.as_int(start)); + let mask = k(self, !MEMORY_READ_ONLY); + let copy = self.s.m.bin(c, Bin::And, number, mask); // A page without a copy: its number, at a place by the number. In a // branch: the notes lie in the PC's memory, and a store there with // every node of every ray would be most of what a trace does. @@ -3073,6 +3077,12 @@ impl<'a> Lower<'a> { ); self.end_guarded(noting, &[]); let c = self.cur; + let copy = if store { + let closed = self.s.m.cmp(c, pred::SLT, number, zero); + self.s.m.select(c, closed, zero, copy) + } else { + copy + }; let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0); let slot = self.s.m.bin(c, Bin::Add, base, copy); // The builder's threads read what others of the dispatch wrote (a @@ -3112,7 +3122,7 @@ impl<'a> Lower<'a> { /// another block. /// shortcut: an access of several dwords is taken not to cross the end /// of a host copy (the builder's records lie on their size). - fn root_memory(&mut self, src: &Source, off: V, guard: Option) -> Option<(V, V)> { + fn root_memory(&mut self, src: &Source, off: V, guard: Option, store: bool) -> Option<(V, V)> { let (lo, hi) = self.root_address(src)?; let c = self.cur; let i32t = self.s.t.i32; @@ -3123,7 +3133,7 @@ impl<'a> Lower<'a> { 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 (h, byte) = self.memory(sum, hi, guard); + let (h, byte) = self.memory(sum, hi, guard, store); self.root_copy = Some(h); Some((h, byte)) } @@ -3173,7 +3183,7 @@ impl<'a> Lower<'a> { let Some(Operand::Vector { reg, .. }) = *dst else { return Err("a global load result"); }; - let (h, byte) = self.memory(lo, hi, guard); + let (h, byte) = self.memory(lo, hi, guard, false); let c = self.cur; let mask = self.s.m.i8((1u8 << n) - 1); let r = self.s.op( @@ -3195,7 +3205,7 @@ impl<'a> Lower<'a> { let n = count(rest)?; let d = data.as_ref().ok_or("global store data")?; let vals = self.vgprs(inst, d, n)?; - let (h, byte) = self.memory(lo, hi, guard); + let (h, byte) = self.memory(lo, hi, guard, true); let mut args = vec![h, byte, iu]; args.extend(&vals); args.resize(3 + 4, iu); @@ -3222,7 +3232,7 @@ impl<'a> Lower<'a> { Some(x) => self.i32_of(x)?, None => self.s.m.i32(0), }; - let (h, byte) = self.memory(lo, hi, guard); + let (h, byte) = self.memory(lo, hi, guard, true); let c = self.cur; // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8. @@ -3357,7 +3367,7 @@ impl<'a> Lower<'a> { for first in (0..count).step_by(4) { let n = (count - first).min(4); let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first)); - let (h, byte) = self.memory(lo, hi, None); + let (h, byte) = self.memory(lo, hi, None, false); let c = self.cur; let mask = self.s.m.i8((1u8 << n) - 1); let r = self.s.op( @@ -6004,7 +6014,7 @@ impl<'a> Lower<'a> { return Ok(()); } if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { - let h = match self.root_memory(src, addr, None) { + let h = match self.root_memory(src, addr, None, false) { Some((h, byte)) => { addr = byte; h @@ -11279,7 +11289,7 @@ impl<'a> Lower<'a> { off = self.s.m.bin(c, Bin::Add, element, off); index = None; } - if let Some((_, byte)) = self.root_memory(src, off, guard) { + if let Some((_, byte)) = self.root_memory(src, off, guard, store || atomic.is_some()) { off = byte; } } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index e23971f..2f06eac 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -117,7 +117,7 @@ pub use sampler::StaticSampler; pub use lower::{host_settings, set_host_max_wave}; pub use rect::rect_list_gs; pub use shader::{ - MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, + 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_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 7ae8baf..d2605dc 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -37,7 +37,8 @@ pub const SLOT_STRIDES_COUNT: u32 = 1 << 21; /// - the root SRV `t` in [`ROOT_CBV_SPACE`] is a directory of /// [`MEMORY_PAGES`] entries of two dwords, one per 64 KiB of title /// address space: the number of the host copy holding that page (0: none -/// yet) and the page's byte offset in that copy; +/// yet; with [`MEMORY_READ_ONLY`]: stores there are dropped) and the page's +/// byte offset in that copy; /// - copy `n` is the raw buffer view at view-heap slot `base + n`, `base` /// the user-data dword of kind [`USER_MEMORY_BASE`]; slot `base` itself /// reads zeros and drops writes; @@ -49,6 +50,9 @@ pub const SLOT_MEMORY: u8 = 254; pub const SLOT_FAULTS: u8 = 253; /// Entries of the [`SLOT_MEMORY`] directory: title addresses below 128 GiB. pub const MEMORY_PAGES: u32 = 1 << 21; +/// In a directory entry's first dword: shaders do not store there by address +/// (a title buffer the structure builder has not been given to write). +pub const MEMORY_READ_ONLY: u32 = 1 << 31; /// Dwords of the [`SLOT_FAULTS`] buffer. pub const MEMORY_FAULTS: u32 = 4096; /// `RootType::Other` code of a user-data dword the host computes: the view From 1420b07a64d28b443070623b941c38514188d581 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:00:17 -0600 Subject: [PATCH 333/445] Every buffer read as raw bytes through the heap is read at its raw twin Runs n03 and n04 lost the device in the main pass. The pixel program 3711fdad456538a1, bound in both stopped lists, reads entry 35 of its big table as raw bytes per lane, and that slot is a structured view of 8 byte elements that begins at 8 mod 16 (capture play-1125-0127, all 766 draws): no raw view begins there, so it stayed structured, and a raw load through it has no end on AMD. So not only picked buffers: tables' buffers too, in title slots and in the dynamic slots, which have twins now as well (a constant buffer of a fresh table has a raw one of its bytes). Measured with it: constant buffer loads, uniform and per lane, end with a constant buffer's view. Loads by title address end with the raw view of the copy, or read the null view for a page without one. VICTORY_RAW_VIEWS=0: as before. Every shader is translated again (5 min). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 59 +++++++++++++++----- crates/victory-gpu/src/indirect.rs | 4 +- crates/victory-shader/src/emit/lower.rs | 20 +++++-- crates/victory-shader/src/emit/shader.rs | 7 ++- crates/victory-shader/src/emit/size_tests.rs | 34 +++++++++-- 5 files changed, 97 insertions(+), 27 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 2a6372f..b1b3b28 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1163,7 +1163,7 @@ impl HostHeap { dynamic: extra, sampler, raw, - twins: (0..if raw == 0 { 0 } else { count }).map(|_| std::sync::atomic::AtomicBool::new(false)).collect(), + twins: (0..if raw == 0 { 0 } else { count + extra }).map(|_| std::sync::atomic::AtomicBool::new(false)).collect(), made: Mutex::new(vec![0; count as usize]), copied: Mutex::new(Vec::new()), waiting: Mutex::default(), @@ -2031,11 +2031,12 @@ impl HostHeap { /// Makes slot `index` (a dynamic one) from `view`; a null view if the /// host cannot. pub(crate) fn make_at(&self, index: u32, view: &View) { - let kept = make(view, self.at(index)); + let kept = make_twinned(view, self.at(index), self.twin(index)); if kept.is_none() { null_for(view, self.at(index)); } self.put(index); + self.twin_made(index, kept.is_some() && twinned(view)); self.keep(index, kept.flatten()); } @@ -2047,15 +2048,28 @@ impl HostHeap { null_view(self.at(index)); self.put(index); } + self.clear_twin(index); self.keep(index, None); } - /// Where the raw twin of title slot `index` is. + /// Where the raw twin of slot `index` is made. fn twin(&self, index: u32) -> Option { (index < self.twins.len() as u32).then(|| staged(self.sampler, 1).unwrap_or_else(|| self.cpu(self.raw + index))) } - /// The raw twin of title slot `index` is a null view again. + /// The raw twin of slot `index` was made by this thread ([`make_twinned`]), + /// or is a null view if it was not. + fn twin_made(&self, index: u32, made: bool) { + if !made { + return self.clear_twin(index); + } + if let Some(shown) = self.twins.get(index as usize) { + self.put_twin(index); + shown.store(true, std::sync::atomic::Ordering::Relaxed); + } + } + + /// The raw twin of slot `index` is a null view again. fn clear_twin(&self, index: u32) { if let Some(made) = self.twins.get(index as usize) && made.swap(false, std::sync::atomic::Ordering::Relaxed) @@ -2108,6 +2122,8 @@ impl HostHeap { .CreateShaderResourceView(buffer, Some(&desc), self.at(index)) }; self.put(index); + // (Bound by its handle, not read by index.) + self.clear_twin(index); self.keep(index, Some(buffer.clone())); } @@ -2116,6 +2132,7 @@ impl HostHeap { pub(crate) fn null_raw_at(&self, index: u32) { null_buffer_view(self.at(index)); self.put(index); + self.clear_twin(index); self.keep(index, None); } @@ -2149,6 +2166,7 @@ impl HostHeap { ) }; self.put(index); + self.clear_twin(index); self.keep(index, Some(buffer.clone())); } @@ -2177,6 +2195,7 @@ impl HostHeap { ) }; self.put(index); + self.clear_twin(index); self.keep(index, None); } @@ -2212,6 +2231,28 @@ impl HostHeap { .CreateConstantBufferView(Some(&desc), self.at(index)) }; self.put(index); + // A program that reads it as raw bytes reads its twin. + let twin = self.twin(index).filter(|_| desc.SizeInBytes > 0); + if let Some(twin) = twin { + // SAFETY: a live buffer that holds the range. + let first = (gpu - unsafe { buffer.GetGPUVirtualAddress() }) / 4; + let raw = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: first, + NumElements: desc.SizeInBytes / 4, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }, + }, + }; + // SAFETY: as above, and a slot of our heaps. + unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) }; + } + self.twin_made(index, twin.is_some()); // After the descriptor: what it showed is let go when nothing shows // it any more. self.keep(index, holds.then(|| buffer.clone())); @@ -2370,7 +2411,6 @@ impl HostHeap { // title released): nothing to read. if made[index as usize] != 0 { made[index as usize] = 0; - self.clear_twin(index); self.make_null(index); let _ = self.note_buffer(index, None, false); } else if for_draw { @@ -2424,14 +2464,7 @@ impl HostHeap { if kept.is_some() || !self.sampler { self.put(index); } - if kept.is_some() && twinned(&view) { - self.put_twin(index); - if let Some(made) = self.twins.get(index as usize) { - made.store(true, std::sync::atomic::Ordering::Relaxed); - } - } else { - self.clear_twin(index); - } + self.twin_made(index, kept.is_some() && twinned(&view)); self.keep(index, kept.flatten()); } Some(view) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 60b645c..09be698 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -1006,6 +1006,7 @@ RWByteAddressBuffer o : register(u0); void main(uint3 id : SV_DispatchThreadID, uint g : SV_GroupIndex) { if (step == 0) { if (id.x == 0) o.Store(at, v[which].Load(first)); } else if (step == 1) { if (id.x == 0) o.Store(at, c[which].d[first / 16][(first / 4) & 3]); } + else if (step == 16) { o.Store(at + id.x * 4, c[which].d[first / 16 + id.x][(first / 4) & 3]); } else { o.Store(at + id.x * 4, v[which].Load(first + id.x * step)); } } "#; @@ -1071,7 +1072,7 @@ void main(uint3 id : SV_DispatchThreadID, uint g : SV_GroupIndex) { } let table2 = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: table.ptr + 8 * step as u64 }; let offsets = [0u32, 4092, 4096, 4104, 8192, 65536, 524_288, (1 << 20) - 4]; - for mode in ["one load (uniform)", "a load a thread", "constant buffer load"] { + for mode in ["one load (uniform)", "a load a thread", "constant buffer load", "Constant buffer load a thread"] { println!("{mode}:"); for (which, name) in names.iter().enumerate() { // SAFETY: our open list, live buffers. @@ -1087,6 +1088,7 @@ void main(uint3 id : SV_DispatchThreadID, uint g : SV_GroupIndex) { let step = match mode.as_bytes()[0] { b'o' => 0u32, b'c' => 1, + b'C' => 16, _ => 4, }; // (A thread's loads end at the offset.) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 86ceff9..3c60174 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6810,11 +6810,17 @@ impl<'a> Lower<'a> { } /// The heap index to read descriptor `src` at, `index` being the title's: - /// for a buffer picked from the heap itself and read as raw bytes (or as - /// a constant buffer), the host's raw twin of that slot - /// ([`super::shader::raw_views`]), whose reads end where the view does. - /// Everything else (tables, textures, typed buffers) stays in place. - /// And whether it is a twin's (inside the host's heap). + /// for a buffer read as raw bytes, through a table or picked from the + /// heap itself (or picked and read as a constant buffer), the host's raw + /// twin of that slot ([`super::shader::raw_views`]), whose reads end where + /// the view does. Everything else (textures, typed buffers, tables' + /// constant buffers) stays in place. And whether it is a twin's (inside + /// the host's heap). + /// + /// Tables too: a view that does not begin on 16 bytes cannot be raw, and + /// a pixel program of the main pass (3711fdad456538a1, stopped at in the + /// device losses of runs n03 and n04) reads a structured one of 8 byte + /// elements at 8 as raw bytes per lane. fn raw_twin(&mut self, src: &Source, index: V, sampler: bool, props: (u32, u32)) -> (V, bool) { // Raw and constant buffers (DXIL resource kinds 11 and 13). const RAW: u32 = 11; @@ -6827,7 +6833,9 @@ impl<'a> Lower<'a> { self.scalar .get(load) .and_then(|a| self.x.native.layout.get(a.param)) - .is_some_and(|p| p.root == RootType::ResourceHeap) + .is_some_and(|p| { + p.root == RootType::ResourceHeap || (p.root == RootType::Table && props.0 & 0xFF == RAW) + }) }; if first == 0 || sampler || !matches!(props.0 & 0xFF, RAW | CONSTANT) || !src.leaves().iter().all(picked) { return (index, false); diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index c545294..a0cf4bf 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -138,9 +138,10 @@ pub fn view_heap_limit() -> u32 { /// entry nothing wrote. On AMD a raw load through a view that is not raw (typed, structured, a /// constant buffer's) has no end: it reads whatever lies there, up to 4 GiB on, and loses the /// device where nothing does; and a texture's descriptor read as a buffer's is a wild address. -/// So the host keeps, for title slot `i`, a raw view of the same bytes at this place + `i` -/// (a constant buffer view of a constant buffer, a null raw view of everything else and of every -/// slot past the title's), and shaders translated while this is set read picked buffers there. +/// So the host keeps, for slot `i`, a raw view of the same bytes at this place + `i` (a constant +/// buffer view of a constant buffer in a title slot, a null raw view of everything else), and +/// shaders translated while this is set read picked buffers there, and tables' buffers that they +/// read as raw bytes. /// A power of two above every slot index. static RAW_VIEWS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); diff --git a/crates/victory-shader/src/emit/size_tests.rs b/crates/victory-shader/src/emit/size_tests.rs index 0cb8696..9c78bf4 100644 --- a/crates/victory-shader/src/emit/size_tests.rs +++ b/crates/victory-shader/src/emit/size_tests.rs @@ -322,15 +322,17 @@ fn a_picked_buffer_is_read_at_its_raw_twin() { }; let (title, twin, last, texel) = ([1u32, 2, 3, 4], [5u32, 6, 7, 8], [9u32, 10, 11, 12], [[0.0; 4]; 1]); let raw = |data| View::Buffer { data, stride: Stride::Raw }; - let views = || { + // (The store goes through the table's third entry: its twin, too.) + let views = |twins: bool| { + let uav = |here: bool| if here { View::RawUav(2) } else { View::Texture(1, 1, &texel) }; [ View::Texture(1, 1, &texel), raw(&title), - View::RawUav(2), + uav(!twins), View::Texture(1, 1, &texel), View::Texture(1, 1, &texel), raw(&twin), - View::Texture(1, 1, &texel), + uav(twins), raw(&last), ] }; @@ -338,8 +340,32 @@ fn a_picked_buffer_is_read_at_its_raw_twin() { super::shader::RAW_VIEWS_HERE.set(Some(first)); let shader = build(&program(at), (8, 0)).expect("translates"); super::shader::RAW_VIEWS_HERE.set(None); - for (label, got) in run(&shader, &views()) { + for (label, got) in run(&shader, &views(first != 0)) { assert_eq!(got[..2], [0, expected], "{label}: twins from {first}, byte {at}"); } } } + +/// A table's buffer read as raw bytes is read at its raw twin too. +#[test] +fn a_tables_raw_buffer_is_read_at_its_raw_twin() { + let load = [ + 0xF408_0201u32, // s_load_dwordx4 s[8:11], s[2:3], 0 + 0xFA00_0000, + 0xE030_0004, // buffer_load_dword v5, off, s[8:11], 0 offset:4 + 0x8002_0500, + 0x7E0A_0505, // v_readfirstlane_b32 s5, v5 + 0xBE84_0380, // s_mov_b32 s4, 0 + ]; + let words = [TABLE, &load, STORE].concat(); + let (title, twin, texel) = ([1u32, 2, 3, 4], [5u32, 6, 7, 8], [[0.0; 4]; 1]); + let raw = |data| View::Buffer { data, stride: Stride::Raw }; + super::shader::RAW_VIEWS_HERE.set(Some(4)); + let shader = build(&words, (4, 0)).expect("translates"); + super::shader::RAW_VIEWS_HERE.set(None); + let other = || View::Texture(1, 1, &texel); + let views = [raw(&title), other(), other(), other(), raw(&twin), other(), View::RawUav(2)]; + for (label, got) in run(&shader, &views) { + assert_eq!(got[..2], [0, 6], "{label}"); + } +} From a9c2e9911ddf8810d88378dd505eb1a877ad41a5 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:00:34 -0600 Subject: [PATCH 334/445] Draw records of 2^23 vertices or more and unfilled mesh records run empty After victory-fork f85101b6, whose window checker found 90 records of 2^24 vertices in one list; ours also run mesh records over 65,535 groups (all ones) empty instead of as 65,535 groups. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/indirect.rs | 54 +++++++++++++----------- crates/victory-gpu/src/indirect/batch.rs | 9 +++- 2 files changed, 37 insertions(+), 26 deletions(-) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 60b645c..d062a48 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -28,7 +28,7 @@ //! run empty, saturating without 32-bit wraparound so a list of thousands of //! garbage records cannot run for seconds either. //! -//! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535 +//! shortcut: the bounds (below 2^23 vertices an instance, 2^26 vertex instances, 65,535 //! groups per dimension, in x 2^20 ([`widest`]), and 2^20 per dispatch, one-dimensional mesh //! dispatches, the budget) cut legitimate work beyond them; raise them if //! the title needs more. @@ -62,6 +62,8 @@ RWByteAddressBuffer dst_args : register(u0); // records run empty. RWByteAddressBuffer budget : register(u1); static const uint BUDGET = 1u << 27; +// The vertices or indices an instance from which a draw record runs empty. +static const uint MOST_DRAW = 1u << 23; // Groups of one dispatch; more run empty. static const uint GROUPS = 1u << 20; // Each group charges the budget once: the costs of its records go here, @@ -102,7 +104,14 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { if (ahead && (want.x > (1u << 24) || want.y > (1u << 24))) { want = uint2(0, 0); } - uint count = min(want.x, 1u << 24); + // A record of MOST_DRAW vertices or indices an instance, or more, is + // no draw of the title's (a slot it has not filled): it runs empty + // and charges nothing (victory-fork f85101b6, its window checker + // found 90 of 2^24 vertices in one list). + if (want.x >= MOST_DRAW) { + want = uint2(0, 0); + } + uint count = want.x; uint instances = min(want.y, (1u << 26) / max(count, 1u)); cost = count * instances; draw_counts = uint2(count, instances); @@ -119,10 +128,11 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { } else if (active) { // Mesh dispatches: the console's are one-dimensional. uint3 g = src_args.Load3(src_at); - // Ahead of its draw, a record over the most a dispatch runs is a - // slot the title has not filled (the title leaves all - // ones there): empty, and not counted below either. - if (ahead && g.x > 65535u) { + // A record over the most a dispatch runs is a slot the title has + // not filled (the title leaves all ones there): empty, + // and not counted below either. (65,535 groups of meshlets read + // through the garbage beside it read past every buffer.) + if (g.x > 65535u) { g = uint3(0, 0, 0); } asked = g.x; @@ -1832,18 +1842,13 @@ void main(uint3 t : SV_DispatchThreadID) { assert_eq!(rec, [groups, u32::from(groups > 0).max(1).min(1), 1, 0xAB00 + i as u32], "filled record {i}, ahead {ahead}"); } let charged_filled = (5 + 519) * 128; - if ahead { - for i in filled.len()..RECORDS as usize { - assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty"); - assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are"); - } - assert_eq!(spent, charged_filled, "unfilled slots charge nothing"); - assert_eq!(largest, 519, "and are not counted as asked for"); - } else { - // Thirteen slots at 65,535 groups: sixteen would be all of it. - assert_eq!(spent, charged_filled + 13 * 65535 * 128, "clamped one by one, each slot is charged the most"); - assert_eq!(largest, u32::MAX); + // As one window ahead of its draws and one by one alike. + for i in filled.len()..RECORDS as usize { + assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty"); + assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are"); } + assert_eq!(spent, charged_filled, "unfilled slots charge nothing"); + assert_eq!(largest, 519, "and are not counted as asked for"); } } @@ -1866,8 +1871,9 @@ void main(uint3 t : SV_DispatchThreadID) { let mut initial_src = vec![0u8; total_bytes]; for i in 0..RECORDS as usize { let words: [u32; 6] = [ - u32::MAX, // IndexCount -> clamps to 1 << 24 - u32::MAX, // InstanceCount -> clamps to 4 (cost = 1 << 26) + // The last is no draw: empty, and free. + if i + 1 < RECORDS as usize { 1 << 22 } else { 1 << 23 }, // IndexCount + u32::MAX, // InstanceCount -> clamps to 16 (cost = 1 << 26) 1000 + i as u32, // StartIndexLocation (-200i32 + i as i32) as u32, // BaseVertexLocation 5000 + i as u32, // StartInstanceLocation @@ -1932,7 +1938,7 @@ void main(uint3 t : SV_DispatchThreadID) { let mut zeroed = 0usize; for i in 0..RECORDS as usize { let rec = &out_words[i * 6..(i + 1) * 6]; - if rec[0] == (1 << 24) && rec[1] == 4 { + if rec[0] == (1 << 22) && rec[1] == 16 { kept += 1; } else { assert_eq!((rec[0], rec[1]), (0, 0), "excess draw must be zeroed"); @@ -2519,7 +2525,7 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { }; let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP"); let kinds = [0u32, 1, 2, 10]; - let values = [0u32, 1, 3, 100, 65_535, 65_536, 1 << 20, 1 << 24, (1 << 26) + 1, u32::MAX]; + let values = [0u32, 1, 3, 100, 65_535, 65_536, 1 << 20, (1 << 23) - 1, 1 << 23, 1 << 24, (1 << 26) + 1, u32::MAX]; // Every kind with many records, in two sources. let mut records: Vec<(u32, [u32; 5])> = Vec::new(); for kind in kinds { @@ -2612,7 +2618,7 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { let mut table = unsafe { std::ptr::write_bytes(budget_ptr, 0, 256); for r in 0..records { - for (w, word) in [1u32 << 24, 4, 5, 6].into_iter().enumerate() { + for (w, word) in [1u32 << 22, 16, 5, 6].into_iter().enumerate() { src_ptr.cast::().add(r as usize * 4 + w).write_volatile(word); } } @@ -2636,8 +2642,8 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { (0..records as usize).map(|r| back_ptr.cast::().add(r * batch::SLOT as usize / 4).read_volatile()).collect(), ) }; - assert_eq!(out.iter().filter(|&&v| v == 1 << 24).count(), filled, "{times} times {records}: {out:?}"); - assert!(out.iter().all(|&v| v == 0 || v == 1 << 24)); + assert_eq!(out.iter().filter(|&&v| v == 1 << 22).count(), filled, "{times} times {records}: {out:?}"); + assert!(out.iter().all(|&v| v == 0 || v == 1 << 22)); assert_eq!(spent, BUDGET.min((1 << 26) * times * records as u32)); } } diff --git a/crates/victory-gpu/src/indirect/batch.rs b/crates/victory-gpu/src/indirect/batch.rs index ed25aa5..21af58a 100644 --- a/crates/victory-gpu/src/indirect/batch.rs +++ b/crates/victory-gpu/src/indirect/batch.rs @@ -77,7 +77,10 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { record[w] = load(job.x & 3, job.y + w * 4); } if (kind <= 1) { - record[0] = min(record[0], 1u << 24); + if (record[0] >= 1u << 23) { + record[0] = 0; + record[1] = 0; + } record[1] = min(record[1], (1u << 26) / max(record[0], 1u)); cost = record[0] * record[1]; } else if (kind == 2) { @@ -91,8 +94,10 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { record[1] = g.y; record[2] = g.z; } else { + if (record[0] > 65535u) { + record[0] = 0; + } asked = record[0]; - record[0] = min(record[0], 65535u); record[1] = min(record[1], 1u); record[2] = min(record[2], 1u); cost = record[0] * record[1] * record[2] * 128u; From 2dfba4dbd83591fd317e0b2840a6bc4bf43f1bb7 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:14:38 -0600 Subject: [PATCH 335/445] Texture uploads wait for no mapping, ask no guards and hash cheaply; the sweep looks at a part; bakes pass once for what is new A bake's uploads waited for the lock the runtime holds while it remaps, and a staging buffer a draw kept waited at every later refresh (29 to 239 ms a frame, all threads, run n04): gone, a read through the kernel gets every page. A staging buffer made for one upload asks neither the write watch nor the guards (VICTORY_TEXTURE_ONCE=0: as before). blake3 makes way for a 128-bit digest (0.035 against 0.2 ms a megabyte). While textures are kept for minutes the sweep looks at 8,192 a time (VICTORY_TEXTURE_SWEEP=whole). The pass before a bake is made again only for something new. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 8 ++ crates/victory-gpu/src/draw.rs | 34 ++++- crates/victory-gpu/src/host.rs | 10 +- crates/victory-gpu/src/resource.rs | 38 ++++- crates/victory-gpu/src/texture.rs | 163 ++++++++++++++++++---- 5 files changed, 215 insertions(+), 38 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index b1b3b28..62777fd 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1358,6 +1358,14 @@ impl HostHeap { (if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame)) } + /// A number that changes when a slot is written or made due anew, and + /// whether memory was noted since a pass last took the notes. + pub(crate) fn texture_news(&self) -> (u64, bool) { + let writes = self.textures.lock().unwrap_or_else(|e| e.into_inner()).writes; + let noted = |ranges: &Mutex>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty(); + (writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN)) + } + /// Every title slot of the queue that is due at `frame`, and whether /// it was uploaded before (in part, or whole and waiting for another /// look): for the card accounting line diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e5fd151..4bca1ac 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -120,8 +120,14 @@ fn recheck_soon() -> bool { /// Frames ahead the pass before a bake takes slots from that are due only /// then ([`bake_exact`]): those of notices (1 and 2), and the first looks -/// again ([`RECHECK_FRAMES`]). -const BAKE_AHEAD: u64 = 12; +/// again ([`RECHECK_FRAMES`]), these at the frame's first bake alone (a +/// look reads 48 KiB, and a frame bakes up to sixteen times). +const BAKE_AHEAD: [u64; 2] = [12, 2]; + +/// What [`crate::descriptor::host::HostHeap::texture_news`] said when the +/// pass before a bake last served all there was, plus one (0: it did not): +/// until something is new, the next bakes of the frame need no pass. +static BAKE_SERVED: AtomicU64 = AtomicU64::new(0); /// The pixel shaders of the title's decoration bake (the title: /// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the @@ -1844,6 +1850,12 @@ impl State { return; }; let bake = bake && left > 0; + if bake && !first && bake_exact() { + let (writes, noted) = host.texture_news(); + if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 { + return; + } + } let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1; if bake && n.is_power_of_two() { let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); @@ -2027,7 +2039,9 @@ impl State { let on_time = due.len(); if baking { let known: std::collections::HashSet = due.iter().map(|&(index, _)| index).collect(); - let (ahead, _) = host.texture_slots_due(frame + BAKE_AHEAD, 1 << 16); + static AHEAD: AtomicU64 = AtomicU64::new(u64::MAX); + let again = AHEAD.swap(frame, Ordering::Relaxed) == frame; + let (ahead, _) = host.texture_slots_due(frame + BAKE_AHEAD[usize::from(again)], 1 << 16); due.extend(ahead.into_iter().filter(|(index, _)| !known.contains(index))); } HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed); @@ -2083,8 +2097,11 @@ impl State { None => (span, per_frame), }; let began = std::time::Instant::now(); + BAKE_SERVED.store(0, Ordering::Relaxed); + let mut served = true; for (index, write) in due { if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span { + served = false; break; } // A placed texture whose memory is not mapped (not streamed in @@ -2149,6 +2166,7 @@ impl State { } } let mut partly = None; + let mut there = None; if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) { let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let first = crate::resource::first_mip(&desc); @@ -2162,6 +2180,7 @@ impl State { continue; } host.texture_slot_here(index); + there = Some(mapped); if mapped < len { if mapped <= host.texture_slot_mapped(index) { HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed); @@ -2275,7 +2294,11 @@ impl State { continue; } if let Some(view) = &view { + // (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))); readable(list, sampled.kind, view); + crate::texture::PICKING.set(None); } if shows_other && let Some(handle) = heap.handle(index) { host.texture_slot_flip(list, index, handle); @@ -2291,7 +2314,7 @@ impl State { crate::host::log_removal_context(); return; } - let (bytes, whole) = crate::texture::staged(resource).unwrap_or((0, true)); + let (bytes, whole) = crate::texture::staged(resource, there.is_none()).unwrap_or((0, true)); // Not all of it there: looked at again next frame, and from // then on as a slot with nothing new (a placed texture: until // more of it is mapped; a texture object at an address the @@ -2340,6 +2363,9 @@ impl State { None => host.texture_slot_done(index, write, again), } } + if baking && served { + BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed); + } } /// For the frame listing, after a dropped dispatch's line: its group diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 5393d72..a90fb22 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -7531,11 +7531,17 @@ impl Meter { "textures from the first level viewed (VICTORY_HELD_LEVELS=0: whole), since the start: {copies} host copies of the \ levels viewed alone ({} MB on the card, {} MB of title memory whole), {grown} replaced by one with more levels, \ {flipped} slots made from their new view after its upload had run ({missed} written again first); {} uploads left \ - out as the host copy held those bytes (VICTORY_TEXTURE_SAME=0: made); {} MB of texture blocks free", + out as the host copy held those bytes (VICTORY_TEXTURE_SAME=0: made); {} MB of texture blocks free; \ + {} looks for textures to let go, {:.2} ms each, the longest {:.1}", bytes >> 20, whole >> 20, crate::draw::HEAP_TEXTURES_SAME.load(Ordering::Relaxed), - crate::pool::texture_room() >> 20 + crate::pool::texture_room() >> 20, + crate::resource::SWEPT_US[0].load(Ordering::Relaxed), + crate::resource::SWEPT_US[1].load(Ordering::Relaxed) as f64 + / 1e3 + / crate::resource::SWEPT_US[0].load(Ordering::Relaxed).max(1) as f64, + crate::resource::SWEPT_US[2].load(Ordering::Relaxed) as f64 / 1e3 ); } { diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index b44ba86..c524ba1 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1180,7 +1180,7 @@ pub(crate) struct HostTexture { /// What a host copy was filled with last: the first level of it and the /// hash of the title memory it was read from. #[cfg(windows)] -pub(crate) type Holds = std::sync::Mutex>; +pub(crate) type Holds = std::sync::Mutex>; /// [`HostTexture::serial`] of the last one made. #[cfg(windows)] @@ -2051,15 +2051,37 @@ pub(crate) fn let_go_idle() { } by_age.sort_unstable(); } - let every = all.iter().copied().filter(|_| most == u64::MAX); - for at in every.chain(by_age.iter().map(|&(_, at)| at)) { + // Without one, while textures are kept for minutes, a part of them at + // each look, the next one at the next: a play has over 100,000 + // (`VICTORY_TEXTURE_SWEEP=whole`: all each time, as before). + const PART: usize = 8192; + static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + static WHOLE: std::sync::OnceLock = std::sync::OnceLock::new(); + let whole = *WHOLE.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_some_and(|v| v == "whole")); + let part = if most != u64::MAX { + 0 + } else if whole || idle_ms < 60_000 { + usize::MAX + } else { + PART + }; + let from = if part == PART { FROM.load(Relaxed) } else { 0 }; + let mut looked = 0; + let began = std::time::Instant::now(); + for at in all.range(from..).take(part).copied().chain(by_age.iter().map(|&(_, at)| at)) { if bytes >= most { break; } + looked += 1; + if part == PART { + FROM.store(if looked == PART { at + 1 } else { 0 }, Relaxed); + } // SAFETY: a texture leaves the table before it is freed, under the // lock held here (`Drop for Resource`). let r = unsafe { &*(at as *const Resource) }; - if !fills(&r.desc) || crate::texture::host_wrote(at) { + // (Without its lock first: most were used lately or have none.) + let used = r.host.used.load(Relaxed); + if used == 0 || !fills(&r.desc) || !crate::host::long_ago(used, idle_ms, IDLE_FRAMES) || crate::texture::host_wrote(at) { continue; } let gone = { @@ -2091,6 +2113,9 @@ pub(crate) fn let_go_idle() { crate::host::retire(host); } } + SWEPT_US[0].fetch_add(1, Relaxed); + SWEPT_US[1].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + SWEPT_US[2].fetch_max(began.elapsed().as_micros() as u64, Relaxed); if went > 0 { crate::host::trail(|| { format!( @@ -2102,6 +2127,11 @@ pub(crate) fn let_go_idle() { } } +/// Since the start: looks of [`let_go_idle`], their microseconds, and the +/// longest one's. +#[cfg(windows)] +pub(crate) static SWEPT_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + /// For the memory line: the host copies the sweep never lets go /// ([`let_go_idle`] takes only copies of textures the title fills that the /// host never copied into), by what would say they are dead weight. A diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index f970f70..7ad9915 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -57,9 +57,9 @@ pub(crate) struct Staging { /// Which host copy it uploads into, and what that is told to hold. serial: u64, holds: Arc, - /// Title memory being remapped is waited for whatever [`no_wait`] says: - /// a list that bakes from the texture now recorded the upload. - waits: std::sync::atomic::AtomicBool, + /// Made by the pass over textures picked by index, for one upload + /// ([`once`]): read when the list is submitted, and never looked at again. + once: std::sync::atomic::AtomicBool, /// The staging buffer's bytes (counted in `STAGED` while it lives). bytes: u64, memory: *const u8, @@ -95,7 +95,7 @@ pub(crate) struct Staging { /// (memory not watched), or the write-watch asking it was detiled after. #[derive(Default)] struct Last { - hash: Option, + hash: Option, asked: u64, /// The frame a partly mapped texture was last read in. partial: Option, @@ -648,11 +648,76 @@ pub(crate) fn upload(list: &HostList, resource: This, _texture: &ID3D12Resource) } thread_local! { - /// The thread records uploads for a draw that bakes from them - /// ([`Staging::waits`]). + /// The thread records uploads for a draw that bakes from them. pub(crate) static BAKING: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// The thread records the upload of a texture picked by index, of which + /// that many bytes were found mapped just now (`u64::MAX`: not asked). + pub(crate) static PICKING: std::cell::Cell> = const { std::cell::Cell::new(None) }; } +/// Whether a staging buffer made for one upload of a texture picked by index +/// is filled without asking the write watch and the guards +/// (`VICTORY_TEXTURE_ONCE=0`: with, as before). What they say is for the next +/// refresh, and there is none: the buffer goes with the upload. Asking guards +/// the texture's blocks (a change of protection, under the lock every other +/// refresh wants), and the title's next write there faults to open them. +fn once() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_ONCE").is_none_or(|v| v != "0")) +} + +/// A 128-bit digest of `bytes`, to tell a texture's memory changed: four +/// lanes of folded multiplications over 64 bytes at a time. (Not a +/// cryptographic one, which took 0.27 ms a megabyte, four times the detiling +/// it was to spare; nobody makes up textures to collide.) +pub(crate) fn digest(bytes: &[u8]) -> Digest { + const K: [u64; 8] = [ + 0xa076_1d64_78bd_642f, + 0xe703_7ed1_a0b4_28db, + 0x8ebc_6af0_9c88_c6e3, + 0x5899_65cc_7537_4cc3, + 0x1d8e_4e27_c47d_124f, + 0xeb44_acca_b455_d165, + 0x9e37_79b9_7f4a_7c15, + 0xc2b2_ae3d_27d4_eb4f, + ]; + let fold = |a: u64, b: u64| { + let p = u128::from(a) * u128::from(b); + p as u64 ^ (p >> 64) as u64 + }; + let word = |b: &[u8]| { + let mut w = [0; 8]; + w[..b.len()].copy_from_slice(b); + u64::from_le_bytes(w) + }; + let mut lanes = [K[0], K[1], K[2], K[3]]; + let mut step = |block: &[u8; 64]| { + for (i, lane) in lanes.iter_mut().enumerate() { + let a = word(&block[16 * i..16 * i + 8]); + let b = word(&block[16 * i + 8..16 * i + 16]); + // (What went in is added again: a product with a factor of zero + // forgets neither the lane nor the block.) + *lane = fold(a ^ K[4 + i], b ^ *lane).wrapping_add(a.rotate_left(23) ^ lane.rotate_left(41)) ^ b; + } + }; + let mut blocks = bytes.chunks_exact(64); + for block in &mut blocks { + step(block.try_into().unwrap_or(&[0; 64])); + } + let rest = blocks.remainder(); + let mut last = [0u8; 64]; + last[..rest.len()].copy_from_slice(rest); + step(&last); + let len = bytes.len() as u64; + let low = fold(lanes[0] ^ K[1], lanes[1] ^ len) ^ fold(lanes[2] ^ K[3], lanes[3] ^ K[5]); + let high = fold(lanes[0].rotate_left(32) ^ K[6], lanes[2] ^ len) ^ fold(lanes[1].rotate_left(32) ^ K[7], lanes[3] ^ K[2]); + Digest(u128::from(low) << 64 | u128::from(high)) +} + +/// See [`digest`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Digest(u128); + /// [`upload`] of the levels from `first` on, the ones a view shows: of a /// texture the title placed there may be no memory of the larger ones, and /// what lies there is another texture's. (After victory-amd 4436f8f1.) @@ -684,8 +749,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { return; }; use std::sync::atomic::Ordering::Relaxed; - if BAKING.get() { - staging.waits.store(true, Relaxed); + let picking = PICKING.get(); + if picking.is_none() { + // A draw samples it through a table: kept and checked from here on. + staging.once.store(false, Relaxed); } staging.used.store(crate::host::moment(), Relaxed); // Levels on demand: a view of the texture now starts at another @@ -727,7 +794,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexUploads, 1); if no_wait() && fill_unlocked() { - let there = mapped_bytes(staging.memory, staging.read); + let there = match picking { + Some(there) if there != u64::MAX => there, + _ => mapped_bytes(staging.memory, staging.read), + }; staging.expected.store(there, Relaxed); } const COPY_DEST: u32 = 0x400; @@ -1064,7 +1134,11 @@ impl Staging { let start = self.memory as usize; let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); let last = &mut *last; - if let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) { + let alone = self.once.load(std::sync::atomic::Ordering::Relaxed); + if alone && last.hash.is_some() { + return 0; + } + if !alone && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) { if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { return 0; } @@ -1092,7 +1166,8 @@ impl Staging { static GUARD: std::sync::OnceLock = std::sync::OnceLock::new(); // The guard saw no write: a change the hash finds came another way. let mut blind = false; - if *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) + if !alone + && *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true)) { const HASH_EVERY: u64 = 8; @@ -1127,7 +1202,7 @@ impl Staging { // stays mapped (see `crate::watch::title_memory_reading`; without // it a page went between the asking and the read in runs 71 and // 74). - let _mapped = if no_wait() && !self.waits.load(std::sync::atomic::Ordering::Relaxed) { + let _mapped = if no_wait() { // Not waited for: while the runtime remaps title memory the // texture is read through the kernel instead, whole or not at // all (`no_wait`). @@ -1155,7 +1230,7 @@ impl Staging { crate::copystat::add(crate::copystat::C::TexHashed, size as u64); let changed = with_read(size, |read| { crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); - let hash = blake3::hash(read); + let hash = digest(read); if last.hash == Some(hash) { return false; } @@ -1177,7 +1252,7 @@ impl Staging { } if through_copy() { return with_title(self.memory, size, |tiled| { - let hash = blake3::hash(tiled); + let hash = digest(tiled); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); if last.hash == Some(hash) { @@ -1194,7 +1269,7 @@ impl Staging { // SAFETY: committed memory of the texture's layout size, and it // stays committed while `_mapped` is held. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; - let hash = blake3::hash(tiled); + let hash = digest(tiled); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); if last.hash == Some(hash) { @@ -1221,7 +1296,7 @@ impl Staging { if !crate::host::read_into(self.memory, read) { return false; } - let hash = blake3::hash(read); + let hash = digest(read); if last.hash != Some(hash) { last.hash = Some(hash); self.detile(read); @@ -1256,14 +1331,14 @@ impl Staging { let mut got = 0; for _ in 0..4 { got = crate::host::read_there(self.memory, read) as u64; - crate::watch::change_over(); there = mapped_bytes(self.memory, size); - if got >= there { + if got >= there.max(self.expected.load(Relaxed)) { break; } + crate::watch::change_over(); } if got != 0 { - last.hash = Some(blake3::hash(read)); + last.hash = Some(digest(read)); self.detile(read); } got @@ -1361,14 +1436,14 @@ pub(crate) fn fingerprint(at: u64, len: u64) -> u64 { static READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } let len = len as usize; - let mut hasher = blake3::Hasher::new(); + let mut print = 0u128; READ.with(|read| { let mut read = read.borrow_mut(); read.resize(3 * WINDOW, 0); let mut take = |from: usize, bytes: usize| { read[..bytes].fill(0); crate::host::copy_mapped(read.as_mut_ptr(), (at as usize + from) as *const u8, bytes, false); - hasher.update(&read[..bytes]); + print = print.rotate_left(37) ^ digest(&read[..bytes]).0; }; if len <= 3 * WINDOW { take(0, len); @@ -1378,9 +1453,7 @@ pub(crate) fn fingerprint(at: u64, len: u64) -> u64 { take(len - WINDOW, WINDOW); } }); - let hash = hasher.finalize(); - let mut first = [0u8; 8]; - first.copy_from_slice(&hash.as_bytes()[..8]); + let first = (print as u64 ^ (print >> 64) as u64).to_le_bytes(); u64::from_le_bytes(first) | 1 } @@ -1436,7 +1509,7 @@ pub(crate) fn unchanged(resource: This, first: u32) -> bool { if crate::host::read_there(memory, read) == 0 { return false; } - blake3::hash(read) == held + digest(read) == held }) } @@ -1456,12 +1529,13 @@ pub(crate) fn is_staged(resource: This) -> bool { /// The bytes of a title texture's memory, and whether all of it is mapped, /// if the texture has been staged for upload. -pub(crate) fn staged(resource: This) -> Option<(u64, bool)> { +/// (Whether it is mapped is asked only if `ask`; else it counts as mapped.) +pub(crate) fn staged(resource: This, ask: bool) -> Option<(u64, bool)> { let s = { let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); map.as_ref()?.get(&(resource as usize))?.clone() }; - Some((s.read as u64, committed(s.memory, s.read))) + Some((s.read as u64, !ask || committed(s.memory, s.read))) } /// Whether `[at, at + len)` is committed memory (streamed textures may be @@ -1713,7 +1787,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O read, serial: copy.serial, holds: copy.holds.clone(), - waits: std::sync::atomic::AtomicBool::new(false), + once: std::sync::atomic::AtomicBool::new(once() && !on_demand && PICKING.get().is_some()), bytes: total, memory, last: Mutex::default(), @@ -1932,6 +2006,36 @@ mod allocation_costs { } } + /// The digest tells every length and every changed byte apart, zeros + /// among them. + #[test] + fn a_digest_tells_bytes_apart() { + use super::digest; + let zeros = [0u8; 400]; + let mut seen: Vec = (0..400).map(|n| digest(&zeros[..n])).collect(); + for at in 0..400 { + for value in [1u8, 0x80, 0xff] { + let mut bytes = zeros; + bytes[at] = value; + seen.push(digest(&bytes)); + } + } + let text: Vec = (0..400u32).map(|i| (i * 37 >> 2) as u8).collect(); + for at in 0..399 { + let mut bytes = text.clone(); + bytes.swap(at, at + 1); + if bytes != text { + seen.push(digest(&bytes)); + } + } + seen.push(digest(&text)); + let n = seen.len(); + seen.sort_unstable_by_key(|d| d.0); + seen.dedup(); + assert_eq!(seen.len(), n); + assert_eq!(digest(&text), digest(&text.clone())); + } + /// What a texture met for the first time costs, by step, in /// milliseconds a megabyte on one thread: for whether a store of /// detiled copies on disk could be worth it (its key is a hash of the @@ -1965,6 +2069,9 @@ mod allocation_costs { timed("blake3", &mut || { std::hint::black_box(blake3::hash(&title)); }); + timed("digest", &mut || { + std::hint::black_box(super::digest(&title)); + }); timed("detiled into upload memory", &mut || { let mut at = 0; for (mip, m) in layout.mips.iter().enumerate() { From e1561288e7b7d0c072ca23148e10e70211a20618 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:29:50 -0600 Subject: [PATCH 336/445] Title memory by address: packed structures that are gone give their pages back; ranges only for views written 4 MiB for every constant that looked like an address took a third of the pages (run light-5). Which pages came for what is in the ten-second line. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/memory.rs | 185 ++++++++++++++++++++++++++----- crates/victory-gpu/src/shadow.rs | 4 +- 2 files changed, 161 insertions(+), 28 deletions(-) diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index a1168c5..2daab6f 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -36,8 +36,9 @@ //! packed ("dehydrated") structure there, all of it: the title ships its //! structures packed, and the builder's rehydration stages unpack each in //! place once it is streamed in; -//! - 4 MiB from each pair of root constants that is a title address and from -//! each root constant that is one in 256-byte units (structures built); +//! - 4 MiB from each unordered access view outside buffers (structures built); +//! - the page of each pair of root constants that is a title address and of +//! each root constant that is one in 256-byte units; //! - the first page of every structure a list's upload memory names //! (a top-level build's instances). //! @@ -58,7 +59,10 @@ //! dispatches was given that buffer as an unordered access view (its scratch //! memory, its results); what else a store reaches is an arena's. //! -//! shortcut: a page is kept for the rest of the run. +//! A packed structure is gone when title memory has no header of it any more +//! (looked at over [`SWEEP`] frames); the pages it alone has are given back. +//! +//! shortcut: a page held for anything else is kept for the rest of the run. //! shortcut: pages a list does not name are looked at again in turn, over //! [`SWEEP`] frames. @@ -80,15 +84,15 @@ const PAGE: u64 = 1 << 16; const ARENA: u64 = 64 << 20; /// What is compared at a time. const PIECE: usize = 4096; -/// Pages held, at most (2 GiB). -const MOST: usize = 1 << 15; +/// Pages held, at most (3 GiB). +const MOST: usize = 3 << 14; /// Pages of title memory with small title buffers in them, at most. const WINDOWS: usize = 512; /// The biggest packed structure taken for one. const PACKED: u64 = 64 << 20; /// A packed structure not named for so many frames is another one. const AGAIN: u64 = 8; -/// From a root view; from an address in constants. +/// From a root view; from one that is written (a structure being built). const VIEW: u64 = 256 << 10; const BUILT: u64 = 4 << 20; /// The biggest title buffer whose builder results come back. @@ -97,7 +101,7 @@ const BACK: u64 = 256 << 10; /// structure that is not right goes anywhere, and 2,048 a frame took all the /// pages there are in the first seconds (run light-4). const FAULTS: usize = 128; -const FAULTS_ALL: usize = 8192; +const FAULTS_ALL: usize = 2048; /// Frames over which every page is looked at once. const SWEEP: usize = 128; @@ -119,6 +123,19 @@ struct Held { taken: u64, /// The frame it was last looked at in. looked: u64, + /// Packed structures that have bytes in it, and whether it is held for + /// them alone. + owners: u32, + theirs: bool, +} + +/// A packed structure the builder came to. +struct Packed { + /// The frame it last did. + frame: u64, + len: u64, + /// Its first two dwords in title memory. + header: u64, } struct Memory { @@ -140,7 +157,12 @@ struct Memory { /// Windows of title memory itself ([`Memory::map`]). windows: usize, /// Packed structures the builder came to: the frame it last did. - packed: HashMap, + packed: HashMap, + /// Their addresses in the order they came, and where the sweep is. + packed_order: Vec, + packed_sweep: usize, + /// Places of pages given back: the copy, the address in the arena. + free: Vec<(usize, usize)>, /// Copies of title buffers the builder may store in. open: std::collections::HashSet, /// Pages taken from faults. @@ -169,6 +191,11 @@ struct Stats { looked: u64, changed: u64, packed: u64, + packed_bytes: u64, + gone: u64, + /// Pages that came for an address in constants, a written view, another + /// view, a structure named in upload memory. + came: [u64; 4], micros: u64, } @@ -213,6 +240,9 @@ impl Memory { sweep: 0, windows: 0, packed: HashMap::new(), + packed_order: Vec::new(), + packed_sweep: 0, + free: Vec::new(), open: Default::default(), faulted: 0, heaps: HashMap::new(), @@ -337,6 +367,10 @@ impl Memory { ONCE.call_once(|| tracing::warn!(MOST, "title memory by address: no more pages are taken; others read zeros")); return false; } + if let Some((copy, at)) = self.free.pop() { + self.hold(page, at, copy); + return true; + } if self.used == ARENA / PAGE { let Some(at) = crate::upload::reserve(ARENA as usize) else { return false; @@ -355,12 +389,71 @@ impl Memory { }; let offset = self.used * PAGE; self.used += 1; - self.pages.insert(page, Held { at: arena + offset as usize, copy, taken: 0, looked: u64::MAX }); - self.order.push(page); - fill(self.entry(page), copy, offset); + self.hold(page, arena + offset as usize, copy); true } + /// `page` is held at `at` in the arena that is `copy`. + fn hold(&mut self, page: u64, at: usize, copy: usize) { + self.pages.insert(page, Held { at, copy, taken: 0, looked: u64::MAX, owners: 0, theirs: false }); + self.order.push(page); + fill(self.entry(page), copy, at as u64 - self.copies[copy].span().0); + } + + /// The packed structure at `address` is gone: the pages it alone had are + /// given back. + fn gone(&mut self, address: u64) { + let Some(packed) = self.packed.remove(&address) else { return }; + for page in address / PAGE..=(address + packed.len - 1) / PAGE { + let Some(held) = self.pages.get_mut(&page) else { continue }; + held.owners = held.owners.saturating_sub(1); + if held.owners == 0 && held.theirs { + self.free.push((held.copy, held.at)); + self.pages.remove(&page); + // SAFETY: an entry of the directory, under the mutex. + unsafe { self.entry(page).write_volatile(0) }; + } + } + self.stats.gone += 1; + } + + /// Whether the packed structure at `address` is still in title memory. + fn there(&self, address: u64) -> bool { + let mut header = [0u8; 8]; + crate::texture::committed(address as *const u8, 8) && { + crate::host::copy_mapped(header.as_mut_ptr(), address as *const u8, 8, false); + self.packed.get(&address).is_some_and(|p| p.header == u64::from_le_bytes(header)) + } + } + + /// Looks at some of the pages and packed structures again. + fn look_again(&mut self) { + for _ in 0..self.order.len().div_ceil(SWEEP) { + self.sweep = (self.sweep + 1) % self.order.len(); + let page = self.order[self.sweep]; + if self.pages.contains_key(&page) { + self.bring(page, page + 1); + } else { + self.order.swap_remove(self.sweep); + if self.order.is_empty() { + break; + } + } + } + for _ in 0..self.packed_order.len().div_ceil(SWEEP) { + self.packed_sweep = (self.packed_sweep + 1) % self.packed_order.len(); + let address = self.packed_order[self.packed_sweep]; + if !self.packed.contains_key(&address) { + self.packed_order.swap_remove(self.packed_sweep); + if self.packed_order.is_empty() { + break; + } + } else if !self.there(address) { + self.gone(address); + } + } + } + /// A dispatch of the builder was given `address` to write: if it is in a /// title buffer's copy, stores by address reach that from here on. fn opens(&mut self, address: u64) { @@ -453,9 +546,31 @@ impl Memory { let Some(len) = packed_len(u64::from_le_bytes(header)) else { return false; }; - let last = self.packed.insert(address, self.frame); - if last.is_some_and(|f| f + AGAIN >= self.frame) { - return true; + let header = u64::from_le_bytes(header); + if let Some(known) = self.packed.get_mut(&address) { + let soon = known.frame + AGAIN >= self.frame; + known.frame = self.frame; + if known.header == header && soon { + return true; + } + if known.header != header { + self.gone(address); + } + } + if !self.packed.contains_key(&address) { + self.packed.insert(address, Packed { frame: self.frame, len, header }); + self.packed_order.push(address); + for page in address / PAGE..=(address + len - 1) / PAGE { + let new = !self.pages.contains_key(&page); + if !self.map(page) { + continue; + } + if let Some(held) = self.pages.get_mut(&page) { + held.owners += 1; + held.theirs |= new; + } + } + self.stats.packed_bytes += len; } self.ready(address, len); let mut title = [0u8; PIECE]; @@ -575,7 +690,8 @@ impl Memory { tracing::info!( "title memory by address: {} pages ({} MB) in {} arenas, {} copies in all; per frame {:.0} dispatches that read, {:.0} that build, \ {:.1} pages that had no copy, {:.1} pages turned down, {:.1} results brought back; {:.0} pages looked at, {:.1} KB changed, \ - {:.1} packed structures ({} seen), {:.2} ms; {} windows", + {:.1} packed structures ({} there), {:.2} ms; {} windows; since the last line {} KB of packed structures came and {} of them went, \ + and pages for constants {}, views written {}, others {}, upload memory {}, faults in all {}", self.pages.len(), (self.pages.len() as u64 * PAGE) >> 20, self.arenas.len(), @@ -590,7 +706,14 @@ impl Memory { s.packed as f64 / frames, self.packed.len(), s.micros as f64 / 1000.0 / frames, - self.windows + self.windows, + s.packed_bytes >> 10, + s.gone, + s.came[0], + s.came[1], + s.came[2], + s.came[3], + self.faulted ); self.stats.from = Some((now, self.frame)); } @@ -663,12 +786,7 @@ pub(crate) fn ready( m.frame = frame; m.refused.clear(); m.take_faults(); - let n = m.order.len().div_ceil(SWEEP); - for _ in 0..n { - m.sweep = (m.sweep + 1) % m.order.len(); - let page = m.order[m.sweep]; - m.bring(page, page + 1); - } + m.look_again(); m.report(); } let builds = use_ != Use::Reads; @@ -682,7 +800,8 @@ pub(crate) fn ready( // in one in 256-byte units (the builder's alone). A constant that only // looks like one names memory nothing reads; one that is not the title's // memory is refused. - let built = if builds { BUILT } else { PAGE }; + let held = |m: &Memory| m.pages.len() as u64; + let before = held(m); for (i, &c) in constants.iter().enumerate() { if let Some(&high) = constants.get(i + 1) && (1..=0x1F).contains(&high) @@ -690,16 +809,17 @@ pub(crate) fn ready( { let at = u64::from(c) | u64::from(high) << 32; if named(1, at) { - m.ready(at, built); + m.ready(at, 1); } } if builds && (0x0100_0000..0x2000_0000).contains(&c) { let at = u64::from(c) << 8; if named(1, at) { - m.ready(at, built); + m.ready(at, 1); } } } + let mut came = [held(m) - before, 0, 0, 0]; for &at in addresses.iter().filter(|&&a| a >= 1 << 32) { // (Several structures to a page.) let packed = builds && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize) && m.unpacks(at); @@ -711,18 +831,31 @@ pub(crate) fn ready( m.small(list, start, len); } m.opens(at); + if !packed && crate::shadow::in_buffer(at, 1).is_none() { + let before = held(m); + m.ready(at, BUILT); + came[1] += held(m).saturating_sub(before); + } } if packed || !named(2, at) { continue; } + let before = held(m); match crate::shadow::in_buffer(at, 1) { Some(_) => { m.ready(at, 1); m.named_in_upload(at); + came[3] += held(m).saturating_sub(before); + } + None => { + m.ready(at, if builds { VIEW } else { PAGE }); + came[2] += held(m).saturating_sub(before); } - None => m.ready(at, if builds { VIEW } else { PAGE }), } } + for (sum, n) in m.stats.came.iter_mut().zip(came) { + *sum += n; + } let key = std::ptr::from_ref(heap) as usize; let (base, made) = match m.heaps.get(&key) { Some(&run) => run, diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 3f2b89d..e3c8fc1 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -4592,14 +4592,14 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option> { if !cards() || !host.card_ready() { return None; } - // At most so much on the card's own memory (2 GiB unless + // At most so much on the card's own memory (4 GiB unless // `VICTORY_MEMORY_CARD_MB` says otherwise), and while it has room; past // that the side shaders see is in the PC's memory. static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); static USED: AtomicU64 = AtomicU64::new(0); let most = *MOST.get_or_init(|| { let mb = std::env::var("VICTORY_MEMORY_CARD_MB").ok().and_then(|v| v.trim().parse::().ok()); - mb.unwrap_or(2048) << 20 + mb.unwrap_or(4096) << 20 }); let room = host.video_memory().is_none_or(|[budget, used, ..]| used + len < budget / 100 * 97); let (staging, data) = host.shared_buffer(len)?; From 2c982ee5a58693dc116f1c63265135d2d2315c12 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:32:52 -0600 Subject: [PATCH 337/445] Landing goes beside the guards while mappings change; rectangles read without that lock Pieces went through the title's address, guards opened, whenever the runtime was mapping pages, which is most of the time since they are mapped in groups (28 of 1,620 pieces a frame beside the guards in run textures-4, 640 before): 5,000 blocks opened and 7,000 guarded a frame. VICTORY_LAND_ANYTIME=0: as before. The vertices of rectangle lists are read through the kernel at submission, not under the lock the mapping holds. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 13 ++++++++----- crates/victory-gpu/src/land.rs | 25 +++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 4bca1ac..7197f01 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3187,15 +3187,18 @@ impl State { let (from, to, stride) = (from as usize, to as usize, stride as usize); let n = rects as usize; list.defer_host_read(from, n * 3 * stride, move || { - // The vertices are read in place, at submission: no change - // of mapping under the read (see - // `crate::watch::title_memory_reading`). - let _mapped = crate::watch::title_memory_reading(); + // The vertices are read through the kernel, at submission; in + // place only if that fails, with no change of mapping under + // the read (see `crate::watch::title_memory_reading`): while + // the world streams a change is under way most of the time, + // and this is the thread that submits. + let mut read = vec![0u8; n * 3 * stride]; + let held = (!crate::host::read_into(from as *const u8, &mut read)).then(crate::watch::title_memory_reading); // SAFETY: the vertices lie in a title buffer (checked when // recorded) and the scratch memory is the list's. let (src, dst) = unsafe { ( - std::slice::from_raw_parts(from as *const u8, n * 3 * stride), + if held.is_some() { std::slice::from_raw_parts(from as *const u8, n * 3 * stride) } else { &read[..] }, std::slice::from_raw_parts_mut(to as *mut u8, n * 6 * stride), ) }; diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index f8d1cf9..34c359e 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -419,6 +419,26 @@ impl Had { } } +/// Whether a piece is put through a view of ours while the runtime changes +/// a mapping too (`VICTORY_LAND_ANYTIME=0`: through the title's address, as +/// before). +/// +/// While the world streams a change is under way nearly all the time (pages +/// are mapped in groups, eight threads side by side: 28 of 1,620 pieces a +/// frame went through a view of ours in run textures-4, 630 in run n03). Put +/// through the title's address a piece opens the guards of its blocks, 5,000 +/// changes of protection a frame, which wait for the address-space lock the +/// mapping wants as well, and every refresh guards them again: the frame went +/// from 105 to 140 ms. The record names a run of a section only while it is +/// mapped there (it is taken out before a view goes and put in when one is +/// there), so the change is one of other memory, or one the title makes of +/// memory its shaders are writing at that moment, which it may not (its +/// fences are signalled after the landing). +fn anytime() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAND_ANYTIME").is_none_or(|v| v != "0")) +} + /// What a job wrote beside the guards, to be noted ([`Notes::flush`]). #[derive(Default)] pub(crate) struct Notes { @@ -528,9 +548,10 @@ unsafe fn piece_at( }; // From here until the piece is put the runtime changes no mapping: our // view's address stays where the title sees `title`. Not waited for: if - // a change is under way, the title's own address does. + // a change is under way, what the record of the views says now does + // ([`anytime`]), or the title's own address. let reading = beside.then(crate::watch::title_memory_reading_now).flatten(); - let beside = reading.as_ref().and_then(|_| crate::inplace::beside(title, end)); + let beside = if reading.is_some() || beside && anytime() { crate::inplace::beside(title, end) } else { None }; count(stat::PIECES, 1); count(if beside.is_some() { stat::BESIDE } else { stat::DIRECT }, 1); // The pages that differ, before any is written: none, and the guard From 8d6b1a6c7677fec753cc636cd0e5f837c6c751ac Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:38:11 -0600 Subject: [PATCH 338/445] Batched clamp: an unfilled mesh record is all zeros, as the clamp of one leaves it Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/indirect/batch.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/victory-gpu/src/indirect/batch.rs b/crates/victory-gpu/src/indirect/batch.rs index 21af58a..e6da6a1 100644 --- a/crates/victory-gpu/src/indirect/batch.rs +++ b/crates/victory-gpu/src/indirect/batch.rs @@ -96,6 +96,8 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { } else { if (record[0] > 65535u) { record[0] = 0; + record[1] = 0; + record[2] = 0; } asked = record[0]; record[1] = min(record[1], 1u); From 2132366127aaa8451a9f472b5e37dea04961f6b6 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:38:51 -0600 Subject: [PATCH 339/445] AMD's wait instructions are replaced in place at their first fault (VICTORY_PATCH_WAITS=0: emulated each time) monitorx and mwaitx raised an illegal instruction exception at every pass of the title's wait loops. Diagnostics builds log the faulting console instructions a second by kind and place. Co-Authored-By: Claude Opus 5.5 --- crates/victory-loader/src/console_insn.rs | 227 +++++++++++++++++++++- 1 file changed, 225 insertions(+), 2 deletions(-) diff --git a/crates/victory-loader/src/console_insn.rs b/crates/victory-loader/src/console_insn.rs index 946230d..775961c 100644 --- a/crates/victory-loader/src/console_insn.rs +++ b/crates/victory-loader/src/console_insn.rs @@ -46,6 +46,154 @@ static EMULATED: AtomicU64 = AtomicU64::new(0); static ASKED: AtomicU64 = AtomicU64::new(0); static ZEROED: AtomicU64 = AtomicU64::new(0); +/// Whether `monitorx` and `mwaitx` are replaced in the title's code the first time they fault +/// (`monitorx` by a 3-byte no-op, `mwaitx` by `pause` and a no-op), so that they never fault +/// again. Emulated, each pass of such a wait loop is two trips into Windows and back, through +/// every vectored handler, and no lighter a wait for it: the emulation does no more than +/// `pause` either, and the loop looks at its value again after it. On by default; +/// `VICTORY_PATCH_WAITS=0` emulates each time, as before. +fn patches_waits() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PATCH_WAITS").is_none_or(|v| v != "0")) +} + +/// What replaces the 3 bytes of a wait instruction. +fn wait_patch(what: ConsoleOnly) -> Option<[u8; 3]> { + match what { + ConsoleOnly::Monitorx => Some([0x0f, 0x1f, 0x00]), + ConsoleOnly::Mwaitx => Some([0xf3, 0x90, 0x90]), + _ => None, + } +} + +/// The aligned 8 bytes `word` around address `at` with the 3 bytes at `at` replaced; `None` +/// where they do not all lie in those 8. +fn with_patch(word: u64, at: usize, patch: [u8; 3]) -> Option { + let offset = at & 7; + if offset + patch.len() > 8 { + return None; + } + let mut bytes = word.to_le_bytes(); + bytes[offset..offset + patch.len()].copy_from_slice(&patch); + Some(u64::from_le_bytes(bytes)) +} + +/// One thread at a time changes code: a second one would take the first one's loosened +/// protection for the page's own. +static PATCHING: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Replaces the 3 bytes at `at`, which are `was`, by `patch`, in one store that other threads +/// see whole: whether they are replaced now (not where they cross 8 aligned bytes, or the page +/// cannot be written). +/// +/// # Safety +/// `at` is in code that stays mapped, and `patch` does for it what `was` does. +unsafe fn patch(at: usize, was: [u8; 3], patch: [u8; 3]) -> bool { + use std::sync::atomic::Ordering::SeqCst; + 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; + if (at & 7) + 3 > 8 { + return false; + } + let _one = PATCHING.lock().unwrap_or_else(|e| e.into_inner()); + let word = (at & !7) as *mut u64; + let here = (at & 7)..(at & 7) + 3; + let mut old = 0u32; + // SAFETY: the aligned 8 bytes around the instruction lie in one page of mapped code, made + // writable for the store and put back. + unsafe { + if VirtualProtect(word.cast(), 8, PAGE_EXECUTE_READWRITE, &mut old) == 0 { + return false; + } + let done = AtomicU64::from_ptr(word) + .fetch_update(SeqCst, SeqCst, |now| if now.to_le_bytes()[here.clone()] == was { with_patch(now, at, patch) } else { None }) + // (Another thread's fault at the same place: done already.) + .map_or_else(|now| now.to_le_bytes()[here.clone()] == patch, |_| true); + VirtualProtect(word.cast(), 8, old, &mut old); + FlushInstructionCache(GetCurrentProcess(), word.cast(), 8); + done + } +} + +/// Diagnostics: how often each place in the title's code raises one of these exceptions, the +/// busiest logged every five seconds. +#[cfg(feature = "diagnostics")] +mod sites { + use super::{AtomicU64, Relaxed}; + use std::sync::atomic::AtomicUsize; + + /// Address, what is there (an index into [`NAMES`]), exceptions since the last line. + static SITES: [(AtomicUsize, AtomicUsize, AtomicU64); 512] = + [const { (AtomicUsize::new(0), AtomicUsize::new(0), AtomicU64::new(0)) }; 512]; + const NAMES: [&str; 8] = ["other", "clwb", "monitorx", "mwaitx", "clzero", "clzero loop", "rdpru", "extrq/insertq"]; + static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); + static PATCHED: AtomicU64 = AtomicU64::new(0); + + pub(super) fn patched() { + PATCHED.fetch_add(1, Relaxed); + } + + pub(super) fn count(at: usize, what: super::ConsoleOnly) { + use super::ConsoleOnly as C; + let kind = match what { + C::Clwb => 1, + C::Monitorx => 2, + C::Mwaitx => 3, + C::Clzero => 4, + C::ClzeroLoop { .. } => 5, + C::Rdpru => 6, + C::Extrq { .. } | C::Insertq { .. } => 7, + _ => 0, + }; + let mut i = (at ^ at >> 9) % SITES.len(); + for _ in 0..8 { + let s = &SITES[i]; + let there = s.0.compare_exchange(0, at, Relaxed, Relaxed).unwrap_or_else(|there| there); + if there == 0 || there == at { + s.1.store(kind, Relaxed); + s.2.fetch_add(1, Relaxed); + break; + } + i = (i + 1) % SITES.len(); + } + // Now and then: is a line due? Never waited for. + if let Ok(mut last) = LAST.try_lock() { + let since = *last.get_or_insert_with(std::time::Instant::now); + if since.elapsed().as_secs() >= 5 { + let s = since.elapsed().as_secs_f64(); + *last = Some(std::time::Instant::now()); + drop(last); + line(s); + } + } + } + + fn line(seconds: f64) { + let mut all: Vec<(u64, usize, usize)> = + SITES.iter().map(|s| (s.2.swap(0, Relaxed), s.0.load(Relaxed), s.1.load(Relaxed))).filter(|s| s.0 > 0).collect(); + all.sort_unstable_by_key(|s| std::cmp::Reverse(s.0)); + let mut kinds = [0u64; NAMES.len()]; + for s in &all { + kinds[s.2] += s.0; + } + let kinds: Vec = NAMES + .iter() + .zip(kinds) + .filter(|(_, n)| *n > 0) + .map(|(name, n)| format!("{name} {:.0}", n as f64 / seconds)) + .collect(); + let top: Vec = + all.iter().take(8).map(|s| format!("{:#x} {} {:.0}", s.1, NAMES[s.2], s.0 as f64 / seconds)).collect(); + tracing::info!( + "console CPU instructions that fault, a second: {}; wait instructions replaced in place so far: {}; the busiest places: {}", + kinds.join(", "), + PATCHED.load(Relaxed), + top.join(", ") + ); + } +} + fn readable(va: usize, bytes: usize) -> bool { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQuery}; // SAFETY: plain data filled in by the query. @@ -135,12 +283,17 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { tracing::warn!(instruction = ?what, at = format_args!("{rip:#x}"), "a console CPU instruction this CPU lacks: emulated (logged once)"); } } + #[cfg(feature = "diagnostics")] + if what != ConsoleOnly::Ud2 { + sites::count(rip, what); + } match what { ConsoleOnly::Ud2 => return 0, ConsoleOnly::Clwb => { // nothing to write back on the PC: patched to NOPs, no exception next time use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect}; let mut old = 0u32; + let _one = PATCHING.lock().unwrap_or_else(|e| e.into_inner()); // SAFETY: the instruction's own bytes, made writable for the patch and restored. unsafe { if VirtualProtect(rip as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) != 0 { @@ -149,8 +302,20 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { } } } - ConsoleOnly::Monitorx => {} - ConsoleOnly::Mwaitx => std::hint::spin_loop(), + ConsoleOnly::Monitorx | ConsoleOnly::Mwaitx => { + // Without a prefix, so 3 bytes: replaced, the next pass does not fault. + if len == 3 + && patches_waits() + && let Some(new) = wait_patch(what) + // SAFETY: the title's code, where the instruction just faulted; both + // replacements are waits that wait for nothing, as the emulation is. + && unsafe { patch(rip, [code[0], code[1], code[2]], new) } + { + #[cfg(feature = "diagnostics")] + sites::patched(); + } + std::hint::spin_loop(); + } ConsoleOnly::Clzero => { // with an address-size prefix (0x67) the line is at EAX, zero-extended let a32 = code[..len - 3].contains(&0x67); @@ -255,3 +420,61 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { } CONTINUE_EXECUTION } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wait_instructions_are_replaced_inside_eight_aligned_bytes() { + let word = u64::from_le_bytes([1, 2, 0x0f, 0x01, 0xfb, 6, 7, 8]); + let new = with_patch(word, 0x1002, [0xf3, 0x90, 0x90]).unwrap(); + assert_eq!(new.to_le_bytes(), [1, 2, 0xf3, 0x90, 0x90, 6, 7, 8]); + assert!(with_patch(word, 0x1005, [0; 3]).is_some()); + assert!(with_patch(word, 0x1006, [0; 3]).is_none(), "crosses into the next eight"); + } + + /// `monitorx; mwaitx; ret` in a page of its own: each is replaced at its first fault, + /// and the page is protected as before. + #[test] + fn a_wait_faults_once_and_the_page_keeps_its_protection() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READ, PAGE_READWRITE, VirtualAlloc, VirtualFree, + VirtualProtect, VirtualQuery, + }; + // SAFETY: memory of our own, read, written and run within its page. + unsafe { + let page = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE).cast::(); + assert!(!page.is_null()); + let code = [0x0f, 0x01, 0xfa, 0x0f, 0x01, 0xfb, 0xc3]; + // Both within the aligned eight bytes at 8; and one over the end of its eight + // (at 22), which is left alone. + std::ptr::copy_nonoverlapping(code.as_ptr(), page.add(8), code.len()); + std::ptr::copy_nonoverlapping(code.as_ptr(), page.add(22), code.len()); + let mut old = 0; + assert_ne!(VirtualProtect(page.cast(), 4096, PAGE_EXECUTE_READ, &mut old), 0); + let at = page as usize; + let mut context: CONTEXT = std::mem::zeroed(); + for rip in [at + 8, at + 11, at + 22] { + context.Rip = rip as u64; + assert_eq!(emulate(&mut context), CONTINUE_EXECUTION); + assert_eq!(context.Rip, rip as u64 + 3); + } + if patches_waits() { + let now = std::slice::from_raw_parts(page.add(8), 7); + assert_eq!(now, [0x0f, 0x1f, 0x00, 0xf3, 0x90, 0x90, 0xc3]); + // They run now. + let run: extern "system" fn() = std::mem::transmute(page.add(8)); + run(); + // A second thread that faulted at the same place meanwhile. + assert!(patch(at + 8, [0x0f, 0x01, 0xfa], [0x0f, 0x1f, 0x00])); + assert!(!patch(at + 22, [0x0f, 0x01, 0xfa], [0x0f, 0x1f, 0x00]), "crosses its eight bytes"); + } + assert_eq!(std::slice::from_raw_parts(page.add(22), 3), [0x0f, 0x01, 0xfa]); + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery(page.cast(), &mut m, size_of_val(&m)); + assert_eq!(m.Protect, PAGE_EXECUTE_READ); + VirtualFree(page.cast(), 0, MEM_RELEASE); + } + } +} From b8b30d1cf93d3a7088f12d7115a3429f6961ec50 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:38:51 -0600 Subject: [PATCH 340/445] Submissions are prepared and sent by a thread of ours (VICTORY_ASYNC_SUBMIT=1, off) The idea is fxceless/victory-fork's, commit f85101b6. Here one line holds what all queues were given, presents too, in the order of the calls. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/fence.rs | 1 + crates/victory-gpu/src/host.rs | 7 +- crates/victory-gpu/src/queue.rs | 111 +++- crates/victory-gpu/src/queue/behind.rs | 758 +++++++++++++++++++++++++ 4 files changed, 868 insertions(+), 9 deletions(-) create mode 100644 crates/victory-gpu/src/queue/behind.rs diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index b066fd6..d3103b0 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -101,6 +101,7 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c #[cfg(windows)] if crate::host::late() { drop(waiters); + crate::queue::before_sync(); crate::host::settle_for_fence(); if fence.value.load(Ordering::Acquire) >= value { return S_OK; diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index c505bcb..2bbfa54 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -285,7 +285,9 @@ pub(crate) fn submissions() -> (u64, u64) { /// Drops `object` once every submission running now has finished: at once /// if none is. pub(crate) fn retire(object: T) { - let started = STARTED.load(Ordering::Acquire); + // (Those the title made and the host has not begun get the next numbers.) + let queued = crate::queue::queued(); + let started = STARTED.load(Ordering::Acquire) + queued; if started <= FINISHED.load(Ordering::Acquire) { RETIREMENTS[0].fetch_add(1, Ordering::Relaxed); drop(object); @@ -4625,6 +4627,8 @@ impl Host { /// Runs closed lists and waits for them, and with [`late`] for /// everything sent to the card before them, which is settled first. 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); } @@ -7680,6 +7684,7 @@ impl Meter { crate::shadow::exact_line(frames); crate::descriptor::sync_line(frames); late_line(frames); + crate::queue::behind_line(frames); card_clock_line(frames, ms); crate::shadow::back_line(frames); #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 069a431..47fd0b7 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -7,6 +7,9 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUEUE, S_OK, Table, This, guid}; use crate::resource::PAGEABLE_IIDS; +#[cfg(windows)] +mod behind; + const QUEUE_IIDS: [Iid; 4] = [ guid( 0x0ec870a6, @@ -307,6 +310,11 @@ fn hold(this: This, what: impl FnOnce() -> Held) -> bool { /// one. #[cfg(windows)] pub(crate) fn release_held(all: bool) { + if behind::on() { + // What queues stand at is looked at by the thread that runs them. + behind::wake(); + return; + } // One caller at a time, so a queue's submissions keep their order. static RELEASING: std::sync::Mutex<()> = std::sync::Mutex::new(()); if lock(&WAITING).is_empty() { @@ -423,6 +431,30 @@ pub(crate) fn release_held(all: bool) { } } +/// Before a submission of ours that is waited for, or a wait for flights by +/// a thread of the title's: what the title gave its queues before goes to the +/// card first ([`behind`]). +#[cfg(windows)] +pub(crate) fn before_sync() { + if behind::on() { + behind::drain(); + } +} + +/// Submissions the title made that the host has not begun ([`behind`]). +#[cfg(windows)] +pub(crate) fn queued() -> u64 { + behind::queued() +} + +/// For the frame-rate line. +#[cfg(windows)] +pub(crate) fn behind_line(frames: f64) { + if behind::on() { + behind::line(frames); + } +} + /// Whether a queue may pass `wait`: memory holds the value, or, with /// submissions sent to the card without a wait (`crate::host::late`), it /// will once those in the air have run. @@ -521,6 +553,10 @@ extern "system" fn execute(this: This, count: u32, lists: *const This) { if let Some(host) = crate::host::host() { // SAFETY: the title passes `count` lists. let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) }; + if behind::on() && !this.is_null() { + behind::submit(this, lists); + return; + } if cuts() && !this.is_null() { submit_cut(this, lists); return; @@ -614,6 +650,11 @@ extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT { if fence.is_null() { return E_INVALIDARG; } + #[cfg(windows)] + if behind::on() && !this.is_null() { + behind::signal(this, fence, value); + return S_OK; + } // A queue that waits signals after what it holds. #[cfg(windows)] if hold(this, || Held::Signal(fence as usize, value)) { @@ -651,6 +692,10 @@ extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { } #[cfg(feature = "diagnostics")] crate::capture::op(this as usize, || format!("WAIT queue kind {} for fence {fence:?} value {value} (now {now})", queue(this).kind)); + if behind::on() && waits() { + behind::wait(this, fence, value); + return S_OK; + } let behind = { let mut held = lock(&queue(this).held); let behind = !held.is_empty() || now < value; @@ -755,17 +800,21 @@ pub(crate) fn presented() -> u64 { /// shortcut: one plane, no scaling or placement, the source expected in /// the common state. extern "system" fn present( - _: This, + this: This, planes: u32, plane_parameters: *const Plane, _parameters: *const u8, ) -> HRESULT { + #[cfg(not(windows))] + let _ = this; #[cfg(all(windows, feature = "diagnostics"))] crate::copystat::present_begins(); // Submissions sent to the card and not waited for are settled first, // and what that frees runs in its own order, before anything is forced. #[cfg(windows)] - if crate::host::late() && !crate::host::late_free_present() { + if behind::on() { + // The present goes into the line of what the queues were given. + } else if crate::host::late() && !crate::host::late_free_present() { crate::host::settle_for_present(); release_held(false); crate::host::settle_for_present(); @@ -777,7 +826,9 @@ extern "system" fn present( // shortcut: what a queue still holds at a present runs now, whatever // its fence: a wait is not kept across frames. #[cfg(windows)] - release_held(forces()); + if !behind::on() { + release_held(forces()); + } let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; if frame.is_power_of_two() { let (draws, dispatches) = crate::list::take_counts(); @@ -811,10 +862,36 @@ extern "system" fn present( { crate::capture::frame_drew(frame, crate::draw::drawn()); if crate::capture::listed(frame) { + before_sync(); crate::capture::dump_targets(frame); } } #[cfg(windows)] + if behind::on() && !this.is_null() { + const COPY_SOURCE: u32 = 0x800; + let texture = if planes > 0 + // SAFETY: the title passes `planes` plane descriptions. + && let Some(plane) = unsafe { plane_parameters.as_ref() } + && plane.count > 0 + && !plane.resources.is_null() + { + // SAFETY: the plane lists `count` resources. + let resource = unsafe { *plane.resources }; + // The state the lists recorded so far leave it in (the next + // frame's, recorded before this is shown, go on from there). + crate::resource::host_copy(resource).map(|copy| { + let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before); + crate::resource::host_transition(resource, state); + (resource as usize, copy, state) + }) + } else { + None + }; + let resource = texture.as_ref().map_or(0, |t| t.0); + behind::present(this, texture.map(|(_, copy, state)| (copy, state)), Shown { frame, resource }); + return S_OK; + } + #[cfg(windows)] if planes > 0 // SAFETY: the title passes `planes` plane descriptions. && let Some(plane) = unsafe { plane_parameters.as_ref() } @@ -828,17 +905,35 @@ extern "system" fn present( const COPY_SOURCE: u32 = 0x800; let state = crate::resource::host_transition(resource, COPY_SOURCE) .map_or(COPY_SOURCE, |(_, before)| before); - let shown = host.present(texture, state, frame); + show(texture, state, Shown { frame, resource: resource as usize }); crate::resource::host_transition(resource, state); - #[cfg(feature = "diagnostics")] - blinks(frame, resource, state, shown); - #[cfg(not(feature = "diagnostics"))] - let _ = shown; + let _ = host; } #[cfg(not(windows))] let _ = (planes, plane_parameters); S_OK } +/// The frame a present shows, and the title's resource it shows. +#[cfg(windows)] +#[derive(Clone, Copy)] +struct Shown { + frame: u64, + resource: usize, +} + +/// Shows `texture`, in host state `state`, in our window. +#[cfg(windows)] +fn show(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32, what: Shown) { + let Some(host) = crate::host::host() else { + return; + }; + let shown = host.present(texture, state, what.frame); + #[cfg(feature = "diagnostics")] + blinks(what.frame, what.resource as This, state, shown); + #[cfg(not(feature = "diagnostics"))] + let _ = (shown, what.resource); +} + /// Diagnostics: logs a presented frame that is black after one that was /// not, with what was presented and how many draws ran since. #[cfg(all(windows, feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/queue/behind.rs b/crates/victory-gpu/src/queue/behind.rs new file mode 100644 index 0000000..8089997 --- /dev/null +++ b/crates/victory-gpu/src/queue/behind.rs @@ -0,0 +1,758 @@ +//! Submissions prepared and sent by a thread of ours, in order, instead of by +//! the thread of the title that submits them (`VICTORY_ASYNC_SUBMIT=1`). +//! +//! The idea and the argument are fxceless/victory-fork's, commit f85101b6 +//! (GPL-3.0-or-later, as this): a profile had the title's render thread inside +//! `queue::execute` for 202 of 292 ms of a frame while its recording threads +//! and the card stood idle, and the title does nothing with the result of that +//! work: it only has to be done before the lists run, in order. (Here, at +//! 77-79 ms a frame: 58 ms of it in the submit calls, the card idle for 37 ms +//! behind them.) What differs from that commit: one line for all queues, kept +//! in the order of the title's calls; the present stands in it too; nobody but +//! our thread runs what is in it. +//! +//! With the switch a submission's lists are taken from the title's lists (as +//! they are for every flight, `crate::list::detach`) and put in the [`Lane`], +//! with what they wait for, the queues' fence waits and signals, and the +//! presents. [`Lane::serve`], on a thread of ours, takes from it whatever is +//! free to run, the oldest first; within a queue the order is the title's, +//! always. What tells the title that work is done (fence values, +//! bottom-of-pipe writes) is told by the flights as before, when the card has +//! run them: later than the title's call by more than before, never earlier. +//! +//! What the title may do between its submit call and the moment our thread +//! prepares the lists, and why that is all right: +//! +//! - Reset or release the lists and allocators: their host sides, upload +//! memory and draw state were taken out of them. +//! - Write upload memory, descriptors, constants for later lists: those of +//! lists submitted are the card's to read until a fence behind them is +//! reached, on the console as here; no fence behind them is reached before +//! the lists have run ([`signal`] goes into the line behind them). +//! - Signal, wait, present on the queue: in the line behind them. +//! - Write a fence or a value in memory by the CPU: at once; our thread looks +//! at what it stands at again ([`wake`], and every millisecond). +//! - Map pages (`CopyPageMappingsBatchX`): at once, as before, where the lists +//! on the card may be reading them too; the bytes of uploads were read when +//! the lists were recorded. +//! - Ask for something that has to see earlier submissions done (a read-back, +//! a fence waited for without an event): [`drain`] first. +//! - Release a texture or a view's memory: what is retired waits for what is +//! in the line too ([`queued`]). +//! +//! The line is bounded: a present returns when the one before it was shown +//! ([`frames_most`]), and a submission when at most [`runs_most`] are in the +//! line. + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; +use std::time::{Duration, Instant}; + +use super::This; + +/// One thing in the line: what it stands at, if it does, and what it does. +pub(super) trait Work: Send { + /// What has to be met before it goes. + type Ask; + fn ask(&self) -> Option; + fn met(ask: &Self::Ask) -> bool; + /// Whether it is a present: everything before it goes first, met or not. + fn shows(&self) -> bool; + /// Whether it is a submission. + fn runs(&self) -> bool; + /// Does it. `forced`: its wait was not met. + fn go(self, forced: bool); +} + +struct Entry { + number: u64, + queue: usize, + what: W, +} + +struct State { + /// In the order of the title's calls, whatever queue they were made on. + items: VecDeque>, + /// The number the next entry gets. + next: u64, + /// The queue whose entry is being done now (it is no longer in `items`; + /// what that queue is given stays behind it all the same). + running: Option, + /// Times a look at the line was asked for, and the last of them that a + /// whole look has followed. + asked: u64, + served: u64, + /// Presents and submissions in the line or being done. + presents: usize, + runs: usize, +} + +/// See the module's text. +pub(super) struct Lane { + state: Mutex>, + /// Something to look at. + work: Condvar, + /// Something was done, or a look at the line ended. + moved: Condvar, +} + +impl Lane { + pub(super) const fn new() -> Self { + Lane { + state: Mutex::new(State { + items: VecDeque::new(), + next: 0, + running: None, + asked: 0, + served: 0, + presents: 0, + runs: 0, + }), + work: Condvar::new(), + moved: Condvar::new(), + } + } + + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn put(state: &mut State, queue: usize, what: W) { + state.presents += usize::from(what.shows()); + state.runs += usize::from(what.runs()); + let number = state.next; + state.next += 1; + state.items.push_back(Entry { number, queue, what }); + } + + /// Adds to the end of the line, and has it looked at. + pub(super) fn push(&self, queue: usize, what: impl IntoIterator) { + let mut state = self.lock(); + for what in what { + Self::put(&mut state, queue, what); + } + state.asked += 1; + drop(state); + self.work.notify_one(); + } + + /// Adds `what` if `queue` has anything in the line or being done (or + /// `always`); else does `now`, with nothing of the queue's able to come + /// in between. + pub(super) fn push_behind(&self, queue: usize, always: bool, what: W, now: impl FnOnce()) { + let mut state = self.lock(); + if always || state.running == Some(queue) || state.items.iter().any(|e| e.queue == queue) { + Self::put(&mut state, queue, what); + } else { + now(); + } + state.asked += 1; + drop(state); + self.work.notify_one(); + } + + /// Has the line looked at: something an entry stands at may have moved. + pub(super) fn wake(&self) { + let mut state = self.lock(); + if state.items.is_empty() { + return; + } + state.asked += 1; + drop(state); + self.work.notify_one(); + } + + /// Waits until everything in the line that is free to run has been done + /// (what comes in after this call may not be). + pub(super) fn drain(&self) { + let mut state = self.lock(); + if state.items.is_empty() && state.running.is_none() { + return; + } + state.asked += 1; + let ticket = state.asked; + self.work.notify_one(); + while state.served < ticket { + state = self.moved.wait(state).unwrap_or_else(|e| e.into_inner()); + } + } + + /// Waits until at most `most` presents are in the line. + pub(super) fn wait_presents(&self, most: usize) { + let mut state = self.lock(); + while state.presents > most { + state = self.moved.wait(state).unwrap_or_else(|e| e.into_inner()); + } + } + + /// Waits until at most `most` submissions are in the line, or what is + /// left of it stands at something. + pub(super) fn wait_runs(&self, most: usize) { + let mut state = self.lock(); + while state.runs > most && state.served < state.asked { + state = self.moved.wait(state).unwrap_or_else(|e| e.into_inner()); + } + } + + /// Looks at the line for as long as the process runs. + fn serve(&self) -> ! { + loop { + let (asked, limit) = { + let mut state = self.lock(); + while state.asked == state.served { + if state.items.is_empty() { + state = self.work.wait(state).unwrap_or_else(|e| e.into_inner()); + } else { + // It stands at something the CPU may write without + // a call of ours. + let (back, out) = + self.work.wait_timeout(state, Duration::from_millis(1)).unwrap_or_else(|e| e.into_inner()); + state = back; + if out.timed_out() { + break; + } + } + } + (state.asked, state.next) + }; + self.look(limit); + let mut state = self.lock(); + state.served = state.served.max(asked); + drop(state); + self.moved.notify_all(); + } + } + + /// Does what is free to run of the entries before number `limit`. + pub(super) fn look(&self, limit: u64) { + while self.step(limit) {} + } + + /// Does one entry: the oldest that is the first of its queue and free to + /// run. Whether there was one. Only one thread calls this. + fn step(&self, limit: u64) -> bool { + // Each queue's first entry, oldest first. + let mut heads: Vec<(u64, usize, Option, bool)> = Vec::new(); + { + let state = self.lock(); + for e in state.items.iter().take_while(|e| e.number < limit) { + if !heads.iter().any(|h| h.1 == e.queue) { + heads.push((e.number, e.queue, e.what.ask(), e.what.shows())); + } + } + } + let Some(&(first, ..)) = heads.first() else { + return false; + }; + let ready = heads.iter().find(|(number, _, ask, shows)| match ask { + Some(ask) => W::met(ask), + // A present comes behind everything given before it. + None => !shows || *number == first || !super::forces(), + }); + let (number, forced) = match ready { + Some(head) => (head.0, false), + None => { + // Nothing is free to run. With a present in the line the + // oldest goes on regardless: a wait is not kept across + // frames (`super::present`). + let state = self.lock(); + if !super::forces() || !state.items.iter().any(|e| e.number < limit && e.what.shows()) { + return false; + } + (first, true) + } + }; + let entry = { + let mut state = self.lock(); + let Some(at) = state.items.iter().position(|e| e.number == number) else { + return false; + }; + let Some(entry) = state.items.remove(at) else { + return false; + }; + state.running = Some(entry.queue); + entry + }; + let (shows, runs) = (entry.what.shows(), entry.what.runs()); + entry.what.go(forced); + { + let mut state = self.lock(); + state.running = None; + state.presents -= usize::from(shows); + state.runs -= usize::from(runs); + } + self.moved.notify_all(); + true + } +} + +/// What the title's queues put in the line. +enum Job { + /// The queue waits for the fence (its address) to reach the value. + Wait(usize, u64), + /// A part of a submission waits for a memory value. + Value(crate::list::ValueWait), + /// A submission, or a part of one: the lists' host sides and the order + /// they run in. + Run(usize, Vec, Vec), + /// A signal of the queue's. + Signal(usize, u64), + /// A frame is shown: the texture and the state its lists leave it in. + Present(Option<(std::sync::Arc, u32)>, super::Shown), +} + +// SAFETY: D3D12 objects are free-threaded; a job is touched by whoever put it +// in the line and then, once it is taken out, by our thread alone (the flights +// it becomes are handed to other threads the same way). +unsafe impl Send for Job {} + +enum Ask { + Wait(usize, u64), + Value(crate::list::ValueWait), +} + +impl Work for Job { + type Ask = Ask; + + fn ask(&self) -> Option { + match self { + &Job::Wait(fence, value) => Some(Ask::Wait(fence, value)), + Job::Value(wait) => Some(Ask::Value(*wait)), + _ => None, + } + } + + fn met(ask: &Ask) -> bool { + match ask { + &Ask::Wait(fence, value) => crate::fence::completed(fence as This) >= value, + Ask::Value(wait) => super::value_met(wait), + } + } + + fn shows(&self) -> bool { + matches!(self, Job::Present(..)) + } + + fn runs(&self) -> bool { + matches!(self, Job::Run(..)) + } + + fn go(self, forced: bool) { + let began = Instant::now(); + if forced { + STATS[FORCED].fetch_add(1, Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Forced, 1); + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("a queue still stood at a wait at a present: it was not met")); + } + match self { + Job::Wait(..) | Job::Value(..) => {} + Job::Run(queue, lists, order) => { + let _ = queue; + #[cfg(feature = "diagnostics")] + crate::capture::op(queue, || format!("RUN submission of {} lists (its thread's)", order.len())); + match crate::host::host() { + Some(host) => host.execute_late(lists, order), + None => drop(lists), + } + QUEUED.fetch_sub(1, Relaxed); + } + Job::Signal(fence, value) => { + if !crate::host::late_signal(fence, value) { + crate::fence::set(fence as This, value); + } + } + Job::Present(texture, shown) => { + if let Some((texture, state)) = texture { + super::show(&texture.texture, state, shown); + } + QUEUED.fetch_sub(1, Relaxed); + } + } + STATS[BUSY].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + } +} + +static LANE: Lane = Lane::new(); + +/// Submissions and presents in the line that have not been given to the host +/// yet. +static QUEUED: AtomicU64 = AtomicU64::new(0); + +/// Since the last frame-rate line: submissions put in the line, presents, the +/// times they found things in it (the sum of their numbers) and the most; what +/// 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]; +const RUNS: usize = 0; +const PRESENTS: usize = 1; +const DEPTH: usize = 2; +const DEEPEST: usize = 3; +const ROOM: usize = 4; +const AT_PRESENT: usize = 5; +const DRAINING: usize = 6; +const DRAINS: usize = 7; +const BUSY: usize = 8; +const FORCED: usize = 9; + +/// How many submissions may be in the line when a submit call returns +/// (`VICTORY_SUBMIT_DEPTH`; 64: about two frames of the title's). +fn runs_most() -> usize { + static MOST: OnceLock = OnceLock::new(); + *MOST.get_or_init(|| number("VICTORY_SUBMIT_DEPTH").unwrap_or(64).max(1)) +} + +/// How many presents may be in the line when a present call returns +/// (`VICTORY_SUBMIT_FRAMES`; 1: the frame before is sent, this one may not be; +/// 0: both are). +fn frames_most() -> usize { + static MOST: OnceLock = OnceLock::new(); + *MOST.get_or_init(|| number("VICTORY_SUBMIT_FRAMES").unwrap_or(1)) +} + +fn number(name: &str) -> Option { + std::env::var(name).ok()?.trim().parse().ok() +} + +thread_local! { + /// This is the thread that does what is in the line. + static OURS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether submissions are prepared by a thread of ours +/// (`VICTORY_ASYNC_SUBMIT=1`; needs flights with the present sent ahead, as +/// the relay has them, and lists cut at their waits). +pub(super) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var_os("VICTORY_ASYNC_SUBMIT").is_some_and(|v| v == "1") { + return false; + } + if !crate::host::late_free_present() || !super::cuts() { + tracing::warn!("VICTORY_ASYNC_SUBMIT=1 needs the relay and lists cut at their waits: submissions are prepared by the thread that makes them"); + return false; + } + let worker = || { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL}; + // SAFETY: this thread's own priority. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) }; + OURS.set(true); + let ended = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| LANE.serve())); + if ended.is_err() { + // Nothing would ever be sent again, and the title's thread + // would stand at its next present for good. + crate::host::fail(format_args!("the thread that prepares and sends submissions panicked")); + } + }; + match std::thread::Builder::new().name("victory-submit".into()).spawn(worker) { + Ok(_) => { + tracing::info!( + frames = frames_most(), + runs = runs_most(), + "submissions are prepared and sent by a thread of ours, not by the thread that submits (VICTORY_ASYNC_SUBMIT=1)" + ); + true + } + Err(e) => { + tracing::warn!(error = %e, "no thread to prepare submissions: the threads that make them do"); + false + } + } + }) +} + +/// Submissions in the line that the host has not begun +/// (`crate::host::retire` waits for them too). +pub(super) fn queued() -> u64 { + QUEUED.load(Relaxed) +} + +/// Something a queue may stand at moved. +pub(super) fn wake() { + LANE.wake(); +} + +/// Before something that has to see the submissions made so far sent: they +/// are, as far as they are free to run. Not on our own thread, which is +/// inside one of them. +pub(super) fn drain() { + if OURS.get() { + return; + } + let began = Instant::now(); + LANE.drain(); + STATS[DRAINING].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + STATS[DRAINS].fetch_add(1, Relaxed); +} + +/// A submission of `lists` to queue `this`. +pub(super) fn submit(this: This, lists: &[This]) { + let queue = this as usize; + // In one piece up to the first list that waits for a memory value, as + // `super::submit_cut` runs them; the rest part by part. + let first = lists.iter().position(|&l| crate::list::cut_list(l)).unwrap_or(lists.len()); + #[cfg(feature = "diagnostics")] + crate::capture::op(queue, || { + let named: Vec = lists + .iter() + .map(|&l| match crate::list::host_list(l) { + Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize), + None => format!("title {l:?}"), + }) + .collect(); + format!( + "SUBMIT queue kind {} lists {named:?} to the line (the first {first} in one piece)", + super::queue(this).kind + ) + }); + let mut jobs: Vec = Vec::new(); + if first > 0 { + let (taken, order) = crate::list::detach(&lists[..first]); + jobs.push(Job::Run(queue, taken, order)); + } + if first < lists.len() { + for (waits, taken, order) in crate::list::detach_parts(&lists[first..]) { + jobs.extend(waits.into_iter().map(Job::Value)); + jobs.push(Job::Run(queue, taken, order)); + } + } + let runs = jobs.iter().filter(|j| j.runs()).count() as u64; + let before = QUEUED.fetch_add(runs, Relaxed); + STATS[RUNS].fetch_add(runs, Relaxed); + STATS[DEPTH].fetch_add(before, Relaxed); + STATS[DEEPEST].fetch_max(before + runs, Relaxed); + LANE.push(queue, jobs); + if before + runs > runs_most() as u64 { + let began = Instant::now(); + LANE.wait_runs(runs_most()); + STATS[ROOM].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + } +} + +/// A signal of queue `this`: behind what it has in the line; if that is +/// nothing, behind the flights in the air, or now. +pub(super) fn signal(this: This, fence: This, value: u64) { + let fence = fence as usize; + LANE.push_behind(this as usize, false, Job::Signal(fence, value), || { + if !crate::host::late_signal(fence, value) { + crate::fence::set(fence as This, value); + } + }); +} + +/// Queue `this` waits for `fence`: nothing if it has nothing in the line and +/// the fence is there already. +pub(super) fn wait(this: This, fence: This, value: u64) { + let always = crate::fence::completed(fence) < value; + LANE.push_behind(this as usize, always, Job::Wait(fence as usize, value), || {}); +} + +/// A present on queue `this` of `texture`, in the state the lists recorded so +/// far leave it in. +pub(super) fn present(this: This, texture: Option<(std::sync::Arc, u32)>, shown: super::Shown) { + QUEUED.fetch_add(1, Relaxed); + STATS[PRESENTS].fetch_add(1, Relaxed); + LANE.push(this as usize, [Job::Present(texture, shown)]); + let began = Instant::now(); + LANE.wait_presents(frames_most()); + STATS[AT_PRESENT].fetch_add(began.elapsed().as_micros() as u64, Relaxed); +} + +/// For the frame-rate line. +pub(super) fn line(frames: f64) { + let s: Vec = STATS.iter().map(|s| s.swap(0, Relaxed) as f64).collect(); + let ms = |i: usize| s[i] / 1000.0 / frames; + 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}", + s[RUNS] / frames, + s[PRESENTS] / frames, + s[DEPTH] / s[RUNS].max(1.0), + s[DEEPEST], + ms(BUSY), + ms(ROOM), + ms(AT_PRESENT), + ms(DRAINING), + s[DRAINS] / frames, + s[FORCED] / frames + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + type Log = Arc>>; + + /// A job of a test: what it stands at, and what it does. + enum T { + /// Stands until the fence has the value. + Wait(usize, u64), + Run(&'static str, Log), + /// Runs once the gate is open: a submission that takes long. + Slow(&'static str, Log, Arc<(Mutex, Condvar)>), + Signal(usize, u64, Log), + Present(&'static str, Log), + } + + impl Work for T { + type Ask = (usize, u64); + fn ask(&self) -> Option<(usize, u64)> { + match self { + &T::Wait(fence, value) => Some((fence, value)), + _ => None, + } + } + fn met(ask: &(usize, u64)) -> bool { + crate::fence::completed(ask.0 as This) >= ask.1 + } + fn shows(&self) -> bool { + matches!(self, T::Present(..)) + } + fn runs(&self) -> bool { + matches!(self, T::Run(..) | T::Slow(..)) + } + fn go(self, forced: bool) { + match self { + T::Wait(..) => { + if forced { + FORCED_HERE.with(|f| f.set(f.get() + 1)); + } + } + T::Run(name, log) | T::Present(name, log) => log.lock().unwrap().push(name.into()), + T::Slow(name, log, gate) => { + let mut open = gate.0.lock().unwrap(); + while !*open { + open = gate.1.wait(open).unwrap(); + } + log.lock().unwrap().push(name.into()); + } + T::Signal(fence, value, log) => { + log.lock().unwrap().push(format!("signal {value}")); + crate::fence::set(fence as This, value); + } + } + } + } + + thread_local! { + static FORCED_HERE: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + fn fence() -> usize { + let mut f = std::ptr::null(); + assert_eq!(crate::fence::create(std::ptr::null(), 0, 0, &crate::fence::FENCE_IIDS[0], &mut f), super::super::S_OK); + f as usize + } + + fn value(f: usize) -> u64 { + crate::fence::completed(f as This) + } + + fn look(lane: &Lane) { + let limit = lane.lock().next; + lane.look(limit); + } + + /// A queue's order is kept, a wait for another queue's signal holds only + /// what is behind it on its own queue, and the oldest goes first. + #[test] + fn queues_keep_their_order_and_wait_for_each_others_fences() { + let lane = Lane::new(); + let log: Log = Default::default(); + let f = fence(); + let run = |name| T::Run(name, log.clone()); + // The compute queue waits for what the graphics queue signals later. + lane.push(2, [T::Wait(f, 1), run("compute")]); + lane.push(1, [run("draw 1")]); + lane.push_behind(1, false, T::Signal(f, 1, log.clone()), || panic!("the queue is not empty")); + lane.push(1, [run("draw 2")]); + look(&lane); + assert_eq!(*log.lock().unwrap(), ["draw 1", "signal 1", "compute", "draw 2"]); + assert_eq!(value(f), 1); + // Nothing in the line: a signal is at once. + let mut done = false; + lane.push_behind(1, false, T::Signal(f, 2, log.clone()), || done = true); + assert!(done); + } + + /// A wait that nothing meets holds its queue until a present, which + /// comes behind everything given before it and before what comes after. + #[test] + fn a_present_goes_behind_everything_before_it_met_or_not() { + let lane = Lane::new(); + let log: Log = Default::default(); + let f = fence(); + let run = |name| T::Run(name, log.clone()); + lane.push(2, [T::Wait(f, 9), run("held")]); + lane.push(1, [run("draw")]); + look(&lane); + assert_eq!(*log.lock().unwrap(), ["draw"], "the wait holds its queue and no other"); + lane.push(1, [T::Present("present", log.clone())]); + lane.push(1, [run("next frame")]); + lane.push(2, [T::Wait(f, 10), run("held again")]); + look(&lane); + assert_eq!(*log.lock().unwrap(), ["draw", "held", "present", "next frame"]); + assert_eq!(FORCED_HERE.get(), 1); + // The second wait is met by a signal of the CPU. + crate::fence::set(f as This, 10); + look(&lane); + assert_eq!(log.lock().unwrap().last().unwrap(), "held again"); + assert_eq!(FORCED_HERE.get(), 1); + let state = lane.lock(); + assert_eq!((state.presents, state.runs, state.items.len()), (0, 0, 0)); + } + + /// With the thread: a fence behind a submission is not reached before the + /// submission has been done, presents hold the title back a frame later, + /// and a drain comes back when everything was done. + #[test] + fn the_title_goes_on_and_is_told_in_order() { + let lane: &'static Lane = Box::leak(Box::new(Lane::new())); + std::thread::spawn(|| lane.serve()); + let log: Log = Default::default(); + let f = fence(); + let gate = Arc::new((Mutex::new(false), Condvar::new())); + lane.push(1, [T::Slow("slow", log.clone(), gate.clone())]); + lane.push_behind(1, false, T::Signal(f, 1, log.clone()), || panic!("behind the submission")); + lane.push(1, [T::Present("present 1", log.clone())]); + // One present may be in the line: this returns with it there. + lane.wait_presents(1); + assert_eq!(value(f), 0); + assert!(log.lock().unwrap().is_empty()); + // A fence behind a submission being done (no longer in the line). + while lane.lock().running.is_none() { + std::thread::yield_now(); + } + lane.push(1, [T::Run("second", log.clone())]); + lane.push(1, [T::Present("present 2", log.clone())]); + let opener = { + let gate = gate.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(20)); + *gate.0.lock().unwrap() = true; + gate.1.notify_all(); + }) + }; + lane.wait_presents(1); + assert!(value(f) == 1, "the first frame was done"); + lane.drain(); + assert_eq!(*log.lock().unwrap(), ["slow", "signal 1", "present 1", "second", "present 2"]); + opener.join().unwrap(); + // A wait the CPU meets without telling anybody; a drain does not + // stand at it. + lane.push(1, [T::Wait(f, 5), T::Run("after the wait", log.clone())]); + lane.drain(); + assert_eq!(log.lock().unwrap().len(), 5); + lane.wait_runs(0); + crate::fence::set(f as This, 5); + while log.lock().unwrap().len() < 6 { + std::thread::yield_now(); + } + } +} From 59bccacaf9e3b538030585424f46a2f866e4f4b4 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:43:37 -0600 Subject: [PATCH 341/445] The first copy into a texture the title fills goes over zeros VICTORY_COPY_OVER_TITLE=title: over what title memory holds; =0: over whatever the block of the pool held. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/list.rs | 28 ++++++++++++++++------ crates/victory-gpu/src/texture.rs | 40 +++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 84aa3a3..b0a1c33 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1024,19 +1024,33 @@ extern "system" fn copy_texture_region( // source above too). list.twin_use(dst.resource, false, true); // The first copy into a texture of the title's: what it does not - // write is what title memory holds, as on the console. (The host + // write is zeros, as in a texture that was an allocation of its own + // (`VICTORY_COPY_OVER_TITLE=title`: what title memory holds, which + // may be another texture's: specks on the waitress's forehead were + // left in run n04). (The host // copy is cut from a block and held whatever lay there, and no // upload is made once a copy wrote it: the atlas the title copies // its baked decorations into, a 2048x2048 BC3 texture of which a // bake writes 256x256 at most, was drawn over a character's face // with other textures' bytes wherever nothing was baked, runs n01 and // textures-1.) - static OVER: std::sync::OnceLock = std::sync::OnceLock::new(); - if *OVER.get_or_init(|| std::env::var_os("VICTORY_COPY_OVER_TITLE").is_none_or(|v| v != "0")) - && crate::texture::title_written(to) - && !crate::texture::host_wrote(dst.resource as usize) - { - crate::texture::upload(list, dst.resource, to); + static OVER: std::sync::OnceLock = std::sync::OnceLock::new(); + let over = *OVER.get_or_init(|| match std::env::var("VICTORY_COPY_OVER_TITLE").as_deref() { + Ok("0") => 0, + Ok("title") => 1, + _ => 2, + }); + if over != 0 && crate::texture::title_written(to) && !crate::texture::host_wrote(dst.resource as usize) { + // One a list uploaded, or a draw sampled, holds the title's. + if over == 2 && !list.used(dst.resource as usize) && !crate::texture::is_staged(dst.resource) { + if let Some(host) = crate::host::host() { + ensure_state(list, dst.resource, COPY_DEST); + let _ = list.first_use(dst.resource as usize); + crate::texture::zeros(list, host, to); + } + } else { + crate::texture::upload(list, dst.resource, to); + } // (Done before the title's copy writes over it.) if list.used(dst.resource as usize) { ensure_state(list, dst.resource, COPY_SOURCE); diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 7ad9915..dc7bad1 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -937,6 +937,46 @@ impl Drop for Claimed { } } +/// Records copies of zeros into every subresource of `texture`, which is in +/// the copy destination state. +pub(crate) fn zeros(list: &HostList, host: &crate::host::Host, texture: &ID3D12Resource) { + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + let layers = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { u32::from(d.DepthOrArraySize) }; + let count = u32::from(d.MipLevels) * layers; + let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize]; + let mut bytes = 0u64; + // SAFETY: outputs for `count` subresources. + unsafe { + host.device + .GetCopyableFootprints(&d, 0, count, 0, Some(footprints.as_mut_ptr()), None, None, Some(&mut bytes)); + } + if bytes == 0 || bytes == u64::MAX { + return; + } + let Some((buffer, data)) = list.upload(host, bytes) else { + return; + }; + // SAFETY: a mapped buffer of `bytes` bytes, just made. + unsafe { std::ptr::write_bytes(data, 0, bytes as usize) }; + for (i, footprint) in 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: i as u32 }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above; the list holds the buffer until it is reset. + pResource: unsafe { std::mem::transmute_copy(&buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *footprint }, + }; + // SAFETY: an open list; both locations name live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } +} + /// Levels on demand (`crate::tiles`): the card itself is about to write /// title texture `resource` in `list` (a copy or a resolve into level /// `level`, or into every level). If its host copy `texture` was made From 2eb7d0c079be1dfc147aaddf6d00bae662ecfdab Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:44:04 -0600 Subject: [PATCH 342/445] Raw twins of views off dwords are moved there too, not null 4.6 twins a frame of run crash-3 were null because they begin off a dword (16 bit values at an odd one); the typed view they stand for begins there as well. Measured (raw_loads_past_views): a raw view moved on by 8 bytes gives the bytes from there and ends where it should, uniform and per lane. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 8 +++-- crates/victory-gpu/src/indirect.rs | 39 +++++++++++++++++++++-- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index b1b3b28..e0a7bcb 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -2848,8 +2848,10 @@ pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync: /// no raw view. An AMD descriptor of a raw buffer is its address (48 bits), /// its bytes and flags; only one that says just that is changed, and only /// where what the handle points at is the descriptor. False: not moved. -fn move_raw(at: D3D12_CPU_DESCRIPTOR_HANDLE, start: u64, bytes: u32, by: u32) -> bool { - if !by.is_multiple_of(4) || by >= bytes { +pub(crate) fn move_raw(at: D3D12_CPU_DESCRIPTOR_HANDLE, start: u64, bytes: u32, by: u32) -> bool { + // (Off dwords too, as the typed view it stands for begins there: a view + // of 16 bit values at an odd one.) + if by >= bytes { return false; } let mut words = [0u8; 16]; @@ -4003,7 +4005,7 @@ mod tests { let before = words(); assert!(!move_raw(at, start + 16, 400, 8), "another address"); assert!(!move_raw(at, start, 404, 8), "another size"); - assert!(!move_raw(at, start, 400, 2), "not a dword"); + assert!(!move_raw(at, start, 400, 400), "nothing left"); assert_eq!(words(), before); if move_raw(at, start, 400, 8) { let moved = words(); diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 09be698..88360fd 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -1035,7 +1035,7 @@ void main(uint3 id : SV_DispatchThreadID, uint g : SV_GroupIndex) { gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize, ) }; - let names = ["raw", "structured 24 at 24", "structured 16", "typed u32", "typed u16", "typed 4 x u32", "constant buffer", "null raw"]; + let names = ["raw", "structured 24 at 24", "structured 16", "typed u32", "typed u16", "typed 4 x u32", "constant buffer", "raw, moved to 8"]; let view = |i: usize, format: i32, first: u64, count: u32, stride: u32, raw: bool, null: bool| { let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT(format), @@ -1061,7 +1061,42 @@ void main(uint3 id : SV_DispatchThreadID, uint g : SV_GroupIndex) { view(base + 3, 42, 0, 1024, 0, false, false); view(base + 4, 57, 0, 2048, 0, false, false); view(base + 5, 3, 0, 256, 0, false, false); - view(base + 7, 39, 0, 1, 0, true, true); + // 1,024 dwords from 0 made in a heap the card does not see, moved + // on by 8 bytes (`descriptor::host::move_raw`), copied in. + // SAFETY: plain heap creation, slots of live heaps. + unsafe { + let beside: ID3D12DescriptorHeap = gpu + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 1, + ..Default::default() + }) + .unwrap(); + let at = beside.GetCPUDescriptorHandleForHeapStart(); + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(39), + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: 0, + NumElements: 1024, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }, + }, + }; + gpu.device.CreateShaderResourceView(&buffer, Some(&desc), at); + let moved = crate::descriptor::host::move_raw(at, buffer.GetGPUVirtualAddress(), 4096, 8); + println!("the raw view was moved: {moved}"); + gpu.device.CopyDescriptorsSimple( + 1, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu + (base + 7) * step }, + at, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + ); + } let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { // SAFETY: a live buffer. BufferLocation: unsafe { buffer.GetGPUVirtualAddress() }, From c51ca571ee4b024c16292f019932b4a829ed6981 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:48:04 -0600 Subject: [PATCH 343/445] Title memory by address: the dump names what was built and unpacked; a small buffer's results once a list Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/memory.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 2daab6f..41ba575 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -823,15 +823,21 @@ pub(crate) fn ready( for &at in addresses.iter().filter(|&&a| a >= 1 << 32) { // (Several structures to a page.) let packed = builds && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize) && m.unpacks(at); - if builds && written.contains(&at) && named(4, at) { + if builds && written.contains(&at) && list.first_use(usize::MAX - (4 << 33) - (at >> 2 & 0x7FFF_FFFF) as usize) { if let Some((start, len)) = crate::shadow::in_buffer(at, 1) && len <= BACK && use_ == (Use::Builds { back: true }) + && list.first_use(usize::MAX - (5 << 33) - (start >> 2 & 0x7FFF_FFFF) as usize) { m.small(list, start, len); } m.opens(at); if !packed && crate::shadow::in_buffer(at, 1).is_none() { + #[cfg(feature = "diagnostics")] + { + let built = m.dump.built.entry(at).or_insert((frame, frame, 0)); + (built.1, built.2) = (frame, built.2 + 1); + } let before = held(m); m.ready(at, BUILT); came[1] += held(m).saturating_sub(before); @@ -914,6 +920,9 @@ mod dump { #[derive(Default)] pub(super) struct Dump { walked: std::collections::BTreeSet, + /// Views the builder was given to write outside buffers: the first + /// and the last frame, how often. + pub(super) built: std::collections::BTreeMap, /// The frame it is written at, and the copies. due: Option<(u64, Vec<(ID3D12Resource, usize)>)>, done: bool, @@ -962,6 +971,13 @@ mod dump { for a in &self.dump.walked { text += &format!("walked {a:#x}\n"); } + for (a, (first, last, n)) in &self.dump.built { + text += &format!("built {a:#x} {first} {last} {n}\n"); + } + for (a, p) in &self.packed { + text += &format!("packed {a:#x} {} {}\n", p.len, p.frame); + } + text += &format!("frame {}\n", self.frame); for (page, held) in &self.pages { let arena = self.arenas.iter().position(|a| a.0 == held.copy).unwrap_or(usize::MAX); let at = held.at - self.arenas[arena].1; From 3c0721033b7af9fecfb19dcfb19a21bd96687ab2 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:48:49 -0600 Subject: [PATCH 344/445] docs: ray tracing, the state after the first runs Co-Authored-By: Claude Opus 5.5 --- docs/fork-ray-tracing.md | 66 ++++++++++++++++++++++++++++++++-------- 1 file changed, 54 insertions(+), 12 deletions(-) diff --git a/docs/fork-ray-tracing.md b/docs/fork-ray-tracing.md index dee0281..6c05d8d 100644 --- a/docs/fork-ray-tracing.md +++ b/docs/fork-ray-tracing.md @@ -1,8 +1,10 @@ # Ray tracing in this fork: what the title does and what has been built -Status, 2026-11-25: **nothing is lit by ray tracing yet.** Most of the -machinery translates and is unit-tested; it has not yet run end to end in the -game. Everything here is off by default. +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. ## What the title does @@ -35,8 +37,8 @@ shaders and emulates the one instruction. ## What this fork adds -1. **The builder programs translate** (49 of 52; all that the title creates in - the scenes tested). They pass buffer addresses in a spilled parameter table +1. **The builder programs translate** (all 52, with host pipelines on the RX + 7900 XTX; the title creates 53 such pipelines). They pass buffer addresses in a spilled parameter table rather than in descriptors. Added: the spilled user-data table, root unordered-access views (translator and host binding), byte and 16-bit buffer accesses, and several control-flow shapes. @@ -61,18 +63,58 @@ shaders and emulates the one instruction. partly working builder wrote garbage bounds into title memory and crashed the title. +## The structures (from dumps of the arenas, `VICTORY_MEMORY_DUMP`) + +- Header, 64 bytes: dword 0 the version 6 in the low half and marks in the high + (0x8000 bottom level, 0x4 compacted, 0x2 rehydrated, 0x100 still packed), + dword 1 the size in 64-byte nodes, 3 the number of elements, 4-9 the bounds, + 10 the offset of the box nodes, 12 the root's node pointer, 13 the offset of + the elements, 14 the offset of the parent table (from the header; the static + ones' index counts the leaves too, so it is negative). +- An instance is 128 bytes at the top level's offset 13: a 3x4 matrix in dwords + 0-11, id and mask, flags, the root pointer (bit 30 set for static ones), the + bottom level's address in 256-byte units. +- The static world's structures are shipped **packed ("dehydrated")** and + unpacked in place, once, by DecompressHeader, Box32/Box16Rehydration and + LeafRehydration when they have been streamed in (3,000 in the opening). +- Dynamic ones are built, their compacted size read back by the title from a + small buffer, and copied to a place of that size. + +## How title memory by address is held (`memory.rs`) + +Pages of 64 KiB in arenas on the card, whole title buffers in their own copies, +pages with small title buffers as windows of title memory. The module's +comment has the rules. In short: what the builder stores stays on the card +(only small title buffers it was given to write come back); a packed structure +goes up whole when the builder comes to it; title buffers take its stores only +after it was given them as an unordered access view. + +| variable | does | +|---|---| +| `VICTORY_BVH_BUILDER=1` | the builder's stages run | +| `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) | +| `VICTORY_UPLOAD_LOW=0`, `VICTORY_LENT_HEAP=0` | lists' upload memory above 2^40, no view heap for lists without one, as before | + +Every ten seconds the log has a line "title memory by address: ..." with pages, +dispatches, faults and what came. + ## Known gaps -- With `VICTORY_BVH_BUILDER=1` the builder still stays off in a real run: a few - of its pipelines are refused by the host (they still ask for 64-lane waves on - a 32-lane GPU) or do not translate. -- Five shadow-mask trace programs do not translate yet. -- An access to a title page that has no host copy is lost (a read gives zero, a - store is dropped). +- 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. +- 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 + run so far. +- An access to a page that is not there is lost (a read gives zero, a store is + dropped). - Not publicly documented, and assumed: the instruction's rounding, the order of two boxes entered at the same distance, and the result for a ray exactly through an edge. -- Cost on the GPU is unmeasured. ## Where to look From 28fbbfdcbce4eeb6c3b6337f2010fd1f50cf858b Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 06:09:43 -0600 Subject: [PATCH 345/445] Title memory by address: every list brings up every copy, whoever made it An arena another list made while this one was being recorded was brought up by that list's submission alone: structures unpacked from zeros, then written over by the arena's first upload. In run light-8 half of the 470 structures unpacked in the frame with the most (1381) were wrong, 5-15 % in frames with few. A title buffer the builder stores in sends up only the dwords the title changed. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/memory.rs | 24 +++++++++++++++--------- crates/victory-gpu/src/shadow.rs | 14 ++++++++++---- 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 41ba575..5a7112f 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -463,6 +463,8 @@ impl Memory { if self.pages.contains_key(&(address / PAGE)) || !self.open.insert(n) { return; } + // (Its pages hold what the CPU writes beside the builder's scratch.) + self.copies[n].keep_stores(); let (first, len) = self.copies[n].span(); tracing::info!( start = format_args!("{first:#x}"), @@ -791,7 +793,6 @@ pub(crate) fn ready( } let builds = use_ != Use::Reads; m.stats.uses[usize::from(builds)] += 1; - let numbered = m.copies.len(); // Once per list and page named: the builder dispatches hundreds of times // a frame with the same arguments. const READ: usize = usize::MAX - 0x6d; @@ -880,17 +881,22 @@ pub(crate) fn ready( heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len); } m.heaps.insert(key, (base, m.copies.len() as u32)); - // shortcut: a copy another list numbers meanwhile is brought up to date - // by that list's submission, which may run after this one's. + // Every copy by every list that has come to by-address memory, whoever + // numbered it: an arena another list made while this one was being + // recorded was brought up to date by that list's submission alone, which + // may run after this one's (structures unpacked from zeros, and then + // written over by the arena's first upload: in frames that stream much in + // half of them, run light-8). let first_read = list.first_use(READ); - let from = if first_read { 0 } else { numbered }; - if first_read || m.copies.len() > numbered { + if list.first_use(usize::MAX - (6 << 33) - m.copies.len()) { let (start, len) = m.directory.1.span(); m.directory.1.refresh(list, start, len); - } - for shadow in &m.copies[from..] { - let (start, len) = shadow.span(); - shadow.refresh(list, start, len); + for (n, shadow) in m.copies.iter().enumerate() { + if list.first_use(usize::MAX - (7 << 33) - n) { + let (start, len) = shadow.span(); + shadow.refresh(list, start, len); + } + } } if first_read { list.keep(&m.faults.0); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 124ecd5..0690506 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -85,7 +85,7 @@ pub(crate) struct Shadow { window: bool, /// Of a copy with two sides: only the dwords the title changed go up, /// as with [`send_changed`] ([`by_address`]). - changes_only: bool, + changes_only: std::sync::atomic::AtomicBool, /// A window in card memory the CPU maps ([`window_mapped_for`]). mapped: bool, /// With `crate::inplace`: not a copy at all. `buffer` is placed in a @@ -2686,7 +2686,7 @@ impl Shadow { }, card: None, window: false, - changes_only: false, + changes_only: Default::default(), mapped: false, place: None, } @@ -3572,7 +3572,7 @@ impl Shadow { /// A page of title memory, as read. static TITLE: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } - let Some(card) = self.card.as_ref().filter(|_| self.changes_only || send_changed()) else { + let Some(card) = self.card.as_ref().filter(|_| self.changes_only.load(Ordering::Relaxed) || send_changed()) else { return self.copy(from, to); }; let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none(); @@ -3640,6 +3640,12 @@ impl Shadow { self.card.is_some() } + /// Shaders store in it what is not declared: from here on only the dwords + /// the title changes go up ([`by_address`]). + pub(crate) fn keep_stores(&self) { + self.changes_only.store(true, Ordering::Relaxed); + } + /// Offsets `[from, to)` go up again whole, as the CPU's side has them. pub(crate) fn resend(&self, from: usize, to: usize) { self.card_changed(from, to); @@ -4673,7 +4679,7 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option> { let gpu = unsafe { buffer.GetGPUVirtualAddress() }; let mut shadow = Shadow::new(buffer, data, gpu, start, len); shadow.window = true; - shadow.changes_only = true; + shadow.changes_only.store(true, Ordering::Relaxed); shadow.card = Some(Card { staging, before: Mutex::default(), From 51d3f4da001b0d7e1f438f03533a101f6b32668b Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 06:19:18 -0600 Subject: [PATCH 346/445] A texture is not copied onto itself; the process opts out of the efficiency mode (victory-fork a2537066) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/list.rs | 50 +++++++++++++++++++++++++++++-- crates/victory-hle/src/runtime.rs | 14 +++++++-- 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index b0a1c33..f851a10 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -858,6 +858,11 @@ fn unlike(dst: This, src: This) -> bool { unlike } +/// Copies left out because both sides were one host texture +/// ([`copy_resource`], [`copy_texture_region`]), since the start. +#[cfg(windows)] +pub(crate) static SELF_COPIES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + extern "system" fn copy_resource(this: This, dst: This, src: This) { #[cfg(windows)] { @@ -871,6 +876,17 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { if unlike(dst, src) { return; } + // Two title textures over the same memory have one host + // texture between them: the copy would be of that texture onto + // itself, which the host does not allow, and it would change + // nothing. It was recorded all the same, with the texture left + // in the source state as the copy's destination (run 205's + // debug layer: "CopyResource with its destination in the + // COPY_SOURCE state", 37 times, a 2560x1440 depth texture). + // Only the two state changes and the copy are left out: what + // is noted of the textures stays as it was. After + // triippywhale 6e502b3b. + let same = windows::core::Interface::as_raw(to) == windows::core::Interface::as_raw(from); // A source the title fills itself is uploaded first (upstream // PR #671): a copy read whatever the host texture held. if crate::texture::title_written(from) { @@ -882,9 +898,21 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { // A destination made level by level gets its levels' memory // ahead of this list (`crate::tiles`). crate::texture::card_writes(list, dst, to, None); + crate::texture::host_written(dst); + if same { + SELF_COPIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!( + ?dst, + ?src, + "a copy between two title textures that share one host texture is left out: the first one" + ); + }); + return; + } ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); - crate::texture::host_written(dst); #[cfg(feature = "diagnostics")] list.note_op(|| format!("copy resource {src:?} to {dst:?}")); // SAFETY: an open list and live textures. @@ -977,6 +1005,8 @@ extern "system" fn copy_texture_region( return; } let mut from = src; + // Both sides are the same subresource of one host texture (set below). + let mut same = false; let _upload; // keeps the source alive while this call records it #[cfg(feature = "diagnostics")] let mut read = None; @@ -1013,11 +1043,21 @@ extern "system" fn copy_texture_region( let Some(texture) = crate::resource::host_resource(src.resource) else { return; }; + // The same subresource of one host texture on both sides (two + // title textures over one memory): not a copy the host allows. + // The states and the copy are left out below; the rest is + // noted as before. + same = texture.as_raw() == to.as_raw() + && src.kind != FOOTPRINT + && dst.kind != FOOTPRINT + && src.footprint.offset as u32 == dst.footprint.offset as u32; list.twin_use(src.resource, false, false); if crate::texture::title_written(texture) { crate::texture::upload(list, src.resource, texture); } - ensure_state(list, src.resource, COPY_SOURCE); + if !same { + ensure_state(list, src.resource, COPY_SOURCE); + } from.resource = texture.as_raw().cast_const().cast(); } // A depth texture shaders also write: what they wrote, first (the @@ -1061,8 +1101,12 @@ extern "system" fn copy_texture_region( // of its result into a block-compressed texture of that kind, and // a copy into a level without memory is dropped. crate::texture::card_writes(list, dst.resource, to, Some(dst.footprint.offset as u32)); - ensure_state(list, dst.resource, COPY_DEST); crate::texture::host_written(dst.resource); + if same { + SELF_COPIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return; + } + ensure_state(list, dst.resource, COPY_DEST); let mut to_location = dst; to_location.resource = to.as_raw().cast_const().cast(); let host_box = (!source_box.is_null()).then(|| source_box.cast::()); diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index a42c89f..b4f8dbe 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -239,13 +239,23 @@ pub fn title() -> Title { pub fn use_console_timers() { use windows_sys::Win32::Media::timeBeginPeriod; use windows_sys::Win32::System::Threading::{ - GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION, + GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION, PROCESS_POWER_THROTTLING_EXECUTION_SPEED, PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE, ProcessPowerThrottling, SetProcessInformation, }; + // Also: the system does not run this process at reduced speed (its + // "efficiency mode": lower clock, the slow cores of a hybrid processor) + // when its window is not the one in front, as while its owner works in + // another window or streams. The console has eight cores alike and no + // such mode. `VICTORY_EFFICIENCY_MODE=1` leaves the system its choice. + let execution = if std::env::var_os("VICTORY_EFFICIENCY_MODE").is_some_and(|v| v == "1") { + 0 + } else { + PROCESS_POWER_THROTTLING_EXECUTION_SPEED + }; let keep = PROCESS_POWER_THROTTLING_STATE { Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, - ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, + ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION | execution, StateMask: 0, }; // SAFETY: plain process settings; `keep` outlives the call. From d2a8f03b6d73b753316c5b4f6e0576cbc18dcd5b Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 06:20:48 -0600 Subject: [PATCH 347/445] Title memory by address: what streaming brings is taken when the list is submitted, not when it is recorded Dumps of runs light-8 and light-9: of structures of the same size some are unpacked right and some not, more of them in frames that stream much. The title's queue waits for its streaming, so a packed structure's bytes may come after the dispatch that unpacks it is recorded. Not run in the game yet. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/memory.rs | 207 ++++++++++++++++++++++--------- 1 file changed, 148 insertions(+), 59 deletions(-) diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 5a7112f..65a2cd7 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -90,6 +90,10 @@ const MOST: usize = 3 << 14; const WINDOWS: usize = 512; /// The biggest packed structure taken for one. const PACKED: u64 = 64 << 20; +/// For so many frames what a page holds may still be on its way. +const YOUNG: u64 = 4; +/// Free pages there are, at least, when a list is recorded. +const SPARE: usize = 1024; /// A packed structure not named for so many frames is another one. const AGAIN: u64 = 8; /// From a root view; from one that is written (a structure being built). @@ -121,8 +125,9 @@ struct Held { copy: usize, /// The write-watch asking after which it was last taken (0: never). taken: u64, - /// The frame it was last looked at in. + /// The frame it was last looked at in, and the one it came in. looked: u64, + born: u64, /// Packed structures that have bytes in it, and whether it is held for /// them alone. owners: u32, @@ -146,9 +151,8 @@ struct Memory { copies: Vec>, /// Places of title buffers' copies among `copies`. numbers: HashMap, - /// Arenas: place in `copies`, address; pages of the last one handed out. + /// Arenas: place in `copies`, address. arenas: Vec<(usize, usize)>, - used: u64, /// By title page. pages: HashMap, /// Their numbers in the order they came, and where the sweep is. @@ -161,7 +165,7 @@ struct Memory { /// Their addresses in the order they came, and where the sweep is. packed_order: Vec, packed_sweep: usize, - /// Places of pages given back: the copy, the address in the arena. + /// Places of pages that are free: the copy, the address in the arena. free: Vec<(usize, usize)>, /// Copies of title buffers the builder may store in. open: std::collections::HashSet, @@ -234,7 +238,6 @@ impl Memory { copies: Vec::new(), numbers: HashMap::new(), arenas: Vec::new(), - used: ARENA / PAGE, pages: HashMap::new(), order: Vec::new(), sweep: 0, @@ -371,31 +374,33 @@ impl Memory { self.hold(page, at, copy); return true; } - if self.used == ARENA / PAGE { - let Some(at) = crate::upload::reserve(ARENA as usize) else { - return false; - }; - let Some(shadow) = crate::shadow::by_address(at as u64, ARENA) else { - return false; - }; - let Some(n) = self.number(shadow) else { - return false; - }; - self.arenas.push((n, at)); - self.used = 0; + if !self.another() { + return false; } - let Some(&(copy, arena)) = self.arenas.last() else { + let Some((copy, at)) = self.free.pop() else { return false; }; - let offset = self.used * PAGE; - self.used += 1; - self.hold(page, arena + offset as usize, copy); + self.hold(page, at, copy); + true + } + + /// Another arena's pages. + fn another(&mut self) -> bool { + let Some(at) = crate::upload::reserve(ARENA as usize) else { + return false; + }; + let Some(n) = crate::shadow::by_address(at as u64, ARENA).and_then(|s| self.number(s)) else { + return false; + }; + self.arenas.push((n, at)); + // The lowest first. + self.free.extend((0..(ARENA / PAGE) as usize).rev().map(|i| (n, at + i * PAGE as usize))); true } /// `page` is held at `at` in the arena that is `copy`. fn hold(&mut self, page: u64, at: usize, copy: usize) { - self.pages.insert(page, Held { at, copy, taken: 0, looked: u64::MAX, owners: 0, theirs: false }); + self.pages.insert(page, Held { at, copy, taken: 0, looked: u64::MAX, born: self.frame, owners: 0, theirs: false }); self.order.push(page); fill(self.entry(page), copy, at as u64 - self.copies[copy].span().0); } @@ -536,35 +541,54 @@ impl Memory { self.stats.micros += started.elapsed().as_micros() as u64; } - /// If title memory has a packed structure at `address` that the builder - /// comes to anew: all of it has its pages, and goes up as it is there. - /// Whether there is a packed structure. - fn unpacks(&mut self, address: u64) -> bool { - if address & 0xFF != 0 || !self.possible(address / PAGE) { - return false; + /// The bytes of a packed structure title memory has at `address` by now, + /// and its first two dwords. + fn packed_at(&self, address: u64) -> Option<(u64, u64)> { + if address & 0xFF != 0 { + return None; } let mut header = [0u8; 8]; crate::host::copy_mapped(header.as_mut_ptr(), address as *const u8, 8, false); - let Some(len) = packed_len(u64::from_le_bytes(header)) else { - return false; - }; let header = u64::from_le_bytes(header); + Some((packed_len(header)?, header)) + } + + /// At the submission of a list whose builder dispatch was given `address` + /// outside buffers, in the order of its copies: what title memory has + /// there now goes up. When the dispatch is recorded it may not be there + /// yet: the title's queue waits for its streaming. (Nothing is asked of + /// the write watch here: the submission's asking stands.) + fn land(&mut self, address: u64) { + let page = address / PAGE; + if !crate::texture::committed((page * PAGE) as *const u8, PAGE as usize) { + return; + } + let Some((len, header)) = self.packed_at(address) else { + // Anything else: what came since its page was first taken. + for page in page..=(address + VIEW - 1) / PAGE { + if self.pages.get(&page).is_some_and(|h| h.born + YOUNG >= self.frame) { + self.take(page, 0, PAGE as usize, false); + } + } + return; + }; if let Some(known) = self.packed.get_mut(&address) { let soon = known.frame + AGAIN >= self.frame; known.frame = self.frame; if known.header == header && soon { - return true; + return; } if known.header != header { self.gone(address); } } + let last = (address + len - 1) / PAGE; if !self.packed.contains_key(&address) { self.packed.insert(address, Packed { frame: self.frame, len, header }); self.packed_order.push(address); - for page in address / PAGE..=(address + len - 1) / PAGE { - let new = !self.pages.contains_key(&page); - if !self.map(page) { + for page in page..=last { + let new = self.copy_of(page).is_none(); + if new && !self.place(page) { continue; } if let Some(held) = self.pages.get_mut(&page) { @@ -574,26 +598,59 @@ impl Memory { } self.stats.packed_bytes += len; } - self.ready(address, len); - let mut title = [0u8; PIECE]; - let mut at = address; - while at < address + len { - let n = (PAGE - at % PAGE).min(address + len - at).min(PIECE as u64) as usize; - if let Some(held) = self.pages.get(&(at / PAGE)) { - let place = held.at + (at % PAGE) as usize; - crate::host::copy_mapped(title.as_mut_ptr(), at as *const u8, n, false); - // SAFETY: a page of an arena of ours, under the mutex. - unsafe { std::slice::from_raw_parts_mut(place as *mut u8, n) }.copy_from_slice(&title[..n]); - let shadow = &self.copies[held.copy]; - let base = place - shadow.span().0 as usize; - shadow.resend(base, base + n); - } - at += n as u64; + for page in page..=last { + let from = address.max(page * PAGE) - page * PAGE; + let to = (address + len).min((page + 1) * PAGE) - page * PAGE; + self.take(page, from as usize, to as usize, true); } self.stats.packed += 1; + } + + /// A place in an arena for a page of committed title memory, at a + /// submission: only one there is already (the list brings up the arenas + /// it knew when it was recorded). + fn place(&mut self, page: u64) -> bool { + if page < 0x1_0000 + || page >= u64::from(MEMORY_PAGES) - 1 + || !crate::texture::committed((page * PAGE) as *const u8, PAGE as usize) + || crate::shadow::in_buffer(page * PAGE, PAGE).is_some() + { + return false; + } + let Some((copy, at)) = self.free.pop() else { + return false; + }; + self.hold(page, at, copy); + crate::watch::wrote(self.entry(page) as usize, 8); + self.take(page, 0, PAGE as usize, true); true } + /// Bytes `from..to` of `page` from title memory into its arena's page, at + /// a submission; `whole`: sent whether they differ from those last taken + /// or not. + fn take(&mut self, page: u64, from: usize, to: usize, whole: bool) { + let Some(held) = self.pages.get(&page) else { return }; + let shadow = &self.copies[held.copy]; + let base = held.at - shadow.span().0 as usize; + let mut title = [0u8; PIECE]; + let mut at = from; + while at < to { + let n = (PIECE - at % PIECE).min(to - at); + crate::host::copy_mapped(title.as_mut_ptr(), (page as usize * PAGE as usize + at) as *const u8, n, false); + // SAFETY: a page of an arena of ours, under the mutex. + let ours = unsafe { std::slice::from_raw_parts_mut((held.at + at) as *mut u8, n) }; + if *ours != title[..n] { + ours.copy_from_slice(&title[..n]); + crate::watch::wrote(held.at + at, n); + } + at += n; + } + if whole { + shadow.resend(base + from, base + to); + } + } + /// The pages shaders found empty since the last frame. fn take_faults(&mut self) { let mut pages = Vec::new(); @@ -680,6 +737,17 @@ impl Memory { } } + /// Every copy is brought up to date when `list` is submitted, after what + /// it deferred so far (once until a copy of the title's intervenes). + fn bring_up(&self, list: &HostList) { + let (start, len) = self.directory.1.span(); + self.directory.1.refresh(list, start, len); + for shadow in &self.copies { + let (start, len) = shadow.span(); + shadow.refresh(list, start, len); + } + } + /// Every ten seconds or so, what was used. fn report(&mut self) { let now = std::time::Instant::now(); @@ -792,6 +860,7 @@ pub(crate) fn ready( m.report(); } let builds = use_ != Use::Reads; + 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 // a frame with the same arguments. @@ -823,7 +892,34 @@ pub(crate) fn ready( let mut came = [held(m) - before, 0, 0, 0]; for &at in addresses.iter().filter(|&&a| a >= 1 << 32) { // (Several structures to a page.) - let packed = builds && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize) && m.unpacks(at); + let mut packed = false; + if builds + && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize) + && crate::shadow::in_buffer(at, 1).is_none() + && m.possible(at / PAGE) + { + // What it needs, as far as it is known now; the rest when the + // list is submitted ([`Memory::land`]). + if let Some((len, _)) = m.packed_at(at) { + packed = true; + for page in at / PAGE..=(at + len - 1) / PAGE { + let new = m.copy_of(page).is_none(); + if m.map(page) + && new + && let Some(held) = m.pages.get_mut(&page) + { + held.theirs = true; + } + } + m.bring(at / PAGE, (at + len - 1) / PAGE + 1); + } + list.defer_host(move || { + if let Some(m) = MEMORY.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + m.land(at); + } + }); + m.bring_up(list); + } if builds && written.contains(&at) && list.first_use(usize::MAX - (4 << 33) - (at >> 2 & 0x7FFF_FFFF) as usize) { if let Some((start, len)) = crate::shadow::in_buffer(at, 1) && len <= BACK @@ -889,14 +985,7 @@ pub(crate) fn ready( // half of them, run light-8). let first_read = list.first_use(READ); if list.first_use(usize::MAX - (6 << 33) - m.copies.len()) { - let (start, len) = m.directory.1.span(); - m.directory.1.refresh(list, start, len); - for (n, shadow) in m.copies.iter().enumerate() { - if list.first_use(usize::MAX - (7 << 33) - n) { - let (start, len) = shadow.span(); - shadow.refresh(list, start, len); - } - } + m.bring_up(list); } if first_read { list.keep(&m.faults.0); From 040aa272c2f6057c702e75588e8c4b425aa2dd4e Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 06:26:36 -0600 Subject: [PATCH 348/445] VICTORY_CARD_AWAKE: menus keep the card awake too (comment) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host/awake.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/host/awake.rs b/crates/victory-gpu/src/host/awake.rs index 8837d15..14f6ea5 100644 --- a/crates/victory-gpu/src/host/awake.rs +++ b/crates/victory-gpu/src/host/awake.rs @@ -8,8 +8,9 @@ //! //! One group of 64 threads counts on a compute queue, over and //! over: it takes one or two of the card's few thousand wave slots, and the -//! card is never idle. Nothing is sent once no submission has gone out for a -//! while (a menu at 30 fps, a minimized window). +//! card is never idle. Nothing is sent once no submission has gone out for +//! a quarter of a second (a title that stands still; not a menu, which goes on +//! drawing: the system's counter shows the compute queue at 100 % there too). use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; From 13ffc2833df58bb570900c7facff54dca4dbe707 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 06:48:29 -0600 Subject: [PATCH 349/445] Wait instructions over the end of eight bytes are replaced too; clzero loops become plain stores (VICTORY_PATCH_CLZERO=0: emulated) Run cpu-5: 25,000 exceptions a second at five clzero loops of one function of the title, against 1,400-7,000 at the one monitorx/mwaitx pair (28,000 at the monitorx alone with only the mwaitx replaced, run cpu-6). Co-Authored-By: Claude Opus 5.5 --- crates/victory-loader/src/console_insn.rs | 251 ++++++++++++++++++---- 1 file changed, 212 insertions(+), 39 deletions(-) diff --git a/crates/victory-loader/src/console_insn.rs b/crates/victory-loader/src/console_insn.rs index 775961c..3ca43e5 100644 --- a/crates/victory-loader/src/console_insn.rs +++ b/crates/victory-loader/src/console_insn.rs @@ -66,52 +66,157 @@ fn wait_patch(what: ConsoleOnly) -> Option<[u8; 3]> { } } -/// The aligned 8 bytes `word` around address `at` with the 3 bytes at `at` replaced; `None` -/// where they do not all lie in those 8. -fn with_patch(word: u64, at: usize, patch: [u8; 3]) -> Option { - let offset = at & 7; - if offset + patch.len() > 8 { +/// Whether a `clzero` loop ([`ConsoleOnly::ClzeroLoop`]) is replaced the first time it faults +/// by a jump to the same loop with plain stores ([`clzero_stub`]). Run cpu-5 (the dorm): 25,000 +/// exceptions a second, 2,100 a frame, at five such loops of one function of the title, for +/// some kilobytes each; ten times what the wait instructions raised. On by default; +/// `VICTORY_PATCH_CLZERO=0` emulates each time, as before. +fn patches_clzero() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PATCH_CLZERO").is_none_or(|v| v != "0")) +} + +/// `jmp rel32` at `at` to `to`, if it reaches. +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]) +} + +/// The `clzero` loop of 12 bytes at `at` with plain stores, as code at `stub`: every register +/// and the flags come out as the loop leaves them. `cmp` is its `cmp rax, reg` (3 bytes, the +/// register not `rax`), `None` for another form. (The scratch register is saved on the stack +/// and back before the compare, whose register it may be.) +fn clzero_stub(at: usize, stub: usize, cmp: [u8; 3]) -> Option> { + if !matches!(cmp[0], 0x48 | 0x4c) || cmp[1] != 0x39 || cmp[2] & 0xc7 != 0xc0 || (cmp[0] == 0x48 && cmp[2] == 0xc0) { + return None; + } + let mut code = vec![ + 0x51, // push rcx + 0x48, 0x89, 0xc1, // mov rcx, rax + 0x48, 0x83, 0xe1, 0xc0, // and rcx, -64 + ]; + for k in 0..8 { + code.extend([0x48, 0xc7, 0x41, k * 8, 0, 0, 0, 0]); // mov qword [rcx + 8k], 0 + } + code.push(0x59); // pop rcx + code.extend([0x48, 0x83, 0xc0, 0x40]); // add rax, 0x40 + code.extend(cmp); + let back = -(code.len() as i64 + 2); + code.extend([0x72, i8::try_from(back).ok()? as u8]); // jb the start + let end = stub + code.len(); + code.extend(jump(end, at + 12)?); + Some(code) +} + +/// 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; + +/// Memory for code within reach of a `jmp rel32` at `at`. +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| { + // SAFETY: reserves free memory at that address or fails. + let got = unsafe { VirtualAlloc(place as *const _, STUBS_LEN, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) } as usize; + (got != 0).then_some(got) + }) +} + +/// Replaces the `clzero` loop at `at`, whose 12 bytes are `code`: whether it did. +/// +/// No thread is ever inside the loop's other instructions (the emulation does the whole loop +/// in one), so the five bytes of the jump may take the place of two of them. +/// +/// # Safety +/// `at` is in the title's code, which stays mapped. +unsafe fn patch_clzero(at: usize, code: &[u8]) -> bool { + let &[a, b, c, d, e, _, _, x, y, z, 0x72, 0xf4] = code else { + return false; + }; + let mut stubs = STUBS.lock().unwrap_or_else(|e| e.into_inner()); + if stubs.is_none() { + *stubs = near(at).map(|place| (place, 0)); + } + let Some((place, used)) = stubs.as_mut() else { + return false; + }; + let stub = *place + *used; + let (Some(body), Some(jump)) = (clzero_stub(at, stub, [x, y, z]), jump(at, stub)) else { + return false; + }; + if *used + body.len() > STUBS_LEN || (at & 15) + 5 > 16 { + return false; + } + // SAFETY: inside the memory made for it, which nothing runs yet; then the title's code. + unsafe { + std::ptr::copy_nonoverlapping(body.as_ptr(), stub as *mut u8, body.len()); + *used += body.len().next_multiple_of(16); + patch(at, [a, b, c, d, e], jump) + } +} + +/// The aligned 16 bytes `word` around address `at` with the bytes at `at` replaced; `None` +/// where they do not all lie in those 16. (16 and not 8: the title's busiest one lies over the +/// end of its 8 and took 28,000 exceptions a second, run cpu-6.) +fn with_patch(word: u128, at: usize, patch: &[u8]) -> Option { + let offset = at & 15; + if offset + patch.len() > 16 { return None; } let mut bytes = word.to_le_bytes(); - bytes[offset..offset + patch.len()].copy_from_slice(&patch); - Some(u64::from_le_bytes(bytes)) + bytes[offset..offset + patch.len()].copy_from_slice(patch); + Some(u128::from_le_bytes(bytes)) } /// One thread at a time changes code: a second one would take the first one's loosened /// protection for the page's own. static PATCHING: std::sync::Mutex<()> = std::sync::Mutex::new(()); -/// Replaces the 3 bytes at `at`, which are `was`, by `patch`, in one store that other threads -/// see whole: whether they are replaced now (not where they cross 8 aligned bytes, or the page +/// Replaces the bytes at `at`, which are `was`, by `patch`, in one store that other threads +/// see whole: whether they are replaced now (not where they cross 16 aligned bytes, or the page /// cannot be written). /// /// # Safety /// `at` is in code that stays mapped, and `patch` does for it what `was` does. -unsafe fn patch(at: usize, was: [u8; 3], patch: [u8; 3]) -> bool { +unsafe fn patch(at: usize, was: [u8; N], patch: [u8; N]) -> bool { use std::sync::atomic::Ordering::SeqCst; 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; - if (at & 7) + 3 > 8 { + if (at & 15) + N > 16 || !std::is_x86_feature_detected!("cmpxchg16b") { return false; } let _one = PATCHING.lock().unwrap_or_else(|e| e.into_inner()); - let word = (at & !7) as *mut u64; - let here = (at & 7)..(at & 7) + 3; + let word = (at & !15) as *mut u128; + let here = (at & 15)..(at & 15) + N; let mut old = 0u32; - // SAFETY: the aligned 8 bytes around the instruction lie in one page of mapped code, made - // writable for the store and put back. + // SAFETY: the aligned 16 bytes around the instruction lie in one page of mapped code, made + // writable for the store and put back; the processor has the instruction (asked above). unsafe { - if VirtualProtect(word.cast(), 8, PAGE_EXECUTE_READWRITE, &mut old) == 0 { + if VirtualProtect(word.cast(), 16, PAGE_EXECUTE_READWRITE, &mut old) == 0 { return false; } - let done = AtomicU64::from_ptr(word) - .fetch_update(SeqCst, SeqCst, |now| if now.to_le_bytes()[here.clone()] == was { with_patch(now, at, patch) } else { None }) - // (Another thread's fault at the same place: done already.) - .map_or_else(|now| now.to_le_bytes()[here.clone()] == patch, |_| true); - VirtualProtect(word.cast(), 8, old, &mut old); - FlushInstructionCache(GetCurrentProcess(), word.cast(), 8); + // What is there (zeros are replaced by zeros). + let mut now = std::arch::x86_64::cmpxchg16b(word, 0, 0, SeqCst, SeqCst); + let done = loop { + let bytes = &now.to_le_bytes()[here.clone()]; + if bytes == patch { + // (Another thread's fault at the same place: done already.) + break true; + } + let Some(new) = (bytes == was).then(|| with_patch(now, at, &patch)).flatten() else { + break false; + }; + let there = std::arch::x86_64::cmpxchg16b(word, now, new, SeqCst, SeqCst); + if there == now { + break true; + } + now = there; + }; + VirtualProtect(word.cast(), 16, old, &mut old); + FlushInstructionCache(GetCurrentProcess(), word.cast(), 16); done } } @@ -186,7 +291,7 @@ mod sites { let top: Vec = all.iter().take(8).map(|s| format!("{:#x} {} {:.0}", s.1, NAMES[s.2], s.0 as f64 / seconds)).collect(); tracing::info!( - "console CPU instructions that fault, a second: {}; wait instructions replaced in place so far: {}; the busiest places: {}", + "console CPU instructions that fault, a second: {}; places replaced so far: {}; the busiest places: {}", kinds.join(", "), PATCHED.load(Relaxed), top.join(", ") @@ -328,6 +433,15 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { } ConsoleOnly::ClzeroLoop { end_reg } => { // the whole `clzero; add rax,40h; cmp rax,end; jb` loop at once + // (and not again: the next time it is plain stores) + if len == 12 + && patches_clzero() + // SAFETY: the title's code, where the loop's first instruction just faulted. + && unsafe { patch_clzero(rip, &code[..12]) } + { + #[cfg(feature = "diagnostics")] + sites::patched(); + } let regs: [u64; 16] = [ ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.Rbx, ctx.Rsp, ctx.Rbp, ctx.Rsi, ctx.Rdi, ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15, ]; @@ -426,12 +540,12 @@ mod tests { use super::*; #[test] - fn wait_instructions_are_replaced_inside_eight_aligned_bytes() { - let word = u64::from_le_bytes([1, 2, 0x0f, 0x01, 0xfb, 6, 7, 8]); - let new = with_patch(word, 0x1002, [0xf3, 0x90, 0x90]).unwrap(); - assert_eq!(new.to_le_bytes(), [1, 2, 0xf3, 0x90, 0x90, 6, 7, 8]); - assert!(with_patch(word, 0x1005, [0; 3]).is_some()); - assert!(with_patch(word, 0x1006, [0; 3]).is_none(), "crosses into the next eight"); + fn wait_instructions_are_replaced_inside_sixteen_aligned_bytes() { + let word = u128::from_le_bytes([1, 2, 3, 4, 5, 6, 7, 0x0f, 0x01, 0xfb, 11, 12, 13, 14, 15, 16]); + let new = with_patch(word, 0x1007, &[0xf3, 0x90, 0x90]).unwrap(); + assert_eq!(new.to_le_bytes(), [1, 2, 3, 4, 5, 6, 7, 0xf3, 0x90, 0x90, 11, 12, 13, 14, 15, 16]); + assert!(with_patch(word, 0x100d, &[0; 3]).is_some()); + assert!(with_patch(word, 0x100e, &[0; 3]).is_none(), "crosses into the next sixteen"); } /// `monitorx; mwaitx; ret` in a page of its own: each is replaced at its first fault, @@ -447,34 +561,93 @@ mod tests { let page = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE).cast::(); assert!(!page.is_null()); let code = [0x0f, 0x01, 0xfa, 0x0f, 0x01, 0xfb, 0xc3]; - // Both within the aligned eight bytes at 8; and one over the end of its eight - // (at 22), which is left alone. - std::ptr::copy_nonoverlapping(code.as_ptr(), page.add(8), code.len()); - std::ptr::copy_nonoverlapping(code.as_ptr(), page.add(22), code.len()); + // The first over the end of its aligned eight bytes, as the title's is; and one + // over the end of its sixteen (at 46), which is left alone. + std::ptr::copy_nonoverlapping(code.as_ptr(), page.add(6), code.len()); + std::ptr::copy_nonoverlapping(code.as_ptr(), page.add(46), code.len()); let mut old = 0; assert_ne!(VirtualProtect(page.cast(), 4096, PAGE_EXECUTE_READ, &mut old), 0); let at = page as usize; let mut context: CONTEXT = std::mem::zeroed(); - for rip in [at + 8, at + 11, at + 22] { + for rip in [at + 6, at + 9, at + 46] { context.Rip = rip as u64; assert_eq!(emulate(&mut context), CONTINUE_EXECUTION); assert_eq!(context.Rip, rip as u64 + 3); } if patches_waits() { - let now = std::slice::from_raw_parts(page.add(8), 7); + let now = std::slice::from_raw_parts(page.add(6), 7); assert_eq!(now, [0x0f, 0x1f, 0x00, 0xf3, 0x90, 0x90, 0xc3]); // They run now. - let run: extern "system" fn() = std::mem::transmute(page.add(8)); + let run: extern "system" fn() = std::mem::transmute(page.add(6)); run(); // A second thread that faulted at the same place meanwhile. - assert!(patch(at + 8, [0x0f, 0x01, 0xfa], [0x0f, 0x1f, 0x00])); - assert!(!patch(at + 22, [0x0f, 0x01, 0xfa], [0x0f, 0x1f, 0x00]), "crosses its eight bytes"); + assert!(patch(at + 6, [0x0f, 0x01, 0xfa], [0x0f, 0x1f, 0x00])); + assert!(!patch(at + 46, [0x0f, 0x01, 0xfa], [0x0f, 0x1f, 0x00]), "crosses its sixteen bytes"); } - assert_eq!(std::slice::from_raw_parts(page.add(22), 3), [0x0f, 0x01, 0xfa]); + assert_eq!(std::slice::from_raw_parts(page.add(46), 3), [0x0f, 0x01, 0xfa]); let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); VirtualQuery(page.cast(), &mut m, size_of_val(&m)); assert_eq!(m.Protect, PAGE_EXECUTE_READ); VirtualFree(page.cast(), 0, MEM_RELEASE); } } + + /// `clzero` loops run as plain stores: the lines they name are zero and no other byte, + /// and the pointer, the scratch register and the flags come out as from the loop. + #[test] + fn a_clzero_loop_becomes_plain_stores() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAlloc, VirtualFree}; + // Against rdx (rm rax, reg rdx) and against rcx, the scratch register. + for (cmp, by) in [([0x48, 0x39, 0xd0], 2), ([0x48, 0x39, 0xc8], 1), ([0x4c, 0x39, 0xc0], 8)] { + // SAFETY: memory of our own, written and run inside it. + unsafe { + let page = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize; + assert_ne!(page, 0); + // A function of (start, end): the start in rax, the end in its register, the + // loop at 16, and what rax became. + let mut head = vec![0x48, 0x89, 0xc8]; // mov rax, rcx + match by { + 1 => head.extend([0x48, 0x89, 0xd1]), // mov rcx, rdx + 8 => head.extend([0x49, 0x89, 0xd0]), // mov r8, rdx + _ => {} + } + head.resize(16, 0x90); + let mut code = head; + code.extend([0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x40]); + code.extend(cmp); + code.extend([0x72, 0xf4]); + code.push(0xc3); + std::ptr::copy_nonoverlapping(code.as_ptr(), page as *mut u8, code.len()); + let mut context: CONTEXT = std::mem::zeroed(); + let mut block = vec![0xaau8; 64 * 8 + 64]; + let base = block.as_mut_ptr() as usize; + let first = base.next_multiple_of(64); + // The fault itself: emulated whole, and replaced. + context.Rip = page as u64 + 16; + context.Rax = first as u64; + context.Rdx = first as u64 + 128; + context.Rcx = context.Rdx; + context.R8 = context.Rdx; + assert_eq!(emulate(&mut context), CONTINUE_EXECUTION); + assert_eq!((context.Rip, context.Rax), (page as u64 + 28, first as u64 + 128)); + if patches_clzero() { + assert_eq!(*((page + 16) as *const u8), 0xe9, "a jump"); + block.fill(0xaa); + let run: extern "system" fn(usize, usize) -> usize = std::mem::transmute(page); + // From inside a line to inside the third: whole lines, one past the end. + assert_eq!(run(first + 8, first + 130), first + 8 + 128); + let at = first - base; + assert!(block[at..at + 128].iter().all(|&b| b == 0)); + assert!(block[..at].iter().chain(&block[at + 128..]).all(|&b| b == 0xaa)); + // An end at the start: one line. + block.fill(0xaa); + assert_eq!(run(first, first), first + 64); + assert!(block[at..at + 64].iter().all(|&b| b == 0) && block[at + 64] == 0xaa); + } + VirtualFree(page as *mut _, 0, MEM_RELEASE); + } + } + assert!(clzero_stub(0x1000, 0x2000, [0x48, 0x39, 0xc0]).is_none(), "against rax itself"); + assert!(jump(0x1000, 0x9000_0000_0000).is_none(), "out of reach"); + } } From 67471988dc9752dc561984c8e2ad28b9c8091c77 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 06:53:10 -0600 Subject: [PATCH 350/445] A book of who has and had the card's memory; a check of every view slot With device-removed data on, every buffer, texture and texture block stands in a book with its address (a texture's is the base in its first descriptor) and stays with the time it went. A device loss prints who has and had the faulting address, newest first, and every slot of the view heap whose descriptor reaches it, with what our books say of the slot. VICTORY_BOOK=0: not kept. VICTORY_SLOT_CHECK=1 walks the view heap (2^22 slots, 3.8 s a round) and says which slots name memory that is gone. Run crash-5 (opening, -Walk, 260 s): 1.7 million descriptors a round, 105,352 things alive, 27,342 gone, none of the slots named anything gone or unknown in any round. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/book.rs | 675 ++++++++++++++++++++++ crates/victory-gpu/src/descriptor/host.rs | 81 +++ crates/victory-gpu/src/draw.rs | 2 + crates/victory-gpu/src/host.rs | 41 +- crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/pool.rs | 5 + 6 files changed, 805 insertions(+), 1 deletion(-) create mode 100644 crates/victory-gpu/src/book.rs diff --git a/crates/victory-gpu/src/book.rs b/crates/victory-gpu/src/book.rs new file mode 100644 index 0000000..df3e9a9 --- /dev/null +++ b/crates/victory-gpu/src/book.rs @@ -0,0 +1,675 @@ +//! Who has what memory of the card, and who had it (diagnostics). +//! +//! A device loss names a faulting address and, from a short list, what was +//! freed there. A texture gone for minutes is in "nothing named", and which +//! descriptor still names it is not told at all. Here every buffer, texture +//! and texture block of ours stands with its address from when it is made, +//! and stays with the time it went ([`made`], [`block`]); a texture's address +//! is the base in the descriptor of its first view, which the card's heaps +//! hold as plain bytes (measured: `indirect::tests::descriptors_written_under_readers`). +//! +//! - At a device loss ([`at_loss`]): who owns the faulting address and who +//! owned it, newest first, and every slot of the view heap whose +//! descriptor reaches it. +//! - `VICTORY_SLOT_CHECK=1`: a thread walks the view heap and says which +//! slots name memory that is gone, while nothing is lost yet ([`check`]). +//! +//! The book is kept with device-removed data on (`VICTORY_D3D12_DRED`) or the +//! check; `VICTORY_BOOK=0` keeps none. +//! +//! What the descriptors' bits mean is AMD's (RDNA 2 and 3); on another card +//! nothing is decoded as an address we know, and nothing is said. + +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; +use windows::core::{GUID, HRESULT, IUnknown, Interface}; + +/// Entries of what is gone that are kept. +const GONE: usize = 400_000; +/// Longer than anything of ours: how far below an address its owner starts. +const LONGEST: u64 = 2 << 30; +/// Entries longer than this are few and looked through one by one. +const LONG: u64 = 64 << 20; + +#[derive(Clone, Debug)] +struct Entry { + start: u64, + size: u64, + what: String, + made: u64, +} + +#[derive(Default)] +struct Book { + next: u64, + live: HashMap, + by_start: BTreeMap<(u64, u64), ()>, + long: Vec, + /// By the object's address, for a name given after it was made. + by_object: HashMap, + gone: VecDeque<(Entry, u64)>, + /// Objects whose address could not be told, by what they are. + unknown: BTreeMap, +} + +static BOOK: Mutex> = Mutex::new(None); +/// Root descriptors given by address lately: time, address, bytes. +static ROOTS: Mutex> = Mutex::new(VecDeque::new()); + +pub(crate) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + std::env::var_os("VICTORY_BOOK").is_none_or(|v| v != "0") + && !cfg!(test) + && (crate::host::dred_any() || checks()) + }) +} + +/// `VICTORY_SLOT_CHECK=1`. +pub(crate) fn checks() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SLOT_CHECK").is_some_and(|v| v != "0")) +} + +fn with(f: impl FnOnce(&mut Book) -> T) -> T { + f(BOOK.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(Book::default)) +} + +impl Book { + fn add(&mut self, object: usize, start: u64, size: u64, what: String, now: u64) -> u64 { + self.next += 1; + let id = self.next; + self.by_start.insert((start, id), ()); + if size > LONG { + self.long.push(id); + } + self.live.insert(id, Entry { start, size, what, made: now }); + if object != 0 { + self.by_object.insert(object, id); + } + id + } + + fn remove(&mut self, id: u64, object: usize, now: u64) { + if let Some(entry) = self.live.remove(&id) { + self.by_start.remove(&(entry.start, id)); + if entry.size > LONG { + self.long.retain(|&l| l != id); + } + if self.gone.len() >= GONE { + self.gone.pop_front(); + } + self.gone.push_back((entry, now)); + } + if self.by_object.get(&object) == Some(&id) { + self.by_object.remove(&object); + } + } + + /// Whether something alive holds `at`. + fn alive(&self, at: u64) -> bool { + let holds = |id: &u64| self.live.get(id).is_some_and(|e| at >= e.start && at - e.start < e.size); + self.by_start + .range((at.saturating_sub(LONG), 0)..=(at, u64::MAX)) + .rev() + .any(|((_, id), ())| holds(id)) + || self.long.iter().any(holds) + } + + /// The live entries that hold `at`, the one that starts last first. + fn holders(&self, at: u64) -> Vec<&Entry> { + let from = at.saturating_sub(LONGEST); + self.by_start + .range((from, 0)..=(at, u64::MAX)) + .rev() + .filter_map(|((_, id), ())| self.live.get(id)) + .filter(|e| at - e.start < e.size) + .take(8) + .collect() + } + + /// The live entry that starts last at or below `at`, and the next above. + fn neighbours(&self, at: u64) -> [Option<&Entry>; 2] { + let below = self.by_start.range(..=(at, u64::MAX)).next_back(); + let above = self.by_start.range((at + 1, 0)..).next(); + [below, above].map(|e| e.and_then(|((_, id), ())| self.live.get(id))) + } + + /// What held `at` and is gone, newest first. + fn gone_at(&self, at: u64, most: usize) -> Vec<&(Entry, u64)> { + self.gone.iter().rev().filter(|(e, _)| at >= e.start && at - e.start < e.size).take(most).collect() + } +} + +#[repr(C)] +struct Notice { + methods: &'static [*const (); 3], + references: AtomicU32, + id: u64, + object: usize, +} + +struct Methods([*const (); 3]); +// SAFETY: function addresses only. +unsafe impl Sync for Methods {} +static NOTICE: Methods = Methods([query as *const (), add_ref as *const (), release as *const ()]); + +unsafe extern "system" fn query(this: *mut c_void, iid: *const GUID, out: *mut *mut c_void) -> HRESULT { + // SAFETY: COM's arguments. + unsafe { + if out.is_null() { + return HRESULT(0x8000_4003_u32 as i32); + } + if iid.as_ref().is_some_and(|iid| *iid == IUnknown::IID) { + add_ref(this); + *out = this; + return HRESULT(0); + } + *out = std::ptr::null_mut(); + } + HRESULT(0x8000_4002_u32 as i32) +} + +unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + // SAFETY: one of ours, alive while a reference to it is. + unsafe { (*this.cast::()).references.fetch_add(1, Ordering::Relaxed) + 1 } +} + +unsafe extern "system" fn release(this: *mut c_void) -> u32 { + // SAFETY: as above; the last reference frees the box it was made as. + unsafe { + let left = (*this.cast::()).references.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { + let gone = Box::from_raw(this.cast::()); + let now = crate::host::now_ms(); + with(|b| b.remove(gone.id, gone.object, now)); + } + left + } +} + +/// Has the book told when `object` goes. +fn watch(object: &ID3D12Object, id: u64) { + const KEY: GUID = GUID::from_u128(0x2c7d1a55_9e0b_46f2_8c11_5b8e70a4d913); + let raw = object.as_raw() as usize; + let notice = Box::into_raw(Box::new(Notice { methods: &NOTICE.0, references: AtomicU32::new(1), id, object: raw })); + // SAFETY: a COM object of ours with one reference, which this drops; the + // object takes its own. + unsafe { + let notice = IUnknown::from_raw(notice.cast()); + if object.SetPrivateDataInterface(&KEY, ¬ice).is_err() { + std::mem::forget(notice); + } + } +} + +/// A view format for a typeless one (its first with a plain type). +fn viewable(format: i32) -> Option { + Some(match format { + 1 => 2, + 5 => 6, + 9 => 11, + 15 => 16, + 19 => 21, + 23 => 24, + 27 => 28, + 33 => 35, + 39 => 41, + 44 => 46, + 48 => 49, + 53 => 56, + 60 => 61, + 70 | 73 | 76 | 79 | 82 | 94 | 97 => format + 1, + 90 => 87, + 92 => 88, + 20 | 40 | 45 | 55 => return None, // typed depth: no shader view + f => f, + }) +} + +/// The address of a texture: the base its descriptor has. +fn texture_address(texture: &ID3D12Resource, desc: &D3D12_RESOURCE_DESC) -> Option { + struct Slot(ID3D12DescriptorHeap, usize); + // SAFETY: a descriptor heap, used under the lock. + unsafe impl Send for Slot {} + static SLOT: Mutex> = Mutex::new(None); + if desc.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 != 0 { + return None; + } + let host = crate::host::made_host()?; + let mut slot = SLOT.lock().unwrap_or_else(|e| e.into_inner()); + if slot.is_none() { + // SAFETY: plain heap creation. + let heap: ID3D12DescriptorHeap = unsafe { + host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 1, + ..Default::default() + }) + } + .ok()?; + // SAFETY: a live heap. + let at = unsafe { heap.GetCPUDescriptorHandleForHeapStart().ptr }; + *slot = Some(Slot(heap, at)); + } + let at = slot.as_ref()?.1; + let format = viewable(desc.Format.0)?; + let mut view = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(format), + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + ..Default::default() + }; + match desc.Dimension { + D3D12_RESOURCE_DIMENSION_TEXTURE1D => { + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; + view.Anonymous.Texture1D.MipLevels = 1; + } + D3D12_RESOURCE_DIMENSION_TEXTURE3D => { + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + view.Anonymous.Texture3D.MipLevels = 1; + } + _ if desc.SampleDesc.Count > 1 => view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS, + _ => view.Anonymous.Texture2D.MipLevels = 1, + } + let mut words = [0u8; 32]; + // SAFETY: a slot of ours, a live texture; the handle is the descriptor's + // memory or the read fails. + unsafe { + host.device + .CreateShaderResourceView(texture, Some(&view), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: at }); + } + if !crate::host::read_into(at as *const u8, &mut words) { + return None; + } + match decode(&words) { + Names::Texture { base, .. } => Some(base), + _ => None, + } +} + +/// `resource` was made; `what` it is (a name given later replaces it). +pub(crate) fn made(resource: &ID3D12Resource, what: impl FnOnce() -> String) { + if !on() { + return; + } + let Ok(object) = resource.cast::() else { return }; + let raw = object.as_raw() as usize; + if with(|b| b.by_object.contains_key(&raw)) { + return named(&object, what); + } + // SAFETY: a live resource. + let desc = unsafe { resource.GetDesc() }; + let (start, size) = if desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + // SAFETY: as above. + (Some(unsafe { resource.GetGPUVirtualAddress() }), desc.Width) + } else { + let size = crate::host::made_host() + // SAFETY: a plain query. + .map_or(0, |h| unsafe { h.device.GetResourceAllocationInfo(0, &[desc]) }.SizeInBytes); + (texture_address(resource, &desc), if size == u64::MAX { 0 } else { size }) + }; + let Some(start) = start.filter(|&s| s != 0) else { + return with(|b| *b.unknown.entry(format!("f{} flags {:#x}", desc.Format.0, desc.Flags.0)).or_default() += 1); + }; + let what = what(); + let now = crate::host::now_ms(); + let id = with(|b| b.add(raw, start, size.max(1), what, now)); + watch(&object, id); +} + +/// A block of texture memory, found by the texture `resource` at `offset` of it. +pub(crate) fn block(heap: &ID3D12Heap, resource: &ID3D12Resource, offset: u64, bytes: u64) { + if !on() { + return; + } + let (Ok(heap), Ok(object)) = (heap.cast::(), resource.cast::()) else { + return; + }; + let raw = heap.as_raw() as usize; + let now = crate::host::now_ms(); + let id = with(|b| { + if b.by_object.contains_key(&raw) { + return None; + } + let at = b.by_object.get(&(object.as_raw() as usize)).and_then(|id| b.live.get(id))?.start; + Some(b.add(raw, at.checked_sub(offset)?, bytes, "a block of textures".into(), now)) + }); + if let Some(id) = id { + watch(&heap, id); + } +} + +/// A name for something made before. +pub(crate) fn named(object: &ID3D12Object, what: impl FnOnce() -> String) { + let raw = object.as_raw() as usize; + if with(|b| b.by_object.contains_key(&raw)) { + let what = what(); + with(|b| { + if let Some(id) = b.by_object.get(&raw).copied() + && let Some(e) = b.live.get_mut(&id) + { + e.what = what; + } + }); + } +} + +/// A root descriptor was set by address. +pub(crate) fn root(gpu: u64, bytes: u64) { + if on() { + let mut roots = ROOTS.lock().unwrap_or_else(|e| e.into_inner()); + if roots.len() >= 16_384 { + roots.pop_front(); + } + roots.push_back((crate::host::now_ms(), gpu, bytes)); + } +} + +/// What a descriptor's 32 bytes name. +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) enum Names { + Nothing, + Texture { base: u64, meta: Option, kind: u32, width: u32, height: u32 }, + Buffer { base: u64, stride: u32, bytes: u64 }, +} + +/// The descriptor `bytes` hold, as AMD's cards have them since RDNA 2. +pub(crate) fn decode(bytes: &[u8; 32]) -> Names { + let w = |i: usize| u32::from_le_bytes([bytes[4 * i], bytes[4 * i + 1], bytes[4 * i + 2], bytes[4 * i + 3]]); + let kind = w(3) >> 28; + if kind >= 8 { + let base = (u64::from(w(0)) | u64::from(w(1) & 0xff) << 32) << 8; + if base == 0 { + return Names::Nothing; + } + // Compressed (dword 6, bit 21): where the metadata lies. + let meta = (w(6) >> 21 & 1 != 0 && w(7) != 0).then(|| u64::from(w(7)) << 16 | u64::from(w(6) >> 24) << 8); + let width = ((w(1) >> 30) | (w(2) & 0xfff) << 2) + 1; + let height = (w(2) >> 14 & 0x3fff) + 1; + return Names::Texture { base, meta, kind, width, height }; + } + let base = u64::from(w(0)) | u64::from(w(1) & 0xffff) << 32; + let stride = w(1) >> 16 & 0x3fff; + let bytes = u64::from(w(2)) * u64::from(stride.max(1)); + if base == 0 || bytes == 0 { + Names::Nothing + } else { + Names::Buffer { base, stride, bytes } + } +} + +/// What the book says of an address: alive, gone or never there. +fn fate(at: u64) -> Fate { + with(|b| { + if b.alive(at) { + return Fate::Alive; + } + match b.gone_at(at, 1).first() { + Some((e, gone)) => Fate::Gone(format!( + "{} at {:#x}+{:#x} made at {:.1} s, gone at {:.1} s", + e.what, + e.start, + e.size, + e.made as f64 / 1e3, + *gone as f64 / 1e3 + )), + None => Fate::Never, + } + }) +} + +enum Fate { + Alive, + Gone(String), + Never, +} + +/// The addresses a descriptor reads first. +fn bases(names: Names) -> Vec<(&'static str, u64)> { + match names { + Names::Nothing => Vec::new(), + Names::Texture { base, meta, .. } => { + let mut out = vec![("texture", base)]; + out.extend(meta.map(|m| ("metadata", m))); + out + } + Names::Buffer { base, bytes, .. } => vec![("buffer", base), ("buffer's end", base + bytes - 1)], + } +} + +/// Starts the thread of `VICTORY_SLOT_CHECK=1`, once. +pub(crate) fn check() { + static ONCE: std::sync::Once = std::sync::Once::new(); + if !checks() || !on() { + return; + } + ONCE.call_once(|| { + let _ = std::thread::Builder::new().name("slot check".into()).spawn(walk); + }); +} + +/// Slots found, since the start: looked at, naming nothing, textures, +/// buffers, naming what is gone, naming what was never there. +static FOUND: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; + +fn walk() { + use Ordering::Relaxed; + const CHUNK: u32 = 4096; + let mut at = 0u32; + // Slots said already, by slot and address. + let mut said: HashMap<(u32, u64), u64> = HashMap::new(); + let mut suspects: Vec<(u32, [u8; 32], u64)> = Vec::new(); + let mut round = std::time::Instant::now(); + let mut never_said = 0; + let mut gone_said = 0; + loop { + let read = crate::descriptor::host::shown_bytes(at, CHUNK); + let Some((first, bytes, end)) = read else { + std::thread::sleep(std::time::Duration::from_millis(500)); + continue; + }; + for (i, d) in bytes.chunks_exact(32).enumerate() { + let d: [u8; 32] = d.try_into().unwrap_or([0; 32]); + let names = decode(&d); + FOUND[0].fetch_add(1, Relaxed); + FOUND[match names { + Names::Nothing => 1, + Names::Texture { .. } => 2, + Names::Buffer { .. } => 3, + }] + .fetch_add(1, Relaxed); + if bases(names).iter().any(|&(_, base)| !matches!(fate(base), Fate::Alive)) { + suspects.push((first + i as u32, d, crate::host::now_ms())); + } + } + // Again a moment later: a slot between two states says nothing. + let now = crate::host::now_ms(); + let due: Vec<(u32, [u8; 32], u64)> = { + let (due, later) = suspects.into_iter().partition(|s| now >= s.2 + 400); + suspects = later; + due + }; + for (slot, was, since) in due { + let Some((_, again, _)) = crate::descriptor::host::shown_bytes(slot, 1) else { continue }; + if again != was { + continue; + } + for (part, base) in bases(decode(&was)) { + let (what, text) = match fate(base) { + Fate::Alive => continue, + Fate::Gone(text) => (4, text), + Fate::Never => (5, "nothing the book ever had".to_owned()), + }; + FOUND[what].fetch_add(1, Relaxed); + let times = said.entry((slot, base)).or_insert(0); + *times += 1; + let quota = if what == 4 { &mut gone_said } else { &mut never_said }; + if *times > 1 || *quota >= if what == 4 { 400 } else { 60 } { + continue; + } + *quota += 1; + tracing::warn!( + "slot check: view slot {slot} names {part} {base:#x} ({:?}), {text}; seen since {:.1} s; {}", + decode(&was), + since as f64 / 1e3, + crate::descriptor::host::slot_story(slot) + ); + } + } + at = first + (bytes.len() / 32) as u32; + if at >= end { + at = 0; + let f = [0, 1, 2, 3, 4, 5].map(|i| FOUND[i].swap(0, Relaxed)); + let (live, gone, unknown) = with(|b| (b.live.len(), b.gone.len(), b.unknown.clone())); + tracing::info!( + "slot check: a round of the view heap in {:.1} s: {} slots, {} null, {} textures, {} buffers; {} name what is gone, {} what the book never had; the book has {live} things alive and {gone} gone; textures without an address {unknown:?}", + round.elapsed().as_secs_f64(), + f[0], f[1], f[2], f[3], f[4], f[5] + ); + round = std::time::Instant::now(); + std::thread::sleep(std::time::Duration::from_millis(50)); + } + } +} + +/// For the report of a lost device: who has and had the faulting address, +/// and what names it. +pub(crate) fn at_loss(va: u64) -> String { + if !on() { + return String::new(); + } + let mut text = with(|b| { + let one = |e: &Entry| format!("{} {:#x}+{:#x} made at {:.1} s", e.what, e.start, e.size, e.made as f64 / 1e3); + let mut text = String::from("; BOOK: alive there:"); + for e in b.holders(va) { + text.push_str(&format!(" [{}]", one(e))); + } + for (name, e) in ["below", "above"].iter().zip(b.neighbours(va)) { + if let Some(e) = e { + text.push_str(&format!(" {name} [{}, {:#x} away]", one(e), e.start.abs_diff(va))); + } + } + text.push_str("; gone there, newest first:"); + for (e, gone) in b.gone_at(va, 12) { + text.push_str(&format!(" [{} gone at {:.1} s]", one(e), *gone as f64 / 1e3)); + } + text.push_str(&format!("; now {:.1} s, {} alive, {} gone", crate::host::now_ms() as f64 / 1e3, b.live.len(), b.gone.len())); + text + }); + { + let roots = ROOTS.lock().unwrap_or_else(|e| e.into_inner()); + let mut near: Vec<(u64, u64, u64)> = roots.iter().filter(|r| r.1 <= va && va - r.1 < 4 << 30).copied().collect(); + near.sort_by_key(|r| va - r.1); + near.dedup_by_key(|r| r.1); + for (at, gpu, bytes) in near.into_iter().take(4) { + text.push_str(&format!("; root descriptor {gpu:#x}+{bytes:#x} ({:#x} below) at {:.1} s", va - gpu, at as f64 / 1e3)); + } + } + // Every slot that reaches the address, and the nearest below it. + let mut reach: Vec<(u32, Names)> = Vec::new(); + let mut near: Vec<(u64, u32, Names)> = Vec::new(); + let mut at = 0; + let began = std::time::Instant::now(); + while let Some((first, bytes, end)) = crate::descriptor::host::shown_bytes(at, 16_384) { + for (i, d) in bytes.chunks_exact(32).enumerate() { + let slot = first + i as u32; + let names = decode(&d.try_into().unwrap_or([0; 32])); + let (base, len) = match names { + Names::Nothing => continue, + Names::Texture { base, meta, .. } => { + if meta.is_some_and(|m| va >= m && va - m < 32 << 20) { + reach.push((slot, names)); + } + let len = with(|b| { + b.holders(base) + .iter() + .map(|e| e.start + e.size - base) + .min() + .or_else(|| b.gone_at(base, 1).first().map(|(e, _)| e.start + e.size - base)) + }); + (base, len.unwrap_or(64 << 20) + (64 << 10)) + } + Names::Buffer { base, bytes, .. } => (base, bytes), + }; + if va >= base && va - base < len { + reach.push((slot, names)); + } else if va >= base && va - base < 4 << 30 { + near.push((va - base, slot, names)); + if near.len() > 4096 { + near.sort_by_key(|n| n.0); + near.truncate(16); + } + } + } + at = first + (bytes.len() / 32) as u32; + if at >= end || began.elapsed().as_secs() > 20 { + break; + } + } + text.push_str(&format!("; {} slots reach it (heap read in {:.1} s)", reach.len(), began.elapsed().as_secs_f64())); + for (slot, names) in reach.iter().take(24) { + let (Names::Texture { base, .. } | Names::Buffer { base, .. }) = *names else { continue }; + let fate = match fate(base) { + Fate::Alive => "alive".to_owned(), + Fate::Gone(text) => format!("GONE: {text}"), + Fate::Never => "never in the book".to_owned(), + }; + text.push_str(&format!("; slot {slot} {names:?} {fate} {}", crate::descriptor::host::slot_story(*slot))); + } + near.sort_by_key(|n| n.0); + for (away, slot, names) in near.iter().take(8) { + text.push_str(&format!("; near: slot {slot} {names:?} {away:#x} below {}", crate::descriptor::host::slot_story(*slot))); + } + text +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The two descriptors of the card that were read (a texture of 64x64 and + /// one of 2048x2048, RX 7900 XTX) and a raw buffer's. + #[test] + fn descriptors_are_read_as_the_card_has_them() { + let mut d = [0u8; 32]; + d[..16].copy_from_slice(&[0, 0xb4, 0, 2, 0, 0, 0xa0, 0xc2, 0x0f, 0xc0, 0x0f, 0, 0xac, 0x0f, 0x60, 0x91]); + assert_eq!(decode(&d), Names::Texture { base: 0x2_00b4_0000, meta: None, kind: 9, width: 64, height: 64 }); + d[..16].copy_from_slice(&[0, 0xb4, 2, 2, 0, 0, 0xa0, 0xc2, 0xff, 0xc1, 0xff, 1, 0xac, 0x0f, 0xb0, 0x91]); + assert_eq!(decode(&d), Names::Texture { base: 0x2_02b4_0000, meta: None, kind: 9, width: 2048, height: 2048 }); + d = [0; 32]; + assert_eq!(decode(&d), Names::Nothing); + d[..8].copy_from_slice(&0x1_2345_6780u64.to_le_bytes()); + d[8..12].copy_from_slice(&400u32.to_le_bytes()); + assert_eq!(decode(&d), Names::Buffer { base: 0x1_2345_6780, stride: 0, bytes: 400 }); + d[6] = 24; // a stride + assert_eq!(decode(&d), Names::Buffer { base: 0x1_2345_6780, stride: 24, bytes: 9600 }); + } + + /// Who has an address, and who had it, newest first. + #[test] + fn the_book_knows_what_is_gone() { + let mut b = Book::default(); + let block = b.add(1, 0x1000_0000, 64 << 20, "a block".into(), 5); + let one = b.add(2, 0x1000_0000, 0x8000, "one".into(), 6); + let two = b.add(3, 0x1000_8000, 0x8000, "two".into(), 7); + let names = |b: &Book, at| b.holders(at).iter().map(|e| e.what.clone()).collect::>(); + assert_eq!(names(&b, 0x1000_0100), ["one", "a block"]); + assert_eq!(names(&b, 0x1000_8100), ["two", "a block"]); + assert!(b.alive(0x1000_8100) && !b.alive(0x1000_0000 + (64 << 20)) && !b.alive(0xfff_ffff)); + assert!(names(&b, 0x1000_0000 + (64 << 20)).is_empty()); + b.remove(one, 2, 10); + b.remove(block, 1, 12); + assert!(names(&b, 0x1000_0100).is_empty()); + let gone: Vec<(String, u64)> = b.gone_at(0x1000_0100, 9).iter().map(|(e, at)| (e.what.clone(), *at)).collect(); + assert_eq!(gone, [("a block".to_owned(), 12), ("one".to_owned(), 10)]); + assert_eq!(b.neighbours(0x1000_0100)[1].map(|e| e.what.as_str()), Some("two")); + b.remove(two, 3, 13); + assert!(b.neighbours(u64::MAX - 1)[0].is_none() && b.by_object.is_empty()); + } +} diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 70483e4..2597d45 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -29,6 +29,9 @@ pub(crate) struct HostHeap { /// them are not null. raw: u32, twins: Vec, + /// When each slot was written last (with `crate::book`; else empty). + #[cfg(feature = "diagnostics")] + written: Vec, /// The record (view index and generation) each slot was last made from. made: Mutex>, /// The same for a slot whose descriptor is made and stays (else 0): what @@ -939,6 +942,76 @@ pub(crate) fn describe_slots(words: &[u32]) -> Vec<(usize, u32, String)> { .unwrap_or_default() } +/// For `crate::book`: the bytes of up to `n` descriptors of the view heap from +/// slot `at` on (from the first twin on, where `at` lies before it and past +/// the others), as the card's heap has them: the first slot, the bytes, and +/// the slot behind the last one worth reading. +#[cfg(feature = "diagnostics")] +pub(crate) fn shown_bytes(at: u32, n: u32) -> Option<(u32, Vec, u32)> { + super::with_view_heap(|host| { + let own = host.count + host.dynamic; + let end = if host.raw == 0 { own } else { host.raw + own }; + let at = if at >= own && at < host.raw { host.raw } else { at }; + let stop = if at < own { own } else { end }; + let n = n.min(stop.saturating_sub(at)); + if n == 0 || host.step != 32 { + return None; + } + let mut bytes = vec![0u8; n as usize * 32]; + crate::host::read_into(host.cpu(at).ptr as *const u8, &mut bytes).then_some((at, bytes, end)) + })? +} + +/// For `crate::book`: what our books say of a slot of the view heap. +#[cfg(feature = "diagnostics")] +pub(crate) fn slot_story(slot: u32) -> String { + use std::sync::atomic::Ordering::Relaxed; + use windows::core::Interface; + super::with_view_heap(|host| { + let (index, twin) = if host.raw != 0 && slot >= host.raw { (slot - host.raw, true) } else { (slot, false) }; + let mut text = if index < host.count { + format!("title slot {index}, made from {}", host.describe_slot(index).unwrap_or_default()) + } else { + let taken = host.next.lock().unwrap_or_else(|e| e.into_inner()).1.get((index - host.count) as usize).copied(); + format!("dynamic slot {} (taken {taken:?})", index - host.count) + }; + if twin { + let made = host.twins.get(index as usize).map(|t| t.load(Relaxed)); + text.push_str(&format!(", its raw twin (made {made:?})")); + } + if let Some(at) = host.written.get(slot as usize) { + text.push_str(&format!(", written last at {:.1} s", f64::from(at.load(Relaxed)) / 1e3)); + } + let kept = host.kept.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize).cloned().flatten(); + match kept { + None => text.push_str(", holds nothing"), + Some(resource) => { + // SAFETY: a resource the slot holds. + let d = unsafe { resource.GetDesc() }; + let gpu = if d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + // SAFETY: as above. + unsafe { resource.GetGPUVirtualAddress() } + } else { + 0 + }; + text.push_str(&format!( + ", holds {:#x}: dimension {} {}x{}x{} levels {} f{} at {gpu:#x}, {} references", + resource.as_raw() as usize, + d.Dimension.0, + d.Width, + d.Height, + d.DepthOrArraySize, + d.MipLevels, + d.Format.0, + crate::host::references(&resource) + )); + } + } + text + }) + .unwrap_or_default() +} + /// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for /// device-removed reports: a shader indexing a heap past its end faults. static GPU_RANGES: Mutex> = Mutex::new(Vec::new()); @@ -1167,6 +1240,10 @@ impl HostHeap { sampler, raw, twins: (0..if raw == 0 { 0 } else { count + extra }).map(|_| std::sync::atomic::AtomicBool::new(false)).collect(), + #[cfg(feature = "diagnostics")] + 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]), quick: (0..count).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(), copied: Mutex::new(Vec::new()), @@ -2292,6 +2369,10 @@ impl HostHeap { } fn copy_to(&self, to: u32, which: u32) { + #[cfg(feature = "diagnostics")] + if let Some(written) = self.written.get(to as usize) { + written.store(crate::host::now_ms() as u32, std::sync::atomic::Ordering::Relaxed); + } let (Some(from), Some(host)) = (staged(self.sampler, which), host()) else { return; // made in place }; diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 313e509..73c50d0 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -695,6 +695,8 @@ fn root_view(list: &HostList, address: u64, srv: bool) -> Option { let gpu = shadow.gpu(address); if srv || gpu % 256 == 0 { shadow.refresh(list, address, len); + #[cfg(feature = "diagnostics")] + crate::book::root(gpu, len); return Some(gpu); } let (gpu, to) = list.scratch(len)?; diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 60af779..a682657 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -269,6 +269,8 @@ fn sweep() { { return; } + #[cfg(feature = "diagnostics")] + crate::book::check(); crate::pool::room(host().and_then(|h| h.video_memory())); crate::pipeline::trim_library(); crate::shadow::let_go_idle(); @@ -619,10 +621,17 @@ pub(crate) fn fail(what: std::fmt::Arguments) -> ! { } } +static HOST: OnceLock> = OnceLock::new(); + +/// The host GPU if it is made already. +#[cfg(feature = "diagnostics")] +pub(crate) fn made_host() -> Option<&'static Host> { + HOST.get()?.as_ref() +} + /// The host GPU, created on first use; `None` without one (a run then /// behaves as before: nothing executes). pub(crate) fn host() -> Option<&'static Host> { - static HOST: OnceLock> = OnceLock::new(); HOST.get_or_init(|| match create() { Ok(host) => Some(host), Err(e) => { @@ -1520,6 +1529,18 @@ fn timing() -> bool { /// allocations a page fault hit (only with device-removed data on), or for /// the frame recorder (`VICTORY_RECORD`). pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) { + #[cfg(feature = "diagnostics")] + if crate::book::on() + && let Ok(resource) = object.cast::() + { + let text = text(); + crate::book::made(&resource, || text.clone()); + return name_it(object, || text); + } + name_it(object, text); +} + +fn name_it(object: &impl Interface, text: impl FnOnce() -> String) { #[cfg(feature = "diagnostics")] if crate::replay::record::on() { let text = text(); @@ -5341,6 +5362,8 @@ impl Host { } text.push_str(&crate::shadow::near(va)); text.push_str(&crate::descriptor::host::near_heaps(va)); + #[cfg(feature = "diagnostics")] + text.push_str(&crate::book::at_loss(va)); } // The plain output: the extended one (with marker texts) came // back without stopped lists on this host. @@ -7586,6 +7609,12 @@ impl Host { b.Map(0, None, Some(&mut data)) }) }; + #[cfg(feature = "diagnostics")] + if made.is_ok() + && let Some(b) = &buffer + { + crate::book::made(b, || "an upload buffer".into()); + } match made { Ok(()) => Some((buffer?, data.cast())), Err(e) => { @@ -8281,6 +8310,12 @@ impl Host { b.Map(0, None, Some(&mut data)) }) }; + #[cfg(feature = "diagnostics")] + if made.is_ok() + && let Some(b) = &buffer + { + crate::book::made(b, || "a shared buffer".into()); + } match made { Ok(()) => Some((buffer?, data.cast())), Err(e) => { @@ -8406,6 +8441,10 @@ impl Host { &mut buffer, ) }; + #[cfg(feature = "diagnostics")] + if let Some(b) = &buffer { + crate::book::made(b, || "an unordered access buffer".into()); + } match made { Ok(()) => buffer, Err(e) => { diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 6d96211..1e6c869 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -27,6 +27,8 @@ mod draw; pub mod dxgi; pub mod fence; pub mod frame; +#[cfg(all(windows, feature = "diagnostics"))] +mod book; #[cfg(windows)] mod host; #[cfg(windows)] diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index e3da7ac..7e84447 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -391,6 +391,11 @@ pub(crate) unsafe fn texture( (Ok(()), Some(made)) => { HELD.fetch_add(piece.len, Ordering::Relaxed); give_back_with(&made, piece); + #[cfg(feature = "diagnostics")] + { + crate::book::made(&made, || "a texture in a block".into()); + crate::book::block(&heap, &made, piece.start, BLOCK); + } Some(made) } _ => { From 96f2f32e845afa20406e98f94ce0d116059097b6 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 06:53:52 -0600 Subject: [PATCH 351/445] The threads a frame waits for are kept on the fast cores (VICTORY_FAST_CORES=0: not; 1: without the helpers) cpu_sets and keep_on_fast_cores are fxceless/victory-fork's (framelog.rs, commit 0b0074e0). Asked for by: submit, relay, late-wait, heap-sync, aside; and the helpers of the wide copies (refreshes, fills, snapshots) and of the landings. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/cores.rs | 98 ++++++++++++++++++++++++++ crates/victory-gpu/src/descriptor.rs | 1 + crates/victory-gpu/src/host.rs | 2 + crates/victory-gpu/src/host/aside.rs | 5 +- crates/victory-gpu/src/land.rs | 5 +- crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/queue/behind.rs | 1 + crates/victory-gpu/src/shadow.rs | 1 + 8 files changed, 113 insertions(+), 2 deletions(-) create mode 100644 crates/victory-gpu/src/cores.rs diff --git a/crates/victory-gpu/src/cores.rs b/crates/victory-gpu/src/cores.rs new file mode 100644 index 0000000..436f2f6 --- /dev/null +++ b/crates/victory-gpu/src/cores.rs @@ -0,0 +1,98 @@ +//! Which processors our own threads run on, where a processor has two kinds +//! of cores. `cpu_sets` and `keep_on_fast_cores` are fxceless/victory-fork's +//! (`framelog.rs`, commit 0b0074e0, GPL-3.0-or-later, as this). + +/// The system's processor sets of group 0: each one's id and its efficiency +/// class (higher is faster). +fn cpu_sets() -> Vec<(u32, u8)> { + use windows_sys::Win32::System::SystemInformation::{GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut bytes = 0u32; + // SAFETY: a size query, then the call into a buffer of that size. + unsafe { GetSystemCpuSetInformation(std::ptr::null_mut(), 0, &mut bytes, GetCurrentProcess(), 0) }; + let mut buffer = vec![0u64; (bytes as usize).div_ceil(8).max(1)]; + // SAFETY: as above; the buffer holds `bytes` bytes, aligned for the records. + let ok = unsafe { GetSystemCpuSetInformation(buffer.as_mut_ptr().cast(), bytes, &mut bytes, GetCurrentProcess(), 0) }; + let mut sets = Vec::new(); + let mut at = 0usize; + while ok != 0 && at + size_of::() <= bytes as usize { + // SAFETY: a record inside the buffer; each says its own size. + let info = unsafe { &*(buffer.as_ptr().cast::().add(at).cast::()) }; + if info.Size == 0 { + break; + } + // SAFETY: the record's type is CpuSet (the only one there is). + let set = unsafe { &info.Anonymous.CpuSet }; + if set.Group == 0 { + sets.push((set.Id, set.EfficiencyClass)); + } + at += info.Size as usize; + } + sets +} + +/// The sets of the fastest class, if there are slower ones too. +fn fast_of(sets: &[(u32, u8)]) -> Vec { + let best = sets.iter().map(|c| c.1).max().unwrap_or(0); + let fast: Vec = sets.iter().filter(|c| c.1 == best).map(|c| c.0).collect(); + if fast.len() == sets.len() { Vec::new() } else { fast } +} + +/// `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. +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)) +} + +/// Asks the system to run the calling thread, which a frame waits for, on +/// the fast cores only, where the processor has two kinds. That fork's submit +/// thread was found on a slow one in 1,529 looks of 24,021. (A selection of +/// processors is a preference the scheduler keeps unless nothing of it is +/// free.) The title's threads are not asked for. +pub(crate) fn keep_on_fast_cores(what: &str) { + ask(what, 1); +} + +/// [`keep_on_fast_cores`] for one of the threads a submission's preparing or +/// a landing shares its work with. +pub(crate) fn keep_helper_on_fast_cores(what: &str) { + ask(what, 2); +} + +fn ask(what: &str, from: u32) { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets}; + if stage() < from { + return; + } + static FAST: std::sync::OnceLock<(Vec, usize)> = std::sync::OnceLock::new(); + let (fast, of) = FAST.get_or_init(|| { + let sets = cpu_sets(); + (fast_of(&sets), sets.len()) + }); + // All alike (or nothing known): nothing to ask for. + if fast.is_empty() { + return; + } + // SAFETY: our own thread and a list of the system's own set ids. + let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), fast.as_ptr(), fast.len() as u32) }; + if ok == 0 { + tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept on the fast cores"); + } else { + tracing::info!(what, fast = fast.len(), of, "the thread is kept on the fast cores (VICTORY_FAST_CORES=0: not)"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_fast_cores_are_those_of_the_best_class_if_there_is_a_worse_one() { + assert_eq!(fast_of(&[(256, 1), (257, 1), (258, 0)]), [256, 257]); + assert!(fast_of(&[(256, 0), (257, 0)]).is_empty()); + assert!(fast_of(&[]).is_empty()); + assert!(!cpu_sets().is_empty()); + std::thread::spawn(|| keep_on_fast_cores("test")).join().unwrap(); + } +} diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 8395436..91f9f68 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -216,6 +216,7 @@ pub(crate) fn begin_sync_heaps() -> SyncedHeaps { static THREAD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); STARTED.call_once(|| { let made = std::thread::Builder::new().name("victory-heap-sync".into()).spawn(|| { + crate::cores::keep_on_fast_cores("victory-heap-sync"); let rounds = || SYNC_ROUNDS.0.lock().unwrap_or_else(|e| e.into_inner()); /// A round is over, however it ends. struct Over; diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 60af779..35bd7bd 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2833,6 +2833,7 @@ fn land() { /// value while the submitting thread waits for that thread would never /// see it. fn late_helper() { + crate::cores::keep_on_fast_cores("victory-late-wait"); let Some(host) = host() else { return; }; @@ -2963,6 +2964,7 @@ struct RelayFetch { /// anything a caller of [`Host::settle`] may hold: resetting the landed /// lists and looking at what queues hold are left to [`late_helper`]. fn relay_worker() { + crate::cores::keep_on_fast_cores("victory-relay"); let Some(host) = host() else { return; }; diff --git a/crates/victory-gpu/src/host/aside.rs b/crates/victory-gpu/src/host/aside.rs index 051debc..e466613 100644 --- a/crates/victory-gpu/src/host/aside.rs +++ b/crates/victory-gpu/src/host/aside.rs @@ -63,7 +63,10 @@ pub(crate) fn begin(work: impl FnOnce() -> Vec + Send + 'static) -> std let (send, jobs) = std::sync::mpsc::channel::(); std::thread::Builder::new() .name("victory-aside".into()) - .spawn(move || jobs.into_iter().for_each(|job| job())) + .spawn(move || { + crate::cores::keep_on_fast_cores("victory-aside"); + jobs.into_iter().for_each(|job| job()) + }) .ok() .map(|_| Mutex::new(send)) }); diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 34c359e..4d207f4 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -237,7 +237,10 @@ 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 || pool.help()); + let _ = std::thread::Builder::new().name(format!("victory-land-{i}")).spawn(move || { + crate::cores::keep_helper_on_fast_cores("victory-land"); + pool.help() + }); } pool } diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 6d96211..c875c5f 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(windows)] +mod cores; pub mod descriptor; pub mod device; #[cfg(windows)] diff --git a/crates/victory-gpu/src/queue/behind.rs b/crates/victory-gpu/src/queue/behind.rs index 8089997..69dbdd9 100644 --- a/crates/victory-gpu/src/queue/behind.rs +++ b/crates/victory-gpu/src/queue/behind.rs @@ -439,6 +439,7 @@ pub(super) fn on() -> bool { use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL}; // SAFETY: this thread's own priority. unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) }; + crate::cores::keep_on_fast_cores("victory-submit"); OURS.set(true); let ended = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| LANE.serve())); if ended.is_err() { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 0570916..abc75c1 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1453,6 +1453,7 @@ fn workers() -> &'static Workers { STARTED.call_once(|| { for i in 0..wide_threads() { let _ = std::thread::Builder::new().name(format!("victory-wide-{i}")).spawn(move || { + crate::cores::keep_helper_on_fast_cores("victory-wide"); let workers = WORKERS.get().expect("made above"); loop { let job = { From ef556e4218d42bbfef56e671a014c7cd451aa0ed Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 07:09:17 -0600 Subject: [PATCH 352/445] The crash report names direct mesh dispatches; buffers and groups stay inside what there is - The lists' notes for a lost device hold direct mesh dispatches too (pipeline, groups, user data): run n06c stopped among them. - A mesh dispatch of more than 65,535 groups is cut to that (more is undefined on the host; said once). Vertex and index buffer views end with the copy they show. - indirect::tests::loads_far_outside_views (a measurement): raw, typed, constant buffer and texture loads at the ends of 32 bits, uniform and per lane, samples at coordinates, levels and gradients that are no numbers: all 198 ways end inside their views on the RX 7900 XTX. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 15 +- crates/victory-gpu/src/host.rs | 7 +- crates/victory-gpu/src/host/indirects.rs | 39 ++++-- crates/victory-gpu/src/indirect.rs | 170 +++++++++++++++++++++++ 4 files changed, 217 insertions(+), 14 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 73c50d0..28b9a32 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1308,7 +1308,7 @@ impl State { shadow.refresh(list, v.address, u64::from(v.size)); *view = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: shadow.gpu(v.address), - SizeInBytes: v.size, + SizeInBytes: v.size.min(u32::try_from(shadow.left(v.address)).unwrap_or(u32::MAX)), StrideInBytes: v.stride, }; } @@ -1326,7 +1326,7 @@ impl State { shadow.refresh(list, v.address, u64::from(v.size)); let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: shadow.gpu(v.address), - SizeInBytes: v.size, + SizeInBytes: v.size.min(u32::try_from(shadow.left(v.address)).unwrap_or(u32::MAX)), Format: DXGI_FORMAT(v.format as i32), }; // SAFETY: an open list; the view names a live host buffer. @@ -2791,8 +2791,17 @@ impl State { #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("mesh {x}"), false)); self.mesh_scissor(list, true); + #[cfg(feature = "diagnostics")] + if let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) { + list.ran_indirect(p.pso.as_raw() as usize, &p.name, crate::host::indirects::DIRECT, x, &self.user); + } + // (The host takes 65,535 groups in a dimension: more is + // undefined there.) + if x > 65_535 { + once!(x, "a mesh dispatch of more groups than the host takes: cut"); + } // SAFETY: an open list with everything set. - unsafe { l6.DispatchMesh(x, 1, 1) }; + unsafe { l6.DispatchMesh(x.min(65_535), 1, 1) }; self.drew(crate::pipeline::host_pipeline(self.pipeline as This)); self.mesh_scissor(list, false); DRAWN.fetch_add(1, Ordering::Relaxed); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index a682657..d3cfac6 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -8505,15 +8505,18 @@ fn indirects_around(history: &[D3D12_AUTO_BREADCRUMB_OP], done: usize, all: &ind let all = all.lock().unwrap_or_else(|e| e.into_inner()); let mut text = String::new(); let mut shown = 0; + let mesh = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_DISPATCHMESH; for (at, op) in history.iter().enumerate().skip(done.saturating_sub(1)) { if shown == 4 || (at > done && *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER) { break; } - if !indirect(op) { + if !indirect(op) && !mesh(op) { continue; } shown += 1; - let Some((what, words)) = all.nth(indirects::before(history, at, indirect)) else { + let direct = mesh(op); + let nth = if direct { indirects::before(history, at, mesh) } else { indirects::before(history, at, indirect) }; + let Some((what, words)) = all.nth(nth, direct) else { continue; }; text.push_str(&format!("; command {at} ran {what}")); diff --git a/crates/victory-gpu/src/host/indirects.rs b/crates/victory-gpu/src/host/indirects.rs index cc34bff..282b008 100644 --- a/crates/victory-gpu/src/host/indirects.rs +++ b/crates/victory-gpu/src/host/indirects.rs @@ -14,6 +14,9 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; +/// The kind of a direct mesh dispatch. +pub(crate) const DIRECT: u32 = u32::MAX; + /// Words of user data kept of each execution. pub(crate) const WORDS: usize = 16; @@ -31,6 +34,8 @@ pub(crate) struct Ran { pub(crate) struct Indirects { names: HashMap, ran: Vec, + /// The direct mesh dispatches, likewise. + meshes: Vec, } /// A list's, shared with the report's table of lists. @@ -39,28 +44,40 @@ pub(crate) type Shared = Arc>; impl Indirects { /// An indirect execution of `kind` (the argument's type) of at most /// `count` records with `pipeline` (a host object) and user data. + /// A direct mesh dispatch of `count` groups is of kind [`DIRECT`]. pub(crate) fn note(&mut self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) { self.names.entry(pipeline).or_insert_with(|| name.to_owned()); let used = user.len().min(WORDS); let mut words = [0; WORDS]; words[..used].copy_from_slice(&user[..used]); - self.ran.push(Ran { pipeline, kind, count, words, used: used as u8 }); + let ran = Ran { pipeline, kind, count, words, used: used as u8 }; + if kind == DIRECT { + self.meshes.push(ran); + } else { + self.ran.push(ran); + } } pub(crate) fn clear(&mut self) { self.ran.clear(); + self.meshes.clear(); if self.names.len() > 512 { self.names.clear(); } } - /// The `nth` execution (from 0): its text and its user data. - pub(crate) fn nth(&self, nth: usize) -> Option<(String, &[u32])> { - let ran = self.ran.get(nth)?; + /// The `nth` execution (from 0), or direct mesh dispatch: its text and + /// its user data. + pub(crate) fn nth(&self, nth: usize, direct: bool) -> Option<(String, &[u32])> { + let ran = if direct { &self.meshes } else { &self.ran }.get(nth)?; let name = self.names.get(&ran.pipeline).map_or("a pipeline", String::as_str); let words = &ran.words[..usize::from(ran.used)]; Some(( - format!("{name} (indirect kind {} max {}, the list's indirect execution {nth}, user data {words:x?})", ran.kind, ran.count), + if direct { + format!("{name} (a mesh dispatch of {} groups, the list's {nth}, user data {words:x?})", ran.count) + } else { + format!("{name} (indirect kind {} max {}, the list's indirect execution {nth}, user data {words:x?})", ran.kind, ran.count) + }, words, )) } @@ -104,16 +121,20 @@ mod tests { let history = [6, 5, 15, 5, 5]; let nth = before(&history, 3, |op| *op == 5); assert_eq!(nth, 1); - let (text, words) = all.nth(nth).unwrap(); + let (text, words) = all.nth(nth, false).unwrap(); assert!(text.starts_with("[compute b] (indirect kind 2 max 1"), "{text}"); assert_eq!(words, [7; WORDS]); - let (text, words) = all.nth(2).unwrap(); + all.note(2, "[mesh b]", DIRECT, 9, &[1]); + let (text, _) = all.nth(0, true).unwrap(); + assert!(text.starts_with("[compute b] (a mesh dispatch of 9 groups"), "{text}"); + assert!(all.nth(1, true).is_none()); + let (text, words) = all.nth(2, false).unwrap(); assert!(text.starts_with("[compute a] (indirect kind 10 max 4"), "{text}"); assert!(words.is_empty()); - assert!(all.nth(3).is_none()); + assert!(all.nth(3, false).is_none()); assert_eq!(before(&history, 99, |op| *op == 5), 3); all.clear(); - assert!(all.nth(0).is_none()); + assert!(all.nth(0, false).is_none() && all.nth(0, true).is_none()); } /// A table's byte offset names the slots from it on; a small word that diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 237b7d8..5e4d335 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -1568,6 +1568,176 @@ void main(uint3 t : SV_DispatchThreadID) { println!("device: {:?}", unsafe { gpu.device.GetDeviceRemovedReason() }); } + /// Loads far outside their views (ignored: it may lose the device, and + /// says which way did): raw, typed, constant and texture loads at the + /// ends of 32 bits, uniform and per lane, and samples at coordinates, + /// levels and gradients that are no numbers. Each way is a submission of + /// its own. + #[test] + #[ignore] + fn loads_far_outside_views() { + let Some(mut gpu) = WarpHarness::on(std::env::var_os("VICTORY_BENCH_WARP").is_some()) else { + return; + }; + const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=4,b0), DescriptorTable(SRV(t0,numDescriptors=4),CBV(b1)), UAV(u0), StaticSampler(s0,filter=FILTER_MIN_MAG_MIP_LINEAR,addressU=TEXTURE_ADDRESS_WRAP,addressV=TEXTURE_ADDRESS_WRAP)" +cbuffer C : register(b0) { uint how; uint far; uint lane; uint out_at; } +ByteAddressBuffer raw : register(t0); +Buffer typed : register(t1); +Texture2D tex : register(t2); +struct Block { uint4 d[4096]; }; +ConstantBuffer block : register(b1); +SamplerState s : register(s0); +RWByteAddressBuffer o : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 t : SV_DispatchThreadID) { + uint at = far + t.x * lane * 4; + float4 c = 0; + if (how == 0) c = asfloat(raw.Load4(at)); + if (how == 1) c = asfloat(raw.Load(at + 4092)); + if (how == 2) c = typed.Load(at); + if (how == 3) c = asfloat(block.d[at]); + if (how == 4) c = tex.Load(int3(at, 0, 0)); + if (how == 5) c = tex.Load(int3(0, 0, at)); + if (how == 6) c = tex.SampleLevel(s, asfloat(uint2(at, at)), 0); + if (how == 7) c = tex.SampleLevel(s, float2(0.5, 0.5), asfloat(at)); + if (how == 8) c = tex.SampleGrad(s, float2(0.5, 0.5), asfloat(at).xx, asfloat(at).xx); + uint was; + o.InterlockedAdd(any(asuint(c) != 0) ? 4 : 0, 1, was); +} +"#; + let pass = compile_cs(&gpu.device, SOURCE).expect("the pass must compile"); + let (buffer, data, gpu_at) = gpu.shared_buffer(1 << 16); + // SAFETY: the mapping. + unsafe { std::ptr::write_bytes(data, 0x3f, 1 << 16) }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 7, + Format: DXGI_FORMAT(28), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + // SAFETY: plain creation; slots of our heap, live objects. + let (_texture, heap) = unsafe { + let mut made: Option = None; + gpu.device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + None, + &mut made, + ) + .unwrap(); + let texture = made.unwrap(); + let heap: ID3D12DescriptorHeap = gpu + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 5, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .unwrap(); + let step = gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let at = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: heap.GetCPUDescriptorHandleForHeapStart().ptr + i * step }; + for (i, format, count, flags) in + [(0, 39, 1024, D3D12_BUFFER_SRV_FLAG_RAW), (1, 2, 256, D3D12_BUFFER_SRV_FLAG_NONE)] + { + let view = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(format), + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { FirstElement: 0, NumElements: count, StructureByteStride: 0, Flags: flags }, + }, + }; + gpu.device.CreateShaderResourceView(&buffer, Some(&view), at(i)); + } + gpu.device.CreateShaderResourceView(&texture, None, at(2)); + gpu.device.CreateShaderResourceView(&texture, None, at(3)); + gpu.device.CreateConstantBufferView( + Some(&D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu_at, SizeInBytes: 4096 }), + at(4), + ); + (texture, heap) + }; + let names = [ + "raw, 4 dwords", + "raw, offset added", + "typed", + "constant buffer", + "texel", + "level of a texel", + "sample", + "level of a sample", + "gradients of a sample", + ]; + for (how, name) in names.iter().enumerate() { + for far in [ + 0u32, + 0x1000, + 0x7fff_fff0, + 0x8000_0000, + 0xffff_f000, + 0xffff_fff0, + 0xffff_fffc, + 0x7fc0_0000, + 0x7f80_0000, + 0xff80_0000, + 0x7f7f_ffff, + ] { + for lane in [0u32, 1] { + let (_out, out_ptr, out_gpu) = gpu.shared_buffer(1 << 12); + // SAFETY: the mapping; our open list, live objects. + unsafe { + std::ptr::write_bytes(out_ptr, 0, 1 << 12); + gpu.list.SetDescriptorHeaps(&[Some(heap.clone())]); + gpu.list.SetComputeRootSignature(&pass.root); + gpu.list.SetPipelineState(&pass.pso); + gpu.list.SetComputeRoot32BitConstants(0, 4, [how as u32, far, lane, 0].as_ptr().cast(), 0); + gpu.list.SetComputeRootDescriptorTable(1, heap.GetGPUDescriptorHandleForHeapStart()); + gpu.list.SetComputeRootUnorderedAccessView(2, out_gpu); + gpu.list.Dispatch(1, 1, 1); + // (Not `submit_and_wait`, which expects to go on.) + gpu.list.Close().unwrap(); + gpu.submitted += 1; + let cmd: ID3D12CommandList = gpu.list.cast().unwrap(); + gpu.queue.ExecuteCommandLists(&[Some(cmd)]); + let _ = gpu.queue.Signal(&gpu.fence, gpu.submitted); + let _ = gpu.fence.SetEventOnCompletion(gpu.submitted, gpu.event); + WaitForSingleObject(gpu.event, 8_000); + } + // SAFETY: the mapping; plain queries. + let (zeros, others, device) = unsafe { + ( + out_ptr.cast::().read_volatile(), + out_ptr.cast::().add(1).read_volatile(), + gpu.device.GetDeviceRemovedReason(), + ) + }; + println!( + "{name} at {far:#x}, lanes {lane}: zeros {zeros}, others {others}{}", + if device.is_ok() { "" } else { " DEVICE LOST" } + ); + if device.is_err() { + return; + } + // SAFETY: the card is done with them. + unsafe { + gpu.allocator.Reset().unwrap(); + gpu.list.Reset(&gpu.allocator, None).unwrap(); + } + } + } + } + } + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { From 9e30a46122920a02ba7aac26a4cad5c667f264af Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 07:19:34 -0600 Subject: [PATCH 353/445] Scripted keys can be held from one time to another Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/gameinput.rs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index bb5f26a..d0b0bf9 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1246,12 +1246,13 @@ mod host { } /// Debugging aid: `VICTORY_KEYS=:,...` holds each key for - /// 0.2 s that long after input starts, with or without focus. A key is a + /// 0.2 s that long after input starts (`-:`: all that + /// time), with or without focus. A key is a /// letter, a digit, or `Enter`, `Esc`, `Tab`, `Back`, `Up`, `Down`, /// `Left`, `Right` (the stand-in pad's table maps them to buttons). #[cfg(feature = "diagnostics")] fn scripted() -> Vec { - static SCRIPT: LazyLock<(Instant, Vec<(Duration, u8)>)> = LazyLock::new(|| { + static SCRIPT: LazyLock<(Instant, Vec<(Duration, Duration, u8)>)> = LazyLock::new(|| { let list = std::env::var("VICTORY_KEYS").unwrap_or_default(); let keys = list.split(',').filter_map(|entry| { let (at, key) = entry.split_once(':')?; @@ -1269,18 +1270,20 @@ mod host { } _ => return None, }; - Some(( - Duration::try_from_secs_f64(at.trim().parse().ok()?).ok()?, - vk, - )) + let time = |t: &str| Duration::try_from_secs_f64(t.trim().parse().ok()?).ok(); + let (from, to) = match at.split_once('-') { + Some((from, to)) => (time(from)?, time(to)?), + None => (time(at)?, time(at)? + Duration::from_millis(200)), + }; + Some((from, to, vk)) }); (Instant::now(), keys.collect()) }); let (start, keys) = &*SCRIPT; let now = start.elapsed(); keys.iter() - .filter(|&&(at, _)| (at..at + Duration::from_millis(200)).contains(&now)) - .map(|&(_, vk)| vk) + .filter(|&&(from, to, _)| (from..to).contains(&now)) + .map(|&(_, _, vk)| vk) .collect() } From a0b4909dfbbf3acee534a49bf76ae38ebb75ae81 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 07:21:55 -0600 Subject: [PATCH 354/445] Objects let go and lists that ran are kept about two frames longer (VICTORY_BURY_LAG=0: not) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 37 ++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index d3cfac6..1a8a432 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -71,7 +71,7 @@ unsafe impl Sync for Host {} /// releases reach the host at once, from its own threads, while the host /// runs a submission: freeing there is a GPU page fault on the freed /// texture (a device hang). -static RETIRED: Mutex> = Mutex::new(Vec::new()); +static RETIRED: Mutex> = Mutex::new(std::collections::VecDeque::new()); /// Submissions started and finished (waited for). static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -290,7 +290,7 @@ pub(crate) fn retire(object: T) { // (Those the title made and the host has not begun get the next numbers.) let queued = crate::queue::queued(); let started = STARTED.load(Ordering::Acquire) + queued; - if started <= FINISHED.load(Ordering::Acquire) { + if bury_lag() == 0 && started <= FINISHED.load(Ordering::Acquire) { RETIREMENTS[0].fetch_add(1, Ordering::Relaxed); drop(object); return; @@ -299,21 +299,32 @@ pub(crate) fn retire(object: T) { RETIRED .lock() .unwrap_or_else(|e| e.into_inner()) - .push((started, Retired(Box::new(object)))); + .push_back((started, Retired(Box::new(object)))); } -/// Drops what waited for submissions up to `finished`. +/// How many submissions later than it could (the last one that may use it +/// has finished) an object let go is dropped, and a host list that has run +/// is reset, about two frames: the device losses of the night of 2026-11-25 +/// were page faults in memory nothing of ours named any more, at no command +/// in particular. Objects let go while nothing runs wait as well: lists +/// recorded and not yet sent may name them. `VICTORY_BURY_LAG=0`: not. +fn bury_lag() -> u64 { + static LAG: OnceLock = OnceLock::new(); + *LAG.get_or_init(|| std::env::var("VICTORY_BURY_LAG").ok().and_then(|v| v.parse().ok()).unwrap_or(64)) +} + +/// Drops what waited for submissions up to `finished` ([`bury_lag`]). The +/// numbers come in order, but for threads that overtake each other: one of +/// those is dropped a little later than it could be. fn bury(finished: u64) { + let finished = finished.saturating_sub(bury_lag()); let done: Vec<(u64, Retired)> = { let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner()); - if retired.is_empty() { + let n = retired.iter().take_while(|(at, _)| *at <= finished).count(); + if n == 0 { return; } - let (done, keep) = std::mem::take(&mut *retired) - .into_iter() - .partition(|(at, _)| *at <= finished); - *retired = keep; - done + retired.drain(..n).collect() }; drop(done); } @@ -2842,7 +2853,11 @@ pub(crate) fn settle_for_fence() { /// Resets the host lists of settled flights and keeps them for reuse, as /// a queue does for the lists it ran (`crate::list::recycle`). fn land() { - let landed = std::mem::take(&mut line().landed); + let landed: Vec<_> = { + let mut line = line(); + let n = line.landed.len().saturating_sub(bury_lag() as usize); + line.landed.drain(..n).collect() + }; for (lists, order) in landed { crate::list::recycle(lists, &order); } From 0322b39abd5cd24747a71d360a42552ce86cab20 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 07:40:47 -0600 Subject: [PATCH 355/445] New memory is resident before anything names it (VICTORY_WAIT_RESIDENT=0: as before) Lists already on the card read our descriptor heaps as they are; only lists sent later wait for a new heap's mapping. Run n08's loss: a page fault in a texture made that instant, in a new block. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 60 ++++++++++++++++++++++++++++-- crates/victory-gpu/src/pool.rs | 8 +++- crates/victory-gpu/src/resource.rs | 18 +++++++-- 3 files changed, 77 insertions(+), 9 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index bae4a5b..b386f73 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -185,6 +185,54 @@ fn vram_idle_for(video_memory: Option<[u64; 4]>, keep: bool) -> u64 { } } +/// Whether new memory is made resident, and waited for, before anything can +/// name it (on by default; `VICTORY_WAIT_RESIDENT=0`: as before). A heap or +/// resource of the default kind is resident once it is made, but its +/// mapping into the card's address space is work of the system's that runs +/// later: only lists sent after it wait for it. Lists sent before run on, +/// and read our descriptor heaps as they are: a slot that shows a texture +/// in a new block is a page fault for them until the block is mapped. The +/// device losses of the night of 2026-11-25 were that (run n08: the fault +/// lay in a texture made in the same tenth of a second, in a new block). +fn wait_resident() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WAIT_RESIDENT").is_none_or(|v| v != "0")) +} + +/// The flag memory is made with that [`resident`] waits for. +pub(crate) fn not_resident() -> D3D12_HEAP_FLAGS { + if wait_resident() { D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT } else { D3D12_HEAP_FLAG_NONE } +} + +/// New memory (made with [`not_resident`]) is resident when this returns. +pub(crate) fn resident(device: &ID3D12Device, object: &impl Interface) -> windows::core::Result<()> { + if !wait_resident() { + return Ok(()); + } + let started = std::time::Instant::now(); + let object: ID3D12Pageable = object.cast()?; + // SAFETY: a live heap or resource of the device's. + let made = unsafe { device.MakeResident(&[Some(object)]) }; + let us = started.elapsed().as_micros() as u64; + RESIDENT[0].fetch_add(1, Ordering::Relaxed); + RESIDENT[1].fetch_add(us, Ordering::Relaxed); + RESIDENT[2].fetch_max(us, Ordering::Relaxed); + static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = RESIDENT[0].load(Ordering::Relaxed); + if n >= 1000 * (SAID.load(Ordering::Relaxed) + 1) { + SAID.store(n / 1000, Ordering::Relaxed); + tracing::info!( + "new memory waited for (VICTORY_WAIT_RESIDENT=0: not), since the start: {n} times, {:.1} ms, the longest {:.1} ms", + RESIDENT[1].load(Ordering::Relaxed) as f64 / 1000.0, + RESIDENT[2].load(Ordering::Relaxed) as f64 / 1000.0 + ); + } + made +} + +/// Times, microseconds and the longest of [`resident`]. +static RESIDENT: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + /// Whether memory the card was given stays with it while there is room (on /// by default; `VICTORY_KEEP_FREED=0`: it is given back as before). A shader /// that reads past a view (a raw load through a typed, structured or @@ -7615,7 +7663,7 @@ impl Host { self.device .CreateCommittedResource( &heap, - D3D12_HEAP_FLAG_NONE, + not_resident(), &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, @@ -7623,6 +7671,7 @@ impl Host { ) .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + resident(&self.device, b)?; b.Map(0, None, Some(&mut data)) }) }; @@ -8316,7 +8365,7 @@ impl Host { self.device .CreateCommittedResource( &heap, - D3D12_HEAP_FLAG_NONE, + not_resident(), &desc, D3D12_RESOURCE_STATE_COMMON, None, @@ -8324,6 +8373,7 @@ impl Host { ) .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + resident(&self.device, b)?; b.Map(0, None, Some(&mut data)) }) }; @@ -8403,7 +8453,7 @@ impl Host { self.device .CreateCommittedResource( &heap, - D3D12_HEAP_FLAG_NONE, + not_resident(), &desc, D3D12_RESOURCE_STATE_COMMON, None, @@ -8411,6 +8461,7 @@ impl Host { ) .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + resident(&self.device, b)?; b.Map(0, None, Some(&mut data)) }) }; @@ -8451,7 +8502,7 @@ impl Host { let made = unsafe { self.device.CreateCommittedResource( &heap, - D3D12_HEAP_FLAG_NONE, + not_resident(), &desc, D3D12_RESOURCE_STATE_COMMON, None, @@ -8462,6 +8513,7 @@ impl Host { if let Some(b) = &buffer { crate::book::made(b, || "an unordered access buffer".into()); } + let made = made.and_then(|()| buffer.as_ref().map_or(Ok(()), |b| resident(&self.device, b))); match made { Ok(()) => buffer, Err(e) => { diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index 7e84447..f8a8301 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -374,13 +374,19 @@ pub(crate) unsafe fn texture( SizeInBytes: BLOCK, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, - Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES | crate::host::not_resident(), }; let mut heap: Option = None; // SAFETY: plain creation. if let Err(e) = unsafe { device.CreateHeap(&desc, &mut heap) } { tracing::warn!(error = %e, "no block of texture memory"); } + if let Some(h) = &heap + && let Err(e) = crate::host::resident(device, h) + { + tracing::warn!(error = %e, "a block of texture memory is not resident"); + return None; + } heap })?; let mut made: Option = None; diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index c524ba1..564edd4 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -495,7 +495,7 @@ fn twin_texture( let made = unsafe { host.device.CreateCommittedResource( &heap, - D3D12_HEAP_FLAG_NONE, + crate::host::not_resident(), (&raw const d).cast(), D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32), None, @@ -509,6 +509,7 @@ fn twin_texture( TWINS[1].fetch_add(1, Relaxed); return None; }; + let _ = crate::host::resident(&host.device, &texture); crate::host::name(&texture, || { format!("depth twin {}x{} f{}", d.width, d.height, d.format) }); @@ -558,7 +559,7 @@ fn twin_texture( let made = unsafe { host.device.CreateCommittedResource( &heap, - D3D12_HEAP_FLAG_NONE, + crate::host::not_resident(), (&raw const d).cast(), D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32), None, @@ -569,6 +570,7 @@ fn twin_texture( tracing::warn!(error = %e, desc = ?d, "no twin for a depth plane"); } texture.map(|texture| { + let _ = crate::host::resident(&host.device, &texture); crate::host::name(&texture, || { format!("depth plane twin {}x{} f{}", d.width, d.height, d.format) }); @@ -2491,7 +2493,7 @@ fn host_texture_as( unsafe { host.device.CreateCommittedResource( &heap, - D3D12_HEAP_FLAG_NONE, + crate::host::not_resident(), (&raw const d).cast(), D3D12_RESOURCE_STATES( crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, @@ -2502,9 +2504,17 @@ fn host_texture_as( ) } }; - if let Err(e) = made { + if let Err(e) = &made { tracing::warn!(error = %e, desc = ?d, reserved, "no host texture"); } + if !reserved + && made.is_ok() + && let Some(t) = &texture + && let Err(e) = crate::host::resident(&host.device, t) + { + tracing::warn!(error = %e, desc = ?d, "a host texture is not resident"); + texture = None; + } if let Some(t) = &texture { crate::host::name(t, || { format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags) From 336f613986e4833981831fd7463857fb0e539151 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:48:39 -0600 Subject: [PATCH 356/445] A timeline of a few frames, with the chain each present came out of (VICTORY_TIMELINE) Diagnostics only. VICTORY_TIMELINE= records three frames (or VICTORY_TIMELINE_FRAMES) after VICTORY_TIMELINE_AT seconds and writes a Chrome trace and a text summary: spans of our work, the waits and wake-ups of the title's threads (its imports) and of ours (our import table), long kernel calls on the address space, and when each submission ran on the card. The summary walks back from each present through who waited on whom. Nothing is wrapped without the variable. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 008de5f9ffcef132079b1af8b7f4f1c22235cee9) --- crates/victory-gpu/Cargo.toml | 2 +- crates/victory-gpu/src/ab.rs | 122 +++ crates/victory-gpu/src/copystat.rs | 4 +- crates/victory-gpu/src/descriptor.rs | 2 + crates/victory-gpu/src/draw.rs | 3 + crates/victory-gpu/src/fence.rs | 14 +- crates/victory-gpu/src/frame.rs | 1 + crates/victory-gpu/src/host.rs | 78 ++ crates/victory-gpu/src/host/aside.rs | 2 + crates/victory-gpu/src/host/stamps.rs | 187 ++++ crates/victory-gpu/src/land.rs | 3 + crates/victory-gpu/src/lib.rs | 3 + crates/victory-gpu/src/list.rs | 2 + crates/victory-gpu/src/queue.rs | 30 + crates/victory-gpu/src/queue/behind.rs | 30 +- crates/victory-gpu/src/shadow.rs | 2 + crates/victory-gpu/src/texture.rs | 1 + crates/victory-gpu/src/timeline.rs | 57 ++ crates/victory-gpu/src/timeline/hooks.rs | 322 +++++++ crates/victory-gpu/src/timeline/record.rs | 678 +++++++++++++++ crates/victory-gpu/src/timeline/report.rs | 957 +++++++++++++++++++++ crates/victory-gpu/src/watch.rs | 1 + crates/victory-hle/src/host.rs | 8 +- crates/victory-hle/src/modules/dstorage.rs | 3 + crates/victory-hle/src/modules/xmem.rs | 1 + 25 files changed, 2506 insertions(+), 7 deletions(-) create mode 100644 crates/victory-gpu/src/ab.rs create mode 100644 crates/victory-gpu/src/host/stamps.rs create mode 100644 crates/victory-gpu/src/timeline.rs create mode 100644 crates/victory-gpu/src/timeline/hooks.rs create mode 100644 crates/victory-gpu/src/timeline/record.rs create mode 100644 crates/victory-gpu/src/timeline/report.rs diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index cba972b..858802a 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_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"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D_Fxc", diff --git a/crates/victory-gpu/src/ab.rs b/crates/victory-gpu/src/ab.rs new file mode 100644 index 0000000..1edc162 --- /dev/null +++ b/crates/victory-gpu/src/ab.rs @@ -0,0 +1,122 @@ +//! Diagnostics: switches that change while the title runs, so that one run +//! measures both sides in the same scene. `VICTORY_AB=,[,..]`: +//! every so many seconds, at a present, the next phase begins; switch number +//! n is on in the phases whose number has bit n, so that all combinations +//! come one after another, again and again. Each phase's frame times are +//! logged at its end (the frames of its first second left out). A switch +//! named here does not go by its own variable any more. + +use std::sync::atomic::{AtomicU32, Ordering::Relaxed}; +use std::sync::{Mutex, OnceLock}; + +struct Asked { + seconds: f64, + switches: Vec, +} + +fn parse(text: &str) -> Option { + let mut parts = text.split(',').map(str::trim); + let seconds = parts.next()?.parse::().ok().filter(|s| *s > 1.0)?; + let switches: Vec = parts.filter(|s| !s.is_empty()).map(str::to_string).collect(); + (!switches.is_empty() && switches.len() <= 8).then_some(Asked { seconds, switches }) +} + +fn asked() -> Option<&'static Asked> { + static ASKED: OnceLock> = OnceLock::new(); + ASKED.get_or_init(|| parse(&std::env::var("VICTORY_AB").ok()?)).as_ref() +} + +/// The switches that are on now, a bit each. +static BITS: AtomicU32 = AtomicU32::new(0); + +/// Whether `switch` is on now, if it is one of those that change. +pub(crate) fn pick(switch: &str) -> Option { + let n = asked()?.switches.iter().position(|s| s == switch)?; + Some(BITS.load(Relaxed) >> n & 1 != 0) +} + +/// What the run has seen of the phase under way. +struct Phase { + started: std::time::Instant, + number: u64, + began: std::time::Instant, + last: std::time::Instant, + drawn: u64, + frames: Vec, + draws: u64, +} + +/// The frames' mean, median and nine tenths. +fn summary(frames: &mut [f32]) -> (f32, f32, f32) { + if frames.is_empty() { + return (0.0, 0.0, 0.0); + } + let mean = frames.iter().sum::() / frames.len() as f32; + frames.sort_by(f32::total_cmp); + (mean, frames[frames.len() / 2], frames[frames.len() * 9 / 10]) +} + +/// The title's present ends on this thread. `change`: called when another +/// phase begins, before any switch changes, with what `switch` is and what it +/// will be. +pub(crate) fn presented(change: impl Fn(&str, bool, bool)) { + let Some(asked) = asked() else { + return; + }; + static PHASE: Mutex> = Mutex::new(None); + let now = std::time::Instant::now(); + let drawn = crate::draw::drawn(); + let mut phase = PHASE.lock().unwrap_or_else(|e| e.into_inner()); + let p = phase.get_or_insert_with(|| Phase { + started: now, + number: 0, + began: now, + last: now, + drawn, + frames: Vec::new(), + draws: 0, + }); + if (now - p.began).as_secs_f64() > 1.0 { + p.frames.push((now - p.last).as_secs_f32() * 1000.0); + p.draws += drawn.saturating_sub(p.drawn); + } + (p.last, p.drawn) = (now, drawn); + let number = ((now - p.started).as_secs_f64() / asked.seconds) as u64; + if number == p.number { + return; + } + let bits = |number: u64| (number % (1 << asked.switches.len())) as u32; + let (was, will) = (bits(p.number), bits(number)); + let (mean, median, most) = summary(&mut p.frames); + let on: Vec<&str> = asked.switches.iter().enumerate().filter(|(n, _)| was >> n & 1 != 0).map(|(_, s)| s.as_str()).collect(); + tracing::info!( + "A/B phase {} bits {was} on [{}]: {} frames, mean {mean:.1} ms, median {median:.1}, p90 {most:.1}, {:.0} draws a frame", + p.number, + on.join(" "), + p.frames.len(), + p.draws as f64 / p.frames.len().max(1) as f64 + ); + for (n, switch) in asked.switches.iter().enumerate() { + change(switch, was >> n & 1 != 0, will >> n & 1 != 0); + } + BITS.store(will, Relaxed); + (p.number, p.began, p.draws) = (number, now, 0); + p.frames.clear(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn switches_and_seconds_are_read_and_frames_summed_up() { + let a = parse("10, VICTORY_A,VICTORY_B").unwrap(); + assert_eq!((a.seconds, a.switches), (10.0, vec!["VICTORY_A".to_string(), "VICTORY_B".to_string()])); + assert!(parse("10").is_none()); + assert!(parse("x,VICTORY_A").is_none()); + assert!(parse("0,VICTORY_A").is_none()); + assert_eq!(summary(&mut [30.0, 10.0, 20.0]), (20.0, 20.0, 30.0)); + assert_eq!(summary(&mut []), (0.0, 0.0, 0.0)); + assert_eq!(pick("VICTORY_NONE_SUCH"), None); + } +} diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index c43d1af..aebd018 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -981,7 +981,9 @@ fn submitter(all: &mut Vec<(u32, Submitter)>, id: u32) -> &mut Submitter { /// A list call on this thread that began at `started` has returned. pub(crate) fn recorded(started: std::time::Instant) { - let ns = started.elapsed().as_nanos() as u64; + let took = started.elapsed(); + let ns = took.as_nanos() as u64; + crate::timeline::called(took); add(C::RecordCalls, 1); add(C::RecordNs, ns); if !RECORDED_SINCE.load(Relaxed) && !RECORDED_SINCE.swap(true, Relaxed) { diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 91f9f68..2e0c3a6 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -249,6 +249,8 @@ pub(crate) fn begin_sync_heaps() -> SyncedHeaps { last = std::time::Instant::now(); Over }); + let _round = + crate::timeline::span(if asked { "the heaps' records, for a submission" } else { "the heaps' records, early" }); let _ = std::panic::catch_unwind(sync_heaps); } }); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 28b9a32..f082efe 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1846,6 +1846,7 @@ impl State { return Some(gpu); } let started = std::time::Instant::now(); + let mut stage = crate::timeline::span("the heap pass: begun, or done here"); if crate::host::aside::on() { let at = std::ptr::from_ref(heap) as usize; list.refreshes_coming(move || { @@ -1860,7 +1861,9 @@ impl State { } #[cfg(feature = "diagnostics")] let refreshed = std::time::Instant::now(); + stage.next("the heap pass: textures"); self.heap_textures(list, heap, host); + stage.end(); #[cfg(feature = "diagnostics")] HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed); HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index d3103b0..10a9e93 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -85,6 +85,13 @@ extern "system" fn release(this: This) -> u32 { pub(crate) extern "system" fn completed(this: This) -> u64 { fence(this).value.load(Ordering::Acquire) } +/// The title's `GetCompletedValue`. +extern "system" fn completed_called(this: This) -> u64 { + let value = completed(this); + #[cfg(all(windows, feature = "diagnostics"))] + crate::timeline::polled(this as usize, value); + value +} extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT { let fence = fence(this); let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); @@ -94,6 +101,8 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c } return S_OK; } + #[cfg(all(windows, feature = "diagnostics"))] + crate::timeline::told("an event asked for", this as usize, value); if event.is_null() { // With submissions sent to the card and not waited for // (`crate::host::late`) the signal may be behind them: they are @@ -120,6 +129,8 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c /// Moves the fence to `value` and sets the events that waited for it. pub(crate) fn set(this: This, value: u64) { let fence = fence(this); + #[cfg(all(windows, feature = "diagnostics"))] + crate::timeline::told("a fence set", this as usize, value); let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); fence.value.store(value, Ordering::Release); waiters.retain(|&(wanted, event)| { @@ -131,6 +142,7 @@ pub(crate) fn set(this: This, value: u64) { }); } pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { + let _called = crate::timeline::span("a fence set"); set(this, value); // A queue may have waited for it: what it held runs now. #[cfg(windows)] @@ -153,7 +165,7 @@ static FUNCTIONS: Table<24> = { f[0] = query as *const (); f[2] = release as *const (); f[7] = object::parent_device as *const (); // 0x38 - f[8] = completed as *const (); // 0x40 + f[8] = completed_called as *const (); // 0x40 f[9] = set_event_on_completion as *const (); // 0x48 f[10] = signal as *const (); // 0x50 f[11] = creation_flags as *const (); // 0x58 diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index e9da52c..8bf432f 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -148,6 +148,7 @@ pub(crate) extern "system" fn wait( tick -= 1; wait = Duration::ZERO; } + let _called = crate::timeline::span("the title's frame wait"); let hr = if wait > limit { std::thread::sleep(limit); TIMEOUT diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index bae4a5b..27c440e 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2894,7 +2894,9 @@ fn late_helper() { } }; let Some(target) = target else { + let mut helping = crate::timeline::span("helper: landed lists reset and given back"); land(); + helping.next("helper: looking at what queues hold"); crate::queue::release_held(false); continue; }; @@ -2903,6 +2905,8 @@ fn late_helper() { // SAFETY: our fence and event. unsafe { if host.fence.SetEventOnCompletion(target, event).is_ok() { + #[cfg(feature = "diagnostics")] + let _card = crate::timeline::card_wait(Some(target)); WaitForSingleObject(event, INFINITE); } } @@ -2960,6 +2964,15 @@ fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) { LATE_STATS[why].fetch_add(1, Ordering::Relaxed); let was_working = working(false); let waiting = std::time::Instant::now(); + let _waiting = crate::timeline::span(match why { + WHY_SYNC => "waiting for landings: everything (a present, the sweep)", + WHY_VALUE => "waiting for landings: a memory value", + WHY_STALE => "waiting for landings: title memory changed under shader writes", + WHY_READ => "waiting for landings: title memory read", + WHY_MOST => "waiting for landings: lists in the air", + WHY_FENCE => "waiting for landings: a blocking fence wait", + _ => "waiting for landings: another reason", + }); while !done(&line) { line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner()); } @@ -3051,6 +3064,8 @@ fn relay_worker() { Ok(items) => host.relay_land(items, &mut fetch), Err(target) => { let waiting = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + let _card = crate::timeline::card_wait(Some(target)); // SAFETY: the host's fence and this thread's event. let waited = unsafe { host.fence.SetEventOnCompletion(target, event).map(|()| { @@ -3281,6 +3296,10 @@ pub(crate) use send::{goes_as_words, words_under}; pub(crate) mod spans; mod torn; pub(crate) mod upcheck; +#[cfg(feature = "diagnostics")] +mod stamps; +#[cfg(feature = "diagnostics")] +pub(crate) use stamps::{timeline_ready, timeline_restart, timeline_stamps}; #[cfg(test)] mod late_tests { @@ -4300,11 +4319,14 @@ impl Host { } list.Close()?; let lists = [Some(list.cast::()?)]; + let _fetching = crate::timeline::span("landing: fetching pieces"); if let Some(queue) = ©_queue { queue.ExecuteCommandLists(&lists); queue.Signal(&fence, sent)?; meanwhile(); fence.SetEventOnCompletion(sent, event)?; + #[cfg(feature = "diagnostics")] + let _card = crate::timeline::card_wait(None); WaitForSingleObject(event, INFINITE); return Ok(behind); } @@ -4318,6 +4340,8 @@ impl Host { self.queue.Signal(&fence, sent)?; meanwhile(); fence.SetEventOnCompletion(sent, event)?; + #[cfg(feature = "diagnostics")] + let _card = crate::timeline::card_wait(None); WaitForSingleObject(event, INFINITE); Ok(after) })() @@ -4336,6 +4360,7 @@ impl Host { CARD_STATS[6].fetch_add(us, Ordering::Relaxed); } let merging = std::time::Instant::now(); + let _merging = crate::timeline::span("landing: merging fetched pieces"); let mut written = 0; if land::on() { let titles: Vec<(usize, usize)> = @@ -4404,6 +4429,7 @@ impl Host { /// is complete before the title is told anything. fn relay_land(&self, items: Vec, fetch: &mut Option) { let landing = std::time::Instant::now(); + let mut stage = crate::timeline::span("landing: what is to be looked through"); { let flights: Vec<&Flight> = items .iter() @@ -4436,12 +4462,16 @@ impl Host { } } let mut hand_back = relay_hand_back(&back); + stage.next("landing: copies in the card's memory"); self.relay_card_back(&plans, fetch, &mut || { if crate::land::on() { + let _looking = crate::timeline::span("landing: looking through copies, beside the fetch"); hand_back.look(crate::land::stat::SCAN_BESIDE); } }); + stage.next("landing: copies in the PC's memory"); hand_back.merge(); + stage.next("landing: ranges done with"); let finishing = std::time::Instant::now(); // Only now, and flight by flight: a range another flight // in the air declared too stays closed to refreshes. @@ -4457,6 +4487,7 @@ impl Host { } } // In the order given: what tells the title the card is done. + stage.next("landing: read-backs, telling the title"); let mut last = 0; let mut landed = Vec::new(); let mut telling = std::time::Instant::now(); @@ -4490,6 +4521,7 @@ impl Host { FINISHED.store(last, Ordering::Release); bury(last); } + stage.next("landing: the rest"); self.log_messages(); crate::land::spent(crate::land::stat::REST, telling); RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); @@ -4726,6 +4758,7 @@ impl Host { LINE_MOVED.notify_one(); } drop(submitted); + let _landing = crate::timeline::span("landed lists reset and given back"); land(); } @@ -4791,6 +4824,7 @@ impl Host { return; } let was_working = working(true); + let _settling = crate::timeline::span("settling flights"); let mut counted = false; loop { let items = { @@ -4820,6 +4854,8 @@ impl Host { match self.fence.SetEventOnCompletion(*submitted, self.event) { Ok(()) => { working(false); + #[cfg(feature = "diagnostics")] + let _card = crate::timeline::card_wait(Some(*submitted)); WaitForSingleObject(self.event, INFINITE); stood(waiting); working(true); @@ -4962,6 +4998,7 @@ impl Host { crate::copystat::submission_begins(); // One submission at a time from preparation to copy-back: snapshots // and the ranges shaders write are per host copy, not per submission. + let mut stage = crate::timeline::span("submit: the submission lock"); let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); let was_working = working(true); submitting(1, runs.len()); @@ -4969,6 +5006,7 @@ impl Host { let ahead = Split::begin(); #[cfg(feature = "diagnostics")] SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed); + stage.next("submit: steps given to the card"); // Flights in the air ([`late`]): a submission that is waited for // settles them first, one sent ahead only if preparing it reads // what they write. @@ -4976,6 +5014,7 @@ impl Host { let own = if late { self.card_steps(runs) } else { None }; #[cfg(feature = "diagnostics")] ahead.part(12); + stage.next("submit: waiting for flights it reads from"); if !late { self.settle(&mut submitted, WHY_SYNC); } else if own.is_none() @@ -5005,6 +5044,7 @@ impl Host { } None => runs, }; + stage.next("submit: the sweep"); let behind = late && flying(); // Before this submission counts as started: what the sweep lets go // of is named by no list, and nothing runs now (behind flights the @@ -5028,6 +5068,7 @@ impl Host { SWEPT.store(now_ms(), Ordering::Relaxed); } let behind = late && flying(); + stage.next("submit: gathering what to ask about"); let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1; // The ranges shaders write are counted for it (with the relay). crate::shadow::preparing(this_submission); @@ -5067,9 +5108,11 @@ impl Host { let ranges: Vec<(usize, usize)> = spans.into_values().collect(); #[cfg(feature = "diagnostics")] SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed); + stage.next("submit: asking the write watch"); crate::watch::ask_once(&ranges); #[cfg(feature = "diagnostics")] split.part(0); + stage.next("submit: title bytes under flights' writes"); // Behind flights: the title wrote memory that a flight's shaders // may write too, and this submission refreshes it. The flights // are settled, and the asking made again: the copy-back wrote @@ -5095,9 +5138,11 @@ impl Host { split.part(1); // What flights in the air may write. let air = line().written.clone(); + stage.next("submit: refreshes ahead of writes"); 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"); for list in runs { list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i))); firsts.push(lists.len()); @@ -5107,10 +5152,12 @@ impl Host { lists.push(list.list.cast().ok()); } batch.fill(); + stage.next("submit: the last refreshes"); batch.flush(); crate::watch::ask_once_end(); #[cfg(feature = "diagnostics")] split.part(2); + stage.next("submit: snapshots"); // The snapshots of the ranges shaders may write, if they were left // for now (`crate::shadow::wide_back`): the refreshes are done, the // lists have not gone to the card. @@ -5123,6 +5170,7 @@ impl Host { } #[cfg(feature = "diagnostics")] split.part(3); + stage.next("submit: copies in the card's memory"); // Copies in the card's memory: what changed on their CPU side goes // up ahead of the lists, and a compare of what the shaders may // write follows them in the same submission. @@ -5149,6 +5197,7 @@ impl Host { } #[cfg(feature = "diagnostics")] split.part(4); + stage.next("submit: waiting for the heaps' records"); drop(heaps_synced); // The slots that waited for a texture's host copy, before the // lists that may read them run. @@ -5156,6 +5205,18 @@ impl Host { #[cfg(feature = "diagnostics")] split.part(15); let prepared = std::time::Instant::now(); + stage.next("submit: sending"); + // When it runs on the card, for the timeline. + #[cfg(feature = "diagnostics")] + let stamp = stamps::take(); + #[cfg(feature = "diagnostics")] + if let Some((ahead, behind)) = stamp.and_then(stamps::lists) { + lists.insert(0, Some(ahead)); + lists.push(Some(behind)); + firsts.iter_mut().for_each(|first| *first += 1); + } + #[cfg(feature = "diagnostics")] + let sending = crate::timeline::ticks(); if late { *submitted += 1; #[cfg(feature = "diagnostics")] @@ -5169,7 +5230,10 @@ impl Host { self.queue.Signal(&self.fence, *submitted) }; awake::sent(&self.device); + #[cfg(feature = "diagnostics")] + crate::timeline::sent(sending, *submitted, stamp); self.card_sent(); + stage.next("submit: noting what is in the air"); if let Err(e) = signalled { fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); } @@ -5216,9 +5280,13 @@ impl Host { .queue .Signal(&self.fence, *submitted) .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)); + #[cfg(feature = "diagnostics")] + crate::timeline::sent(sending, *submitted, stamp); match waited { Ok(()) => { working(false); + #[cfg(feature = "diagnostics")] + let _card = crate::timeline::card_wait(Some(*submitted)); WaitForSingleObject(self.event, INFINITE); stood(started); working(true); @@ -5285,6 +5353,7 @@ impl Host { )); } submitting(3, runs.len()); + stage.next("submit: copying back"); // What shaders wrote goes back before the bottom-of-pipe writes, // which tell the title the GPU is done; each range once per // submission, however many dispatches declared it (the world's @@ -5633,6 +5702,7 @@ impl HostList { } pub(crate) fn close(&self) { + let _closing = crate::timeline::span("closing a host list"); self.twins_to_depth(); let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone(); if let Some((scratch, _)) = scratch { @@ -5685,6 +5755,7 @@ impl HostList { pub(crate) fn reset(&self) { #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); + let _resetting = crate::timeline::span("resetting a host list"); self._alive.used(); *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = None; *self.deferred() = Deferred::default(); @@ -6622,6 +6693,7 @@ impl HostList { if matches!(step, Step::Run(_)) { batch.title_written(); } + let _step = crate::timeline::span("a step of ours"); work(); // It wrote title memory, where is not known here: the // submission's one asking ends, later refreshes ask anew. @@ -7052,6 +7124,7 @@ impl Batch { /// Brings `[from, to)` of a copy up to date, timed. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) { let started = std::time::Instant::now(); + let _one = crate::timeline::span("a copy's refresh"); let copied = shadow.update(from, to - from); let us = started.elapsed().as_micros() as u64; #[cfg(feature = "diagnostics")] @@ -7155,6 +7228,7 @@ impl Batch { self.due.drain(..).for_each(|staging| staging.refresh()); return; } + let _textures = crate::timeline::span("textures brought up to date"); // The time counted is the time it took, not the threads' sum. let started = std::time::Instant::now(); let before = PREPARING[2].load(Ordering::Relaxed); @@ -7172,6 +7246,7 @@ impl Batch { } #[cfg(feature = "diagnostics")] let (began, all) = (std::time::Instant::now(), self.refreshes.len()); + let _flush = crate::timeline::span("refreshes of copies"); self.flush_all(); #[cfg(feature = "diagnostics")] { @@ -8095,8 +8170,11 @@ impl Host { } #[cfg(feature = "diagnostics")] crate::replay::record::present(texture, state); + let mut showing = crate::timeline::span("the host's Present"); let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + showing.next("the frame meter"); p.meter.frame(p.hwnd); + showing.end(); #[cfg(feature = "diagnostics")] return Some(probe.is_some_and(|b| crate::capture::black(&b))); #[cfg(not(feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/host/aside.rs b/crates/victory-gpu/src/host/aside.rs index e466613..b46cf61 100644 --- a/crates/victory-gpu/src/host/aside.rs +++ b/crates/victory-gpu/src/host/aside.rs @@ -25,6 +25,7 @@ impl Coming { /// What was found. pub(crate) fn wait(&self) -> Vec { let began = std::time::Instant::now(); + let _waiting = crate::timeline::span("a list's close waits for the heap's views"); let mut found = self.0.lock().unwrap_or_else(|e| e.into_inner()); loop { if let Some(found) = found.take() { @@ -56,6 +57,7 @@ pub(crate) fn begin(work: impl FnOnce() -> Vec + Send + 'static) -> std let told = coming.clone(); let job: Job = Box::new(move || { // (However it ends, the list that waits goes on.) + let _aside = crate::timeline::span("beside: the heap's views"); let found = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)).unwrap_or_default(); told.found(found); }); diff --git a/crates/victory-gpu/src/host/stamps.rs b/crates/victory-gpu/src/host/stamps.rs new file mode 100644 index 0000000..6abbcfb --- /dev/null +++ b/crates/victory-gpu/src/host/stamps.rs @@ -0,0 +1,187 @@ +//! Diagnostics: when each submission began and ended on the card, for the +//! timeline (`crate::timeline`). Lists made ahead, each a timestamp and its +//! way into memory the PC reads, go ahead of and behind every submission +//! while the timeline records. + +use std::sync::atomic::{AtomicUsize, Ordering}; + +use windows::core::Interface; + +use super::*; + +/// Submissions stamped (three frames have some hundred and twenty). +const MOST: usize = 1024; + +struct Stamps { + /// The first half the lists that go ahead, then those that go behind. + lists: Vec, + /// The mapping of what they write, a tick count each. + back: usize, + /// Keeps it all. + _kept: (ID3D12CommandAllocator, ID3D12QueryHeap, ID3D12Resource), + /// The card's ticks and the PC's counter at one moment. + calibrated: (u64, u64), +} + +// SAFETY: free-threaded objects, and a mapping only read. +unsafe impl Send for Stamps {} +// SAFETY: as above. +unsafe impl Sync for Stamps {} + +static STAMPS: OnceLock> = OnceLock::new(); +static NEXT: AtomicUsize = AtomicUsize::new(0); + +/// Makes the lists, before the recording begins. +pub(crate) fn timeline_ready() { + let Some(host) = host() else { + return; + }; + STAMPS.get_or_init(|| match host.make_stamps() { + Ok(stamps) => Some(stamps), + Err(e) => { + tracing::warn!(error = %e, "the timeline is without the card's times"); + None + } + }); +} + +/// The place of the next submission's stamps, if the timeline records. +pub(super) fn take() -> Option { + if !crate::timeline::on() || STAMPS.get()?.is_none() { + return None; + } + let at = NEXT.fetch_add(1, Ordering::Relaxed); + (at < MOST).then_some(at) +} + +/// The list that goes ahead of the submission at `at`, and the one behind. +pub(super) fn lists(at: usize) -> Option<(ID3D12CommandList, ID3D12CommandList)> { + let stamps = STAMPS.get()?.as_ref()?; + Some((stamps.lists[at].clone(), stamps.lists[MOST + at].clone())) +} + +/// By place, from when to when a submission ran on the card, in ticks of +/// the PC's counter. Once the card has run them. +pub(crate) fn timeline_stamps() -> Vec<(u64, u64)> { + times(NEXT.load(Ordering::Relaxed).min(MOST)) +} + +/// The stamps are used from the first again, for the next timeline. +pub(crate) fn timeline_restart() { + if let Some(Some(stamps)) = STAMPS.get() { + // SAFETY: the mapping holds twice `MOST` tick counts; the card wrote + // them some frames ago. + unsafe { std::ptr::write_bytes(stamps.back as *mut u8, 0, 16 * MOST) }; + } + NEXT.store(0, Ordering::Relaxed); +} + +/// The first `taken` of them. +fn times(taken: usize) -> Vec<(u64, u64)> { + let (Some(Some(stamps)), Some(host)) = (STAMPS.get(), host()) else { + return Vec::new(); + }; + let (mut card, mut pc) = (0, 0); + // SAFETY: plain queries; the mapping holds twice `MOST` tick counts. + let (frequency, back) = unsafe { + if host.queue.GetClockCalibration(&mut card, &mut pc).is_err() { + return Vec::new(); + } + let frequency = host.queue.GetTimestampFrequency().unwrap_or(0); + (frequency, std::slice::from_raw_parts(stamps.back as *const u64, 2 * MOST)) + }; + if frequency == 0 { + return Vec::new(); + } + // By the two calibrations, the card's clock as it ran between them. + let (card0, pc0) = stamps.calibrated; + let rate = match card.saturating_sub(card0) { + 0 => 1e7 / frequency as f64, + passed => pc.saturating_sub(pc0) as f64 / passed as f64, + }; + let place = |ticks: u64| (pc0 as f64 + (ticks as f64 - card0 as f64) * rate) as u64; + (0..taken) + .map(|at| match (back[at], back[MOST + at]) { + (0, _) | (_, 0) => (0, 0), + (from, to) => (place(from), place(to)), + }) + .collect() +} + +impl Host { + fn make_stamps(&self) -> windows::core::Result { + let Some((buffer, back)) = self.shared_buffer(16 * MOST as u64) else { + return Err(windows::core::Error::from(windows::Win32::Foundation::E_OUTOFMEMORY)); + }; + // SAFETY: plain object creation; a fresh mapping of that size. + unsafe { + std::ptr::write_bytes(back, 0, 16 * MOST); + let mut heap: Option = None; + self.device.CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2 * MOST as u32, + NodeMask: 0, + }, + &mut heap, + )?; + let heap = heap.ok_or_else(windows::core::Error::empty)?; + let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let mut lists = Vec::with_capacity(2 * MOST); + for at in 0..2 * MOST as u32 { + let list: ID3D12GraphicsCommandList = + self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.EndQuery(&heap, D3D12_QUERY_TYPE_TIMESTAMP, at); + list.ResolveQueryData(&heap, D3D12_QUERY_TYPE_TIMESTAMP, at, 1, &buffer, u64::from(at) * 8); + list.Close()?; + lists.push(list.cast()?); + } + let (mut card, mut pc) = (0, 0); + self.queue.GetClockCalibration(&mut card, &mut pc)?; + Ok(Stamps { + lists, + back: back as usize, + _kept: (allocator, heap, buffer), + calibrated: (card, pc), + }) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// What goes ahead of and behind a submission says when it ran, by the + /// PC's own counter. + #[test] + fn a_submissions_times_are_the_pcs() { + let Some(host) = host() else { + return; + }; + timeline_ready(); + let Some((ahead, behind)) = lists(5) else { + return; + }; + let sent = crate::timeline::ticks(); + { + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + *submitted += 1; + // SAFETY: closed lists; the fence and event are the host's, under + // its lock. + unsafe { + host.queue.ExecuteCommandLists(&[Some(ahead), Some(behind)]); + host.queue.Signal(&host.fence, *submitted).unwrap(); + host.fence.SetEventOnCompletion(*submitted, host.event).unwrap(); + WaitForSingleObject(host.event, INFINITE); + } + } + let done = crate::timeline::ticks(); + let times = times(6); + assert_eq!(times[4], (0, 0), "not run"); + let (from, to) = times[5]; + // (The two clocks agree to some tens of microseconds.) + let near = 2_000; + assert!(from <= to && from + near >= sent && to <= done + near, "{sent} {from} {to} {done}"); + } +} diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 4d207f4..0bc5d5f 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -254,8 +254,10 @@ impl Pool { }; state.running += 1; drop(state); + let working = crate::timeline::span("a landing's job"); // SAFETY: counted in `running`, so `each` has not returned. let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { (*work.0)(i) })); + working.end(); state = self.state(); state.running -= 1; state.panicked |= ran.is_err(); @@ -272,6 +274,7 @@ impl Pool { (0..count).for_each(f); return; } + let _spread = crate::timeline::span("landing: spread over threads"); let _turn = self.turn.lock().unwrap_or_else(|e| e.into_inner()); // SAFETY: the lifetime is left out only until this call returns, and // it does not before no helper is inside `f` and none can enter. diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 045e5d6..75fa6e6 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -68,10 +68,13 @@ mod shadow; mod tiles; pub mod signature; mod switch; +#[cfg(all(windows, feature = "diagnostics"))] +mod ab; #[cfg(windows)] mod tdr; #[cfg(windows)] mod texture; +pub mod timeline; #[cfg(windows)] mod upload; #[cfg(windows)] diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 4c5fa52..52c49b0 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -621,6 +621,7 @@ extern "system" fn list_type(this: This) -> u32 { unsafe { (*this.cast::()).kind } } extern "system" fn close(this: This) -> HRESULT { + let _called = crate::timeline::span("the title's Close"); #[cfg(windows)] if let Some(host) = host_list(this) { host.close(); @@ -631,6 +632,7 @@ extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT if allocator.is_null() { return E_INVALIDARG; } + let _called = crate::timeline::span("the title's list Reset"); // A wait recorded and never submitted goes with the recording. VALUE_WAITS .lock() diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index bd80ec5..90ec3d8 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -320,6 +320,7 @@ pub(crate) fn release_held(all: bool) { if lock(&WAITING).is_empty() { return; } + let _looking = crate::timeline::span("looking at what queues hold"); let _one = lock(&RELEASING); loop { let queues = lock(&WAITING).clone(); @@ -549,6 +550,9 @@ extern "system" fn execute(this: This, count: u32, lists: *const This) { if lists.is_null() { return; } + let _called = crate::timeline::span("the title's ExecuteCommandLists"); + #[cfg(all(windows, feature = "diagnostics"))] + crate::timeline::title_thread(); #[cfg(windows)] if let Some(host) = crate::host::host() { // SAFETY: the title passes `count` lists. @@ -650,6 +654,7 @@ extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT { if fence.is_null() { return E_INVALIDARG; } + let _called = crate::timeline::span("the title's queue Signal"); #[cfg(windows)] if behind::on() && !this.is_null() { behind::signal(this, fence, value); @@ -680,6 +685,7 @@ extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { if fence.is_null() { return E_INVALIDARG; } + let _called = crate::timeline::span("the title's queue Wait"); #[cfg(windows)] if !this.is_null() { let now = crate::fence::completed(fence); @@ -767,6 +773,8 @@ impl Written { } Written::SystemTimestamp => system_timestamp(), }; + #[cfg(all(windows, feature = "diagnostics"))] + crate::timeline::told("written when its list had run", at as usize, value); // SAFETY: the title names writable GPU memory (unified with ours). unsafe { if bytes == 4 { @@ -837,6 +845,9 @@ extern "system" fn present( let _ = this; #[cfg(all(windows, feature = "diagnostics"))] crate::copystat::present_begins(); + let called = crate::timeline::span("the title's Present"); + #[cfg(all(windows, feature = "diagnostics"))] + crate::timeline::title_thread(); // Submissions sent to the card and not waited for are settled first, // and what that frees runs in its own order, before anything is forced. #[cfg(windows)] @@ -917,6 +928,9 @@ extern "system" fn present( }; let resource = texture.as_ref().map_or(0, |t| t.0); behind::present(this, texture.map(|(_, copy, state)| (copy, state)), Shown { frame, resource }); + called.end(); + #[cfg(feature = "diagnostics")] + frame_ends(); return S_OK; } #[cfg(windows)] @@ -939,8 +953,23 @@ extern "system" fn present( } #[cfg(not(windows))] let _ = (planes, plane_parameters); + called.end(); + #[cfg(all(windows, feature = "diagnostics"))] + frame_ends(); S_OK } + +/// Diagnostics: the title's present is over. +#[cfg(all(windows, feature = "diagnostics"))] +fn frame_ends() { + crate::timeline::presented(); + crate::ab::presented(|switch, was, will| { + if switch == "VICTORY_ASYNC_SUBMIT" && was && !will { + behind::leave(); + } + }); +} + /// The frame a present shows, and the title's resource it shows. #[cfg(windows)] #[derive(Clone, Copy)] @@ -1037,6 +1066,7 @@ extern "system" fn copy_page_mappings( if batches.is_null() && count > 0 { return E_INVALIDARG; } + let _called = crate::timeline::span("the title's CopyPageMappings"); let batches = (count > 0).then(|| { // SAFETY: the title passes `count` batches. unsafe { std::slice::from_raw_parts(batches, count as usize) } diff --git a/crates/victory-gpu/src/queue/behind.rs b/crates/victory-gpu/src/queue/behind.rs index 69dbdd9..b2f3de7 100644 --- a/crates/victory-gpu/src/queue/behind.rs +++ b/crates/victory-gpu/src/queue/behind.rs @@ -340,6 +340,12 @@ impl Work for Job { fn go(self, forced: bool) { let began = Instant::now(); + let _doing = crate::timeline::span(match self { + Job::Run(..) => "the line: a submission", + Job::Present(..) => "the line: a present", + Job::Signal(..) => "the line: a signal", + _ => "the line: a wait that is met", + }); if forced { STATS[FORCED].fetch_add(1, Relaxed); #[cfg(feature = "diagnostics")] @@ -426,11 +432,27 @@ thread_local! { /// (`VICTORY_ASYNC_SUBMIT=1`; needs flights with the present sent ahead, as /// the relay has them, and lists cut at their waits). pub(super) fn on() -> bool { + // Diagnostics: on and off while the title runs (`crate::ab`). + #[cfg(feature = "diagnostics")] + if let Some(on) = crate::ab::pick("VICTORY_ASYNC_SUBMIT") { + return on && started(); + } + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_ASYNC_SUBMIT").is_some_and(|v| v == "1") && started()) +} + +/// The line is about to be left for the way without it: everything in it is +/// done first. (At a present, by the title's thread that submits.) +#[cfg(feature = "diagnostics")] +pub(super) fn leave() { + LANE.wait_presents(0); + LANE.drain(); +} + +/// Starts the thread, once: whether there is one. +fn started() -> bool { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| { - if !std::env::var_os("VICTORY_ASYNC_SUBMIT").is_some_and(|v| v == "1") { - return false; - } if !crate::host::late_free_present() || !super::cuts() { tracing::warn!("VICTORY_ASYNC_SUBMIT=1 needs the relay and lists cut at their waits: submissions are prepared by the thread that makes them"); return false; @@ -528,6 +550,7 @@ pub(super) fn submit(this: This, lists: &[This]) { LANE.push(queue, jobs); if before + runs > runs_most() as u64 { let began = Instant::now(); + let _waiting = crate::timeline::span("a submission waits for room in the line"); LANE.wait_runs(runs_most()); STATS[ROOM].fetch_add(began.elapsed().as_micros() as u64, Relaxed); } @@ -558,6 +581,7 @@ pub(super) fn present(this: This, texture: Option<(std::sync::Arc &'static Workers { jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner()); } }; + let _working = crate::timeline::span("a job for another thread"); job(); } }); @@ -1483,6 +1484,7 @@ fn wide(jobs: Vec) { return; } let workers = workers(); + let _wide = crate::timeline::span("work spread over threads"); let left = Arc::new((Mutex::new(jobs.len()), std::sync::Condvar::new())); { let mut queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index dc7bad1..365d024 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -1155,6 +1155,7 @@ impl Staging { pub(crate) fn refresh(&self) { use std::sync::atomic::Ordering::Relaxed; let started = std::time::Instant::now(); + let _texture = crate::timeline::span("a texture's refresh"); let read = self.refresh_now(); let preparing = &crate::host::PREPARING; preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed); diff --git a/crates/victory-gpu/src/timeline.rs b/crates/victory-gpu/src/timeline.rs new file mode 100644 index 0000000..3bdbcf7 --- /dev/null +++ b/crates/victory-gpu/src/timeline.rs @@ -0,0 +1,57 @@ +//! Diagnostics: a timeline of a few frames. `VICTORY_TIMELINE=` writes +//! one, from the first present after `VICTORY_TIMELINE_AT` seconds (60) on +//! and for `VICTORY_TIMELINE_FRAMES` frames (3); +//! `VICTORY_TIMELINE=[+..],,` one for each of +//! the times (each in a file of its own, the second in its name): a Chrome trace (JSON, for +//! `chrome://tracing` or Perfetto) and beside it a text summary (`.txt`) +//! with the chain of work and waits each frame's present came out of. +//! +//! What is recorded while it runs, by every thread: +//! - spans of ours ([`span`]): the title's calls, the submitting thread's +//! stages, the relay's, the pools' jobs, texture and streaming work; +//! - waits and the wake-ups that end them ([`hooks`]): the functions the +//! title's threads wait with (its imports are bound to wrappers) and those +//! our own code does (the entries of our own import table: every contended +//! lock, condition and park of the standard library is a `WaitOnAddress`), +//! each with the thread that woke it and where it waited; +//! - kernel calls on the address space that took long; +//! - the card: when each submission began and ended on it (timestamps). +//! +//! Without the variable nothing is wrapped and a span is one load of a +//! flag; a build without `diagnostics` has nothing of it. + +#[cfg(all(windows, feature = "diagnostics"))] +mod hooks; +#[cfg(all(windows, feature = "diagnostics"))] +mod record; +#[cfg(all(windows, feature = "diagnostics"))] +mod report; + +#[cfg(all(windows, feature = "diagnostics"))] +pub use hooks::import; +#[cfg(all(windows, feature = "diagnostics"))] +pub use record::{Span, span}; +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) use record::{called, card_wait, on, polled, presented, sent, ticks, title_thread, told}; + +/// A span of ours: from where it is made until it is dropped. +#[cfg(not(all(windows, feature = "diagnostics")))] +pub struct Span; + +#[cfg(not(all(windows, feature = "diagnostics")))] +impl Span { + /// The span ends here and another begins. + #[inline(always)] + pub fn next(&mut self, _name: &'static str) {} + + /// The span ends here. + #[inline(always)] + pub fn end(self) {} +} + +/// A span named `name`. +#[cfg(not(all(windows, feature = "diagnostics")))] +#[inline(always)] +pub fn span(_name: &'static str) -> Span { + Span +} diff --git a/crates/victory-gpu/src/timeline/hooks.rs b/crates/victory-gpu/src/timeline/hooks.rs new file mode 100644 index 0000000..83afa26 --- /dev/null +++ b/crates/victory-gpu/src/timeline/hooks.rs @@ -0,0 +1,322 @@ +//! The wrappers around what threads wait and wake each other with. The +//! title's imports are bound to them ([`import`]), and the entries of our +//! own import table point at them, if a timeline was asked for; else nothing +//! is wrapped. While nothing is recorded a wrapper is a load and a jump. + +use std::ffi::{CStr, c_void}; +use std::sync::Once; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use super::record::{kernel, on, standing, stood_at, ticks, waited, woken}; + +type Handle = *mut c_void; + +macro_rules! wrapped { + ($($index:literal $name:ident ($($arg:ident: $type:ty),*) $(-> $result:ty)? => $body:expr;)*) => { + /// The functions wrapped, by name: their own addresses, ours. + static TABLE: [(&str, AtomicUsize, usize); [$($index),*].len()] = [ + $((stringify!($name), AtomicUsize::new(0), $index)),* + ]; + + fn wrapper(index: usize) -> usize { + match index { + $($index => wrappers::$name as *const () as usize,)* + _ => 0, + } + } + + #[allow(non_snake_case)] + mod wrappers { + use super::*; + $( + pub(super) unsafe extern "system" fn $name($($arg: $type),*) $(-> $result)? { + // SAFETY: the function of that name, as the system has it + // (or the module the title imports it from). + let real: unsafe extern "system" fn($($type),*) $(-> $result)? = + unsafe { std::mem::transmute(TABLE[$index].1.load(Ordering::Relaxed)) }; + if !on() { + // SAFETY: the caller's own call. + return unsafe { real($($arg),*) }; + } + ($body)(real) + } + )* + } + }; +} + +/// Runs `call`, a wait on `object` that may be long; what the caller may +/// ask [`GetLastError`] about stays. +/// +/// [`GetLastError`]: windows_sys::Win32::Foundation::GetLastError +fn wait(name: &'static str, object: u64, call: impl FnOnce() -> T) -> T { + use windows_sys::Win32::Foundation::{GetLastError, SetLastError}; + let t0 = ticks(); + let result = { + let _standing = standing(object); + call() + }; + // SAFETY: plain queries of this thread's own. + unsafe { + let error = GetLastError(); + waited(name, object, t0); + SetLastError(error); + } + result +} + +/// Runs `call`, a call of the kernel's on `bytes`. +fn measured(name: &'static str, bytes: usize, call: impl FnOnce() -> T) -> T { + use windows_sys::Win32::Foundation::{GetLastError, SetLastError}; + let t0 = ticks(); + let result = call(); + // SAFETY: plain queries of this thread's own. + unsafe { + let error = GetLastError(); + kernel(name, bytes as u64, t0); + SetLastError(error); + } + result +} + +/// The function `name` of the table, as the system has it. +fn real(name: &str) -> usize { + TABLE.iter().find(|t| t.0 == name).map_or(0, |t| t.1.load(Ordering::Relaxed)) +} + +/// `take(lock)`, a try that does not wait, then `wait`. +fn lock_of(name: &'static str, lock: Handle, take: &str, call: impl FnOnce()) { + let take = real(take); + if take != 0 { + // SAFETY: `TryEnterCriticalSection` or a `TryAcquireSRWLock` call: + // one pointer, a truth value (one byte of it for the latter). + let taken = unsafe { std::mem::transmute:: u8>(take)(lock) }; + if taken != 0 { + return; + } + } + wait(name, lock as u64, call); +} + +fn released(name: &'static str, object: Handle) { + if stood_at(object as u64) { + woken(name, object as u64); + } +} + +wrapped! { + 0 WaitForSingleObject(object: Handle, ms: u32) -> u32 => |real: unsafe extern "system" fn(Handle, u32) -> u32| { + // SAFETY: the caller's own call (so below). + wait("WaitForSingleObject", object as u64, || unsafe { real(object, ms) }) + }; + 1 WaitForSingleObjectEx(object: Handle, ms: u32, alertable: i32) -> u32 => |real: unsafe extern "system" fn(Handle, u32, i32) -> u32| { + wait("WaitForSingleObjectEx", object as u64, || unsafe { real(object, ms, alertable) }) + }; + 2 Sleep(ms: u32) => |real: unsafe extern "system" fn(u32)| { + wait("Sleep", 0, || unsafe { real(ms) }) + }; + 3 SleepEx(ms: u32, alertable: i32) -> u32 => |real: unsafe extern "system" fn(u32, i32) -> u32| { + wait("SleepEx", 0, || unsafe { real(ms, alertable) }) + }; + 4 SetEvent(object: Handle) -> i32 => |real: unsafe extern "system" fn(Handle) -> i32| { + woken("SetEvent", object as u64); + unsafe { real(object) } + }; + 5 ReleaseSemaphore(object: Handle, count: i32, before: *mut i32) -> i32 => |real: unsafe extern "system" fn(Handle, i32, *mut i32) -> i32| { + woken("ReleaseSemaphore", object as u64); + unsafe { real(object, count, before) } + }; + 6 ReleaseMutex(object: Handle) -> i32 => |real: unsafe extern "system" fn(Handle) -> i32| { + woken("ReleaseMutex", object as u64); + unsafe { real(object) } + }; + 7 EnterCriticalSection(lock: Handle) => |real: unsafe extern "system" fn(Handle)| { + lock_of("EnterCriticalSection", lock, "TryEnterCriticalSection", || unsafe { real(lock) }) + }; + 8 LeaveCriticalSection(lock: Handle) => |real: unsafe extern "system" fn(Handle)| { + released("LeaveCriticalSection", lock); + unsafe { real(lock) } + }; + 9 AcquireSRWLockExclusive(lock: Handle) => |real: unsafe extern "system" fn(Handle)| { + lock_of("AcquireSRWLockExclusive", lock, "TryAcquireSRWLockExclusive", || unsafe { real(lock) }) + }; + 10 ReleaseSRWLockExclusive(lock: Handle) => |real: unsafe extern "system" fn(Handle)| { + released("ReleaseSRWLockExclusive", lock); + unsafe { real(lock) } + }; + 11 AcquireSRWLockShared(lock: Handle) => |real: unsafe extern "system" fn(Handle)| { + lock_of("AcquireSRWLockShared", lock, "TryAcquireSRWLockShared", || unsafe { real(lock) }) + }; + 12 ReleaseSRWLockShared(lock: Handle) => |real: unsafe extern "system" fn(Handle)| { + released("ReleaseSRWLockShared", lock); + unsafe { real(lock) } + }; + 13 WaitOnAddress(at: Handle, compare: Handle, size: usize, ms: u32) -> i32 => |real: unsafe extern "system" fn(Handle, Handle, usize, u32) -> i32| { + wait("WaitOnAddress", at as u64, || unsafe { real(at, compare, size, ms) }) + }; + 14 WakeByAddressSingle(at: Handle) => |real: unsafe extern "system" fn(Handle)| { + released("WakeByAddressSingle", at); + unsafe { real(at) } + }; + 15 WakeByAddressAll(at: Handle) => |real: unsafe extern "system" fn(Handle)| { + released("WakeByAddressAll", at); + unsafe { real(at) } + }; + 16 SleepConditionVariableSRW(at: Handle, lock: Handle, ms: u32, flags: u32) -> i32 => |real: unsafe extern "system" fn(Handle, Handle, u32, u32) -> i32| { + wait("SleepConditionVariableSRW", at as u64, || unsafe { real(at, lock, ms, flags) }) + }; + 17 SleepConditionVariableCS(at: Handle, lock: Handle, ms: u32) -> i32 => |real: unsafe extern "system" fn(Handle, Handle, u32) -> i32| { + wait("SleepConditionVariableCS", at as u64, || unsafe { real(at, lock, ms) }) + }; + 18 WakeConditionVariable(at: Handle) => |real: unsafe extern "system" fn(Handle)| { + released("WakeConditionVariable", at); + unsafe { real(at) } + }; + 19 WakeAllConditionVariable(at: Handle) => |real: unsafe extern "system" fn(Handle)| { + released("WakeAllConditionVariable", at); + unsafe { real(at) } + }; + 20 WaitForMultipleObjects(count: u32, objects: *const Handle, all: i32, ms: u32) -> u32 => |real: unsafe extern "system" fn(u32, *const Handle, i32, u32) -> u32| { + // (Named by the first of them.) + // SAFETY: the caller passes `count` handles. + let first = if count > 0 && !objects.is_null() { (unsafe { *objects }) as u64 } else { 0 }; + wait("WaitForMultipleObjects", first, || unsafe { real(count, objects, all, ms) }) + }; + 21 GetWriteWatch(flags: u32, at: Handle, size: usize, found: Handle, count: Handle, granularity: Handle) -> u32 => |real: unsafe extern "system" fn(u32, Handle, usize, Handle, Handle, Handle) -> u32| { + measured("GetWriteWatch", size, || unsafe { real(flags, at, size, found, count, granularity) }) + }; + 22 VirtualProtect(at: Handle, size: usize, new: u32, old: Handle) -> i32 => |real: unsafe extern "system" fn(Handle, usize, u32, Handle) -> i32| { + measured("VirtualProtect", size, || unsafe { real(at, size, new, old) }) + }; + 23 ReadProcessMemory(process: Handle, at: Handle, to: Handle, size: usize, done: Handle) -> i32 => |real: unsafe extern "system" fn(Handle, Handle, Handle, usize, Handle) -> i32| { + measured("ReadProcessMemory", size, || unsafe { real(process, at, to, size, done) }) + }; + 24 VirtualQuery(at: Handle, info: Handle, size: usize) -> usize => |real: unsafe extern "system" fn(Handle, Handle, usize) -> usize| { + measured("VirtualQuery", 0, || unsafe { real(at, info, size) }) + }; + 25 VirtualAlloc(at: Handle, size: usize, kind: u32, protect: u32) -> Handle => |real: unsafe extern "system" fn(Handle, usize, u32, u32) -> Handle| { + measured("VirtualAlloc", size, || unsafe { real(at, size, kind, protect) }) + }; + 26 VirtualFree(at: Handle, size: usize, kind: u32) -> i32 => |real: unsafe extern "system" fn(Handle, usize, u32) -> i32| { + measured("VirtualFree", size, || unsafe { real(at, size, kind) }) + }; + 27 _Mtx_lock(lock: Handle) -> i32 => |real: unsafe extern "system" fn(Handle) -> i32| { + wait("_Mtx_lock", lock as u64, || unsafe { real(lock) }) + }; + 28 _Mtx_unlock(lock: Handle) -> i32 => |real: unsafe extern "system" fn(Handle) -> i32| { + released("_Mtx_unlock", lock); + unsafe { real(lock) } + }; + 29 TryEnterCriticalSection(lock: Handle) -> u8 => |real: unsafe extern "system" fn(Handle) -> u8| unsafe { real(lock) }; + 30 TryAcquireSRWLockExclusive(lock: Handle) -> u8 => |real: unsafe extern "system" fn(Handle) -> u8| unsafe { real(lock) }; + 31 TryAcquireSRWLockShared(lock: Handle) -> u8 => |real: unsafe extern "system" fn(Handle) -> u8| unsafe { real(lock) }; +} + +/// The wrappers from here on are there for their real functions only. +const ONLY_REAL: usize = 29; + +/// Asks the system for the real functions, and points our own import table +/// at the wrappers: once, if a timeline is wanted. +fn arm() -> bool { + static ONCE: Once = Once::new(); + if !super::record::wanted() { + return false; + } + ONCE.call_once(wrap_own); + true +} + +/// See [`arm`]. +pub(super) fn wrap_own() { + find_real(); + // SAFETY: our own module's mapped image. + let changed = unsafe { wrap_imports() }; + tracing::info!(changed, "the timeline's wrappers are in (VICTORY_TIMELINE)"); +} + +fn find_real() { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + for dll in [c"kernelbase.dll", c"kernel32.dll", c"ntdll.dll"] { + // SAFETY: NUL-terminated names of modules every process has. + let module = unsafe { GetModuleHandleA(dll.as_ptr().cast()) }; + for (name, at, _) in &TABLE { + if at.load(Ordering::Relaxed) == 0 && !module.is_null() { + let text = std::ffi::CString::new(*name).expect("a plain name"); + // SAFETY: as above. + if let Some(f) = unsafe { GetProcAddress(module, text.as_ptr().cast()) } { + at.store(f as *const () as usize, Ordering::Relaxed); + } + } + } + } +} + +/// What the title's import `name`, found at `address`, is bound to: the +/// address itself, or our wrapper of it. +pub fn import(name: &str, address: usize) -> usize { + if !arm() { + return address; + } + let Some((i, (_, at, _))) = TABLE.iter().enumerate().find(|(i, t)| *i < ONLY_REAL && t.0 == name) else { + return address; + }; + if at.load(Ordering::Relaxed) == 0 { + at.store(address, Ordering::Relaxed); + } + wrapper(i) +} + +/// Points the entries of our own import table that are in [`TABLE`] at the +/// wrappers: how many. +/// +/// # Safety +/// The process's module is mapped as the loader left it. +unsafe fn wrap_imports() -> usize { + use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; + use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; + // SAFETY: a plain query. + let base = unsafe { GetModuleHandleW(std::ptr::null()) } as usize; + let mut changed = 0; + // SAFETY: the headers, the import directory and the tables it names lie + // in the mapped image, as the loader read them; an entry is eight bytes, + // aligned, and made writable for the store. + unsafe { + let at = |rva: u32| base + rva as usize; + let read = |at: usize| (at as *const u32).read_unaligned(); + let headers = at(read(base + 0x3c)); + // The second data directory of the 64-bit optional header: imports. + let mut descriptor = at(read(headers + 0x18 + 0x70 + 8)); + loop { + let (names, first) = (read(descriptor), read(descriptor + 16)); + if first == 0 { + break; + } + let names = if names != 0 { names } else { first }; + for i in 0.. { + let entry = (at(names) as *const u64).add(i).read_unaligned(); + if entry == 0 { + break; + } + if entry >> 63 != 0 { + continue; // by number + } + let name = CStr::from_ptr((at(entry as u32) + 2) as *const _); + let Some(index) = TABLE[..ONLY_REAL].iter().position(|t| t.0.as_bytes() == name.to_bytes()) else { + continue; + }; + if TABLE[index].1.load(Ordering::Relaxed) == 0 { + continue; + } + let slot = (at(first) as *mut usize).add(i); + let (mut old, mut ignored) = (0, 0); + if VirtualProtect(slot.cast(), 8, PAGE_READWRITE, &mut old) != 0 { + (*slot.cast::()).store(wrapper(index), Ordering::SeqCst); + VirtualProtect(slot.cast(), 8, old, &mut ignored); + changed += 1; + } + } + descriptor += 20; + } + } + changed +} diff --git a/crates/victory-gpu/src/timeline/record.rs b/crates/victory-gpu/src/timeline/record.rs new file mode 100644 index 0000000..fb3b517 --- /dev/null +++ b/crates/victory-gpu/src/timeline/record.rs @@ -0,0 +1,678 @@ +//! What is recorded, and when. Every event goes into one buffer made ahead: +//! a write takes a place in it (one atomic addition) and nothing else, so it +//! can be done anywhere, the handler of write faults included. + +use std::cell::Cell; +use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock}; + +/// What an event is. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Kind { + /// A span of ours. + Span, + /// A run of list calls: `a` calls, `b` ticks inside them. + Calls, + /// A wait on the object `a` (an address, or a handle's value); `b`: the + /// value of the host's fence it stands for (0: none, [`COPY_QUEUE`]). + Wait, + /// The object `a` is signalled or released. + Wake, + /// A call of the kernel's that took long; `a` its bytes. + Kernel, + /// Lists went to the card: `a` the value signalled behind them, `b` the + /// place of their timestamps plus one. + Sent, + /// A present came back: a frame ends. + Frame, + /// The title is told something: `b` is stored at `a` (a fence, or what + /// a list writes when it has run). + Told, + /// The title asked a fence (`a`) for its value and got `b`, again and + /// again from the beginning to the end. + Poll, + /// Where a thread of the title's was: `a` the instruction, the stack + /// what on its stack may be return addresses. + Sample, +} + +/// The `b` of a wait for the card's copy queue. +pub(super) const COPY_QUEUE: u64 = u64::MAX; + +#[derive(Clone, Copy, Debug)] +pub(super) struct Event { + pub(super) t0: u64, + pub(super) t1: u64, + pub(super) a: u64, + pub(super) b: u64, + pub(super) name: &'static str, + pub(super) thread: u32, + /// Its place among the stacks, plus one (0: none). + pub(super) stack: u32, + pub(super) cpu: u16, + pub(super) kind: Kind, +} + +struct Slot { + event: std::cell::UnsafeCell>, + written: AtomicBool, +} + +/// Events kept, and stacks. +const EVENTS: usize = 1 << 20; +const STACKS: usize = 1 << 16; +/// Return addresses of a stack. +pub(super) const DEPTH: usize = 14; + +static ON: AtomicBool = AtomicBool::new(false); +static SLOTS: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); +static NEXT: AtomicUsize = AtomicUsize::new(0); +static STACK: AtomicPtr<[usize; DEPTH]> = AtomicPtr::new(std::ptr::null_mut()); +static NEXT_STACK: AtomicUsize = AtomicUsize::new(0); + +/// [`ticks`] per second. +pub(super) fn frequency() -> u64 { + static TICKS: OnceLock = OnceLock::new(); + *TICKS.get_or_init(|| { + let mut ticks = 0; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceFrequency(&mut ticks) }; + ticks.max(1) as u64 + }) +} + +/// The performance counter: the clock the card's is calibrated against. +pub(crate) fn ticks() -> u64 { + let mut ticks = 0; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut ticks) }; + ticks as u64 +} + +pub(super) fn micros(ticks: u64) -> u64 { + ticks.saturating_mul(1_000_000) / frequency() +} + +/// Whether events are recorded now. +#[inline(always)] +pub(crate) fn on() -> bool { + ON.load(Ordering::Relaxed) +} + +pub(super) fn thread() -> u32 { + thread_local!(static ID: Cell = const { Cell::new(0) }); + ID.with(|id| { + if id.get() == 0 { + // SAFETY: a plain query. + id.set(unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }); + } + id.get() + }) +} + +/// Records an event of this thread. +pub(super) fn put(kind: Kind, name: &'static str, t: (u64, u64), a: u64, b: u64, stack: u32) { + put_of(thread(), kind, name, t, a, b, stack); +} + +/// Records an event of `thread`. +fn put_of(thread: u32, kind: Kind, name: &'static str, (t0, t1): (u64, u64), a: u64, b: u64, stack: u32) { + let slots = SLOTS.load(Ordering::Acquire); + if slots.is_null() { + return; + } + let at = NEXT.fetch_add(1, Ordering::Relaxed); + if at >= EVENTS { + return; + } + // SAFETY: a plain query. + let cpu = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessorNumber() } as u16; + let event = Event { t0, t1, a, b, name, thread, stack, cpu, kind }; + // SAFETY: within the buffer, and this place was given to this call alone. + unsafe { + let slot = &*slots.add(at); + (*slot.event.get()).write(event); + slot.written.store(true, Ordering::Release); + } +} + +/// The caller's stack: its place, plus one. +fn stack() -> u32 { + let stacks = STACK.load(Ordering::Acquire); + if stacks.is_null() { + return 0; + } + let at = NEXT_STACK.fetch_add(1, Ordering::Relaxed); + if at >= STACKS { + return 0; + } + let mut frames = [0usize; DEPTH]; + // SAFETY: room for `DEPTH` return addresses; the place was given to this + // call alone. + unsafe { + windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace( + 1, + DEPTH as u32, + frames.as_mut_ptr().cast(), + std::ptr::null_mut(), + ); + stacks.add(at).write(frames); + } + at as u32 + 1 +} + +/// Shorter spans of ours are not kept (microseconds). +const SHORTEST: u64 = 5; +/// The stack of a wait or a list call this long is kept (microseconds). +const DEEP: u64 = 50; + +/// A span of ours: from where it is made until it is dropped. +pub struct Span { + name: &'static str, + /// When it began (0: nothing is recorded). + began: u64, +} + +/// A span named `name`. +#[inline(always)] +pub fn span(name: &'static str) -> Span { + Span { + name, + began: if on() { ticks() } else { 0 }, + } +} + +impl Span { + /// The span ends here and another begins. + #[inline(always)] + pub fn next(&mut self, name: &'static str) { + self.close(); + (self.name, self.began) = (name, if on() { ticks() } else { 0 }); + } + + /// The span ends here. + #[inline(always)] + pub fn end(self) {} + + fn close(&mut self) { + let began = std::mem::take(&mut self.began); + if began != 0 { + let now = ticks(); + if micros(now - began) >= SHORTEST { + put(Kind::Span, self.name, (began, now), 0, 0, 0); + } + } + } +} + +impl Drop for Span { + #[inline(always)] + fn drop(&mut self) { + if self.began != 0 { + self.close(); + } + } +} + +/// List calls closer than this (microseconds) are one event. +const RUN_GAP: u64 = 10; + +/// A list call of the title's that took `took` has returned. +pub(crate) fn called(took: std::time::Duration) { + if !on() { + return; + } + let inside = (took.as_nanos() as u64).saturating_mul(frequency()) / 1_000_000_000; + let t1 = ticks(); + let t0 = t1 - inside; + thread_local! { + /// The run under way: from, to, calls, ticks inside them. + static RUN: Cell<(u64, u64, u64, u64)> = const { Cell::new((0, 0, 0, 0)) }; + } + RUN.with(|run| { + let (from, to, calls, sum) = run.get(); + if calls > 0 && micros(t0.saturating_sub(to)) < RUN_GAP { + run.set((from, t1, calls + 1, sum + inside)); + return; + } + if calls > 0 { + put(Kind::Calls, "list calls", (from, to), calls, sum, 0); + } + run.set((t0, t1, 1, inside)); + }); + if micros(inside) >= DEEP { + put(Kind::Span, "a long list call", (t0, t1), 0, 0, stack()); + } +} + +thread_local! { + /// What the wait this thread makes now stands for ([`card_wait`]). + static CARD: Cell = const { Cell::new(0) }; +} + +/// While it lives, this thread's waits are for the card. +pub(crate) struct CardWait(()); + +/// This thread's waits are for the card to reach `fence` (`None`: for its +/// copy queue) until what comes back is dropped. +pub(crate) fn card_wait(fence: Option) -> CardWait { + CARD.with(|c| c.set(fence.unwrap_or(COPY_QUEUE))); + CardWait(()) +} + +impl Drop for CardWait { + fn drop(&mut self) { + CARD.with(|c| c.set(0)); + } +} + +/// This thread waited on `object` with `name` since `t0`. +pub(super) fn waited(name: &'static str, object: u64, t0: u64) { + let t1 = ticks(); + let us = micros(t1 - t0); + if us >= 2 { + let stack = if us >= DEEP { stack() } else { 0 }; + put(Kind::Wait, name, (t0, t1), object, CARD.with(Cell::get), stack); + } +} + +/// `object` is about to be signalled. +pub(super) fn woken(name: &'static str, object: u64) { + let t = ticks(); + put(Kind::Wake, name, (t, t), object, 0, 0); +} + +/// A call of the kernel's on `bytes` began at `t0`. +pub(super) fn kernel(name: &'static str, bytes: u64, t0: u64) { + let t1 = ticks(); + if micros(t1 - t0) >= 20 { + put(Kind::Kernel, name, (t0, t1), bytes, 0, 0); + } +} + +/// Lists went to the card between `t0` ([`ticks`]) and now, the value +/// `fence` signalled behind them, with the timestamps at `stamp`. +pub(crate) fn sent(t0: u64, fence: u64, stamp: Option) { + if on() { + put(Kind::Sent, "ExecuteCommandLists", (t0, ticks()), fence, stamp.map_or(0, |s| s as u64 + 1), 0); + } +} + +/// `value` is being stored at `at`, where the title looks for it. +#[inline(always)] +pub(crate) fn told(name: &'static str, at: usize, value: u64) { + if on() { + let t = ticks(); + put(Kind::Told, name, (t, t), at as u64, value, 0); + } +} + +/// The title asked the fence at `at` for its value, which is `value`. +#[inline(always)] +pub(crate) fn polled(at: usize, value: u64) { + if !on() { + return; + } + thread_local! { + /// The same answer, again and again: fence, value, from, to. + static SAME: Cell<(usize, u64, u64, u64)> = const { Cell::new((0, 0, 0, 0)) }; + } + let t = ticks(); + SAME.with(|same| { + let (fence, was, from, to) = same.get(); + if (fence, was) == (at, value) && micros(t.saturating_sub(to)) < 1000 { + same.set((at, value, from, t)); + return; + } + if fence != 0 && micros(to.saturating_sub(from)) >= 100 { + put(Kind::Poll, "asks a fence", (from, to), fence as u64, was, 0); + } + same.set((at, value, t, t)); + }); +} + +/// Threads of the title's that submit or present. +static TITLES: [AtomicU32; 4] = [const { AtomicU32::new(0) }; 4]; + +/// This thread is one of the title's that submit: what it does is sampled. +#[inline(always)] +pub(crate) fn title_thread() { + if !on() { + return; + } + let id = thread(); + for place in &TITLES { + match place.load(Ordering::Relaxed) { + there if there == id => return, + 0 if place.compare_exchange(0, id, Ordering::Relaxed, Ordering::Relaxed).is_ok() => return, + _ => {} + } + } +} + +/// Looks every quarter of a millisecond where the title's submitting threads +/// are, while the recording goes on: what they do outside our calls (a loop +/// on a value in memory has no event of its own). +fn sample() { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Diagnostics::Debug::{CONTEXT, CONTEXT_CONTROL_AMD64, GetThreadContext}; + use windows_sys::Win32::System::Threading::{ + OpenThread, ResumeThread, SuspendThread, THREAD_GET_CONTEXT, THREAD_SUSPEND_RESUME, + }; + /// `GetThreadContext` wants a 16-byte aligned context. + #[repr(C, align(16))] + struct Aligned(CONTEXT); + let mut open: Vec<(u32, *mut std::ffi::c_void)> = Vec::new(); + while on() { + for place in &TITLES { + let id = place.load(Ordering::Relaxed); + if id == 0 { + continue; + } + let thread = match open.iter().find(|o| o.0 == id) { + Some(o) => o.1, + None => { + // SAFETY: a thread of our own process. + let handle = unsafe { OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT, 0, id) }; + open.push((id, handle)); + handle + } + }; + if thread.is_null() { + continue; + } + let mut words = [0usize; 64]; + // SAFETY: zeroed is a valid CONTEXT; the thread is another one of + // this process and runs on before anything here allocates or + // locks; its stack is read from its pointer to the end of that + // page alone. + let at = unsafe { + let mut context = Aligned(std::mem::zeroed()); + context.0.ContextFlags = CONTEXT_CONTROL_AMD64; + if SuspendThread(thread) == u32::MAX { + continue; + } + let known = GetThreadContext(thread, &mut context.0) != 0; + if known { + let sp = context.0.Rsp as usize & !7; + let n = ((sp | 0xfff) + 1 - sp) / 8; + for (i, word) in words.iter_mut().enumerate().take(n) { + *word = (sp as *const usize).add(i).read_volatile(); + } + } + ResumeThread(thread); + if known { context.0.Rip as usize } else { 0 } + }; + let t = ticks(); + // What lies near the instruction may be a return address; where + // the instruction is the system's, all of it may tell something. + let mut frames = [0usize; DEPTH]; + let near = words.iter().copied().filter(|w| *w != 0 && (at >> 40 == 0x7f || w.abs_diff(at) < 0x1000_0000)); + for (frame, word) in frames.iter_mut().zip(near) { + *frame = word; + } + put_of(id, Kind::Sample, "a sample", (t, t), at as u64, 0, keep(frames)); + } + let until = ticks() + frequency() / 4000; + while ticks() < until { + std::hint::spin_loop(); + } + } + for (_, handle) in open { + // SAFETY: opened above. + unsafe { CloseHandle(handle) }; + } +} + +/// `frames` among the stacks: its place, plus one. +fn keep(frames: [usize; DEPTH]) -> u32 { + let stacks = STACK.load(Ordering::Acquire); + let at = NEXT_STACK.fetch_add(1, Ordering::Relaxed); + if stacks.is_null() || at >= STACKS { + return 0; + } + // SAFETY: the place was given to this call alone. + unsafe { stacks.add(at).write(frames) }; + at as u32 + 1 +} + +/// What was asked for. +struct Asked { + file: std::path::PathBuf, + /// Seconds after which a recording begins, for each. + after: Vec, + frames: u64, + started: std::time::Instant, +} + +/// `[+..],,`, or a file alone. +fn parse(text: &str) -> (Option<(Vec, u64)>, &str) { + let mut parts = text.splitn(3, ','); + let three = (parts.next(), parts.next(), parts.next()); + if let (Some(from), Some(frames), Some(file)) = three + && let Ok(from) = from.split('+').map(|f| f.trim().parse::()).collect::, _>>() + && let Ok(frames) = frames.trim().parse::() + { + return (Some((from, frames)), file); + } + (None, text) +} + +/// The variables, read once (before the title runs: its imports are bound +/// by them). +fn asked() -> Option<&'static Asked> { + static ASKED: OnceLock> = OnceLock::new(); + ASKED + .get_or_init(|| { + let file = std::env::var_os("VICTORY_TIMELINE").filter(|v| !v.is_empty())?; + let number = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()); + let text = file.to_string_lossy(); + let (when, file) = parse(&text); + let (after, frames) = when.unwrap_or_else(|| { + ( + vec![number("VICTORY_TIMELINE_AT").unwrap_or(60.0)], + number("VICTORY_TIMELINE_FRAMES").map_or(3, |n| n as u64), + ) + }); + Some(Asked { + file: file.into(), + after, + frames: frames.clamp(1, 60), + started: std::time::Instant::now(), + }) + }) + .as_ref() +} + +/// Whether a timeline was asked for. +pub(super) fn wanted() -> bool { + asked().is_some() +} + +/// Where the recording is. +struct Stage { + ready: bool, + began: bool, + frames: u64, + /// Recordings made, and whether one is being written. + made: usize, + writing: bool, + before: Option, +} + +/// The title's present came back. +pub(crate) fn presented() { + let Some(asked) = asked() else { + return; + }; + static STAGE: Mutex = Mutex::new(Stage { + ready: false, + began: false, + frames: 0, + made: 0, + writing: false, + before: None, + }); + let mut stage = STAGE.lock().unwrap_or_else(|e| e.into_inner()); + let Some(&after) = asked.after.get(stage.made) else { + return; + }; + if stage.writing || asked.started.elapsed().as_secs_f64() < after { + return; + } + if !stage.ready { + // The buffers, the card's lists and the threads' clocks take a + // while: the recording begins two frames later. + stage.ready = true; + make_room(); + crate::host::timeline_ready(); + return; + } + if !stage.began { + stage.began = true; + stage.before = Some(super::report::Threads::now()); + tracing::info!(file = %asked.file.display(), frames = asked.frames, "the timeline begins (VICTORY_TIMELINE)"); + begin(); + if std::thread::Builder::new().name("victory-sample".into()).spawn(sample).is_err() { + tracing::warn!("the timeline is without samples of the title's threads"); + } + frame(); + return; + } + frame(); + stage.frames += 1; + if stage.frames < asked.frames { + return; + } + stage.writing = true; + let before = stage.before.take().unwrap_or_default(); + // Several recordings: a file each. + let file = match asked.after.len() { + 1 => asked.file.clone(), + _ => { + let end = asked.file.extension().map_or("json".into(), |e| e.to_string_lossy().into_owned()); + asked.file.with_extension(format!("{after:.0}.{end}")) + } + }; + drop(stage); + let write = move || { + let after = super::report::Threads::now(); + // The spans under way at the last present end first. + std::thread::sleep(std::time::Duration::from_millis(250)); + let data = end(); + super::report::write(&file, data, &before, &after, crate::host::timeline_stamps()); + crate::host::timeline_restart(); + let mut stage = STAGE.lock().unwrap_or_else(|e| e.into_inner()); + (stage.began, stage.frames, stage.writing) = (false, 0, false); + stage.made += 1; + }; + if std::thread::Builder::new().name("victory-timeline".into()).spawn(write).is_err() { + tracing::warn!("no thread to write the timeline"); + } +} + +/// A frame ends now. +pub(super) fn frame() { + let t = ticks(); + put(Kind::Frame, "present", (t, t), 0, 0, 0); +} + +/// Makes the buffers (kept for good: a thread may be about to write). +pub(super) fn make_room() { + if !SLOTS.load(Ordering::Acquire).is_null() { + return; + } + fn zeroed(n: usize) -> *mut T { + let layout = std::alloc::Layout::array::(n).expect("a small number"); + // SAFETY: not of no size. + unsafe { std::alloc::alloc_zeroed(layout) }.cast() + } + STACK.store(zeroed(STACKS), Ordering::Release); + SLOTS.store(zeroed(EVENTS), Ordering::Release); +} + +/// Recording starts. +pub(super) fn begin() { + ON.store(true, Ordering::SeqCst); +} + +/// What was recorded, in no order. +pub(super) struct Data { + pub(super) events: Vec, + pub(super) stacks: Vec<[usize; DEPTH]>, + /// Events there was no room for. + pub(super) lost: usize, +} + +/// Recording ends. +pub(super) fn end() -> Data { + ON.store(false, Ordering::SeqCst); + // Those about to write do. + std::thread::sleep(std::time::Duration::from_millis(20)); + let taken = NEXT.load(Ordering::SeqCst); + TITLES.iter().for_each(|t| t.store(0, Ordering::SeqCst)); + let slots = SLOTS.load(Ordering::Acquire); + let mut events = Vec::with_capacity(taken.min(EVENTS)); + for at in 0..taken.min(EVENTS) { + // SAFETY: within the buffer; a written place is never written again. + unsafe { + let slot = &*slots.add(at); + if slot.written.load(Ordering::Acquire) { + events.push((*slot.event.get()).assume_init()); + slot.written.store(false, Ordering::Release); + } + } + } + NEXT.store(0, Ordering::SeqCst); + let count = NEXT_STACK.swap(0, Ordering::SeqCst).min(STACKS); + // SAFETY: that many were given out; each was written before the event + // that names it. + let stacks = unsafe { std::slice::from_raw_parts(STACK.load(Ordering::Acquire), count) }.to_vec(); + Data { + events, + stacks, + lost: taken.saturating_sub(EVENTS), + } +} + +/// Objects threads stand at now, by a hash of theirs: releases of a lock +/// nobody waits for are not recorded. +static STOOD_AT: [AtomicU32; 4096] = [const { AtomicU32::new(0) }; 4096]; + +fn place(object: u64) -> &'static AtomicU32 { + &STOOD_AT[(object.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 52) as usize] +} + +/// This thread is about to wait for `object`, until what comes back is +/// dropped. +pub(super) fn standing(object: u64) -> Standing { + place(object).fetch_add(1, Ordering::SeqCst); + Standing(object) +} + +/// See [`standing`]. +pub(super) struct Standing(u64); + +impl Drop for Standing { + fn drop(&mut self) { + place(self.0).fetch_sub(1, Ordering::SeqCst); + } +} + +/// Whether a thread may wait for `object`. +pub(super) fn stood_at(object: u64) -> bool { + place(object).load(Ordering::SeqCst) != 0 +} + +#[cfg(test)] +mod tests { + use super::parse; + + #[test] + fn a_timeline_is_asked_for_by_seconds_frames_and_a_file() { + assert_eq!(parse("120,20,D:/a.json"), (Some((vec![120.0], 20)), "D:/a.json")); + assert_eq!(parse("120+130.5,20,D:/a,b.json"), (Some((vec![120.0, 130.5], 20)), "D:/a,b.json")); + assert_eq!(parse("D:/a,1,2.json"), (None, "D:/a,1,2.json")); + assert_eq!(parse("D:/a.json"), (None, "D:/a.json")); + } +} diff --git a/crates/victory-gpu/src/timeline/report.rs b/crates/victory-gpu/src/timeline/report.rs new file mode 100644 index 0000000..d07a5e8 --- /dev/null +++ b/crates/victory-gpu/src/timeline/report.rs @@ -0,0 +1,957 @@ +//! What was recorded, put in order: the Chrome trace, and the text summary +//! with the chain each present came out of. + +use std::collections::{BTreeMap, HashMap}; +use std::fmt::Write as _; + +use super::record::{COPY_QUEUE, DEPTH, Data, Event, Kind, frequency}; + +/// The process's threads at a moment. +#[derive(Default)] +pub(super) struct Threads { + /// By number: its processor cycles so far, its name, where it started. + all: HashMap, + /// The processor's clock and the performance counter then. + cycles: u64, + ticks: u64, +} + +#[link(name = "kernel32")] +unsafe extern "system" { + fn QueryThreadCycleTime(thread: *mut std::ffi::c_void, cycles: *mut u64) -> i32; +} + +#[link(name = "ntdll")] +unsafe extern "system" { + fn NtQueryInformationThread( + thread: *mut std::ffi::c_void, + class: i32, + out: *mut std::ffi::c_void, + len: u32, + returned: *mut u32, + ) -> i32; +} + +impl Threads { + pub(super) fn now() -> Threads { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE, LocalFree}; + use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, + }; + use windows_sys::Win32::System::Threading::{ + GetCurrentProcessId, GetThreadDescription, OpenThread, THREAD_QUERY_INFORMATION, + }; + /// `ThreadQuerySetWin32StartAddress`. + const START: i32 = 9; + let mut threads = Threads::default(); + // SAFETY: a snapshot of our own, walked with a sized entry; handles + // opened here are closed; the name is the system's, freed as asked. + unsafe { + let own = GetCurrentProcessId(); + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if snapshot == INVALID_HANDLE_VALUE { + return threads; + } + let mut entry = THREADENTRY32 { + dwSize: size_of::() as u32, + ..Default::default() + }; + let mut more = Thread32First(snapshot, &mut entry) != 0; + while more { + if entry.th32OwnerProcessID == own { + let thread = OpenThread(THREAD_QUERY_INFORMATION, 0, entry.th32ThreadID); + if !thread.is_null() { + let (mut cycles, mut start, mut name) = (0, 0usize, std::ptr::null_mut()); + QueryThreadCycleTime(thread, &mut cycles); + NtQueryInformationThread(thread, START, (&raw mut start).cast(), 8, std::ptr::null_mut()); + let mut text = String::new(); + if GetThreadDescription(thread, &mut name) >= 0 && !name.is_null() { + let len = (0..).take_while(|&i| *name.add(i) != 0).count(); + text = String::from_utf16_lossy(std::slice::from_raw_parts(name, len)); + LocalFree(name.cast()); + } + CloseHandle(thread); + threads.all.insert(entry.th32ThreadID, (cycles, text, start)); + } + } + more = Thread32Next(snapshot, &mut entry) != 0; + } + CloseHandle(snapshot); + threads.cycles = std::arch::x86_64::_rdtsc(); + } + threads.ticks = super::record::ticks(); + threads + } +} + +/// Names of addresses. +pub(super) struct Names { + known: HashMap, + symbols: Option, +} + +/// The system's symbol library (asked for when a timeline is written, not +/// at start). +struct Symbols { + from_address: unsafe extern "system" fn(*mut std::ffi::c_void, u64, *mut u64, *mut u8) -> i32, + process: *mut std::ffi::c_void, +} + +impl Symbols { + fn load() -> Option { + use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExA}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + type Initialize = unsafe extern "system" fn(*mut std::ffi::c_void, *const u16, i32) -> i32; + type Options = unsafe extern "system" fn(u32) -> u32; + // SAFETY: the system's own library and functions, by their names and + // signatures. + unsafe { + let module = LoadLibraryExA(c"dbghelp.dll".as_ptr().cast(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32); + if module.is_null() { + return None; + } + let options: Options = std::mem::transmute(GetProcAddress(module, c"SymSetOptions".as_ptr().cast())?); + let initialize: Initialize = std::mem::transmute(GetProcAddress(module, c"SymInitializeW".as_ptr().cast())?); + let from_address = std::mem::transmute::< + unsafe extern "system" fn() -> isize, + unsafe extern "system" fn(*mut std::ffi::c_void, u64, *mut u64, *mut u8) -> i32, + >(GetProcAddress(module, c"SymFromAddr".as_ptr().cast())?); + let process = GetCurrentProcess(); + // Undecorated names, loaded when asked for, no dialogs. + options(0x2 | 0x4 | 0x200); + // Our symbols lie beside the program, which names them by their + // file alone. (It fails if a backtrace was asked for before: + // then it is there, and looks beside every module.) + let beside = std::env::current_exe().ok().and_then(|p| Some(p.parent()?.to_path_buf())).unwrap_or_default(); + let beside: Vec = std::os::windows::ffi::OsStrExt::encode_wide(beside.as_os_str()).chain([0]).collect(); + initialize(process, beside.as_ptr(), 1); + Some(Symbols { from_address, process }) + } + } + + fn name(&self, address: usize) -> Option { + // `SYMBOL_INFO`: 88 bytes with the name's first character at 84. + const NAME: usize = 84; + const ROOM: usize = 512; + let mut info = [0u64; (NAME + ROOM) / 8 + 1]; + let at = info.as_mut_ptr().cast::(); + let mut off = 0u64; + // SAFETY: a buffer of the structure's size and the name's, its size + // fields set as asked. + unsafe { + at.cast::().write(88); + at.add(80).cast::().write(ROOM as u32); + if (self.from_address)(self.process, address as u64 - 1, &mut off, at) == 0 { + return None; + } + let name = std::ffi::CStr::from_ptr(at.add(NAME).cast()); + Some(name.to_string_lossy().into_owned()) + } + } +} + +impl Names { + pub(super) fn new() -> Names { + Names { + known: HashMap::new(), + symbols: Symbols::load(), + } + } + + /// The module `address` lies in, and where in it; whether it is ours. + fn module(address: usize) -> (String, usize, bool) { + use windows_sys::Win32::System::LibraryLoader::{ + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleFileNameW, + GetModuleHandleExW, GetModuleHandleW, + }; + let mut module = std::ptr::null_mut(); + let mut path = [0u16; 260]; + // SAFETY: an address, no name; plain queries. + unsafe { + let flags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT; + if GetModuleHandleExW(flags, address as *const u16, &mut module) == 0 { + return ("?".into(), address, false); + } + let len = GetModuleFileNameW(module, path.as_mut_ptr(), path.len() as u32) as usize; + let path = String::from_utf16_lossy(&path[..len]); + let file = path.rsplit('\\').next().unwrap_or("?").to_string(); + (file, address - module as usize, module == GetModuleHandleW(std::ptr::null())) + } + } + + /// A name for `address`: our own functions by their names, others by + /// their module and place in it. + fn of(&mut self, address: usize) -> String { + if let Some(name) = self.known.get(&address) { + return name.clone(); + } + let (file, at, ours) = Self::module(address); + let name = match self.symbols.as_ref().filter(|_| ours).and_then(|s| s.name(address)) { + Some(name) => name, + None => format!("{}+{at:#x}", file.strip_suffix(".dll").unwrap_or(&file)), + }; + self.known.insert(address, name.clone()); + name + } + + /// Where a stack says the thread was: the innermost functions that are + /// not the standard library's or this module's. + fn site(&mut self, stack: &[usize; DEPTH]) -> String { + let mut parts: Vec = Vec::new(); + for &address in stack.iter().take_while(|a| **a != 0) { + let name = self.of(address); + let plain = name.trim_start_matches('<').trim_start_matches("impl$").trim_start_matches(|c: char| c.is_ascii_digit()); + let skipped = ["std::", "core::", "alloc::", "windows_core::", "windows::"].iter().any(|p| plain.starts_with(p)) + || ["timeline::hooks::", "timeline::record::"].iter().any(|p| name.contains(p)) + || ["KERNEL", "ntdll", "kernel"].iter().any(|p| name.starts_with(p)); + if !skipped { + parts.push(name.replace("victory_gpu::", "").replace("victory_hle::", "hle::")); + } + if parts.len() == 3 { + break; + } + } + parts.join(" < ") + } +} + +/// A part of a chain: what was done, or waited for, from when to when. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Part { + pub(super) from: u64, + pub(super) to: u64, + /// The thread (0: the card). + pub(super) thread: u32, + pub(super) cause: String, +} + +/// A wait that ended, as the chains see it. +#[derive(Clone, Copy, Debug)] +struct Wait { + t0: u64, + t1: u64, + object: u64, + fence: u64, + event: usize, +} + +/// A submission: when it went to the card, from which thread, and from when +/// to when it ran there. +#[derive(Clone, Copy, Debug)] +pub(super) struct Run { + pub(super) fence: u64, + pub(super) t0: u64, + pub(super) t1: u64, + pub(super) thread: u32, + pub(super) on: (u64, u64), +} + +/// What was recorded, by thread and in order. +pub(super) struct Trace { + pub(super) events: Vec, + /// The spans of a thread (places among the events), by their beginning. + spans: HashMap>, + /// The waits of a thread, by their end. + waits: HashMap>, + /// Who signalled an object when. + wakes: HashMap>, + /// The submissions, by the fence's value. + pub(super) runs: Vec, + pub(super) frames: Vec<(u64, u32)>, +} + +impl Trace { + /// `stamps`: the card's times of a submission by its place, as ticks. + pub(super) fn new(mut events: Vec, stamps: &[(u64, u64)]) -> Trace { + events.sort_by_key(|e| (e.t0, std::cmp::Reverse(e.t1))); + let mut trace = Trace { + events: Vec::new(), + spans: HashMap::new(), + waits: HashMap::new(), + wakes: HashMap::new(), + runs: Vec::new(), + frames: Vec::new(), + }; + for (i, e) in events.iter().enumerate() { + match e.kind { + Kind::Span | Kind::Calls | Kind::Kernel => trace.spans.entry(e.thread).or_default().push(i), + Kind::Wait => trace.waits.entry(e.thread).or_default().push(Wait { + t0: e.t0, + t1: e.t1, + object: e.a, + fence: e.b, + event: i, + }), + Kind::Wake => trace.wakes.entry(e.a).or_default().push((e.t0, e.thread)), + Kind::Sent => { + let on = (e.b as usize).checked_sub(1).and_then(|at| stamps.get(at)).copied().unwrap_or((0, 0)); + trace.runs.push(Run { + fence: e.a, + t0: e.t0, + t1: e.t1, + thread: e.thread, + on, + }); + trace.spans.entry(e.thread).or_default().push(i); + } + Kind::Frame => trace.frames.push((e.t1, e.thread)), + Kind::Told | Kind::Poll | Kind::Sample => {} + } + } + for waits in trace.waits.values_mut() { + waits.sort_by_key(|w| w.t1); + } + trace.runs.sort_by_key(|r| r.fence); + trace.events = events; + trace + } + + /// Who ended the wait `w` of `thread`, and when. + fn waker(&self, thread: u32, w: &Wait) -> Option<(u32, u64)> { + let wakes = self.wakes.get(&w.object)?; + let end = wakes.partition_point(|k| k.0 <= w.t1); + wakes[..end].iter().rev().take_while(|k| k.0 >= w.t0).find(|k| k.1 != thread).map(|k| (k.1, k.0)) + } + + /// What `thread` was doing in `[from, to)`, the innermost span counting; + /// the newest part first. + fn doing(&self, thread: u32, from: u64, to: u64, out: &mut Vec) { + if from >= to { + return; + } + let none = Vec::new(); + let spans = self.spans.get(&thread).unwrap_or(&none); + // The spans that touch it (a span is at most some frames long). + let end = spans.partition_point(|&i| self.events[i].t0 < to); + let touching: Vec<&Event> = + spans[..end].iter().map(|&i| &self.events[i]).filter(|e| e.t1 > from).collect(); + let mut edges: Vec = vec![from, to]; + for e in &touching { + edges.extend([e.t0, e.t1].iter().filter(|t| **t > from && **t < to)); + } + edges.sort_unstable(); + edges.dedup(); + let mut parts: Vec = Vec::new(); + for pair in edges.windows(2) { + let (a, b) = (pair[0], pair[1]); + let inner = touching.iter().filter(|e| e.t0 <= a && e.t1 >= b).max_by_key(|e| (e.t0, std::cmp::Reverse(e.t1))); + let cause = match inner { + Some(e) if e.kind == Kind::Calls => { + // Of a run of list calls, the part that was ours. + let ours = (b - a) * e.b.min(e.t1 - e.t0) / (e.t1 - e.t0).max(1); + parts.push(Part { + from: a, + to: a + ours, + thread, + cause: "recording: inside our list calls".into(), + }); + parts.push(Part { + from: a + ours, + to: b, + thread, + cause: "recording: between list calls (the caller's code)".into(), + }); + continue; + } + Some(e) if e.kind == Kind::Kernel => format!("kernel: {}", e.name), + Some(e) => e.name.to_string(), + None => OUTSIDE.into(), + }; + match parts.last_mut() { + Some(last) if last.cause == cause => last.to = b, + _ => parts.push(Part { from: a, to: b, thread, cause }), + } + } + out.extend(parts.into_iter().rev().filter(|p| p.from < p.to)); + } + + /// The chain that ended at `t` on `thread`, back to `until`: what that + /// thread did since its last wait ended, then what the thread that ended + /// the wait had done, or the card, and so on. Newest first, end to end. + pub(super) fn chain(&self, mut thread: u32, mut t: u64, until: u64) -> Vec { + let mut out = Vec::new(); + for _ in 0..200_000 { + if t <= until { + break; + } + let waits = self.waits.get(&thread).map_or(&[][..], |w| w); + let last = waits[..waits.partition_point(|w| w.t1 <= t)].last().filter(|w| w.t1 > until).copied(); + let Some(w) = last else { + self.doing(thread, until, t, &mut out); + break; + }; + self.doing(thread, w.t1, t, &mut out); + let name = self.events[w.event].name; + if w.fence != 0 && w.fence != COPY_QUEUE { + match self.card(w.fence, w.t1, until, &mut out) { + Some((sender, at)) if at < t => { + (thread, t) = (sender, at); + continue; + } + Some(_) => {} + None => break, + } + } + match self.waker(thread, &w) { + Some((other, at)) if at < t && w.fence == 0 => { + out.push(Part { + from: at.max(until), + to: w.t1, + thread, + cause: "woken, not running yet".into(), + }); + (thread, t) = (other, at); + } + _ => { + let cause = match w.fence { + 0 => format!("a wait nobody seen here ended ({name})"), + COPY_QUEUE => "the card's copy queue".into(), + _ => "the card (no times of it)".into(), + }; + out.push(Part { + from: w.t0.max(until), + to: w.t1, + thread, + cause, + }); + t = w.t0; + } + } + } + out.retain(|p| p.from < p.to); + out + } + + /// The card's part of a chain: it reached `fence` by `t`. Back through + /// the submissions that stood in its queue, to the sending of one that + /// found it idle: by whom, and when; `None` if that goes back before + /// `until`, or (nothing put in) if the card's times are not known. + fn card(&self, fence: u64, t: u64, until: u64, out: &mut Vec) -> Option<(u32, u64)> { + let mut i = self.runs.partition_point(|r| r.fence < fence); + let first = self.runs.get(i)?; + if first.on == (0, 0) || first.t0 >= t { + return Some((0, u64::MAX)); + } + let part = |from: u64, to: u64, cause: &str| Part { + from: from.max(until), + to: to.max(until), + thread: 0, + cause: cause.into(), + }; + let mut end = first.on.1.min(t); + out.push(part(end, t, "the card was done, the wait not over yet")); + loop { + let run = self.runs[i]; + let begun = run.on.0.clamp(run.t0.min(end), end); + out.push(part(begun, end, "the card running submissions")); + if begun <= until { + return None; + } + match i.checked_sub(1).map(|before| self.runs[before]) { + Some(before) if before.on != (0, 0) && before.on.1 >= run.t0 => { + let to = before.on.1.min(begun); + out.push(part(to, begun, "the card between submissions")); + end = to; + i -= 1; + if end <= until { + return None; + } + } + _ => { + let sent = run.t1.min(begun); + out.push(part(sent, begun, "sent, the card not started yet")); + return Some((run.thread, sent)); + } + } + } + } +} + +/// The cause of what a thread did outside every span. +const OUTSIDE: &str = "outside our spans"; + +fn ms(ticks: u64) -> f64 { + ticks as f64 * 1e3 / frequency() as f64 +} + +/// `parts` by cause, the largest first. +fn by_cause(parts: &[Part], label: &dyn Fn(u32) -> String) -> Vec<(String, u64)> { + let mut sums: BTreeMap = BTreeMap::new(); + for p in parts { + let cause = if p.cause == OUTSIDE { format!("{} on {}", p.cause, label(p.thread)) } else { p.cause.clone() }; + *sums.entry(cause).or_default() += p.to - p.from; + } + let mut sums: Vec<(String, u64)> = sums.into_iter().collect(); + sums.sort_by_key(|s| std::cmp::Reverse(s.1)); + sums +} + +/// The summary. +pub(super) fn summary(trace: &Trace, names: &mut Names, stacks: &[[usize; DEPTH]], before: &Threads, after: &Threads) -> String { + let mut text = String::new(); + let Some((&(start, _), &(stop, _))) = trace.frames.first().zip(trace.frames.last()) else { + return "no frames\n".into(); + }; + let frames = (trace.frames.len() - 1).max(1) as f64; + let mut labels: HashMap = HashMap::new(); + for (&id, (_, name, begun)) in after.all.iter().chain(before.all.iter()) { + labels.entry(id).or_insert_with(|| match name.is_empty() { + true => format!("{id} ({})", names.of(*begun + 1)), + false => format!("{id} \"{name}\""), + }); + } + let label = |id: u32| match id { + 0 => "the card".to_string(), + id => labels.get(&id).cloned().unwrap_or_else(|| id.to_string()), + }; + let _ = writeln!(text, "{} frames in {:.1} ms ({:.1} ms a frame); {} events", frames, ms(stop - start), ms(stop - start) / frames, trace.events.len()); + + // The chains. + let mut all: Vec = Vec::new(); + for pair in trace.frames.windows(2) { + let chain = trace.chain(pair[1].1, pair[1].0, pair[0].0); + let _ = writeln!(text, "\nframe of {:.1} ms, present on {}: the chain it came out of, by cause", ms(pair[1].0 - pair[0].0), label(pair[1].1)); + for (cause, sum) in by_cause(&chain, &label).into_iter().take(24) { + let _ = writeln!(text, " {:7.2} ms {cause}", ms(sum)); + } + all.extend(chain); + } + let whole = trace.chain(trace.frames.last().map_or(0, |f| f.1), stop, start); + let _ = writeln!(text, "\nthe chain back through all frames, per frame, by cause"); + for (cause, sum) in by_cause(&whole, &label).into_iter().take(40) { + let _ = writeln!(text, " {:7.2} ms {cause}", ms(sum) / frames); + } + let _ = writeln!(text, "\nby thread, per frame"); + let mut by_thread: BTreeMap = BTreeMap::new(); + for p in &whole { + *by_thread.entry(p.thread).or_default() += p.to - p.from; + } + let mut by_thread: Vec<(u32, u64)> = by_thread.into_iter().collect(); + by_thread.sort_by_key(|t| std::cmp::Reverse(t.1)); + for (thread, sum) in by_thread { + let _ = writeln!(text, " {:7.2} ms {}", ms(sum) / frames, label(thread)); + } + let _ = writeln!(text, "\nthat chain, oldest first (parts under 0.15 ms left out; ms since the first present)"); + for p in whole.iter().rev().filter(|p| ms(p.to - p.from) >= 0.15) { + let _ = writeln!(text, " {:8.2} +{:6.2} {:32} {}", ms(p.from - start), ms(p.to - p.from), label(p.thread), p.cause); + } + + // The card. + let runs: Vec<&Run> = trace.runs.iter().filter(|r| r.on != (0, 0) && r.on.1 > start && r.on.0 < stop).collect(); + let (mut busy, mut reach) = (0, start); + let mut idle: BTreeMap = BTreeMap::new(); + let mut idle_all = 0; + for r in &runs { + let (a, b) = (r.on.0.clamp(start, stop), r.on.1.clamp(start, stop)); + if a > reach { + idle_all += a - reach; + if r.t1 > reach { + for p in trace.chain(r.thread, r.t1.min(a), reach) { + let cause = if p.cause == OUTSIDE { format!("{} on {}", p.cause, label(p.thread)) } else { p.cause }; + *idle.entry(cause).or_default() += p.to - p.from; + } + } + } + busy += b.saturating_sub(a.max(reach)); + reach = reach.max(b); + } + let _ = writeln!( + text, + "\nthe card, per frame: {:.2} ms running {:.1} submissions, {:.2} ms idle between them; of the idle time, by what the chain to the \ + next submission was", + ms(busy) / frames, + runs.len() as f64 / frames, + ms(idle_all) / frames + ); + let mut idle: Vec<(String, u64)> = idle.into_iter().collect(); + idle.sort_by_key(|i| std::cmp::Reverse(i.1)); + for (cause, sum) in idle.into_iter().take(30) { + let _ = writeln!(text, " {:7.2} ms {cause}", ms(sum) / frames); + } + + // Threads. + let rate = (after.cycles.saturating_sub(before.cycles)) as f64 / ms(after.ticks.saturating_sub(before.ticks)).max(1e-9); + let mut threads: Vec<(u32, f64, u64)> = after + .all + .iter() + .map(|(&id, t)| { + let ran = t.0.saturating_sub(before.all.get(&id).map_or(0, |b| b.0)) as f64 / rate.max(1e-9); + let waits = trace.waits.get(&id).map_or(&[][..], |w| w); + let waited = waits.iter().map(|w| w.t1.min(stop).saturating_sub(w.t0.max(start))).sum(); + (id, ran, waited) + }) + .collect(); + threads.sort_by(|a, b| b.1.total_cmp(&a.1)); + let _ = writeln!(text, "\nthreads, per frame: running, waiting in what is wrapped, outermost spans of ours"); + for (id, ran, waited) in threads.into_iter().filter(|t| t.1 / frames >= 0.2).take(60) { + let mut sums: BTreeMap<&str, u64> = BTreeMap::new(); + let mut reach = 0; + for &i in trace.spans.get(&id).map_or(&[][..], |s| s) { + let e = &trace.events[i]; + if e.t1 > reach { + *sums.entry(e.name).or_default() += e.t1.min(stop).saturating_sub(e.t0.max(reach).max(start)); + reach = e.t1; + } + } + let mut sums: Vec<(&str, u64)> = sums.into_iter().collect(); + sums.sort_by_key(|s| std::cmp::Reverse(s.1)); + let spans: Vec = sums.iter().take(5).map(|(name, sum)| format!("{name} {:.1}", ms(*sum) / frames)).collect(); + let _ = writeln!(text, " {:6.1} ran {:6.1} waited {:36} {}", ran / frames, ms(waited) / frames, label(id), spans.join(", ")); + } + + // Spans, all threads, each by name with what lies in it. + let mut sums: BTreeMap<&str, (u64, u64, u64)> = BTreeMap::new(); + for e in trace.events.iter().filter(|e| matches!(e.kind, Kind::Span | Kind::Kernel | Kind::Sent) && e.t1 > start && e.t0 < stop) { + let s = sums.entry(e.name).or_default(); + let took = e.t1.min(stop) - e.t0.max(start); + *s = (s.0 + took, s.1 + 1, s.2.max(took)); + } + let mut sums: Vec<_> = sums.into_iter().collect(); + sums.sort_by_key(|s| std::cmp::Reverse(s.1.0)); + let _ = writeln!(text, "\nspans and kernel calls, all threads, per frame (a span counts what lies in it)"); + for (name, (sum, n, most)) in sums.into_iter().take(80) { + let _ = writeln!(text, " {:8.2} ms in {:8.1}, longest {:6.2} {name}", ms(sum) / frames, n as f64 / frames, ms(most)); + } + + // Waits: who, where, for whom. + let mut groups: HashMap<(u32, String, String), (u64, u64, u64)> = HashMap::new(); + for (&thread, waits) in &trace.waits { + for w in waits.iter().filter(|w| w.t1 > start && w.t0 < stop && ms(w.t1 - w.t0) >= 0.05) { + let e = &trace.events[w.event]; + let site = (e.stack as usize).checked_sub(1).and_then(|s| stacks.get(s)).map_or(String::new(), |s| names.site(s)); + let by = match (w.fence, self_waker(trace, thread, w)) { + (COPY_QUEUE, _) => "the card's copy queue".to_string(), + (0, Some((other, _))) => label(other), + (0, None) => "nobody seen".into(), + _ => "the card".into(), + }; + let g = groups.entry((thread, format!("{} at {site}", e.name), by)).or_default(); + let took = w.t1.min(stop) - w.t0.max(start); + *g = (g.0 + took, g.1 + 1, g.2.max(took)); + } + } + let mut groups: Vec<_> = groups.into_iter().collect(); + groups.sort_by_key(|g| std::cmp::Reverse(g.1.0)); + let _ = writeln!(text, "\nwaits of 50 us or more, per frame: who, what and where, who ended them"); + for ((thread, what, by), (sum, n, most)) in groups.into_iter().take(150) { + let _ = writeln!( + text, + " {:7.2} ms in {:7.1}, longest {:6.2} {} | {what} | ended by {by}", + ms(sum) / frames, + n as f64 / frames, + ms(most), + label(thread) + ); + } + + // Long list calls. + let mut calls: HashMap = HashMap::new(); + for e in trace.events.iter().filter(|e| e.name == "a long list call" && e.t1 > start && e.t0 < stop) { + let site = (e.stack as usize).checked_sub(1).and_then(|s| stacks.get(s)).map_or(String::new(), |s| names.site(s)); + let c = calls.entry(site).or_default(); + *c = (c.0 + (e.t1 - e.t0), c.1 + 1); + } + let mut calls: Vec<_> = calls.into_iter().collect(); + calls.sort_by_key(|c| std::cmp::Reverse(c.1.0)); + let _ = writeln!(text, "\nlist calls of 50 us or more, per frame"); + for (site, (sum, n)) in calls.into_iter().take(25) { + let _ = writeln!(text, " {:7.2} ms in {:7.1} {site}", ms(sum) / frames, n as f64 / frames); + } + text +} + +fn self_waker(trace: &Trace, thread: u32, w: &Wait) -> Option<(u32, u64)> { + trace.waker(thread, w) +} + +fn escaped(text: &str) -> String { + text.chars() + .flat_map(|c| match c { + '"' => vec!['\\', '"'], + '\\' => vec!['\\', '\\'], + c if (c as u32) < 32 => vec![' '], + c => vec![c], + }) + .collect() +} + +/// The Chrome trace. +pub(super) fn chrome( + trace: &Trace, + names: &mut Names, + stacks: &[[usize; DEPTH]], + threads: &Threads, + out: &mut impl std::io::Write, +) -> std::io::Result<()> { + let start = trace.events.first().map_or(0, |e| e.t0); + let us = |t: u64| t.saturating_sub(start) as f64 * 1e6 / frequency() as f64; + write!(out, "{{\"traceEvents\":[\n{{\"ph\":\"M\",\"pid\":1,\"tid\":0,\"name\":\"thread_name\",\"args\":{{\"name\":\"the card\"}}}}")?; + for (id, (_, name, begun)) in &threads.all { + let name = if name.is_empty() { names.of(*begun + 1) } else { name.clone() }; + write!( + out, + ",\n{{\"ph\":\"M\",\"pid\":1,\"tid\":{id},\"name\":\"thread_name\",\"args\":{{\"name\":\"{}\"}}}}", + escaped(&name) + )?; + } + for e in &trace.events { + let (ts, dur) = (us(e.t0), us(e.t1) - us(e.t0)); + let (pid, tid, cpu) = (1, e.thread, e.cpu); + match e.kind { + Kind::Wake => {} + Kind::Told => write!( + out, + ",\n{{\"ph\":\"i\",\"s\":\"t\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"cat\":\"told\",\"name\":\"{}\",\"args\":{{\"at\":\"{:#x}\",\"value\":\"{:#x}\"}}}}", + escaped(e.name), + e.a, + e.b + )?, + Kind::Sample => { + let stack = (e.stack as usize).checked_sub(1).and_then(|s| stacks.get(s)).map_or(&[][..], |s| &s[..]); + let stack: Vec = stack.iter().take_while(|a| **a != 0).map(|a| format!("{a:#x}")).collect(); + write!( + out, + ",\n{{\"ph\":\"i\",\"s\":\"t\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"cat\":\"sample\",\"name\":\"{}\",\"args\":{{\"at\":\"{:#x}\",\"stack\":\"{}\"}}}}", + escaped(&names.of(e.a as usize)), + e.a, + stack.join(" ") + )?; + } + Kind::Frame => write!(out, ",\n{{\"ph\":\"i\",\"s\":\"g\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"name\":\"a frame ends\"}}")?, + Kind::Wait => { + let site = (e.stack as usize).checked_sub(1).and_then(|s| stacks.get(s)).map_or(String::new(), |s| names.site(s)); + write!( + out, + ",\n{{\"ph\":\"X\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"dur\":{dur:.1},\"cat\":\"wait\",\"cname\":\"grey\",\ + \"name\":\"wait\",\"args\":{{\"what\":\"{}\",\"object\":\"{:#x}\",\"fence\":\"{}\",\"at\":\"{}\"}}}}", + e.name, + e.a, + e.b, + escaped(&site) + )?; + } + _ => write!( + out, + ",\n{{\"ph\":\"X\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"dur\":{dur:.1},\"cat\":\"{:?}\",\"name\":\"{}\",\ + \"args\":{{\"a\":{},\"b\":{},\"cpu\":{cpu}}}}}", + e.kind, + escaped(e.name), + e.a, + e.b + )?, + } + } + for r in trace.runs.iter().filter(|r| r.on != (0, 0)) { + write!( + out, + ",\n{{\"ph\":\"X\",\"pid\":1,\"tid\":0,\"ts\":{:.1},\"dur\":{:.1},\"name\":\"submission {}\",\"args\":{{\"sent by\":{}}}}}", + us(r.on.0), + us(r.on.1) - us(r.on.0), + r.fence, + r.thread + )?; + } + // Who woke whom. + let mut id = 0u64; + for (&thread, waits) in &trace.waits { + for w in waits.iter().filter(|w| ms(w.t1 - w.t0) >= 0.1) { + if let Some((other, at)) = trace.waker(thread, w) { + id += 1; + write!( + out, + ",\n{{\"ph\":\"s\",\"pid\":1,\"tid\":{other},\"ts\":{:.1},\"id\":{id},\"cat\":\"wake\",\"name\":\"woke\"}},\ + \n{{\"ph\":\"f\",\"bp\":\"e\",\"pid\":1,\"tid\":{thread},\"ts\":{:.1},\"id\":{id},\"cat\":\"wake\",\"name\":\"woke\"}}", + us(at), + us(w.t1) + )?; + } + } + } + writeln!(out, "\n]}}") +} + +/// Writes both files. +pub(super) fn write(file: &std::path::Path, data: Data, before: &Threads, after: &Threads, stamps: Vec<(u64, u64)>) { + let mut names = Names::new(); + let (events, lost) = (data.events.len(), data.lost); + let trace = Trace::new(data.events, &stamps); + let mut text = summary(&trace, &mut names, &data.stacks, before, after); + if lost > 0 { + let _ = writeln!(text, "\n{lost} events were lost: the buffer was full"); + } + let beside = file.with_extension("txt"); + let written = std::fs::write(&beside, text).and_then(|()| { + let mut out = std::io::BufWriter::new(std::fs::File::create(file)?); + chrome(&trace, &mut names, &data.stacks, after, &mut out)?; + std::io::Write::flush(&mut out) + }); + match written { + Ok(()) => tracing::info!(file = %file.display(), summary = %beside.display(), events, lost, "the timeline is written"), + Err(e) => tracing::warn!(error = %e, file = %file.display(), "the timeline could not be written"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn event(kind: Kind, name: &'static str, thread: u32, t: (u64, u64), a: u64, b: u64) -> Event { + Event { + t0: t.0, + t1: t.1, + a, + b, + name, + thread, + stack: 0, + cpu: 0, + kind, + } + } + + fn causes(parts: &[Part]) -> Vec<(u32, u64, u64, &str)> { + parts.iter().map(|p| (p.thread, p.from, p.to, p.cause.as_str())).collect() + } + + /// The present's thread waited for the title's, which waited for the + /// relay, which waited for the card, whose submission a third thread + /// sent: the chain goes back through all of them, end to end. + #[test] + fn a_chain_goes_back_through_who_woke_whom_and_the_card() { + let events = vec![ + event(Kind::Frame, "present", 1, (1000, 1000), 0, 0), + event(Kind::Frame, "present", 1, (2000, 2000), 0, 0), + // Thread 1 presents after waiting for object 7. + event(Kind::Span, "present", 1, (1900, 2000), 0, 0), + event(Kind::Wait, "WaitForSingleObject", 1, (1100, 1850), 7, 0), + event(Kind::Wake, "SetEvent", 2, (1840, 1840), 7, 0), + // (An earlier wake of the same object, before the wait.) + event(Kind::Wake, "SetEvent", 9, (1050, 1050), 7, 0), + // Thread 2 landed flights after the card reached 12. + event(Kind::Span, "landing", 2, (1700, 1845), 0, 0), + event(Kind::Span, "merging", 2, (1750, 1800), 0, 0), + event(Kind::Wait, "WaitForSingleObject", 2, (1200, 1690), 99, 12), + // The card ran 11 and 12, both sent by thread 3; 11 found it idle. + event(Kind::Sent, "ExecuteCommandLists", 3, (1290, 1300), 11, 1), + event(Kind::Sent, "ExecuteCommandLists", 3, (1390, 1400), 12, 2), + event(Kind::Span, "steps", 3, (1100, 1290), 0, 0), + ]; + let trace = Trace::new(events, &[(1310, 1500), (1500, 1680)]); + let chain = trace.chain(1, 2000, 1000); + assert_eq!( + causes(&chain), + [ + (1, 1900, 2000, "present"), + (1, 1850, 1900, OUTSIDE), + (1, 1840, 1850, "woken, not running yet"), + (2, 1800, 1840, "landing"), + (2, 1750, 1800, "merging"), + (2, 1700, 1750, "landing"), + (2, 1690, 1700, OUTSIDE), + (0, 1680, 1690, "the card was done, the wait not over yet"), + (0, 1500, 1680, "the card running submissions"), + (0, 1310, 1500, "the card running submissions"), + (0, 1300, 1310, "sent, the card not started yet"), + (3, 1290, 1300, "ExecuteCommandLists"), + (3, 1100, 1290, "steps"), + (3, 1000, 1100, OUTSIDE), + ] + ); + // End to end: no part of the frame is missing or counted twice. + assert!(chain.windows(2).all(|p| p[0].from == p[1].to)); + } + + /// A wait nobody was seen to end (a timer) is a cause of its own, and + /// the chain goes on with the thread before it. + #[test] + fn a_wait_without_a_waker_stays_with_its_thread() { + let events = vec![ + event(Kind::Wait, "Sleep", 1, (120, 180), 0, 0), + event(Kind::Wait, "WaitOnAddress", 1, (20, 60), 5, 0), + event(Kind::Wake, "WakeByAddressSingle", 1, (50, 50), 5, 0), + ]; + let trace = Trace::new(events, &[]); + assert_eq!( + causes(&trace.chain(1, 200, 0)), + [ + (1, 180, 200, OUTSIDE), + (1, 120, 180, "a wait nobody seen here ended (Sleep)"), + (1, 60, 120, OUTSIDE), + (1, 20, 60, "a wait nobody seen here ended (WaitOnAddress)"), + (1, 0, 20, OUTSIDE), + ] + ); + } + + /// Real threads, real waits: what the wrappers record names who ended + /// them, and the chain leads to the thread that worked. + #[test] + fn real_waits_are_recorded_with_who_ended_them() { + use super::super::{hooks, record, span}; + use std::sync::{Arc, Condvar, Mutex}; + hooks::wrap_own(); + record::make_room(); + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let lock = Arc::new(Mutex::new(())); + record::begin(); + record::frame(); + let first = super::super::record::ticks(); + let worker = { + let (gate, lock) = (gate.clone(), lock.clone()); + std::thread::spawn(move || { + let held = lock.lock().unwrap(); + let working = span("the work of a test"); + std::thread::sleep(std::time::Duration::from_millis(5)); + let spun = std::time::Instant::now(); + while spun.elapsed().as_millis() < 30 { + std::hint::spin_loop(); + } + working.end(); + drop(held); + *gate.0.lock().unwrap() = true; + gate.1.notify_all(); + record::thread() + }) + }; + { + let mut open = gate.0.lock().unwrap(); + while !*open { + open = gate.1.wait(open).unwrap(); + } + } + let last = super::super::record::ticks(); + let me = record::thread(); + let other = worker.join().unwrap(); + // A contended lock. + let held = lock.lock().unwrap(); + let second = { + let lock = lock.clone(); + std::thread::spawn(move || { + drop(lock.lock().unwrap()); + record::thread() + }) + }; + std::thread::sleep(std::time::Duration::from_millis(20)); + drop(held); + let second = second.join().unwrap(); + let data = record::end(); + assert_eq!(data.lost, 0); + let trace = Trace::new(data.events, &[]); + let chain = trace.chain(me, last, first); + let work: u64 = chain.iter().filter(|p| p.thread == other && p.cause == "the work of a test").map(|p| p.to - p.from).sum(); + assert!(ms(work) >= 20.0, "{chain:?}"); + let contended = trace.waits[&second] + .iter() + .filter(|w| ms(w.t1 - w.t0) >= 10.0) + .find_map(|w| trace.waker(second, w)); + assert_eq!(contended.map(|c| c.0), Some(me)); + let mut names = Names::new(); + let sites: Vec = data.stacks.iter().map(|s| names.site(s)).collect(); + assert!(sites.iter().any(|s| s.contains("real_waits_are_recorded")), "{sites:?}"); + let mut json = Vec::new(); + chrome(&trace, &mut names, &data.stacks, &Threads::now(), &mut json).unwrap(); + assert!(json.starts_with(b"{\"traceEvents\"")); + let text = summary(&trace, &mut names, &data.stacks, &Threads::now(), &Threads::now()); + assert!(text.contains("frames in")); + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 94684f5..92c69e5 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -2123,6 +2123,7 @@ pub(crate) fn install() { EXCEPTION_POINTERS, }; unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 { + let _fault = crate::timeline::span("a fault looked at"); // SAFETY: the system passes the exception being dispatched. let r = unsafe { &*(*info).ExceptionRecord }; const READ: usize = 0; diff --git a/crates/victory-hle/src/host.rs b/crates/victory-hle/src/host.rs index 7300687..3c217d8 100644 --- a/crates/victory-hle/src/host.rs +++ b/crates/victory-hle/src/host.rs @@ -78,7 +78,13 @@ impl HostPolicy { if !self.allows(dll) { return None; } - imp::resolve(dll, symbol) + let address = imp::resolve(dll, symbol)?; + // With a timeline asked for, what threads wait with is wrapped. + #[cfg(all(windows, feature = "diagnostics"))] + if let ImportSymbol::Name { name, .. } = symbol { + return Some(victory_gpu::timeline::import(name, address)); + } + Some(address) } } diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 5d0a5f2..a44d599 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -774,7 +774,9 @@ fn work(scheduler: &'static Scheduler) { drop(lanes); let started = std::time::Instant::now(); let traced = Traced::start(&job); + let reading = victory_gpu::timeline::span("streaming: a request"); let result = execute(&job.request); + reading.end(); walls_request(&job.request, &result, started); stream_log::request(&job, started, &result); if let Some(traced) = traced { @@ -1341,6 +1343,7 @@ fn queue(this: QueueRef, command: Command) { /// the pages are mapped just before, also those under addresses without a /// list (memory only the CPU sees). extern "system" fn submit(this: QueueRef) { + let _called = victory_gpu::timeline::span("the title's DirectStorage Submit"); // SAFETY: as above. let id = unsafe { &*this }.state.id; let Some(scheduler) = scheduler() else { diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 4181edb..64920a8 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -1065,6 +1065,7 @@ pub extern "system" fn XMemMapPhysicalPages( // SAFETY: the title passes `n` page numbers, or null. 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 mut physical = physical(); if let Some(costed) = &mut costed { costed.waited = costed.started.elapsed().as_nanos() as u64; From a7e8c3509145f371ef0a6644b77aa2add504af70 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 08:09:33 -0600 Subject: [PATCH 357/445] A measurement: textures of new blocks read by lists sent before; the book knows a block again whose pointer something else had Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/book.rs | 51 +++++- crates/victory-gpu/src/indirect.rs | 285 +++++++++++++++++++++++++++++ 2 files changed, 334 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/book.rs b/crates/victory-gpu/src/book.rs index df3e9a9..b63f150 100644 --- a/crates/victory-gpu/src/book.rs +++ b/crates/victory-gpu/src/book.rs @@ -61,7 +61,15 @@ static BOOK: Mutex> = Mutex::new(None); /// Root descriptors given by address lately: time, address, bytes. static ROOTS: Mutex> = Mutex::new(VecDeque::new()); +/// Tests that want the book. +#[cfg(test)] +static FORCED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + pub(crate) fn on() -> bool { + #[cfg(test)] + if FORCED.load(Ordering::Relaxed) { + return true; + } static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| { std::env::var_os("VICTORY_BOOK").is_none_or(|v| v != "0") @@ -334,10 +342,15 @@ pub(crate) fn block(heap: &ID3D12Heap, resource: &ID3D12Resource, offset: u64, b let raw = heap.as_raw() as usize; let now = crate::host::now_ms(); let id = with(|b| { - if b.by_object.contains_key(&raw) { + let at = b.by_object.get(&(object.as_raw() as usize)).and_then(|id| b.live.get(id))?.start; + // Known, unless the entry is of what had the pointer before. + if b.by_object + .get(&raw) + .and_then(|id| b.live.get(id)) + .is_some_and(|e| at >= e.start && at - e.start < e.size) + { return None; } - let at = b.by_object.get(&(object.as_raw() as usize)).and_then(|id| b.live.get(id))?.start; Some(b.add(raw, at.checked_sub(offset)?, bytes, "a block of textures".into(), now)) }); if let Some(id) = id { @@ -652,6 +665,40 @@ mod tests { } /// Who has an address, and who had it, newest first. + /// A texture of the pool and its block stand in the book while they + /// live, and not after. + #[test] + fn a_pooled_texture_and_its_block_are_in_the_book() { + let Some(host) = crate::host::host() else { return }; + FORCED.store(true, Ordering::Relaxed); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT(83), + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + // SAFETY: a valid description. + let texture = unsafe { crate::pool::texture(&host.device, &desc, D3D12_RESOURCE_STATE_COMMON) }; + if let Some(texture) = texture { + let at = texture_address(&texture, &desc); + println!("address {at:x?}"); + if let Some(at) = at { + let names = || with(|b| b.holders(at).iter().map(|e| e.what.clone()).collect::>()); + let found = names(); + println!("held by {found:?}"); + assert!(found.iter().any(|n| n.contains("a texture in a block")), "{found:?}"); + assert!(found.iter().any(|n| n.contains("a block of textures")), "{found:?}"); + drop(texture); + assert!(!names().iter().any(|n| n.contains("a texture in a block"))); + } + } + FORCED.store(false, Ordering::Relaxed); + } + #[test] fn the_book_knows_what_is_gone() { let mut b = Book::default(); diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 5e4d335..4216c5f 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -1738,6 +1738,291 @@ void main(uint3 t : SV_DispatchThreadID) { } } + /// Whether lists on the card may read a texture of a block made after + /// they were sent, through a slot they read by index (ignored: a + /// measurement that loses the device, so each way runs in a process of + /// its own; `VICTORY_BENCH_S` seconds a way, 30; `VICTORY_BENCH_N` runs of + /// each, 3). Threads (`VICTORY_BENCH_THREADS`, 4) make blocks of 64 MiB, a texture in each and its + /// view, and copies the view into a slot; long dispatches that read all + /// the slots are always on the card. + #[test] + #[ignore] + fn new_blocks_under_readers() { + if let Ok(way) = std::env::var("VICTORY_BLOCK_WAY") { + return new_blocks(&way); + } + let times: u32 = std::env::var("VICTORY_BENCH_N").ok().and_then(|v| v.parse().ok()).unwrap_or(3); + // "never": never resident, what must lose the device. + for way in ["made", "waited", "enqueued", "never"] { + for n in 0..if way == "never" { 1 } else { times } { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["indirect::tests::new_blocks_under_readers", "--exact", "--ignored", "--nocapture"]) + .env("VICTORY_BLOCK_WAY", way) + .output() + .unwrap(); + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + let said = |what: &str| text.lines().find(|l| l.contains(what)).unwrap_or("(nothing said)").trim().to_owned(); + println!("{way}, run {n}: {}; {} (exit {:?})", said("dispatches a"), said("blocks,"), out.status.code()); + } + } + } + + fn new_blocks(way: &str) { + let Some(mut gpu) = WarpHarness::on(false) else { + println!("no card: 0 blocks,"); + return; + }; + const SLOTS: usize = 64; + const BLOCK: u64 = 64 << 20; + let seconds = std::env::var("VICTORY_BENCH_S").ok().and_then(|v| v.parse().ok()).unwrap_or(30u64); + const SOURCE: &str = r#" +#define RS "DescriptorTable(SRV(t0,numDescriptors=64,flags=DESCRIPTORS_VOLATILE|DATA_VOLATILE)), UAV(u0)" +Texture2D t[64] : register(t0); +RWByteAddressBuffer o : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { + uint which = g.x & 63; + float4 c = 0; + for (uint k = 0; k < 8; k++) + c += t[(which + k * 8) & 63].Load(int3((i + k * 13) & 127, (g.y + k * 29) & 255, 0)); + if (c.x < -1) o.Store(0, 1); +} +"#; + let pass = compile_cs(&gpu.device, SOURCE).expect("the pass must compile"); + // SAFETY: plain heap creation. + let heap = |visible: bool, n: u32| -> ID3D12DescriptorHeap { + unsafe { + gpu.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: n, + Flags: if visible { D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE } else { D3D12_DESCRIPTOR_HEAP_FLAG_NONE }, + NodeMask: 0, + }) + } + .unwrap() + }; + let (shown, beside) = (heap(true, SLOTS as u32), heap(false, 65)); + // SAFETY: live heaps. + let (to, from, step) = unsafe { + ( + shown.GetCPUDescriptorHandleForHeapStart().ptr, + beside.GetCPUDescriptorHandleForHeapStart().ptr, + gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize, + ) + }; + let null = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(28), + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() }, + }, + }; + let slot = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: to + i * step }; + let own = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from + i * step }; + // SAFETY: slots of our heaps. + unsafe { + gpu.device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&null), own(0)); + for i in 0..SLOTS { + gpu.device.CopyDescriptorsSimple(1, slot(i), own(0), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + } + } + let (_out, _, out_gpu) = gpu.shared_buffer(1 << 12); + // SAFETY: a live heap. + let table = unsafe { shown.GetGPUDescriptorHandleForHeapStart() }; + let list = |dispatches: u32| -> (ID3D12CommandAllocator, ID3D12GraphicsCommandList) { + // SAFETY: plain creation and recording. + unsafe { + let allocator: ID3D12CommandAllocator = + gpu.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = + gpu.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + list.SetDescriptorHeaps(&[Some(shown.clone())]); + list.SetComputeRootSignature(&pass.root); + list.SetPipelineState(&pass.pso); + list.SetComputeRootDescriptorTable(0, table); + list.SetComputeRootUnorderedAccessView(1, out_gpu); + for _ in 0..dispatches { + list.Dispatch(1024, 64, 1); + } + list.Close().unwrap(); + (allocator, list) + } + }; + // Lists of some 5 ms, always five sent: some run while a slot changes. + let mut sent = 0u64; + let mut dispatches = 8; + let ms = loop { + let one = list(dispatches); + let began = std::time::Instant::now(); + // SAFETY: a closed list of ours; waited for. + unsafe { + gpu.queue.ExecuteCommandLists(&[Some(one.1.cast().unwrap())]); + sent += 1; + gpu.queue.Signal(&gpu.fence, sent).unwrap(); + let _ = gpu.fence.SetEventOnCompletion(sent, gpu.event); + WaitForSingleObject(gpu.event, 10_000); + } + let ms = began.elapsed().as_secs_f64() * 1e3; + if ms >= 4.0 || dispatches >= 1 << 14 { + break ms; + } + dispatches *= 2; + }; + println!("{dispatches} dispatches a list, {ms:.1} ms each"); + let lists: Vec<_> = (0..6).map(|_| list(dispatches)).collect(); + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::SeqCst}; + let sent = AtomicU64::new(sent); + let stop = AtomicBool::new(false); + // Blocks; microseconds making a block, the longest; waiting, the longest. + let counts: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + let threads: usize = std::env::var("VICTORY_BENCH_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4); + let started = std::time::Instant::now(); + let lost = std::thread::scope(|scope| { + for thread in 0..threads { + let (device, fence) = (gpu.device.clone(), gpu.fence.clone()); + let (sent, stop, counts) = (&sent, &stop, &counts); + scope.spawn(move || { + // Slots of its own, and a staged view of its own. + let mine = SLOTS / threads; + let slot = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: to + (thread * mine + i) * step }; + let own = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from + i * step }; + let wait = way != "made"; + let mut alive: Vec<(ID3D12Heap, ID3D12Resource)> = Vec::new(); + let mut n = 0u64; + while !stop.load(SeqCst) { + // SAFETY: plain creation; slots of our heaps, this thread's. + unsafe { + let mut block: Option = None; + let flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES + | if wait { D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT } else { D3D12_HEAP_FLAG_NONE }; + let heap = D3D12_HEAP_DESC { + SizeInBytes: BLOCK, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: flags, + }; + let began = std::time::Instant::now(); + if device.CreateHeap(&heap, &mut block).is_err() { + break; + } + let us = began.elapsed().as_micros() as u64; + counts[1].fetch_add(us, SeqCst); + counts[2].fetch_max(us, SeqCst); + let block = block.unwrap(); + let pageable: ID3D12Pageable = block.cast().unwrap(); + let began = std::time::Instant::now(); + if way == "waited" && device.MakeResident(&[Some(pageable.clone())]).is_err() { + break; + } + if way == "enqueued" { + let device: ID3D12Device3 = device.cast().unwrap(); + let paged: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let asked = + device.EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, &[Some(pageable)], &paged, 1); + if asked.is_err() { + break; + } + while paged.GetCompletedValue() < 1 { + std::hint::spin_loop(); + } + } + let us = began.elapsed().as_micros() as u64; + counts[3].fetch_add(us, SeqCst); + counts[4].fetch_max(us, SeqCst); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT(28), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let mut texture: Option = None; + // Somewhere in the block, as the pool's pieces are. + let at = (n * 7 % 900) << 16; + if device + .CreatePlacedResource(&block, at, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut texture) + .is_err() + { + break; + } + let texture = texture.unwrap(); + let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + device.CreateShaderResourceView(&texture, None, own(1 + thread)); + device.CopyDescriptorsSimple(1, slot(n as usize % mine), own(1 + thread), kind); + alive.push((block, texture)); + n += 1; + counts[0].fetch_add(1, SeqCst); + if alive.len() >= 24 { + // Nothing shows or reads them any more when they go. + for i in 0..mine { + device.CopyDescriptorsSimple(1, slot(i), own(0), kind); + } + let until = sent.load(SeqCst) + 1; + while fence.GetCompletedValue() < until && !stop.load(SeqCst) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + if fence.GetCompletedValue() < until { + break; + } + alive.clear(); + } + } + } + // The lists sent last may read them: the process goes next. + std::mem::forget(alive); + }); + } + let lost = loop { + // SAFETY: closed lists of ours, each run again only when it has run. + unsafe { + let done = gpu.fence.GetCompletedValue(); + if done == u64::MAX || gpu.device.GetDeviceRemovedReason().is_err() { + break true; + } + while sent.load(SeqCst) < done + 5 { + let n = sent.load(SeqCst); + let list: ID3D12CommandList = lists[(n % 6) as usize].1.cast().unwrap(); + gpu.queue.ExecuteCommandLists(&[Some(list)]); + let _ = gpu.queue.Signal(&gpu.fence, n + 1); + sent.store(n + 1, SeqCst); + } + } + if started.elapsed().as_secs() >= seconds { + break false; + } + std::thread::sleep(std::time::Duration::from_micros(300)); + }; + stop.store(true, SeqCst); + lost + }); + let sent = sent.into_inner(); + let counts = counts.map(|c| c.into_inner()); + let blocks = counts[0]; + // SAFETY: a plain query. + let reason = unsafe { gpu.device.GetDeviceRemovedReason() }; + println!( + "{blocks} blocks, {sent} lists in {:.1} s; making {:.0} us a block, the longest {}; waiting {:.0} us, the longest {}; {}", + started.elapsed().as_secs_f64(), + counts[1] as f64 / blocks.max(1) as f64, + counts[2], + counts[3] as f64 / blocks.max(1) as f64, + counts[4], + if lost { format!("LOST: {reason:?}") } else { "the device lives".to_owned() } + ); + if !lost { + // SAFETY: waits for what was sent. + unsafe { + let _ = gpu.fence.SetEventOnCompletion(sent, gpu.event); + WaitForSingleObject(gpu.event, 10_000); + } + } + } + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { From a1bdba4cf9ce4c285c90d922108c3ffd8cc334fd Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 08:14:21 -0600 Subject: [PATCH 358/445] Recording: a lock a descriptor slot, a thread's own answers about buffers, tables left as they are when nothing changed Timeline waits-1 (dorm, 78 ms): the title's render thread stands 20 to 30 ms a frame at one recording job and the rest at others; recording is the critical path, and our list calls are 95 % of it. Profile waits-1, the five recording threads: 21 % contended locks, 11 % HostHeap::keep, 17 % readable, 7 % the look-up of buffers, 8 % clocks and counters of ours. VICTORY_QUICK_FIND=0 and VICTORY_READY_ONCE=0 go back; counters of the diagnostics by thread, a coarse clock for what is noted per texture and slot. VICTORY_AB=, turns switches on and off while the title runs. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/ab.rs | 13 ++- crates/victory-gpu/src/copystat.rs | 67 +++++++++---- crates/victory-gpu/src/descriptor/host.rs | 50 +++++----- crates/victory-gpu/src/draw.rs | 112 ++++++++++++++++++++-- crates/victory-gpu/src/host.rs | 84 ++++++++++++++-- crates/victory-gpu/src/host/place.rs | 1 + crates/victory-gpu/src/resource.rs | 18 +++- crates/victory-gpu/src/shadow.rs | 94 +++++++++++++++++- crates/victory-gpu/src/switch.rs | 27 ++++++ 9 files changed, 405 insertions(+), 61 deletions(-) diff --git a/crates/victory-gpu/src/ab.rs b/crates/victory-gpu/src/ab.rs index 1edc162..56922e4 100644 --- a/crates/victory-gpu/src/ab.rs +++ b/crates/victory-gpu/src/ab.rs @@ -31,8 +31,17 @@ static BITS: AtomicU32 = AtomicU32::new(0); /// Whether `switch` is on now, if it is one of those that change. pub(crate) fn pick(switch: &str) -> Option { - let n = asked()?.switches.iter().position(|s| s == switch)?; - Some(BITS.load(Relaxed) >> n & 1 != 0) + bit(switch).map(on) +} + +/// The number of `switch` among those that change. +pub(crate) fn bit(switch: &str) -> Option { + Some(asked()?.switches.iter().position(|s| s == switch)? as u32) +} + +/// Whether the switch of that number is on now. +pub(crate) fn on(bit: u32) -> bool { + BITS.load(Relaxed) >> bit & 1 != 0 } /// What the run has seen of the phase under way. diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index aebd018..484c90a 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -131,10 +131,39 @@ pub(crate) enum C { IndirectBounded, } const COUNTERS: usize = 80; -static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; +/// One of some sets of counters, each in lines of the processor's memory of +/// its own: a set for all threads had them wait for each other's lines at +/// every list call (what counts here is summed up for the log alone). +#[repr(align(64))] +struct Bank([AtomicU64; N]); + +/// The sets. +const BANKS: usize = 32; + +static COUNT: [Bank; BANKS] = [const { Bank([const { AtomicU64::new(0) }; COUNTERS]) }; BANKS]; + +/// This thread's set. +#[inline] +fn bank() -> usize { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + thread_local!(static MINE: std::cell::Cell = const { std::cell::Cell::new(usize::MAX) }); + // (Asked by the allocator too: nothing here allocates.) + MINE.try_with(|mine| { + if mine.get() == usize::MAX { + mine.set(NEXT.fetch_add(1, Relaxed) % BANKS); + } + mine.get() + }) + .unwrap_or(0) +} pub(crate) fn add(c: C, n: u64) { - COUNT[c as usize].fetch_add(n, Relaxed); + COUNT[bank()].0[c as usize].fetch_add(n, Relaxed); +} + +/// 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() } /// How copies run: 0 guarded (as always), 1 plain, 2 not at all. @@ -277,7 +306,13 @@ pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) { /// runtime and of the driver alike (3.5 GB in run 60's gameplay, growing by /// some 2 MB a frame, and nothing said whose): this says which part is /// ours. Bigger blocks are allocations of their own in the map. -static OWN: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; +static OWN: [Bank<8>; BANKS] = [const { Bank([const { AtomicU64::new(0) }; 8]) }; BANKS]; + +/// Count `i` of [`OWN`], all sets together (a block made by one thread and +/// released by another leaves one set below zero: the sum is right). +fn owned(i: usize) -> u64 { + OWN.iter().fold(0u64, |sum, b| sum.wrapping_add(b.0[i].load(Relaxed))) +} /// The class of [`OWN`] a block of `size` bytes counts in. fn block_class(size: usize) -> usize { @@ -291,12 +326,13 @@ fn block_class(size: usize) -> usize { fn own(size: usize, made: bool) { let class = block_class(size); + let own = &OWN[bank()].0; if made { - OWN[class].fetch_add(size as u64, Relaxed); - OWN[4 + class].fetch_add(1, Relaxed); + own[class].fetch_add(size as u64, Relaxed); + own[4 + class].fetch_add(1, Relaxed); } else { - OWN[class].fetch_sub(size as u64, Relaxed); - OWN[4 + class].fetch_sub(1, Relaxed); + own[class].fetch_sub(size as u64, Relaxed); + own[4 + class].fetch_sub(1, Relaxed); } } @@ -408,7 +444,7 @@ mod command_tests { #[cfg(test)] mod own_tests { - use super::{OWN, block_class}; + use super::{block_class, owned}; use std::sync::atomic::Ordering::Relaxed; #[test] @@ -446,10 +482,10 @@ mod own_tests { #[test] fn a_block_is_counted_while_it_lives() { let block = vec![1u8; 8 << 20]; - assert!(OWN[3].load(Relaxed) >= 8 << 20); - assert!(OWN[7].load(Relaxed) >= 1); + assert!(owned(3) >= 8 << 20); + assert!(owned(7) >= 1); drop(block); - assert!(OWN[7].load(Relaxed) < u64::MAX / 2, "no count below zero"); + assert!(owned(7) < u64::MAX / 2, "no count below zero"); } } @@ -815,7 +851,7 @@ fn log_memory() { let alive: Vec = crate::host::ALIVE.iter().map(|a| a.load(Relaxed)).collect(); let window = crate::shadow::window_use(); let views = crate::descriptor::views_kept(); - let own: Vec = OWN.iter().map(|o| o.load(Relaxed)).collect(); + let own: Vec = (0..8).map(owned).collect(); tracing::info!( "memory, what holds it: {} host lists alive; their scratch memory: {} chunks {:.0} MB, of them {} chunks {:.0} MB spare ({} taken from the spare ones so far); their other upload buffers: {} alive {:.0} MB; windows outside buffers (grid {} KiB): {:.0} MB of their pages ever copied, {} shown by descriptor slots {:.0} MB, {} held by lists or the pass over the heap {:.0} MB, {} asked for without a length {:.0} MB; buffer views of the heap whose slot showed another copy than the one brought up to date: {}; distinct views kept: {} ({} free) {:.0} MB; our own allocations: {:.0} MB in {} blocks (under 4 KiB {:.0} MB in {}, to 64 KiB {:.0} MB in {}, to 1 MiB {:.0} MB in {}, larger {:.0} MB in {})", alive[0], @@ -1095,15 +1131,12 @@ fn page_faults() -> u64 { /// second or more: a 4 s frame after an unlogged 4 s frame showed two /// frames' counts as one's). pub(crate) fn log(frames: f64) { - let counted = COUNT[C::Frames as usize].swap(0, Relaxed); + let counted = taken(C::Frames as usize); let frames = if counted > 0 { counted as f64 } else { frames }; static FAULTS: AtomicU64 = AtomicU64::new(0); let faults = page_faults(); let faults = faults - FAULTS.swap(faults, Relaxed).min(faults); - let c: Vec = COUNT - .iter() - .map(|a| a.swap(0, Relaxed) as f64 / frames) - .collect(); + let c: Vec = (0..COUNTERS).map(|i| taken(i) as f64 / frames).collect(); let mb = |v: f64| v / 1e6; let ms = |v: f64| v / 1e3; tracing::info!( diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 2597d45..be54253 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -52,7 +52,11 @@ pub(crate) struct HostHeap { /// index heaps directly, so a slot the title has not rewritten since it /// released the resource may still be read, and a freed host resource /// read there is a GPU page fault (the console reads stale memory). - kept: Mutex>>, + /// + /// A lock for each slot: one for the heap was what the recording threads + /// waited for most (5.6 % of their time, profile waits-1: each descriptor + /// made for a draw takes it, and lets go of what the slot held under it). + kept: Box<[Mutex>]>, /// Where the search for free dynamic slots starts, and which are taken /// (by lists not yet reset). next: Mutex<(u32, Vec)>, @@ -982,7 +986,7 @@ pub(crate) fn slot_story(slot: u32) -> String { if let Some(at) = host.written.get(slot as usize) { text.push_str(&format!(", written last at {:.1} s", f64::from(at.load(Relaxed)) / 1e3)); } - let kept = host.kept.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize).cloned().flatten(); + let kept = host.kept_in(index); match kept { None => text.push_str(", holds nothing"), Some(resource) => { @@ -1249,7 +1253,7 @@ impl HostHeap { copied: Mutex::new(Vec::new()), waiting: Mutex::default(), away: Mutex::default(), - kept: Mutex::new(vec![None; (count + extra) as usize]), + kept: (0..count + extra).map(|_| Mutex::new(None)).collect(), next: Mutex::new((0, vec![false; extra as usize])), free: std::sync::atomic::AtomicU32::new(extra), too_long: std::sync::atomic::AtomicU32::new(u32::MAX), @@ -1644,12 +1648,7 @@ impl HostHeap { // 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 - .lock() - .unwrap_or_else(|e| e.into_inner()) - .get(index as usize) - .is_some_and(Option::is_some) + && self.kept_in(index).is_some() } /// Levels on demand (`crate::tiles`): makes again the host slots of the @@ -2171,21 +2170,30 @@ impl HostHeap { /// Slot `index` now views `resource` (or nothing of the host's). fn keep(&self, index: u32, resource: Option) { - let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(slot) = kept.get_mut(index as usize) { + let Some(slot) = self.kept.get(index as usize) else { + return; + }; + let old = { use windows::core::Interface; + let mut slot = slot.lock().unwrap_or_else(|e| e.into_inner()); // The same again: nothing to retire. if slot.as_ref().map(Interface::as_raw) == resource.as_ref().map(Interface::as_raw) { return; } - // A running submission may still read the old resource through - // this slot. - if let Some(old) = std::mem::replace(slot, resource) { - crate::host::retire(old); - } + std::mem::replace(&mut *slot, resource) + }; + // A running submission may still read the old resource through + // this slot. + if let Some(old) = old { + crate::host::retire_resource(old); } } + /// What slot `index` views. + fn kept_in(&self, index: u32) -> Option { + self.kept.get(index as usize)?.lock().unwrap_or_else(|e| e.into_inner()).clone() + } + /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes /// of `buffer` from byte `offset` (a multiple of 16): a root SRV with a /// size, whose reads past it return zeros instead of reaching whatever @@ -2371,7 +2379,7 @@ impl HostHeap { fn copy_to(&self, to: u32, which: u32) { #[cfg(feature = "diagnostics")] if let Some(written) = self.written.get(to as usize) { - written.store(crate::host::now_ms() as u32, std::sync::atomic::Ordering::Relaxed); + written.store(crate::host::coarse_ms() as u32, std::sync::atomic::Ordering::Relaxed); } let (Some(from), Some(host)) = (staged(self.sampler, which), host()) else { return; // made in place @@ -2593,9 +2601,8 @@ impl HostHeap { /// that is brought up to date for it). #[cfg(feature = "diagnostics")] pub(crate) fn shows(&self, index: u32, buffer: &ID3D12Resource) -> Option { - let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); - let shown = kept.get(index as usize)?.as_ref()?; - Some(windows::core::Interface::as_raw(shown) == windows::core::Interface::as_raw(buffer)) + let shown = self.kept_in(index)?; + Some(windows::core::Interface::as_raw(&shown) == windows::core::Interface::as_raw(buffer)) } /// What the queue of textures picked by index knows of title slot @@ -3060,8 +3067,7 @@ fn buffer_srv( } let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); let raw = buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; - // SAFETY: a live buffer. - let width = unsafe { shadow.buffer.GetDesc() }.Width; + let width = shadow.width(); if !buffer_view_ok(desc.Format, first, count, stride, raw, width) { REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); once!( diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index f082efe..24a8d87 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -328,7 +328,7 @@ pub(crate) struct State { host_heaps: [usize; 2], /// Tables made afresh in this list: (table, slot count, contents) → first /// dynamic slot. - fresh_tables: std::collections::HashMap<(u64, u32, u64), u32>, + fresh_tables: std::collections::HashMap<(u64, u32, u64), FreshTable, std::hash::BuildHasherDefault>, /// The dynamic slots the list holds: title heap, first, count; given /// back when the list has run, is reset or released. dynamic: Vec<(usize, u32, u32)>, @@ -3021,16 +3021,33 @@ impl State { } // The table and what its entries hold (record words). let key = { - use std::hash::{Hash, Hasher}; - let mut h = std::collections::hash_map::DefaultHasher::new(); + let mut h = RecordHash::default(); for k in 0..n { let at = table + u64::from(k) * 32; // SAFETY: a descriptor slot in title memory. - unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h); + h.add(unsafe { (at as *const [u32; 3]).read_unaligned() }); } - (table, n, h.finish()) + (table, n, h.0) }; - if let Some(&first) = self.fresh_tables.get(&key) { + // Who reads of it, and as what, as far as [`readable`] goes by it. + let reader = (used.as_ptr() as usize, used.len(), STORES.get(), TESTED_DEPTH.get().0); + if let Some(known) = self.fresh_tables.get_mut(&key) { + let first = known.first; + // This reader had it brought up to date, and nothing in the + // list changed since: nothing to do again. + let once = ready_once() && selected.is_empty() && entries.iter().all(|u| u.kind != ResourceType::Uav); + if once + && known.epoch == list.epoch() + && let Some((_, depth)) = known.ready.iter().find(|(r, _)| *r == reader) + { + if *depth { + TESTED_DEPTH.set((reader.3, true)); + } + made.push((slot, first * 32)); + continue; + } + let depth_before = TESTED_DEPTH.get(); + TESTED_DEPTH.set((depth_before.0, false)); for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { let handle = table + u64::from(u.table_offset_dwords) * 4; if let Some(view) = crate::descriptor::view(handle) { @@ -3048,6 +3065,20 @@ impl State { readable(list, kind, &view); } } + let depth = TESTED_DEPTH.get().1; + TESTED_DEPTH.set((depth_before.0, depth_before.1 || depth)); + if once && let Some(known) = self.fresh_tables.get_mut(&key) { + // (The epoch as it is now: what this changed itself it + // need not do again.) + let epoch = list.epoch(); + if known.epoch != epoch { + known.epoch = epoch; + known.ready.clear(); + } + if known.ready.len() < 16 { + known.ready.push((reader, depth)); + } + } made.push((slot, first * 32)); continue; } @@ -3057,7 +3088,7 @@ impl State { made.push((slot, u32::MAX)); continue; }; - self.fresh_tables.insert(key, first); + self.fresh_tables.insert(key, FreshTable { first, epoch: 0, ready: Vec::new() }); self.dynamic .push((std::ptr::from_ref(heap) as usize, first, n)); // The title's own slots of this table: what the draw reads of @@ -3708,6 +3739,41 @@ fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_ } } +/// A table made afresh in dynamic slots, in a list ([`State::tables`]). +struct FreshTable { + first: u32, + /// The list's epoch ([`HostList::epoch`]) at which all its entries that + /// these readers (a stage's list of what it reads, whether it stores, the + /// tested depth target) read were brought up to date, and whether that read the + /// tested depth target. + epoch: u64, + ready: Vec<((usize, usize, bool, usize), bool)>, +} + +/// Whether a table a list reads again, with nothing changed in the list +/// since, is left as it is (`VICTORY_READY_ONCE=0`: every entry is gone +/// through again at every draw). +fn ready_once() -> bool { + crate::toggled!("VICTORY_READY_ONCE") +} + +/// A hash of records' words: 64 bits, two multiplications a record. (The +/// standard library's took 3 % of the recording threads' time.) +#[derive(Default)] +struct RecordHash(u64); + +impl RecordHash { + fn add(&mut self, [a, b, c]: [u32; 3]) { + let fold = |x: u64, y: u64| { + let p = u128::from(x) * u128::from(y); + p as u64 ^ (p >> 64) as u64 + }; + let words = u64::from(a) << 32 | u64::from(b); + let first = fold(self.0 ^ words ^ 0x2d35_8dcc_aa6c_78a5, 0x8bb8_4b93_962e_acc9 ^ u64::from(c)); + self.0 = fold(first ^ 0x4b33_a62e_d433_d4a3, 0x4d5a_2da5_1de1_aa47 ^ self.0.rotate_left(23)) ^ first; + } +} + fn readable(list: &HostList, kind: ResourceType, view: &View) { const UNORDERED_ACCESS: u32 = 0x8; let placed = crate::descriptor::host::placed_texture(view); @@ -3763,7 +3829,9 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) { }; crate::list::ensure_state(list, *resource as This, state); #[cfg(feature = "diagnostics")] - if let Some(t) = crate::resource::host_resource(*resource as This) { + if tracing::enabled!(tracing::Level::DEBUG) + && let Some(t) = crate::resource::host_resource(*resource as This) + { // SAFETY: a live resource. let d = unsafe { t.GetDesc() }; if d.Flags.0 & 7 == 0 { @@ -4012,3 +4080,31 @@ mod tests { assert_eq!(staging_budget_per_frame(Some(32 * GIB)), 384 * MIB); } } + +#[cfg(test)] +mod record_hash_tests { + use super::RecordHash; + + #[test] + fn records_that_differ_hash_apart() { + let of = |records: &[[u32; 3]]| { + let mut h = RecordHash::default(); + records.iter().for_each(|r| h.add(*r)); + h.0 + }; + let mut seen = std::collections::HashSet::new(); + // One record, one word or two of it different; runs of zeros; order. + for a in 0..64u32 { + for b in 0..64u32 { + for c in [0, 1, 0x8000_0000, u32::MAX] { + assert!(seen.insert(of(&[[a, b, c]]))); + assert!(seen.insert(of(&[[1, 2, 3], [a, b, c]]))); + assert!(seen.insert(of(&[[a, b, c], [1, 2, 3], [0, 0, 0]]))); + } + } + } + assert!(seen.insert(of(&[]))); + let zeros: Vec = (1..100).map(|n| of(&vec![[0; 3]; n])).collect(); + assert!(zeros.iter().all(|h| seen.insert(*h))); + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 27c440e..0a03742 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -77,7 +77,12 @@ static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// A retired object, dropped on whatever thread finishes the submission. -struct Retired(#[allow(dead_code)] Box); +#[allow(dead_code)] +enum Retired { + Any(Box), + /// What a descriptor slot showed: 20,000 a frame, without a box each. + Resource(ID3D12Resource), +} // SAFETY: what is retired is D3D12 objects (free-threaded) and the // reference-counted wrappers holding them, dropped once. unsafe impl Send for Retired {} @@ -88,12 +93,24 @@ pub(crate) fn now_ms() -> u64 { EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 } +/// [`now_ms`] to the system's tick (16 ms): a few nanoseconds, where the +/// performance counter's are 25. For what is noted tens of thousands of +/// times a frame and read in tenths of a second. +pub(crate) fn coarse_ms() -> u64 { + use windows_sys::Win32::System::SystemInformation::GetTickCount64; + // The same beginning as `now_ms`. + static BEGAN: OnceLock = OnceLock::new(); + // SAFETY: a plain query. + let now = unsafe { GetTickCount64() }; + now.saturating_sub(*BEGAN.get_or_init(|| now.saturating_sub(now_ms()))) +} + /// This moment, for telling later how long ago it was ([`long_ago`]): the /// frames begun so far (high half, `crate::frame::current`) and tenths of a /// second since the start. Host copies of title memory, staging buffers and /// host textures note when they were last used with it. pub(crate) fn moment() -> u64 { - (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff) + (crate::frame::current() << 32) | ((coarse_ms() / 100) & 0xffff_ffff) } /// Whether `moment` lies at least `ms` milliseconds and `frames` frames @@ -299,7 +316,20 @@ pub(crate) fn retire(object: T) { RETIRED .lock() .unwrap_or_else(|e| e.into_inner()) - .push_back((started, Retired(Box::new(object)))); + .push_back((started, Retired::Any(Box::new(object)))); +} + +/// [`retire`] for a resource. +pub(crate) fn retire_resource(object: ID3D12Resource) { + let queued = crate::queue::queued(); + let started = STARTED.load(Ordering::Acquire) + queued; + if bury_lag() == 0 && started <= FINISHED.load(Ordering::Acquire) { + RETIREMENTS[0].fetch_add(1, Ordering::Relaxed); + drop(object); + return; + } + RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); + RETIRED.lock().unwrap_or_else(|e| e.into_inner()).push_back((started, Retired::Resource(object))); } /// How many submissions later than it could (the last one that may use it @@ -992,6 +1022,10 @@ pub(crate) struct HostList { /// Refreshes of host copies that a thread of ours is still finding, and /// where among the list's steps they belong ([`aside`]). coming: Mutex)>>, + /// Another number each time something changes that what a draw reads + /// depends on ([`HostList::changed_something`]); no two lists have the + /// same. + epoch: std::sync::atomic::AtomicU64, /// Counts the list in [`ALIVE`] while it lives. _alive: Counted, /// The texts of the markers `note_op` set, in order (for device-removed @@ -1993,7 +2027,7 @@ struct Deferred { kept: Vec, /// Buffer ranges refreshed since the last title copy (host copy, /// address, bytes): refreshing them again would find the same bytes. - refreshed: std::collections::HashSet<(usize, usize, usize)>, + refreshed: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet, /// Bottom-of-pipe writes, done once the list has run: address, what, @@ -3698,6 +3732,7 @@ impl Host { indirect_args: Mutex::default(), batch_args: Mutex::default(), coming: Mutex::default(), + epoch: std::sync::atomic::AtomicU64::new(next_epoch()), _alive: Counted::new(), #[cfg(feature = "diagnostics")] notes, @@ -5753,6 +5788,7 @@ impl HostList { /// Only after the list's last submission finished (every one is waited /// for). pub(crate) fn reset(&self) { + self.changed_something(); #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); let _resetting = crate::timeline::span("resetting a host list"); @@ -5788,6 +5824,18 @@ impl HostList { crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64); } + /// Something changed in this list that bringing a draw's textures and + /// buffers up to date depends on: a texture's state, a twin, what was + /// refreshed. + pub(crate) fn changed_something(&self) { + self.epoch.store(next_epoch(), Ordering::Relaxed); + } + + /// See [`HostList::changed_something`]. + pub(crate) fn epoch(&self) -> u64 { + self.epoch.load(Ordering::Relaxed) + } + /// Moves a title texture's host copy to `wanted` (a host state) in this /// list: the host texture and the state it leaves, if that is a change. /// The list's first use of a texture records nothing: its prelude brings @@ -5801,15 +5849,19 @@ impl HostList { // SAFETY: as in `crate::resource::host_resource`; the list's states // hold the copy from here on. let texture: &'static ID3D12Resource = unsafe { &*std::ptr::from_ref(©.texture) }; - let wanted = legal_state(texture, wanted); + let wanted = legal_for(copy.flags(), wanted); let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); match states.entry(std::sync::Arc::as_ptr(©) as usize) { std::collections::hash_map::Entry::Vacant(v) => { v.insert((wanted, wanted, copy)); + self.changed_something(); None } std::collections::hash_map::Entry::Occupied(mut o) => { let before = std::mem::replace(&mut o.get_mut().1, wanted); + if before != wanted { + self.changed_something(); + } (before != wanted).then_some((texture, before)) } } @@ -5820,7 +5872,8 @@ impl HostList { /// records the barrier: for textures that are not a title resource's /// host copy (colour twins) and for the copies between the two. fn settle(&self, copy: &std::sync::Arc, wanted: u32) { - let wanted = legal_state(©.texture, wanted); + let wanted = legal_for(copy.flags(), wanted); + self.changed_something(); let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) { std::collections::hash_map::Entry::Vacant(v) => { @@ -5884,6 +5937,7 @@ impl HostList { writing: false, late: false, }); + let was = (u.needs, u.behind, u.writing); let copy = match u.behind[side] { Some(behind) => behind, None => { @@ -5900,6 +5954,9 @@ impl HostList { (true, false) => u.behind[1] = Some(true), (false, _) => {} } + if was != (u.needs, u.behind, u.writing) || copy || colour { + self.changed_something(); + } // shortcut: the depth plane's twin is not drawn into the plane // here: the pass sets a pipeline and a target of ours, which a list // still recording the title's commands cannot take. This use sees @@ -6005,6 +6062,7 @@ impl HostList { for u in twins.values_mut().filter(|u| u.writing) { u.writing = false; u.behind[0] = Some(true); + self.changed_something(); } } @@ -6214,6 +6272,7 @@ impl HostList { .copies .push(Step::Copy(dst as usize, src as usize, len)); deferred.refreshed.clear(); + self.changed_something(); } /// Copies `len` bytes of title memory at `src` into the list's upload @@ -6596,6 +6655,7 @@ impl HostList { pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) { self.deferred().copies.push(Step::Run(Box::new(work))); self.deferred().refreshed.clear(); + self.changed_something(); } /// As [`HostList::defer`], for work that writes only host memory. @@ -6750,6 +6810,12 @@ impl HostList { } } +/// The numbers of [`HostList::epoch`]. +fn next_epoch() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) +} + /// A table by a copy's address. pub(crate) type ByCopy = std::collections::HashMap>; @@ -6772,6 +6838,12 @@ impl std::hash::Hasher for AddressHash { let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15); self.0 = h ^ (h >> 32); } + fn write_u64(&mut self, n: u64) { + self.write_usize(n as usize); + } + fn write_u32(&mut self, n: u32) { + self.write_usize(n as usize); + } } /// Since the last frame-rate line, nanoseconds of the submitting thread's diff --git a/crates/victory-gpu/src/host/place.rs b/crates/victory-gpu/src/host/place.rs index 7d494e0..cde0149 100644 --- a/crates/victory-gpu/src/host/place.rs +++ b/crates/victory-gpu/src/host/place.rs @@ -256,6 +256,7 @@ impl HostList { from: scratch.map(|s| s.2 as usize), })); deferred.refreshed.clear(); + self.changed_something(); true } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index c524ba1..d718073 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1175,6 +1175,9 @@ 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, + /// The texture's flags (asked once: the runtime takes 100 ns to say, and + /// every texture of every draw is asked about). + flags: u32, } /// What a host copy was filled with last: the first level of it and the @@ -1625,7 +1628,10 @@ fn hosted(this: This, make: bool) -> Option { // are made before the next submission runs. crate::descriptor::texture_made(this as usize); } - r.host.used.store(crate::host::moment(), Relaxed); + let now = crate::host::moment(); + if r.host.used.load(Relaxed) != now { + r.host.used.store(now, Relaxed); + } made.clone() } @@ -2266,9 +2272,15 @@ fn host_bytes(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource) -> #[cfg(windows)] impl HostTexture { + pub(crate) fn flags(&self) -> u32 { + self.flags + } + fn new(texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32) -> HostTexture { use std::sync::atomic::Ordering::Relaxed; let bytes = host_bytes(&texture); + // SAFETY: a live texture. + let flags = unsafe { texture.GetDesc() }.Flags.0 as u32; HOST_TEXTURES[0].fetch_add(1, Relaxed); HOST_TEXTURES[1].fetch_add(bytes, Relaxed); HostTexture { @@ -2281,6 +2293,7 @@ impl HostTexture { serial: SERIAL.fetch_add(1, Relaxed) + 1, grown: Default::default(), holds: Default::default(), + flags, } } @@ -2292,6 +2305,8 @@ impl HostTexture { tiled: crate::tiles::Tiled, ) -> HostTexture { HOST_TEXTURES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + // SAFETY: a live texture. + let flags = unsafe { texture.GetDesc() }.Flags.0 as u32; HostTexture { texture, state: std::sync::atomic::AtomicU32::new(state), @@ -2302,6 +2317,7 @@ impl HostTexture { serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1, grown: Default::default(), holds: Default::default(), + flags, } } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index b1675ad..d7055a9 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -26,6 +26,8 @@ use crate::watch::PAGE; /// A title buffer's host copy. pub(crate) struct Shadow { + /// The bytes of `buffer`. + width: u64, pub(crate) buffer: ID3D12Resource, data: *mut u8, gpu: u64, @@ -2741,11 +2743,19 @@ impl Shadow { list.defer_refresh(self, address as usize, len as usize); } + /// The bytes of the host buffer. + pub(crate) fn width(&self) -> u64 { + self.width + } + fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Shadow { + // SAFETY: a live buffer. + let width = unsafe { buffer.GetDesc() }.Width; let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64; LIVE[0].fetch_add(1, Ordering::Relaxed); LIVE[1].fetch_add(len, Ordering::Relaxed); Shadow { + width, buffer, data, gpu, @@ -4378,7 +4388,63 @@ struct Entry { static BUFFERS: std::sync::RwLock> = std::sync::RwLock::new(BTreeMap::new()); fn buffers() -> std::sync::RwLockWriteGuard<'static, BTreeMap<(u64, usize), Entry>> { - BUFFERS.write().unwrap_or_else(|e| e.into_inner()) + let map = BUFFERS.write().unwrap_or_else(|e| e.into_inner()); + // What threads remember of it ([`FOUND`]) is of before. + BUFFERS_CHANGED.fetch_add(1, Ordering::SeqCst); + map +} + +/// How often [`BUFFERS`] was taken to be changed. +static BUFFERS_CHANGED: AtomicU64 = AtomicU64::new(1); + +/// Answers a thread remembers. +const FOUND_MOST: usize = 1024; + +/// An ask (address, bytes), the count of changes it was answered at, and the +/// answer. +type Found = (u64, u64, u64, std::sync::Weak); + +thread_local! { + /// The last answers of [`lookup`] out of [`BUFFERS`], by a hash of the + /// ask: the same buffers are asked about draw after draw, from five + /// threads, each time through the map's lock and a dozen of its nodes + /// (7 % of the recording threads' time, profile waits-1). + static FOUND: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Whether [`FOUND`] is kept (`VICTORY_QUICK_FIND=0`: not). +fn quick_find() -> bool { + crate::toggled!("VICTORY_QUICK_FIND") +} + +fn found_at(address: u64, len: u64) -> usize { + let h = (address ^ len.rotate_left(32)).wrapping_mul(0x9E37_79B9_7F4A_7C15); + (h >> 54) as usize % FOUND_MOST +} + +/// What this thread remembers of an ask, if nothing changed since. +fn found(address: u64, len: u64) -> Option> { + let changed = BUFFERS_CHANGED.load(Ordering::SeqCst); + let shadow = FOUND.with(|f| { + let f = f.borrow(); + let (a, n, at, shadow) = f.get(found_at(address, len))?; + ((*a, *n, *at) == (address, len, changed)).then(|| shadow.upgrade()).flatten() + })?; + // Whoever takes the map to let a copy go that nobody holds finds it held + // now, or had counted before: then it is not handed out. + std::sync::atomic::fence(Ordering::SeqCst); + (BUFFERS_CHANGED.load(Ordering::SeqCst) == changed).then_some(shadow) +} + +/// Remembers an answer given while `changed` was the count. +fn remember(address: u64, len: u64, changed: u64, shadow: &Arc) { + FOUND.with(|f| { + let mut f = f.borrow_mut(); + if f.is_empty() { + f.resize_with(FOUND_MOST, || (0, 0, 0, std::sync::Weak::new())); + } + f[found_at(address, len)] = (address, len, changed, Arc::downgrade(shadow)); + }); } fn buffers_read() -> std::sync::RwLockReadGuard<'static, BTreeMap<(u64, usize), Entry>> { @@ -4494,12 +4560,22 @@ pub(crate) fn peek(address: u64, len: u64) -> Option> { } fn lookup(address: u64, len: u64, any: bool) -> Option> { + let quick = quick_find(); + if quick && let Some(shadow) = found(address, len) { + return Some(shadow); + } let end = address.checked_add(len.max(1))?; { let map = buffers_read(); match map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end) { // The copy is made already (nearly always). - Some((_, Entry { shadow: Some(shadow), .. })) => return Some(shadow.clone()), + Some((_, Entry { shadow: Some(shadow), .. })) => { + if quick { + // (Nobody changes the map while this lock is held.) + remember(address, len, BUFFERS_CHANGED.load(Ordering::SeqCst), shadow); + } + return Some(shadow.clone()); + } Some(_) => {} None => { drop(map); @@ -4794,9 +4870,17 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option address { + shadow.asked[0].fetch_min(address, Ordering::Relaxed); + } + if shadow.asked[1].load(Ordering::Relaxed) < end { + shadow.asked[1].fetch_max(end, Ordering::Relaxed); + } if unsized_ask { shadow.unsized_asks.fetch_add(1, Ordering::Relaxed); } diff --git a/crates/victory-gpu/src/switch.rs b/crates/victory-gpu/src/switch.rs index f3ea9b9..b5ef277 100644 --- a/crates/victory-gpu/src/switch.rs +++ b/crates/victory-gpu/src/switch.rs @@ -15,6 +15,33 @@ pub(crate) fn on(name: &str) -> bool { value_is_on(std::env::var_os(name).as_deref()) } +/// A switch that is on unless its variable is `0`, read once; with +/// `VICTORY_AB` naming it (diagnostics builds, `crate::ab`), on and off while +/// the title runs. +#[cfg(windows)] +#[macro_export] +#[doc(hidden)] +macro_rules! toggled { + ($name:literal) => {{ + #[cfg(feature = "diagnostics")] + { + static BIT: std::sync::OnceLock> = std::sync::OnceLock::new(); + match BIT.get_or_init(|| match $crate::ab::bit($name) { + Some(bit) => Err(bit), + None => Ok(std::env::var_os($name).is_none_or(|v| v != "0")), + }) { + Ok(on) => *on, + Err(bit) => $crate::ab::on(*bit), + } + } + #[cfg(not(feature = "diagnostics"))] + { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os($name).is_none_or(|v| v != "0")) + } + }}; +} + #[cfg(test)] mod tests { use super::value_is_on; From f1d3eb2b644734a04e4bae8f8885e05caecf2ef9 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 08:23:19 -0600 Subject: [PATCH 359/445] New card memory is waited for until a queue of its own has run after it (VICTORY_WAIT_RESIDENT=0: not) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 100 ++++++++++++++++++++++++++++- crates/victory-gpu/src/pool.rs | 2 +- crates/victory-gpu/src/resource.rs | 2 +- 3 files changed, 101 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b386f73..bfd49f0 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -204,6 +204,102 @@ pub(crate) fn not_resident() -> D3D12_HEAP_FLAGS { if wait_resident() { D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT } else { D3D12_HEAP_FLAG_NONE } } +/// A queue of its own that new memory is waited for with ([`mapped`]). +struct Aside { + queue: ID3D12CommandQueue, + list: ID3D12CommandList, + fence: ID3D12Fence, + event: windows::Win32::Foundation::HANDLE, + value: u64, + _keep: (ID3D12CommandAllocator, [ID3D12Resource; 2]), +} +// SAFETY: D3D12 objects are free-threaded, the event is waited on by one +// thread at a time (the lock). +unsafe impl Send for Aside {} + +/// New memory of the card is mapped into its address space when this +/// returns: a copy of a few bytes is sent to a queue of ours after the +/// memory was made, which the system starts only when all mappings asked +/// for so far are done, and waited for. (`MakeResident` came back before +/// that: run n11 was lost as n08 was with it alone.) Best done off a hot +/// path: a tenth of a millisecond to some. +pub(crate) fn mapped(device: &ID3D12Device) -> windows::core::Result<()> { + static ASIDE: Mutex> = Mutex::new(None); + if !wait_resident() { + return Ok(()); + } + let started = std::time::Instant::now(); + let mut aside = ASIDE.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: plain object creation; the objects the list names are kept. + unsafe { + if aside.is_none() { + let buffer = |kind: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| -> windows::core::Result { + let mut made: Option = None; + device.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + state, + None, + &mut made, + )?; + made.ok_or_else(windows::core::Error::empty) + }; + let from = buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ)?; + let to = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST)?; + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COPY, + ..Default::default() + })?; + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?; + let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?; + list.CopyBufferRegion(&to, 0, &from, 0, 16); + list.Close()?; + *aside = Some(Aside { + queue, + list: list.cast()?, + fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?, + event: CreateEventW(None, false, false, None)?, + value: 0, + _keep: (allocator, [from, to]), + }); + } + let Some(a) = aside.as_mut() else { return Ok(()) }; + a.queue.ExecuteCommandLists(&[Some(a.list.clone())]); + a.value += 1; + a.queue.Signal(&a.fence, a.value)?; + if a.fence.GetCompletedValue() < a.value { + a.fence.SetEventOnCompletion(a.value, a.event)?; + WaitForSingleObject(a.event, INFINITE); + } + } + let us = started.elapsed().as_micros() as u64; + MAPPED[0].fetch_add(1, Ordering::Relaxed); + MAPPED[1].fetch_add(us, Ordering::Relaxed); + MAPPED[2].fetch_max(us, Ordering::Relaxed); + let n = MAPPED[0].load(Ordering::Relaxed); + if n == 1 || n.is_multiple_of(200) { + tracing::info!( + "new card memory waited for until it is mapped (VICTORY_WAIT_RESIDENT=0: not), since the start: {n} times, {:.1} ms, the longest {:.1} ms", + MAPPED[1].load(Ordering::Relaxed) as f64 / 1000.0, + MAPPED[2].load(Ordering::Relaxed) as f64 / 1000.0 + ); + } + Ok(()) +} + +/// Times, microseconds and the longest of [`mapped`]. +static MAPPED: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + /// New memory (made with [`not_resident`]) is resident when this returns. pub(crate) fn resident(device: &ID3D12Device, object: &impl Interface) -> windows::core::Result<()> { if !wait_resident() { @@ -8374,6 +8470,7 @@ impl Host { .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; resident(&self.device, b)?; + mapped(&self.device)?; b.Map(0, None, Some(&mut data)) }) }; @@ -8462,6 +8559,7 @@ impl Host { .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; resident(&self.device, b)?; + mapped(&self.device)?; b.Map(0, None, Some(&mut data)) }) }; @@ -8513,7 +8611,7 @@ impl Host { if let Some(b) = &buffer { crate::book::made(b, || "an unordered access buffer".into()); } - let made = made.and_then(|()| buffer.as_ref().map_or(Ok(()), |b| resident(&self.device, b))); + let made = made.and_then(|()| buffer.as_ref().map_or(Ok(()), |b| resident(&self.device, b))).and_then(|()| mapped(&self.device)); match made { Ok(()) => buffer, Err(e) => { diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index f8a8301..e44ebb3 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -382,7 +382,7 @@ pub(crate) unsafe fn texture( tracing::warn!(error = %e, "no block of texture memory"); } if let Some(h) = &heap - && let Err(e) = crate::host::resident(device, h) + && let Err(e) = crate::host::resident(device, h).and_then(|()| crate::host::mapped(device)) { tracing::warn!(error = %e, "a block of texture memory is not resident"); return None; diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 564edd4..61ac424 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -2510,7 +2510,7 @@ fn host_texture_as( if !reserved && made.is_ok() && let Some(t) = &texture - && let Err(e) = crate::host::resident(&host.device, t) + && let Err(e) = crate::host::resident(&host.device, t).and_then(|()| crate::host::mapped(&host.device)) { tracing::warn!(error = %e, desc = ?d, "a host texture is not resident"); texture = None; From 3b73cb0eec9d69b3680ef18b7bf574971b524316 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 08:23:49 -0600 Subject: [PATCH 360/445] Textures are cut from blocks older than every list on the card (VICTORY_RIPE_BLOCKS=0: from new ones too) Runs n08 and n11 were lost to page faults in the first texture of a block made that instant: lists on the card read the slots new textures are put in. 12 empty blocks are made ahead; textures up to a whole block lie in them. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/indirect.rs | 22 ++++- crates/victory-gpu/src/pool.rs | 149 ++++++++++++++++++++++++++--- 2 files changed, 151 insertions(+), 20 deletions(-) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 4216c5f..b48b71d 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -1752,12 +1752,16 @@ void main(uint3 t : SV_DispatchThreadID) { return new_blocks(&way); } let times: u32 = std::env::var("VICTORY_BENCH_N").ok().and_then(|v| v.parse().ok()).unwrap_or(3); - // "never": never resident, what must lose the device. - for way in ["made", "waited", "enqueued", "never"] { - for n in 0..if way == "never" { 1 } else { times } { + let seconds = std::env::var("VICTORY_BENCH_S").unwrap_or_else(|_| "30".into()); + // "never": never resident, what must lose the device. "fresh-": no + // block goes (280 of them, 18 GB), so each has addresses no block had. + for way in ["fresh-made", "fresh-waited", "fresh-enqueued", "made", "waited", "enqueued", "never"] { + let fresh = way.starts_with("fresh-"); + for n in 0..if way == "never" { 1 } else if fresh { times * 5 } else { times } { let out = std::process::Command::new(std::env::current_exe().unwrap()) .args(["indirect::tests::new_blocks_under_readers", "--exact", "--ignored", "--nocapture"]) .env("VICTORY_BLOCK_WAY", way) + .env("VICTORY_BENCH_S", if fresh { "3" } else { &seconds }) .output() .unwrap(); let text = String::from_utf8_lossy(&out.stdout).into_owned(); @@ -1768,10 +1772,14 @@ void main(uint3 t : SV_DispatchThreadID) { } fn new_blocks(way: &str) { - let Some(mut gpu) = WarpHarness::on(false) else { + let Some(gpu) = WarpHarness::on(false) else { println!("no card: 0 blocks,"); return; }; + let (way, fresh) = match way.strip_prefix("fresh-") { + Some(way) => (way, true), + None => (way, false), + }; const SLOTS: usize = 64; const BLOCK: u64 = 64 << 20; let seconds = std::env::var("VICTORY_BENCH_S").ok().and_then(|v| v.parse().ok()).unwrap_or(30u64); @@ -1957,7 +1965,11 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { alive.push((block, texture)); n += 1; counts[0].fetch_add(1, SeqCst); - if alive.len() >= 24 { + if fresh { + if alive.len() >= 280 / threads { + break; + } + } else if alive.len() >= 24 { // Nothing shows or reads them any more when they go. for i in 0..mine { device.CopyDescriptorsSimple(1, slot(i), own(0), kind); diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index f8a8301..4855ae1 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -25,7 +25,8 @@ use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering}; use windows::Win32::Graphics::Direct3D12::*; use windows::core::{GUID, HRESULT, IUnknown, Interface}; -/// Bytes of a block; pieces of more than half of one are not pooled. +/// Bytes of a block; pieces of more than half of one are not pooled (with +/// blocks made ahead, [`ahead`]: of more than one). const BLOCK: u64 = 64 << 20; /// Blocks with nothing in them that are kept. const SPARE: usize = 2; @@ -65,6 +66,49 @@ pub(crate) fn on() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_POOL").is_none_or(|v| v != "0")) } +/// How many blocks of textures are made ahead, so that one has been there +/// for a while when its first piece is taken (`VICTORY_RIPE_BLOCKS`, 12; +/// 0: none, and new blocks are used at once, as before). +/// +/// A page fault of lists already on the card, in a texture made the same +/// tenth of a second as the first piece of a block made for it, lost the +/// device in runs n08 and n11 (2026-11-25): the title gives a slot that +/// those lists read by index a new texture. Why the card does not have the +/// new block's addresses yet is not known (n11 waited for `MakeResident`; +/// `indirect::tests::new_blocks_under_readers` never loses it). A block that +/// every submission begun before its making has left behind ([`Ripe`]) has +/// no such lists: pieces are cut from those first. +fn ahead() -> usize { + static AHEAD: std::sync::OnceLock = std::sync::OnceLock::new(); + *AHEAD.get_or_init(|| std::env::var("VICTORY_RIPE_BLOCKS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(12)) +} + +/// Submissions begun and finished ([`crate::host::submissions`]), and how +/// many blocks to make ahead (0: every block is ripe at once). +#[derive(Clone, Copy)] +struct Ripe { + started: u64, + finished: u64, + ahead: usize, +} + +impl Ripe { + const ALL: Ripe = Ripe { started: 0, finished: 0, ahead: 0 }; + + fn now() -> Ripe { + let (started, finished) = crate::host::submissions(); + // Not more than are kept ([`room`]): they would go and be made again. + Ripe { started, finished, ahead: ahead().min(SPARES.load(Ordering::Relaxed)) } + } + + fn is(self, block: &Block) -> bool { + self.ahead == 0 || block.made <= self.finished + } +} + +/// Pieces cut from blocks that were not ripe, for want of a ripe one. +static UNRIPE: AtomicU64 = AtomicU64::new(0); + /// The free ranges of a block: start and length, never two that touch. struct Ranges(BTreeMap); @@ -121,6 +165,8 @@ struct Block { /// The end of the highest piece ever taken: above it the memory is as /// it was made (zeros). used_to: u64, + /// The newest submission begun when it was made ([`Ripe`]). + made: u64, } struct Pool { @@ -140,42 +186,82 @@ impl Pool { /// A piece of `len` bytes and the memory it lies in, and whether that /// part was ever used before; `make` makes a block when none has room. - fn take(&mut self, len: u64, align: u64, now: u64, make: impl FnOnce() -> Option) -> Option<(Piece, B, bool)> { - if len == 0 || len > BLOCK / 2 { + fn take(&mut self, len: u64, align: u64, now: u64, make: impl FnMut() -> Option) -> Option<(Piece, B, bool)> { + self.take_ripe(len, align, now, Ripe::ALL, make) + } + + /// The same from a block that is ripe, if one has room; `make` makes one + /// ahead too, when few are empty. + fn take_ripe( + &mut self, + len: u64, + align: u64, + now: u64, + ripe: Ripe, + mut make: impl FnMut() -> Option, + ) -> Option<(Piece, B, bool)> { + // With blocks made ahead, what would be an allocation of its own (and + // new when the card first reads it) lies in one of those too. + if len == 0 || len > if ripe.ahead > 0 { BLOCK } else { BLOCK / 2 } { return None; } self.rested(now); let mut found = None; for (i, block) in self.blocks.iter_mut().enumerate() { if let Some(block) = block + && ripe.is(block) && let Some(start) = block.free.take(len, align) { found = Some((i, start)); break; } } + if found.is_none() && ripe.ahead > 0 { + // The one that has been there the longest. + let mut unripe: Vec<(u64, usize)> = + self.blocks.iter().enumerate().filter_map(|(i, b)| Some((b.as_ref()?.made, i))).collect(); + unripe.sort_unstable(); + found = unripe.into_iter().find_map(|(_, i)| Some((i, self.blocks[i].as_mut()?.free.take(len, align)?))); + } let (i, start) = match found { Some(found) => found, None => { - let mut block = Block { memory: make()?, free: Ranges::new(BLOCK), used_to: 0 }; - let start = block.free.take(len, align)?; - let i = match self.blocks.iter().position(Option::is_none) { - Some(i) => i, - None => { - self.blocks.push(None); - self.blocks.len() - 1 - } - }; - self.blocks[i] = Some(block); - (i, start) + let i = self.add(make()?, ripe.started); + (i, self.blocks[i].as_mut()?.free.take(len, align)?) } }; + if ripe.ahead > 0 { + if !ripe.is(self.blocks[i].as_ref()?) { + let n = UNRIPE.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::info!("textures cut from blocks made while lists ran that still run: {n}"); + } + } + let empty = self.blocks.iter().flatten().filter(|b| b.free.whole(BLOCK)).count(); + if empty < ripe.ahead + && let Some(memory) = make() + { + self.add(memory, ripe.started); + } + } let block = self.blocks[i].as_mut()?; let again = start < block.used_to; block.used_to = block.used_to.max(start + len); Some((Piece { block: i, start, len }, block.memory.clone(), again)) } + fn add(&mut self, memory: B, made: u64) -> usize { + let i = match self.blocks.iter().position(Option::is_none) { + Some(i) => i, + None => { + self.blocks.push(None); + self.blocks.len() - 1 + } + }; + self.blocks[i] = Some(Block { memory, free: Ranges::new(BLOCK), used_to: 0, made }); + i + } + fn give(&mut self, piece: Piece, now: u64) { self.resting.push_back((now + REST, piece)); } @@ -369,7 +455,7 @@ pub(crate) unsafe fn texture( if info.SizeInBytes == u64::MAX { return None; } - let (piece, heap, _) = lock(&TEXTURES).take(info.SizeInBytes, info.Alignment.max(1), now(), || { + let (piece, heap, _) = lock(&TEXTURES).take_ripe(info.SizeInBytes, info.Alignment.max(1), now(), Ripe::now(), || { let desc = D3D12_HEAP_DESC { SizeInBytes: BLOCK, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, @@ -473,6 +559,39 @@ mod tests { assert!(none.take(65536, 65536, 0, || None).is_none()); } + #[test] + fn pieces_come_from_blocks_older_than_the_lists_that_run() { + let mut pool: Pool = Pool::new(SPARE_KEPT); + let made = std::cell::Cell::new(0); + let make = || { + made.set(made.get() + 1); + Some(made.get()) + }; + let at = |started, finished| Ripe { started, finished, ahead: 2 }; + let take = |pool: &mut Pool, ripe| pool.take_ripe(BLOCK / 2, 65536, 0, ripe, make).unwrap().1; + // Nothing runs: at once, and two are made ahead, one a time. + assert_eq!(take(&mut pool, at(0, 0)), 1); + assert_eq!(made.get(), 2); + assert_eq!(take(&mut pool, at(0, 0)), 1); + assert_eq!(made.get(), 3); + // 4 is made while submission 5 runs. + assert_eq!(take(&mut pool, at(5, 4)), 2); + assert_eq!(made.get(), 4); + assert_eq!(take(&mut pool, at(5, 4)), 2); + assert_eq!(take(&mut pool, at(6, 4)), 3); + assert_eq!(take(&mut pool, at(6, 4)), 3); + // None is ripe: the oldest; it is ripe once 5 has finished. + assert_eq!(take(&mut pool, at(7, 4)), 4); + assert_eq!(take(&mut pool, at(7, 5)), 4); + // A whole block's worth too. + assert_eq!(pool.take_ripe(BLOCK, 65536, 0, at(8, 7), make).unwrap().1, 5); + // Off: the first with room, whatever its age, none ahead. + let n = made.get(); + assert_eq!(pool.take(BLOCK / 2, 65536, 0, make).unwrap().1, 6); + assert_eq!(made.get(), n); + assert!(pool.take(BLOCK, 65536, 0, make).is_none()); + } + /// A pooled texture's piece comes back when its last reference goes, not /// before; its staging piece begins as zeros. #[test] From 4e77a8795b99566ac347dca66c2df31c3652bf64 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 09:03:29 -0600 Subject: [PATCH 361/445] A list makes a view its tables hold once and copies its descriptor (VICTORY_LIST_VIEWS=0: for every table); a draw's tables are gone through without memory of the heap The recording job the frame waits for last (24 of 65 ms, timeline waits-2) is 2,500 indirect dispatches, each with a table of its own that differs in a constant buffer. VICTORY_AB can turn VICTORY_MAP_THREADS (8 or 1) too. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 10 ++ crates/victory-gpu/src/descriptor/host.rs | 159 ++++++++++++++++++++ crates/victory-gpu/src/draw.rs | 174 ++++++++++++++++++---- crates/victory-gpu/src/lib.rs | 7 + crates/victory-hle/src/modules/xmem.rs | 5 + 5 files changed, 326 insertions(+), 29 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 2e0c3a6..6585bfa 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -1126,6 +1126,16 @@ fn view_at(i: u32, generation: u32) -> Option { } } +/// The words of the record at `handle`, if they are a view's. +pub(crate) fn record_at(handle: u64) -> Option<[u32; 3]> { + if handle == 0 { + return None; + } + // SAFETY: the handle is a descriptor slot the title passes back. + let words = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + (words[0] == VIEW_TAG).then_some(words) +} + /// The view recorded at `handle`, if one is (and its resource is alive). pub(crate) fn view(handle: u64) -> Option { if handle == 0 { diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index be54253..5869757 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -2129,6 +2129,68 @@ impl HostHeap { self.keep(index, kept.flatten()); } + /// Makes slot `index` (a dynamic one) the view the record `words` names, + /// from this thread's descriptor of it if the recording `recording` has + /// made one, else as [`HostHeap::make_at`] does, and keeps that + /// ([`ListViews`]). What is known of the record in this recording; + /// `None` (the slot is not made): not a view kept so. + pub(crate) fn make_listed(&self, recording: u64, words: [u32; 3], index: u32) -> Option { + if self.sampler { + return None; + } + LIST_VIEWS.with(|views| { + let mut views = views.borrow_mut(); + if views.is_none() { + *views = Some(ListViews::new()?); + } + let views = views.as_mut()?; + if views.recording != recording { + views.recording = recording; + views.made.clear(); + } + let twins = self.twins.get(index as usize).is_some(); + if !views.made.contains_key(&words) { + let view = super::view_at(words[1], words[2])?; + let at = 2 * views.made.len() as u32; + // (A constant buffer's bytes are copied for each draw.) + if at >= ListViews::SLOTS || matches!(view, View::Constant(..)) { + return None; + } + let twin = twinned(&view); + let kept = make_twinned(&view, views.slot(at), Some(views.slot(at + 1)))?; + let listed = Listed { + kind: crate::draw::view_kind(&view), + texture: is_texture_view(&view), + ready: (0, 0, false), + tabled: None, + }; + views.made.insert(words, ListView { view, at, twin, kept, listed }); + } + let made = &views.made[&words]; + self.copy_from(index, views.slot(made.at)); + if made.twin && twins { + self.copy_from(self.raw + index, views.slot(made.at + 1)); + self.twins[index as usize].store(true, std::sync::atomic::Ordering::Relaxed); + } else { + self.clear_twin(index); + } + self.keep(index, made.kept.clone()); + Some(made.listed) + }) + } + + /// As [`HostHeap::copy_to`], from the slot `from`, which the card does not + /// see. + fn copy_from(&self, to: u32, from: D3D12_CPU_DESCRIPTOR_HANDLE) { + #[cfg(feature = "diagnostics")] + if let Some(written) = self.written.get(to as usize) { + written.store(crate::host::coarse_ms() as u32, std::sync::atomic::Ordering::Relaxed); + } + let Some(host) = host() else { return }; + // SAFETY: a slot of our heap, and one of this thread's heap. + unsafe { host.device.CopyDescriptorsSimple(1, self.cpu(to), from, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) }; + } + /// Makes slot `index` read nothing: a null view, or a plain sampler. pub(crate) fn make_null(&self, index: u32) { if self.sampler { @@ -4664,3 +4726,100 @@ mod tests { assert_eq!(heap.dynamic(2), None); } } + +/// What is known of a record a list's tables hold, in that recording of the +/// list ([`HostHeap::make_listed`]). +#[derive(Clone, Copy)] +pub(crate) struct Listed { + pub(crate) kind: Option, + pub(crate) texture: bool, + /// Read at this epoch of the list ([`crate::host::HostList::epoch`]) with + /// this depth target tested: up to date; and whether it is that target's. + pub(crate) ready: (u64, usize, bool), + /// The title's slot last noted for it, and whether the draw read it. + pub(crate) tabled: Option<(u32, bool)>, +} + +struct ListView { + view: View, + /// Its descriptor's slot in [`ListViews`]; its raw twin's is the next. + at: u32, + twin: bool, + kept: Kept, + listed: Listed, +} + +/// The descriptors a thread made for one recording of a list, by the record +/// they were made from, in a heap the card does not see. +/// +/// The title's culling and lighting dispatches each bind a table of their own +/// that differs in one constant buffer, and the same thirty views beside it: +/// each was found, checked, made and brought up to date anew for every +/// dispatch, some 2,500 indirect dispatches in the one recording job the +/// frame waits for last (timeline waits-2: 24 of 65 ms). Here a list makes a +/// view once, as it makes a table once (`crate::draw::State::tables`), and +/// copies its descriptor. +struct ListViews { + recording: u64, + heap: ID3D12DescriptorHeap, + step: usize, + start: usize, + made: std::collections::HashMap<[u32; 3], ListView, std::hash::BuildHasherDefault>, +} + +impl ListViews { + const SLOTS: u32 = 8192; + + fn new() -> Option { + let host = host()?; + // SAFETY: plain object creation. + unsafe { + let heap: ID3D12DescriptorHeap = host + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: Self::SLOTS, + ..Default::default() + }) + .ok()?; + let step = host.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let start = heap.GetCPUDescriptorHandleForHeapStart().ptr; + Some(ListViews { recording: 0, heap, step, start, made: Default::default() }) + } + } + + fn slot(&self, i: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { + debug_assert!(i < Self::SLOTS && !windows::core::Interface::as_raw(&self.heap).is_null()); + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: self.start + i as usize * self.step } + } +} + +thread_local! { + static LIST_VIEWS: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// The view the record `words` names, as this thread made it for `recording`. +pub(crate) fn listed_view(recording: u64, words: [u32; 3]) -> Option { + LIST_VIEWS.with(|views| { + let views = views.borrow(); + let views = views.as_ref().filter(|v| v.recording == recording)?; + views.made.get(&words).map(|m| m.view.clone()) + }) +} + +/// Notes what is known of the record `words` in `recording`. +pub(crate) fn note_listed(recording: u64, words: [u32; 3], listed: Listed) { + LIST_VIEWS.with(|views| { + if let Some(views) = views.borrow_mut().as_mut().filter(|v| v.recording == recording) + && let Some(made) = views.made.get_mut(&words) + { + made.listed = listed; + } + }); +} + +/// Whether a list makes a view its tables hold once (`VICTORY_LIST_VIEWS=0`: +/// for every table). +pub(crate) fn list_views() -> bool { + crate::toggled!("VICTORY_LIST_VIEWS") +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 24a8d87..1850b78 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -341,6 +341,9 @@ pub(crate) struct State { root_uav_slots: std::collections::HashMap<(usize, u64), RootSlot>, /// The list ran and its dynamic slots were given back. tables_gone: bool, + /// This recording, for [`crate::descriptor::host::HostHeap::make_listed`] + /// (0: it has none yet). + recording: u64, } impl Drop for State { @@ -371,6 +374,7 @@ impl State { crate::descriptor::release_dynamic(heap, first, n); } self.fresh_tables.clear(); + self.recording = 0; self.root_srv_slots.clear(); self.root_uav_slots.clear(); self.tables_gone = true; @@ -1463,7 +1467,16 @@ impl State { None }; if let Some((param, dwords)) = stage.user_data { - let mut values = vec![0u32; dwords as usize]; + // (A root signature holds 64 dwords.) + let mut room = [0u32; 64]; + let mut more = Vec::new(); + let values: &mut [u32] = match room.get_mut(..dwords as usize) { + Some(values) => values, + None => { + more.resize(dwords as usize, 0); + &mut more + } + }; for u in &t.host.user_data { if let RootType::Other(kind) = u.root { values[u.index as usize] = @@ -1481,7 +1494,7 @@ impl State { #[cfg(feature = "diagnostics")] { self.user.clear(); - self.user.extend_from_slice(&values); + self.user.extend_from_slice(values); } // SAFETY: an open list; `values` covers the parameter. unsafe { @@ -2934,14 +2947,14 @@ impl State { used: &[UsedResource], indexed: &[RootIndexedView], compute: bool, - ) -> Vec<(u8, u32)> { + ) -> Few<(u8, u32), 16> { let tables = |u: &&UsedResource| u.root == RootType::Table; - let mut fresh: Vec = used - .iter() - .filter(tables) - .filter(|u| u.kind == ResourceType::Cbv) - .map(|u| u.slot) - .collect(); + let mut fresh: Few = Few::default(); + for u in used.iter().filter(tables).filter(|u| u.kind == ResourceType::Cbv) { + if !fresh.contains(&u.slot) { + fresh.push(u.slot); + } + } // Tables reaching past a host heap smaller than the title's (the // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the // title's slots there have no host slot of their own. @@ -2964,22 +2977,22 @@ impl State { } } fresh.sort_unstable(); - fresh.dedup(); for u in used.iter().filter(tables) { if !fresh.contains(&u.slot) { self.table_entry(list, u, compute); } } - let mut made = Vec::new(); - for slot in fresh { + let mut made = Few::default(); + for &slot in fresh.iter() { let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else { continue; }; - let entries: Vec<&UsedResource> = used - .iter() - .filter(tables) - .filter(|u| u.slot == slot) - .collect(); + // (Their places among `used`.) + let mut places: Few = Few::default(); + for (i, _) in used.iter().enumerate().filter(|(_, u)| tables(u) && u.slot == slot) { + places.push(i as u16); + } + let entries = || places.iter().map(|&i| &used[usize::from(i)]); let Some(heap) = self.heap_of(table) else { continue; }; @@ -3005,8 +3018,7 @@ impl State { .collect(); selected.sort_unstable(); selected.dedup(); - let n = entries - .iter() + let n = entries() .map(|u| u.table_offset_dwords / 8) .chain(selected.last().copied()) .max() @@ -3035,7 +3047,7 @@ impl State { let first = known.first; // This reader had it brought up to date, and nothing in the // list changed since: nothing to do again. - let once = ready_once() && selected.is_empty() && entries.iter().all(|u| u.kind != ResourceType::Uav); + let once = ready_once() && selected.is_empty() && entries().all(|u| u.kind != ResourceType::Uav); if once && known.epoch == list.epoch() && let Some((_, depth)) = known.ready.iter().find(|(r, _)| *r == reader) @@ -3048,14 +3060,14 @@ impl State { } let depth_before = TESTED_DEPTH.get(); TESTED_DEPTH.set((depth_before.0, false)); - for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { + for u in entries().filter(|u| u.kind != ResourceType::Cbv) { let handle = table + u64::from(u.table_offset_dwords) * 4; if let Some(view) = crate::descriptor::view(handle) { readable(list, u.kind, &view); } } for k in selected { - if entries.iter().any(|u| u.table_offset_dwords / 8 == k) { + if entries().any(|u| u.table_offset_dwords / 8 == k) { continue; } let handle = table + u64::from(k) * 32; @@ -3098,15 +3110,63 @@ impl State { // which may lie over slots shaders pick by index, only the ones // the shader names.) if let Some(title) = title_first { - for k in (0..n).filter(|&k| n <= 64 || entries.iter().any(|u| u.table_offset_dwords / 8 == k)) { + for k in (0..n).filter(|&k| n <= 64 || entries().any(|u| u.table_offset_dwords / 8 == k)) { host.slot_tabled(title + k); } } + let list_views = crate::descriptor::host::list_views(); + if self.recording == 0 { + static NEXT: AtomicU64 = AtomicU64::new(1); + self.recording = NEXT.fetch_add(1, Ordering::Relaxed); + } + let recording = self.recording; // The whole range: a shader may index past the entries its // used-resource list names (descriptor arrays). for k in 0..n { let index = first + k; - let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k); + // A view this list has made before: its descriptor copied, + // and nothing more if nothing changed in the list since. + if list_views + && let Some(words) = crate::descriptor::record_at(table + u64::from(k) * 32) + && let Some(mut listed) = host.make_listed(recording, words, index) + { + let kind = entries() + .find(|u| u.table_offset_dwords / 8 == k) + .map(|u| u.kind) + .or_else(|| selected.binary_search(&k).ok().and(listed.kind)); + let was = (listed.ready, listed.tabled); + if let Some(kind) = kind { + let tested = TESTED_DEPTH.get(); + if kind == ResourceType::Srv && listed.ready.0 == list.epoch() && listed.ready.1 == tested.0 { + if listed.ready.2 { + TESTED_DEPTH.set((tested.0, true)); + } + } else if let Some(view) = crate::descriptor::host::listed_view(recording, words) { + TESTED_DEPTH.set((tested.0, false)); + readable(list, kind, &view); + let depth = TESTED_DEPTH.get().1; + TESTED_DEPTH.set((tested.0, tested.1 || depth)); + if kind == ResourceType::Srv { + listed.ready = (list.epoch(), tested.0, depth); + } + } + } + if let Some(title) = title_first + && listed.texture + && listed.tabled != Some((title + k, kind.is_some())) + { + listed.tabled = Some((title + k, kind.is_some())); + host.texture_slot_tabled(title + k, kind.is_some()); + if kind.is_some() { + host.mirror(title + k, table + u64::from(k) * 32, true); + } + } + if was != (listed.ready, listed.tabled) { + crate::descriptor::host::note_listed(recording, words, listed); + } + continue; + } + let used = entries().find(|u| u.table_offset_dwords / 8 == k); match crate::descriptor::view(table + u64::from(k) * 32) { Some(View::Constant(address, size)) => { let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else { @@ -3703,7 +3763,7 @@ fn host_signature(kind: u32, stride: u32) -> Option { /// Gets what a shader reads or writes through a view ready: buffer data /// copied, textures moved to the state they need. -fn view_kind(view: &View) -> Option { +pub(crate) fn view_kind(view: &View) -> Option { match view { View::Shader(..) | View::Placed(false, ..) => Some(ResourceType::Srv), View::Unordered(..) | View::Placed(true, ..) => Some(ResourceType::Uav), @@ -3739,6 +3799,48 @@ fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_ } } +/// A few things, up to `N` of them without memory of the heap: what a draw's +/// tables are gone through with, some six lists a stage. +struct Few { + few: [T; N], + len: usize, + /// All of them, if they are more. + many: Vec, +} + +impl Default for Few { + fn default() -> Self { + Few { few: [T::default(); N], len: 0, many: Vec::new() } + } +} + +impl Few { + fn push(&mut self, what: T) { + if self.many.is_empty() && self.len < N { + self.few[self.len] = what; + self.len += 1; + } else { + if self.many.is_empty() { + self.many.extend_from_slice(&self.few); + } + self.many.push(what); + } + } +} + +impl std::ops::Deref for Few { + type Target = [T]; + fn deref(&self) -> &[T] { + if self.many.is_empty() { &self.few[..self.len] } else { &self.many } + } +} + +impl std::ops::DerefMut for Few { + fn deref_mut(&mut self) -> &mut [T] { + if self.many.is_empty() { &mut self.few[..self.len] } else { &mut self.many } + } +} + /// A table made afresh in dynamic slots, in a list ([`State::tables`]). struct FreshTable { first: u32, @@ -3806,9 +3908,11 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) { let aliased = crate::resource::alias_of(*resource as This) .is_some_and(|source| crate::texture::alias(list, *resource as This, source)); if !aliased - && let Some(t) = crate::resource::host_resource(*resource as This) - && crate::texture::title_written(t) + && let Some(t) = crate::resource::host_copy(*resource as This) + && t.flags() & 0x7 == 0 { + // (A texture the title writes: no target, depth or unordered + // access, `crate::texture::title_written`.) // Of a texture the title placed, the levels the view shows. let first = match (&placed, view) { (Some(_), View::Shader(_, Some(desc))) => crate::resource::first_mip(desc), @@ -4083,7 +4187,18 @@ mod tests { #[cfg(test)] mod record_hash_tests { - use super::RecordHash; + use super::{Few, RecordHash}; + + #[test] + fn a_few_things_are_kept_in_order_however_many() { + for n in 0..10u32 { + let mut few: Few = Few::default(); + (0..n).for_each(|i| few.push(n - i)); + assert_eq!(few.to_vec(), (0..n).map(|i| n - i).collect::>()); + few.sort_unstable(); + assert_eq!(few.to_vec(), (1..=n).collect::>()); + } + } #[test] fn records_that_differ_hash_apart() { @@ -4104,7 +4219,8 @@ mod record_hash_tests { } } assert!(seen.insert(of(&[]))); - let zeros: Vec = (1..100).map(|n| of(&vec![[0; 3]; n])).collect(); + // (One record of zeros is among the above.) + let zeros: Vec = (2..100).map(|n| of(&vec![[0; 3]; n])).collect(); assert!(zeros.iter().all(|h| seen.insert(*h))); } } diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 75fa6e6..29947a7 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -83,6 +83,13 @@ mod watch; #[cfg(windows)] pub use host::on_failure; +/// Whether `switch` is on now, if it is one of those `VICTORY_AB` turns on and +/// off while the title runs (`ab`). +#[cfg(all(windows, feature = "diagnostics"))] +pub fn switched(switch: &str) -> Option { + ab::pick(switch) +} + /// What the frame is at (`copystat::phase`), for the sampling profiler. #[cfg(all(windows, feature = "diagnostics"))] pub fn frame_phase() -> u32 { diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 64920a8..ad0cdb1 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -1264,6 +1264,11 @@ const GROUP: usize = 64; /// queue once at a time. In a bench (60,000 views, five threads changing /// protections) one thread mapped 1,500 pages a second, eight 30,000. fn side_by_side() -> usize { + // Diagnostics: 1 and 8 by turns. + #[cfg(all(windows, feature = "diagnostics"))] + 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) }); From 6acfbb8697e0960e8bd0e17eae651c14750f5593 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 09:07:01 -0600 Subject: [PATCH 362/445] A copy's buffer is asked for its bytes when they are first needed (copies of tests have none) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/shadow.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index d7055a9..671d6d8 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -26,8 +26,8 @@ use crate::watch::PAGE; /// A title buffer's host copy. pub(crate) struct Shadow { - /// The bytes of `buffer`. - width: u64, + /// The bytes of `buffer`, once asked. + width: std::sync::OnceLock, pub(crate) buffer: ID3D12Resource, data: *mut u8, gpu: u64, @@ -2745,17 +2745,16 @@ impl Shadow { /// The bytes of the host buffer. pub(crate) fn width(&self) -> u64 { - self.width + // SAFETY: a live buffer. + *self.width.get_or_init(|| unsafe { self.buffer.GetDesc() }.Width) } fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Shadow { - // SAFETY: a live buffer. - let width = unsafe { buffer.GetDesc() }.Width; let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64; LIVE[0].fetch_add(1, Ordering::Relaxed); LIVE[1].fetch_add(len, Ordering::Relaxed); Shadow { - width, + width: Default::default(), buffer, data, gpu, From 3bab23c066084702cb0c3021afe7f989624af015 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 09:24:15 -0600 Subject: [PATCH 363/445] Title slots show a new texture after its upload has run (VICTORY_SHOW_AFTER=1; off), and the book says more of one Three losses were page faults in a texture made and shown in the last tenth of a second. With the switch the texture pass, and a draw's table for the title's slots, put a neutral 1x1 texture (or the old view of the same texture) there until the submission with the upload has finished. The book's report has the piece and its block, the submissions at the making, the upload's submission, and what the slot showed before. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/book.rs | 27 +- crates/victory-gpu/src/descriptor/host.rs | 284 +++++++++++++++++++++- crates/victory-gpu/src/draw.rs | 50 +++- crates/victory-gpu/src/pool.rs | 41 +++- 4 files changed, 389 insertions(+), 13 deletions(-) diff --git a/crates/victory-gpu/src/book.rs b/crates/victory-gpu/src/book.rs index b63f150..469952d 100644 --- a/crates/victory-gpu/src/book.rs +++ b/crates/victory-gpu/src/book.rs @@ -42,6 +42,8 @@ struct Entry { size: u64, what: String, made: u64, + /// What was told of it since ([`note`]). + notes: String, } #[derive(Default)] @@ -96,7 +98,7 @@ impl Book { if size > LONG { self.long.push(id); } - self.live.insert(id, Entry { start, size, what, made: now }); + self.live.insert(id, Entry { start, size, what, made: now, notes: String::new() }); if object != 0 { self.by_object.insert(object, id); } @@ -358,6 +360,22 @@ pub(crate) fn block(heap: &ID3D12Heap, resource: &ID3D12Resource, offset: u64, b } } +/// Something to say of the object at `raw` if it is in the book. +pub(crate) fn note(raw: usize, what: impl FnOnce() -> String) { + if !on() { + return; + } + let what = what(); + with(|b| { + if let Some(id) = b.by_object.get(&raw).copied() + && let Some(e) = b.live.get_mut(&id) + && e.notes.len() < 600 + { + e.notes.push_str(&what); + } + }); +} + /// A name for something made before. pub(crate) fn named(object: &ID3D12Object, what: impl FnOnce() -> String) { let raw = object.as_raw() as usize; @@ -558,7 +576,8 @@ pub(crate) fn at_loss(va: u64) -> String { return String::new(); } let mut text = with(|b| { - let one = |e: &Entry| format!("{} {:#x}+{:#x} made at {:.1} s", e.what, e.start, e.size, e.made as f64 / 1e3); + let one = + |e: &Entry| format!("{} {:#x}+{:#x} made at {:.3} s{}", e.what, e.start, e.size, e.made as f64 / 1e3, e.notes); let mut text = String::from("; BOOK: alive there:"); for e in b.holders(va) { text.push_str(&format!(" [{}]", one(e))); @@ -570,9 +589,9 @@ pub(crate) fn at_loss(va: u64) -> String { } text.push_str("; gone there, newest first:"); for (e, gone) in b.gone_at(va, 12) { - text.push_str(&format!(" [{} gone at {:.1} s]", one(e), *gone as f64 / 1e3)); + text.push_str(&format!(" [{} gone at {:.3} s]", one(e), *gone as f64 / 1e3)); } - text.push_str(&format!("; now {:.1} s, {} alive, {} gone", crate::host::now_ms() as f64 / 1e3, b.live.len(), b.gone.len())); + text.push_str(&format!("; now {:.3} s, submissions (begun, finished) {:?}, {} alive, {} gone", crate::host::now_ms() as f64 / 1e3, crate::host::submissions(), b.live.len(), b.gone.len())); text }); { diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 5869757..2e1c06a 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -176,6 +176,152 @@ struct Flip { index: u32, handle: u64, key: u64, + /// The frame it was asked in, of a slot that shows nothing of the + /// texture until then ([`HostHeap::texture_slot_show_after`]). + late: Option, +} + +/// Whether a title slot shows a texture that is new to it only once the +/// submission with its upload has finished (`VICTORY_SHOW_AFTER=1`; off). +/// Shown at once, the lists already on the card read it by index while it is +/// made: all three losses whose report had the address book (n08, n11, n15) +/// were page faults in a texture made and shown in the last tenth of a +/// second. +pub(crate) fn show_after() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SHOW_AFTER").is_some_and(|v| v != "0")) +} + +/// Slots shown late ([`show_after`]), the frames they waited, the longest; +/// those that were given the neutral texture meanwhile; those not shown any +/// more when their time came. +static LATE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// What a texture slot showed before its last write: its record (0: null or +/// the neutral texture), when (ms), and the submissions begun and finished. +#[cfg(feature = "diagnostics")] +static BEFORE: Mutex> = + Mutex::new(std::collections::BTreeMap::new()); + +#[cfg(feature = "diagnostics")] +fn note_before(index: u32, was: u64, by: &'static str) { + if crate::book::on() { + let entry = (was, crate::host::now_ms(), crate::host::submissions(), by); + BEFORE.lock().unwrap_or_else(|e| e.into_inner()).insert(index, entry); + } +} + +/// A 1x1 gray texture, in the place of one that is not there yet. +fn neutral() -> Option<&'static ID3D12Resource> { + static TEXTURE: std::sync::OnceLock> = std::sync::OnceLock::new(); + TEXTURE + .get_or_init(|| { + let host = host()?; + let device = &host.device; + let (from, data) = host.upload_buffer(256)?; + // SAFETY: the buffer's mapping; plain creation and recording, + // waited for before what it names goes. + unsafe { + std::ptr::write_bytes(data, 0x80, 256); + let mut made: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut made, + ) + .ok()?; + let made = made?; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COPY, ..Default::default() }) + .ok()?; + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY).ok()?; + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None).ok()?; + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&made), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Width: 1, + Height: 1, + Depth: 1, + RowPitch: 256, + }, + }; + let source = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&from), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint }, + }; + list.CopyTextureRegion(&to, 0, 0, 0, &source, None); + list.Close().ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).ok()?)]); + queue.Signal(&fence, 1).ok()?; + // (Without an event: this waits.) + fence.SetEventOnCompletion(1, windows::Win32::Foundation::HANDLE::default()).ok()?; + Some(made) + } + }) + .as_ref() +} + +/// Makes the descriptor of [`neutral`] for a slot of `view` at `at`, if the +/// view is a 2D texture's or an array's; else a null one of its kind. +fn neutral_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { + const TEXTURE2D: u32 = 4; + const TEXTURE2D_ARRAY: u32 = 5; + let dimension = match view { + View::Shader(_, Some(desc)) => desc[1], + View::Placed(false, resource, desc) if resource[0] != 1 => desc[1], + _ => 0, + }; + let desc = match dimension { + TEXTURE2D => D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() }, + }, + }, + TEXTURE2D_ARRAY => D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { MipLevels: 1, ArraySize: 1, ..Default::default() }, + }, + }, + _ => { + null_for(view, at); + return None; + } + }; + let (Some(texture), Some(host)) = (neutral(), host()) else { + null_for(view, at); + return None; + }; + // SAFETY: a slot of our heap, a live texture. + unsafe { host.device.CreateShaderResourceView(texture, Some(&desc), at) }; + Some(texture.clone()) } static FLIPS: Mutex> = Mutex::new(Vec::new()); @@ -986,6 +1132,18 @@ pub(crate) fn slot_story(slot: u32) -> String { if let Some(at) = host.written.get(slot as usize) { text.push_str(&format!(", written last at {:.1} s", f64::from(at.load(Relaxed)) / 1e3)); } + let before = BEFORE.lock().unwrap_or_else(|e| e.into_inner()).get(&index).copied(); + if let Some((was, at, (started, finished), by)) = before { + let what = match view_at(was as u32, (was >> 32) as u32) { + _ if was == 0 => "nothing (or the neutral texture)".into(), + None => "a view that is gone".into(), + Some(view) => format!("{view:?}").chars().take(160).collect::(), + }; + text.push_str(&format!( + ", changed ({by}) at {:.3} s with submissions {started} begun and {finished} finished, showed before: {what}", + at as f64 / 1e3 + )); + } let kept = host.kept_in(index); match kept { None => text.push_str(", holds nothing"), @@ -1821,10 +1979,71 @@ impl HostHeap { /// until then it shows what it showed. (Made at once, the frames on the /// card read the new view before its levels were filled.) pub(crate) fn texture_slot_flip(&self, list: &crate::host::HostList, index: u32, handle: u64) { + self.flip(list, index, handle, None); + } + + /// The same of a slot that shows nothing of the texture the record at + /// `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) { + 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; + }; + { + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + let Some(&shown) = made.get(index as usize) 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 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; + 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); + } + } + self.flip(list, index, handle, Some(crate::frame::current())); + } + + /// [`HostHeap::mirror`] of a slot whose table a draw read: a texture made + /// a moment ago is shown after the draw's list ([`show_after`]; the draw + /// reads the table's dynamic slots). + pub(crate) fn mirror_after(&self, list: &crate::host::HostList, index: u32, handle: u64) { + if show_after() + && index < self.count + && !self.texture_slot_made_from(index, handle) + && let Some(view) = super::view(handle) + && 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) + { + return self.texture_slot_show_after(list, index, handle); + } + self.mirror(index, handle, true); + } + + fn flip(&self, list: &crate::host::HostList, index: u32, handle: u64, late: Option) { let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle)); list.defer_host(move || { let after = crate::host::submissions().0; - let flip = Flip { after, heap, index, handle, key }; + let flip = Flip { after, heap, index, handle, key, late }; FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip); }); } @@ -1855,16 +2074,47 @@ impl HostHeap { 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 (true, true, Some(view)) = (f.key != 0 && record_key(f.handle) == f.key, *shown != 0, view) else { + 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); continue; }; + // Its memory went meanwhile: the texture pass finds that. + if f.late.is_some() + && let View::Placed(_, resource, desc) = &view + { + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let len = crate::resource::placed_bytes(resource).unwrap_or(1); + if crate::texture::mapped_bytes(address as *const u8, len as usize) == 0 { + LATE[4].fetch_add(1, Relaxed); + continue; + } + } 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" }); self.put(f.index); *shown = f.key; self.keep(f.index, kept); - flipped += 1; + if let Some(since) = f.late { + let frames = crate::frame::current().saturating_sub(since); + let n = LATE[0].fetch_add(1, Relaxed) + 1; + let all = LATE[1].fetch_add(frames, Relaxed) + frames; + let most = LATE[2].fetch_max(frames, Relaxed).max(frames); + if n == 1 || n.is_multiple_of(5000) { + tracing::info!( + "slots shown after their texture's upload (VICTORY_SHOW_AFTER=1), since the start: {n}, {:.2} frames after they were asked for, the longest {most}; the neutral texture meanwhile in {}; {} not shown any more by then", + all as f64 / n as f64, + LATE[3].load(Relaxed), + LATE[4].load(Relaxed) + ); + } + } else { + flipped += 1; + } } } FLIPPED[0].fetch_add(flipped as u64, Relaxed); @@ -2620,6 +2870,10 @@ impl HostHeap { KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); 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" }); + } self.quick_is(index, 0); made[index as usize] = if later { 0 } else { key }; let kept = if later { @@ -3990,6 +4244,30 @@ mod tests { assert_eq!(view(1, 4, 0.0), (0, 2, 0.0)); } + /// 2D textures and arrays have a neutral stand-in, others a null view. + #[test] + fn a_texture_not_there_yet_has_a_neutral_stand_in() { + let Some(host) = host() else { return }; + // SAFETY: plain heap creation and queries. + unsafe { + let heap: ID3D12DescriptorHeap = host + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 1, + ..Default::default() + }) + .unwrap(); + let at = heap.GetCPUDescriptorHandleForHeapStart(); + let view = |dimension| View::Shader(0, Some([98, dimension, 5768, 0, 0, 1, 0, 1, 0, 0])); + assert!(neutral_for(&view(4), at).is_some()); + assert!(neutral_for(&view(5), at).is_some()); + assert!(neutral_for(&view(9), at).is_none()); + assert!(neutral_for(&view(8), at).is_none()); + assert!(host.device.GetDeviceRemovedReason().is_ok()); + } + } + /// Memory past the levels a slot's view shows is not its texture's. #[test] fn a_view_of_smaller_levels_is_not_told_of_memory_past_them() { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 1850b78..7ba0431 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2329,19 +2329,33 @@ impl State { let shows_other = !baking && crate::resource::held_only() && heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle)); + // A slot that shows nothing of it yet, or something else, shows it + // when the upload has run too. + let late = !shows_other + && !baking + && crate::descriptor::host::show_after() + && heap.handle(index).is_some_and(|handle| !host.texture_slot_made_from(index, handle)); let view = heap.handle(index).and_then(|handle| { - if shows_other { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) } + if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) } }); + let at_once = || { + if late && let Some(handle) = heap.handle(index) { + let _ = host.mirror(index, handle, true); + } + }; let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); let resource = match placed.as_ref().or(view.as_ref()) { Some(&View::Shader(resource, _)) => resource as This, _ => { + at_once(); host.texture_slot_done(index, write, None); continue; } }; - let title_fills = crate::resource::host_resource(resource).is_some_and(crate::texture::title_written); + let texture = crate::resource::host_resource(resource); + let title_fills = texture.is_some_and(crate::texture::title_written); if !title_fills { + at_once(); // a render target, a depth or unordered access texture: the host's own host.texture_slot_done(index, write, None); continue; @@ -2361,6 +2375,14 @@ impl State { if shows_other && let Some(handle) = heap.handle(index) { 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 let Some(handle) = heap.handle(index) { + host.texture_slot_show_after(list, index, handle); + } + } else { + at_once(); + } let again = partly.map(|mapped| (frame + 1, mapped)); let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None }; match memory { @@ -2382,6 +2404,26 @@ impl State { if shows_other && let Some(handle) = heap.handle(index) { host.texture_slot_flip(list, index, handle); } + if late && let Some(handle) = heap.handle(index) { + host.texture_slot_show_after(list, index, handle); + } + #[cfg(feature = "diagnostics")] + if crate::book::on() + && let Some(texture) = texture.filter(|t| crate::pool::fresh(t)) + { + use windows::core::Interface; + let raw = texture.as_raw() as usize; + let asked = crate::host::submissions(); + list.defer_host(move || { + let (started, finished) = crate::host::submissions(); + crate::book::note(raw, || { + format!( + "; upload for slot {index} recorded at submissions {asked:?}, sent as submission {started} (finished {finished}) at {:.3} s", + crate::host::now_ms() as f64 / 1e3 + ) + }); + }); + } // A texture view the host refuses removes the device: name it. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if !GONE.load(Ordering::Relaxed) @@ -3158,7 +3200,7 @@ impl State { listed.tabled = Some((title + k, kind.is_some())); host.texture_slot_tabled(title + k, kind.is_some()); if kind.is_some() { - host.mirror(title + k, table + u64::from(k) * 32, true); + host.mirror_after(list, title + k, table + u64::from(k) * 32); } } if was != (listed.ready, listed.tabled) { @@ -3195,7 +3237,7 @@ impl State { { host.texture_slot_tabled(title + k, kind.is_some()); if kind.is_some() { - host.mirror(title + k, table + u64::from(k) * 32, true); + host.mirror_after(list, title + k, table + u64::from(k) * 32); } } } diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index 0c8250c..4d6a92d 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -167,6 +167,9 @@ struct Block { used_to: u64, /// The newest submission begun when it was made ([`Ripe`]). made: u64, + /// When that was (ms). + #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] + since: u64, } struct Pool { @@ -258,7 +261,7 @@ impl Pool { self.blocks.len() - 1 } }; - self.blocks[i] = Some(Block { memory, free: Ranges::new(BLOCK), used_to: 0, made }); + self.blocks[i] = Some(Block { memory, free: Ranges::new(BLOCK), used_to: 0, made, since: crate::host::now_ms() }); i } @@ -412,6 +415,25 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { } } +/// Textures made in the last second ([`fresh`]), and when. +static RECENT: Mutex> = Mutex::new(VecDeque::new()); + +/// Whether `texture` was made in a block in the last second. +pub(crate) fn fresh(texture: &ID3D12Resource) -> bool { + let raw = texture.as_raw() as usize; + let since = now().saturating_sub(1000); + RECENT.lock().unwrap_or_else(|e| e.into_inner()).iter().rev().take_while(|r| r.1 >= since).any(|r| r.0 == raw) +} + +fn made_now(texture: &ID3D12Resource) { + let now = now(); + let mut recent = RECENT.lock().unwrap_or_else(|e| e.into_inner()); + while recent.front().is_some_and(|r| r.1 + 1000 < now) { + recent.pop_front(); + } + recent.push_back((texture.as_raw() as usize, now)); +} + /// Makes `texture` give `piece` back when the last reference to it goes. fn give_back_with(texture: &ID3D12Resource, piece: Piece) { const KEY: GUID = GUID::from_u128(0x6f0e2f0c_5a59_4b1e_9a3f_7f4d2c9be713); @@ -455,7 +477,8 @@ pub(crate) unsafe fn texture( if info.SizeInBytes == u64::MAX { return None; } - let (piece, heap, _) = lock(&TEXTURES).take_ripe(info.SizeInBytes, info.Alignment.max(1), now(), Ripe::now(), || { + #[cfg_attr(not(feature = "diagnostics"), allow(unused_variables))] + let (piece, heap, again) = lock(&TEXTURES).take_ripe(info.SizeInBytes, info.Alignment.max(1), now(), Ripe::now(), || { let desc = D3D12_HEAP_DESC { SizeInBytes: BLOCK, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, @@ -483,10 +506,24 @@ pub(crate) unsafe fn texture( (Ok(()), Some(made)) => { HELD.fetch_add(piece.len, Ordering::Relaxed); give_back_with(&made, piece); + made_now(&made); #[cfg(feature = "diagnostics")] { crate::book::made(&made, || "a texture in a block".into()); crate::book::block(&heap, &made, piece.start, BLOCK); + crate::book::note(made.as_raw() as usize, || { + let block = lock(&TEXTURES).blocks.get(piece.block).and_then(Option::as_ref).map(|b| (b.made, b.since)); + let (submission, since) = block.unwrap_or_default(); + format!( + "; piece {:#x}+{:#x} of block {} {:#x} made {:.1} s before it at submission {submission}, used before: {again}, made at submissions {:?}", + piece.start, + piece.len, + piece.block, + heap.as_raw() as usize, + now().saturating_sub(since) as f64 / 1e3, + crate::host::submissions() + ) + }); } Some(made) } From 810efe5829e80d998b9b606a610a1df346c35045 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 09:39:18 -0600 Subject: [PATCH 364/445] Structure builder and rays: dispatches counted in threads, empty slots never entered, pages that are not there never hit; vertex signatures as DXC orders them From DexNom/VIctory (GPL-3.0-or-later) bc3cd4b0 and 5f4c3df4: - DispatchX's flag 0x20 says the counts are threads (bc3cd4b0). Taken for groups, a rehydration stage ran up to 64 times its threads and stored over the structures after its own. The lanes past the count leave at once, in every builder program of one dimension without a group barrier (there: in two, by digest). VICTORY_THREAD_DIMENSIONS=0: as before. - A child that is not there may have inverted infinite bounds: it was entered at minus infinity, came first and ended the walk (bc3cd4b0). - A node in a page without a copy reads zeros, a child and a box: no hit (bc3cd4b0). - Signature rows in the order of their names; vertex outputs interpolated as the title's PSV0 says; an unread input packed beside a per-vertex one is constant too (5f4c3df4), with their tests. Every shader is translated again. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 62 +++++++++++- crates/victory-gpu/src/list.rs | 17 ++-- crates/victory-gpu/src/pipeline.rs | 7 ++ crates/victory-shader/src/bvh.rs | 18 +++- crates/victory-shader/src/emit/container.rs | 58 +++++++++++- crates/victory-shader/src/emit/intersect.rs | 88 ++++++++++++----- .../src/emit/intersect_tests.rs | 6 ++ crates/victory-shader/src/emit/lower.rs | 56 ++++++++++- crates/victory-shader/src/emit/mod.rs | 94 ++++++++++++++++++- crates/victory-shader/src/emit/shader.rs | 27 ++++++ .../victory-shader/src/emit/wave64_tests.rs | 54 ++++++++++- 11 files changed, 443 insertions(+), 44 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 7ba0431..9889269 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1161,6 +1161,10 @@ impl State { if kind == USER_MEMORY_BASE { return memory.map_or(0, |m| m.base); } + // All of every group, unless the dispatch says otherwise. + if kind == victory_shader::emit::USER_DISPATCH_THREADS_X { + return 0; + } if kind == USER_ROOT_ADDRESS || kind == USER_ROOT_ADDRESS + 1 { return match self.roots_ref(compute).get(usize::from(slot)) { Some(&Root::View(address)) if kind == USER_ROOT_ADDRESS => address as u32, @@ -2526,7 +2530,7 @@ impl State { } /// Runs a dispatch on the host. - pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) { + pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32, flags: u32) { // It may write the arguments a window holds clamped. self.window = None; #[cfg(feature = "diagnostics")] @@ -2578,6 +2582,23 @@ impl State { crate::capture::op(list as *const _ as usize, || format!("builder {}", p.name)); self.list_dropped_roots([x, y, z]); } + // Counted in threads: whole groups of them, and the program is told + // how many of the last one run, where it asks (its `bind` set that to + // all of them). + let size = (flags & THREAD_DIMENSIONS != 0 && thread_dimensions()) + .then(|| p.stages.first().and_then(|s| s.translated().threads)) + .flatten(); + let threads = [x, y, z]; + let [x, y, z] = size.map_or(threads, |size| dispatch_groups(threads, size)); + if size.is_some() { + if !crate::pipeline::is_builder(self.pipeline as This) { + once!(pipeline = p.name, "a dispatch counted in threads that is not the structure builder's"); + } + if let Some((param, word)) = compute_word(p, victory_shader::emit::USER_DISPATCH_THREADS_X) { + // SAFETY: an open list; the root signature has the word. + unsafe { list.list.SetComputeRoot32BitConstant(param, threads[0], word) }; + } + } // SAFETY: an open list with everything set. unsafe { list.list.Dispatch(x, y, z) }; self.buffers_written(); @@ -3765,6 +3786,45 @@ impl State { } } +/// `DispatchX`: the counts are threads (the console's dispatch initiator bit +/// "use thread dimensions"; DexNom/VIctory bc3cd4b0). Taken for groups, a +/// rehydration stage of the structure builder ran up to 64 times its threads +/// and stored over the structures after its own (runs light-1 to light-9). +const THREAD_DIMENSIONS: u32 = 0x20; + +/// `VICTORY_THREAD_DIMENSIONS=0`: such counts are taken for groups, as before. +fn thread_dimensions() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_THREAD_DIMENSIONS").is_none_or(|v| v != "0")) +} + +/// The groups of `size` threads that hold `threads`. +fn dispatch_groups(threads: [u32; 3], size: [u32; 3]) -> [u32; 3] { + std::array::from_fn(|i| threads[i].div_ceil(size[i])) +} + +/// Where a compute pipeline's user data has a word the host computes: the +/// root parameter and the dword in it. +fn compute_word(p: &HostPipeline, kind: u32) -> Option<(u32, u32)> { + let stage = p.stages.first().filter(|_| p.compute)?; + let (param, _) = stage.user_data?; + let word = stage.translated().host.user_data.iter().find(|u| u.root == RootType::Other(kind))?; + Some((param, word.index)) +} + +#[cfg(test)] +mod thread_tests { + use super::*; + + #[test] + fn threads_are_counted_in_the_programs_groups() { + assert_eq!(dispatch_groups([8847, 1, 1], [64, 1, 1]), [139, 1, 1]); + assert_eq!(dispatch_groups([74, 1, 1], [64, 1, 1]), [2, 1, 1]); + assert_eq!(dispatch_groups([32, 1, 1], [32, 1, 1]), [1, 1, 1]); + assert_eq!(dispatch_groups([0, 12, 9], [64, 4, 4]), [0, 3, 3]); + } +} + /// The host command signature for one argument of `kind` with records /// `stride` bytes apart (no root arguments, so no root signature), made /// once. diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 52c49b0..ade005b 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1435,16 +1435,15 @@ extern "system" fn driver_hint(_: This, _feature: u64, _value: u64) -> u64 { 0 } -/// `DispatchX(x, y, z, flags)`: a dispatch with console flags, which the -/// host has no use for (the ray-tracing builder dispatches this way). -extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) { +/// `DispatchX(x, y, z, flags)`: a dispatch with console flags, of which the +/// host follows one: the counts are threads, not groups (`draw.rs` +/// `THREAD_DIMENSIONS`; the ray-tracing structure builder dispatches this way). +extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, flags: u32) { + count_dispatch(); #[cfg(windows)] - state::dispatch(this, x, y, z); + with_state(this, |list, s| s.dispatch(list, x, y, z, flags)); #[cfg(not(windows))] - { - let _ = (this, x, y, z); - count_dispatch(); - } + let _ = (this, x, y, z, flags); } /// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when @@ -1756,7 +1755,7 @@ mod state { } pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) { super::count_dispatch(); - with_state(this, |list, s| s.dispatch(list, x, y, z)); + with_state(this, |list, s| s.dispatch(list, x, y, z, 0)); } /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh /// programs take `x` groups only. diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index e94d740..7a00633 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -122,6 +122,8 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc { #[cfg(windows)] pub(crate) struct Translated { pub(crate) host: victory_shader::emit::HostShader, + /// A compute program's threads in a group. + pub(crate) threads: Option<[u32; 3]>, pub(crate) used: Vec, /// Whether the shader's code can store to buffer memory ([`stores`]); /// true when its code is not known. @@ -200,6 +202,10 @@ fn translate(container: &[u8]) -> Result { }; let host = crate::shader_cache::host_shader(container)?; let stores = programs.is_empty() || programs.iter().any(stores); + let threads = programs.iter().find_map(|p| match &p.io { + victory_shader::native::StageIo::Cs(cs) if cs.threads.iter().all(|&n| n > 0) => Some(cs.threads), + _ => None, + }); let stores_by_address = programs.is_empty() || programs.iter().any(stores_by_address); let used = programs .into_iter() @@ -213,6 +219,7 @@ fn translate(container: &[u8]) -> Result { .unwrap_or_default(); Ok(Translated { host, + threads, used, stores, stores_by_address, diff --git a/crates/victory-shader/src/bvh.rs b/crates/victory-shader/src/bvh.rs index 9f54001..3f79f82 100644 --- a/crates/victory-shader/src/bvh.rs +++ b/crates/victory-shader/src/bvh.rs @@ -196,8 +196,11 @@ pub fn boxes(children: &[u32; 4], boxes: &[[f32; 6]; 4], ray: &Ray, sort: bool) } let enter = near[0].max(near[1]).max(near[2]); let leave = far[0].min(far[1]).min(far[2]); - // A box whose minimum x is NaN is switched off. - if !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent { + // A box whose minimum x is NaN is switched off. A child that is not + // there may have inverted infinite bounds, which every ray enters at + // minus infinity: it would be first of the sorted children and end + // the walk before them (DexNom/VIctory bc3cd4b0). + if children[n] != NONE && !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent { ids[n] = children[n]; distances[n] = enter; } @@ -287,6 +290,17 @@ pub fn half_to_f32(h: u16) -> f32 { pub(crate) mod tests { use super::*; + /// An empty slot's inverted infinite bounds do not come before the + /// children a ray enters (after DexNom/VIctory bc3cd4b0). + #[test] + fn an_empty_slot_is_never_entered() { + let inside = |x: f32| [x - 1.0, -1.0, -1.0, x + 1.0, 1.0, 1.0]; + let (up, down) = (f32::INFINITY, f32::NEG_INFINITY); + let bounds = [inside(30.0), [up, up, up, down, down, down], inside(10.0), [up, up, up, down, down, down]]; + let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 100.0); + assert_eq!(boxes(&[8, NONE, 16, NONE], &bounds, &ray, true), [16, 8, NONE, NONE]); + } + /// The smallest 16-bit float not below `x` (`up`) or not above it. pub(crate) fn f32_to_half(x: f32, up: bool) -> u16 { let mut best: Option = None; diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index a244076..9ed2b78 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -72,7 +72,7 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { // Validator 1.6 writes one name per element in element order, repeats // included, except that system values share theirs (it keys names by // the semantic's string, which is one static string per system value); - // the rows sorted by register (unallocated last). + // the rows sorted by register (unallocated last), then name offset. let mut offsets: Vec = Vec::new(); let mut next = 8 + 32 * elements.len() as u32; let mut names = Vec::new(); @@ -90,7 +90,7 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { } } let mut order: Vec = (0..elements.len()).collect(); - order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), elements[i].col)); + order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), offsets[i])); for i in order { let (e, offset) = (&elements[i], offsets[i]); let used = e.usage << e.col; @@ -419,6 +419,60 @@ fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) { mod tests { use super::*; + #[test] + fn packed_vertex_outputs_preserve_name_order_and_declared_interpolation() { + let integer = SigElement { + name: "TEXCOORD".into(), + index: 1, + kind: 0, + comp: 5, + interp: 1, + row: Some(0), + col: 2, + cols: 2, + usage: 3, + half: false, + }; + let flat_float = SigElement { + name: "COLOR".into(), + index: 0, + comp: 9, + col: 0, + ..integer.clone() + }; + let smooth_float = SigElement { + index: 2, + row: Some(1), + interp: 2, + comp: 9, + ..integer.clone() + }; + let outputs = [integer, flat_float, smooth_float]; + let mut recovered = super::super::signature(&signature(&outputs, false)).unwrap(); + // DXC orders the row by semantic-name offset even though TEXCOORD + // occupies z/w and COLOR occupies x/y. + assert_eq!(recovered[0].name, "TEXCOORD"); + assert_eq!(recovered[1].name, "COLOR"); + // PSV records can be in a different order again. + let psv = psv(&Psv { + stage: 1, + flag: false, + inputs: &[], + outputs: &[outputs[2].clone(), outputs[1].clone(), outputs[0].clone()], + prims: &[], + mesh: None, + geometry: None, + bindings: &[], + threads: [0; 3], + wave_size: None, + }); + recovered[1].interp = 2; + super::super::vertex_output_interpolation(&psv, &mut recovered).unwrap(); + assert_eq!(recovered.iter().map(|e| e.interp).collect::>(), [1, 1, 2]); + assert!(super::super::vertex_output_interpolation(&psv[..psv.len() - 1], &mut recovered) + .is_err()); + } + #[test] fn md5_core_matches_the_standard() { // Standard MD5 of "abc" with standard padding, through md5_block. diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs index b5335cb..b32afa8 100644 --- a/crates/victory-shader/src/emit/intersect.rs +++ b/crates/victory-shader/src/emit/intersect.rs @@ -46,8 +46,9 @@ enum NodeAt { Buffer { handle: V, byte: V }, /// In title memory: the raw view of the host copy holding the node's /// first 64 bytes and the node's byte in it ([`Lower::bvh_memory`]), - /// and the node's address, for the second half of a 128-byte node. - Memory { handle: V, byte: V, low: V, high: V }, + /// the node's address, for the second half of a 128-byte node, and + /// whether there is a copy. + Memory { handle: V, byte: V, low: V, high: V, mapped: V }, } /// The ray operands, as floats. @@ -163,12 +164,13 @@ impl<'a> Lower<'a> { // One look for the node's copy, before the branches: a // node is 64 bytes on 64, so its first half lies in one // 64 KiB page whatever its kind. - let (handle, byte) = self.bvh_memory(low, high, guard); + let (handle, byte, mapped) = self.bvh_memory(low, high, guard); NodeAt::Memory { handle, byte, low, high, + mapped, } } }; @@ -225,7 +227,7 @@ impl<'a> Lower<'a> { /// host copy holding the address and the byte in that view /// ([`Lower::memory`]: a page the host has no copy of reads zeros and /// is left for the host to fetch, for lanes that run). - fn bvh_memory(&mut self, low: V, high: V, guard: Option) -> (V, V) { + fn bvh_memory(&mut self, low: V, high: V, guard: Option) -> (V, V, V) { #[cfg(test)] if let Some((slot, base)) = TEST_MEMORY.get() { // The buffer at heap slot `slot` holds the bytes from title @@ -242,34 +244,49 @@ impl<'a> Lower<'a> { let inside = self.s.m.bin(c, Bin::And, in_low, in_high); let outside = self.s.m.i32(0xffff_ff00); let at = self.s.m.select(c, inside, at, outside); - return (handle, at); + return (handle, at, inside); } - self.memory(low, high, guard, false) + let (handle, byte) = self.memory(low, high, guard, false); + let mapped = self.page_there.expect("memory says"); + (handle, byte, mapped) } - /// `count` dwords of the node from its byte `base` + `offset` (`base` - /// computed, `offset` fixed; none of the node's bytes past 127), read - /// four at a time. + /// The second 64 bytes of a 128-byte node: in a page, and in a copy, of + /// their own maybe. Goes on in another block. + fn bvh_second_half(&mut self, at: NodeAt) -> NodeAt { + match at { + NodeAt::Buffer { handle, byte } => { + let size = self.s.m.i32(64); + let byte = self.s.m.bin(self.cur, Bin::Add, byte, size); + NodeAt::Buffer { handle, byte } + } + NodeAt::Memory { low, high, .. } => { + let (low, high) = self.address_plus(low, high, 64); + // Every lane in this block runs the instruction. + let (handle, byte, mapped) = self.bvh_memory(low, high, None); + NodeAt::Memory { + handle, + byte, + low, + high, + mapped, + } + } + } + } + + /// `count` dwords of 64 bytes of a node from their byte `base` + `offset` + /// (`base` computed, `offset` fixed), read four at a time. fn bvh_node_words(&mut self, at: NodeAt, base: Option, offset: u32, count: u32) -> Vec { let (undef, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); - // The second half of a 128-byte node may lie in the next 64 KiB - // page, which may be in another copy: its own look, made once. - let mut second = None; + let (handle, start_byte) = match at { + NodeAt::Buffer { handle, byte } | NodeAt::Memory { handle, byte, .. } => (handle, byte), + }; let mut out = Vec::with_capacity(count as usize); for start in (0..count).step_by(4) { let n = (count - start).min(4); let node_byte = offset + 4 * start; - let (handle, mut byte) = match at { - NodeAt::Buffer { handle, byte } => (handle, byte), - NodeAt::Memory { handle, byte, .. } if node_byte < 64 => (handle, byte), - NodeAt::Memory { low, high, .. } => *second.get_or_insert_with(|| { - let (low, high) = self.address_plus(low, high, 64); - // Every lane in this block runs the instruction. - let (handle, byte) = self.bvh_memory(low, high, None); - let (k64, c) = (self.s.m.i32(64), self.cur); - (handle, self.s.m.bin(c, Bin::Sub, byte, k64)) - }), - }; + let mut byte = start_byte; let c = self.cur; if let Some(b) = base { byte = self.s.m.bin(c, Bin::Add, byte, b); @@ -328,7 +345,9 @@ impl<'a> Lower<'a> { // 32-bit floats: 24 dwords from byte 16. self.cur = wide_block; let k16 = self.s.m.i32(16); - let words = self.bvh_node_words(at, None, 16, 24); + let mut words = self.bvh_node_words(at, None, 16, 12); + let second = self.bvh_second_half(at); + words.extend(self.bvh_node_words(second, None, 0, 12)); let floats: Vec = words.iter().map(|&w| self.as_float(w)).collect(); // (The look for the second half goes on in another block.) let wide_block = self.cur; @@ -356,6 +375,21 @@ impl<'a> Lower<'a> { } self.s.m.terminate(half_block, Term::Br(join)); self.cur = join; + // A page that is not there reads zeros, which are a child and a box: + // no child of it is hit. (The last two boxes of a 128-byte node are in + // its second half.) + let there = match (at, second) { + (NodeAt::Memory { mapped: first, .. }, NodeAt::Memory { mapped: last, .. }) => { + let i1t = self.s.m.type_of(first); + let mapped = self.s.m.phi(join, i1t); + self.s + .m + .set_phi(mapped, vec![(last, wide_block), (first, half_block)]); + let both = self.s.m.bin(join, Bin::And, first, mapped); + Some([first, first, both, both]) + } + _ => None, + }; let mut coords = Vec::with_capacity(24); for n in 0..24 { let phi = self.s.m.phi(join, f32t); @@ -405,6 +439,12 @@ impl<'a> Lower<'a> { let on = self.s.m.bin(c, Bin::Xor, off, on); let hit = self.s.m.bin(c, Bin::And, through, before); let hit = self.s.m.bin(c, Bin::And, hit, on); + let child = self.s.m.cmp(c, pred::NE, children[n], none); + let hit = self.s.m.bin(c, Bin::And, hit, child); + let hit = match there { + Some(there) => self.s.m.bin(c, Bin::And, hit, there[n]), + None => hit, + }; ids[n] = self.s.m.select(c, hit, children[n], none); distances[n] = self.s.m.select(c, hit, enter, infinity); } diff --git a/crates/victory-shader/src/emit/intersect_tests.rs b/crates/victory-shader/src/emit/intersect_tests.rs index 0266579..684a08e 100644 --- a/crates/victory-shader/src/emit/intersect_tests.rs +++ b/crates/victory-shader/src/emit/intersect_tests.rs @@ -295,6 +295,12 @@ fn scene() -> (Scene, Vec>) { let ids2 = [8, bvh::NONE, 24, 0x1fff_fffc]; box_nodes.push((s.add(nodes::box32(ids2, around), 32), 5)); box_nodes.push((s.add(nodes::box16(ids2, around), 16), 4)); + // A child that is not there with inverted infinite bounds (the title's + // builder leaves such slots): every ray "enters" it at minus infinity. + let mut empty = lined; + empty[1] = [f32::INFINITY, f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY]; + let ids3 = [0x105, bvh::NONE, 0x304, 0x400]; + box_nodes.push((s.add(nodes::box32(ids3, empty), 32), 5)); // Random boxes. for n in 0..6 { let boxes: [[f32; 6]; 4] = std::array::from_fn(|_| { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 3684315..d8387d5 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -87,9 +87,33 @@ enum Stop { } pub(crate) fn lower(parts: &Parts) -> Result { + lower_counted(parts, counted_in_threads(parts)) +} + +/// Whether the title dispatches the program by a count of threads whose last +/// group may be partial: the structure builder's programs of one dimension. +/// Their lanes past the count must not run (they count the lanes of a wave +/// and store). Not where a group barrier would wait for lanes that left, nor +/// where two host waves of 32 stand for a console wave (they exchange, which +/// takes all lanes). +fn counted_in_threads(parts: &Parts) -> bool { + let crate::native::StageIo::Cs(cs) = &parts.native.io else { + return false; + }; + cs.threads[0] > 1 + && cs.threads[1..] == [1, 1] + && crate::spill::is_spilled(parts.native) + && (!parts.native.wave64 || host_max_wave() >= 64) + && !parts.p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_barrier") +} + +/// [`lower`]; `counted`: the lanes past a dispatch's count of threads leave +/// at once (`shader.rs` `USER_DISPATCH_THREADS_X`; after DexNom/VIctory +/// bc3cd4b0, which does so for two of the programs by their digests). +pub(super) fn lower_counted(parts: &Parts, counted: bool) -> Result { let mut bad = HashMap::new(); loop { - match Lower::new(parts, &bad).run() { + match Lower::new(parts, &bad).run(counted) { Ok(l) => return Ok(l), Err(Stop::Retry(v, why)) => { if bad.insert(v, why).is_some() { @@ -262,6 +286,8 @@ struct Lower<'a> { /// In the instruction being lowered: the host copy its root view's bytes /// are in ([`Lower::root_memory`]). root_copy: Option, + /// Whether the page [`Lower::memory`] last looked for has a copy. + page_there: Option, mask_phis: HashMap, pending_masks: Vec<(V, usize, usize)>, data_phis: Vec<(V, usize, usize)>, @@ -1576,6 +1602,7 @@ impl<'a> Lower<'a> { stale: HashSet::new(), coherent: HashSet::new(), root_copy: None, + page_there: None, ordered: if x.native.stage == HwStage::Ps { ordered_section(p) } else { @@ -2257,8 +2284,32 @@ impl<'a> Lower<'a> { Ok(self.s.m.bin(c, Bin::Or, first, total)) } - fn run(mut self) -> Result { + fn run(mut self, counted: bool) -> Result { let p = self.x.p; + if counted { + // Before anything else, so that wave counts, reads of the first + // lane and stores know only the lanes that run. + let original = self.s.entry; + let width = self.s.threads.expect("compute thread count")[0]; + let limit = self.host_word(RootType::Other(super::shader::USER_DISPATCH_THREADS_X), 0, width); + let Val::I32(group) = self.compute_id("groupId.i32", 94, 0) else { + unreachable!() + }; + let Val::I32(thread) = self.thread_id(0) else { + unreachable!() + }; + let width = self.s.m.i32(width); + let first = self.s.m.bin(original, Bin::Mul, group, width); + let x = self.s.m.bin(original, Bin::Add, first, thread); + let zero = self.s.m.i32(0); + let all = self.s.m.cmp(original, pred::EQ, limit, zero); + let inside = self.s.m.cmp(original, pred::IULT, x, limit); + let runs = self.s.m.bin(original, Bin::Or, all, inside); + let (body, done) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(original, Term::CondBr(runs, body, done)); + self.s.m.terminate(done, Term::Ret); + self.s.entry = body; + } self.find_coherent(); let order = crate::ir::reverse_postorder(&p.blocks); for (n, &b) in order.iter().enumerate() { @@ -3077,6 +3128,7 @@ impl<'a> Lower<'a> { ); self.end_guarded(noting, &[]); let c = self.cur; + self.page_there = Some(self.s.m.cmp(c, pred::NE, copy, zero)); let copy = if store { let closed = self.s.m.cmp(c, pred::SLT, number, zero); self.s.m.select(c, closed, zero, copy) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 2f06eac..f98517d 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -118,7 +118,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_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS, + SLOT_STRIDES_COUNT, USER_DATA_SPACE, 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, }; @@ -650,6 +650,12 @@ fn emit_program( _ => 0, }; } + // (DexNom/VIctory 5f4c3df4.) + if native.stage == HwStage::Vs + && let Some(psv) = c.part(FourCC::PSV0) + { + vertex_output_interpolation(psv.data, &mut outputs)?; + } // With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL // wants the position centroid (or per sample), as DXC declares it then. if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) { @@ -719,6 +725,67 @@ fn emit_program( Ok((shader, wave_size)) } +/// The title's vertex output interpolation lives in PSV0. A float packed +/// beside an integer can be explicitly constant, as can a float on its own. +/// OSG1 supplies the physical rows and columns used to match both tables. +fn vertex_output_interpolation( + mut data: &[u8], + outputs: &mut [container::SigElement], +) -> Result<(), ShaderError> { + const TRUNCATED: ShaderError = + ShaderError::Malformed("truncated vertex pipeline validation data"); + fn take<'a>(data: &mut &'a [u8], len: usize) -> Result<&'a [u8], ShaderError> { + let (head, tail) = data.split_at_checked(len).ok_or(TRUNCATED)?; + *data = tail; + Ok(head) + } + fn size(data: &mut &[u8]) -> Result { + Ok(u32::from_le_bytes(take(data, 4)?.try_into().unwrap()) as usize) + } + let info_size = size(&mut data)?; + let info = take(&mut data, info_size)?; + // PSVRuntimeInfo0 has no signature. PSVRuntimeInfo1 and later share + // these stage and signature count fields. + if info.len() < 36 || info[24] != 1 || info[29] == 0 { + return Ok(()); + } + let resources = size(&mut data)?; + if resources != 0 { + let stride = size(&mut data)?; + take(&mut data, resources.checked_mul(stride).ok_or(TRUNCATED)?)?; + } + let strings = size(&mut data)?; + take(&mut data, strings)?; + let indices = size(&mut data)?; + take(&mut data, indices.checked_mul(4).ok_or(TRUNCATED)?)?; + let stride = size(&mut data)?; + if stride < 16 { + return Err(TRUNCATED); + } + let count = usize::from(info[28]) + usize::from(info[29]); + let elements = take(&mut data, count.checked_mul(stride).ok_or(TRUNCATED)?)?; + for record in elements.chunks_exact(stride).skip(usize::from(info[28])) { + let packed = record[10]; + if packed & 0x40 == 0 { + continue; + } + if record[13] > 7 { + return Err(ShaderError::Malformed("invalid vertex output interpolation")); + } + let first = u32::from(record[9]); + let rows = first..first + u32::from(record[8]); + for output in outputs.iter_mut().filter(|e| { + e.row.is_some_and(|r| rows.contains(&r)) + && e.col == ((packed >> 4) & 3) + && e.cols == (packed & 15) + && e.kind == record[11] + }) { + output.interp = record[13]; + } + } + Ok(()) +} + /// The rows of an `ISG1`/`OSG1` part. fn signature(part: &[u8]) -> Result, ShaderError> { use crate::dxbc::u32_at; @@ -2232,6 +2299,10 @@ mod barycentric_tests { /// Translates a pixel program with the input VGPRs `input_addr` /// enables and one float4 TEXCOORD0 attribute (attr 0, row 0). fn pixel(words: &[u32], input_addr: u32) -> Result { + pixel_with_inputs(words, input_addr, &[element("TEXCOORD", 0, 0)]) + } + + fn pixel_with_inputs(words: &[u32], input_addr: u32, inputs: &[container::SigElement]) -> Result { let native = NativeProgram { stage: HwStage::Ps, wave64: false, @@ -2257,7 +2328,7 @@ mod barycentric_tests { }; let mut target = element("SV_Target", 16, 0); target.usage = 15; - let isg1 = container::signature(&[element("TEXCOORD", 0, 0)], true); + let isg1 = container::signature(inputs, true); let osg1 = container::signature(&[target], false); let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); let c = Container::parse(&bytes).unwrap(); @@ -2268,6 +2339,25 @@ mod barycentric_tests { emit(&c, &native, &p, &st, &io, &res) } + #[test] + fn an_unused_packed_input_matches_its_provoking_vertex_sibling() { + let [e0, e1] = exp_mrt0(3); + // v_interp_mov_f32 v3, p0, attr0.z followed by exp mrt0. + let words = [0xC80E_0202, e0, e1, 0xBF81_0000]; + let xy = container::SigElement { cols: 2, ..element("TEXCOORD", 0, 0) }; + let zw = container::SigElement { col: 2, cols: 2, ..element("NORMAL", 0, 0) }; + let shader = pixel_with_inputs(&words, PERSP_CENTER, &[xy, zw]).unwrap(); + let c = Container::parse(&shader.dxil).unwrap(); + let psv = c.part(FourCC::PSV0).unwrap().data; + for columns in [0x42, 0x62] { + let record = [1, 0, columns, 0, 3, 1]; + assert!(psv.windows(record.len()).any(|w| w == record)); + } + let inputs = c.part(FourCC::ISG1).unwrap().data; + assert_eq!((inputs[8 + 25], inputs[8 + 32 + 25]), (0, 4)); + validate(&shader); + } + /// A pixel program's first-lane loop (no table entry in it, so not a waterfall the tracker /// knows) asks for helper lanes, which is valid DXIL (upstream #946's program). #[test] diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index d33e1bd..264de50 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -80,6 +80,12 @@ pub const USER_VIEW_BIAS: u32 = 0x103; /// has no size, and the host's copy of what it names may end in the middle of /// it (a structure of megabytes crosses the 4 MiB windows). pub const USER_ROOT_ADDRESS: u32 = 0x104; +/// `RootType::Other` code of a user-data dword the host sets at a dispatch +/// counted in threads (the console's `DispatchX`): how many of the threads +/// numbered along X run (0: all of every group). The metadata's `dword` is +/// the group's width. Asked for by the structure builder's programs +/// ([`crate::spill::is_spilled`]). +pub const USER_DISPATCH_THREADS_X: u32 = 0x106; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { @@ -507,6 +513,27 @@ impl Shader { /// The finished container. pub fn finish(mut self) -> Vec { + if self.pixel { + // Reading a per-vertex value with attributeAtVertex needs a + // constant input, even when the source declaration was smooth. + // D3D requires all components packed into the same register to + // share a mode, including the ones the shader never reads. + for index in 0..self.inputs.len() { + let unused = &self.inputs[index]; + if unused.kind != 0 || unused.usage != 0 || unused.row.is_none() { + continue; + } + let mut modes = self.inputs.iter() + .filter(|e| e.row == unused.row && e.usage != 0) + .map(|e| e.interp); + if let Some(mode) = modes.next() + && (mode == 1 || unused.comp == 9) + && modes.all(|other| other == mode) + { + self.inputs[index].interp = mode; + } + } + } let ud_size = (self.user_data * 4).next_multiple_of(16); self.fix_user_data_size(ud_size); // The clean-up, before anything is declared about the code: a diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index 43f2062..5d1557b 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -104,12 +104,22 @@ fn lowered_on( p: &ir::Program, wide: &HashSet, host_wave: u32, +) -> Result { + lowered_counted(native, p, wide, host_wave, false) +} + +fn lowered_counted( + native: &NativeProgram, + p: &ir::Program, + wide: &HashSet, + host_wave: u32, + counted: bool, ) -> Result { let st = structure::structure_wide(p, wide).expect("structure"); let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track"); let io = io::raise(p, native).expect("io::raise"); let was = lower::TEST_HOST_WAVE.replace(Some(host_wave)); - let lowered = lower::lower(&lower::Parts { + let lowered = lower::lower_counted(&lower::Parts { native, p, st: &st, @@ -119,7 +129,7 @@ fn lowered_on( outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, - }); + }, counted); lower::TEST_HOST_WAVE.set(was); let lowered = lowered?; Ok(HostShader { @@ -686,3 +696,43 @@ fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() } eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside"); } + +/// A dispatch counted in threads: of the last group only the lanes below the +/// count store (after DexNom/VIctory bc3cd4b0). +#[test] +fn the_lanes_past_a_count_of_threads_do_not_run() { + // Each lane that runs adds 1 to counter[local x]. + let native = native(&[ + 0x3402_0082, // v_lshlrev_b32 v1, 2, v0 + 0x7e04_0281, // v_mov_b32 v2, 1 + 0xe0c8_1000, 0x8002_0201, // buffer_atomic_add v2, v1, s[8:11], 0 offen + ]); + let p = ir::build(&native.code, native.wave64, native.vgprs).unwrap(); + let shader = lowered_counted(&native, &p, &HashSet::new(), 64, true).unwrap(); + let limit = shader + .user_data + .iter() + .find(|u| u.root == RootType::Other(super::USER_DISPATCH_THREADS_X)) + .unwrap(); + assert_eq!((limit.slot, limit.dword), (0, 64)); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(true) else { return }; + let Ok((root, pso)) = host.compute_pipeline(&shader) else { return }; + for count in [0u32, 1, 7, 63, 64, 65, 74, 77, 127, 128] { + let mut constants = vec![0; shader.user_data_dwords() as usize]; + constants[limit.index as usize] = count; + let result = host + .dispatch(&root, &pso, &Dispatch { + roots: vec![(0, Root::Constants(constants))], + views: &[View::RawUav(68)], + samplers: &[], + groups: [2, 1, 1], + }) + .unwrap(); + let active = if count == 0 { 128 } else { count }; + for (i, &word) in result[0].iter().enumerate().take(64) { + let i = i as u32; + assert_eq!(word, u32::from(i < active) + u32::from(i + 64 < active), "count {count}, word {i}"); + } + } +} From d1c412c57b94267ef7d8c5dc1897e62e68c5ac42 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 10:39:25 -0600 Subject: [PATCH 365/445] 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 366/445] 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 367/445] 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 368/445] 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 369/445] 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 3a99ee610cc706d0e7a28dde6a4f5d82303ce70f Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:05:14 -0600 Subject: [PATCH 370/445] List calls written down and translated by threads of ours (VICTORY_THIN=1, off) The title's 45,000 to 60,000 list calls a frame append their arguments to a stream; threads of ours translate it, several lists at a time, and the line of submissions goes on with a submission when its recordings are translated. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/list.rs | 44 +- crates/victory-gpu/src/list/thin.rs | 912 +++++++++++++++++++++++++ crates/victory-gpu/src/queue.rs | 22 + crates/victory-gpu/src/queue/behind.rs | 140 +++- 4 files changed, 1096 insertions(+), 22 deletions(-) create mode 100644 crates/victory-gpu/src/list/thin.rs diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index ade005b..8a17ddb 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -18,6 +18,9 @@ use crate::object::{ use crate::queue::Written; use crate::resource::PAGEABLE_IIDS; +#[cfg(windows)] +pub(crate) mod thin; + const ALLOCATOR_IIDS: [Iid; 4] = [ guid( 0x6102dee4, @@ -127,6 +130,10 @@ struct List { /// at them before it runs `host`. #[cfg(windows)] gate: Vec, + /// With `VICTORY_THIN=1`, of a list the title has: what it wrote down + /// ([`thin`]; then there is no `host`). + #[cfg(windows)] + thin: thin::Front, } /// One part of a title list cut at its waits: the waits the queue stands @@ -560,11 +567,29 @@ fn new_list( return E_INVALIDARG; } tracing::debug!(kind, "command list"); + #[cfg(windows)] + if thin::on() { + let mut list = boxed(kind, pipeline, true); + list.thin.begin(kind, pipeline); + return object::hand_out(LIST, list, iid, &LIST_IIDS, out); + } + object::hand_out(LIST, boxed(kind, pipeline, false), iid, &LIST_IIDS, out) +} + +/// A list; with `thin` one whose calls are written down (it has no host list). +fn boxed(kind: u32, pipeline: This, thin: bool) -> Box { + #[cfg(not(windows))] + let _ = thin; let list = Box::new(List { - object: if crate::device::newer() { - Object::new(&NEWER_LIST_FUNCTIONS) - } else { - Object::new(&LIST_FUNCTIONS) + object: match (crate::device::newer(), thin) { + (true, false) => Object::new(&NEWER_LIST_FUNCTIONS), + (false, false) => Object::new(&LIST_FUNCTIONS), + #[cfg(windows)] + (true, true) => Object::new(&NEWER_THIN_FUNCTIONS), + #[cfg(windows)] + (false, true) => Object::new(&THIN_FUNCTIONS), + #[cfg(not(windows))] + _ => Object::new(&LIST_FUNCTIONS), }, kind, put: [0; 5], @@ -575,7 +600,7 @@ fn new_list( newer: [0; 256], uploads: Default::default(), #[cfg(windows)] - host: crate::host::host().and_then(|h| match h.new_list() { + host: crate::host::host().filter(|_| !thin).and_then(|h| match h.new_list() { Ok(list) => Some(list), Err(e) => { tracing::warn!(error = %e, "no host command list"); @@ -592,10 +617,12 @@ fn new_list( earlier: Vec::new(), #[cfg(windows)] gate: Vec::new(), + #[cfg(windows)] + thin: Default::default(), }); #[cfg(not(windows))] let _ = pipeline; - object::hand_out(LIST, list, iid, &LIST_IIDS, out) + list } extern "system" fn allocator_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { @@ -2339,6 +2366,11 @@ const fn list_table(newer: bool) -> [*const (); 160] { /// titles add. static LIST_FUNCTIONS: Table<160> = Table(list_table(false)); static NEWER_LIST_FUNCTIONS: Table<160> = Table(list_table(true)); +/// Of lists whose calls are written down. +#[cfg(windows)] +static THIN_FUNCTIONS: Table<160> = Table(thin::table(false)); +#[cfg(windows)] +static NEWER_THIN_FUNCTIONS: Table<160> = Table(thin::table(true)); #[cfg(test)] mod tests { diff --git a/crates/victory-gpu/src/list/thin.rs b/crates/victory-gpu/src/list/thin.rs new file mode 100644 index 0000000..1991a33 --- /dev/null +++ b/crates/victory-gpu/src/list/thin.rs @@ -0,0 +1,912 @@ +//! List calls that only write down their arguments (`VICTORY_THIN=1`); what +//! they mean is worked out by threads of ours, beside the title's. +//! +//! Why: the title makes 45,000 to 60,000 list calls a frame. Each was +//! translated inside the call, 3.5 us of it, 160 to 190 ms of processor time a +//! frame on the title's five recording threads; its own code between the calls +//! is a tenth of that. Nothing else of the title's frame could go on +//! meanwhile: recording took 55 of 65 ms, and behind it the card stood idle +//! for half the frame (timeline waits-3). On the console such a call writes a +//! few words into the list's memory and the card reads them when the list +//! runs. So it is here now: a call appends its arguments (and copies of what +//! they point at) to a stream of words; threads of ours run the stream, call +//! by call and in order, through the list methods there were before, on a list +//! of ours ([`Recording::back`]) that the title never sees. They begin while +//! the title still records (every [`CHUNK`] words are handed over), several +//! lists at a time. A submission goes into the line of submissions +//! (`crate::queue::behind`) as it was made, by the recordings' names; the +//! thread that serves the line goes on with it when they are translated. +//! +//! What may be looked at later than before, and why that is all right: all +//! that the card of the console looks at when the list runs (descriptor heaps, +//! constants, upload memory, indirect arguments): it must stay as it is until +//! the list has run, and no fence behind the list is set before. What D3D12 +//! reads at the call is copied at the call: the arrays and structures passed, +//! and the render target and depth views, whose slots may be written again +//! right after. Objects named (pipelines, resources) must live until the list +//! has run; a recording the title resets or releases without submitting it is +//! not run any further. + +use super::*; +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::*}; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; + +use crate::descriptor::RtvRecord; +use crate::draw::{IndexView, VertexView}; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT; + +/// Words after which a stream is handed to the translating threads. +const CHUNK: usize = 1024; + +/// Whether list calls are only written down (`VICTORY_THIN=1`; needs the line +/// of submissions, which it turns on). +pub(crate) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + wanted() && crate::host::host().is_some() && crate::queue::line_on() && { + start(); + true + } + }) +} + +/// Whether it is asked for. +pub(crate) fn wanted() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_THIN").is_some_and(|v| v == "1")) +} + +/// What a title list keeps: the recording being written and the words of it +/// not handed over yet. +#[derive(Default)] +pub(super) struct Front { + recording: Option>, + words: Vec, + closed: bool, + submitted: bool, +} + +impl Drop for Front { + fn drop(&mut self) { + self.leave(); + } +} + +impl Front { + /// Lets go of the recording there is: one never submitted is not run any + /// further. + fn leave(&mut self) { + if let Some(recording) = self.recording.take() + && !self.submitted + { + recording.abandoned.store(true, Release); + } + self.words.clear(); + } + + /// Begins a recording, with `pipeline` bound. + pub(super) fn begin(&mut self, kind: u32, pipeline: This) { + self.leave(); + self.recording = Some(Arc::new(Recording::new(kind))); + self.closed = false; + self.submitted = false; + self.put(RESET, &[pipeline as u64]); + } + + #[inline] + fn put(&mut self, op: u64, args: &[u64]) { + if self.closed || self.recording.is_none() { + return; + } + self.words.push(op | (args.len() as u64) << 16); + self.words.extend_from_slice(args); + if self.words.len() >= CHUNK { + self.hand_over(); + } + } + + /// [`Self::put`] of some words and then the bytes of some things. + fn put_with(&mut self, op: u64, args: &[u64], blobs: &[&[u8]]) { + if self.closed || self.recording.is_none() { + return; + } + let at = self.words.len(); + self.words.push(0); + self.words.extend_from_slice(args); + for blob in blobs { + let from = self.words.len(); + self.words.resize(from + blob.len().div_ceil(8), 0); + // SAFETY: the words just made hold the bytes; plain data. + unsafe { + std::ptr::copy_nonoverlapping(blob.as_ptr(), self.words.as_mut_ptr().add(from).cast(), blob.len()) + }; + } + let len = (self.words.len() - at - 1) as u64; + self.words[at] = op | len << 16; + if self.words.len() >= CHUNK { + self.hand_over(); + } + } + + fn hand_over(&mut self) { + let Some(recording) = &self.recording else { return }; + if self.words.is_empty() { + return; + } + let fresh = held(&WORDS).pop().unwrap_or_else(|| Vec::with_capacity(CHUNK + 256)); + let words = std::mem::replace(&mut self.words, fresh); + CHUNKS.fetch_add(1, Relaxed); + let schedule = { + let mut inner = held(&recording.inner); + inner.chunks.push_back(words); + !std::mem::replace(&mut inner.scheduled, true) + }; + if schedule { + held(&READY).push_back(recording.clone()); + WORK.notify_one(); + } + } + + fn close(&mut self) { + if self.closed { + return; + } + self.put(CLOSE, &[]); + self.closed = true; + self.hand_over(); + } +} + +/// Streams' memory to use again. +static WORDS: Mutex>> = Mutex::new(Vec::new()); +/// Recordings with words to translate. +static READY: Mutex>> = Mutex::new(VecDeque::new()); +static WORK: Condvar = Condvar::new(); +/// Lists of ours nobody uses, closed. +static BACKS: Mutex> = Mutex::new(Vec::new()); +/// Since the last line of the log: streams handed over; calls translated and +/// the microseconds that took (all threads), recordings translated, and +/// recordings let go of in the middle. +static CHUNKS: AtomicU64 = AtomicU64::new(0); +static STATS: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +fn held(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// One recording of a title list: what was written of it and not translated +/// yet, and the list of ours it goes to. +pub(crate) struct Recording { + kind: u32, + inner: Mutex, + /// Translated to its end. + done: AtomicBool, + moved: Condvar, + abandoned: AtomicBool, +} + +#[derive(Default)] +struct Inner { + chunks: VecDeque>, + /// Streams translated (commands may name places in them until the end). + kept: Vec>, + /// It is among [`READY`] or being translated. + scheduled: bool, + /// The list of ours (0: none yet). + back: usize, + /// That list was closed by the stream. + closed: bool, +} + +impl Recording { + fn new(kind: u32) -> Self { + Recording { + kind, + inner: Mutex::default(), + done: AtomicBool::new(false), + moved: Condvar::new(), + abandoned: AtomicBool::new(false), + } + } + + pub(crate) fn done(&self) -> bool { + self.done.load(Acquire) + } + + /// Waits until it is translated. + pub(crate) fn wait(&self) { + let mut inner = held(&self.inner); + while !self.done() { + inner = self.moved.wait(inner).unwrap_or_else(|e| e.into_inner()); + } + } + + /// The list of ours it went to (null: it was never begun). + pub(crate) fn back(&self) -> This { + held(&self.inner).back as This + } + + /// Translates what there is. + fn run(&self) { + loop { + let (chunk, back) = { + let mut inner = held(&self.inner); + let Some(chunk) = inner.chunks.pop_front() else { + inner.scheduled = false; + return; + }; + if inner.back == 0 { + inner.back = back_list(self.kind) as usize; + } + (chunk, inner.back as This) + }; + let began = std::time::Instant::now(); + let (calls, closed) = translate(back, &chunk, || self.abandoned.load(Acquire)); + STATS[0].fetch_add(calls, Relaxed); + STATS[1].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + let mut inner = held(&self.inner); + inner.kept.push(chunk); + if closed { + inner.closed = true; + let kept = std::mem::take(&mut inner.kept); + self.done.store(true, Release); + self.moved.notify_all(); + drop(inner); + give_back(kept); + STATS[2].fetch_add(1, Relaxed); + crate::queue::line_moved(); + } + } + } +} + +impl Drop for Recording { + fn drop(&mut self) { + let inner = self.inner.get_mut().unwrap_or_else(|e| e.into_inner()); + give_back(inner.chunks.drain(..).chain(std::mem::take(&mut inner.kept)).collect()); + if inner.back != 0 { + if !inner.closed { + // Left in the middle. + STATS[3].fetch_add(1, Relaxed); + super::close(inner.back as This); + } + held(&BACKS).push(inner.back); + } + } +} + +fn give_back(streams: Vec>) { + let mut words = held(&WORDS); + for mut s in streams { + if words.len() < 1024 && s.capacity() <= 16 * CHUNK { + s.clear(); + words.push(s); + } + } +} + +/// A list of ours, closed. +fn back_list(kind: u32) -> This { + if let Some(back) = held(&BACKS).pop() { + // SAFETY: a list of ours nobody uses. + unsafe { (*(back as *mut List)).kind = kind }; + return back as This; + } + let list: This = Box::into_raw(super::boxed(kind, std::ptr::null(), false)).cast_const().cast(); + super::close(list); + list +} + +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::queue::no_drain_here(); + loop { + let recording = { + let mut ready = held(&READY); + loop { + match ready.pop_front() { + Some(r) => break r, + None => ready = WORK.wait(ready).unwrap_or_else(|e| e.into_inner()), + } + } + }; + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| recording.run())).is_err() { + crate::host::fail(format_args!("a thread that translates lists panicked")); + } + } + }; + if let Err(e) = std::thread::Builder::new().name(format!("victory-list-{i}")).spawn(worker) { + tracing::warn!(error = %e, "a thread less to translate lists"); + } + } + tracing::info!(threads, "list calls are written down and translated by threads of ours (VICTORY_THIN=1)"); +} + +/// The recordings of submitted lists, in order (one that was not begun is left +/// out). +pub(crate) fn submitted(lists: &[This]) -> Arc<[Arc]> { + lists + .iter() + .filter(|l| !l.is_null()) + .filter_map(|&l| { + // SAFETY: the title passes its lists, which nobody records into now. + let front = unsafe { &mut (*l.cast_mut().cast::()).thin }; + front.close(); + front.submitted = true; + front.recording.clone() + }) + .collect() +} + +/// For the frame-rate line. +pub(crate) fn line(frames: f64) { + if !wanted() || !on() { + return; + } + let s: Vec = STATS.iter().map(|s| s.swap(0, Relaxed) as f64 / frames).collect(); + tracing::info!( + "list calls translated by threads of ours per frame (VICTORY_THIN): {:.0} in {:.1} ms (all threads), {:.1} lists, {:.1} pieces; left in the middle {:.2}", + s[0], + s[1] / 1000.0, + s[2], + CHUNKS.swap(0, Relaxed) as f64 / frames, + s[3] + ); +} + +#[inline] +fn front<'a>(this: This) -> &'a mut Front { + // SAFETY: the title passes one of our lists; a list is recorded by one + // thread at a time. + unsafe { &mut (*this.cast_mut().cast::()).thin } +} + +/// An argument as a word. +trait Word: Copy { + fn word(self) -> u64; + fn unword(w: u64) -> Self; +} +macro_rules! words { + ($($t:ty),*) => { $(impl Word for $t { + #[inline] + fn word(self) -> u64 { self as u64 } + #[inline] + fn unword(w: u64) -> Self { w as $t } + })* }; +} +words!(u8, u32, i32, u64, This); +impl Word for f32 { + #[inline] + fn word(self) -> u64 { + u64::from(self.to_bits()) + } + #[inline] + fn unword(w: u64) -> Self { + f32::from_bits(w as u32) + } +} + +/// The methods whose arguments are all plain values: the one the title calls, +/// and the call made of it later. +macro_rules! plain { + ($($op:ident $name:ident = $was:path, ($($a:ident: $t:ty),*);)*) => { + #[allow(clippy::upper_case_acronyms, non_camel_case_types)] + #[repr(u64)] + enum Plain { $($op),* , END } + $(extern "system" fn $name(this: This $(, $a: $t)*) { + front(this).put(Plain::$op as u64, &[$(Word::word($a)),*]); + })* + /// Whether `op` was one of them; done on `list`. + #[inline] + fn run_plain(op: u64, list: This, w: &[u64]) -> bool { + match op { + $(n if n == Plain::$op as u64 => { + let mut words = w.iter(); + $(let $a: $t = Word::unword(words.next().copied().unwrap_or(0));)* + let _ = words; + $was(list $(, $a)*); + })* + _ => return false, + } + true + } + }; +} + +plain! { + TOPOLOGY topology = state::topology, (v: u32); + STENCIL_REF stencil_ref = state::stencil_ref, (v: u32); + DEPTH_BOUNDS depth_bounds = state::depth_bounds, (min: f32, max: f32); + COMPUTE_TABLE compute_table = state::compute_table, (slot: u32, handle: u64); + GRAPHICS_TABLE graphics_table = state::graphics_table, (slot: u32, handle: u64); + COMPUTE_CONSTANT compute_constant = state::compute_constant, (slot: u32, value: u32, offset: u32); + GRAPHICS_CONSTANT graphics_constant = state::graphics_constant, (slot: u32, value: u32, offset: u32); + COMPUTE_VIEW compute_view = state::compute_view, (slot: u32, address: u64); + GRAPHICS_VIEW graphics_view = state::graphics_view, (slot: u32, address: u64); + SET_PIPELINE set_pipeline = super::set_pipeline, (pipeline: This); + DRAW draw = state::draw, (vertices: u32, instances: u32, first: u32, first_instance: u32); + DRAW_INDEXED draw_indexed = state::draw_indexed, (indices: u32, instances: u32, first: u32, base: i32, first_instance: u32); + DISPATCH dispatch = state::dispatch, (x: u32, y: u32, z: u32); + DISPATCH_X dispatch_x = super::dispatch_x, (x: u32, y: u32, z: u32, flags: u32); + DISPATCH_MESH dispatch_mesh = state::dispatch_mesh, (x: u32, y: u32, z: u32); + DISPATCH_MESH_X dispatch_mesh_x = state::dispatch_mesh_x, (x: u32, flags: u64, indirect: u64, payload: u64); + COPY_BUFFER copy_buffer_region = super::copy_buffer_region, (dst: This, dst_offset: u64, src: This, src_offset: u64, len: u64); + COPY_RESOURCE copy_resource = super::copy_resource, (dst: This, src: This); + COPY_RESOURCE_X copy_resource_x = super::copy_resource_x, (dst: This, src: This, flags: u32); + COPY_MEMORY copy_memory = super::copy_memory, (dst: u64, src: u64, len: u64, flags: u32); + RESOLVE resolve = super::resolve, (dst: This, dst_sub: u32, src: This, src_sub: u32, format: u32); + RESOLVE_QUERIES resolve_queries = super::resolve_queries, (heap: This, kind: u32, first: u32, count: u32, buffer: This, offset: u64); + EXECUTE_INDIRECT execute_indirect = super::execute_indirect, (signature: This, max: u32, arguments: This, offset: u64, count: This, count_offset: u64); + WRITE32 write32 = super::write32, (address: u64, value: u32, flush: u32, flags: u32); + WRITE64 write64 = super::write64, (address: u64, value: u64, flush: u32, flags: u32); + WAIT_VALUE wait_value = super::wait_value, (address: u64, comparison: u32, reference: u64); + WAIT_VALUE64 wait_value64 = super::wait_value64, (address: u64, comparison: u32, reference: u64); + SYNC sync = super::sync, (flags: u32, control: u32, address: u64, size: u64); +} + +const fn after(n: u64) -> u64 { + Plain::END as u64 + n +} +const RESET: u64 = after(0); +const CLOSE: u64 = after(1); +const UPLOAD: u64 = after(2); +const BARRIER: u64 = after(3); +const BARRIER_GROUPS: u64 = after(4); +const VIEWPORTS: u64 = after(5); +const SCISSORS: u64 = after(6); +const BLEND_FACTOR: u64 = after(7); +const HEAPS: u64 = after(8); +const COMPUTE_CONSTANTS: u64 = after(9); +const GRAPHICS_CONSTANTS: u64 = after(10); +const INDEX_BUFFER: u64 = after(11); +const VERTEX_BUFFERS: u64 = after(12); +const TARGETS: u64 = after(13); +const CLEAR_RTV: u64 = after(14); +const CLEAR_DSV: u64 = after(15); +const COPY_TEXTURE: u64 = after(16); + +/// The bytes of `count` things at `items` (none if null). +fn bytes_of<'a, T>(items: *const T, count: usize) -> &'a [u8] { + if items.is_null() || count == 0 { + return &[]; + } + // SAFETY: the title passes `count` items. + unsafe { std::slice::from_raw_parts(items.cast(), count * size_of::()) } +} + +/// Where the things are in a stream (null for none). +fn at(w: &[u64], from: usize, count: usize) -> *const T { + if count == 0 || from >= w.len() { std::ptr::null() } else { w[from..].as_ptr().cast() } +} + +/// [`at`] where an empty array is not null. +fn at_or(w: &[u64], from: usize) -> *const T { + // SAFETY: at most one past the end. + unsafe { w.as_ptr().add(from.min(w.len())).cast() } +} + +/// A view's record as it is now (zeros for no view), so that its slot may be +/// written again: the copy stands for the handle. +fn record(handle: u64) -> [u64; RECORD] { + let mut words = [0u64; RECORD]; + if handle != 0 { + // SAFETY: a descriptor slot the title passes (they are larger). + unsafe { + std::ptr::copy_nonoverlapping(handle as *const u8, words.as_mut_ptr().cast(), size_of::()) + }; + } + words +} +const RECORD: usize = size_of::().div_ceil(8); + +extern "system" fn list_close(this: This) -> HRESULT { + front(this).close(); + S_OK +} +extern "system" fn list_reset(this: This, allocator: This, pipeline: This) -> HRESULT { + if allocator.is_null() { + return E_INVALIDARG; + } + // SAFETY: the title passes one of our lists. + let kind = unsafe { (*this.cast::()).kind }; + front(this).begin(kind, pipeline); + S_OK +} +extern "system" fn list_reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT { + list_reset(this, allocator, pipeline) +} +extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 { + let align = usize::try_from(alignment).unwrap_or(0).max(16); + let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else { + return std::ptr::null_mut(); + }; + if this.is_null() || !align.is_power_of_two() { + return std::ptr::null_mut(); + } + let front = front(this); + if front.closed || front.recording.is_none() { + return std::ptr::null_mut(); + } + let Some(mut block) = Upload::new(len) else { + return std::ptr::null_mut(); + }; + let start = block.start(); + // SAFETY: the offset is below `align`, so `size` bytes fit after it. + let place = unsafe { start.add(start.align_offset(align)) }; + front.put(UPLOAD, &[Box::into_raw(Box::new(block)) as u64]); + place +} +extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 { + if !barriers.is_null() { + front(this).put_with(BARRIER, &[u64::from(count)], &[bytes_of(barriers, count as usize)]); + } + 0 +} +extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { + front(this).put(BARRIER_GROUPS, &[u64::from(count)]); +} +extern "system" fn viewports(this: This, count: u32, items: *const D3D12_VIEWPORT) { + let count = if items.is_null() { 0 } else { count }; + front(this).put_with(VIEWPORTS, &[u64::from(count)], &[bytes_of(items, count as usize)]); +} +extern "system" fn scissors(this: This, count: u32, items: *const RECT) { + let count = if items.is_null() { 0 } else { count }; + front(this).put_with(SCISSORS, &[u64::from(count)], &[bytes_of(items, count as usize)]); +} +extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) { + let given = !factor.is_null(); + front(this).put_with(BLEND_FACTOR, &[u64::from(given)], &[bytes_of(factor, usize::from(given))]); +} +extern "system" fn heaps(this: This, count: u32, items: *const This) { + let count = if items.is_null() { 0 } else { count }; + front(this).put_with(HEAPS, &[u64::from(count)], &[bytes_of(items, count as usize)]); +} +fn constants(this: This, op: u64, slot: u32, count: u32, values: *const u32, offset: u32) { + let count = if values.is_null() { 0 } else { count }; + front(this).put_with( + op, + &[u64::from(slot) | u64::from(offset) << 32, u64::from(count)], + &[bytes_of(values, count as usize)], + ); +} +extern "system" fn compute_constants(this: This, slot: u32, count: u32, values: *const u32, offset: u32) { + constants(this, COMPUTE_CONSTANTS, slot, count, values, offset); +} +extern "system" fn graphics_constants(this: This, slot: u32, count: u32, values: *const u32, offset: u32) { + constants(this, GRAPHICS_CONSTANTS, slot, count, values, offset); +} +extern "system" fn index_buffer(this: This, view: *const IndexView) { + let given = !view.is_null(); + front(this).put_with(INDEX_BUFFER, &[u64::from(given)], &[bytes_of(view, usize::from(given))]); +} +extern "system" fn vertex_buffers(this: This, start: u32, count: u32, views: *const VertexView) { + let given = !views.is_null(); + front(this).put_with( + VERTEX_BUFFERS, + &[u64::from(start) | u64::from(count) << 32, u64::from(given)], + &[bytes_of(views, count as usize)], + ); +} +extern "system" fn targets(this: This, count: u32, handles: *const u64, one_range: i32, depth: *const u64) { + let count = if handles.is_null() { 0 } else { (count as usize).min(8) }; + // SAFETY: the title passes a handle or null. + let depth = unsafe { depth.as_ref() }.copied().unwrap_or(0); + let mut records = [0u64; RECORD * 9]; + let mut present = 0u64; + for i in 0..count { + // SAFETY: the title passes `count` handles, or the first of a range + // of views of 128 bytes. + let handle = unsafe { if one_range != 0 { *handles + 128 * i as u64 } else { *handles.add(i) } }; + present |= u64::from(handle != 0) << i; + records[i * RECORD..(i + 1) * RECORD].copy_from_slice(&record(handle)); + } + records[count * RECORD..(count + 1) * RECORD].copy_from_slice(&record(depth)); + let records = &records[..(count + 1) * RECORD]; + front(this).put_with( + TARGETS, + &[count as u64, present, u64::from(depth != 0)], + &[bytes_of(records.as_ptr(), records.len())], + ); +} +extern "system" fn clear_rtv(this: This, handle: u64, color: *const [f32; 4], count: u32, rects: *const Rect) { + if handle == 0 || color.is_null() { + return; + } + let count = if rects.is_null() { 0 } else { count }; + let view = record(handle); + front(this).put_with( + CLEAR_RTV, + &[u64::from(count)], + &[bytes_of(view.as_ptr(), RECORD), bytes_of(color, 1), bytes_of(rects, count as usize)], + ); +} +extern "system" fn clear_dsv( + this: This, + handle: u64, + flags: u32, + depth: f32, + stencil: u8, + count: u32, + rects: *const Rect, +) { + if handle == 0 { + return; + } + let count = if rects.is_null() { 0 } else { count }; + let view = record(handle); + front(this).put_with( + CLEAR_DSV, + &[u64::from(count), u64::from(flags) | u64::from(stencil) << 32, Word::word(depth)], + &[bytes_of(view.as_ptr(), RECORD), bytes_of(rects, count as usize)], + ); +} +extern "system" fn copy_texture_region( + this: This, + dst: *const CopyLocation, + x: u32, + y: u32, + z: u32, + src: *const CopyLocation, + source_box: *const [u32; 6], +) { + if dst.is_null() || src.is_null() { + return; + } + let boxed = !source_box.is_null(); + front(this).put_with( + COPY_TEXTURE, + &[u64::from(x) | u64::from(y) << 32, u64::from(z) | u64::from(boxed) << 32], + &[bytes_of(dst, 1), bytes_of(src, 1), bytes_of(source_box, usize::from(boxed))], + ); +} +#[allow(clippy::too_many_arguments)] // the method's own arguments +extern "system" fn copy_texture_region_x( + this: This, + dst: *const CopyLocation, + x: u32, + y: u32, + z: u32, + src: *const CopyLocation, + source_box: *const [u32; 6], + _flags: u32, +) { + copy_texture_region(this, dst, x, y, z, src, source_box); +} + +/// Makes the calls of a stream on `list`: how many, and whether the last one +/// closed it. Once `left` says so only what must not be lost is done. +fn translate(list: This, stream: &[u64], left: impl Fn() -> bool) -> (u64, bool) { + let (mut i, mut calls, mut closed) = (0, 0, false); + let mut skip = left(); + while i < stream.len() { + let (op, len) = (stream[i] & 0xffff, (stream[i] >> 16) as usize); + let w = &stream[i + 1..i + 1 + len]; + i += 1 + len; + calls += 1; + if calls % 64 == 0 { + skip = left(); + } + if op == UPLOAD { + // SAFETY: made by `allocate_upload`, named once. + let block = *unsafe { Box::from_raw(w[0] as *mut Upload) }; + // SAFETY: a list of ours. + let uploads = unsafe { &(*list.cast::()).uploads }; + held(uploads).push(block); + continue; + } + if skip && op != CLOSE && op != RESET { + continue; + } + if run_plain(op, list, w) { + continue; + } + let n = w.first().map_or(0, |&n| n as usize); + match op { + RESET => { + // (Only whether there is an allocator is looked at.) + let allocator: This = std::ptr::NonNull::::dangling().as_ptr().cast_const().cast(); + super::reset(list, allocator, w[0] as This); + } + CLOSE => { + super::close(list); + closed = true; + } + BARRIER => { + super::barrier(list, n as u32, at_or(w, 1)); + } + BARRIER_GROUPS => super::barrier_groups(list, n as u32, std::ptr::null()), + VIEWPORTS => state::viewports(list, n as u32, at(w, 1, n)), + SCISSORS => state::scissors(list, n as u32, at(w, 1, n)), + BLEND_FACTOR => state::blend_factor(list, at(w, 1, n)), + HEAPS => state::heaps(list, n as u32, at(w, 1, n)), + COMPUTE_CONSTANTS => { + state::compute_constants(list, w[0] as u32, w[1] as u32, at(w, 2, w[1] as usize), (w[0] >> 32) as u32) + } + GRAPHICS_CONSTANTS => { + state::graphics_constants(list, w[0] as u32, w[1] as u32, at(w, 2, w[1] as usize), (w[0] >> 32) as u32) + } + INDEX_BUFFER => state::index_buffer(list, at(w, 1, n)), + VERTEX_BUFFERS => { + let views = if w[1] != 0 { at_or(w, 2) } else { std::ptr::null() }; + state::vertex_buffers(list, w[0] as u32, (w[0] >> 32) as u32, views); + } + TARGETS => { + let mut handles = [0u64; 8]; + let place = |k: usize| w[3 + k * RECORD..].as_ptr() as u64; + for (k, h) in handles.iter_mut().enumerate().take(n) { + if w[1] >> k & 1 != 0 { + *h = place(k); + } + } + let depth = if w[2] != 0 { place(n) } else { 0 }; + state::targets(list, n as u32, handles.as_ptr(), 0, &depth); + } + CLEAR_RTV => { + super::clear_rtv( + list, + w[1..].as_ptr() as u64, + at_or(w, 1 + RECORD), + n as u32, + at(w, 1 + RECORD + 2, n), + ); + } + CLEAR_DSV => { + super::clear_dsv( + list, + w[3..].as_ptr() as u64, + w[1] as u32, + Word::unword(w[2]), + (w[1] >> 32) as u8, + n as u32, + at(w, 3 + RECORD, n), + ); + } + COPY_TEXTURE => { + let step = size_of::().div_ceil(8); + let boxed = (w[1] >> 32) as usize; + super::copy_texture_region( + list, + at_or(w, 2), + w[0] as u32, + (w[0] >> 32) as u32, + w[1] as u32, + at_or(w, 2 + step), + at(w, 2 + 2 * step, boxed), + ); + } + _ => {} + } + } + (calls, closed) +} + +/// The table of a list whose calls are written down: that of the others with +/// the methods that record replaced (slots as in [`super::METHODS`]). +pub(super) const fn table(newer: bool) -> [*const (); 160] { + let mut f = super::list_table(newer); + let mut i = 0; + while i < MINE.len() { + let (slot, method) = MINE[i]; + f[if newer { newer_slot(slot) } else { slot }] = method; + i += 1; + } + if newer { + f[146] = barrier_groups as *const (); + f[148] = allocate_upload as *const (); + } + f +} + +const MINE: [(usize, *const ()); 50] = [ + (9, list_close as *const ()), + (10, list_reset as *const ()), + (12, draw as *const ()), + (13, draw_indexed as *const ()), + (14, dispatch as *const ()), + (15, copy_buffer_region as *const ()), + (16, copy_texture_region as *const ()), + (17, copy_resource as *const ()), + (19, resolve as *const ()), + (20, topology as *const ()), + (21, viewports as *const ()), + (22, scissors as *const ()), + (23, blend_factor as *const ()), + (24, stencil_ref as *const ()), + (25, set_pipeline as *const ()), + (26, barrier as *const ()), + (30, resolve_queries as *const ()), + (32, heaps as *const ()), + (35, compute_table as *const ()), + (36, graphics_table as *const ()), + (37, compute_constant as *const ()), + (38, graphics_constant as *const ()), + (39, compute_constants as *const ()), + (40, graphics_constants as *const ()), + (41, compute_view as *const ()), + (42, graphics_view as *const ()), + (43, compute_view as *const ()), + (44, graphics_view as *const ()), + (45, compute_view as *const ()), + (46, graphics_view as *const ()), + (47, index_buffer as *const ()), + (48, vertex_buffers as *const ()), + (50, targets as *const ()), + (51, clear_dsv as *const ()), + (52, clear_rtv as *const ()), + (59, execute_indirect as *const ()), + (60, copy_memory as *const ()), + (68, depth_bounds as *const ()), + (69, write32 as *const ()), + (70, write64 as *const ()), + (71, wait_value as *const ()), + (72, wait_value64 as *const ()), + (78, dispatch_x as *const ()), + (83, copy_texture_region_x as *const ()), + (84, copy_resource_x as *const ()), + (98, dispatch_mesh_x as *const ()), + (127, dispatch_mesh as *const ()), + (129, sync as *const ()), + (130, sync as *const ()), + (137, list_reset_x as *const ()), +]; + +#[cfg(test)] +mod tests { + use super::*; + + /// Every method of the tables that records is written down too: what is + /// left in both tables alike records nothing. + #[test] + fn every_recording_method_is_written_down() { + const NOTHING: [usize; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 28, 29, 33, 34, 73, 99, 124]; + let mine: Vec = MINE.iter().map(|m| m.0).collect(); + for (slot, _) in METHODS.iter().chain(MORE_METHODS.iter()) { + assert!(mine.contains(slot) != NOTHING.contains(slot), "slot {slot}"); + } + for &slot in &mine { + assert!( + METHODS.iter().chain(MORE_METHODS.iter()).any(|m| m.0 == slot), + "slot {slot} is written down and not there" + ); + } + } + + /// Arguments come out of a stream as they went in. + #[test] + fn a_stream_gives_back_what_was_written() { + let mut f = Front::default(); + f.recording = Some(Arc::new(Recording::new(0))); + f.put(Plain::DRAW_INDEXED as u64, &[3, 1, 0, Word::word(-7i32), 5]); + let viewport = [1.0f32, 2.0, 3.0, 4.0, 0.0, 1.0]; + f.put_with(VIEWPORTS, &[1], &[bytes_of(viewport.as_ptr(), 6)]); + f.put_with(COMPUTE_CONSTANTS, &[4 | 2 << 32, 3], &[bytes_of([7u32, 8, 9].as_ptr(), 3)]); + let s = std::mem::take(&mut f.words); + assert_eq!((s[0] & 0xffff, s[0] >> 16), (Plain::DRAW_INDEXED as u64, 5)); + assert_eq!(::unword(s[4]), -7); + let w = &s[6..]; + assert_eq!((w[0] & 0xffff, w[0] >> 16, w[1]), (VIEWPORTS, 4, 1)); + // SAFETY: what was written just now. + assert_eq!(unsafe { *at::<[f32; 6]>(&w[1..], 1, 1) }, viewport); + let w = &w[5..]; + assert_eq!((w[0] & 0xffff, w[0] >> 16), (COMPUTE_CONSTANTS, 4)); + // SAFETY: as above. + assert_eq!(unsafe { *at::<[u32; 3]>(&w[1..], 2, 3) }, [7, 8, 9]); + assert!(at::(&w[1..], 2, 0).is_null()); + } + + /// A view's record is the one at the call, also if its slot is written + /// again right after. + #[test] + fn a_target_is_the_one_at_the_call() { + let mut slot = [0x5256_5476u64, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + let kept = record(slot.as_ptr() as u64); + slot[1] = 99; + assert_eq!(kept[1], 2); + assert_eq!(record(0), [0; RECORD]); + } +} diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 90ec3d8..b4cf177 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -442,6 +442,24 @@ pub(crate) fn before_sync() { } } +/// Whether submissions go into the line of a thread of ours ([`behind`]). +#[cfg(windows)] +pub(crate) fn line_on() -> bool { + behind::on() +} + +/// Lists in the line may have been translated ([`crate::list::thin`]). +#[cfg(windows)] +pub(crate) fn line_moved() { + behind::wake(); +} + +/// This thread does work the line waits for: it does not wait for the line. +#[cfg(windows)] +pub(crate) fn no_drain_here() { + behind::no_drain_here(); +} + /// Submissions the title made that the host has not begun ([`behind`]). #[cfg(windows)] pub(crate) fn queued() -> u64 { @@ -452,6 +470,7 @@ pub(crate) fn queued() -> u64 { #[cfg(windows)] pub(crate) fn behind_line(frames: f64) { if behind::on() { + crate::list::thin::line(frames); behind::line(frames); } } @@ -921,6 +940,9 @@ extern "system" fn present( crate::resource::host_copy(resource).map(|copy| { let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before); crate::resource::host_transition(resource, state); + // (Lists not translated yet leave it in no state yet: the + // one it is in when its turn in the line comes.) + let state = if crate::list::thin::wanted() { u32::MAX } else { state }; (resource as usize, copy, state) }) } else { diff --git a/crates/victory-gpu/src/queue/behind.rs b/crates/victory-gpu/src/queue/behind.rs index b2f3de7..b7152de 100644 --- a/crates/victory-gpu/src/queue/behind.rs +++ b/crates/victory-gpu/src/queue/behind.rs @@ -61,6 +61,19 @@ pub(super) trait Work: Send { fn shows(&self) -> bool; /// Whether it is a submission. fn runs(&self) -> bool; + /// Whether it stands for other work, which takes its place in the line + /// once it is free to go ([`Work::unfold`]). + fn folded(&self) -> bool { + false + } + fn unfold(self) -> Vec + where + Self: Sized, + { + vec![self] + } + /// Waits until a folded one is free to go. + fn settle(_: &Self::Ask) {} /// Does it. `forced`: its wait was not met. fn go(self, forced: bool); } @@ -166,6 +179,9 @@ impl Lane { /// Waits until everything in the line that is free to run has been done /// (what comes in after this call may not be). pub(super) fn drain(&self) { + let folded: Vec = + self.lock().items.iter().filter(|e| e.what.folded()).filter_map(|e| e.what.ask()).collect(); + folded.iter().for_each(W::settle); let mut state = self.lock(); if state.items.is_empty() && state.running.is_none() { return; @@ -234,11 +250,14 @@ impl Lane { fn step(&self, limit: u64) -> bool { // Each queue's first entry, oldest first. let mut heads: Vec<(u64, usize, Option, bool)> = Vec::new(); + // Whether one of them stands for others not known yet. + let mut folded = false; { let state = self.lock(); for e in state.items.iter().take_while(|e| e.number < limit) { if !heads.iter().any(|h| h.1 == e.queue) { heads.push((e.number, e.queue, e.what.ask(), e.what.shows())); + folded |= e.what.folded(); } } } @@ -255,7 +274,11 @@ impl Lane { None => { // Nothing is free to run. With a present in the line the // oldest goes on regardless: a wait is not kept across - // frames (`super::present`). + // frames (`super::present`). (Not while there is work whose + // parts are not known: it may be what is waited for.) + if folded { + return false; + } let state = self.lock(); if !super::forces() || !state.items.iter().any(|e| e.number < limit && e.what.shows()) { return false; @@ -275,6 +298,24 @@ impl Lane { entry }; let (shows, runs) = (entry.what.shows(), entry.what.runs()); + if entry.what.folded() { + // Its parts take its place: behind everything before it, before + // everything after it (they share its number; the first of them + // is found first). + let (number, queue) = (entry.number, entry.queue); + let parts = entry.what.unfold(); + let mut state = self.lock(); + state.running = None; + state.runs -= usize::from(runs); + state.runs += parts.iter().filter(|p| p.runs()).count(); + let place = state.items.iter().position(|e| e.number > number).unwrap_or(state.items.len()); + for (i, what) in parts.into_iter().enumerate() { + state.items.insert(place + i, Entry { number, queue, what }); + } + drop(state); + self.moved.notify_all(); + return true; + } entry.what.go(forced); { let mut state = self.lock(); @@ -287,6 +328,8 @@ impl Lane { } } +type Recordings = std::sync::Arc<[std::sync::Arc]>; + /// What the title's queues put in the line. enum Job { /// The queue waits for the fence (its address) to reach the value. @@ -296,6 +339,9 @@ enum Job { /// A submission, or a part of one: the lists' host sides and the order /// they run in. Run(usize, Vec, Vec), + /// A submission whose lists are being translated ([`crate::list::thin`]): + /// the parts of it are known when they are. + Lists(usize, Recordings), /// A signal of the queue's. Signal(usize, u64), /// A frame is shown: the texture and the state its lists leave it in. @@ -310,6 +356,7 @@ unsafe impl Send for Job {} enum Ask { Wait(usize, u64), Value(crate::list::ValueWait), + Lists(Recordings), } impl Work for Job { @@ -319,14 +366,40 @@ impl Work for Job { match self { &Job::Wait(fence, value) => Some(Ask::Wait(fence, value)), Job::Value(wait) => Some(Ask::Value(*wait)), + Job::Lists(_, lists) => Some(Ask::Lists(lists.clone())), _ => None, } } + fn folded(&self) -> bool { + matches!(self, Job::Lists(..)) + } + + fn unfold(self) -> Vec { + let Job::Lists(queue, recordings) = self else { + return vec![self]; + }; + let lists: Vec = recordings.iter().map(|r| r.back()).collect(); + let jobs = jobs_of(queue as This, &lists); + // It stood for one submission not begun. + let runs = jobs.iter().filter(|j| j.runs()).count() as u64; + QUEUED.fetch_add(runs, Relaxed); + QUEUED.fetch_sub(1, Relaxed); + STATS[RUNS].fetch_add(runs, Relaxed); + jobs + } + + fn settle(ask: &Ask) { + if let Ask::Lists(recordings) = ask { + recordings.iter().for_each(|r| r.wait()); + } + } + fn met(ask: &Ask) -> bool { match ask { &Ask::Wait(fence, value) => crate::fence::completed(fence as This) >= value, Ask::Value(wait) => super::value_met(wait), + Ask::Lists(recordings) => recordings.iter().all(|r| r.done()), } } @@ -335,7 +408,7 @@ impl Work for Job { } fn runs(&self) -> bool { - matches!(self, Job::Run(..)) + matches!(self, Job::Run(..) | Job::Lists(..)) } fn go(self, forced: bool) { @@ -354,7 +427,8 @@ impl Work for Job { ONCE.call_once(|| tracing::warn!("a queue still stood at a wait at a present: it was not met")); } match self { - Job::Wait(..) | Job::Value(..) => {} + // (A folded one is unfolded, never done.) + Job::Wait(..) | Job::Value(..) | Job::Lists(..) => {} Job::Run(queue, lists, order) => { let _ = queue; #[cfg(feature = "diagnostics")] @@ -372,6 +446,9 @@ impl Work for Job { } Job::Present(texture, shown) => { if let Some((texture, state)) = texture { + // (Where its lists were not translated when the title + // presented: the state they left it in.) + let state = if state == u32::MAX { texture.state.load(Relaxed) } else { state }; super::show(&texture.texture, state, shown); } QUEUED.fetch_sub(1, Relaxed); @@ -438,7 +515,9 @@ pub(super) fn on() -> bool { return on && started(); } static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_ASYNC_SUBMIT").is_some_and(|v| v == "1") && started()) + *ON.get_or_init(|| { + (std::env::var_os("VICTORY_ASYNC_SUBMIT").is_some_and(|v| v == "1") || crate::list::thin::wanted()) && started() + }) } /// The line is about to be left for the way without it: everything in it is @@ -498,6 +577,11 @@ pub(super) fn wake() { LANE.wake(); } +/// This thread does work the line waits for. +pub(super) fn no_drain_here() { + OURS.set(true); +} + /// Before something that has to see the submissions made so far sent: they /// are, as far as they are free to run. Not on our own thread, which is /// inside one of them. @@ -513,6 +597,41 @@ pub(super) fn drain() { /// A submission of `lists` to queue `this`. pub(super) fn submit(this: This, lists: &[This]) { + let queue = this as usize; + if crate::list::thin::on() { + let recordings = crate::list::thin::submitted(lists); + if recordings.is_empty() { + return; + } + let before = QUEUED.fetch_add(1, Relaxed); + STATS[DEPTH].fetch_add(before, Relaxed); + STATS[DEEPEST].fetch_max(before + 1, Relaxed); + LANE.push(queue, [Job::Lists(queue, recordings)]); + room(before + 1); + return; + } + let jobs = jobs_of(this, lists); + let runs = jobs.iter().filter(|j| j.runs()).count() as u64; + let before = QUEUED.fetch_add(runs, Relaxed); + STATS[RUNS].fetch_add(runs, Relaxed); + STATS[DEPTH].fetch_add(before, Relaxed); + STATS[DEEPEST].fetch_max(before + runs, Relaxed); + LANE.push(queue, jobs); + room(before + runs); +} + +/// Waits for room in the line, with `queued` submissions in it. +fn room(queued: u64) { + if queued > runs_most() as u64 { + let began = Instant::now(); + let _waiting = crate::timeline::span("a submission waits for room in the line"); + LANE.wait_runs(runs_most()); + STATS[ROOM].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + } +} + +/// What a submission of `lists` is in the line. +fn jobs_of(this: This, lists: &[This]) -> Vec { let queue = this as usize; // In one piece up to the first list that waits for a memory value, as // `super::submit_cut` runs them; the rest part by part. @@ -542,18 +661,7 @@ pub(super) fn submit(this: This, lists: &[This]) { jobs.push(Job::Run(queue, taken, order)); } } - let runs = jobs.iter().filter(|j| j.runs()).count() as u64; - let before = QUEUED.fetch_add(runs, Relaxed); - STATS[RUNS].fetch_add(runs, Relaxed); - STATS[DEPTH].fetch_add(before, Relaxed); - STATS[DEEPEST].fetch_max(before + runs, Relaxed); - LANE.push(queue, jobs); - if before + runs > runs_most() as u64 { - let began = Instant::now(); - let _waiting = crate::timeline::span("a submission waits for room in the line"); - LANE.wait_runs(runs_most()); - STATS[ROOM].fetch_add(began.elapsed().as_micros() as u64, Relaxed); - } + jobs } /// A signal of queue `this`: behind what it has in the line; if that is From 30f46c92a974514ba0a90acc36c814c237c002bc Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:09:40 -0600 Subject: [PATCH 371/445] 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 372/445] 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 373/445] 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 374/445] 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 375/445] 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 376/445] 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 377/445] 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 378/445] 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 379/445] 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 380/445] 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 381/445] 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 382/445] 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 383/445] 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 384/445] 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 20b9834252d9da0128bbda5172962050010d71aa Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:49:12 -0600 Subject: [PATCH 385/445] Max, min, legacy products, medians and fractions as the RDNA card's own (VICTORY_RDNA_FLOAT, on; 0: spelled out as before) The console's v_max/v_min (seven host operations each, for the order of the two zeros), v_mul_legacy (a product, two comparisons, an or and a select; two thirds of all products of the lighting program), v_med3 and v_fract are written as the one operation the driver makes the same instruction of, where the host is an AMD card with waves of 32 and 64. Checked on the RX 7900 XTX against the spelled-out forms with zeros, infinities and NaN (a legacy product's zero may have the other sign). RX 7900 XTX, yard capture replayed turn by turn with and without (12 loops each): dispatches and draws 18.41 -> 17.58 ms, the lists' 29.2 -> 28.4 of a 36.6 ms frame; 0.4 of it without the legacy products. The picture is the same (79 dB; two replays of one set differ by 68). A product that is only a product would give 0.65 ms more and NaN where the console has 0. Measured and left out (nothing): v_mad as one multiply-add, fast reciprocals, scalar loads of four dwords at once, buffers picked from the heap read without asking for their kind (0.12 ms), a wave size for every compute program (32: +0.26 ms, 64: +0.1, the console's: +0.1), no barriers at all (0). Changes the translator: every shader is translated again. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 12 +++ crates/victory-gpu/src/indirect.rs | 2 +- crates/victory-shader/src/emit/bitcode/opt.rs | 76 +++++++++++++++++ crates/victory-shader/src/emit/lower.rs | 77 ++++++++++++++++- crates/victory-shader/src/emit/mod.rs | 56 +++++++++++- crates/victory-shader/src/emit/probe_tests.rs | 74 ++++++++++++++++ crates/victory-shader/src/emit/valu_tests.rs | 85 +++++++++++++++++++ 7 files changed, 377 insertions(+), 5 deletions(-) create mode 100644 crates/victory-shader/src/emit/probe_tests.rs diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 507a79d..8cee056 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -921,6 +921,9 @@ fn create() -> windows::core::Result { { tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes"); victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax); + // (RDNA has waves of 32 and 64, the vendor's older cards of 64 alone.) + let amd = crate::indirect::amd(&device); + victory_shader::emit::set_host_rdna(amd && o1.WaveLaneCountMin == 32 && o1.WaveLaneCountMax == 64); } let messages = debug .then(|| device.cast::().ok()) @@ -968,6 +971,15 @@ fn create() -> windows::core::Result { } } +impl Host { + /// The driver's version, as the system counts it (0: not known). + pub(crate) fn driver(&self) -> i64 { + let adapter = self.adapter.as_ref(); + // SAFETY: a plain query. + adapter.map_or(0, |a| unsafe { a.CheckInterfaceSupport(&IDXGIDevice::IID) }.unwrap_or(0)) + } +} + /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). /// Reject it before creating a device in diagnostics' software-only mode. pub(crate) fn warp_adapter() -> windows::core::Result { diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index b48b71d..d74b748 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -268,7 +268,7 @@ fn widest(amd: bool) -> u32 { } /// Whether `device` is an AMD card's. -fn amd(device: &ID3D12Device) -> bool { +pub(crate) fn amd(device: &ID3D12Device) -> bool { use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIAdapter1, IDXGIFactory4}; // SAFETY: plain queries. unsafe { diff --git a/crates/victory-shader/src/emit/bitcode/opt.rs b/crates/victory-shader/src/emit/bitcode/opt.rs index 89dc8b7..4fb2940 100644 --- a/crates/victory-shader/src/emit/bitcode/opt.rs +++ b/crates/victory-shader/src/emit/bitcode/opt.rs @@ -399,6 +399,82 @@ impl Module { Some((bits, *x as u64 & mask(bits))) } + /// The bits of a 32-bit float that is a constant, given as one or as a + /// cast of an integer constant. + pub(crate) fn float_k(&self, v: V) -> Option { + let (v, cast) = match v { + V::Inst(i) => match self.insts[i as usize].op { + Op::Cast(Cast::Bitcast, x) => (x, true), + _ => return None, + }, + _ => (v, false), + }; + let V::Const(i) = v else { return None }; + match &self.consts[i as usize].1 { + Const::Float(bits) if !cast => Some(f32::from_bits(*bits)), + Const::Int(_) if cast => { + let (bits, x) = self.int_k(v)?; + (bits == 32).then_some(f32::from_bits(x as u32)) + } + _ => None, + } + } + + /// For a float that is a number and not an infinity whatever the program + /// reads: a power of two its magnitude does not pass. + pub(crate) fn bounded(&self, v: V, depth: u32) -> Option { + if let Some(k) = self.float_k(v) { + return k.is_finite().then(|| k.abs().max(1e-30).log2().ceil()); + } + let V::Inst(i) = v else { return None }; + let depth = depth.checked_sub(1)?; + let of = |v: V| self.bounded(v, depth); + // (A power that overflows, or might with rounding, is no bound.) + let held = |b: f32| (b < 126.0).then_some(b); + match &self.insts[i as usize].op { + Op::Cast(Cast::UiToFp | Cast::SiToFp, _) => Some(32.0), + Op::Cast(Cast::Bitcast, x) => match *x { + V::Inst(j) => match self.insts[j as usize].op { + Op::Cast(Cast::Bitcast, y) if self.type_of(y) == self.type_of(v) => of(y), + _ => None, + }, + _ => None, + }, + Op::Bin(Bin::Mul, a, b) => held(of(*a)? + of(*b)?), + Op::Bin(Bin::Add | Bin::Sub, a, b) => held(of(*a)?.max(of(*b)?) + 1.0), + Op::Select(_, a, b) => Some(of(*a)?.max(of(*b)?)), + Op::Call(_, args) => { + let (_, code) = self.int_k(*args.first()?)?; + match (code, &args[1..]) { + // Saturated, a fraction, a cosine or sine (of a number). + (7, [_]) => Some(0.0), + (6, [x]) => of(*x), + (22 | 12 | 13, [x]) => of(*x).map(|_| 0.0), + (26..=29, [x]) => held(of(*x)? + 1.0), + // Of two numbers; or one of them the other way round: the + // minimum (36) of a constant and a maximum of another. + (35 | 36, [a, b]) => match (of(*a), of(*b)) { + (Some(x), Some(y)) => Some(x.max(y)), + _ => { + let other = if code == 35 { 36 } else { 35 }; + let (inner, k) = if self.float_k(*b).is_some() { (*a, *b) } else { (*b, *a) }; + let k = self.float_k(k).and_then(|_| of(k))?; + let V::Inst(j) = inner else { return None }; + let Op::Call(_, inner) = &self.insts[j as usize].op else { return None }; + let (_, code) = self.int_k(*inner.first()?)?; + let low = inner[1..].iter().find(|x| self.float_k(**x).is_some())?; + (code == other).then_some(())?; + Some(k.max(of(*low)?)) + } + }, + (46, [a, b, c]) => held((of(*a)? + of(*b)?).max(of(*c)?) + 1.0), + _ => None, + } + } + _ => None, + } + } + /// The constant `x` of the integer type `ty`, kept sign-extended as /// [`Module::i32`] and [`Module::bool`] keep theirs. fn k(&mut self, ty: Ty, bits: u32, x: u64) -> V { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index d8387d5..6fa3cbb 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1111,9 +1111,33 @@ fn own_bits_on() -> bool { } /// What the translator was told of the host, for a cache's key: the widest -/// wave, the view heap's limit and where the raw twins of its views start. -pub fn host_settings() -> [u32; 3] { - [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views()] +/// wave, the view heap's limit, where the raw twins of its views start, and +/// what it writes for the console's own hardware. +pub fn host_settings() -> [u32; 4] { + [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views(), host_rdna()] +} + +static HOST_RDNA: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Tells the translator that the host's shaders run on AMD RDNA hardware +/// ([`super::rdna_float`]). +pub fn set_host_rdna(on: bool) { + HOST_RDNA.store(on, std::sync::atomic::Ordering::Relaxed); +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`host_rdna`], for its thread only. + pub(super) static TEST_RDNA: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// The bits of [`super::rdna`] that count on this host. +pub(super) fn host_rdna() -> u32 { + #[cfg(test)] + if let Some(bits) = TEST_RDNA.get() { + return bits; + } + if HOST_RDNA.load(std::sync::atomic::Ordering::Relaxed) { super::rdna_float() } else { 0 } } /// The refusal of a first half of an interpolation whose result is read @@ -3674,6 +3698,9 @@ impl<'a> Lower<'a> { fn max_min(&mut self, max: bool, a: V, b: V) -> V { let c = self.cur; let r = self.binary(if max { 35 } else { 36 }, a, b); + if host_rdna() & super::rdna::MAX_MIN != 0 { + return r; + } let (ia, ib) = (self.as_int(a), self.as_int(b)); let either = self.s.m.bin(c, Bin::Or, ia, ib); let magnitude = self.s.m.i32(0x7FFF_FFFF); @@ -3807,6 +3834,25 @@ impl<'a> Lower<'a> { /// is the smallest number among them). fn med3(&mut self, a: V, b: V, third: V) -> V { let c = self.cur; + // Between two constants in order: the lower one for a NaN either way. + if host_rdna() & super::rdna::MED3 != 0 { + let k = [a, b, third].map(|x| self.s.m.float_k(x)); + let ordered = match k { + [None, Some(x), Some(y)] => Some((a, b, third, x, y)), + [Some(x), None, Some(y)] => Some((b, a, third, x, y)), + [Some(x), Some(y), None] => Some((third, a, b, x, y)), + _ => None, + }; + if let Some((v, p, q, x, y)) = ordered + && !x.is_nan() + && !y.is_nan() + && x != y + { + let (low, high) = if x < y { (p, q) } else { (q, p) }; + let t = self.binary(35, v, low); + return self.binary(36, t, high); + } + } let lo = self.binary(36, a, b); let hi = self.binary(35, a, b); let t = self.binary(36, hi, third); @@ -3829,6 +3875,9 @@ impl<'a> Lower<'a> { fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V { let c = self.cur; let r = self.unary(22, a); + if host_rdna() & super::rdna::FRACT != 0 && below_one == f32::from_bits(0x3F7F_FFFF) { + return r; + } let limit = self.s.m.f32(threshold.to_bits()); let k = self.s.m.f32(below_one.to_bits()); let over = self.s.m.cmp(c, pred::OGE, r, limit); @@ -3878,6 +3927,28 @@ impl<'a> Lower<'a> { /// `0 × anything = 0`, as in D3D9. fn legacy_mul(&mut self, a: V, b: V) -> V { let c = self.cur; + if host_rdna() & super::rdna::LEGACY != 0 { + let m = self.s.m.bin(c, Bin::Mul, a, b); + let zero = self.s.m.f32(0); + // A product is not 0 only where one factor is 0 and the other an + // infinity or no number: never of a value with itself, nor of two + // finite ones, and only where the finite one of two is 0. + let (fa, fb) = (self.s.m.bounded(a, 12).is_some(), self.s.m.bounded(b, 12).is_some()); + let not_zero = |l: &Self, x: V| l.s.m.float_k(x).is_some_and(|k| k != 0.0 && k.is_finite()); + if a == b || fa && fb || not_zero(self, a) || not_zero(self, b) { + return m; + } + let asked = match (fa, fb) { + (true, _) => a, + (_, true) => b, + _ => { + let (a, b) = (self.unary(6, a), self.unary(6, b)); + self.binary(36, a, b) + } + }; + let z = self.s.m.cmp(c, pred::OEQ, asked, zero); + return self.s.m.select(c, z, zero, m); + } let m = self.s.m.bin(c, Bin::Mul, a, b); let zero = self.s.m.f32(0); let az = self.s.m.cmp(c, pred::OEQ, a, zero); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index f98517d..479d149 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -99,6 +99,8 @@ mod threading; #[cfg(windows)] pub mod validator; #[cfg(all(test, windows))] +mod probe_tests; +#[cfg(all(test, windows))] mod size_tests; #[cfg(all(test, windows))] mod valu_tests; @@ -114,7 +116,7 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use bitcode::census; pub use sampler::StaticSampler; -pub use lower::{host_settings, set_host_max_wave}; +pub use lower::{host_settings, set_host_max_wave, set_host_rdna}; 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, @@ -200,6 +202,57 @@ pub fn shader_opt() -> u32 { *PASSES.get_or_init(|| parse_shader_opt(std::env::var("VICTORY_SHADER_OPT").ok().as_deref())) } +/// On a host whose shaders run on the console's own kind of hardware (AMD +/// RDNA, [`set_host_rdna`]): which of the console's float instructions are +/// written as the one host operation the driver makes the same instruction +/// of, instead of spelled out in operations every host agrees on. +/// `VICTORY_RDNA_FLOAT`: a set of [`rdna`]'s bits (decimal or `0x` hex); all +/// of them when it is unset, `0` none. Nothing on other hosts. +/// +/// Measured on an RX 7900 XTX (a frame of the yard, replayed turn by turn with +/// and without): the title's dispatches and draws 18.4 -> 17.6 ms, 0.4 of it +/// without [`rdna::LEGACY`]. Tried and worth nothing there: `v_mad_f32` as one +/// multiply-add, a fast reciprocal, scalar buffer loads of four dwords at once, +/// a wave size for every compute program (32, 64, the console's). +/// +/// Part of the translation: the shader cache keys on it ([`host_settings`]). +pub fn rdna_float() -> u32 { + static BITS: std::sync::OnceLock = std::sync::OnceLock::new(); + *BITS.get_or_init(|| { + let value = std::env::var("VICTORY_RDNA_FLOAT").ok(); + parse_set(value.as_deref(), rdna::ALL, rdna::ALL) + }) +} + +/// The bits of [`rdna_float`]. +pub mod rdna { + /// `v_max_f32` and the like: the host's FMax and FMin, without the code + /// that orders -0 below +0. + pub const MAX_MIN: u32 = 1; + /// `v_mul_legacy_f32` and the like (0 times anything is 0): a plain product + /// where no factor can be an infinity or no number where the other is 0, + /// and one comparison where it can. A zero may have the other sign. + pub const LEGACY: u32 = 2; + /// `v_med3_f32` of a value between two ordered constants: a minimum of a + /// maximum. + pub const MED3: u32 = 4; + /// `v_fract_f32`: the host's Frc as it is. + pub const FRACT: u32 = 8; + pub const ALL: u32 = 15; +} + +/// A switch's set of bits; `unset` when it is unset or unreadable. Pure, for +/// testing. +fn parse_set(value: Option<&str>, unset: u32, all: u32) -> u32 { + let parsed = value + .map(str::trim) + .and_then(|v| match v.strip_prefix("0x") { + Some(hex) => u32::from_str_radix(hex, 16).ok(), + None => v.parse().ok(), + }); + parsed.map_or(unset, |n| n & all) +} + /// Everything a translation depends on besides the container: the /// translator's own source (hashed at build time), the value of every /// `VICTORY_*` switch it reads, the host facts the device hands it (widest @@ -220,6 +273,7 @@ pub fn translation_fingerprint() -> Vec { out.push(0); } out.extend_from_slice(&lower::host_max_wave().to_le_bytes()); + out.extend_from_slice(&lower::host_rdna().to_le_bytes()); out.extend_from_slice(&shader::view_heap_limit().to_le_bytes()); out.extend_from_slice(&shader::raw_views().to_le_bytes()); out.extend_from_slice(&loop_limit().to_le_bytes()); diff --git a/crates/victory-shader/src/emit/probe_tests.rs b/crates/victory-shader/src/emit/probe_tests.rs new file mode 100644 index 0000000..fd109ba --- /dev/null +++ b/crates/victory-shader/src/emit/probe_tests.rs @@ -0,0 +1,74 @@ +//! Not a test of the translator: what the host's compiler makes of DXIL. +//! `VICTORY_PROBE=` and `--ignored probe`: each `.dxil` there (a +//! compute program with a constant buffer `b0` of four dwords and a raw +//! buffer, slot 0 of the view heap) is run on the card. `sem*` programs are +//! given the bits of 0.0, infinity, -0.0 and a NaN and what they store is +//! printed; of the others the time is (several runs of 4096 groups). + +use super::HostShader; +use super::host::{Dispatch, Host, Root, View}; +use crate::native::{HwStage, RootType}; + +#[test] +#[ignore = "a tool: VICTORY_PROBE="] +fn probe() { + let Some(folder) = std::env::var_os("VICTORY_PROBE") else { return }; + let host = Host::new(false).expect("a card"); + let mut files: Vec<_> = std::fs::read_dir(folder) + .expect("the folder") + .filter_map(|e| Some(e.ok()?.path())) + .filter(|p| p.extension().is_some_and(|e| e == "dxil")) + .collect(); + files.sort(); + for file in files { + let name = file.file_stem().unwrap_or_default().to_string_lossy().into_owned(); + let shader = HostShader { + stage: HwStage::Cs, + dxil: std::fs::read(&file).expect("the file"), + user_data: (0..4) + .map(|n| super::UserData { index: n, slot: 0, root: RootType::Constants, dword: n }) + .collect(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + }; + let (root, pso) = match host.compute_pipeline(&shader) { + Ok(made) => made, + Err(e) => { + println!("{name}: {e}"); + continue; + } + }; + let run = |constants: [u32; 4], groups: u32| { + let began = std::time::Instant::now(); + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(constants.to_vec()))], + views: &[View::RawUav(64)], + samplers: &[], + groups: [groups, 1, 1], + }, + ) + .expect("a dispatch"); + (out[0].clone(), began.elapsed().as_secs_f64() * 1e3) + }; + if name.starts_with("sem") { + let (out, _) = run([0, 0x7F80_0000, 0x8000_0000, 0x7FC0_0000], 1); + for (n, x) in out.iter().enumerate().take(40) { + println!("{name} {n:>2}: {x:08x} {}", f32::from_bits(*x)); + } + continue; + } + let constants = [0.37f32.to_bits(), 0.11f32.to_bits(), 16384, 0]; + run(constants, 64); + let mut times: Vec = (0..9).map(|_| run(constants, 4096).1).collect(); + times.sort_by(f64::total_cmp); + println!("{name}: {:.2} ms (least {:.2})", times[times.len() / 2], times[0]); + } +} diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index cd2806f..1062843 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -1912,3 +1912,88 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() { } } } + +/// Whether the hardware adapter is an AMD RDNA card's: what the translator +/// writes for one ([`super::rdna`]) holds there. +fn rdna_card() -> bool { + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::*; + let Ok(host) = Host::new(false) else { return false }; + let mut waves = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + // SAFETY: plain queries. + unsafe { + let amd = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| f.EnumAdapterByLuid::(host.device.GetAdapterLuid())) + .and_then(|a| a.GetDesc1()) + .is_ok_and(|d| d.VendorId == 0x1002); + amd && host + .device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS1, + (&raw mut waves).cast(), + size_of_val(&waves) as u32, + ) + .is_ok() + && waves.WaveLaneCountMin == 32 + && waves.WaveLaneCountMax == 64 + } +} + +/// The forms written for the console's own kind of hardware give, on such a +/// card, what the ones spelled out for every host give; a legacy product's +/// zero may have the other sign. +#[test] +fn rdna_forms_give_what_the_spelled_out_ones_give() { + if !rdna_card() { + eprintln!("no RDNA card; skipped"); + return; + } + const ONE: u16 = 242; + const MINUS_ONE: u16 = 243; + let (a, b, c) = (vgpr(1), vgpr(2), vgpr(3)); + let saturated = vop3_mod(0x110, 5, vgpr(1), vgpr(1), 0, 0, 0, 0, true); + let two = |x: [u32; 2], y: [u32; 2]| [x, y].concat(); + let bodies: [(&str, Vec, bool); 14] = [ + ("max", vop3(0x110, 0, a, b, 0).to_vec(), true), + ("min", vop3(0x10F, 0, a, b, 0).to_vec(), true), + ("max3", vop3(0x154, 0, a, b, c).to_vec(), true), + ("min3", vop3(0x151, 0, a, b, c).to_vec(), true), + ("med3 0 1", vop3(0x157, 0, a, 128, ONE).to_vec(), true), + ("med3 1 0", vop3(0x157, 0, ONE, a, 128).to_vec(), true), + ("med3 1 -1", vop3(0x157, 0, ONE, MINUS_ONE, a).to_vec(), true), + ("fract", vec![vop1(0x020, 0, a)], true), + ("mul_legacy", vop3(0x107, 0, a, b, 0).to_vec(), false), + ("mul_legacy by itself", vop3(0x107, 0, a, a, 0).to_vec(), false), + ("mul_legacy by a constant", vop3(0x107, 0, a, MINUS_ONE, 0).to_vec(), false), + ("mul_legacy of a saturated", two(saturated, vop3(0x107, 0, vgpr(5), b, 0)), false), + ("mad_legacy", vop3(0x140, 0, a, b, c).to_vec(), false), + ("max of a mul_legacy", two(vop3(0x107, 5, a, b, 0), vop3(0x110, 0, vgpr(5), c, 0)), false), + ]; + let numbers = [0.0f32, -0.0, 1.0, -1.0, 0.3, -2.5e-7, 3e38, f32::INFINITY, f32::NEG_INFINITY, f32::NAN]; + let mut cases = Vec::new(); + for (i, x) in numbers.iter().enumerate() { + for (j, y) in numbers.iter().enumerate() { + let z = numbers[(3 * i + j) % numbers.len()]; + cases.push([x.to_bits(), y.to_bits(), z.to_bits(), 0]); + } + } + for (name, body, exact) in bodies { + let mut got: Vec> = Vec::new(); + let mut written = Vec::new(); + for bits in [0, super::rdna::ALL] { + lower::TEST_RDNA.set(Some(bits)); + let shader = build_valu_cs(&body); + lower::TEST_RDNA.set(None); + written.push(shader.dxil.clone()); + let mut all = Vec::new(); + run_cases_on(&shader, &cases, &[("hardware", false)], |_, _, _, r| all.push(r)); + got.push(all); + } + assert_ne!(written[0], written[1], "{name}: written alike"); + for (case, (&was, &is)) in cases.iter().zip(got[0].iter().zip(&got[1])) { + let (x, y) = (f32::from_bits(was), f32::from_bits(is)); + let same = was == is || x.is_nan() && y.is_nan() || !exact && x == 0.0 && y == 0.0; + assert!(same, "{name} of {:?}: {x} ({was:#x}), now {y} ({is:#x})", case.map(f32::from_bits)); + } + } +} From 6912fb1d764fb700c8d0e5980b5399459c39e15c Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:49:12 -0600 Subject: [PATCH 386/445] Frame replay: shaders of another translation (--retranslate, --shaders, --shaders-b turn by turn), times per pass as medians --shaders after local/models 098ec1d4. The capture's 1,266 containers are collected from the title's files once (beside the capture) and translated by this build in 15 s; a pipeline that is refused with them keeps the recorded ones. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 84 ++++++++++++++ crates/victory-gpu/src/replay/play.rs | 156 +++++++++++++++++++++----- docs/replay.md | 2 + 3 files changed, 217 insertions(+), 25 deletions(-) diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index 490b523..38af935 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -195,6 +195,25 @@ pub(crate) struct Replay { /// `:` (repeatable). #[arg(long)] split: Vec, + /// Take shaders from this folder where it has them (`.dxil`, by the + /// hash the runtime names the title's shader by). + #[arg(long)] + shaders: Option, + /// With --compare: the folder the second run's shaders are from. + #[arg(long)] + shaders_b: Option, + /// Only translate the capture's shaders, into this folder (for --shaders), + /// with the translator's settings of this run. Containers are looked up in + /// `containers` beside the capture, and first collected there from the + /// title's files. + #[arg(long)] + retranslate: Option, + /// With --retranslate: the view heap's null slot, and where raw twins of + /// views start, as the capture's shaders have them (0: none). + #[arg(long, default_value_t = 0)] + view_limit: u32, + #[arg(long, default_value_t = 0)] + raw_views: u32, /// Use the D3D12 debug layer (slow). #[arg(long)] debug_layer: bool, @@ -229,6 +248,9 @@ pub(crate) fn run(r: Replay) -> Result<()> { let lists = range(text).with_context(|| format!("--flow {text}"))?; return play::look::flow(&r.folder, lists, r.flow_draws, r.flow_slots, &mut |line| println!("{line}")); } + if let Some(into) = &r.retranslate { + return retranslate(&r.folder, into, r.view_limit, r.raw_views); + } let until = match &r.until { Some(text) => Some( text.split_once(':') @@ -270,6 +292,8 @@ pub(crate) fn run(r: Replay) -> Result<()> { only, until, skip_shaders: r.skip_shader, + shaders: r.shaders, + shaders_b: r.shaders_b, compare: r.compare, debug: r.debug_layer, breadcrumbs: r.breadcrumbs, @@ -409,6 +433,66 @@ pub(crate) fn run(r: Replay) -> Result<()> { Ok(()) } +/// Translates the capture's shaders into `into`. +fn retranslate(folder: &std::path::Path, into: &std::path::Path, view_limit: u32, raw_views: u32) -> Result<()> { + use std::sync::atomic::{AtomicUsize, Ordering}; + let wanted = play::title_shaders(folder)?; + let kept = play::find(folder)?.with_file_name("containers"); + std::fs::create_dir_all(&kept)?; + std::fs::create_dir_all(into)?; + let mut missing: std::collections::HashSet<&str> = wanted + .iter() + .map(|w| w.1.as_str()) + .filter(|h| !kept.join(format!("{h}.cdxil")).exists()) + .collect(); + if !missing.is_empty() { + println!("{} of {} containers are looked for in the title's files", missing.len(), wanted.len()); + for root in crate::default_paths(Vec::new())? { + for entry in walkdir::WalkDir::new(root).into_iter().filter_map(std::result::Result::ok) { + let size = entry.metadata().map_or(0, |m| m.len()); + if missing.is_empty() || !entry.file_type().is_file() || size > crate::shader::MAX_FILE { + continue; + } + let Ok(data) = std::fs::read(entry.path()) else { continue }; + for source in crate::shader::sources(&data) { + let Some(bytes) = source.bytes() else { continue }; + let hash = blake3::hash(&bytes).to_hex()[..16].to_owned(); + if missing.remove(hash.as_str()) { + std::fs::write(kept.join(format!("{hash}.cdxil")), &bytes[..])?; + } + } + } + } + } + println!("{} containers not found", missing.len()); + victory_shader::emit::set_host_max_wave(64); + victory_shader::emit::set_host_rdna(true); + victory_shader::emit::set_view_heap_limit(view_limit); + victory_shader::emit::set_raw_views(raw_views); + let all: Vec<_> = wanted.iter().collect(); + let (next, done) = (AtomicUsize::new(0), AtomicUsize::new(0)); + let started = std::time::Instant::now(); + std::thread::scope(|s| { + for _ in 0..std::thread::available_parallelism().map_or(4, |n| n.get()) { + s.spawn(|| { + while let Some((stage, hash)) = all.get(next.fetch_add(1, Ordering::Relaxed)) { + let Ok(bytes) = std::fs::read(kept.join(format!("{hash}.cdxil"))) else { continue }; + match victory_shader::emit::translate(&bytes) { + Ok(t) => { + if std::fs::write(into.join(format!("{hash}.dxil")), &t.dxil).is_ok() { + done.fetch_add(1, Ordering::Relaxed); + } + } + Err(e) => println!("{stage} {hash}: {e}"), + } + } + }); + } + }); + println!("{} of {} shaders translated, {:.1} s", done.into_inner(), all.len(), started.elapsed().as_secs_f64()); + Ok(()) +} + #[cfg(test)] mod tests { #[test] diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index b823576..fa55c85 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -96,6 +96,11 @@ pub struct Options { /// Skip what runs a pipeline whose name or shader hash has one of /// these in it. pub skip_shaders: Vec, + /// Shaders taken from this folder where it has them: `.dxil`, by + /// the hash the runtime names the title's shader by. + pub shaders: Option, + /// With `compare`: the folder the shaders of the second are from. + pub shaders_b: Option, /// Run the frame unchanged first, and compare. pub compare: bool, /// The debug layer, if it is installed. @@ -129,6 +134,8 @@ impl Default for Options { only: None, until: None, skip_shaders: Vec::new(), + shaders: None, + shaders_b: None, compare: false, debug: false, breadcrumbs: false, @@ -180,7 +187,7 @@ pub struct Report { pub delta_ms: Vec, /// Of the last loop, by submission: lists, ms. pub submits: Vec<(usize, f64)>, - /// With detailed timing, of the last loop: ms and count by category. + /// With detailed timing: ms (median of the loops) and count by category. pub categories: Vec<(String, f64, u32)>, /// With detailed timing: ms, count and name of the costliest pipelines. pub shaders: Vec<(f64, u32, String)>, @@ -326,6 +333,43 @@ pub fn find(folder: &Path) -> Result { .ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display())) } +/// The stage and hash by which the runtime names each of the title's shaders +/// in a capture. +pub fn title_shaders(folder: &Path) -> Result> { + let frame = Frame::read(&find(folder)?.join("frame.bin"))?; + let mut all = std::collections::BTreeSet::new(); + for p in &frame.pipelines { + for part in &p.parts { + if let wire::Part::Code { blob, .. } = part + && let Some(hash) = title_hash(p, *blob) + { + let at = p.name.find(hash).unwrap_or(0); + let stage = p.name[..at].trim_end().rsplit(['[', ' ']).next().unwrap_or(""); + all.insert((stage.to_owned(), hash.to_owned())); + } + } + } + Ok(all) +} + +/// The hash by which the runtime names the title's shader that code blob +/// `blob` of pipeline `p` is the translation of. +fn title_hash(p: &wire::Pipeline, blob: u32) -> Option<&str> { + let kind = p.parts.iter().find_map(|part| match part { + wire::Part::Code { kind, blob: b } if *b == blob => Some(*kind), + _ => None, + })?; + let stage = match D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(kind) { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS => "vertex ", + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS => "pixel ", + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS => "mesh ", + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS => "compute ", + _ => return None, + }; + let at = p.name.find(stage)? + stage.len(); + p.name.get(at..at + 16) +} + /// Writes the DXIL of the pipelines whose name has `text` in it to `shaders` /// in the capture, and the pipelines' descriptions; what was written. pub fn dump(folder: &Path, text: &str) -> Result> { @@ -411,7 +455,7 @@ pub fn listing(folder: &Path, lists: (u32, u32), line: &mut dyn FnMut(&str)) -> pub fn replay(folder: &Path, options: &Options) -> Result> { let mut player = Player::load(folder, options)?; let mut out = Vec::new(); - if options.compare && options.edited() { + if options.compare && (options.edited() || options.shaders_b.is_some()) { // Turn by turn: what else the machine does falls on both. let image = Some(player.folder.join("replay-unchanged.png")); let plain = Options { @@ -419,11 +463,20 @@ pub fn replay(folder: &Path, options: &Options) -> Result> ..options.plain() }; let mut a = player.prepare(&plain)?; + // The lists of the first hold its pipelines by name alone: kept. + let _pipelines = match &options.shaders_b { + Some(folder) => { + let kept = std::mem::take(&mut player.pipelines); + player.make_pipelines(Some(folder))?; + kept + } + None => HashMap::new(), + }; let mut b = player.prepare(options)?; let (mut stamps_a, mut stamps_b) = (Vec::new(), Vec::new()); for _ in 0..options.loops.max(1) { - stamps_a = player.once(&plain, &mut a)?; - stamps_b = player.once(options, &mut b)?; + stamps_a.push(player.once(&plain, &mut a)?); + stamps_b.push(player.once(options, &mut b)?); } out.push(("unchanged".into(), player.finish(&plain, a, &stamps_a)?)); out.push(("with the experiments".into(), player.finish(options, b, &stamps_b)?)); @@ -580,7 +633,7 @@ impl Player { let mut at = Instant::now(); player.make_resources(options.buffers, &options.only_buffers)?; step("resources", &mut at); - player.make_pipelines()?; + player.make_pipelines(options.shaders.as_deref())?; step("pipelines", &mut at); player.make_descriptors()?; step("descriptors", &mut at); @@ -828,14 +881,21 @@ impl Player { Ok(()) } - fn make_pipelines(&mut self) -> Result<()> { + fn make_pipelines(&mut self, shaders: Option<&Path>) -> Result<()> { for (id, blob) in &self.frame.roots { + if self.roots.contains_key(id) { + // (Made for another set of shaders: the root signatures are the same.) + continue; + } // SAFETY: a blob the host took. let root = unsafe { self.device.CreateRootSignature(0, &blob.0) } .with_context(|| format!("root signature {id}"))?; self.roots.insert(*id, root); } for s in &self.frame.signatures { + if self.signatures.contains_key(&s.id) { + continue; + } let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: s.stride, NumArgumentDescs: s.args.len() as u32, @@ -851,6 +911,9 @@ impl Player { self.signatures.extend(made.map(|m| (s.id, m))); } for q in &self.frame.query_heaps { + if self.queries.contains_key(&q.id) { + continue; + } let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE(q.kind), Count: q.count, @@ -870,18 +933,34 @@ impl Player { .map_or(4, |n| n.get() / 2) .max(1); let (frame, roots) = (&self.frame, &self.roots); + let (swapped, kept) = (AtomicUsize::new(0), AtomicUsize::new(0)); std::thread::scope(|scope| { for _ in 0..threads { scope.spawn(|| { while let Some(p) = frame.pipelines.get(next.fetch_add(1, Ordering::Relaxed)) { - let code = |i: u32| { + let recorded = |i: u32| { let c = frame.codes.get(i as usize)?; let mut bytes = vec![0; c.len as usize]; read_at(&file, &mut bytes, c.at).ok()?; Some(bytes) }; - let m = - super::pso::make(&device, &p.parts, |id| roots.get(&id).cloned(), code); + let root = |id: u32| roots.get(&id).cloned(); + let taken = std::cell::Cell::new(false); + let mut m = super::pso::make(&device, &p.parts, root, |i| { + let other = shaders.and_then(|dir| { + let hash = title_hash(p, i)?; + std::fs::read(dir.join(format!("{hash}.dxil"))).ok() + }); + taken.set(taken.get() || other.is_some()); + other.or_else(|| recorded(i)) + }); + if taken.get() && m.is_err() { + // Not for the root signature or the other stage recorded. + kept.fetch_add(1, Ordering::Relaxed); + m = super::pso::make(&device, &p.parts, root, recorded); + } else if taken.get() { + swapped.fetch_add(1, Ordering::Relaxed); + } made.lock() .unwrap_or_else(|e| e.into_inner()) .push((p.id, m)); @@ -896,6 +975,15 @@ impl Player { Err(e) => refused.push((id, e)), } } + if shaders.is_some() { + let n = format!( + "{} of {} pipelines made with shaders of the folder given, {} refused with them (as recorded)", + swapped.into_inner(), + self.frame.pipelines.len(), + kept.into_inner() + ); + self.note(n); + } if let Some((id, e)) = refused.first() { let n = format!( "{} pipelines could not be made again, first {}: {e}", @@ -2974,7 +3062,7 @@ impl Player { let _awake = if o.awake { crate::host::awake::start(&self.device, || true) } else { None }; let mut stamps = Vec::new(); for _ in 0..o.loops.max(1) { - stamps = self.once(o, &mut made)?; + stamps.push(self.once(o, &mut made)?); } self.finish(o, made, &stamps) } @@ -3034,7 +3122,7 @@ impl Player { } /// The report after the last run. - fn finish(&mut self, o: &Options, (built, mut report): (Sends, Report), stamps: &[u64]) -> Result { + fn finish(&mut self, o: &Options, (built, mut report): (Sends, Report), stamps: &[Vec]) -> Result { if o.detailed { self.detail(&built, stamps, o, &mut report); } @@ -3049,23 +3137,41 @@ impl Player { Ok(report) } - /// The last loop's time by command. - fn detail(&self, built: &Sends, stamps: &[u64], o: &Options, report: &mut Report) { - let mut kinds: BTreeMap<&str, (f64, u32)> = BTreeMap::new(); - let mut shaders: HashMap = HashMap::new(); - for l in built.steps.iter().flat_map(|(_, l)| l) { - let mut before = stamps[l.first as usize]; - for &(at, kind, pso) in &l.stamps { - let ms = stamps[at].saturating_sub(before) as f64 * 1e3 / self.frequency; - before = before.max(stamps[at]); - let k = kinds.entry(kind).or_default(); - *k = (k.0 + ms, k.1 + 1); - if pso != NONE { - let s = shaders.entry(pso).or_default(); - *s = (s.0 + ms, s.1 + 1); + /// The time by command: the median of the loops, without the first (which + /// is slower) where there are others. + fn detail(&self, built: &Sends, stamps: &[Vec], o: &Options, report: &mut Report) { + let mut kinds: BTreeMap<&str, (Vec, u32)> = BTreeMap::new(); + let mut shaders: HashMap, u32)> = HashMap::new(); + let loops = if stamps.len() > 2 { &stamps[1..] } else { stamps }; + for stamps in loops { + let mut of_kind: BTreeMap<&str, (f64, u32)> = BTreeMap::new(); + let mut of_shader: HashMap = HashMap::new(); + for l in built.steps.iter().flat_map(|(_, l)| l) { + let mut before = stamps[l.first as usize]; + for &(at, kind, pso) in &l.stamps { + let ms = stamps[at].saturating_sub(before) as f64 * 1e3 / self.frequency; + before = before.max(stamps[at]); + let k = of_kind.entry(kind).or_default(); + *k = (k.0 + ms, k.1 + 1); + if pso != NONE { + let s = of_shader.entry(pso).or_default(); + *s = (s.0 + ms, s.1 + 1); + } } } + for (k, (ms, n)) in of_kind { + let all = kinds.entry(k).or_default(); + all.0.push(ms); + all.1 = n; + } + for (k, (ms, n)) in of_shader { + let all = shaders.entry(k).or_default(); + all.0.push(ms); + all.1 = n; + } } + let kinds = kinds.into_iter().map(|(k, (ms, n))| (k, (median(&ms), n))); + let shaders = shaders.into_iter().map(|(k, (ms, n))| (k, (median(&ms), n))); report.categories = kinds .into_iter() .map(|(k, (ms, n))| (k.to_owned(), ms, n)) diff --git a/docs/replay.md b/docs/replay.md index 0459d7d..8dcd7e6 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -69,6 +69,8 @@ with the presented one. | `--only 3..7` | runs these lists; of the others only barriers | | `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) | | `--skip-shader ` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) | +| `--shaders ` | takes shaders from the folder where it has them: `.dxil`, by the hash the runtime names the title's shader by; with `--compare --shaders-b ` a second set, turn by turn with the first | +| `--retranslate ` | only writes that folder: the capture's shaders translated by this build with the `VICTORY_*` switches of this run (`--view-limit`, `--raw-views`: the view heap's null slot and where raw views start, as the capture's shaders have them) | | `--no-restore` | leaves what a loop changed, and makes no copies to restore from (of a capture that does not fit in the card's memory with them) | | `--pace ` | a wait after each submission sent: the card stands idle between them, as in a game that prepares the next one | | `--awake` | keeps the card's clocks up (`VICTORY_CARD_AWAKE=1`) | From adf57069830391af2d2e33c9b04f50dc6ab1615c Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:57:50 -0600 Subject: [PATCH 387/445] 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 388/445] 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 389/445] 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 390/445] 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 391/445] 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 392/445] 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 393/445] 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 9b90ad114c09d84a3163acdb95031ceaef5ae6a7 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 13:32:18 -0600 Subject: [PATCH 394/445] The compare of card copies loads eight places at once (the same hashes) Yard capture, 423 passes a frame, turn by turn: 1.93 -> 1.69 ms (4 loops; four at once 1.70, sixteen 1.71). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 8cee056..b522d4a 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2003,8 +2003,37 @@ void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) { lo = lo & ~15u; hi = (hi + 15u) & ~15u; uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread; + uint at = lo + thread * 16u; + // Eight loads at once: one after the other, each waits for memory. [loop] - for (uint at = lo + thread * 16u; at < hi; at += 1024u) { + for (; at + 7168u < hi; at += 8192u) { + uint4 v0 = now.Load4(at + 0u); + uint4 v1 = now.Load4(at + 1024u); + uint4 v2 = now.Load4(at + 2048u); + uint4 v3 = now.Load4(at + 3072u); + uint4 v4 = now.Load4(at + 4096u); + uint4 v5 = now.Load4(at + 5120u); + uint4 v6 = now.Load4(at + 6144u); + uint4 v7 = now.Load4(at + 7168u); + h = (h ^ v0) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + h = (h ^ v1) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + h = (h ^ v2) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + h = (h ^ v3) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + h = (h ^ v4) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + h = (h ^ v5) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + h = (h ^ v6) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + h = (h ^ v7) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + } + [loop] + for (; at < hi; at += 1024u) { h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); h = h.yzwx ^ (h >> 15); } From 35155bed9a09bb628d57a27c9b1680f100d23769 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 13:32:18 -0600 Subject: [PATCH 395/445] Frame replay: --shaders takes passes of ours too, by their own hash Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/replay/play.rs | 5 +++-- docs/replay.md | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index fa55c85..3c12228 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -97,7 +97,7 @@ pub struct Options { /// these in it. pub skip_shaders: Vec, /// Shaders taken from this folder where it has them: `.dxil`, by - /// the hash the runtime names the title's shader by. + /// the hash the runtime names the title's shader by (ours: by their own). pub shaders: Option, /// With `compare`: the folder the shaders of the second are from. pub shaders_b: Option, @@ -948,7 +948,8 @@ impl Player { let taken = std::cell::Cell::new(false); let mut m = super::pso::make(&device, &p.parts, root, |i| { let other = shaders.and_then(|dir| { - let hash = title_hash(p, i)?; + let own = || frame.codes.get(i as usize).map(|c| c.hash[..8].iter().map(|b| format!("{b:02x}")).collect()); + let hash = title_hash(p, i).map(str::to_owned).or_else(own)?; std::fs::read(dir.join(format!("{hash}.dxil"))).ok() }); taken.set(taken.get() || other.is_some()); diff --git a/docs/replay.md b/docs/replay.md index 8dcd7e6..11c01d6 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -69,7 +69,7 @@ with the presented one. | `--only 3..7` | runs these lists; of the others only barriers | | `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) | | `--skip-shader ` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) | -| `--shaders ` | takes shaders from the folder where it has them: `.dxil`, by the hash the runtime names the title's shader by; with `--compare --shaders-b ` a second set, turn by turn with the first | +| `--shaders ` | takes shaders from the folder where it has them: `.dxil`, by the hash the runtime names the title's shader by (a pass of ours: its own DXIL hash); with `--compare --shaders-b ` a second set, turn by turn with the first | | `--retranslate ` | only writes that folder: the capture's shaders translated by this build with the `VICTORY_*` switches of this run (`--view-limit`, `--raw-views`: the view heap's null slot and where raw views start, as the capture's shaders have them) | | `--no-restore` | leaves what a loop changed, and makes no copies to restore from (of a capture that does not fit in the card's memory with them) | | `--pace ` | a wait after each submission sent: the card stands idle between them, as in a game that prepares the next one | From b7ab9c49c035f5f7a26982e33a03d5f6314b8df7 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 13:32:18 -0600 Subject: [PATCH 396/445] The title's pipelines written down (VICTORY_PIPELINE_BOOK=1, off) and made ahead of a run, each batch in a process of its own (victory warm) Every pipeline the title creates goes to known-pipelines.bin beside the pipeline library, its containers to known-shaders.bin (in the cache folder; they are the title's code). `victory warm` makes their host pipelines in idle-priority processes of 200 each and lets them go: the driver's cache on disk keeps them. Those earlier runs drew with come first; what is done is noted by translator and driver (warm-done.txt); a pipeline that ends or hangs its process is named in warm-bad.txt and skipped. VICTORY_EARLY_ALL does this in the running title and ended it inside the driver. Not measured yet: how long, and how much the driver's cache grows. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/main.rs | 26 ++ apps/victory/src/warm.rs | 199 +++++++++ crates/victory-gpu/src/pipeline.rs | 4 + crates/victory-gpu/src/pipeline/host.rs | 20 +- crates/victory-gpu/src/pipeline/known.rs | 480 +++++++++++++++++++++ crates/victory-gpu/src/pipeline/library.rs | 5 + crates/victory-gpu/src/pipeline/make.rs | 4 + crates/victory-gpu/src/shader_cache.rs | 5 + crates/victory-hle/src/lib.rs | 3 + 9 files changed, 736 insertions(+), 10 deletions(-) create mode 100644 apps/victory/src/warm.rs create mode 100644 crates/victory-gpu/src/pipeline/known.rs diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index 4912821..659a65b 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -10,6 +10,8 @@ mod replay; mod run; mod shader; mod translate; +#[cfg(windows)] +mod warm; use std::path::PathBuf; @@ -103,6 +105,28 @@ enum Command { #[arg(long)] jobs: Option, }, + /// Make the host pipelines of every pipeline the title ever created + /// (runs with `VICTORY_PIPELINE_BOOK=1` write them down), so that the + /// driver's cache on disk has them before a run needs one: once per change + /// of the translator or the driver. Goes on where it was stopped. + #[cfg(windows)] + Warm { + /// Processes at once (default: two thirds of the logical cores). + #[arg(long)] + jobs: Option, + /// At most this many pipelines. + #[arg(long)] + limit: Option, + /// Those made before too. + #[arg(long)] + again: bool, + /// Only the pipelines earlier runs drew with. + #[arg(long)] + used: bool, + /// (What the processes it starts are given.) + #[arg(long, hide = true)] + these: Option, + }, /// Prepare, map and bind a title executable; with --execute, run it. Run { exe: PathBuf, @@ -190,6 +214,8 @@ fn main() -> Result<()> { translate::run(paths, validate, pipelines, list, jobs) } Command::Shaders { paths, jobs } => translate::precompile(paths, jobs), + #[cfg(windows)] + Command::Warm { jobs, limit, again, used, these } => warm::run(jobs, limit, again, used, these), Command::Run { exe, unimplemented, diff --git a/apps/victory/src/warm.rs b/apps/victory/src/warm.rs new file mode 100644 index 0000000..8bd57c2 --- /dev/null +++ b/apps/victory/src/warm.rs @@ -0,0 +1,199 @@ +//! `victory warm`: host pipelines made ahead of a run (`known_pipelines`), in +//! processes of their own: a compiler that crashes or hangs costs one pipeline. + +use std::collections::HashSet; +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result}; +use victory_hle::known_pipelines as known; + +/// Pipelines a process makes before another takes its place: the compiler's +/// and the translations' memory goes with it. +const AT_ONCE: usize = 200; +/// A pipeline that takes longer is taken for one the compiler hangs on. +const LONGEST: Duration = Duration::from_secs(180); + +fn folder() -> Result { + let cfg = victory_core::Config::load()?; + Ok(cfg.cache_subdir("shaders")?.with_file_name("pipelines")) +} + +pub fn run(jobs: Option, limit: Option, again: bool, used: bool, these: Option) -> Result<()> { + let dir = folder()?; + if let Some(these) = these { + return make(&dir, &these); + } + let began = Instant::now(); + victory_hle::known_pipelines::use_translations(dir.with_file_name("shaders")); + let fingerprint = known::fingerprint(); + let done_file = dir.join("warm-done.txt"); + let bad_file = dir.join("warm-bad.txt"); + let keys = known::keys(&dir); + let listed = std::fs::read_to_string(&done_file).unwrap_or_default(); + let mut done: HashSet<&str> = HashSet::new(); + for line in listed.lines() { + if let Some((of, key)) = line.split_once(' ') + && of == fingerprint + { + done.insert(key); + } + } + let bad = std::fs::read_to_string(&bad_file).unwrap_or_default(); + let bad: HashSet<&str> = bad.lines().filter_map(|l| l.split(' ').next()).collect(); + let early = std::fs::read_to_string(dir.join("early-pipelines.txt")).unwrap_or_default(); + let early: HashSet<&str> = early.lines().collect(); + // Those earlier runs drew with first. + let mut all: Vec = (0..keys.len()) + .filter(|&n| { + let key = keys[n].as_str(); + (again || !done.contains(key)) && !bad.contains(key) && (!used || early.contains(key)) + }) + .collect(); + all.sort_by_key(|&n| (!early.contains(keys[n].as_str()), n)); + all.truncate(limit.unwrap_or(usize::MAX)); + let cores = std::thread::available_parallelism().map_or(4, |n| n.get()); + let jobs = jobs.unwrap_or(cores * 2 / 3).max(1); + println!( + "{} pipelines known, {} made before ({fingerprint}), {} bad; {} to make, {jobs} processes", + keys.len(), + done.len(), + bad.len(), + all.len() + ); + let chunks: Vec<&[usize]> = all.chunks(AT_ONCE).collect(); + let next = AtomicUsize::new(0); + let state = Mutex::new((Vec::::new(), 0usize, 0usize)); + let done_out = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(&done_file)?); + let bad_out = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(&bad_file)?); + std::thread::scope(|s| { + for _ in 0..jobs.min(chunks.len()) { + s.spawn(|| { + while let Some(&chunk) = chunks.get(next.fetch_add(1, Ordering::Relaxed)) { + let mut rest = chunk; + while !rest.is_empty() { + let (made, ended) = child(rest, |n, ms, there| { + let mut state = lock(&state); + state.0.push(ms); + state.1 += usize::from(!there); + let count = state.0.len(); + if count % 1000 == 0 { + println!("{count} of {}, {:.0} s", all.len(), began.elapsed().as_secs_f64()); + } + drop(state); + let _ = writeln!(lock(&done_out), "{fingerprint} {}", keys[n]); + }); + rest = &rest[made.min(rest.len())..]; + match (ended, rest.split_first()) { + (Some(why), Some((&n, after))) => { + // The one it was at. + println!("pipeline {n} {}: {why}", keys[n]); + let _ = writeln!(lock(&bad_out), "{} {why}", keys[n]); + lock(&state).2 += 1; + rest = after; + } + _ => break, + } + } + } + }); + } + }); + let (mut times, refused, crashed) = state.into_inner().unwrap_or_else(|e| e.into_inner()); + times.sort_by(f64::total_cmp); + let at = |q: f64| times.get((times.len() as f64 * q) as usize).copied().unwrap_or(0.0); + println!( + "{} made in {:.0} s ({refused} have no host pipeline, {crashed} ended their process); ms each: median {:.1}, p90 {:.1}, p99 {:.1}, most {:.0}, sum {:.0} s", + times.len(), + began.elapsed().as_secs_f64(), + at(0.5), + at(0.9), + at(0.99), + times.last().copied().unwrap_or(0.0), + times.iter().sum::() / 1e3 + ); + Ok(()) +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Has a process make `these`; how many it made, and how it ended if not well. +fn child(these: &[usize], mut each: impl FnMut(usize, f64, bool)) -> (usize, Option) { + let list: Vec = these.iter().map(usize::to_string).collect(); + let spawned = std::env::current_exe().and_then(|exe| { + use std::os::windows::process::CommandExt; + const IDLE_PRIORITY_CLASS: u32 = 0x40; + Command::new(exe) + .args(["warm", "--these", &list.join(",")]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .creation_flags(IDLE_PRIORITY_CLASS) + .spawn() + }); + let Ok(mut process) = spawned else { return (these.len(), None) }; + let Some(out) = process.stdout.take() else { return (these.len(), None) }; + let process = Mutex::new(process); + let (heard, over) = (Mutex::new(Instant::now()), AtomicBool::new(false)); + let hung = AtomicBool::new(false); + let mut made = 0; + std::thread::scope(|s| { + s.spawn(|| { + while !over.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(500)); + if lock(&heard).elapsed() > LONGEST { + hung.store(true, Ordering::Relaxed); + let _ = lock(&process).kill(); + return; + } + } + }); + for line in BufReader::new(out).lines().map_while(Result::ok) { + *lock(&heard) = Instant::now(); + let mut words = line.split(' '); + if words.next() == Some("made") + && let (Some(n), Some(ms), Some(there)) = (words.next(), words.next(), words.next()) + && let (Ok(n), Ok(ms)) = (n.parse(), ms.parse()) + { + made += 1; + each(n, ms, there == "1"); + } + } + over.store(true, Ordering::Relaxed); + }); + let status = lock(&process).wait(); + let well = status.as_ref().is_ok_and(|s| s.success()); + if well { + return (these.len(), None); + } + let why = if hung.load(Ordering::Relaxed) { + format!("hung for {} s", LONGEST.as_secs()) + } else { + status.map_or_else(|e| e.to_string(), |s| format!("{s}")) + }; + (made, Some(why)) +} + +/// What such a process does. +fn make(dir: &Path, these: &str) -> Result<()> { + let these: Vec = these.split(',').map(|n| n.parse().context("--these")).collect::>()?; + let cfg = victory_core::Config::load()?; + victory_hle::known_pipelines::use_translations(cfg.cache_subdir("shaders")?); + let mut out = std::io::stdout(); + known::make(dir, &these, |n, came| { + let _ = match came { + None => writeln!(out, "at {n}"), + Some((ms, there)) => writeln!(out, "made {n} {ms:.2} {}", u8::from(there)), + }; + let _ = out.flush(); + }); + // Without what a run's end does (nothing to save, the host's threads). + let _ = out.flush(); + std::process::exit(0) +} diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 7a00633..244a666 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -561,6 +561,8 @@ fn hand_out( #[cfg(windows)] let host = Arc::new(make::Pending::new(shaders.clone(), graphics)); #[cfg(windows)] + known::note(host.key(), &shaders, host.graphics.as_deref()); + #[cfg(windows)] make::early(&host); #[cfg(windows)] let builder = of_builder(&shaders); @@ -748,6 +750,8 @@ static FUNCTIONS: Table<24> = { #[cfg(windows)] pub(crate) mod host; #[cfg(windows)] +pub mod known; +#[cfg(windows)] mod library; #[cfg(windows)] mod make; diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index e3559c3..50a8645 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -20,19 +20,19 @@ use crate::host::host; /// A stream's graphics state, owned (the title's stream lives only for the /// creation call). Subobjects the stream leaves out keep D3D12's defaults. pub(crate) struct GraphicsState { - blend: D3D12_BLEND_DESC, - sample_mask: u32, - rasterizer: D3D12_RASTERIZER_DESC, - depth: D3D12_DEPTH_STENCIL_DESC, - depth_bounds: bool, + pub(super) blend: D3D12_BLEND_DESC, + pub(super) sample_mask: u32, + pub(super) rasterizer: D3D12_RASTERIZER_DESC, + pub(super) depth: D3D12_DEPTH_STENCIL_DESC, + pub(super) depth_bounds: bool, /// Input elements, their names pointing into `names`. - inputs: Vec, - names: Vec, - strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, + pub(super) inputs: Vec, + pub(super) names: Vec, + pub(super) strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, pub(crate) topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE, pub(crate) targets: D3D12_RT_FORMAT_ARRAY, - depth_format: DXGI_FORMAT, - samples: DXGI_SAMPLE_DESC, + pub(super) depth_format: DXGI_FORMAT, + pub(super) samples: DXGI_SAMPLE_DESC, } impl Default for GraphicsState { diff --git a/crates/victory-gpu/src/pipeline/known.rs b/crates/victory-gpu/src/pipeline/known.rs new file mode 100644 index 0000000..762f920 --- /dev/null +++ b/crates/victory-gpu/src/pipeline/known.rs @@ -0,0 +1,480 @@ +//! Every pipeline the title has ever created, kept on disk +//! (`VICTORY_PIPELINE_BOOK=1`), and their host pipelines made ahead of a run +//! (`victory warm`), so that the driver's own cache on disk has them before +//! a draw asks for one. +//! +//! The title creates 84,000 pipelines while it loads and draws with some +//! 2,000 of them; which ones is known from earlier runs (`library`), and +//! those are made during loading. One met for the first time (a place never +//! seen, or everything after a change of the translator or of the driver) is +//! compiled when a draw wants it. Making all of them in the running title +//! (`VICTORY_EARLY_ALL=1`) ended it inside the driver's compiler; made here, +//! a compiler that crashes or hangs ends a child process, costs that pipeline +//! alone and is named in `warm-bad.txt`. +//! +//! Two files beside the library, both only ever added to (a torn end is cut +//! off): `known-shaders.bin` (stage, hash, length, container) and +//! `known-pipelines.bin` (length, then the key, the shaders' stages and +//! hashes, and the graphics state). They hold the title's own code: they stay +//! in the cache folder. + +use std::collections::{HashMap, HashSet}; +use std::ffi::CString; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::core::PCSTR; + +use super::Shader; +use super::host::{GraphicsState, HostPipeline}; + +const SHADERS: &str = "known-shaders.bin"; +const PIPELINES: &str = "known-pipelines.bin"; +/// Stages by their number in the files. +const STAGES: [&str; 8] = + ["vertex", "pixel", "domain", "hull", "geometry", "compute", "amplification", "mesh"]; + +/// `VICTORY_PIPELINE_BOOK=1`: the pipelines the title creates are kept. +fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_BOOK").is_some_and(|v| v == "1")) +} + +struct Book { + dir: PathBuf, + keys: HashSet<[u8; 16]>, + shaders: HashSet<[u8; 32]>, + /// Not yet written: shaders, then pipelines. + new: [Vec; 2], + added: usize, +} + +static BOOK: OnceLock>> = OnceLock::new(); + +fn book() -> Option<&'static Mutex> { + BOOK.get_or_init(|| { + let dir = super::library::folder().filter(|_| on())?; + std::fs::create_dir_all(&dir).ok()?; + let mut keys = HashSet::new(); + let mut shaders = HashSet::new(); + let ends = [ + walk_shaders(&dir, |_, hash, _, _| drop(shaders.insert(hash))), + walk_pipelines(&dir, |_, bytes| { + keys.extend(bytes.first_chunk::<16>().copied()); + }), + ]; + for (file, end) in [SHADERS, PIPELINES].iter().zip(ends) { + let path = dir.join(file); + if std::fs::metadata(&path).is_ok_and(|m| m.len() > end) + && let Ok(f) = std::fs::OpenOptions::new().write(true).open(&path) + { + let _ = f.set_len(end); + } + } + tracing::info!(pipelines = keys.len(), shaders = shaders.len(), "title pipelines known from earlier runs"); + let spawned = std::thread::Builder::new().name("victory-known".into()).spawn(|| { + loop { + std::thread::sleep(std::time::Duration::from_secs(2)); + flush(); + } + }); + spawned.ok()?; + Some(Mutex::new(Book { dir, keys, shaders, new: Default::default(), added: 0 })) + }) + .as_ref() +} + +/// The title created a pipeline. +pub(super) fn note(key: &str, shaders: &[Arc], graphics: Option<&GraphicsState>) { + let Some(book) = book() else { return }; + let mut id = [0u8; 16]; + for (at, b) in id.iter_mut().enumerate() { + *b = key.get(2 * at..2 * at + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).unwrap_or(0); + } + let mut book = book.lock().unwrap_or_else(|e| e.into_inner()); + if shaders.is_empty() || !book.keys.insert(id) { + return; + } + let mut entry = id.to_vec(); + entry.push(shaders.len() as u8); + for s in shaders { + let hash = *blake3::hash(&s.container).as_bytes(); + let stage = STAGES.iter().position(|&x| x == s.stage).unwrap_or(0) as u8; + entry.push(stage); + entry.extend(hash); + if book.shaders.insert(hash) { + let new = &mut book.new[0]; + new.push(stage); + new.extend(hash); + new.extend((s.container.len() as u32).to_le_bytes()); + new.extend(&s.container); + } + } + entry.push(u8::from(graphics.is_some())); + if let Some(g) = graphics { + g.put(&mut entry); + } + book.new[1].extend((entry.len() as u32).to_le_bytes()); + book.new[1].extend(entry); + book.added += 1; +} + +/// Writes what was noted. +fn flush() { + let Some(Some(book)) = BOOK.get() else { return }; + let (dir, new, added) = { + let mut book = book.lock().unwrap_or_else(|e| e.into_inner()); + if book.added == 0 { + return; + } + (book.dir.clone(), std::mem::take(&mut book.new), std::mem::take(&mut book.added)) + }; + for (file, bytes) in [SHADERS, PIPELINES].iter().zip(&new) { + let written = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(dir.join(file)) + .and_then(|mut f| f.write_all(bytes)); + if let Err(e) = written { + tracing::warn!(error = %e, file, "title pipelines not written down"); + return; + } + } + tracing::info!(pipelines = added, "title pipelines written down"); +} + +/// Calls `f` with each container's stage, hash, place and length; where the +/// last whole one ends. +fn walk_shaders(dir: &Path, mut f: impl FnMut(u8, [u8; 32], u64, u32)) -> u64 { + let Ok(file) = std::fs::File::open(dir.join(SHADERS)) else { return 0 }; + let len = file.metadata().map_or(0, |m| m.len()); + let mut file = std::io::BufReader::new(file); + let mut at = 0; + let mut head = [0u8; 37]; + while file.read_exact(&mut head).is_ok() { + let size = u32::from_le_bytes([head[33], head[34], head[35], head[36]]); + if at + 37 + u64::from(size) > len || file.seek_relative(i64::from(size)).is_err() { + break; + } + let mut hash = [0; 32]; + hash.copy_from_slice(&head[1..33]); + f(head[0], hash, at + 37, size); + at += 37 + u64::from(size); + } + at +} + +/// Calls `f` with each pipeline's number and entry; where the last whole one +/// ends. +fn walk_pipelines(dir: &Path, mut f: impl FnMut(usize, &[u8])) -> u64 { + let bytes = std::fs::read(dir.join(PIPELINES)).unwrap_or_default(); + let (mut at, mut n) = (0, 0); + while let Some(head) = bytes.get(at..at + 4) { + let size = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize; + let Some(entry) = bytes.get(at + 4..at + 4 + size) else { break }; + f(n, entry); + (at, n) = (at + 4 + size, n + 1); + } + at as u64 +} + +/// How many pipelines are known in `dir`. +pub fn count(dir: &Path) -> usize { + let mut n = 0; + walk_pipelines(dir, |_, _| n += 1); + n +} + +/// The key of each pipeline known in `dir`, as the early list has it. +pub fn keys(dir: &Path) -> Vec { + let mut all = Vec::new(); + walk_pipelines(dir, |_, e| { + all.push(e.get(..16).unwrap_or_default().iter().map(|b| format!("{b:02x}")).collect()); + }); + all +} + +/// What a driver's cached pipelines depend on besides the title's: the +/// translator with its settings, and the driver. +pub fn fingerprint() -> String { + let mut h = blake3::Hasher::new(); + h.update(&crate::shader_cache::translation()); + if let Some(host) = crate::host::host() { + h.update(&host.driver().to_le_bytes()); + } + h.finalize().to_hex()[..16].to_owned() +} + +/// The translations of earlier runs are in `dir` (the pipeline library is +/// not used: what is made here is the driver's to keep). +pub fn use_translations(dir: PathBuf) { + crate::shader_cache::use_shader_cache(dir); +} + +/// Makes the host pipelines of those of `which` (numbers in the file) and +/// lets each go again: the driver's cache on disk keeps them. `each` is told +/// the number before, and what came of it after: milliseconds and whether +/// there is one. +pub fn make(dir: &Path, which: &[usize], mut each: impl FnMut(usize, Option<(f64, bool)>)) { + let mut places = HashMap::new(); + walk_shaders(dir, |stage, hash, at, len| drop(places.insert(hash, (stage, at, len)))); + let Ok(mut file) = std::fs::File::open(dir.join(SHADERS)) else { return }; + let wanted: HashSet = which.iter().copied().collect(); + let mut entries = HashMap::new(); + walk_pipelines(dir, |n, bytes| { + if wanted.contains(&n) { + entries.insert(n, bytes.to_vec()); + } + }); + let mut read = |hash: &[u8; 32]| { + let &(_, at, len) = places.get(hash)?; + let mut bytes = vec![0; len as usize]; + file.seek(SeekFrom::Start(at)).ok()?; + file.read_exact(&mut bytes).ok()?; + Some(bytes) + }; + for n in which { + let Some(entry) = entries.get(n) else { continue }; + each(*n, None); + let began = std::time::Instant::now(); + let made = parse(entry, &mut read) + .and_then(|(shaders, g)| HostPipeline::new(&shaders, g.as_deref())) + .is_some(); + each(*n, Some((began.elapsed().as_secs_f64() * 1e3, made))); + } +} + +#[allow(clippy::type_complexity)] +fn parse( + entry: &[u8], + read: &mut impl FnMut(&[u8; 32]) -> Option>, +) -> Option<(Vec>, Option>)> { + let mut rest = entry.get(16..)?; + let (&count, after) = rest.split_first()?; + rest = after; + let mut shaders = Vec::new(); + for _ in 0..count { + let (head, after) = rest.split_first_chunk::<33>()?; + rest = after; + let mut hash = [0; 32]; + hash.copy_from_slice(&head[1..]); + shaders.push(super::shader(STAGES.get(usize::from(head[0]))?, &read(&hash)?)); + } + let (&graphics, rest) = rest.split_first()?; + let g = match graphics { + 0 => None, + _ => Some(Box::new(GraphicsState::get(rest)?)), + }; + Some((shaders, g)) +} + +/// Calls `$f` with each number of a graphics state but its input elements', +/// as a place of 32 bits, in one order. +macro_rules! numbers { + ($g:expr, $f:ident) => {{ + $f!($g.blend.AlphaToCoverageEnable.0); + $f!($g.blend.IndependentBlendEnable.0); + for t in &mut $g.blend.RenderTarget { + $f!(t.BlendEnable.0); + $f!(t.LogicOpEnable.0); + $f!(t.SrcBlend.0); + $f!(t.DestBlend.0); + $f!(t.BlendOp.0); + $f!(t.SrcBlendAlpha.0); + $f!(t.DestBlendAlpha.0); + $f!(t.BlendOpAlpha.0); + $f!(t.LogicOp.0); + $f!(t.RenderTargetWriteMask); + } + $f!($g.sample_mask); + $f!($g.rasterizer.FillMode.0); + $f!($g.rasterizer.CullMode.0); + $f!($g.rasterizer.FrontCounterClockwise.0); + $f!($g.rasterizer.DepthBias); + $f!($g.rasterizer.DepthClipEnable.0); + $f!($g.rasterizer.MultisampleEnable.0); + $f!($g.rasterizer.AntialiasedLineEnable.0); + $f!($g.rasterizer.ForcedSampleCount); + $f!($g.rasterizer.ConservativeRaster.0); + $f!($g.depth.DepthEnable.0); + $f!($g.depth.DepthWriteMask.0); + $f!($g.depth.DepthFunc.0); + $f!($g.depth.StencilEnable.0); + $f!($g.depth.StencilReadMask); + $f!($g.depth.StencilWriteMask); + for face in [&mut $g.depth.FrontFace, &mut $g.depth.BackFace] { + $f!(face.StencilFailOp.0); + $f!(face.StencilDepthFailOp.0); + $f!(face.StencilPassOp.0); + $f!(face.StencilFunc.0); + } + $f!($g.strip_cut.0); + $f!($g.topology.0); + $f!($g.targets.NumRenderTargets); + for format in &mut $g.targets.RTFormats { + $f!(format.0); + } + $f!($g.depth_format.0); + $f!($g.samples.Count); + $f!($g.samples.Quality); + }}; +} + +impl GraphicsState { + /// The state as bytes. + fn put(&self, out: &mut Vec) { + out.push(u8::from(self.depth_bounds)); + for f in [self.rasterizer.DepthBiasClamp, self.rasterizer.SlopeScaledDepthBias] { + out.extend(f.to_le_bytes()); + } + let mut plain = GraphicsState { + blend: self.blend, + sample_mask: self.sample_mask, + rasterizer: self.rasterizer, + depth: self.depth, + strip_cut: self.strip_cut, + topology: self.topology, + targets: self.targets, + depth_format: self.depth_format, + samples: self.samples, + ..Default::default() + }; + macro_rules! write { + ($x:expr) => { + out.extend(($x as u32).to_le_bytes()) + }; + } + numbers!(plain, write); + out.push(self.inputs.len() as u8); + for (e, name) in self.inputs.iter().zip(&self.names) { + let name = name.as_bytes(); + out.push(name.len() as u8); + out.extend(name); + for v in [ + e.SemanticIndex, + e.Format.0 as u32, + e.InputSlot, + e.AlignedByteOffset, + e.InputSlotClass.0 as u32, + e.InstanceDataStepRate, + ] { + out.extend(v.to_le_bytes()); + } + } + } + + fn get(bytes: &[u8]) -> Option { + let mut g = GraphicsState::default(); + let (&bounds, mut rest) = bytes.split_first()?; + g.depth_bounds = bounds != 0; + let mut next = || { + let (head, after) = rest.split_first_chunk::<4>()?; + rest = after; + Some(u32::from_le_bytes(*head)) + }; + g.rasterizer.DepthBiasClamp = f32::from_bits(next()?); + g.rasterizer.SlopeScaledDepthBias = f32::from_bits(next()?); + macro_rules! read { + ($x:expr) => { + $x = next()? as _ + }; + } + numbers!(g, read); + let (&count, mut rest) = rest.split_first()?; + let mut elements = Vec::new(); + for _ in 0..count { + let (&len, after) = rest.split_first()?; + let (name, after) = after.split_at_checked(usize::from(len))?; + let (numbers, after) = after.split_first_chunk::<24>()?; + rest = after; + let mut v = [0u32; 6]; + for (v, b) in v.iter_mut().zip(numbers.chunks_exact(4)) { + *v = u32::from_le_bytes([b[0], b[1], b[2], b[3]]); + } + elements.push((CString::new(name).ok()?, v)); + } + g.names = elements.iter().map(|e| e.0.clone()).collect(); + g.inputs = g + .names + .iter() + .zip(&elements) + .map(|(name, (_, v))| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(name.as_ptr().cast()), + SemanticIndex: v[0], + Format: DXGI_FORMAT(v[1] as i32), + InputSlot: v[2], + AlignedByteOffset: v[3], + InputSlotClass: D3D12_INPUT_CLASSIFICATION(v[4] as i32), + InstanceDataStepRate: v[5], + }) + .collect(); + Some(g) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_state_comes_back_as_it_was() { + let mut g = GraphicsState { sample_mask: 7, depth_bounds: true, ..Default::default() }; + g.rasterizer.DepthBias = -3; + g.rasterizer.SlopeScaledDepthBias = 1.25; + g.blend.RenderTarget[3].RenderTargetWriteMask = 5; + g.depth.StencilReadMask = 9; + g.targets.NumRenderTargets = 2; + g.targets.RTFormats[1] = DXGI_FORMAT_R8_UNORM; + g.depth_format = DXGI_FORMAT_D32_FLOAT; + g.names = vec![CString::new("POSITION").unwrap(), CString::new("T").unwrap()]; + g.inputs = g + .names + .iter() + .enumerate() + .map(|(n, name)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(name.as_ptr().cast()), + SemanticIndex: n as u32, + Format: DXGI_FORMAT_R32G32_FLOAT, + InputSlot: 2, + AlignedByteOffset: D3D12_APPEND_ALIGNED_ELEMENT, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, + InstanceDataStepRate: 4, + }) + .collect(); + let mut bytes = Vec::new(); + g.put(&mut bytes); + let back = GraphicsState::get(&bytes).expect("whole"); + assert_eq!(back.describe(), g.describe()); + assert!(GraphicsState::get(&bytes[..bytes.len() - 1]).is_none()); + assert!(GraphicsState::get(&bytes[..9]).is_none()); + } + + #[test] + fn a_torn_end_is_not_read() { + let dir = std::env::temp_dir().join(format!("victory-known-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut bytes = Vec::new(); + for n in 0..3u8 { + bytes.extend(20u32.to_le_bytes()); + bytes.extend([n; 20]); + } + std::fs::write(dir.join(PIPELINES), &bytes[..bytes.len() - 5]).unwrap(); + assert_eq!(count(&dir), 2); + assert_eq!(keys(&dir)[1], "01".repeat(16)); + assert_eq!(walk_pipelines(&dir, |_, _| ()), 48); + let mut shader = vec![5u8]; + shader.extend([9; 32]); + shader.extend(4u32.to_le_bytes()); + shader.extend([1, 2, 3, 4]); + let one = shader.len() as u64; + shader.extend_from_slice(&shader.clone()[..20]); + std::fs::write(dir.join(SHADERS), &shader).unwrap(); + let mut seen = Vec::new(); + assert_eq!(walk_shaders(&dir, |stage, hash, at, len| seen.push((stage, hash[0], at, len))), one); + assert_eq!(seen, [(5, 9, 37, 4)]); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index fa22cf8..d8c3c14 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -62,6 +62,11 @@ pub fn use_pipeline_cache(dir: PathBuf) { let _ = DIR.set(dir); } +/// The folder the library is kept in. +pub(super) fn folder() -> Option { + DIR.get().cloned() +} + /// Host pipelines created, loaded from the library, and title pipelines /// started at creation, since the start. pub(crate) static MADE: AtomicU64 = AtomicU64::new(0); diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 3b6183e..d9be9d3 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -59,6 +59,10 @@ impl Pending { } } + pub(super) fn key(&self) -> &str { + &self.key + } + fn make(&self) { self.made .get_or_init(|| HostPipeline::new(&self.shaders, self.graphics.as_deref())); diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index d5cf03f..534ed94 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -93,6 +93,11 @@ fn build() -> [u8; 32] { *hash.finalize().as_bytes() } +/// What tells one set of translations from another ([`build`]). +pub(crate) fn translation() -> [u8; 32] { + build() +} + /// Puts the translation of `container` into the cache before any title asks /// for it (`victory shaders`): whether it was there already, or why it does /// not translate. The host is opened first, as a run does: what the card diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs index 0ad25ff..ab8ea45 100644 --- a/crates/victory-hle/src/lib.rs +++ b/crates/victory-hle/src/lib.rs @@ -26,6 +26,9 @@ pub use victory_gpu::console; #[cfg(all(windows, feature = "diagnostics"))] pub use victory_gpu::replay; +#[cfg(windows)] +pub use victory_gpu::pipeline::known as known_pipelines; + use victory_loader::{ImportResolver, Provenance, Resolution}; use victory_pe::ImportSymbol; From c9b3f45ad7ca4364e8d4f6cc2677720e9cf48461 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 13:44:39 -0600 Subject: [PATCH 397/445] 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 e8d3d918c3ec124fe21d06d33f5200416b45f2b2 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 13:45:09 -0600 Subject: [PATCH 398/445] Look-first stubs for moves and vector stores (VICTORY_WRITE_SITES); descriptors copied onto themselves are not written (VICTORY_SAME_RECORDS=0: they are); of tracked pages the parts written are taken (VICTORY_TAKE_PARTS=0: pages); waits for the trackers' locks and the heap sync's parts counted Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/copystat.rs | 10 +- crates/victory-gpu/src/descriptor.rs | 50 ++++- crates/victory-gpu/src/titlewrite.rs | 30 ++- crates/victory-gpu/src/titlewrite/decode.rs | 73 +++++-- crates/victory-gpu/src/watch.rs | 124 +++++++++-- crates/victory-loader/src/write_sites.rs | 226 +++++++++++++++++++- 6 files changed, 465 insertions(+), 48 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 65f5a32..3bbb9dd 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -1210,11 +1210,15 @@ 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, 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!( + "waits for the write trackers' locks per frame, all threads (number, time): {}", + crate::watch::lock_waits(frames as f64) + ); + let [copies, blocks, opened, stores, unknown, full, stayed, copied_same, records] = + [0, 1, 2, 3, 4, 5, 6, 7, 8].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; left out for changing nothing: {stayed} stores, {copied_same} parts of copies; \ + {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, {records} copies of descriptors; \ the busiest stores (left out/changed): {}", crate::titlewrite::busiest() ); diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 47f9852..a6e74ce 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -301,6 +301,9 @@ 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 views, mut bytes) = (0u64, 0u64); + let mut spent = [0u64; 4]; + let since = |at: std::time::Instant| at.elapsed().as_nanos() as u64; let mut page_bytes: Vec = Vec::new(); let mut changed: Vec = Vec::new(); let mut wait: Vec = Vec::new(); @@ -336,7 +339,10 @@ pub(crate) fn sync_heaps() { 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 began = std::time::Instant::now(); + let taken = written.take(start as usize, end as usize); + spent[0] += since(began); + for (range_from, range_end) in taken { let mut page = range_from & !(crate::watch::PAGE - 1); while page < range_end { let from = page.max(range_from); @@ -345,8 +351,13 @@ pub(crate) fn sync_heaps() { // copy: a page the title unmaps meanwhile fails the read // where 2,048 reads in place would fault. page_bytes.resize(to - from, 0); - if crate::host::read_into(from as *const u8, &mut page_bytes) { + let began = std::time::Instant::now(); + let there = crate::host::read_into(from as *const u8, &mut page_bytes); + spent[1] += since(began); + if there { pages += 1; + views += u64::from(crate::watch::guarded(from, to)); + bytes += (to - from) as u64; let slots = changed_slots(from, to, start as usize, step, mirrored_count); // A record that straddles the range's ends is left // to the range that holds its first byte. @@ -360,7 +371,9 @@ pub(crate) fn sync_heaps() { // Only the records that are not the ones last seen // there (`HostHeap::copied_changes`). changed.clear(); + let began = std::time::Instant::now(); host.copied_changes(first as u32, &records[..(count * step) as usize], step as usize, &mut changed); + spent[2] += since(began); for &index in &changed { let at = (u64::from(index) - first) as usize * step as usize; let word = |n: usize| { @@ -393,11 +406,13 @@ pub(crate) fn sync_heaps() { page += crate::watch::PAGE; } } + let began = std::time::Instant::now(); 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); } }); + spent[3] += since(began); if !wait.is_empty() { host.copied_wait(frame, std::mem::take(&mut wait)); } @@ -407,6 +422,10 @@ pub(crate) fn sync_heaps() { for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, micros, tabled, later]) { count.fetch_add(n, Relaxed); } + let [taking, reading, comparing, making] = spent; + for (count, n) in SYNC_SPLIT.iter().zip([views, bytes, taking, reading, comparing, making]) { + count.fetch_add(n, Relaxed); + } } /// Records [`sync_heaps`] gives a thread at a time. @@ -422,6 +441,12 @@ const SYNC_AT_A_TIME: usize = 256; #[cfg(windows)] pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 7] = [const { std::sync::atomic::AtomicU64::new(0) }; 7]; +/// The same, of [`SYNCED`]'s pages: those in view memory that was guarded; +/// bytes read; nanoseconds asking what was written, reading it, comparing it +/// with what was last seen, making views. +#[cfg(windows)] +static SYNC_SPLIT: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; + /// With the frame line: what [`sync_heaps`] did per frame over `frames`. /// Nothing while no heap page changed. #[cfg(windows)] @@ -436,20 +461,27 @@ 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 split = [0, 1, 2, 3, 4, 5].map(|i| SYNC_SPLIT[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64); 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); {:.1} of the pages guarded views, {:.1} MB read; {:.2} ms asking, {:.2} reading, {:.2} comparing, {:.2} making", 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, + split[0] / frames, + split[1] / (1 << 20) as f64 / frames, + split[2] / 1e6 / frames, + split[3] / 1e6 / frames, + split[4] / 1e6 / frames, + split[5] / 1e6 / frames ); } @@ -1249,7 +1281,15 @@ pub(crate) extern "system" fn copy_simple(_: This, count: u32, dst: u64, src: u6 let len = u64::from(count) * step; if dst != 0 && src != 0 { // SAFETY: both ranges are descriptor slots the title owns. - unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len as usize) }; + #[cfg(windows)] + unsafe { + crate::titlewrite::put(dst as *mut u8, src as *const u8, len as usize) + }; + // SAFETY: as above. + #[cfg(not(windows))] + unsafe { + std::ptr::copy(src as *const u8, dst as *mut u8, len as usize) + }; #[cfg(windows)] for i in 0..u64::from(count) { mirror(dst + i * step); diff --git a/crates/victory-gpu/src/titlewrite.rs b/crates/victory-gpu/src/titlewrite.rs index 1a551c5..946fa88 100644 --- a/crates/victory-gpu/src/titlewrite.rs +++ b/crates/victory-gpu/src/titlewrite.rs @@ -33,8 +33,8 @@ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; /// 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; 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]; +/// it was, and were not made; descriptors copied onto themselves. +pub(crate) static DONE: [AtomicU64; 9] = [const { AtomicU64::new(0) }; 9]; fn add(what: usize) { DONE[what].fetch_add(1, Relaxed); @@ -172,6 +172,28 @@ unsafe extern "system-unwind" fn set(to: *mut u8, byte: i32, n: usize) -> *mut u to } +/// Bytes of the title's that we put into its memory for it (a descriptor it +/// has copied): as a copy of its own, but what is there already is never +/// written (`VICTORY_SAME_RECORDS=0`: always). +/// +/// # Safety +/// `[from, from + n)` and `[to, to + n)` are the title's. +pub(crate) unsafe fn put(to: *mut u8, from: *const u8, n: usize) { + // SAFETY: by the caller. + unsafe { + let there = || std::slice::from_raw_parts(to.cast_const(), n) == std::slice::from_raw_parts(from, n); + if crate::toggled!("VICTORY_SAME_RECORDS") && there() { + add(8); + return; + } + if n == 0 || !copies_on() || !crate::watch::guards_any(to as usize, n) || overlap(to as usize, from as usize, n) { + std::ptr::copy(from, to, n); + return; + } + in_pieces(to as usize, n, |_, _, _| false, |at, offset, len| std::ptr::copy_nonoverlapping(from.add(offset), at as *mut u8, len)); + } +} + /// 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 { @@ -257,9 +279,9 @@ fn learn(rip: usize, same: bool, can_look: bool) { return; }; use std::io::Write; - let line = format!("{image} {offset:x} or\n"); + let line = format!("{image} {offset:x}\n"); let known = std::fs::read_to_string(&file).unwrap_or_default(); - if known.lines().any(|l| l == line.trim_end()) { + if known.lines().any(|l| l.starts_with(line.trim_end())) { return; } if let Ok(mut file) = std::fs::OpenOptions::new().append(true).create(true).open(&file) { diff --git a/crates/victory-gpu/src/titlewrite/decode.rs b/crates/victory-gpu/src/titlewrite/decode.rs index e83f5b6..11343c9 100644 --- a/crates/victory-gpu/src/titlewrite/decode.rs +++ b/crates/victory-gpu/src/titlewrite/decode.rs @@ -1,7 +1,7 @@ //! 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`. +//! (locked or not), exchanges, and the 4, 8, 16 and 32 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; @@ -18,7 +18,7 @@ enum Alu { #[derive(Clone, Copy, PartialEq, Debug)] enum Op { /// These bytes (the low `size` of them). - Put([u8; 16]), + Put([u8; 32]), /// With a value; `keeps` carry (`inc`, `dec`). Alu { alu: Alu, with: u64, keeps: bool }, /// With a register, which gets what was there. @@ -116,6 +116,27 @@ fn mask(size: usize) -> u64 { if size >= 8 { u64::MAX } else { (1 << (size * 8)) - 1 } } +/// The upper half of vector register `reg`, where the context has it; nothing +/// in it if the thread used none. +fn upper(c: &CONTEXT, reg: usize) -> Option<[u8; 16]> { + use windows_sys::Win32::System::Diagnostics::Debug::{GetXStateFeaturesMask, LocateXStateFeature}; + const AVX: u32 = 2; + let mut mask = 0; + // SAFETY: a context as the system passes it to a handler (the calls + // change nothing of it). + unsafe { + if GetXStateFeaturesMask(c, &mut mask) == 0 { + return None; + } + if mask >> AVX & 1 == 0 { + return Some([0; 16]); + } + let mut len = 0; + let at = LocateXStateFeature(c, AVX, &mut len) as *const [u8; 16]; + (!at.is_null() && len as usize >= 16 * 16).then(|| at.add(reg).read_unaligned()) + } +} + /// 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; @@ -124,7 +145,7 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { at += 1; byte }; - let (mut locked, mut narrow, mut repeat) = (false, false, 0u8); + let (mut locked, mut narrow, mut repeat, mut long) = (false, false, 0u8, false); let mut byte = next()?; loop { match byte { @@ -160,10 +181,10 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { _ => None, }; if let Some(b) = vector { - // (No 32 byte ones: they fill memory.) - if b & 4 != 0 || narrow || repeat != 0 || locked { + if narrow || repeat != 0 || locked { return None; } + long = b & 4 != 0; // (A store has no third register.) if b >> 3 & 15 != 15 { return None; @@ -223,7 +244,7 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { 4 }; let put = |value: u64| { - let mut bytes = [0; 16]; + let mut bytes = [0; 32]; bytes[..8].copy_from_slice(&value.to_le_bytes()); Op::Put(bytes) }; @@ -231,9 +252,9 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { let vector_bytes = || { // SAFETY: the registers, whichever way they are named. let x = unsafe { &c.Anonymous.FltSave }.XmmRegisters[reg]; - let mut bytes = [0; 16]; + let mut bytes = [0; 32]; bytes[..8].copy_from_slice(&x.Low.to_le_bytes()); - bytes[8..].copy_from_slice(&x.High.to_le_bytes()); + bytes[8..16].copy_from_slice(&x.High.to_le_bytes()); bytes }; let alu_of = |kind: u8| match kind { @@ -244,14 +265,21 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { 6 => Some(Alu::Xor), _ => None, }; - let (op, size) = if two { + let (op, size) = if long { + if !matches!((byte, narrow, repeat), (0x11 | 0x29, _, 0) | (0x7f, true, 0) | (0x7f, false, 0xf3) | (0xe7, true, 0)) { + return None; + } + let mut bytes = vector_bytes(); + bytes[16..].copy_from_slice(&upper(c, reg)?); + (Op::Put(bytes), 32) + } else 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); + bytes.copy_within(8..16, 0); (Op::Put(bytes), 8) } (0x7e, true, 0) => (Op::Put(vector_bytes()), if wide { 8 } else { 4 }), @@ -393,7 +421,7 @@ impl Store { return None; } let mut there = [0u8; 32]; - // SAFETY: by the caller. + // SAFETY: by the caller (32 bytes at the most). 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)), @@ -406,12 +434,18 @@ impl Store { } } - /// 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. + /// Whether the loader may make it look before it writes + /// (`victory_loader::write_sites`, which looks itself): an `or` of a byte + /// with a constant, a move of 4 bytes or more; 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, .. }) + self.len >= 5 + && match self.op { + Op::Alu { alu: Alu::Or, .. } => code[at] == 0x80, + Op::Put(_) => matches!(code[0], 0xc4 | 0xc5) && self.size >= 16 || matches!(code[at], 0x89 | 0xc7), + _ => false, + } } /// Does it, with `to` for the address, and gives the registers what the @@ -428,7 +462,7 @@ impl Store { // 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")); + let low = u64::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]]); 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), @@ -526,9 +560,8 @@ mod tests { 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); + // Not stores of these: a load, a register's, a string instruction, a + // thread's own memory, a compare, adc. assert_eq!(decoded(&[0x48, 0x8b, 0x13]), None); assert_eq!(decoded(&[0x48, 0x89, 0xd3]), None); assert_eq!(decoded(&[0xf3, 0xa4]), None); diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 62fb034..d08825a 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -151,11 +151,48 @@ static JOURNAL: RwLock = RwLock::new(Journal { }); fn journal() -> std::sync::RwLockReadGuard<'static, Journal> { - JOURNAL.read().unwrap_or_else(|e| e.into_inner()) + if let Ok(j) = JOURNAL.try_read() { + return j; + } + waited(1, || JOURNAL.read().unwrap_or_else(|e| e.into_inner())) } fn journal_mut() -> std::sync::RwLockWriteGuard<'static, Journal> { - JOURNAL.write().unwrap_or_else(|e| e.into_inner()) + if let Ok(j) = JOURNAL.try_write() { + return j; + } + waited(2, || JOURNAL.write().unwrap_or_else(|e| e.into_inner())) +} + +/// Since the last line: waits and nanoseconds of waiting, of all threads, for +/// the ranges held ([`ASKING`]), the journal to read it, the journal to note +/// in it, and the guards (faults of the title's among them). +#[cfg(feature = "diagnostics")] +static WAITS: [[std::sync::atomic::AtomicU64; 2]; 4] = [const { [const { std::sync::atomic::AtomicU64::new(0) }; 2] }; 4]; + +#[cfg(feature = "diagnostics")] +fn waited(what: usize, f: impl FnOnce() -> T) -> T { + use std::sync::atomic::Ordering::Relaxed; + let began = std::time::Instant::now(); + let got = f(); + WAITS[what][0].fetch_add(1, Relaxed); + WAITS[what][1].fetch_add(began.elapsed().as_nanos() as u64, Relaxed); + got +} + +#[cfg(not(feature = "diagnostics"))] +fn waited(_: usize, f: impl FnOnce() -> T) -> T { + f() +} + +/// [`WAITS`], taken, for the log: per frame. +#[cfg(feature = "diagnostics")] +pub(crate) fn lock_waits(frames: f64) -> String { + let of = |what: usize| { + let [n, ns] = [0, 1].map(|i| WAITS[what][i].swap(0, std::sync::atomic::Ordering::Relaxed)); + format!("{:.0} {:.2} ms", n as f64 / frames, ns as f64 / 1e6 / frames) + }; + format!("ranges held {}, journal read {}, journal noted in {}, guards {}", of(0), of(1), of(2), of(3)) } /// The page ranges some thread is asking about: asking forgets what it @@ -170,8 +207,14 @@ struct Asking(usize, usize); impl Asking { fn hold(first: usize, last: usize) -> Asking { let mut held = ASKING.0.lock().unwrap_or_else(|e| e.into_inner()); - while held.iter().any(|&(a, b)| a < last && first < b) { - held = ASKING.1.wait(held).unwrap_or_else(|e| e.into_inner()); + if held.iter().any(|&(a, b)| a < last && first < b) { + held = waited(0, || { + let mut held = held; + while held.iter().any(|&(a, b)| a < last && first < b) { + held = ASKING.1.wait(held).unwrap_or_else(|e| e.into_inner()); + } + held + }); } held.push((first, last)); Asking(first, last) @@ -725,13 +768,10 @@ impl Tracked { return Vec::new(); }; let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner()); - let mut ranges: Vec<(usize, usize)> = Vec::new(); + let mut new: Vec<(usize, u64)> = Vec::new(); for (page, write) in pages { - if seen.get(&page).is_some_and(|&last| last >= write) { - continue; - } - let (start, end) = ((page * PAGE).max(from), ((page + 1) * PAGE).min(to)); - if start >= end { + let last = seen.get(&page).copied(); + if last.is_some_and(|last| last >= write) || (page * PAGE).max(from) >= ((page + 1) * PAGE).min(to) { continue; } // Keep partial pages dirty: the caller has not taken the rest. @@ -740,9 +780,26 @@ impl Tracked { { seen.insert(page, write); } - match ranges.last_mut() { - Some((_, last)) if *last == start => *last = end, - _ => ranges.push((start, end)), + new.push((page, last.unwrap_or(0))); + } + // Of a page taken before, the parts written since, where they are + // known (`VICTORY_TAKE_PARTS=0`: the page). + let parts = if crate::toggled!("VICTORY_TAKE_PARTS") { parts_written(&new) } else { vec![WHOLE; new.len()] }; + let mut ranges: Vec<(usize, usize)> = Vec::new(); + for (&(page, last), &parts) in new.iter().zip(&parts) { + let mut parts = if last == 0 { WHOLE } else { parts }; + while parts != 0 { + let first = parts.trailing_zeros() as usize; + let past = first + (!(parts >> first)).trailing_zeros() as usize; + parts &= if past >= PARTS { 0 } else { u16::MAX << past }; + let (start, end) = ((page * PAGE + first * KERNEL_PAGE).max(from), (page * PAGE + past.min(PARTS) * KERNEL_PAGE).min(to)); + if start >= end { + continue; + } + match ranges.last_mut() { + Some((_, last)) if *last == start => *last = end, + _ => ranges.push((start, end)), + } } } ranges @@ -1365,7 +1422,10 @@ static GUARDS: Mutex = Mutex::new(Guards { }); fn guards() -> std::sync::MutexGuard<'static, Guards> { - GUARDS.lock().unwrap_or_else(|e| e.into_inner()) + if let Ok(g) = GUARDS.try_lock() { + return g; + } + waited(3, || GUARDS.lock().unwrap_or_else(|e| e.into_inner())) } /// The 4 KiB pages of title memory that what shaders wrote was put into, @@ -3553,6 +3613,42 @@ mod tests { crate::title_memory_section_gone(section); } + /// Of a page taken before, what is taken again is the kernel's pages + /// written since; where they are not known, all of it. + #[test] + fn what_is_taken_again_is_what_was_written() { + // SAFETY: a fresh write-watched allocation, freed at the end. + let p = unsafe { + VirtualAlloc(std::ptr::null(), 4 * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) + } as usize; + assert_ne!(p, 0); + let write = |at: usize| { + // SAFETY: committed pages of ours. + unsafe { ((p + at) as *mut u8).write_volatile(1) } + }; + let tracked = track(p, 4 * PAGE, false).expect("watched"); + write(5); + write(PAGE + 5000); + assert_eq!(tracked.take(p, p + 4 * PAGE), [(p, p + 2 * PAGE)], "never taken"); + assert!(tracked.take(p, p + 4 * PAGE).is_empty()); + write(PAGE + 5000); + write(PAGE + 8192); + write(PAGE + 65535); + write(2 * PAGE); + assert_eq!( + tracked.take(p, p + 4 * PAGE), + [(p + PAGE + 4096, p + PAGE + 3 * 4096), (p + 2 * PAGE - 4096, p + 3 * PAGE)], + "page 2 was never taken" + ); + write(2 * PAGE + 70); + // Two askings' writes are in what is taken after both. + assert!(writes(p, p + 4 * PAGE, false).is_some()); + write(2 * PAGE + 9000); + assert_eq!(tracked.take(p, p + 4 * PAGE), [(p + 2 * PAGE, p + 2 * PAGE + 4096), (p + 2 * PAGE + 8192, p + 2 * PAGE + 12288)]); + // SAFETY: our allocation. + unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; + } + /// The set of blocks against another of the same. #[test] fn blocks_are_a_set() { diff --git a/crates/victory-loader/src/write_sites.rs b/crates/victory-loader/src/write_sites.rs index 11f2d97..f1167e3 100644 --- a/crates/victory-loader/src/write_sites.rs +++ b/crates/victory-loader/src/write_sites.rs @@ -1,5 +1,6 @@ -//! 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). +//! Places in the title's code that write what is nearly always there already, changed at load to +//! look first (`VICTORY_WRITE_SITES=`; off without it): flags that are set, registers and +//! constants moved to memory, 16 and 32 bytes of the vector registers. //! //! 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 @@ -52,8 +53,141 @@ fn or_byte(code: &[u8]) -> Option<(usize, u8, u8, &[u8], u8)> { Some((end + 1, rex, modrm, &code[rest..end], constant)) } +/// How many bytes behind a ModRM byte name an address, `None` for a register, for the instruction +/// pointer's neighbourhood, the stack (whose pointer is another in our code) and a plain address. +/// `b`: the prefix's bit for the base. +fn address(code: &[u8], modrm: u8, b: bool) -> Option { + let (mode, rm) = (modrm >> 6, modrm & 7); + if mode == 3 || mode == 0 && rm == 5 { + return None; + } + let mut len = 0; + if rm == 4 { + let sib = *code.first()?; + if sib & 7 == 4 && !b || sib & 7 == 5 && mode == 0 { + return None; + } + len = 1; + } + len += match mode { + 1 => 1, + 2 => 4, + _ => 0, + }; + Some(len) +} + +/// The end of a stub that has nothing in rcx if the write is left out, and the title's rcx on the +/// stack: the write (`code[..len]`, at `at`) or not, and back. `wide`: all of rcx counts. +fn write_or_not(out: &mut Vec, stub: usize, code: &[u8], at: usize, len: usize, wide: bool) -> Option<()> { + if !wide { + out.push(0x67); + } + out.extend([0xe3, u8::try_from(1 + len + 5).ok()?]); // jrcxz (jecxz) past the write + out.push(0x59); // pop rcx + out.extend(&code[..len]); + out.extend(crate::console_insn::jump(stub + out.len(), at + len)?); + out.push(0x59); + out.extend(crate::console_insn::jump(stub + out.len(), at + len)?); + Some(()) +} + +/// [`stub`] for a vector register's store. No flag is touched. +fn vector_stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec)> { + let (reg_high, xb, third, op_at) = match *code.first()? { + 0xc5 => { + let b = *code.get(1)?; + (b & 0x80 == 0, 0x60, b, 2) + } + 0xc4 => { + let b = *code.get(1)?; + if b & 0x1f != 1 { + return None; + } + (b & 0x80 == 0, b & 0x60, *code.get(2)?, 3) + } + _ => return None, + }; + let (op, modrm) = (*code.get(op_at)?, *code.get(op_at + 1)?); + if !matches!((op, third & 3), (0x11 | 0x29, 0 | 1) | (0x7f, 1 | 2)) || third >> 3 & 15 != 15 { + return None; + } + let long = third & 4; + if !std::is_x86_feature_detected!("avx2") { + return None; + } + let rest = address(code.get(op_at + 2..)?, modrm, xb & 0x20 == 0)?; + let len = op_at + 2 + rest; + if len < 5 { + return None; + } + let reg = modrm >> 3 & 7 | if reg_high { 8 } else { 0 }; + let spare = if reg == 1 { 2u8 } else { 1 }; + let mut out = vec![0x51]; // push rcx + out.extend([0x48, 0x8d, 0x64, 0x24, 0xe0]); // lea rsp, [rsp-32] + out.extend([0xc5, 0xfe, 0x7f, spare << 3 | 4, 0x24]); // vmovdqu [rsp], spare (32 bytes) + // vpcmpeqb spare, reg, [m] + out.extend([0xc4, 0x80 | xb | 1, (!reg & 15) << 3 | long | 1, 0x74, modrm & 0xc7 | spare << 3]); + out.extend(&code[op_at + 2..len]); + out.extend([0xc5, 0xf9 | long, 0xd7, 0xc8 | spare]); // vpmovmskb ecx, spare + out.extend([0xc5, 0xfe, 0x6f, spare << 3 | 4, 0x24]); // vmovdqu spare, [rsp] + out.extend([0x48, 0x8d, 0x64, 0x24, 0x20]); // lea rsp, [rsp+32] + out.extend([0xf7, 0xd1]); // not ecx + if long == 0 { + out.extend([0x0f, 0xb7, 0xc9]); // movzx ecx, cx + } + write_or_not(&mut out, stub, code, at, len, false)?; + Some((len, out)) +} + +/// [`stub`] for a `mov` of a register or a constant, 4 or 8 bytes. No flag is touched. +fn move_stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec)> { + let mut at_op = 0; + let mut rex = 0x40; + if code.first()? & 0xf0 == 0x40 { + rex = code[0]; + at_op = 1; + } + let (op, modrm) = (*code.get(at_op)?, *code.get(at_op + 1)?); + let wide = rex & 8 != 0; + let reg = modrm >> 3 & 7 | (rex & 4) << 1; + let rest = address(code.get(at_op + 2..)?, modrm, rex & 1 != 0)?; + let end = at_op + 2 + rest; + let (len, constant) = match op { + 0x89 if reg != 1 && reg != 4 => (end, None), + 0xc7 if reg & 7 == 0 => { + let bytes = code.get(end..end + 4)?.try_into().ok()?; + (end + 4, Some(i32::from_le_bytes(bytes).checked_add(1)?)) + } + _ => return None, + }; + if len < 5 { + return None; + } + let mut out = vec![0x51]; // push rcx + out.extend([rex & 0x4b, 0x8b, modrm & 0xc7 | 1 << 3]); // mov rcx, [m] + out.extend(&code[at_op + 2..end]); + let w = 0x40 | rex & 8; + out.extend([w, 0xf7, 0xd1]); // not rcx + match constant { + Some(next) => { + out.extend([w, 0x8d, 0x89]); // lea rcx, [rcx+constant+1] + out.extend(next.to_le_bytes()); + } + // lea rcx, [rcx+reg+1] + None => out.extend([w | (reg & 8) >> 2, 0x8d, 0x4c, (reg & 7) << 3 | 1, 1]), + } + write_or_not(&mut out, stub, code, at, len, wide)?; + Some((len, out)) +} + /// The code at `stub` for the instruction at `at` (`code` from there). fn stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec)> { + vector_stub(code, at, stub).or_else(|| move_stub(code, at, stub)).or_else(|| or_stub(code, at, stub)) +} + +/// [`stub`] for the `or` of a byte with a constant. +fn or_stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec)> { let (len, rex, modrm, rest, constant) = or_byte(code)?; if len < 5 { return None; @@ -232,6 +366,94 @@ mod tests { } } + /// Memory a vector store may ask to lie on its boundary. + #[repr(C, align(64))] + #[derive(Clone, Copy)] + struct Memory([u8; 0x80]); + + /// Moves of registers and constants, and vector stores, in code of a test's: changed, they + /// store what they did, leave registers and flags, and write nothing that is there already. + #[test] + fn changed_moves_and_vector_stores_do_what_they_did() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READONLY, PAGE_READWRITE, VirtualAlloc, VirtualProtect, + }; + // Each stores at r9+40h (r10 is 0): rdx, r13 or a vector register 0, 1, 9. + let stores: &[(&[u8], usize)] = &[ + (&[0x49, 0x89, 0x51, 0x40], 0), // (four bytes: left alone) + (&[0x4b, 0x89, 0x54, 0xd1, 0x40], 8), // mov [r9+r10*8+40h], rdx + (&[0x43, 0x89, 0x54, 0xd1, 0x40], 4), // mov [r9+r10*8+40h], edx + (&[0x4d, 0x89, 0xa9, 0x40, 0, 0, 0], 8), // mov [r9+40h], r13 + (&[0x45, 0x89, 0xa9, 0x40, 0, 0, 0], 4), // mov [r9+40h], r13d + (&[0x41, 0xc7, 0x41, 0x40, 0x78, 0x56, 0x34, 0x92], 4), // mov dword [r9+40h], 92345678h + (&[0x49, 0xc7, 0x41, 0x40, 0x78, 0x56, 0x34, 0x92], 8), // mov qword [r9+40h], the same + (&[0xc4, 0xc1, 0x7a, 0x7f, 0x41, 0x40], 16), // vmovdqu [r9+40h], xmm0 + (&[0xc4, 0xc1, 0x7a, 0x7f, 0x49, 0x40], 16), // vmovdqu [r9+40h], xmm1 + (&[0xc4, 0x41, 0x78, 0x29, 0x49, 0x40], 16), // vmovaps [r9+40h], xmm9 + (&[0xc4, 0x81, 0x78, 0x11, 0x44, 0xd1, 0x40], 16), // vmovups [r9+r10*8+40h], xmm0 + (&[0xc4, 0xc1, 0x7c, 0x11, 0x41, 0x40], 32), // vmovups [r9+40h], ymm0 + (&[0xc4, 0xc1, 0x7e, 0x7f, 0x49, 0x40], 32), // vmovdqu [r9+40h], ymm1 + ]; + type F = unsafe extern "system" fn(*mut u8, u64, *mut u8); + for &(store, size) in stores { + let mut code = vec![0x41, 0x55, 0x49, 0x89, 0xc9, 0x4d, 0x31, 0xd2, 0x49, 0x89, 0xd5]; // push r13 ; r9 = rcx ; r10 = 0 ; r13 = rdx + code.extend([0x48, 0xc7, 0xc1, 0x34, 0x12, 0, 0]); // mov rcx, 1234h + code.extend([0x48, 0x83, 0xec, 0x40, 0xc5, 0x7a, 0x7f, 0x0c, 0x24]); // sub rsp, 40h ; xmm9 kept + code.extend([0xc4, 0xc1, 0x7e, 0x6f, 0x00]); // vmovdqu ymm0, [r8] + code.extend([0xc4, 0xc1, 0x7e, 0x6f, 0x48, 0x20]); // vmovdqu ymm1, [r8+32] + code.extend([0xc4, 0x41, 0x7a, 0x6f, 0x48, 0x10]); // vmovdqu xmm9, [r8+16] + code.extend([0x48, 0x39, 0xc0]); // cmp rax, rax + let at = code.len(); + code.extend(store); + code.extend([0x9c, 0x41, 0x5b]); // pushfq ; pop r11 + code.extend([0xc5, 0xfe, 0x7f, 0x4c, 0x24, 0x10]); // vmovdqu [rsp+10h], ymm1 + code.extend([0x48, 0x8b, 0x44, 0x24, 0x18, 0x48, 0x03, 0x44, 0x24, 0x28]); // rax = two of its parts + code.extend([0xc5, 0x7a, 0x6f, 0x0c, 0x24, 0x48, 0x83, 0xc4, 0x40, 0x41, 0x5d]); // xmm9 back ; rsp ; pop r13 + // Flags, rcx and rax behind the source ; vzeroupper ; ret + code.extend([0x4d, 0x89, 0x58, 0x40, 0x49, 0x89, 0x48, 0x48, 0x49, 0x89, 0x40, 0x50, 0xc5, 0xf8, 0x77, 0xc3]); + // SAFETY: fresh memory for code, twice, one of them changed before it runs; data of ours. + unsafe { + let place = VirtualAlloc(std::ptr::null(), 0x10000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize; + assert_ne!(place, 0); + let second = place + 0x2000; + std::ptr::copy_nonoverlapping(code.as_ptr(), place as *mut u8, code.len()); + std::ptr::copy_nonoverlapping(code.as_ptr(), second as *mut u8, code.len()); + assert_eq!(apply("t.dll", second, 0x2000, &format!("t.dll {at:x}")), usize::from(size != 0), "{store:x?}"); + if size == 0 { + continue; + } + let (plain, changed): (F, F) = (std::mem::transmute(place), std::mem::transmute(second)); + let data = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; + for seed in 0..200u64 { + let value = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15); + let mut source = [[0u8; 0x60]; 2]; + for (k, byte) in source[0][..0x40].iter_mut().enumerate() { + *byte = (value >> (k % 8 * 8)) as u8 ^ k as u8; + } + source[1] = source[0]; + let was = Memory(std::array::from_fn(|k| (seed as usize * 7 + k) as u8)); + let mut memory = [was; 2]; + plain(memory[0].0.as_mut_ptr(), value, source[0].as_mut_ptr()); + changed(memory[1].0.as_mut_ptr(), value, source[1].as_mut_ptr()); + assert!(memory[0].0 == memory[1].0, "{store:x?}"); + assert!(memory[0].0[..0x40] == was.0[..0x40] && memory[0].0[0x40 + size..] == was.0[0x40 + size..]); + assert_eq!(source[0], source[1], "{store:x?}: registers and flags"); + // One bit different; and nothing different, in read-only memory. + let mut off = memory[0]; + off.0[0x40 + seed as usize % size] ^= 1 << (seed % 8); + changed(off.0.as_mut_ptr(), value, source[1].as_mut_ptr()); + assert!(off.0 == memory[0].0, "{store:x?}"); + std::ptr::copy_nonoverlapping(memory[0].0.as_ptr(), data, 0x80); + let mut old = 0; + VirtualProtect(data.cast(), 4096, PAGE_READONLY, &mut old); + changed(data, value, source[1].as_mut_ptr()); + assert_eq!(source[0], source[1], "{store:x?}: registers and flags, nothing written"); + VirtualProtect(data.cast(), 4096, PAGE_READWRITE, &mut old); + } + } + } + } + /// A byte that would not change is not written. #[test] fn a_byte_that_stays_is_not_written() { From 9ab730282f3e9b4120d948acd1b69fef0ef28f74 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 13:46:47 -0600 Subject: [PATCH 399/445] Test of parts taken: other tests' notes at the address Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/watch.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index d08825a..a120b25 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -3627,9 +3627,9 @@ mod tests { unsafe { ((p + at) as *mut u8).write_volatile(1) } }; let tracked = track(p, 4 * PAGE, false).expect("watched"); - write(5); - write(PAGE + 5000); - assert_eq!(tracked.take(p, p + 4 * PAGE), [(p, p + 2 * PAGE)], "never taken"); + // (Other tests' memory was here.) + (0..4).for_each(|page| write(page * PAGE + 5)); + assert_eq!(tracked.take(p, p + 4 * PAGE), [(p, p + 4 * PAGE)], "never taken"); assert!(tracked.take(p, p + 4 * PAGE).is_empty()); write(PAGE + 5000); write(PAGE + 8192); @@ -3637,8 +3637,7 @@ mod tests { write(2 * PAGE); assert_eq!( tracked.take(p, p + 4 * PAGE), - [(p + PAGE + 4096, p + PAGE + 3 * 4096), (p + 2 * PAGE - 4096, p + 3 * PAGE)], - "page 2 was never taken" + [(p + PAGE + 4096, p + PAGE + 3 * 4096), (p + 2 * PAGE - 4096, p + 2 * PAGE + 4096)] ); write(2 * PAGE + 70); // Two askings' writes are in what is taken after both. From f4cc8d8be4880540351d7bea215a51902c4ded02 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 14:01:14 -0600 Subject: [PATCH 400/445] 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 401/445] 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 402/445] 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 403/445] 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. From a30829c4d245467d06df7aaebddc32f8fd954a82 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 14:35:11 -0600 Subject: [PATCH 404/445] Pipelines known to take long are made beside the others, by a quarter of the workers (VICTORY_PIPELINE_SLOW=0: in the order created) Run shaders-1, the first with a changed translator (fresh shader and pipeline caches): 3,020 pipelines started at creation, all 16 workers in programs of seconds to tens of seconds each while the title loaded (97 made in 20 s), then the quick ones at 100-190 a second, too late: 0.5-1.6 s a frame and up to 2,900 draws a frame dropped from 60 to 150 s. A pipeline that took a second is now noted (slow-pipelines.txt; `victory warm` notes them too) and waits in a list of its own. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/warm.rs | 17 +++- crates/victory-gpu/src/pipeline/library.rs | 44 +++++++++ crates/victory-gpu/src/pipeline/make.rs | 103 ++++++++++++++++++--- 3 files changed, 147 insertions(+), 17 deletions(-) diff --git a/apps/victory/src/warm.rs b/apps/victory/src/warm.rs index 8bd57c2..985333a 100644 --- a/apps/victory/src/warm.rs +++ b/apps/victory/src/warm.rs @@ -14,10 +14,13 @@ use victory_hle::known_pipelines as known; /// Pipelines a process makes before another takes its place: the compiler's /// and the translations' memory goes with it. -const AT_ONCE: usize = 200; +const AT_ONCE: usize = 40; /// A pipeline that takes longer is taken for one the compiler hangs on. const LONGEST: Duration = Duration::from_secs(180); +/// As the runs count one that takes long. +const SLOW_MS: f64 = 1000.0; + fn folder() -> Result { let cfg = victory_core::Config::load()?; Ok(cfg.cache_subdir("shaders")?.with_file_name("pipelines")) @@ -69,6 +72,8 @@ pub fn run(jobs: Option, limit: Option, again: bool, used: bool, t let next = AtomicUsize::new(0); let state = Mutex::new((Vec::::new(), 0usize, 0usize)); let done_out = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(&done_file)?); + // (Read back by the runs: these are made beside the others, not before.) + let slow_out = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(dir.join("slow-pipelines.txt"))?); let bad_out = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(&bad_file)?); std::thread::scope(|s| { for _ in 0..jobs.min(chunks.len()) { @@ -77,6 +82,9 @@ pub fn run(jobs: Option, limit: Option, again: bool, used: bool, t let mut rest = chunk; while !rest.is_empty() { let (made, ended) = child(rest, |n, ms, there| { + if ms >= SLOW_MS { + let _ = writeln!(lock(&slow_out), "\n{} {ms:.0}", keys[n]); + } let mut state = lock(&state); state.0.push(ms); state.1 += usize::from(!there); @@ -187,11 +195,14 @@ fn make(dir: &Path, these: &str) -> Result<()> { victory_hle::known_pipelines::use_translations(cfg.cache_subdir("shaders")?); let mut out = std::io::stdout(); known::make(dir, &these, |n, came| { - let _ = match came { + let told = match came { None => writeln!(out, "at {n}"), Some((ms, there)) => writeln!(out, "made {n} {ms:.2} {}", u8::from(there)), }; - let _ = out.flush(); + if told.and_then(|()| out.flush()).is_err() { + // Whoever asked is gone. + std::process::exit(1); + } }); // Without what a run's end does (nothing to save, the host's threads). let _ = out.flush(); diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index d8c3c14..a7e974b 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -633,7 +633,9 @@ pub(crate) fn save(now: bool) { ) }); } + let slow: Vec = slow_ones().iter().flatten().map(|(key, ms)| format!("{key} {ms}")).collect(); let written = library_written + .and_then(|()| write_atomically(&dir.join(SLOW_FILE), slow.join("\n").as_bytes())) .and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes())); match written { Ok(()) => tracing::info!( @@ -696,6 +698,48 @@ fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> res } +/// How long each title pipeline that took long to make took, in ms (beside +/// the early list; a key may be there more than once). +const SLOW_FILE: &str = "slow-pipelines.txt"; +/// A pipeline that takes this long is one ([`slow`]). +pub(crate) const SLOW_MS: u64 = 1000; +static SLOW: Mutex>> = Mutex::new(None); + +fn slow_ones() -> std::sync::MutexGuard<'static, Option>> { + let mut slow = SLOW.lock().unwrap_or_else(|e| e.into_inner()); + if slow.is_none() { + let listed = DIR.get().and_then(|d| std::fs::read_to_string(d.join(SLOW_FILE)).ok()).unwrap_or_default(); + *slow = Some( + listed + .lines() + .filter_map(|l| l.split_once(' ')) + .filter_map(|(key, ms)| Some((key.to_owned(), ms.parse().ok()?))) + .collect(), + ); + } + slow +} + +/// Whether making the title pipeline with `key` took [`SLOW_MS`] in this or +/// an earlier run. +pub(crate) fn slow(key: &str) -> bool { + slow_ones().as_ref().is_some_and(|s| s.contains_key(key)) +} + +/// The title pipeline with `key` took `ms` to make. +pub(crate) fn note_time(key: &str, ms: u64) { + if ms < SLOW_MS { + return; + } + let mut slow = slow_ones(); + let known = slow.get_or_insert_default().entry(key.to_owned()).or_insert(0); + if ms > *known { + *known = ms; + // With the next save of the early list. + USED_CHANGED.store(true, Ordering::Relaxed); + } +} + /// Title pipeline keys requested by draws or dispatches (this run and the last). static USED: Mutex>> = Mutex::new(None); static USED_CHANGED: AtomicBool = AtomicBool::new(false); diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index d9be9d3..4d30346 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -28,6 +28,8 @@ pub(crate) struct Pending { shaders: Vec>, pub(crate) graphics: Option>, queue_state: AtomicU8, + /// Taken by a worker from [`Queue::slow`]. + was_slow: AtomicBool, made: OnceLock>, /// What identifies it across runs (shader containers and state), and /// whether a draw or dispatch has requested it yet. @@ -53,6 +55,7 @@ impl Pending { shaders, graphics, queue_state: AtomicU8::new(NOT_QUEUED), + was_slow: AtomicBool::new(false), made: OnceLock::new(), key: key.finalize().to_hex()[..32].to_owned(), used: AtomicBool::new(false), @@ -64,8 +67,12 @@ impl Pending { } fn make(&self) { - self.made - .get_or_init(|| HostPipeline::new(&self.shaders, self.graphics.as_deref())); + self.made.get_or_init(|| { + let began = Instant::now(); + let made = HostPipeline::new(&self.shaders, self.graphics.as_deref()); + super::library::note_time(&self.key, began.elapsed().as_millis() as u64); + made + }); let (lock, done) = &DONE; let _held = lock.lock().unwrap_or_else(|e| e.into_inner()); done.notify_all(); @@ -228,8 +235,31 @@ const EARLY: u8 = 1; const REQUESTED: u8 = 2; const MAKING: u8 = 3; +/// How many workers may make pipelines at once that are known to take long +/// and that no draw has asked for: a quarter of them. On a fresh cache (a +/// change of the translator or the driver) the early list begins with +/// programs that take tens of seconds each: all 16 workers were in them +/// through the whole of the title's loading, 97 pipelines made in 20 s, and +/// the first minute and a half of the world ran at 0.5 to 1.6 s a frame, +/// dropping up to 2,900 draws a frame (run shaders-1). +/// `VICTORY_PIPELINE_SLOW=0`: in the order the title creates them, as before. +fn slow_limit() -> usize { + static LIMIT: OnceLock = OnceLock::new(); + *LIMIT.get_or_init(|| { + if std::env::var_os("VICTORY_PIPELINE_SLOW").is_some_and(|v| v == "0") { + usize::MAX + } else { + (worker_count(None, std::thread::available_parallelism().map_or(2, |n| n.get())) / 4).max(1) + } + }) +} + struct Queue { early: VecDeque>, + /// Those of the early ones known to take long, and how many of them are + /// being made ([`slow_limit`]). + slow: VecDeque>, + slow_now: usize, requested: VecDeque>, } @@ -237,6 +267,8 @@ impl Queue { const fn new() -> Self { Self { early: VecDeque::new(), + slow: VecDeque::new(), + slow_now: 0, requested: VecDeque::new(), } } @@ -244,6 +276,10 @@ impl Queue { /// Queues an unrequested pipeline or promotes one queued at creation. /// Returns whether it is new to the queue, or `None` if nothing changed. fn push(&mut self, p: &Arc, priority: u8) -> Option { + self.push_as(p, priority, slow_limit() != usize::MAX && super::library::slow(&p.key)) + } + + fn push_as(&mut self, p: &Arc, priority: u8, slow: bool) -> Option { let prev = p.queue_state.load(Ordering::Relaxed); if prev >= priority { return None; @@ -251,18 +287,28 @@ impl Queue { p.queue_state.store(priority, Ordering::Relaxed); if priority == REQUESTED { self.requested.push_back(p.clone()); + } else if slow { + self.slow.push_back(p.clone()); } else { self.early.push_back(p.clone()); } 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, slow_limit: usize) -> Option> { + // An early entry can have been promoted and claimed already. + let unclaimed = |list: &mut VecDeque>| { + std::iter::from_fn(|| list.pop_front()).find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY) + }; + let mut p = self.requested.pop_front().or_else(|| unclaimed(&mut self.early)); + if p.is_none() && self.slow_now < slow_limit { + p = unclaimed(&mut self.slow); + if let Some(p) = &p { + p.was_slow.store(true, Ordering::Relaxed); + self.slow_now += 1; + } + } + let p = p?; p.queue_state.store(MAKING, Ordering::Relaxed); Some(p) } @@ -295,7 +341,7 @@ fn start(p: &Arc, priority: u8) { fn next() -> 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(slow_limit()) { return p; } queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner()); @@ -339,7 +385,13 @@ fn workers() -> bool { let _ = SetThreadPriority(GetCurrentThread(), priority); } loop { - next().make(); + let p = next(); + p.make(); + if p.was_slow.load(Ordering::Relaxed) { + let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); + queue.slow_now -= 1; + AVAILABLE.notify_one(); + } if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 { drained(); } else { @@ -429,10 +481,33 @@ 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(1).unwrap(), &requested)); + assert!(Arc::ptr_eq(&queue.pop(1).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(1).unwrap(), &earlier)); + assert!(queue.pop(1).is_none()); + } + + #[test] + fn pipelines_known_to_take_long_leave_workers_for_the_others() { + let new = || Arc::new(Pending::new(Vec::new(), None)); + let (long, longer, asked, quick) = (new(), new(), new(), new()); + let mut queue = Queue::new(); + for p in [&long, &longer, &asked] { + assert_eq!(queue.push_as(p, EARLY, true), Some(true)); + } + assert_eq!(queue.push_as(&quick, EARLY, false), Some(true)); + // The quick one first, then one long one at a time; one a draw asks + // for waits for nobody. + assert!(Arc::ptr_eq(&queue.pop(1).unwrap(), &quick)); + assert!(Arc::ptr_eq(&queue.pop(1).unwrap(), &long)); + assert!(queue.pop(1).is_none()); + assert_eq!(queue.push_as(&asked, REQUESTED, true), Some(false)); + assert!(Arc::ptr_eq(&queue.pop(1).unwrap(), &asked)); + assert!(!asked.was_slow.load(Ordering::Relaxed)); + assert!(queue.pop(1).is_none()); + queue.slow_now -= 1; + assert!(Arc::ptr_eq(&queue.pop(1).unwrap(), &longer)); + assert!(queue.pop(1).is_none()); } } From 689df313f5f09203ffc4bb7ec8f191835ae949fc Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:24:11 -0600 Subject: [PATCH 405/445] Views mapped beside guarded ones: all views of the page are opened together, under the lock A page shown at several addresses, and one more view of it being mapped: the views that were to be opened were looked for before the lock was taken, so one made clean in between stayed clean with a writable view beside it (a write of the title's through that one was not told until its block's next told write), and they were opened one range after another, so for some microseconds one was writable while others were still known by their bits (told one asking late). Both are older than the faults' work; VICTORY_OPEN_ONE_VIEW made the first common. Also: what is known by its bits is not where bytes were just put in beside the guard (VICTORY_COPY_BESIDE, VICTORY_STORE_BESIDE). The test of writes through other views failed in 6 of 200 runs, then 4 of 380 with the first mended, 0 of 603 (four tests each) with both. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/watch.rs | 48 ++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index a120b25..81d4213 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -1177,7 +1177,11 @@ pub(crate) fn guarded(start: usize, end: usize) -> bool { /// Whether nothing of `[start, end)` can have been written since an asking /// noted it in the journal ([`PUBLISHED`]). fn published(start: usize, end: usize) -> bool { - light() && PUBLISHED.all(start / BLOCK, end.div_ceil(BLOCK)) + let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); + // (In this order: who puts something in beside a guard sets the one bit, + // then clears the other, which an asking that is publishing the block may + // just be setting.) + light() && PUBLISHED.all(first, last) && !BESIDE.any(first, last) } /// Since the last frame line: what asking about title memory was. Kernel @@ -1544,7 +1548,7 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64, /// Whether every write of the title's to 64 KiB block `block` so far is in /// the journal ([`PUBLISHED`]). pub(crate) fn block_published(block: usize) -> bool { - light() && PUBLISHED.all(block, block + 1) + published(block * BLOCK, (block + 1) * BLOCK) } /// Whether shaders' writes went into a page of `[at, at + len)` in the last @@ -2126,20 +2130,22 @@ pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) { if !view_guard() { return; } - let mut ranges = crate::inplace::views_of_section(section, offset, len); + let ranges = crate::inplace::views_of_section(section, offset, len); // (A block is noted in `PROTECTED` ahead of the look at its page's views // that did not find this one yet.) - ranges.retain(|&(at, n)| PROTECTED.any(at / BLOCK, (at + n).div_ceil(BLOCK))); - if ranges.is_empty() { + if !ranges.iter().any(|&(at, n)| PROTECTED.any(at / BLOCK, (at + n).div_ceil(BLOCK))) { return; } + // All of them, once one is guarded: another may have been made clean + // since that look, relying on those that are opened here. And all + // together: none may be writable while another is clean (who asks about + // that one by its bits takes no lock). let mut g = guards(); - for &(at, n) in &ranges { - 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); - } + let blocks: Vec = + ranges.iter().flat_map(|&(at, n)| g.protected.range(at / BLOCK..(at + n).div_ceil(BLOCK)).collect::>()).collect(); + #[cfg(feature = "diagnostics")] + ALIASES[2].fetch_add(blocks.len() as u64, std::sync::atomic::Ordering::Relaxed); + unguard(&mut g, &blocks); } /// The runtime is about to unmap a view of which it maps a part again at @@ -2153,7 +2159,12 @@ 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.) + // (The view itself too: the part that stays is read-only until then. And + // all of them told as written before the first is writable.) + for &other in &others { + g.clean.remove(other / BLOCK); + PUBLISHED.clear(other / BLOCK); + } open(&mut g, at, at.saturating_add(len)); for other in others { open(&mut g, other, other + BLOCK); @@ -3991,6 +4002,8 @@ mod many_askers_tests { let to = page + 1 + next((PAGES - page).min(3)); // Written through one view, asked about at another. let (through, asked) = (all[next(VIEWS)], next(VIEWS)); + #[allow(unused_assignments)] + let mut how = 0; let (at, last) = (all[asked], &mut last[asked]); if next(4) != 0 { // As in the test above, or after a word of ours, @@ -4014,6 +4027,7 @@ mod many_askers_tests { continue; } let reading = (next(3) == 0).then(super::title_memory_reading); + how = usize::from(reading.is_some()); let beside = reading.as_ref().and_then(|_| crate::inplace::beside(word, 8)); if let Some(to) = beside { unsafe { (to as *mut u64).write_volatile(2) }; @@ -4021,8 +4035,10 @@ mod many_askers_tests { past.fetch_add(1, std::sync::atomic::Ordering::Relaxed); assert_eq!(unsafe { (word as *const u64).read_volatile() }, 2, "put elsewhere"); } else { + how += 2; if next(4) == 0 { super::writing(word, 8); + how += 4; } unsafe { (word as *mut u64).write_volatile(1) }; } @@ -4040,7 +4056,13 @@ mod many_askers_tests { } 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}: {number} is not after {}", last[page]); + assert!( + number > last[page], + "{VIEWS} views, page {page}, through {:x} ({how}), asked at {:x}: {number} is not after {}", + through / PAGE + page, + at / PAGE + page, + last[page] + ); for l in &mut last[from..to] { *l = now; } From 30f7859baf89fb5b225aea8bada3272d6de84afb Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:29:08 -0600 Subject: [PATCH 406/445] Copies in the card's memory: the changed runs sorted once and stably, piece runs joined while built; steps on the card: slots made on several threads Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 26 +++++++++--- crates/victory-gpu/src/host/card_steps.rs | 52 ++++++++++++++--------- crates/victory-gpu/src/shadow.rs | 17 +++++--- 3 files changed, 64 insertions(+), 31 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b65ba97..c87da73 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4140,7 +4140,9 @@ impl Host { } None => 0, }; + let gathering = crate::timeline::span("copies in the card's memory: what changed"); let mut dirty = crate::shadow::card_dirty(sent_as); + gathering.end(); if declared.is_empty() && dirty.is_empty() && looked.is_empty() { return None; } @@ -4164,11 +4166,14 @@ impl Host { let mut used: Vec<(bool, Prelude)> = Vec::new(); let mut looks = None; // The bytes as they are now, whatever later submissions put there. + let taking = crate::timeline::span("copies in the card's memory: taken"); let own = if send::own() { send::take(self, &dirty) } else { None }; + taking.end(); if !dirty.is_empty() { let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else { fail(format_args!("no host list to bring host copies in the card's memory up to date")); }; + let _recording = crate::timeline::span("copies in the card's memory: the list"); let (allocator, list) = &sync; // SAFETY: the list's last run finished (it ran ahead of a // submission that was waited for, and came back after that); @@ -4191,12 +4196,13 @@ impl Host { let Some((staging, before, _)) = shadow.card_sides() else { continue; }; - for &(a, b) in ranges { - if own.is_none() { + if own.is_none() { + for &(a, b) in ranges { list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64); } - crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed); } + let bytes: u64 = ranges.iter().map(|&(a, b)| (b - a) as u64).sum(); + crate::shadow::CARD_STATS[0].fetch_add(bytes, 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()); @@ -4226,13 +4232,23 @@ impl Host { // pieces and flags those whose hash is another. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); + let joins = rehash_runs() || own.is_some(); let runs: Vec = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) { vec![shadow.card_run(0, usize::MAX)] } else { - ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect() + // (In order: the next of the same piece, of the + // tens of thousands there are, says nothing.) + let mut runs: Vec = Vec::new(); + for run in ranges.iter().map(|&(a, b)| shadow.card_run(a, b)) { + match runs.last_mut() { + Some(last) if joins && (last.first, last.pieces) == (run.first, run.pieces) => last.to = last.to.max(run.to), + _ => runs.push(run), + } + } + runs }; // The same pieces in fewer passes (`rehash_runs`). - let runs = if rehash_runs() || own.is_some() { crate::shadow::joined_piece_runs(runs) } else { runs }; + let runs = if joins { crate::shadow::joined_piece_runs(runs) } else { runs }; CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed); CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::(), Ordering::Relaxed); for run in runs { diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index b6b99e5..239f576 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -674,11 +674,13 @@ impl Host { } fn take_steps(&self, written: &[(usize, usize)], runs: &[&HostList]) -> Result, &'static str> { + let mut spent = crate::timeline::span("steps on the card: chosen"); let (does, steps) = does_of(written, runs); let chosen = plan(&does, stage(), placed_order(), &mut None)?; if chosen.is_empty() { return Ok(None); } + spent.next("steps on the card: what holds their bytes"); let mut writers = { let line = line(); let mut all = writers(&line.line); @@ -765,6 +767,7 @@ impl Host { to, }); } + spent.next("steps on the card: the list"); let Some(own) = self.own_list() else { return Err("no host list or buffer for it"); }; @@ -817,24 +820,28 @@ impl Host { own.list.close(); // SAFETY: a live buffer. let gpu = unsafe { own.between.GetGPUVirtualAddress() }; - for op in &ops { - DONE[2].fetch_add(op.len as u64, Ordering::Relaxed); - match &op.to { - To::Slot(heap, index) => { - DONE[0].fetch_add(1, Ordering::Relaxed); + spent.next("steps on the card: the slots"); + // (11,000 slots a frame in a street, two descriptors each: on + // several threads, a slot always on the same one, in the steps' + // order.) + let parts = if ops.len() < 256 { 1 } else { 8 }; + crate::land::each_under(parts, &|part| { + for op in &ops { + if let To::Slot(heap, index) = &op.to + && *index as usize / 4 % parts == part + { // (A heap that is gone: nothing can read the slot.) crate::descriptor::constant_slot(*heap, *index, &own.between, gpu + op.at, op.len as u32); } - To::Buffer(_) => { - DONE[0].fetch_add(1, Ordering::Relaxed); - } - To::Copy(..) => { - DONE[1].fetch_add(1, Ordering::Relaxed); - } } - #[cfg(feature = "diagnostics")] - noted(op); - } + }); + let copies = ops.iter().filter(|op| matches!(op.to, To::Copy(..))).count(); + DONE[0].fetch_add((ops.len() - copies) as u64, Ordering::Relaxed); + DONE[1].fetch_add(copies as u64, Ordering::Relaxed); + DONE[2].fetch_add(ops.iter().map(|op| op.len as u64).sum(), Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + noted(&ops); + spent.end(); Ok(Some(Taken { own, steps: chosen.iter().map(|&(i, _)| steps[i]).collect(), @@ -865,14 +872,17 @@ type Noted = std::collections::HashMap<(usize, (u64, u64), (u64, u64)), (u64, us static NOTED: Mutex> = Mutex::new(None); #[cfg(feature = "diagnostics")] -fn noted(op: &Op) { - let (to, dst) = match &op.to { - To::Copy(to, dst) => (to.span(), *dst), - To::Slot(..) | To::Buffer(_) => ((0, 0), 0), - }; +fn noted(ops: &[Op]) { let mut noted = NOTED.lock().unwrap_or_else(|e| e.into_inner()); - let e = noted.get_or_insert_with(Default::default).entry((op.len, op.from.0.span(), to)).or_default(); - *e = (e.0 + 1, op.from.1, dst); + let noted = noted.get_or_insert_with(Default::default); + for op in ops { + let (to, dst) = match &op.to { + To::Copy(to, dst) => (to.span(), *dst), + To::Slot(..) | To::Buffer(_) => ((0, 0), 0), + }; + let e = noted.entry((op.len, op.from.0.span(), to)).or_default(); + *e = (e.0 + 1, op.from.1, dst); + } } /// For the frame-rate line. diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index f69db8e..9851d79 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -549,11 +549,16 @@ fn window_room_for(size: u64) -> Option { struct SentRuns(Vec<(u64, Vec<(usize, usize)>)>); impl SentRuns { + #[cfg(test)] fn note(&mut self, number: u64, ranges: Vec<(usize, usize)>) { + self.note_joined(number, joined(ranges)); + } + + /// `ranges` are in order and joined. + fn note_joined(&mut self, number: u64, ranges: Vec<(usize, usize)>) { if ranges.is_empty() { return; } - let ranges = joined(ranges); match self.0.iter_mut().find(|s| s.0 == number) { Some((_, all)) => *all = joined([std::mem::take(all), ranges].concat()), None => self.0.push((number, ranges)), @@ -608,17 +613,17 @@ pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc, Vec<(usize, usize)>) .filter(|c| c.touched.swap(false, Ordering::AcqRel)) .map(|c| { let mut dirty = c.dirty.lock().unwrap_or_else(|e| e.into_inner()); - let ranges = std::mem::take(&mut *dirty); + let ranges = joined(std::mem::take(&mut *dirty)); if relay() { let mut sent = c.sent.lock().unwrap_or_else(|e| e.into_inner()); sent.forget(fetched); - sent.note(sent_as, ranges.clone()); + sent.note_joined(sent_as, ranges.clone()); } ranges }) .unwrap_or_default(); if !ranges.is_empty() { - out.push((shadow, joined(ranges))); + out.push((shadow, ranges)); } true }); @@ -724,7 +729,9 @@ pub(crate) fn carded_copies() -> Vec> { /// Ranges in order, those that overlap or touch as one. fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> { - ranges.sort_unstable(); + // (The sort that finds what is in order already: they come as a few + // stretches of tens of thousands in order, put behind one another.) + ranges.sort(); let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); for (from, to) in ranges { match out.last_mut() { From 5491ac780139aadbd3a1ee607d3eb0897e234acf Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:31:33 -0600 Subject: [PATCH 407/445] The pages shaders' writes were put into are noted without a lock Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/watch.rs | 102 +++++++++++++++++++++++++++----- 1 file changed, 86 insertions(+), 16 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 81d4213..4077178 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -1433,10 +1433,69 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> { } /// The 4 KiB pages of title memory that what shaders wrote was put into, -/// and the frame it last was. -static LANDED: Mutex>>> = Mutex::new(None); +/// and the frame it last was: in pieces made when first needed and never let +/// go. Some 20,000 pages a frame are noted by the relay and the landing +/// threads: in a map behind one lock that was 309 waits for it and 280 looks +/// at its table in the 40 s of a profile, as many as all else of the landings' +/// notes (run faults-5). +struct Landed([std::sync::atomic::AtomicPtr; Landed::PIECES]); -/// A page's number, spread: some 20,000 a frame are noted in [`LANDED`]. +/// Of 256 MiB: the frame (its low 31 bits and one), 0 for never. +type LandedPiece = [std::sync::atomic::AtomicU32; Landed::PAGES]; + +impl Landed { + const PAGES: usize = 1 << 16; + /// 128 TiB, what a process has. + const PIECES: usize = 1 << 19; + + fn stamp(frame: u64) -> u32 { + (frame as u32 & 0x7fff_ffff) + 1 + } + + fn note(&self, page: usize, frame: u64) { + use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed}; + let Some(place) = self.0.get(page / Landed::PAGES) else { + return; + }; + let mut piece = place.load(Acquire); + if piece.is_null() { + let made: Box = Box::new([const { std::sync::atomic::AtomicU32::new(0) }; Landed::PAGES]); + let made = Box::into_raw(made); + piece = match place.compare_exchange(std::ptr::null_mut(), made, AcqRel, Acquire) { + Ok(_) => made, + Err(there) => { + // SAFETY: made just now, and another thread's is there. + drop(unsafe { Box::from_raw(made) }); + there + } + }; + } + // SAFETY: a piece, which is never freed. + let at = unsafe { &(&*piece)[page % Landed::PAGES] }; + let stamp = Landed::stamp(frame); + // (Most are noted several times a frame: no write then.) + if at.load(Relaxed) != stamp { + at.store(stamp, Relaxed); + } + } + + /// Whether `page` was noted in a frame from `since` on, up to `now`. + fn since(&self, page: usize, since: u64, now: u64) -> bool { + let Some(place) = self.0.get(page / Landed::PAGES) else { + return false; + }; + // SAFETY: null, or a piece, which is never freed. + let Some(piece) = (unsafe { place.load(std::sync::atomic::Ordering::Acquire).as_ref() }) else { + return false; + }; + let stamp = piece[page % Landed::PAGES].load(std::sync::atomic::Ordering::Relaxed); + stamp != 0 && u64::from(Landed::stamp(now).wrapping_sub(stamp) & 0x7fff_ffff) <= now.saturating_sub(since) + } +} + +static LANDED: Landed = Landed([const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; Landed::PIECES]); + +/// A page's number, spread. #[derive(Default)] struct PageHash(u64); @@ -1461,15 +1520,13 @@ impl std::hash::Hasher for PageHash { pub(crate) fn landing(at: usize, len: usize) { { let frame = crate::frame::current(); - let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); - let landed = landed.get_or_insert_with(Default::default); let (first, last) = (at / KERNEL_PAGE, (at + len.max(1) - 1) / KERNEL_PAGE); - landed.extend((first..=last).map(|page| (page, frame))); + (first..=last).for_each(|page| LANDED.note(page, frame)); for (block, others) in elsewhere(at, len) { let block = block / KERNEL_PAGE; let here = first.max(block)..=last.min(block + BLOCK / KERNEL_PAGE - 1); for other in others { - landed.extend(here.clone().map(|page| (page - block + other / KERNEL_PAGE, frame))); + here.clone().for_each(|page| LANDED.note(page - block + other / KERNEL_PAGE, frame)); } } } @@ -1502,15 +1559,13 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64, let elsewhere: Vec<(usize, Vec)> = spans.iter().flat_map(|&(at, len)| elsewhere(at, len)).collect(); { let frame = crate::frame::current(); - let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); - let landed = landed.get_or_insert_with(Default::default); for &page in pages { - landed.insert(page, frame); + LANDED.note(page, frame); } for (block, others) in &elsewhere { let first = block / KERNEL_PAGE; for &page in pages.iter().filter(|&&page| (first..first + BLOCK / KERNEL_PAGE).contains(&page)) { - landed.extend(others.iter().map(|other| (page - first + other / KERNEL_PAGE, frame))); + others.iter().for_each(|other| LANDED.note(page - first + other / KERNEL_PAGE, frame)); } } } @@ -1554,11 +1609,8 @@ pub(crate) fn block_published(block: usize) -> bool { /// Whether shaders' writes went into a page of `[at, at + len)` in the last /// `frames` frames. pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool { - let since = crate::frame::current().saturating_sub(frames); - let landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); - landed.as_ref().is_some_and(|landed| { - (at / 4096..=(at + len.max(1) - 1) / 4096).any(|page| landed.get(&page).is_some_and(|&f| f >= since)) - }) + let now = crate::frame::current(); + (at / 4096..=(at + len.max(1) - 1) / 4096).any(|page| LANDED.since(page, now.saturating_sub(frames), now)) } /// Whether every block of `[at, at + len)` is view memory written since a @@ -3659,6 +3711,24 @@ mod tests { unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; } + /// The frames pages were last landed in. + #[test] + fn landed_pages_are_known_by_their_frame() { + static LANDED: Landed = Landed([const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; Landed::PIECES]); + let landed = &LANDED; + for page in [0, 5, Landed::PAGES - 1, Landed::PAGES, 7 * Landed::PAGES + 3] { + assert!(!landed.since(page, 0, 100)); + landed.note(page, 100); + assert!(landed.since(page, 100, 100) && landed.since(page, 0, 100) && landed.since(page, 90, 110)); + assert!(!landed.since(page, 101, 110)); + landed.note(page, 0x1_0000_0005); + assert!(landed.since(page, 0x1_0000_0000, 0x1_0000_0007) && !landed.since(page, 0x1_0000_0006, 0x1_0000_0007)); + assert!(!landed.since(page + 1, 0, 0x1_0000_0007)); + } + landed.note(usize::MAX / 4096, 1); + assert!(!landed.since(usize::MAX / 4096, 0, 1)); + } + /// The set of blocks against another of the same. #[test] fn blocks_are_a_set() { From 23925a4aa29a6bcb13b29959ec3eddec481f5e00 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:31:36 -0600 Subject: [PATCH 408/445] Textures shaders write that the title reads on the CPU are copied back into title memory (from fxceless f5c03f3b, pull request 999: Geckomacabre 895c0b8f, 04df4350); on by default Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 2 + crates/victory-gpu/src/host.rs | 73 +++++++- crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/resource.rs | 37 +++- crates/victory-gpu/src/texback.rs | 273 +++++++++++++++++++++++++++++ crates/victory-gpu/src/watch.rs | 2 + 6 files changed, 383 insertions(+), 6 deletions(-) create mode 100644 crates/victory-gpu/src/texback.rs diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 0dad207..88729fc 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -4171,6 +4171,8 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) { (View::Unordered(resource, _, _), ResourceType::Uav) => { #[cfg(feature = "diagnostics")] crate::capture::note_target(*resource as This); + // Some compute-written textures are also read by the title CPU. + list.texture_written(*resource as This); // Unordered access to a depth texture is its colour twin's. if !list.twin_use(*resource as This, true, true) { crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index c87da73..d58ae41 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2194,6 +2194,11 @@ struct Deferred { /// memory they go to, the bytes of a row, the rows, the title's row /// pitch. backs: Vec<(ID3D12Resource, usize, [usize; 3])>, + /// Title textures of the kinds copied back ([`crate::texback`]) that + /// the list's shaders write, copied when the list closes. + back_wanted: Vec, + /// Those copies, whose texels go to title memory once the list has run. + texture_backs: Vec, /// Whether the indirect-work budget is zeroed for this recording (a /// step on the CPU, or in the list for the card's copy). budget_zeroed: bool, @@ -2532,6 +2537,8 @@ struct Sent { back: Vec, /// What was taken off it to be done on the card. own: Option, + /// Title-memory ranges written when its shader textures are copied back. + texture_back_ranges: Vec<(usize, usize)>, /// Its bottom-of-pipe writes. writes: Vec<(usize, crate::queue::Written, usize)>, } @@ -2549,6 +2556,7 @@ struct Flight { back: Vec, /// The list of ours that ran ahead of them ([`card_steps`]). own: Option, + texture_back_ranges: Vec<(usize, usize)>, } /// One thing in the line of what waits for the card, in order. @@ -2562,8 +2570,8 @@ enum Late { struct Line { line: Vec, - /// The title memory the flights' shaders may write (address, end), in - /// order and joined. + /// The title memory the flights' shaders and texture readbacks may write + /// (address, end), in order and joined. written: Vec<(usize, usize)>, /// Host lists in the flights. lists: usize, @@ -3725,6 +3733,11 @@ pub(crate) fn walls_trace() -> bool { /// without it, so the title read a buffer nobody wrote, as before read-backs /// were made (the exposure metering's two small float targets, every frame). fn read_backs(list: &HostList) { + // Textures shaders wrote that the title reads on the CPU + // ([`crate::texback`]). + for back in &list.deferred().texture_backs { + crate::texback::land(back); + } for (buffer, at, [row, rows, pitch]) in &list.deferred().backs { let mut data = std::ptr::null_mut(); // SAFETY: a read-back buffer of ours, written by the list that has @@ -4838,6 +4851,7 @@ impl Host { if let Late::Run(flight) = item { *lists += flight.order.len().max(1); ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied())); + ranges.extend(flight.texture_back_ranges.iter().copied()); } } join_ranges(written, ranges); @@ -5045,7 +5059,13 @@ impl Host { let most = { let mut line = line(); let Line { line: items, written, lists: flying, target, .. } = &mut *line; - join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied())); + join_ranges( + written, + sent.back + .iter() + .flat_map(|(_, ranges)| ranges.iter().copied()) + .chain(sent.texture_back_ranges.iter().copied()), + ); *flying += order.len(); *target = *submitted; items.push(Late::Run(Flight { @@ -5056,6 +5076,7 @@ impl Host { card: sent.card, back: sent.back, own: sent.own, + texture_back_ranges: sent.texture_back_ranges, })); items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); *flying >= late_most() @@ -5093,7 +5114,13 @@ impl Host { { let mut line = line(); let Line { line: items, written, lists: flying, target, .. } = &mut *line; - join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied())); + join_ranges( + written, + sent.back + .iter() + .flat_map(|(_, ranges)| ranges.iter().copied()) + .chain(sent.texture_back_ranges.iter().copied()), + ); *flying += 1; *target = *submitted; items.push(Late::Run(Flight { @@ -5104,6 +5131,7 @@ impl Host { card: sent.card, back: sent.back, own: sent.own, + texture_back_ranges: sent.texture_back_ranges, })); items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); } @@ -5571,6 +5599,10 @@ impl Host { #[cfg(feature = "diagnostics")] split.part(5); let back = crate::picked::with(declared, &picked.written); + let mut texture_back_ranges = Vec::new(); + for list in runs { + texture_back_ranges.extend(list.deferred().texture_backs.iter().map(crate::texback::Back::range)); + } 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); @@ -5581,6 +5613,7 @@ impl Host { card, back, own, + texture_back_ranges, writes, }; working(was_working); @@ -6035,6 +6068,7 @@ impl HostList { pub(crate) fn close(&self) { let _closing = crate::timeline::span("closing a host list"); self.twins_to_depth(); + self.textures_back(); let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone(); if let Some((scratch, _)) = scratch { self.indirect_common(&scratch); @@ -6351,6 +6385,34 @@ impl HostList { } } + /// A draw or dispatch being prepared writes title texture `resource` + /// through unordered access: if it is of a kind copied back + /// ([`crate::texback`]), the list copies it when it closes. + pub(crate) fn texture_written(&self, resource: crate::object::This) { + if !crate::texback::wanted(resource) { + return; + } + let mut deferred = self.deferred(); + if !deferred.back_wanted.iter().any(|target| target.owner() == resource as usize) + && let Some(target) = crate::texback::Target::new(resource) + { + deferred.back_wanted.push(target); + } + } + + /// Before the list closes: the textures its shaders wrote that are copied + /// back go into read-back buffers ([`crate::texback::record`]). + fn textures_back(&self) { + const COPY_SOURCE: u32 = 0x800; + let wanted = std::mem::take(&mut self.deferred().back_wanted); + for target in wanted { + self.settle(&target.copy, COPY_SOURCE); + if let Some(back) = crate::texback::record(&self.list, target) { + self.deferred().texture_backs.push(back); + } + } + } + /// The draw or dispatch just prepared is recorded: the twins it writes /// now hold what their depth textures lack. pub(crate) fn twins_written(&self) { @@ -6518,7 +6580,8 @@ impl HostList { && deferred.kept.is_empty() && deferred.textures.is_empty() && deferred.writes.is_empty() - && deferred.backs.is_empty()) + && deferred.backs.is_empty() + && deferred.texture_backs.is_empty()) { return false; } diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 85ba22b..908dbec 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -87,6 +87,8 @@ pub mod titlewrite; mod upload; #[cfg(windows)] mod watch; +#[cfg(windows)] +mod texback; #[cfg(windows)] pub use host::on_failure; diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 416f3a4..437e3ca 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -2690,6 +2690,7 @@ fn hand_out_resource( if desc.dimension != BUFFER { let at = std::ptr::from_ref::(&resource) as usize; textures().insert(at); + crate::texback::replaced(resource.data() as usize); if !fills(&desc) { TARGETS_AT .lock() @@ -2714,7 +2715,9 @@ impl Drop for Resource { // Out of the table of textures first: the sweep looks at the ones // in it, under its lock. if self.desc.dimension != BUFFER { - textures().remove(&(std::ptr::from_ref::(self) as usize)); + let address = std::ptr::from_ref::(self) as usize; + crate::texback::released(address); + textures().remove(&address); if !fills(&self.desc) { let mut targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner()); let at = self.data() as u64; @@ -2946,6 +2949,38 @@ pub(crate) fn placed_filler_twins() -> u64 { PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed) } +/// Width, height and format of texture `this` (`None` for a buffer), for +/// `crate::texback`'s kinds. +#[cfg(windows)] +pub(crate) fn texture_kind(this: This) -> Option<(u64, u32, u32)> { + if this.is_null() { + return None; + } + let r = resource(this); + const TEXTURE_2D: u32 = 3; + (r.desc.dimension == TEXTURE_2D && r.desc.sample_count <= 1) + .then_some((r.desc.width, r.desc.height, r.desc.format)) +} + +/// Texture `this`'s console layout (one plane), where it lies in title +/// memory and the bytes that layout takes, for `crate::texback`; `None` for +/// a buffer or a texture with planes. +#[cfg(windows)] +pub(crate) fn title_texture(this: This) -> Option<(victory_formats::texture::Layout, usize, usize)> { + if this.is_null() { + return None; + } + let r = resource(this); + if r.desc.dimension == BUFFER { + return None; + } + let t = texture_layout(&r.desc)?; + let [plane] = &t.planes[..] else { + return None; + }; + Some((plane.layout.clone(), r.data() as usize, t.size as usize)) +} + /// The bytes of title memory a texture with the resource description /// `desc` (as words) takes where the title placed it; `None` for a buffer /// and for a description without a size. diff --git a/crates/victory-gpu/src/texback.rs b/crates/victory-gpu/src/texback.rs new file mode 100644 index 0000000..cf7b0e3 --- /dev/null +++ b/crates/victory-gpu/src/texback.rs @@ -0,0 +1,273 @@ +//! Textures shaders write that the title's own code then reads on the CPU. +//! On the console the CPU and the GPU share memory, so what a compute pass +//! stores into a texture is in title memory for the CPU to read. Here it stays +//! in the texture's host copy. The title's ocean is one: its wave passes write +//! a 256x256 height map (R32_FLOAT) and a displacement map (R32G32_FLOAT), and +//! its CPU code samples both, which is what boats float on; it read memory +//! nothing had written (run rw1, `VICTORY_READ_WATCH=1`: about 30 places in +//! the title read those two kinds), and boats sank. +//! +//! For textures of the kinds in `VICTORY_TEXTURE_BACK` (comma-separated +//! `xf`; unset or `1`: the four water formats found by +//! the upstream trace; `0`: none), a list in which shaders write one copies it +//! into a read-back buffer of ours when it closes, and once the list has run +//! the texels are tiled into the texture's title memory in the console's +//! layout, as the console's GPU would have left them. +//! +//! shortcut: by kind, not by texture: textures of those kinds the title never +//! reads are copied back too (about a megabyte per such list). The copy shows +//! what the list's last write left; a title read in between sees the frame +//! before, as it would before the console's GPU has run. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, Weak}; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::object::This; + +/// The kinds copied back: (width, height, format). +fn kinds() -> &'static [(u64, u32, u32)] { + static KINDS: OnceLock> = OnceLock::new(); + KINDS.get_or_init(|| { + const DEFAULT: &str = "256x256f41,256x256f16,64x64f16,128x128f36"; + let list = match std::env::var("VICTORY_TEXTURE_BACK").as_deref() { + Ok("1") | Err(_) => DEFAULT.to_owned(), + Ok(spec) => spec.to_owned(), + }; + let kinds: Vec<(u64, u32, u32)> = list + .split(',') + .filter_map(|k| { + let (size, format) = k.trim().split_once('f')?; + let (w, h) = size.split_once('x')?; + Some((w.parse().ok()?, h.parse().ok()?, format.parse().ok()?)) + }) + .collect(); + if !kinds.is_empty() { + tracing::info!(?kinds, "textures of these kinds that shaders write are copied back into title memory (VICTORY_TEXTURE_BACK)"); + } + kinds + }) +} + +/// Whether title texture `resource` is of a kind copied back. +pub(crate) fn wanted(resource: This) -> bool { + let kinds = kinds(); + !kinds.is_empty() + && crate::resource::texture_kind(resource).is_some_and(|k| kinds.contains(&k)) +} + +/// An outstanding write to a specific allocation. Mapping and resource +/// changes invalidate only the writes that could touch the replaced memory. +struct Ticket { + owner: usize, + at: usize, + end: usize, + valid: AtomicBool, +} + +static TICKETS: Mutex>> = Mutex::new(Vec::new()); +static TRACKING: AtomicBool = AtomicBool::new(false); + +fn track(owner: usize, at: usize, end: usize) -> Arc { + let ticket = Arc::new(Ticket { owner, at, end, valid: AtomicBool::new(true) }); + let mut tickets = TICKETS.lock().unwrap_or_else(|e| e.into_inner()); + tickets.retain(|weak| weak.strong_count() != 0); + tickets.push(Arc::downgrade(&ticket)); + TRACKING.store(true, Ordering::Relaxed); + ticket +} + +fn invalidate(matches: impl Fn(&Ticket) -> bool) { + if !TRACKING.load(Ordering::Relaxed) { + return; + } + TICKETS.lock().unwrap_or_else(|e| e.into_inner()).retain(|weak| { + let Some(ticket) = weak.upgrade() else { return false }; + if matches(&ticket) { + ticket.valid.store(false, Ordering::Release); + } + true + }); +} + +pub(crate) fn released(owner: usize) { + invalidate(|ticket| ticket.owner == owner); +} + +pub(crate) fn replaced(at: usize) { + invalidate(|ticket| ticket.at == at); +} + +pub(crate) fn remapped(at: usize, len: usize) { + let end = at.saturating_add(len); + invalidate(|ticket| at < ticket.end && ticket.at < end); +} + +pub(crate) struct Target { + pub(crate) copy: Arc, + layout: victory_formats::texture::Layout, + ticket: Arc, +} + +impl Target { + pub(crate) fn new(resource: This) -> Option { + // Keep the host copy independently of the title's resource lifetime. + let copy = crate::resource::host_copy(resource)?; + let _mapping = crate::watch::title_memory_reading(); + let (layout, at, size) = crate::resource::title_texture(resource)?; + let end = at.checked_add(size).filter(|&end| at != 0 && end > at)?; + let ticket = track(resource as usize, at, end); + Some(Self { copy, layout, ticket }) + } + + pub(crate) fn owner(&self) -> usize { self.ticket.owner } +} + +/// The readback resources and the allocation the pixels belong to. +pub(crate) struct Back { + buffer: ID3D12Resource, + footprints: Vec, + rows: Vec, + mips: u32, + layout: victory_formats::texture::Layout, + ticket: Arc, +} + +impl Back { + pub(crate) fn range(&self) -> (usize, usize) { + (self.ticket.at, self.ticket.end) + } +} + +/// Records a host copy from a texture already in COPY_SOURCE. +pub(crate) fn record(list: &ID3D12GraphicsCommandList, target: Target) -> Option { + if !target.ticket.valid.load(Ordering::Acquire) { + return None; + } + let host = crate::host::host()?; + let texture = &target.copy.texture; + // SAFETY: a live texture kept through the command list's state tracking. + let desc = unsafe { texture.GetDesc() }; + let mips = u32::from(desc.MipLevels.max(1)); + let subresources = mips * u32::from(desc.DepthOrArraySize.max(1)); + let n = subresources as usize; + let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n]; + let mut rows = vec![0u32; n]; + let mut total = 0u64; + // SAFETY: out arrays of `n` entries. + unsafe { + host.device.GetCopyableFootprints( + &desc, + 0, + subresources, + 0, + Some(footprints.as_mut_ptr()), + Some(rows.as_mut_ptr()), + None, + Some(&mut total), + ) + }; + // The last footprint's advertised extent can omit row-end padding. + // The tiler reads a pitched slice, so the mapped buffer must include it. + for (footprint, &rows) in footprints.iter().zip(&rows) { + let format = footprint.Footprint; + let pitched = u64::from(format.RowPitch) + .checked_mul(u64::from(rows))? + .checked_mul(u64::from(format.Depth))?; + total = total.max(footprint.Offset.checked_add(pitched)?); + } + let buffer = host.read_back_buffer(total)?; + for (i, footprint) in footprints.iter().enumerate() { + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(&buffer) }, + 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: i as u32 }, + }; + // SAFETY: an open list; the texture is in the copy-source state. + unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + Some(Back { buffer, footprints, rows, mips, layout: target.layout, ticket: target.ticket }) +} + +/// Once the list has run, tile its texels back into the same title allocation. +pub(crate) fn land(back: &Back) { + static COPIED: AtomicU64 = AtomicU64::new(0); + static STALE: AtomicU64 = AtomicU64::new(0); + let _mapping = crate::watch::title_memory_reading(); + let _ticket_guard = TICKETS.lock().unwrap_or_else(|e| e.into_inner()); + if !back.ticket.valid.load(Ordering::Acquire) { + let skipped = STALE.fetch_add(1, Ordering::Relaxed) + 1; + if skipped.is_power_of_two() { + tracing::info!(skipped, "skipping texture readbacks whose title allocation changed"); + } + return; + } + let (at, end) = back.range(); + let size = end - at; + let mut tiled = vec![0u8; size]; + // Keep title bytes the subresources do not cover. + if !crate::host::read_into(at as *const u8, &mut tiled) { + return; + } + let mut data = std::ptr::null_mut(); + // SAFETY: our read-back buffer, written by the list that has run. + unsafe { + if back.buffer.Map(0, None, Some(&mut data)).is_err() || data.is_null() { + return; + } + } + for (i, (footprint, &rows)) in back.footprints.iter().zip(&back.rows).enumerate() { + let (mip, slice) = (i as u32 % back.mips, i as u32 / back.mips); + let f = footprint.Footprint; + let pitch = f.RowPitch as usize; + let len = pitch * rows as usize * f.Depth as usize; + // SAFETY: the subresource's part of the mapped buffer. + let linear = unsafe { std::slice::from_raw_parts(data.cast::().add(footprint.Offset as usize), len) }; + if let Err(e) = back.layout.tile(&mut tiled, mip, slice, linear, pitch, pitch * rows as usize) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(?e, mip, slice, "a texture copied back could not be tiled")); + // SAFETY: mapped above. + unsafe { back.buffer.Unmap(0, None) }; + return; + } + } + // SAFETY: mapped above. + unsafe { back.buffer.Unmap(0, None) }; + crate::host::copy_mapped(at as *mut u8, tiled.as_ptr(), size, true); + let copied = COPIED.fetch_add(1, Ordering::Relaxed) + 1; + if copied == 1 || copied.is_multiple_of(128) { + tracing::info!(copied, bytes = size, "texture readback landed"); + } +} + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_readbacks_for_changed_allocations_are_invalidated() { + let first = track(91, 0x1000, 0x2000); + let next = track(92, 0x2000, 0x3000); + let far = track(93, 0x4000, 0x5000); + + remapped(0x0f00, 0x200); + assert!(!first.valid.load(Ordering::Acquire)); + assert!(next.valid.load(Ordering::Acquire)); + replaced(0x2000); + assert!(!next.valid.load(Ordering::Acquire)); + assert!(far.valid.load(Ordering::Acquire)); + + released(93); + assert!(!far.valid.load(Ordering::Acquire)); + assert!(track(94, 0x2000, 0x3000).valid.load(Ordering::Acquire)); + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 62fb034..4748c4b 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -2317,6 +2317,7 @@ pub fn title_memory_reading_now() -> Option { /// neither guarded nor writable) and a kernel read into it fail, so the /// write access is given back. pub fn title_memory_remapped(at: usize, len: usize) { + crate::texback::remapped(at, len); open(&mut title_memory_changed(at, len), at, at.saturating_add(len)); } @@ -2326,6 +2327,7 @@ pub fn title_memory_remapped(at: usize, len: usize) { /// before the unmapping would leave the address guarded, clean and known by /// its bits ([`PUBLISHED`]) with no view behind it. pub fn title_memory_unmapping(at: usize, len: usize) { + crate::texback::remapped(at, len); let mut g = title_memory_changed(at, len); if CHANGING.get().0 && len != 0 { CHANGING.set((true, true)); From 2be0515cbec59334798d16318112eaf725dc1510 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:24:11 -0600 Subject: [PATCH 409/445] Views mapped beside guarded ones: all views of the page are opened together, under the lock A page shown at several addresses, and one more view of it being mapped: the views that were to be opened were looked for before the lock was taken, so one made clean in between stayed clean with a writable view beside it (a write of the title's through that one was not told until its block's next told write), and they were opened one range after another, so for some microseconds one was writable while others were still known by their bits (told one asking late). Both are older than the faults' work; VICTORY_OPEN_ONE_VIEW made the first common. Also: what is known by its bits is not where bytes were just put in beside the guard (VICTORY_COPY_BESIDE, VICTORY_STORE_BESIDE). The test of writes through other views failed in 6 of 200 runs, then 4 of 380 with the first mended, 0 of 603 (four tests each) with both. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/watch.rs | 48 ++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 4748c4b..2f8455f 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -1120,7 +1120,11 @@ pub(crate) fn guarded(start: usize, end: usize) -> bool { /// Whether nothing of `[start, end)` can have been written since an asking /// noted it in the journal ([`PUBLISHED`]). fn published(start: usize, end: usize) -> bool { - light() && PUBLISHED.all(start / BLOCK, end.div_ceil(BLOCK)) + let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); + // (In this order: who puts something in beside a guard sets the one bit, + // then clears the other, which an asking that is publishing the block may + // just be setting.) + light() && PUBLISHED.all(first, last) && !BESIDE.any(first, last) } /// Since the last frame line: what asking about title memory was. Kernel @@ -1484,7 +1488,7 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64, /// Whether every write of the title's to 64 KiB block `block` so far is in /// the journal ([`PUBLISHED`]). pub(crate) fn block_published(block: usize) -> bool { - light() && PUBLISHED.all(block, block + 1) + published(block * BLOCK, (block + 1) * BLOCK) } /// Whether shaders' writes went into a page of `[at, at + len)` in the last @@ -2066,20 +2070,22 @@ pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) { if !view_guard() { return; } - let mut ranges = crate::inplace::views_of_section(section, offset, len); + let ranges = crate::inplace::views_of_section(section, offset, len); // (A block is noted in `PROTECTED` ahead of the look at its page's views // that did not find this one yet.) - ranges.retain(|&(at, n)| PROTECTED.any(at / BLOCK, (at + n).div_ceil(BLOCK))); - if ranges.is_empty() { + if !ranges.iter().any(|&(at, n)| PROTECTED.any(at / BLOCK, (at + n).div_ceil(BLOCK))) { return; } + // All of them, once one is guarded: another may have been made clean + // since that look, relying on those that are opened here. And all + // together: none may be writable while another is clean (who asks about + // that one by its bits takes no lock). let mut g = guards(); - for &(at, n) in &ranges { - 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); - } + let blocks: Vec = + ranges.iter().flat_map(|&(at, n)| g.protected.range(at / BLOCK..(at + n).div_ceil(BLOCK)).collect::>()).collect(); + #[cfg(feature = "diagnostics")] + ALIASES[2].fetch_add(blocks.len() as u64, std::sync::atomic::Ordering::Relaxed); + unguard(&mut g, &blocks); } /// The runtime is about to unmap a view of which it maps a part again at @@ -2093,7 +2099,12 @@ 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.) + // (The view itself too: the part that stays is read-only until then. And + // all of them told as written before the first is writable.) + for &other in &others { + g.clean.remove(other / BLOCK); + PUBLISHED.clear(other / BLOCK); + } open(&mut g, at, at.saturating_add(len)); for other in others { open(&mut g, other, other + BLOCK); @@ -3898,6 +3909,8 @@ mod many_askers_tests { let to = page + 1 + next((PAGES - page).min(3)); // Written through one view, asked about at another. let (through, asked) = (all[next(VIEWS)], next(VIEWS)); + #[allow(unused_assignments)] + let mut how = 0; let (at, last) = (all[asked], &mut last[asked]); if next(4) != 0 { // As in the test above, or after a word of ours, @@ -3921,6 +3934,7 @@ mod many_askers_tests { continue; } let reading = (next(3) == 0).then(super::title_memory_reading); + how = usize::from(reading.is_some()); let beside = reading.as_ref().and_then(|_| crate::inplace::beside(word, 8)); if let Some(to) = beside { unsafe { (to as *mut u64).write_volatile(2) }; @@ -3928,8 +3942,10 @@ mod many_askers_tests { past.fetch_add(1, std::sync::atomic::Ordering::Relaxed); assert_eq!(unsafe { (word as *const u64).read_volatile() }, 2, "put elsewhere"); } else { + how += 2; if next(4) == 0 { super::writing(word, 8); + how += 4; } unsafe { (word as *mut u64).write_volatile(1) }; } @@ -3947,7 +3963,13 @@ mod many_askers_tests { } 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}: {number} is not after {}", last[page]); + assert!( + number > last[page], + "{VIEWS} views, page {page}, through {:x} ({how}), asked at {:x}: {number} is not after {}", + through / PAGE + page, + at / PAGE + page, + last[page] + ); for l in &mut last[from..to] { *l = now; } From 53abe45ad2daa714ab1d583ded025ce509309213 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:33:42 -0600 Subject: [PATCH 410/445] wip wide --- crates/victory-shader/src/emit/bitcode/opt.rs | 11 +- crates/victory-shader/src/emit/lower.rs | 54 +++++- crates/victory-shader/src/emit/mod.rs | 164 +++++++++++++++++- 3 files changed, 222 insertions(+), 7 deletions(-) diff --git a/crates/victory-shader/src/emit/bitcode/opt.rs b/crates/victory-shader/src/emit/bitcode/opt.rs index 4fb2940..5be0c09 100644 --- a/crates/victory-shader/src/emit/bitcode/opt.rs +++ b/crates/victory-shader/src/emit/bitcode/opt.rs @@ -52,10 +52,19 @@ pub const LOADS: u32 = 16; /// half has a lane where every lane is in EXEC (`lower.rs`, /// `v_readfirstlane_b32`). pub const FIRST: u32 = 32; +/// Not a pass over the module either: the lowering reads the dwords of one +/// console load (`s_buffer_load_dwordx2` to `x16` from an SRV, a +/// `global_load_dwordx2` to `x4`) by one call for every four of them, not +/// by a call each (`lower.rs`, `raw_dwords`). The same bytes are read. +pub const WIDE: u32 = 64; /// The passes over the module. pub const MODULE: u32 = DEAD | FOLD | REUSE | FACTS | LOADS; /// Every pass. -pub const ALL: u32 = MODULE | FIRST; +pub const ALL: u32 = MODULE | FIRST | WIDE; +/// The passes that run when nothing says which: every one but [`WIDE`], +/// which no card has shown a gain for yet (`VICTORY_SHADER_OPT=127` asks +/// for it). +pub const DEFAULT: u32 = ALL & !WIDE; /// What the instructions a module writes use, of the features a shader /// declares by flag (the validator's "flags must match usage"). diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 63495c9..1dc305a 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6050,6 +6050,47 @@ impl<'a> Lower<'a> { }) } + /// Whether the dwords of one console load are read by one call for up + /// to four of them (`bitcode::opt::WIDE` of `VICTORY_SHADER_OPT`), not + /// by a call each. + fn wide_loads() -> bool { + super::shader_opt() & super::bitcode::opt::WIDE != 0 + } + + /// `count` dwords from byte `addr` on of the raw view `h`, as integers, + /// read in the current block by one call for every four of them + /// ([`Self::wide_loads`]). They are the dwords of ONE console load, + /// which the console reads as one (address plus 4, 8, ... without + /// wrapping at 32 bits): the same bytes as a call a dword reads. Loads + /// of different console instructions are never joined: the program + /// computes their offsets in 32-bit registers, and `x - 4` and `x` at + /// `x = 0` are one dword out of the view and its first one, where one + /// call from `x - 4` on would read both out of it. + fn raw_dwords(&mut self, h: V, addr: V, count: u32) -> Vec { + let c = self.cur; + let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + let mut out = Vec::with_capacity(count as usize); + for first in (0..count).step_by(4) { + let n = (count - first).min(4); + let off = self.s.m.i32(4 * first); + let a = self.s.m.bin(c, Bin::Add, addr, off); + let mask = self.s.m.i8((1u8 << n) - 1); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, a, u, mask, al], + ); + for k in 0..n { + let x = self.s.m.extract(c, r, k); + out.push(self.as_int(x)); + } + } + out + } + fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { let Fields::Smem { data, @@ -6132,7 +6173,12 @@ impl<'a> Lower<'a> { let at = self.begin_guarded(Some(is_buffer)); let h = self.handle(site, src, false, (11, 0))?; let mut raw = Vec::new(); - for k in 0..count { + let wide = Self::wide_loads(); + if wide { + let dwords = self.raw_dwords(h, addr, count); + raw.extend(dwords.into_iter().map(|x| (x, zero))); + } + for k in 0..if wide { 0 } else { count } { let b = self.cur; let off = self.s.m.i32(4 * k); let a = self.s.m.bin(b, Bin::Add, addr, off); @@ -6185,6 +6231,12 @@ impl<'a> Lower<'a> { } None => self.handle(site, src, false, (11, 0))?, }; + if Self::wide_loads() { + for (k, x) in self.raw_dwords(h, addr, count).into_iter().enumerate() { + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } let c = self.cur; for k in 0..count { let off = self.s.m.i32(4 * k); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index cc439a5..baf9226 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -206,13 +206,15 @@ pub fn builder_bounds() -> bool { /// is exact, so the switch is for telling a translator fault from a /// clean-up fault, and for measuring what the clean-up is worth. /// `VICTORY_SHADER_OPT`: -/// - unset: every pass. +/// - unset: every pass but the last one below (63). /// - `0`: none (the module as the lowering made it). /// - a number (decimal or `0x` hex): those passes; 1 dead code, 2 constants /// and identities, 4 one instruction for one value, 8 what a branch taken /// says about its condition, 16 one read for one place within a block, /// 32 a first-lane read of two host waves without the round that asks /// which half has a lane (where every lane has one). +/// 64 the dwords of one console load read by one call for every four +/// (not on unless asked: `127` is every pass with it). /// /// Part of the translation: the shader cache keys on it (`victory-gpu`'s /// does). @@ -310,7 +312,7 @@ fn parse_shader_opt(value: Option<&str>) -> u32 { Some(hex) => u32::from_str_radix(hex, 16).ok(), None => v.parse().ok(), }); - parsed.map_or(bitcode::opt::ALL, |n| n & bitcode::opt::ALL) + parsed.map_or(bitcode::opt::DEFAULT, |n| n & bitcode::opt::ALL) } /// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset, @@ -1080,13 +1082,15 @@ mod tests { #[test] fn the_clean_up_switch_parses_or_runs_every_pass() { - let all = super::bitcode::opt::ALL; - assert_eq!(parse_shader_opt(None), all); + let (all, usual) = (super::bitcode::opt::ALL, super::bitcode::opt::DEFAULT); + assert_eq!(usual, 63, "the passes of the builds before the wide loads"); + assert_eq!(parse_shader_opt(None), usual); assert_eq!(parse_shader_opt(Some("0")), 0); assert_eq!(parse_shader_opt(Some(" 1 ")), 1); assert_eq!(parse_shader_opt(Some("0x1")), 1); + assert_eq!(parse_shader_opt(Some("127")), all); assert_eq!(parse_shader_opt(Some("0xffffffff")), all); - assert_eq!(parse_shader_opt(Some("on")), all); + assert_eq!(parse_shader_opt(Some("on")), usual); } #[test] @@ -2081,6 +2085,156 @@ mod tests { let _ = super::emit(&c, &native, &p, &st, &io, &res); } + /// `s_buffer_load_dwordx4`, `x8` and `x16` from a raw SRV read the dwords + /// the console's range-checked load reads, a call a dword or + /// (`VICTORY_SHADER_OPT` with 64) a call for every four: also where a + /// call's four dwords lie across the view's end (the dwords out of it + /// are 0, the others are read). On the software adapter only: run the + /// test once plain and once with `VICTORY_SHADER_OPT=127`. + #[test] + #[cfg(windows)] + fn scalar_buffer_loads_read_the_same_dwords_one_call_or_four() { + // (first register, dwords) of the three loads, in order. + const LOADS: [(u32, u32); 3] = [(16, 8), (24, 4), (32, 16)]; + let mut words: Vec = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 (the SRV) + 0xF408_0302, + 0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20 (the UAV) + 0xF42C_0404, + 0x0000_0000, // s_buffer_load_dwordx8 s[16:23], s[8:11], s0 + 0xF428_0604, + 0xFA00_0008, // s_buffer_load_dwordx4 s[24:27], s[8:11], 0x8 + 0xF430_0804, + 0x0200_0004, // s_buffer_load_dwordx16 s[32:47], s[8:11], s1, 0x4 + ]; + let mut out_dword = 0u32; + for (first, n) in LOADS { + for k in 0..n { + // v_mov_b32 v1, s + words.push(0x7E00_0000 | 1 << 17 | 0x001 << 9 | (first + k)); + // buffer_store_dword v1, s[12:15], offset 4 * out_dword + words.push(0x38 << 26 | 0x1C << 18 | (4 * out_dword)); + words.push(0x80 << 24 | (12 >> 2) << 16 | 1 << 8); + out_dword += 1; + } + } + words.push(0xBF81_0000); // s_endpgm + let table = |kind, at| crate::UsedResource { + kind, + root: crate::RootType::Table, + table_offset_dwords: at, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }; + let native = super::NativeProgram { + stage: super::HwStage::Cs, + wave64: false, + vgprs: 4, + layout: vec![ + crate::RootParam { + root: crate::RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + crate::RootParam { + root: crate::RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![table(crate::ResourceType::Srv, 0), table(crate::ResourceType::Uav, 8)], + io: crate::native::StageIo::Cs(crate::native::ComputeIo { + rsrc2: 5 << 1, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + let l = super::lower::lower(&super::lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .unwrap(); + // The calls that read the SRV: 28 a dword, 7 with four a call. + let wide = shader_opt() & super::bitcode::opt::WIDE != 0; + let mut dxil = l.dxil; + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut dxil).unwrap(); + } + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = super::host::Host::new(true) else { + eprintln!("no software adapter; the dispatch is skipped"); + return; + }; + let cs = super::HostShader { + stage: super::HwStage::Cs, + dxil, + user_data: l.user_data, + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: l.root_cbvs, + root_srvs: l.root_srvs, + root_uavs: l.root_uavs, + root_indexed_views: Vec::new(), + }; + let (root, pso) = host.compute_pipeline(&cs).unwrap(); + // Twelve dwords: the loads below run across the view's end. + let data: Vec = (0..12u32).map(|i| 0x1111_1111u32.wrapping_mul(i + 1) ^ 0x8000_0000).collect(); + let dword = |byte: u64| -> u32 { + if byte.is_multiple_of(4) && byte + 4 <= 4 * data.len() as u64 { data[(byte / 4) as usize] } else { 0 } + }; + for (s0, s1) in [(0u32, 0u32), (16, 0), (24, 4), (40, 28), (48, 44), (8, 12)] { + let out = host + .dispatch( + &root, + &pso, + &super::host::Dispatch { + roots: vec![(0, super::host::Root::Constants(vec![s0, s1, 0, 0, 0]))], + views: &[ + super::host::View::Buffer { + data: &data, + stride: super::host::Stride::Raw, + }, + super::host::View::RawUav(32), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap(); + let starts = [u64::from(s0), 8, u64::from(s1) + 4]; + let mut want = Vec::new(); + for (&(_, n), start) in LOADS.iter().zip(starts) { + want.extend((0..u64::from(n)).map(|k| dword(start + 4 * k))); + } + eprintln!("offsets {s0} and {s1}, four dwords a call: {wide}: {:x?}", &out[0][..28]); + assert_eq!(out[0][..28], want[..], "offsets {s0} and {s1}, four dwords a call: {wide}"); + } + } + #[test] fn valu_div_f32_sequence_executes_on_gpu() { let words: &[u32] = &[ From 17c4717b44909b171395c19b506ab48d90a39efe Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:35:09 -0600 Subject: [PATCH 411/445] Title buffers' copies down to any size in the card's memory (VICTORY_CARD_BUFFERS_MIN_KB), the card's hashes over the buffer's own bytes (both after fxceless c36971b2) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 4 ++-- crates/victory-gpu/src/shadow.rs | 29 +++++++++++++++++++++++++++-- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index d58ae41..2aa4178 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4234,7 +4234,7 @@ impl Host { list.SetPipelineState(&work.pso); list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); for (shadow, ranges) in &dirty { - let Some((_, Some(before), size)) = shadow.card_sides() else { + let (Some((_, Some(before), _)), size) = (shadow.card_sides(), shadow.card_hash_size()) else { continue; }; // No twin (it cost the card the copy's size again, @@ -4364,7 +4364,7 @@ impl Host { list.SetPipelineState(&work.pso); list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); for r in plan.ranges.iter().filter(|r| r.compared) { - let Some((_, Some(before), size)) = r.shadow.card_sides() else { + let (Some((_, Some(before), _)), size) = (r.shadow.card_sides(), r.shadow.card_hash_size()) else { continue; }; list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 9851d79..43d1b76 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -224,12 +224,22 @@ fn card_limits() -> (u64, u64) { env_mb("VICTORY_CARD_BUFFERS_MIN_MB"), env_mb("VICTORY_CARD_BUFFERS_MB"), ); + // `VICTORY_CARD_BUFFERS_MIN_KB` (after fxceless c36971b2) says the + // least size in KiB, so that it can go under 1 MiB: 64 is every title + // buffer. Copies under 1 MiB are nearly all there are and few bytes; + // in the PC's memory every load, store and atomic a shader does on + // them crosses the bus. + if let Some(kib) = std::env::var("VICTORY_CARD_BUFFERS_MIN_KB").ok().and_then(|v| v.trim().parse::().ok()) + && kib > 0 + { + min_bytes = kib << 10; + } if card_all() { min_bytes = 0; } tracing::info!( vram_budget_mb = vram_budget.map(|b| b >> 20), - card_buffers_min_mb = min_bytes >> 20, + card_buffers_min_kb = min_bytes >> 10, card_buffers_max_mb = max_bytes >> 20, "card buffer limits" ); @@ -4225,10 +4235,25 @@ impl Shadow { /// it in the card's buffer (which may be longer than the copy), widened /// to 16 bytes. pub(crate) fn card_hashed(&self, piece: u32) -> (usize, usize) { - let size = self.card.as_ref().map_or(self.len, |c| c.size) as usize; + let size = self.card_hash_size() as usize; card_hashed_of(self.start as usize, size, piece as usize) } + /// The bytes of the copy the card's hashes cover: the title buffer's own, + /// rounded up to the hash's 16-byte step. The card's buffer is the title + /// buffer rounded up to 64 KiB, of which a title buffer of 288 bytes can + /// give nothing back but those (after fxceless c36971b2). + /// `VICTORY_CARD_HASH_LEN=0`: the whole buffer. + pub(crate) fn card_hash_size(&self) -> u64 { + static OWN: std::sync::OnceLock = std::sync::OnceLock::new(); + let size = self.card.as_ref().map_or(self.len, |c| c.size); + if *OWN.get_or_init(|| std::env::var_os("VICTORY_CARD_HASH_LEN").is_none_or(|v| v != "0")) { + self.len.next_multiple_of(16).min(size) + } else { + size + } + } + /// The walls trace (`crate::host::walls_trace`): a piece of `fetched` /// bytes of this copy came back from the card and `written` of them /// went into title memory. Summed per buffer and logged once a frame: From b32fb9975d74600ac0812fd9424fa2d6829a004a Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:42:04 -0600 Subject: [PATCH 412/445] A range shaders write is declared once until the list next writes title memory (from Belobug dd799aad, romainhedouin); VICTORY_DECLARE_ONCE=0 for the old way Dispatches declare the same few ranges again and again: 4,003 to 5,550 steps a frame of fork-b1-fast, each a flush of its copy's pending refreshes and two locks on the thread that submits (the snapshots alone 1.7 to 2.0 ms a frame). The ranges and their order stay what they were. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 36 +++++++++++++++++++++++----- crates/victory-gpu/src/host/place.rs | 2 +- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 2aa4178..bbb733b 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2184,6 +2184,10 @@ struct Deferred { /// Buffer ranges refreshed since the last title copy (host copy, /// address, bytes): refreshing them again would find the same bytes. refreshed: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, + /// Ranges declared written by shaders since the list last wrote title + /// memory (host copy, address, bytes): declaring them again would + /// change nothing. + gpu_written: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet, /// Bottom-of-pipe writes, done once the list has run: address, what, @@ -2218,6 +2222,13 @@ impl Deferred { self.upload_bytes += size; self.uploads.push(buffer); } + + /// The steps recorded last write title memory: what was brought up to + /// date before them is not any more. + fn title_written(&mut self) { + self.refreshed.clear(); + self.gpu_written.clear(); + } } impl Drop for Deferred { @@ -3685,6 +3696,12 @@ fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool { && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d)) } +/// See [`HostList::defer_gpu_write`]. +fn declare_once() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_DECLARE_ONCE").map_or(true, |v| v != "0")) +} + /// The ranges the shaders of `runs` may write, per host copy, as declared. /// One list's lock at a time: a submission may name a list twice. fn declared_writes(runs: &[&HostList]) -> Vec { @@ -6630,7 +6647,7 @@ impl HostList { deferred .copies .push(Step::Copy(dst as usize, src as usize, len)); - deferred.refreshed.clear(); + deferred.title_written(); self.changed_something(); } @@ -6677,15 +6694,20 @@ impl HostList { /// Shaders of the list write `[address, address + len)` of a buffer's /// host copy: copied back into title memory once the list has run. + /// Declared once until the list next writes title memory (but with + /// `VICTORY_DECLARE_ONCE=0`): the dispatches of a frame declared the + /// same ranges thousands of times, each a step of its own. pub(crate) fn defer_gpu_write( &self, shadow: &std::sync::Arc, address: usize, len: usize, ) { - self.deferred() - .copies - .push(Step::GpuWrite(shadow.clone(), address, len)); + let mut deferred = self.deferred(); + let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); + if deferred.gpu_written.insert(key) || !declare_once() { + deferred.copies.push(Step::GpuWrite(shadow.clone(), address, len)); + } } /// A read back: once the list has run, `rows` rows of `row` bytes go @@ -7012,8 +7034,10 @@ impl HostList { /// Runs `work` when the list is submitted, in order with its copies. /// `work` may write title memory (refreshes after it copy again). pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) { - self.deferred().copies.push(Step::Run(Box::new(work))); - self.deferred().refreshed.clear(); + let mut deferred = self.deferred(); + deferred.copies.push(Step::Run(Box::new(work))); + deferred.title_written(); + drop(deferred); self.changed_something(); } diff --git a/crates/victory-gpu/src/host/place.rs b/crates/victory-gpu/src/host/place.rs index cde0149..9e815d4 100644 --- a/crates/victory-gpu/src/host/place.rs +++ b/crates/victory-gpu/src/host/place.rs @@ -255,7 +255,7 @@ impl HostList { shadow: to, from: scratch.map(|s| s.2 as usize), })); - deferred.refreshed.clear(); + deferred.title_written(); self.changed_something(); true } From ab86ef7f3ffba5cb7e8e21009f28f437222087da Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:42:59 -0600 Subject: [PATCH 413/445] A pipeline a list binds again is not kept and named again (from Belobug 92d353f8, romainhedouin) Two queries for an interface, three locks and a name looked up at every change of pipeline; now one lookup by address. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 4 +--- crates/victory-gpu/src/host.rs | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 88729fc..2641d9c 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1460,10 +1460,8 @@ impl State { // SAFETY: an open list and a live pipeline. unsafe { l.SetPipelineState(&p.pso) }; self.host_pipeline = p.pso.as_raw() as usize; - list.used_pipeline(&p.name); // The title may release the pipeline before it submits the list. - list.keep(&p.pso); - list.keep(&p.root); + list.bind_pipeline(&p.name, &p.pso, &p.root); } for stage in &p.stages { let t = stage.translated(); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index bbb733b..da8f6da 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2181,6 +2181,8 @@ struct Deferred { /// descriptor heaps): the title may release its objects before it /// submits the list. kept: Vec, + /// The pipelines [`HostList::bind_pipeline`] kept, by address. + bound: std::collections::HashSet>, /// Buffer ranges refreshed since the last title copy (host copy, /// address, bytes): refreshing them again would find the same bytes. refreshed: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, @@ -6624,6 +6626,21 @@ impl HostList { } } + /// The list binds a pipeline: it and its root signature are kept until + /// the list is reset, and its name noted, the first time only (a kept + /// pipeline's address names no other). + pub(crate) fn bind_pipeline(&self, name: &str, pso: &ID3D12PipelineState, root: &ID3D12RootSignature) { + { + let mut deferred = self.deferred(); + if !deferred.bound.insert(pso.as_raw() as usize) { + return; + } + deferred.kept.push(pso.clone().into()); + deferred.kept.push(root.clone().into()); + } + self.used_pipeline(name); + } + fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> { self.deferred.lock().unwrap_or_else(|e| e.into_inner()) } From c96525dbb29daa12bc224813a3e64745520fae29 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:43:00 -0600 Subject: [PATCH 414/445] A root constant buffer not 256-byte aligned is copied into scratch memory once for the draws of a list that bind it (from Belobug 84ea9c12, romainhedouin) Until the list next writes title memory, as for refreshes: up to 64 KiB of fill less for every repeat. How often this title binds one was not measured. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 4 +--- crates/victory-gpu/src/host.rs | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2641d9c..04aa40e 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -713,9 +713,7 @@ fn root_view(list: &HostList, address: u64, srv: bool) -> Option { crate::book::root(gpu, len); return Some(gpu); } - let (gpu, to) = list.scratch(len)?; - list.defer_fill(to, address as *const u8, len as usize); - Some(gpu) + list.fill_scratch(address as *const u8, len) } macro_rules! once { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index da8f6da..1d83029 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2190,6 +2190,9 @@ struct Deferred { /// memory (host copy, address, bytes): declaring them again would /// change nothing. gpu_written: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, + /// Scratch memory [`HostList::fill_scratch`] fills since the list last + /// wrote title memory (source, bytes): its host address. + filled: std::collections::HashMap<(usize, usize), u64, std::hash::BuildHasherDefault>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet, /// Bottom-of-pipe writes, done once the list has run: address, what, @@ -2230,6 +2233,7 @@ impl Deferred { fn title_written(&mut self) { self.refreshed.clear(); self.gpu_written.clear(); + self.filled.clear(); } } @@ -6676,6 +6680,21 @@ impl HostList { .push(Step::Fill(dst as usize, src as usize, len, None)); } + /// The host address of `len` bytes of scratch memory that hold the title + /// memory at `src` as of the list's submission: one fill for every ask + /// until the list next writes title memory. + pub(crate) fn fill_scratch(&self, src: *const u8, len: u64) -> Option { + let key = (src as usize, len as usize); + let known = self.deferred().filled.get(&key).copied(); + if known.is_some() { + return known; + } + let (gpu, to) = self.scratch(len)?; + self.defer_fill(to, src, len as usize); + self.deferred().filled.insert(key, gpu); + Some(gpu) + } + /// As [`HostList::defer_fill`], for upload memory that only `slot` (a /// title heap's address, and the slot) shows. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) { From ca1d519f18ccece3daf2b05191a43fae17ac6f91 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:44:14 -0600 Subject: [PATCH 415/445] The same render targets are not set again (after ZJOU acf478b8, author local); VICTORY_BIND_CACHE=0 sets them every time Theirs compares the handles, which a title may write other views behind; here the views themselves (resource, host texture, description) are compared. A call with the same ones saves a host view per target and the driver's call. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 9 +++++++ crates/victory-gpu/src/draw.rs | 36 ++++++++++++++++++++++++---- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index cabe5a1..7ca72cb 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -643,6 +643,15 @@ const RTV_TAG: u32 = u32::from_le_bytes(*b"vRTV"); const _: () = assert!(size_of::() <= 112); impl RtvRecord { + /// All the view it records is made from: records with equal keys have + /// equal views (of the same host texture). + #[cfg(windows)] + pub(crate) fn key(&self) -> (usize, [u32; 7]) { + let mut words = [self.described; 7]; + words[1..].copy_from_slice(&self.desc); + (self.resource as usize, words) + } + /// The view description in the host's type (the same layout). #[cfg(windows)] pub(crate) fn desc( diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 04aa40e..f04fe53 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -306,6 +306,10 @@ pub(crate) struct State { target_handles: Vec, depth_handle: u64, targets_set: bool, + /// The render target views and the depth view the host list has, once + /// it has any ([`State::set_targets`]): per view the host texture (0: + /// a null view) and what its descriptor says. + host_targets: Option<(Vec, Option)>, viewports: Vec, scissors: Vec, blend: Option<[f32; 4]>, @@ -685,6 +689,10 @@ pub(crate) fn dispatched() -> u64 { DISPATCHED.load(Ordering::Relaxed) } +/// What a render target or depth view of the host is made from: the host +/// texture, and [`crate::descriptor::RtvRecord::key`]. +type TargetKey = (usize, (usize, [u32; 7])); + /// The host address of a root view: its buffer's host copy, or for a /// constant buffer not 256-byte aligned there (the console needs 16) a /// copy in upload memory. @@ -993,7 +1001,11 @@ impl State { self.index = view.copied().unwrap_or_default(); } - /// Render targets and depth, set on the host list at once. + /// Render targets and depth, set on the host list at once, unless it has + /// the same ones already: the title sets the same targets again and + /// again, each time a host view per target and a call of the driver + /// (25,662 times in a frame of another fork). `VICTORY_BIND_CACHE=0` + /// sets them every time. pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) { let Some(host) = crate::host::host() else { return; @@ -1003,7 +1015,8 @@ impl State { self.depth_handle = depth; self.targets_set = true; self.targets.clear(); - let mut rtvs = Vec::new(); + let mut views = Vec::with_capacity(handles.len()); + let mut keys = Vec::with_capacity(handles.len()); for &h in handles { let Some(record) = crate::descriptor::rtv_record(h) else { once!( @@ -1023,14 +1036,16 @@ impl State { .desc() .filter(|d| d.Format.0 != 0 && d.ViewDimension.0 != 0); if let Some(desc) = null { - rtvs.push(host.rtv(None, Some(&desc))); + views.push((None, Some(desc))); + keys.push((0, record.key())); } continue; }; self.targets.push(record.resource as usize); #[cfg(feature = "diagnostics")] crate::capture::note_target(record.resource); - rtvs.push(host.rtv(Some(texture), record.desc().as_ref())); + views.push((Some(texture), record.desc())); + keys.push((texture.as_raw() as usize, record.key())); } self.depth = 0; self.depth_state = DEPTH_WRITE; @@ -1043,8 +1058,18 @@ impl State { } #[cfg(feature = "diagnostics")] crate::capture::note_target(record.resource); - Some(host.dsv(texture, record.depth_desc().as_ref())) + Some((texture, record)) }); + let now = (keys, dsv.as_ref().map(|(texture, record)| (texture.as_raw() as usize, record.key()))); + static CACHE: std::sync::OnceLock = std::sync::OnceLock::new(); + if *CACHE.get_or_init(|| std::env::var("VICTORY_BIND_CACHE").map_or(true, |v| v != "0")) + && self.host_targets.as_ref() == Some(&now) + { + return; + } + self.host_targets = Some(now); + let rtvs: Vec<_> = views.iter().map(|(texture, desc)| host.rtv(*texture, desc.as_ref())).collect(); + let dsv = dsv.map(|(texture, record)| host.dsv(texture, record.depth_desc().as_ref())); // SAFETY: an open list; the views were just made. unsafe { list.list.OMSetRenderTargets( @@ -1121,6 +1146,7 @@ impl State { if self.topology_set { self.set_topology(list, self.topology); } + self.host_targets = None; if self.targets_set { let handles = std::mem::take(&mut self.target_handles); self.set_targets(list, &handles, self.depth_handle); From 449830f6fd197909726b7175cd1140575a616668 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:46:34 -0600 Subject: [PATCH 416/445] The frame line says how many indirect records ran empty for want of their list's budget, and the largest cost; VICTORY_INDIRECT_REST=0: a record that does not fit takes nothing from the ones after it Belobug (76387c2d) found draws flickering because the records past a list's budget were not the same ones from frame to frame. Whether ours are refused is not known: the count says it (atomics only when there is something to say). Off by default; the records' order and costs stay what they were. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 20 +++++-- crates/victory-gpu/src/indirect.rs | 68 ++++++++++++++++++++---- crates/victory-gpu/src/indirect/batch.rs | 17 +++++- 3 files changed, 87 insertions(+), 18 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 1d83029..8a18af2 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1707,6 +1707,10 @@ fn list_number(name: &str) -> Option { /// budget buffers, a run late). static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +/// Indirect records that ran empty for want of their list's budget, and the +/// largest cost of one (told from 2^22 on), likewise. +static BUDGET_NOTES: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + /// Whether a list's indirect-work budget lives in the card's own memory /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as /// before). The clamp charges it with atomics, at least two in a row for @@ -6846,14 +6850,18 @@ impl HostList { // SAFETY: the list's own mapped words, written before it runs. // The words after the budget hold what the clamp noted about the // list's last run (mesh dispatches: the largest group count - // asked for, the groups asked in all; with the card's copy, as + // asked for, the groups asked in all; the records refused, the + // largest cost; with the card's copy, as // the list's end copied them here): taken, then zeroed. let notes = Box::new(move || unsafe { let words = at as *mut u32; let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile()); MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed); MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed); - for k in 0..3 { + let (refused, biggest) = (words.add(3).read_volatile(), words.add(4).read_volatile()); + BUDGET_NOTES[0].fetch_add(u64::from(refused), Ordering::Relaxed); + BUDGET_NOTES[1].fetch_max(u64::from(biggest), Ordering::Relaxed); + for k in 0..5 { words.add(k).write_volatile(0); } }); @@ -6888,7 +6896,7 @@ impl HostList { }; // SAFETY: a live buffer. let at = unsafe { card.GetGPUVirtualAddress() }; - let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { + let zeros = [0u64, 4, 8, 12, 16].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: at + offset, Value: 0, }); @@ -6929,7 +6937,7 @@ impl HostList { D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE, )]); - self.list.CopyBufferRegion(mapped, 4, card, 4, 8); + self.list.CopyBufferRegion(mapped, 4, card, 4, 16); self.list.ResourceBarrier(&[transition( card, D3D12_RESOURCE_STATE_COPY_SOURCE, @@ -8516,8 +8524,10 @@ impl Meter { let indirect = crate::list::take_indirect() as f64 / frames; let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed); let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames; + let refused = BUDGET_NOTES[0].swap(0, Ordering::Relaxed) as f64 / frames; + let biggest = BUDGET_NOTES[1].swap(0, Ordering::Relaxed); tracing::info!( - "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame" + "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame; {refused:.2} indirect records a frame ran empty for want of their list's budget (2^27), the largest cost of one {biggest} (0: under 2^22)" ); crate::shadow::exact_line(frames); crate::descriptor::sync_line(frames); diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index d74b748..5c13842 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -157,7 +157,8 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { uint n = eff_count > first ? min(64u, eff_count - first) : 0u; if (gi == 0 && n > 0) { // What the records charge, from `before` on, in lane order: a - // record that does not fit whole runs empty and takes the rest. + // record that does not fit whole runs empty and takes the rest + // (`rest`). // Only the group's own records are walked (one, clamped alone). uint before; budget.InterlockedOr(0, 0, before); @@ -167,7 +168,7 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { for (uint j = 0; j < n; j++) { uint c = costs[j]; if (c > 0 && next < BUDGET) { - next = (BUDGET - next <= c) ? BUDGET : (next + c); + next = (BUDGET - next < c) ? (REST ? BUDGET : next) : (next + c); } } if (next == before) break; @@ -177,15 +178,28 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { before = prev; } uint at = before; + uint refused = 0; + uint biggest = 0; for (uint k = 0; k < n; k++) { uint c = costs[k]; uint fit = 1; if (c > 0) { fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u; - at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c); + at = (at >= BUDGET || BUDGET - at < c) ? (REST ? BUDGET : at) : (at + c); + refused += 1 - fit; + biggest = max(biggest, c); } fits[k] = fit; } + // Diagnostics: the records that run empty for want of budget, and + // the largest cost there was (small ones are not told). + uint told; + if (refused > 0) { + budget.InterlockedAdd(12, refused, told); + } + if (biggest >= (1u << 22)) { + budget.InterlockedMax(16, biggest, told); + } } GroupMemoryBarrierWithGroupSync(); if (gi == 0 && kind > 2 && n > 0) { @@ -279,12 +293,22 @@ pub(crate) fn amd(device: &ID3D12Device) -> bool { } } +/// Whether a record that does not fit in what is left of its list's budget +/// takes the rest, so that every record after it runs empty too +/// (`VICTORY_INDIRECT_REST=0`: it takes nothing, and the next one that fits +/// runs). A list whose budget one garbage record empties loses all its later +/// draws, and which record that is may differ from frame to frame. The frame +/// line says how many records a frame are refused. +fn rest() -> u32 { + u32::from(std::env::var("VICTORY_INDIRECT_REST").map_or(true, |v| v != "0")) +} + /// The clamp compiled from `source` (ours, or in the benchmark the one it /// replaced). fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result { #[cfg(feature = "diagnostics")] let batched = source == batch::SOURCE; - let source = &format!("#define WIDEST {}u\n{source}", widest(amd(device))); + let source = &format!("#define WIDEST {}u\n#define REST {}\n{source}", widest(amd(device)), rest()); let mut code: Option = None; let mut errors: Option = None; // SAFETY: the source and names live through the call; out pointers ours. @@ -2556,9 +2580,35 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { /// word record by record, which of them fitted was up to the GPU.) #[test] fn warp_a_group_charges_its_records_in_lane_order() { - let Some(mut warp) = WarpHarness::new() else { + let Some((left, out)) = four_records_of_a_group(true) else { return; }; + assert_eq!(out[0..4], [100, 1, 7, 9], "the first record fits"); + for i in 1..4 { + assert_eq!(out[i * 4..i * 4 + 4], [0, 0, 7, 9], "record {i} runs empty"); + } + assert_eq!(left, 0, "the record that did not fit took the rest"); + } + + /// As above where a record that does not fit takes nothing + /// (`VICTORY_INDIRECT_REST=0`): those after it that fit run. + #[test] + fn warp_a_record_that_does_not_fit_may_take_nothing() { + let Some((left, out)) = four_records_of_a_group(false) else { + return; + }; + for (i, count) in [100, 0, 50, 100].into_iter().enumerate() { + assert_eq!(out[i * 4..i * 4 + 4], [count, count.min(1), 7, 9], "record {i}"); + } + assert_eq!(left, 50); + } + + /// Draws of 100, 250, 50 and 100 with 300 left of the budget: what is + /// left then, and the records as clamped. + fn four_records_of_a_group(rest: bool) -> Option<(u32, Vec)> { + let mut warp = WarpHarness::new()?; + let source = if rest { SOURCE.to_owned() } else { SOURCE.replace("REST ?", "false ?") }; + let clamp = make_from(&warp.device, &source).expect("the clamp must compile on WARP"); const KIND_DRAW: u32 = 0; const STRIDE: u32 = 16; const BUDGET_CAP: u32 = 1 << 27; @@ -2582,7 +2632,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { (budget_ptr as *mut u32).write_volatile(BUDGET_CAP - 300); } assert!(record_clamp_as( - &warp.clamp, + &clamp, &warp.list, (&dst_buf, D3D12_RESOURCE_STATE_COMMON), budget_gpu, @@ -2609,11 +2659,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { .to_vec(), ) }; - assert_eq!(out[0..4], [100, 1, 7, 9], "the first record fits"); - for i in 1..counts.len() { - assert_eq!(out[i * 4..i * 4 + 4], [0, 0, 7, 9], "record {i} runs empty"); - } - assert_eq!(spent, BUDGET_CAP, "the record that did not fit took the rest"); + Some((BUDGET_CAP - spent, out)) } /// The list's budget starts empty at each submission, wherever it diff --git a/crates/victory-gpu/src/indirect/batch.rs b/crates/victory-gpu/src/indirect/batch.rs index e6da6a1..d4f192d 100644 --- a/crates/victory-gpu/src/indirect/batch.rs +++ b/crates/victory-gpu/src/indirect/batch.rs @@ -124,7 +124,7 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { for (uint j = 0; j < n; j++) { uint c = costs[j]; if (c > 0 && next < BUDGET) { - next = (BUDGET - next <= c) ? BUDGET : (next + c); + next = (BUDGET - next < c) ? (REST ? BUDGET : next) : (next + c); } } if (next == before) break; @@ -134,15 +134,28 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { before = prev; } uint at = before; + uint refused = 0; + uint biggest = 0; for (uint k = 0; k < n; k++) { uint c = costs[k]; uint fit = 1; if (c > 0) { fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u; - at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c); + at = (at >= BUDGET || BUDGET - at < c) ? (REST ? BUDGET : at) : (at + c); + refused += 1 - fit; + biggest = max(biggest, c); } fits[k] = fit; } + // Diagnostics: the records that run empty for want of budget, and + // the largest cost there was (small ones are not told). + uint told; + if (refused > 0) { + budget.InterlockedAdd(12, refused, told); + } + if (biggest >= (1u << 22)) { + budget.InterlockedMax(16, biggest, told); + } } GroupMemoryBarrierWithGroupSync(); if (gi == 0 && n > 0 && all_asked > 0) { From 200a9cc5e656531b4005c2e974913242afbddb6c Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:57:05 -0600 Subject: [PATCH 417/445] Scalar buffer loads four dwords a call (VICTORY_SHADER_OPT=127; off): fxceless c36971b2's shader part What 53abe45a ("wip wide") brought in: opt bit 64, smem's loads through raw_dwords, its test and switch test as they are there (the global loads of this tree were wide already). Yard capture, turn by turn: 18.47 -> 18.45 ms (12 loops) and 18.23 -> 18.16 (5): nothing, so not on. With the bit off the code written is that of before. Not run yet: scalar_buffer_loads_read_the_same_dwords_one_call_or_four and the gpu tests on the second merge of local/next (2be0515c); the diagnostics build of 393e74fb finished. Belobug ae75a66a is this tree's own opt.rs (both from the fork at ba8697aa) without its first-lane pass; 7263339c is a trace: nothing to take. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/bitcode/opt.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/victory-shader/src/emit/bitcode/opt.rs b/crates/victory-shader/src/emit/bitcode/opt.rs index 5be0c09..d3ce5cd 100644 --- a/crates/victory-shader/src/emit/bitcode/opt.rs +++ b/crates/victory-shader/src/emit/bitcode/opt.rs @@ -56,6 +56,9 @@ pub const FIRST: u32 = 32; /// console load (`s_buffer_load_dwordx2` to `x16` from an SRV, a /// `global_load_dwordx2` to `x4`) by one call for every four of them, not /// by a call each (`lower.rs`, `raw_dwords`). The same bytes are read. +/// From fxceless/victory-fork c36971b2. On an RX 7900 XTX it is worth nothing: +/// the yard's frame replayed turn by turn, dispatches and draws 18.47 -> 18.45 +/// ms (12 loops) and 18.23 -> 18.16 (5 loops): the driver joins the loads. pub const WIDE: u32 = 64; /// The passes over the module. pub const MODULE: u32 = DEAD | FOLD | REUSE | FACTS | LOADS; From 44629de2e648a5f2e205050864286bb2fa1590bf Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:57:28 -0600 Subject: [PATCH 418/445] Heaps' records copied as bytes: pages read, compared and sorted out on several threads, empty slots that show nothing left alone; pages of places read by steps on the card asked about once Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 215 +++++++++++++--------- crates/victory-gpu/src/descriptor/host.rs | 70 ++++--- crates/victory-gpu/src/host/card_steps.rs | 21 ++- crates/victory-gpu/src/land.rs | 4 +- 4 files changed, 195 insertions(+), 115 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index cabe5a1..0972983 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -302,11 +302,9 @@ 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 views, mut bytes) = (0u64, 0u64); - let mut spent = [0u64; 4]; + let mut spent = [0u64; 3]; let since = |at: std::time::Instant| at.elapsed().as_nanos() as u64; - let mut kinds = [0u64; 6]; - let mut page_bytes: Vec = Vec::new(); - let mut changed: Vec = Vec::new(); + let mut kinds = [0u64; 5]; let mut wait: Vec = Vec::new(); let frame = crate::frame::current(); let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); @@ -344,87 +342,121 @@ pub(crate) fn sync_heaps() { let began = std::time::Instant::now(); let taken = written.take(start as usize, end as usize); spent[0] += since(began); + let mut parts: Vec<(usize, usize)> = Vec::new(); for (range_from, range_end) in taken { let mut page = range_from & !(crate::watch::PAGE - 1); while page < range_end { - let from = page.max(range_from); - let to = (page + crate::watch::PAGE).min(range_end); + parts.push((page.max(range_from), (page + crate::watch::PAGE).min(range_end))); + page += crate::watch::PAGE; + } + } + // A few pages a thread at a time: read, compared with what was last + // seen there and sorted out, beside one another (14 ms a frame of one + // thread at 160 pages, run faults-6). + let began = std::time::Instant::now(); + let copied = host.copied_begin(step as usize); + let samplers = heap.samplers(); + let found: Vec> = parts.chunks(SYNC_PAGES).map(|_| Default::default()).collect(); + crate::land::each_view(true, found.len(), &|n| { + let mut out = SyncPart::default(); + let mut page_bytes: Vec = Vec::new(); + let mut changed: Vec = Vec::new(); + for &(from, to) in parts.chunks(SYNC_PAGES).nth(n).unwrap_or_default() { // The page's records are read through the kernel, into a // copy: a page the title unmaps meanwhile fails the read // where 2,048 reads in place would fault. page_bytes.resize(to - from, 0); - let began = std::time::Instant::now(); - let there = crate::host::read_into(from as *const u8, &mut page_bytes); - spent[1] += since(began); - if there { - pages += 1; - views += u64::from(crate::watch::guarded(from, to)); - bytes += (to - from) as u64; - let slots = changed_slots(from, to, start as usize, step, mirrored_count); - // A record that straddles the range's ends is left - // to the range that holds its first byte. - let first = ((from - start as usize) as u64).div_ceil(step).max(slots.start); - let Some(records) = page_bytes.get((start + first * step) as usize - from..) else { - page += crate::watch::PAGE; - continue; - }; - let count = (records.len() as u64 / step).min(slots.end.saturating_sub(first)); - looked += count; - // Only the records that are not the ones last seen - // there (`HostHeap::copied_changes`). - changed.clear(); - let began = std::time::Instant::now(); - host.copied_changes(first as u32, &records[..(count * step) as usize], step as usize, &mut changed); - spent[2] += since(began); - for &index in &changed { - let at = (u64::from(index) - first) as usize * step as usize; - let word = |n: usize| { - records - .get(at + 4 * n..at + 4 * n + 4) - .and_then(|b| b.try_into().ok()) - .map_or(0, u32::from_le_bytes) - }; - if !heap.samplers() && word(0) == VIEW_TAG { - // A draw's own table: the draw makes what it - // reads of it (`draw.rs` `tables`). - if host.copied_tabled(index, frame) { - tabled += 1; - continue; - } - // Buffer views and placed textures get no host - // slot from this anyway, they wait for a draw - // or a pass: noted some frames on, unless a - // draw's table turns out to hold them. - if matches!(word(2) >> KIND_SHIFT, CONSTANT | PLACED) && host.copied_waits() { - wait.push(index); - later += 1; - continue; - } - } - 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)); - } + if !crate::host::read_into(from as *const u8, &mut page_bytes) { + continue; } - page += crate::watch::PAGE; + out.pages += 1; + out.views += u64::from(crate::watch::guarded(from, to)); + out.bytes += (to - from) as u64; + let slots = changed_slots(from, to, start as usize, step, mirrored_count); + // A record that straddles the range's ends is left + // to the range that holds its first byte. + let first = ((from - start as usize) as u64).div_ceil(step).max(slots.start); + let Some(records) = page_bytes.get((start + first * step) as usize - from..) else { + continue; + }; + let count = (records.len() as u64 / step).min(slots.end.saturating_sub(first)); + out.looked += count; + // Only the records that are not the ones last seen + // there (`host::Copied::changes`). + changed.clear(); + // SAFETY: the parts are ranges of the heap apart from one + // another, and only records that lie whole in one are its. + unsafe { copied.changes(first as u32, &records[..(count * step) as usize], &mut changed) }; + for &index in &changed { + let at = (u64::from(index) - first) as usize * step as usize; + let word = |n: usize| { + records + .get(at + 4 * n..at + 4 * n + 4) + .and_then(|b| b.try_into().ok()) + .map_or(0, u32::from_le_bytes) + }; + if !samplers && word(0) == VIEW_TAG { + // A draw's own table: the draw makes what it + // reads of it (`draw.rs` `tables`). + if host.copied_tabled(index, frame) { + out.tabled += 1; + continue; + } + // Buffer views and placed textures get no host + // slot from this anyway, they wait for a draw + // or a pass: noted some frames on, unless a + // draw's table turns out to hold them. + if matches!(word(2) >> KIND_SHIFT, CONSTANT | PLACED) && host.copied_waits() { + out.wait.push(index); + continue; + } + } + // No view, in a slot that shows none: nothing to make or + // unmake (32,000 of 41,000 a frame on the water, run + // b2-water). + if word(0) != VIEW_TAG && host.shows_none(index) { + out.nothing += 1; + continue; + } + out.make.push(index); + out.kinds[if samplers { + 3 + } else if word(0) != VIEW_TAG { + 0 + } else if word(2) >> KIND_SHIFT == 0 { + 1 + } else { + 2 + }] += 1; + } + } + *found[n].lock().unwrap_or_else(|e| e.into_inner()) = out; + }); + drop(copied); + for part in found { + let mut part = part.into_inner().unwrap_or_else(|e| e.into_inner()); + pages += part.pages; + views += part.views; + bytes += part.bytes; + looked += part.looked; + tabled += part.tabled; + kinds[0] += part.nothing; + later += part.wait.len() as u64; + mirrored += part.make.len() as u64; + wait.append(&mut part.wait); + make.append(&mut part.make); + for (kind, n) in kinds.iter_mut().zip(part.kinds) { + *kind += n; } } + spent[1] += since(began); let began = std::time::Instant::now(); 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); } }); - spent[3] += since(began); + spent[2] += since(began); if !wait.is_empty() { host.copied_wait(frame, std::mem::take(&mut wait)); } @@ -434,8 +466,8 @@ pub(crate) fn sync_heaps() { for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, micros, tabled, later]) { count.fetch_add(n, Relaxed); } - let [taking, reading, comparing, making] = spent; - for (count, n) in SYNC_SPLIT.iter().zip([views, bytes, taking, reading, comparing, making]) { + let [taking, reading, making] = spent; + for (count, n) in SYNC_SPLIT.iter().zip([views, bytes, taking, reading, making]) { count.fetch_add(n, Relaxed); } for (count, n) in SYNCED_KINDS.iter().zip(kinds) { @@ -444,9 +476,28 @@ pub(crate) fn sync_heaps() { } /// 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. +/// another, a sampler; waited and no draw came. #[cfg(windows)] -static SYNCED_KINDS: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; +static SYNCED_KINDS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// What a thread found on its pages of a heap, for [`sync_heaps`]. +#[cfg(windows)] +#[derive(Default)] +struct SyncPart { + pages: u64, + views: u64, + bytes: u64, + looked: u64, + tabled: u64, + nothing: u64, + make: Vec, + wait: Vec, + kinds: [u64; 5], +} + +/// Pages [`sync_heaps`] gives a thread at a time. +#[cfg(windows)] +const SYNC_PAGES: usize = 8; /// Records [`sync_heaps`] gives a thread at a time. #[cfg(windows)] @@ -462,10 +513,10 @@ const SYNC_AT_A_TIME: usize = 256; pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 7] = [const { std::sync::atomic::AtomicU64::new(0) }; 7]; /// The same, of [`SYNCED`]'s pages: those in view memory that was guarded; -/// bytes read; nanoseconds asking what was written, reading it, comparing it -/// with what was last seen, making views. +/// bytes read; nanoseconds asking what was written, reading it and comparing +/// it with what was last seen, making views. #[cfg(windows)] -static SYNC_SPLIT: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; +static SYNC_SPLIT: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; /// With the frame line: what [`sync_heaps`] did per frame over `frames`. /// Nothing while no heap page changed. @@ -481,8 +532,8 @@ 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 split = [0, 1, 2, 3, 4, 5].map(|i| SYNC_SPLIT[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64); - let kinds = [0, 1, 2, 3, 4, 5].map(|i| SYNCED_KINDS[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames); + let split = [0, 1, 2, 3, 4].map(|i| SYNC_SPLIT[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64); + let kinds = [0, 1, 2, 3, 4].map(|i| SYNCED_KINDS[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames); if pages == 0 { return; } @@ -490,8 +541,8 @@ pub(crate) fn sync_line(frames: f64) { "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); 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; \ - {:.1} of the pages guarded views, {:.1} MB read; {:.2} ms asking, {:.2} reading, {:.2} comparing, {:.2} making", + {:.0} no views (with those of slots that show none), {:.0} of objects, {:.0} others, {:.0} samplers, {:.0} that waited and no draw came; \ + {:.1} of the pages guarded views, {:.1} MB read; {:.2} ms asking, {:.2} reading and comparing, {:.2} making", pages as f64 / frames, looked as f64 / frames, mirrored as f64 / frames, @@ -504,13 +555,11 @@ pub(crate) fn sync_line(frames: f64) { kinds[2], kinds[3], kinds[4], - kinds[5], split[0] / frames, split[1] / (1 << 20) as f64 / frames, split[2] / 1e6 / frames, split[3] / 1e6 / frames, - split[4] / 1e6 / frames, - split[5] / 1e6 / frames + split[4] / 1e6 / frames ); } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 1b9118e..1ffdc72 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -136,7 +136,7 @@ pub(crate) struct HostHeap { /// [`HostHeap::mirror`] asks first, without the lock. Changed under it. quick: Vec, /// The records of the title's heap as the pass over records copied in - /// as bytes last saw them ([`HostHeap::copied_changes`]). Made on first + /// as bytes last saw them ([`Copied::changes`]). Made on first /// use. copied: Mutex>, /// New ones of them that wait for a draw ([`HostHeap::copied_wait`]), @@ -2885,10 +2885,10 @@ impl HostHeap { } } - /// For a run of records of the title's heap from slot `first`, `step` - /// bytes each, on a page that changed with no call - /// (`super::sync_heaps`: the title copies records into its heap as - /// bytes): the slots whose record is not the one this last saw there. + /// The records last seen of the title's heap, `step` bytes each, held for + /// threads that compare what they read of its changed pages beside one + /// another ([`Copied::changes`]; `super::sync_heaps`: the title copies + /// records into its heap as bytes). /// /// The page says only that something on it was written, and `mirror` /// by itself would take every buffer or placed-texture record on it for @@ -2896,23 +2896,15 @@ impl HostHeap { /// or a pass uses it): the texture queue's entry for the slot would /// start again, and the buffer pass would look at 2,048 slots for one /// that changed. - /// `records`: their bytes as the caller read them (through the - /// kernel, which fails on a page the title unmapped meanwhile where a - /// read in place would fault: the title unmaps heap pages too). - pub(crate) fn copied_changes(&self, first: u32, records: &[u8], step: usize, out: &mut Vec) { + pub(crate) fn copied_begin(&self, step: usize) -> Copied<'_> { let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); if copied.is_empty() { // Nothing there: a slot never looked at that holds nothing is // as it was. copied.resize(self.count as usize * step, 0); } - let at = first as usize * step; - let end = (at + records.len()).min(copied.len()); - let Some(last) = copied.get_mut(at..end) else { - return; - }; - let records = &records[..last.len()]; - changed_records(last, records, step, first, out); + let (at, len) = (copied.as_mut_ptr(), copied.len()); + Copied { at, len, step, _held: copied } } /// Whether new records of draws' tables are left to the draws @@ -2941,13 +2933,6 @@ 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) { @@ -3091,6 +3076,12 @@ impl HostHeap { Some(view) } + /// Whether slot `index` was made from no record: what [`HostHeap::mirror`] + /// would find before it did nothing for one that holds no view. + pub(crate) fn shows_none(&self, index: u32) -> bool { + self.made.get(index).unwrap_or(0) == 0 + } + /// Slot `index` is made from record `key` and stays so (0: not). Under /// the lock of `made`. fn quick_is(&self, index: u32, key: u64) { @@ -4318,6 +4309,39 @@ fn quick_mirror() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_QUICK_MIRROR").is_none_or(|v| v != "0")) } +/// The records last seen of a heap, held ([`HostHeap::copied_begin`]). +pub(crate) struct Copied<'a> { + at: *mut u8, + len: usize, + step: usize, + _held: std::sync::MutexGuard<'a, Vec>, +} + +// SAFETY: the bytes are reached through `changes` alone, whose callers take +// parts apart from one another; the guard stays with the thread that has it. +unsafe impl Sync for Copied<'_> {} + +impl Copied<'_> { + /// The slots of `records` (as the title has them now, from slot `first` + /// on) that are not the ones last seen, which they are from here on. + /// (`records`: as the caller read them, through the kernel, which fails on + /// a page the title unmapped meanwhile where a read in place would fault: + /// the title unmaps heap pages too.) + /// + /// # Safety + /// No other call beside this one has any of these slots. + pub(crate) unsafe fn changes(&self, first: u32, records: &[u8], out: &mut Vec) { + let at = first as usize * self.step; + let end = (at + records.len()).min(self.len); + if at >= end { + return; + } + // SAFETY: within the records held; the caller's slots alone. + let last = unsafe { std::slice::from_raw_parts_mut(self.at.add(at), end - at) }; + changed_records(last, &records[..end - at], self.step, first, out); + } +} + /// The records (`step` bytes each, the first is slot `first`) that differ /// between `last` and `records` (of one length) go into `out` and `last`. /// Most of a changed page is as it was: it is looked at sixteen records at a diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 239f576..9ee1494 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -484,12 +484,19 @@ pub(super) fn cut_for(runs: &[&HostList]) -> Option { /// 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. -fn mapped(from: usize, to: usize, room: &mut Vec) -> bool { - if room.len() < to - from { - room.resize(to - from, 0); - } - read_into(from as *const u8, &mut room[..to - from]) +/// `known`: pages that could be, of the same submission: its fills' places +/// lie eight to a page, and each was read whole to find out. +fn mapped(from: usize, to: usize, known: &mut HashMap) -> bool { + const PAGE: usize = 4096; + (from / PAGE..to.div_ceil(PAGE)).all(|page| { + known.contains_key(&page) || { + let there = read_into((page * PAGE).max(from) as *const u8, &mut [0]); + if there { + known.insert(page, ()); + } + there + } + }) } /// A table by addresses and numbers of ours. @@ -697,7 +704,7 @@ impl Host { // Some 2,800 fills a frame, of a few hundred places: what holds each // is looked for once, as long as no copy is added to the writers. let mut held: HashMap<(usize, usize), Arc> = HashMap::default(); - let mut room = Vec::new(); + let mut room = HashMap::default(); let mut end = 0u64; for &(i, level) in &chosen { let Some(((src, _), (dst, _))) = reads_writes(&does[i]) else { diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 33a0164..2bde585 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -340,7 +340,7 @@ pub(crate) fn each_under(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`, 4 with this one; 1: +/// kept for making descriptors (`VICTORY_VIEW_THREADS`, 4 with this one, 6 for records; 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. @@ -348,7 +348,7 @@ 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); + let threads = std::env::var("VICTORY_VIEW_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(if records { 6usize } else { 4 }); Pool::new(if records { "victory-records" } else { "victory-views" }, threads.clamp(1, 16)) }) .each(count, f); From 3b30d6f2cddf8fe9f38f5cff2ed1f6008c41914b Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 16:13:05 -0600 Subject: [PATCH 419/445] README, findings and a start script of this fork; fxceless' README kept in docs; the translator's file may be 640 KiB Co-Authored-By: Claude Opus 5.5 --- README.md | 427 ++++++++++------------------------------ docs/README-fxceless.md | 336 +++++++++++++++++++++++++++++++ docs/asset-policy.md | 2 +- docs/findings.md | 111 +++++++++++ scripts/play.ps1 | 38 ++++ xtask/src/policy.rs | 3 +- 6 files changed, 593 insertions(+), 324 deletions(-) create mode 100644 docs/README-fxceless.md create mode 100644 docs/findings.md create mode 100644 scripts/play.ps1 diff --git a/README.md b/README.md index fc6022e..d347b4a 100644 --- a/README.md +++ b/README.md @@ -1,332 +1,115 @@ -# VIctory fork (work in progress) +# VIctory on an RX 7900 XTX -A work-in-progress fork of [VIctory](https://github.com/Marvisak/VIctory), a -compatibility layer that runs an Xbox Series title natively on Windows from -files the user supplies. This fork follows upstream -`main` and adds fixes aimed at one goal: getting the game's world to render -correctly and playably on one particular PC. +A fork of [VIctory](https://github.com/Marvisak/VIctory), a compatibility layer +that runs an Xbox Series title natively on Windows from files the user supplies. +This one is about **speed on AMD RDNA 3**: the world at 30 frames a second on +one PC, without giving up the picture. It is not there yet. **This repository contains no game files, code or assets.** You need your own -copy of the game. It is not affiliated with or endorsed by the game's -developer or publisher. +copy of the game. It is not affiliated with or endorsed by the game's developer +or publisher. + +## Where it stands (2026-11-25) + +Tested on one machine only: Windows 11, Intel i9-12900K, 64 GB RAM, Radeon +RX 7900 XTX, 1440p, the Series X profile. + +| | | +|---|---| +| Menus, videos, loading screens | 30 fps | +| Prologue, indoors | 50-75 ms a frame (13-20 fps) | +| First mission with the boat | 46-53 ms (19-22 fps) | +| Street chase with many cars and people | 100-165 ms (6-10 fps), single frames far longer | +| Outdoors on foot, the camp | 60-90 ms | +| Flying | 42-57 ms | +| Longest session so far | 41 minutes, no crash | +| Memory | 40-46 GB of private memory: **64 GB of RAM recommended** | + +It started at 280 ms a frame in the same scenes two days earlier. + +What is known to be wrong: + +- Trees, plants and far buildings flicker outdoors in some places. +- Rooms with little direct light are too dark without `-RayTracing`. +- Textures of what just came into view appear late while the title streams. +- The first run with a new driver or a new build stutters while the driver makes + pipelines (`victory warm` makes them ahead). +- Recording a frame in the world makes the title's own watchdog end it. + +## How to run it + +You need Windows 10/11 x64, a CPU with AVX2, a Direct3D 12 GPU with shader +model 6.6 and mesh shaders, Rust (the toolchain is pinned), the MSVC build +tools, and your own dump of the title. + +```powershell +git clone +cd +copy victory.example.toml victory.toml # then set your paths, outside this folder +cargo build --locked --profile diag -p victory --features diagnostics +scripts\play.ps1 -Exe +``` + +`scripts\play.ps1 -Safe` leaves out the newest, faster ways; try it first when +something is wrong. `-RayTracing` turns the title's ray-traced indirect light on. + +Before the first run, ahead of time (both can be stopped and go on later): + +```powershell +target\diag\victory.exe shaders # every shader translated, minutes +target\diag\victory.exe warm --used # pipelines earlier runs drew with, for a new driver or build +``` + +Commands, debugging switches and upstream's own description: +[docs/README-fxceless.md](docs/README-fxceless.md). Every `VICTORY_...` switch is +described in a comment where it is read. + +## What is different here + +In short; the reasons and the measurements are in [docs/findings.md](docs/findings.md). + +- **List calls are written down, not carried out, on the title's threads** + (`VICTORY_THIN`): eight threads of ours translate them. +- **Submissions are prepared by a thread of ours and joined** + (`VICTORY_ASYNC_SUBMIT`, `VICTORY_JOIN_PARTS`), with what can be spread over + threads spread: refreshes, compares (AVX2), descriptor records, landings. +- **What shaders wrote comes back beside the write guards**, by the dwords that + changed, on a thread of its own (`VICTORY_RELAY`, `VICTORY_LAND`). +- **Buffer fills that need bytes still on the card are done on the card** + (`VICTORY_CARD_STEPS`) instead of waiting for it. +- **The title's writes are caught more cheaply**: one view opened at a fault, + blocks that rest, places in the title's code that look before they write. +- **Textures go up on a copy queue of their own** and a slot shows one only after + its upload ran, which also ended a device loss that came every 15 minutes or so. +- **Boats float**: textures that shaders write and the title's CPU reads go back + to title memory (from fxceless and Geckomacabre, on by default here). +- **Frame record and replay** with per-pass times and shader variants compared + turn by turn ([docs/replay.md](docs/replay.md)). ## Credits +This is a tree of other people's work with more on top. The history is kept, and +commits taken from elsewhere name the commit and its author. + - **[VIctory](https://github.com/Marvisak/VIctory)** by Marvisak and its - contributors is the base of everything here: the loader, the runtime - services, the Direct3D 12 back end and the shader recompiler. Licensed - GPL-3.0-or-later; so is this fork. Upstream's history is kept intact below - the single commit that carries this fork's changes. -- **[XCL](https://github.com/ivall/xcl)** by ivall and its contributors - (GPL-2.0-only) was used as a reference for how the same title behaves under - another layer. Fixes inspired by it were written anew in VIctory's code. -- The guard over every view of a memory page is code by **myokex** - ([victory-amd](https://github.com/myokex/victory-amd), commit `c6dc4d8`), which - adapts pull request #115 here by Spexivus, its correction by joroyt and a part of - VIctory #1122 by tightfall. The read-beside fix for kernel reads into title - memory is by **Joshua Odom** (commit `10ea38e` of the same fork family). Both - are carried here unchanged apart from one merge conflict. -- This fork's changes were developed with [Claude Code](https://claude.com/claude-code). - -## Status of this fork (2026-11-25) - -**Not playable yet: 2.5 to 4 frames per second, and shadowed areas are black.** -Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, -32 GB RAM. The Series X profile is used throughout. - -| Stage | State in this fork | -|-------|--------------------| -| Boot, menus, start screen | works, 30 fps (as upstream) | -| Opening cutscene | plays from start to finish, in order, lit: title cards, credits cards, night and dusk shots | -| Saves | the game autosaves a checkpoint and loads it again | -| First gameplay scene (the prologue) | renders: characters, textures, sky, sunlit exterior; HUD, pause menu and pad input work | -| Light in shadow | missing: the game's ray-traced bounce light and ray-traced lamp and sun shadows do not run yet, so anything the sun does not hit directly is black | -| Frame rate in the world | 2-4 fps: 420-450 ms per frame by default, 240-350 ms with the newer switches (`VICTORY_RELAY=2`, or `VICTORY_LATE_WAIT=3 VICTORY_WIDE_BACK=1 VICTORY_CARD_BUFFERS_MIN_MB=1 VICTORY_CARD_BUFFERS_MB=1024`); it started at 3-6 seconds per frame | -| Stability | no driver hang or device loss in normal runs (a hang introduced by the wave64 update was found and fixed: its barrier form for 64-lane programs is now off unless `VICTORY_WAVE_WIDE=1`) | - -### Newest (2026-11-25, later the same day) - -**Update, the same night: the first room now renders right on the test -machine** (walls, textures, people, lamps), at 190 to 450 ms a frame (2 to 5 -frames a second): the picture work has caught up, the frame rate has not. -What did it, on top of the list below: -- Descriptor records the title copies into its heap as plain bytes are - mirrored before every submission (pull request #305 by Flyander, after - upstream VIctory 86a5ed6). Measured here: about 40,000 records a frame - that no call had announced; their host slots were empty or stale. -- A buffer view that does not start on an element of its buffer's host - copy gets a copy of its own bytes instead of being refused (after - upstream 86a5ed6): 3 to 6 such views a frame. -- Room on the card is kept for the render targets and buffer copies a - world makes in its first frame: 98 buffer copies are made (945 MB) where - the runs before made 1, and the processor no longer compares 550 to - 710 MB a frame looking for shader writes (25 MB now). -- Levels on demand ran on the card for the first time - (`VICTORY_LEVELS_ON_DEMAND=1`, still off by default; with the fixes of - pull request #747 by AscilCH): 3.1 GB of the card not allocated for - texture levels the title does not hold, no device loss. -- Guarded blocks under storage writes are opened by default; 14 more - shader programs translate; a program is translated with first-half - interpolation pairs only if it was refused for one (with that on for - every program, 8,551 working pixel programs came out changed). -- Known and counted, not fixed yet: an indirect compute pass asks for - about 77,500 thread groups in x where one dispatch runs 65,535 (the - rest is cut off). - -Memory sync between the title's memory and the copies on the card: -- **A write through one view of a physical page is seen by the copies taken - through its other views** (`VICTORY_VIEW_GUARD=0` turns it off). The title - shows one page at several addresses and a copy was guarded at one of them - only. Measured on the test machine: 0.8 to 1.0 million such writes in a - five-minute run, every one of which used to leave a copy stale. Since it - went in, the first room had its walls in the later frames of 4 runs out of - 4 (2 of 5 before); the room's very first shot still comes up without walls - in some runs. -- Kernel reads into title memory are read beside and copied in, so a block - guarded again in between no longer fails the read. -- Writes of the storage layer into physical pages are counted where the title - has those pages mapped (10,000 to 50,000 guarded blocks of copies lay under - them in every run) and can open the guards there: - `VICTORY_PAGE_WRITES=guards` (off by default; `1`, `slots`, `all` do more). -- Failed page-destination reads are retried (`VICTORY_DSTORAGE_RETRIES=0` = as before). - -Card memory (the test card is full from the first frame of the world: 85 to -99 % of its budget for a whole run, about 26,000 texture copies let go and -3,400 made again in five minutes, 2.8 GB of render targets that are all in -use): -- Levels on demand, **off by default** (`VICTORY_LEVELS_ON_DEMAND=1`): a - texture the title fills takes card memory only for the levels the title - holds (2.2 to 3.0 GB of the copies were levels it does not hold). Its test - runs on the software adapter; it has not run on a card yet. -- Refused texture slots are held back for a few seconds so that a pass - reaches the slots behind them (`VICTORY_FULL_CARD_PASS=0` = as before); - room can be kept for the card copies of title buffers - (`VICTORY_CARD_ROOM_FOR_BUFFERS=1`, off). - -Tools and diagnostics: -- `victory translate --warm all --jobs N` translates every - shader ahead of a run, on the processor only (about 4.5 to 6.5 minutes - here); the shader cache is keyed on the translator's source, so a new - build that does not touch the translator starts warm. -- Counters, all off or diagnostics-only: `VICTORY_MERGE_RACE=1` (title bytes - a copy-back is about to put back to older values: none found in 138,000 - copy-backs), `VICTORY_WALLS_TRACE`, `VICTORY_CARD_ACCOUNTING`, and a census - of the copies the texture sweep never lets go. - -### What this fork changed (summary) - -Rendering: -- Meshlet culling read its scene buffers as the wrong kind of view, so the world drew almost nothing; fixed. -- Per-draw descriptor tables could run out, after which draws used slots never made for them and the card hung; fixed. -- Light packed by the game's compute shaders was read back through empty copies (sky, probes, fog); fixed for every mip level and layer. -- The fog reconstruction, shadow-mask, hair, blend-shape skinning, fire and several material programs did not translate; fixed. -- Gathers at a named mip level (with and without an offset) read level 0; fixed. -- Implicit-level samples outside pixel shaders produced invalid DXIL in 730 compute programs; fixed. -- Rectangle lists, depth and stencil twins for depth textures written by compute, texture read-backs. -- Ray tracing, in progress and off by default: the game's own structure-builder programs translate, title memory can be read by raw address from shaders, the hardware ray/box and ray/triangle test is emulated in DXIL (checked against a reference on the GPU), and 59 of the 64 trace programs translate. Nothing is lit by it yet. See [docs/fork-ray-tracing.md](docs/fork-ray-tracing.md). - -Speed and memory: -- Waits for memory values, write-watch queries and page queries no longer walk page tables per call. -- Large title buffers get a copy in card memory, with shader writes found by hashing on the card. -- Submissions can be sent ahead of the wait for the card (`VICTORY_LATE_WAIT`), with a relay thread that lands results as the card finishes (`VICTORY_RELAY`): in a first five-minute run the card's idle time behind the submitting thread fell from about 136 to 30 ms per frame. -- Independent host-copy refreshes run in parallel by default on systems with at least four logical CPUs (`VICTORY_WIDE_REFRESH=0` disables this; `=1` forces it). This targets the serial memory reads that previously cost about 45–50 ms per frame on the test run. -- Title memory can be opened as a graphics heap so that buffers are used in place instead of copied (`VICTORY_INPLACE`, first stage only; a probe confirmed the approach on the test GPU). -- The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory. -- An intermittent device loss was traced to the pipeline library file being replaced while mapped; fixed. - -- Translated shaders get clean-up passes over the finished module (dead code, constant folding, reuse of values, branch facts); the pack's host instruction count falls by about 43 %, worth about 20 ms of GPU time per frame on the test machine (`VICTORY_SHADER_OPT=0` turns them off). - -Most of the newer speed changes sit behind environment switches that are off -by default (`VICTORY_LATE_WAIT`, `VICTORY_RELAY`, `VICTORY_WIDE_BACK`, -`VICTORY_CARD_BUFFERS_MIN_MB`, `VICTORY_INPLACE`, `VICTORY_BVH_BUILDER`, ...). -Independent host-copy refreshes are the exception: they use parallel workers -automatically on systems with at least four logical CPUs. Each switch is -described in a comment where it is read. - -### Known problems - -- Everything in shadow is black (see above). -- The interior of the first gameplay room is sometimes not drawn after the cutscene hands over to gameplay. -- Around 24 GB of memory is in use during play. -- A few style lints are switched off for this fork in the workspace `Cargo.toml` until the newer code is tidied. -- Many changes here are specific to this title and this GPU, and some are marked `shortcut:` in the code where they approximate what the console does. - -Everything below this line is upstream VIctory's own README, unchanged; its -status section describes upstream, not this fork. - ---- - -# VIctory - -Runs the title (Xbox Series X|S) natively on Windows, from files -the user supplies. - -The title's x86-64 code runs unchanged inside our process; VIctory supplies -the platform underneath it and converts the title's data, ahead of time where -it can (shaders and pipelines too, see Getting started) and on first use -otherwise. See [docs/architecture.md](docs/architecture.md). - -## Status (2026-11-24) - -**Not playable yet.** The title boots, runs its menus at its own 30 fps, -loads the world and shows it: slowly, and with rendering defects. - -| Stage | State | -|-------|-------| -| Boot, first-boot screens (accessibility, language, settings, legal) | works, 30 fps | -| Intro video with sound | works | -| Start screen, profile and saves | works | -| Loading into the world (about 50 s) | works | -| The world (first mission's intro) | drawn and shown: streets, buildings, vehicles, characters, the title card and credits; 1-2 s per frame. Surfaces are unlit, a band of distant geometry is missing, characters come out broken in some shots | - -Tested on one machine: Windows 11, AMD RX 6700 XT. - -> **Warning.** Entering the world on a real GPU has hung it in earlier -> builds, and Windows then resets the display driver (every monitor goes -> black for a moment). The latest runs did not, but it is not ruled out; a -> run can also end on a GPU fault (`crashes.log`). A diagnostics build with -> `VICTORY_D3D12_WARP=1` renders on the software adapter instead (too slow -> to reach the world in minutes). - -What each part does today and what it still needs: - -| Subsystem | Today | Needs | -|-----------|-------|-------| -| Loader | Runs the title's executable and its DLLs in our process; crash reports name the faulting code and are kept in `crashes.log` | – | -| Runtime services | One signed-in offline user, licences, packages, saves that survive a kill at any step, text entry dialog | Speech is silent; the dialog and relaunch are untested live | -| Network | Offline by design: the title cannot reach the network | – | -| Files and streaming | Archives and streamed data read, zlib and BCPack decoded in parallel | Loading is limited by writes into title memory | -| Input | XInput pads, keyboard, keyboard stand-in pad | Trigger rumble | -| Audio | Menu, video and loading sound; XMA voices and Opus streams decode | Reverb is silent; Opus results unverified against the title | -| GPU: menus | Draws, compute and presentation on host D3D12; only changed title memory is copied | Frame pacing drifts on one screen in release builds | -| GPU: world | The scene is drawn and presented: mesh pipelines, indirect execution, views the shaders pick from the heap themselves, title memory read by address (ray-tracing structures), depth written from compute, pipelines pre-built or made by worker threads and kept on disk | Lighting (surfaces are unlit) and some missing geometry; frames take 1-2 s; draws of untranslated shaders are dropped; real queries, depth bounds, HDR and scaling are missing | -| Shaders | Console GPU code recompiled to DXIL, ahead of time (`translate --cache`) or at first use, cached on disk. Menus: all. World: mesh 8,765 of 8,765, vertex/pixel 12,550 of 12,592, compute 2,579 of 2,637 | Merged geometry stages (195 programs) and about 100 others; fused multiply-adds follow the host GPU; some compute programs need a GPU with 64-lane waves | -| Textures | Console tiled layouts and detiling for the modes the title uses | Render-target metadata planes | -| Series S mode | Runs through the menus to the loading screen | The world, as above | - -## Getting started - -Requirements: Windows 10/11 x64, a CPU with AVX2, a Direct3D 12 GPU with -shader model 6.6 (and mesh shaders for the world), Rust (pinned in -`rust-toolchain.toml`). - -To install Rust, use rustup (`winget install --id Rustlang.Rustup -e`, or -the installer from https://rustup.rs). The first `cargo` command in this -repository then fetches the pinned toolchain. Building needs the MSVC C++ -build tools: Visual Studio or its Build Tools with the "Desktop development -with C++" workload. - -The title also needs several GiB of available Windows commit at startup. -Check **Committed** under **Task Manager → Performance → Memory**. If -`crashes.log` reports Windows error 1455, close other applications or increase -the Windows paging file size, then retry. - -```powershell -cargo xtask install-hooks # asset-policy check on every commit -copy victory.example.toml victory.toml # then set your paths (outside the repo) -cargo test --workspace # needs no game data -cargo run -p victory -- config # check your paths -``` - -Run the title: - -```powershell -cargo build --release -p victory -target\release\victory.exe run \ --execute -``` - -The window caption shows the framerate. Saves, settings and `crashes.log` -are kept under the data folder (default `%LOCALAPPDATA%\victory\data`), derived -data under the cache folder. - -Set `VICTORY_WINDOW_MAX=1920x1080` before launching to limit the title's -top-level window to that bounding box. Smaller windows keep their size, -larger windows keep their proportions, and the monitor's work area still -limits them. This scales the displayed image; it does not change the -console render resolution or the swap-chain buffers. With the variable -unset, window sizing is unchanged. - -Input: XInput pads. With none connected the keyboard is a pad while the -title's window has focus: - -| Keys | Pad | -|------|-----| -| W A S D / I J K L | left / right stick | -| arrows | D-pad | -| Enter, Backspace, X, Y | A, B, X, Y | -| Q / E, Z / C | shoulders, triggers | -| F / H | stick clicks | -| Esc, Tab | Menu, View | - -## Commands - -``` -victory inspect [--imports] [--exports] -victory census [paths...] [--missing] [--strict] -victory lib-exports [--list] -victory shader-info [paths...] [--verbose] [--disasm] -victory translate [paths...] [--validate] [--pipelines] [--list] [--jobs N] -victory run [--execute] [--unimplemented trap|zero] [--strict] - [--console series-x|series-s] [-- ] -victory config -``` - -Logging: `VICTORY_LOG=victory_loader=trace,info` (a release build logs -info and above). - -### Windows shader-test validator - -The shader tests use `dxil.dll` to validate Shader Model 6.6 containers. -An older Windows SDK validator can load successfully but reject them with -`Unknown shader model 'ps_6_6'`. If this happens, use a current x64 validator -from [Microsoft's DirectX Shader Compiler releases](https://github.com/microsoft/DirectXShaderCompiler/releases) -or a current Windows SDK. Set its path for the test session: - -```powershell -$env:VICTORY_DXIL = 'C:\tools\dxc\bin\x64\dxil.dll' -cargo test -p victory-shader --lib --locked -- --test-threads=1 -``` - -Without this override, the validator loader selects the newest installed -Windows SDK's `bin/<version>/x64/dxil.dll`, then falls back to the DLL search -path when no SDK copy is found. This is a test/offline-validation dependency; -the translated shaders do not require it at runtime. - -## Debugging - -A release build has no debugging aids. Build them in with - -```powershell -cargo build --profile diag -p victory --features diagnostics # target\diag\victory.exe -``` - -The on/off switches below (`...=1`) are off when unset or set to `0`. - -| Variable | Effect | -|----------|--------| -| `VICTORY_LOG=<target>=debug,...` | debug and trace output | -| `VICTORY_STACKS=20,60` | every thread's stack at those seconds | -| `VICTORY_WATCH=<rva>,...` | logs a title u32 when it changes | -| `VICTORY_POKE=<rva>:<byte>,...` | writes a title byte twice a second (a hang watchdog's tick, say) | -| `VICTORY_KEYS=30:Enter,35:X` | presses keys at those seconds, focus or not | -| `VICTORY_CRASH_SAVE=<rva>:<len>,...` | saves title memory to the cache folder on a crash | -| `VICTORY_CAPTURE=<dir>` | saves presented frames (powers of two, or `VICTORY_CAPTURE_FRAMES=<list>`) | -| `VICTORY_DUMP_TARGETS=1` | with the two above, saves every render target of those frames | -| `VICTORY_D3D12_DEBUG=1` | host debug layer | -| `VICTORY_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) | -| `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | -| `VICTORY_PIPELINE_WAIT_MS=24` | reduce the per-frame wait for background pipeline creation from the default of 500 ms. A draw can be omitted until its pipeline is ready | -| `VICTORY_SKIP_PIPELINES=<hash>,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash | -| `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands | -| `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | -| `VICTORY_SHADER_LOOP_LIMIT=<n>` | translated shader loops stop after `n` iterations per lane instead of 2^20 (own shader cache entries); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow | -| `VICTORY_AUDIO_CAPTURE=<file.wav>` | records what the title plays (our process only) | -| `VICTORY_XMA_DUMP=<dir>` | saves the first 32 XMA voices' context and input | - -Every build appends crashes and host GPU failures to `crashes.log` in the -title's data folder. + contributors: the loader, the runtime services, the Direct3D 12 back end and + the shader recompiler. +- **[fxceless/victory-fork](https://github.com/fxceless/victory-fork)**: the fork + this one started from, and the people whose pull requests it carries. +- **[DexNom/VIctory](https://github.com/DexNom/VIctory)**: ray tracing fixes, + cube gradients, sparse textures. +- **[Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD)**: + the ambient light idea, pipeline workers, and work by romainhedouin. +- **[FQY55kai/ZJOU-VICTORY](https://github.com/FQY55kai/ZJOU-VICTORY)**. +- **[myokex/victory-amd](https://github.com/myokex/victory-amd)**: the guard over + every view of a page (with Spexivus, joroyt and tightfall), and Joshua Odom's + reads into title memory. +- **Geckomacabre** and **cxy0072019-sketch**: the texture read-back. +- **[XCL](https://github.com/ivall/xcl)** (GPL-2.0-only) was read for how the same + title behaves under another layer; no code of it is here. +- This fork's changes were made with [Claude Code](https://claude.com/claude-code). ## License -GPL-3.0-or-later. See [LICENSE](LICENSE). - +GPL-3.0-or-later, as VIctory. See [LICENSE](LICENSE); the one file that is not +covered is named in [docs/asset-policy.md](docs/asset-policy.md). diff --git a/docs/README-fxceless.md b/docs/README-fxceless.md new file mode 100644 index 0000000..44885da --- /dev/null +++ b/docs/README-fxceless.md @@ -0,0 +1,336 @@ +> This is the README of fxceless/victory-fork as this fork had it, kept for its +> description of upstream, the commands and the debugging switches. What it says of +> speed and state is of that fork and another PC; this fork: [README](../README.md). + +# VIctory fork (work in progress) + +A work-in-progress fork of [VIctory](https://github.com/Marvisak/VIctory), a +compatibility layer that runs an Xbox Series title natively on Windows from +files the user supplies. This fork follows upstream +`main` and adds fixes aimed at one goal: getting the game's world to render +correctly and playably on one particular PC. + +**This repository contains no game files, code or assets.** You need your own +copy of the game. It is not affiliated with or endorsed by the game's +developer or publisher. + +## Credits + +- **[VIctory](https://github.com/Marvisak/VIctory)** by Marvisak and its + contributors is the base of everything here: the loader, the runtime + services, the Direct3D 12 back end and the shader recompiler. Licensed + GPL-3.0-or-later; so is this fork. Upstream's history is kept intact below + the single commit that carries this fork's changes. +- **[XCL](https://github.com/ivall/xcl)** by ivall and its contributors + (GPL-2.0-only) was used as a reference for how the same title behaves under + another layer. Fixes inspired by it were written anew in VIctory's code. +- The guard over every view of a memory page is code by **myokex** + ([victory-amd](https://github.com/myokex/victory-amd), commit `c6dc4d8`), which + adapts pull request #115 here by Spexivus, its correction by joroyt and a part of + VIctory #1122 by tightfall. The read-beside fix for kernel reads into title + memory is by **Joshua Odom** (commit `10ea38e` of the same fork family). Both + are carried here unchanged apart from one merge conflict. +- This fork's changes were developed with [Claude Code](https://claude.com/claude-code). + +## Status of this fork (2026-11-25) + +**Not playable yet: 2.5 to 4 frames per second, and shadowed areas are black.** +Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, +32 GB RAM. The Series X profile is used throughout. + +| Stage | State in this fork | +|-------|--------------------| +| Boot, menus, start screen | works, 30 fps (as upstream) | +| Opening cutscene | plays from start to finish, in order, lit: title cards, credits cards, night and dusk shots | +| Saves | the game autosaves a checkpoint and loads it again | +| First gameplay scene (the prologue) | renders: characters, textures, sky, sunlit exterior; HUD, pause menu and pad input work | +| Light in shadow | missing: the game's ray-traced bounce light and ray-traced lamp and sun shadows do not run yet, so anything the sun does not hit directly is black | +| Frame rate in the world | 2-4 fps: 420-450 ms per frame by default, 240-350 ms with the newer switches (`VICTORY_RELAY=2`, or `VICTORY_LATE_WAIT=3 VICTORY_WIDE_BACK=1 VICTORY_CARD_BUFFERS_MIN_MB=1 VICTORY_CARD_BUFFERS_MB=1024`); it started at 3-6 seconds per frame | +| Stability | no driver hang or device loss in normal runs (a hang introduced by the wave64 update was found and fixed: its barrier form for 64-lane programs is now off unless `VICTORY_WAVE_WIDE=1`) | + +### Newest (2026-11-25, later the same day) + +**Update, the same night: the first room now renders right on the test +machine** (walls, textures, people, lamps), at 190 to 450 ms a frame (2 to 5 +frames a second): the picture work has caught up, the frame rate has not. +What did it, on top of the list below: +- Descriptor records the title copies into its heap as plain bytes are + mirrored before every submission (pull request #305 by Flyander, after + upstream VIctory 86a5ed6). Measured here: about 40,000 records a frame + that no call had announced; their host slots were empty or stale. +- A buffer view that does not start on an element of its buffer's host + copy gets a copy of its own bytes instead of being refused (after + upstream 86a5ed6): 3 to 6 such views a frame. +- Room on the card is kept for the render targets and buffer copies a + world makes in its first frame: 98 buffer copies are made (945 MB) where + the runs before made 1, and the processor no longer compares 550 to + 710 MB a frame looking for shader writes (25 MB now). +- Levels on demand ran on the card for the first time + (`VICTORY_LEVELS_ON_DEMAND=1`, still off by default; with the fixes of + pull request #747 by AscilCH): 3.1 GB of the card not allocated for + texture levels the title does not hold, no device loss. +- Guarded blocks under storage writes are opened by default; 14 more + shader programs translate; a program is translated with first-half + interpolation pairs only if it was refused for one (with that on for + every program, 8,551 working pixel programs came out changed). +- Known and counted, not fixed yet: an indirect compute pass asks for + about 77,500 thread groups in x where one dispatch runs 65,535 (the + rest is cut off). + +Memory sync between the title's memory and the copies on the card: +- **A write through one view of a physical page is seen by the copies taken + through its other views** (`VICTORY_VIEW_GUARD=0` turns it off). The title + shows one page at several addresses and a copy was guarded at one of them + only. Measured on the test machine: 0.8 to 1.0 million such writes in a + five-minute run, every one of which used to leave a copy stale. Since it + went in, the first room had its walls in the later frames of 4 runs out of + 4 (2 of 5 before); the room's very first shot still comes up without walls + in some runs. +- Kernel reads into title memory are read beside and copied in, so a block + guarded again in between no longer fails the read. +- Writes of the storage layer into physical pages are counted where the title + has those pages mapped (10,000 to 50,000 guarded blocks of copies lay under + them in every run) and can open the guards there: + `VICTORY_PAGE_WRITES=guards` (off by default; `1`, `slots`, `all` do more). +- Failed page-destination reads are retried (`VICTORY_DSTORAGE_RETRIES=0` = as before). + +Card memory (the test card is full from the first frame of the world: 85 to +99 % of its budget for a whole run, about 26,000 texture copies let go and +3,400 made again in five minutes, 2.8 GB of render targets that are all in +use): +- Levels on demand, **off by default** (`VICTORY_LEVELS_ON_DEMAND=1`): a + texture the title fills takes card memory only for the levels the title + holds (2.2 to 3.0 GB of the copies were levels it does not hold). Its test + runs on the software adapter; it has not run on a card yet. +- Refused texture slots are held back for a few seconds so that a pass + reaches the slots behind them (`VICTORY_FULL_CARD_PASS=0` = as before); + room can be kept for the card copies of title buffers + (`VICTORY_CARD_ROOM_FOR_BUFFERS=1`, off). + +Tools and diagnostics: +- `victory translate <shader file> --warm all --jobs N` translates every + shader ahead of a run, on the processor only (about 4.5 to 6.5 minutes + here); the shader cache is keyed on the translator's source, so a new + build that does not touch the translator starts warm. +- Counters, all off or diagnostics-only: `VICTORY_MERGE_RACE=1` (title bytes + a copy-back is about to put back to older values: none found in 138,000 + copy-backs), `VICTORY_WALLS_TRACE`, `VICTORY_CARD_ACCOUNTING`, and a census + of the copies the texture sweep never lets go. + +### What this fork changed (summary) + +Rendering: +- Meshlet culling read its scene buffers as the wrong kind of view, so the world drew almost nothing; fixed. +- Per-draw descriptor tables could run out, after which draws used slots never made for them and the card hung; fixed. +- Light packed by the game's compute shaders was read back through empty copies (sky, probes, fog); fixed for every mip level and layer. +- The fog reconstruction, shadow-mask, hair, blend-shape skinning, fire and several material programs did not translate; fixed. +- Gathers at a named mip level (with and without an offset) read level 0; fixed. +- Implicit-level samples outside pixel shaders produced invalid DXIL in 730 compute programs; fixed. +- Rectangle lists, depth and stencil twins for depth textures written by compute, texture read-backs. +- Ray tracing, in progress and off by default: the game's own structure-builder programs translate, title memory can be read by raw address from shaders, the hardware ray/box and ray/triangle test is emulated in DXIL (checked against a reference on the GPU), and 59 of the 64 trace programs translate. Nothing is lit by it yet. See [docs/fork-ray-tracing.md](fork-ray-tracing.md). + +Speed and memory: +- Waits for memory values, write-watch queries and page queries no longer walk page tables per call. +- Large title buffers get a copy in card memory, with shader writes found by hashing on the card. +- Submissions can be sent ahead of the wait for the card (`VICTORY_LATE_WAIT`), with a relay thread that lands results as the card finishes (`VICTORY_RELAY`): in a first five-minute run the card's idle time behind the submitting thread fell from about 136 to 30 ms per frame. +- Independent host-copy refreshes run in parallel by default on systems with at least four logical CPUs (`VICTORY_WIDE_REFRESH=0` disables this; `=1` forces it). This targets the serial memory reads that previously cost about 45–50 ms per frame on the test run. +- Title memory can be opened as a graphics heap so that buffers are used in place instead of copied (`VICTORY_INPLACE`, first stage only; a probe confirmed the approach on the test GPU). +- The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory. +- An intermittent device loss was traced to the pipeline library file being replaced while mapped; fixed. + +- Translated shaders get clean-up passes over the finished module (dead code, constant folding, reuse of values, branch facts); the pack's host instruction count falls by about 43 %, worth about 20 ms of GPU time per frame on the test machine (`VICTORY_SHADER_OPT=0` turns them off). + +Most of the newer speed changes sit behind environment switches that are off +by default (`VICTORY_LATE_WAIT`, `VICTORY_RELAY`, `VICTORY_WIDE_BACK`, +`VICTORY_CARD_BUFFERS_MIN_MB`, `VICTORY_INPLACE`, `VICTORY_BVH_BUILDER`, ...). +Independent host-copy refreshes are the exception: they use parallel workers +automatically on systems with at least four logical CPUs. Each switch is +described in a comment where it is read. + +### Known problems + +- Everything in shadow is black (see above). +- The interior of the first gameplay room is sometimes not drawn after the cutscene hands over to gameplay. +- Around 24 GB of memory is in use during play. +- A few style lints are switched off for this fork in the workspace `Cargo.toml` until the newer code is tidied. +- Many changes here are specific to this title and this GPU, and some are marked `shortcut:` in the code where they approximate what the console does. + +Everything below this line is upstream VIctory's own README, unchanged; its +status section describes upstream, not this fork. + +--- + +# VIctory + +Runs the title (Xbox Series X|S) natively on Windows, from files +the user supplies. + +The title's x86-64 code runs unchanged inside our process; VIctory supplies +the platform underneath it and converts the title's data, ahead of time where +it can (shaders and pipelines too, see Getting started) and on first use +otherwise. See [docs/architecture.md](architecture.md). + +## Status (2026-11-24) + +**Not playable yet.** The title boots, runs its menus at its own 30 fps, +loads the world and shows it: slowly, and with rendering defects. + +| Stage | State | +|-------|-------| +| Boot, first-boot screens (accessibility, language, settings, legal) | works, 30 fps | +| Intro video with sound | works | +| Start screen, profile and saves | works | +| Loading into the world (about 50 s) | works | +| The world (first mission's intro) | drawn and shown: streets, buildings, vehicles, characters, the title card and credits; 1-2 s per frame. Surfaces are unlit, a band of distant geometry is missing, characters come out broken in some shots | + +Tested on one machine: Windows 11, AMD RX 6700 XT. + +> **Warning.** Entering the world on a real GPU has hung it in earlier +> builds, and Windows then resets the display driver (every monitor goes +> black for a moment). The latest runs did not, but it is not ruled out; a +> run can also end on a GPU fault (`crashes.log`). A diagnostics build with +> `VICTORY_D3D12_WARP=1` renders on the software adapter instead (too slow +> to reach the world in minutes). + +What each part does today and what it still needs: + +| Subsystem | Today | Needs | +|-----------|-------|-------| +| Loader | Runs the title's executable and its DLLs in our process; crash reports name the faulting code and are kept in `crashes.log` | – | +| Runtime services | One signed-in offline user, licences, packages, saves that survive a kill at any step, text entry dialog | Speech is silent; the dialog and relaunch are untested live | +| Network | Offline by design: the title cannot reach the network | – | +| Files and streaming | Archives and streamed data read, zlib and BCPack decoded in parallel | Loading is limited by writes into title memory | +| Input | XInput pads, keyboard, keyboard stand-in pad | Trigger rumble | +| Audio | Menu, video and loading sound; XMA voices and Opus streams decode | Reverb is silent; Opus results unverified against the title | +| GPU: menus | Draws, compute and presentation on host D3D12; only changed title memory is copied | Frame pacing drifts on one screen in release builds | +| GPU: world | The scene is drawn and presented: mesh pipelines, indirect execution, views the shaders pick from the heap themselves, title memory read by address (ray-tracing structures), depth written from compute, pipelines pre-built or made by worker threads and kept on disk | Lighting (surfaces are unlit) and some missing geometry; frames take 1-2 s; draws of untranslated shaders are dropped; real queries, depth bounds, HDR and scaling are missing | +| Shaders | Console GPU code recompiled to DXIL, ahead of time (`translate --cache`) or at first use, cached on disk. Menus: all. World: mesh 8,765 of 8,765, vertex/pixel 12,550 of 12,592, compute 2,579 of 2,637 | Merged geometry stages (195 programs) and about 100 others; fused multiply-adds follow the host GPU; some compute programs need a GPU with 64-lane waves | +| Textures | Console tiled layouts and detiling for the modes the title uses | Render-target metadata planes | +| Series S mode | Runs through the menus to the loading screen | The world, as above | + +## Getting started + +Requirements: Windows 10/11 x64, a CPU with AVX2, a Direct3D 12 GPU with +shader model 6.6 (and mesh shaders for the world), Rust (pinned in +`rust-toolchain.toml`). + +To install Rust, use rustup (`winget install --id Rustlang.Rustup -e`, or +the installer from https://rustup.rs). The first `cargo` command in this +repository then fetches the pinned toolchain. Building needs the MSVC C++ +build tools: Visual Studio or its Build Tools with the "Desktop development +with C++" workload. + +The title also needs several GiB of available Windows commit at startup. +Check **Committed** under **Task Manager → Performance → Memory**. If +`crashes.log` reports Windows error 1455, close other applications or increase +the Windows paging file size, then retry. + +```powershell +cargo xtask install-hooks # asset-policy check on every commit +copy victory.example.toml victory.toml # then set your paths (outside the repo) +cargo test --workspace # needs no game data +cargo run -p victory -- config # check your paths +``` + +Run the title: + +```powershell +cargo build --release -p victory +target\release\victory.exe run <game dir>\<the title's exe> --execute +``` + +The window caption shows the framerate. Saves, settings and `crashes.log` +are kept under the data folder (default `%LOCALAPPDATA%\victory\data`), derived +data under the cache folder. + +Set `VICTORY_WINDOW_MAX=1920x1080` before launching to limit the title's +top-level window to that bounding box. Smaller windows keep their size, +larger windows keep their proportions, and the monitor's work area still +limits them. This scales the displayed image; it does not change the +console render resolution or the swap-chain buffers. With the variable +unset, window sizing is unchanged. + +Input: XInput pads. With none connected the keyboard is a pad while the +title's window has focus: + +| Keys | Pad | +|------|-----| +| W A S D / I J K L | left / right stick | +| arrows | D-pad | +| Enter, Backspace, X, Y | A, B, X, Y | +| Q / E, Z / C | shoulders, triggers | +| F / H | stick clicks | +| Esc, Tab | Menu, View | + +## Commands + +``` +victory inspect <exe|dll> [--imports] [--exports] +victory census [paths...] [--missing] [--strict] +victory lib-exports <import.lib> [--list] +victory shader-info [paths...] [--verbose] [--disasm] +victory translate [paths...] [--validate] [--pipelines] [--list] [--jobs N] +victory run <exe> [--execute] [--unimplemented trap|zero] [--strict] + [--console series-x|series-s] [-- <title arguments>] +victory config +``` + +Logging: `VICTORY_LOG=victory_loader=trace,info` (a release build logs +info and above). + +### Windows shader-test validator + +The shader tests use `dxil.dll` to validate Shader Model 6.6 containers. +An older Windows SDK validator can load successfully but reject them with +`Unknown shader model 'ps_6_6'`. If this happens, use a current x64 validator +from [Microsoft's DirectX Shader Compiler releases](https://github.com/microsoft/DirectXShaderCompiler/releases) +or a current Windows SDK. Set its path for the test session: + +```powershell +$env:VICTORY_DXIL = 'C:\tools\dxc\bin\x64\dxil.dll' +cargo test -p victory-shader --lib --locked -- --test-threads=1 +``` + +Without this override, the validator loader selects the newest installed +Windows SDK's `bin/<version>/x64/dxil.dll`, then falls back to the DLL search +path when no SDK copy is found. This is a test/offline-validation dependency; +the translated shaders do not require it at runtime. + +## Debugging + +A release build has no debugging aids. Build them in with + +```powershell +cargo build --profile diag -p victory --features diagnostics # target\diag\victory.exe +``` + +The on/off switches below (`...=1`) are off when unset or set to `0`. + +| Variable | Effect | +|----------|--------| +| `VICTORY_LOG=<target>=debug,...` | debug and trace output | +| `VICTORY_STACKS=20,60` | every thread's stack at those seconds | +| `VICTORY_WATCH=<rva>,...` | logs a title u32 when it changes | +| `VICTORY_POKE=<rva>:<byte>,...` | writes a title byte twice a second (a hang watchdog's tick, say) | +| `VICTORY_KEYS=30:Enter,35:X` | presses keys at those seconds, focus or not | +| `VICTORY_CRASH_SAVE=<rva>:<len>,...` | saves title memory to the cache folder on a crash | +| `VICTORY_CAPTURE=<dir>` | saves presented frames (powers of two, or `VICTORY_CAPTURE_FRAMES=<list>`) | +| `VICTORY_DUMP_TARGETS=1` | with the two above, saves every render target of those frames | +| `VICTORY_D3D12_DEBUG=1` | host debug layer | +| `VICTORY_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) | +| `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | +| `VICTORY_PIPELINE_WAIT_MS=24` | reduce the per-frame wait for background pipeline creation from the default of 500 ms. A draw can be omitted until its pipeline is ready | +| `VICTORY_SKIP_PIPELINES=<hash>,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash | +| `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands | +| `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | +| `VICTORY_SHADER_LOOP_LIMIT=<n>` | translated shader loops stop after `n` iterations per lane instead of 2^20 (own shader cache entries); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow | +| `VICTORY_AUDIO_CAPTURE=<file.wav>` | records what the title plays (our process only) | +| `VICTORY_XMA_DUMP=<dir>` | saves the first 32 XMA voices' context and input | + +Every build appends crashes and host GPU failures to `crashes.log` in the +title's data folder. + +## License + +GPL-3.0-or-later. See [LICENSE](../LICENSE). + diff --git a/docs/asset-policy.md b/docs/asset-policy.md index f87c84f..e895aad 100644 --- a/docs/asset-policy.md +++ b/docs/asset-policy.md @@ -45,7 +45,7 @@ user's dump), `test_titles`, and `cache_dir` for everything derived 1. `.gitignore` keeps common data types out of `git status`. 2. `cargo xtask policy` (run by the pre-commit hook; install with `cargo xtask install-hooks`) is an allowlist: files must have an allowed - type, be under 512 KiB, contain no binary data or known binary + type, be under 640 KiB, contain no binary data or known binary signatures, and hold no long hex/base64 runs. Exceptions need an entry with a reason in `xtask/src/policy.rs`. 3. At runtime, everything that writes derived data calls diff --git a/docs/findings.md b/docs/findings.md new file mode 100644 index 0000000..a21dc4a --- /dev/null +++ b/docs/findings.md @@ -0,0 +1,111 @@ +# What was learned on the RX 7900 XTX (2026-11-23 to 2026-11-25) + +One PC: i9-12900K (8 fast cores, 8 slow ones, 24 threads), 64 GB, Radeon RX 7900 XTX +24 GB, Windows 11, 1440p, Series X profile. Figures are of diagnostics builds with a +screenshot a second. Scenes are not the same from run to run, so read differences +under about 5 % as nothing. What a switch does is in the comment where it is read. + +## Where a frame goes + +Median of whole runs, same part of the prologue: 280 ms, then 124, 103, 75, now 46-65. +On the water (first boat mission) 46-53 ms. + +The title needs 33 ms. Of a 55 ms frame on the water: + +- **The thread that prepares submissions: 48 ms.** It is the wall. Steps of the lists + 18 (refreshes of host copies 10), steps done on the card 7, waiting for descriptor + records 6, asking the write watch 5, copies in the card's memory 4, the title's bytes + under shader writes 4. +- **The card: about 41 ms busy**, the next wall. +- **List calls: 36,000 a frame, 230 ms of work** spread over eight threads. In a street + chase 67,000 calls and 430 ms. +- Descriptor records copied as plain bytes: 400,000 slots looked at, 40,000 mirrored a + frame, most of them empty. +- Landing what shaders wrote: 16 MB a frame put as dwords, on a thread of its own. + +## The one idea behind most of it + +On the console the CPU and the graphics processor share memory. Here they do not, so +everything one writes and the other reads must be noticed and moved. Every large cost +is one of four: **noticing** writes of the title (write watch, guards), **noticing** +writes of shaders (hashes on the card, compares on the CPU), **moving** them, and +**waiting** until an order is safe. Gains came from making each of them narrower +(dwords, not pages), wider (threads, AVX2) or later (on the card, behind the frame), +in that order of size: + +| What | Frame before | after | +|---|---|---| +| Descriptor records of draws' tables left to the draws | 280 ms | about 124 | +| Our hash passes over card copies, 64 threads a piece | card 79 ms | 66 | +| Preparing on a thread of its own, refreshes and records spread | 103 | 75 | +| List calls written down and translated by eight threads (`VICTORY_THIN`) | 75 | 68 | +| Submissions joined, card steps, textures sent ahead | 68 | about 63 | +| Title bytes under shader writes compared with AVX2 on six threads | 14 ms of it | 4-7 | +| Stores into guarded memory looked at first, fewer guards reset | 69 ms of threads' time | about 6 | + +(Each figure is from the run in which it was measured; they overlap and do not add up.) + +## Faults found, and what they were + +- **Boats sank, the sea plane went under.** The ocean's height and displacement maps are + textures that compute passes write and the title's physics sample on the CPU. They were + never brought back to title memory. Fixed by Geckomacabre's read-back as merged in + fxceless/victory-fork f5c03f3b; on by default here (`VICTORY_TEXTURE_BACK=0`: off). + With it the boat stays up through a whole run; without it sank in every one. +- **A device loss about every 16 minutes**: a page fault inside a texture made in the same + tenth of a second. A slot showed it before its upload had run. + `VICTORY_SHOW_AFTER=1`; none in the sessions since (likely fixed, not proven). +- **A rare lost write** (6 of 200 runs of a stress test): a view was mapped between our + look at its guards and our lock, and views were opened one after another. None in 603 + runs after. +- **Blocky patches**: indirect dispatches cut at 65,535 groups. +- **Square holes and dashed edges in shadows**: pixel shaders that read their quad's + neighbours with wave reads; on AMD helper lanes take no part in them. +- **Cube reflections too blurred, wrong materials**: DXIL's `Log` is base 2, and + normalized buffer codes were one step off. +- **Every ray missed**: the dispatch flag that says counts are threads, not groups. + +## Measured and not worth it + +- Unordered early pipelines for everything (AMD's compiler crashed). +- Series S profile, smaller textures, a second drawing queue, `ASYNC_SUBMIT` off. +- Mapping pages on sixteen threads: no more pages mapped, frames longer. +- Scalar buffer loads four dwords a call (`VICTORY_SHADER_OPT=127`): no gain on this card. +- Wave sizes, fused multiply-adds, fast reciprocals, raw picked buffers, leaving out + barriers: nothing to 0.1 ms each. Exact RDNA float rules (`VICTORY_RDNA_FLOAT`): 0.8 ms. +- Running the console's shader code natively on the card: the Windows driver takes no raw + code, the two generations differ, and a Vulkan host layer ends at the same compiler. What + is left to gain from shader code was guessed at under 1 ms. +- An on-screen panel of numbers (`VICTORY_PANEL`): it helps finding where a frame goes but + costs some, so it is off and F3 shows it. + +## What is next + +1. The preparing thread: split what one submission does over two threads in a row; ask + for the next submission while this one is sent; view the card's own buffers where fills + copy them now. +2. The card: small buffers' copies in its own memory (`VICTORY_CARD_BUFFERS_MIN_KB=64`, + after fxceless c36971b2; not measured here yet), and the passes that run for nothing + without rays. +3. Stalls: 270-660 s of a session were full of frames over 200 ms, almost all while new + pipelines were made. `victory warm`, and a quarter of the workers for the slow ones. +4. Outdoor flicker: suspected to be one bad indirect record that uses up its list's + budget, so that every later draw of it is empty. The log's frame line counts them; + `VICTORY_INDIRECT_REST=0` is the experiment. +5. Memory, 40-46 GB private: lists' allocators 9 GB, windows 7, uploads 4 + (`VICTORY_MEMORY_MAP=1` lists it). + +## The other repositories, compared + +Read up to 2026-11-25: Marvisak/VIctory, fxceless/victory-fork, DexNom/VIctory, +Belobug/VIctory-Belobug-AMD, FQY55kai/ZJOU-VICTORY. What was taken is in the history, +each commit naming its source. In short: + +- Marvisak's commits hardly apply any more; nearly all of what they fix is here, often + another way. Taken: nearest normalized codes, d16 views, shader model flags. +- fxceless: the base. Newest taken: texture read-back, small buffers on the card, hashes + over a buffer's own bytes. +- DexNom: thread counts of ray dispatches, cube gradients, joined sparse ranges. +- Belobug: pipeline workers for screen passes, the ambient stand-in's idea, pipeline and + constant buffer bookkeeping (romainhedouin). +- ZJOU: render targets not set again; some shader corrections are being looked at. diff --git a/scripts/play.ps1 b/scripts/play.ps1 new file mode 100644 index 0000000..10fda8b --- /dev/null +++ b/scripts/play.ps1 @@ -0,0 +1,38 @@ +# Starts the title with the settings this fork is played with (README.md, "How to run it"). +# scripts\play.ps1 -Exe <path of your own copy's executable> +# -Safe without the newer, faster ways (the first thing to try when something is wrong) +# -RayTracing the title's own ray-traced indirect light: lit interiors, about a third slower +# -Build target\diag (the default, the build all measurements are of) or target\release +# -More other settings: -More @{VICTORY_PANEL='1'} +# Run it from a normal window, not as administrator: the driver then keeps its shader cache elsewhere. +param( + [Parameter(Mandatory)][string]$Exe, + [switch]$Safe, + [switch]$RayTracing, + [ValidateSet('diag', 'release')][string]$Build = 'diag', + [hashtable]$More = @{} +) +$settings = @{ + VICTORY_TEXTURE_NO_WAIT = '1'; VICTORY_RELAY = '2'; VICTORY_WIDE_BACK = '1'; VICTORY_CARD_REHASH_RUNS = '1' + VICTORY_JOIN_COPIES = '1'; VICTORY_INDIRECT_WINDOW = '1'; VICTORY_RELAY_COPY = '1'; VICTORY_CARD_STEPS = '2' + VICTORY_INDIRECT_BATCH = '2'; VICTORY_MAP_THREADS = '1'; VICTORY_TITLE_PRIORITIES = '0'; VICTORY_CARD_AWAKE = '1' + VICTORY_SHOW_AFTER = '1'; VICTORY_AMBIENT = '0.8'; VICTORY_D3D12_DRED = 'light'; VICTORY_SKIP_PIPELINES = 'none' +} +if ($Safe) { + $settings.VICTORY_UNDER_WIDE = '0'; $settings.VICTORY_LAND_ECHO = '0' +} else { + $settings.VICTORY_THIN = '1'; $settings.VICTORY_JOIN_PARTS = '8'; $settings.VICTORY_UPLOAD_AHEAD = '1' +} +if ($RayTracing) { $settings.VICTORY_BVH_BUILDER = '1' } +foreach ($k in $More.Keys) { $settings[$k] = $More[$k] } + +$victory = Join-Path $PSScriptRoot "..\target\$Build\victory.exe" +if (-not (Test-Path $victory)) { Write-Host "No $victory. Build it first (README.md)."; return } +if (-not (Test-Path $Exe)) { Write-Host "No $Exe."; return } +# (Other settings left over in this window go; where your files are stays.) +$paths = 'VICTORY_CONFIG', 'VICTORY_GAME_DIR', 'VICTORY_CACHE_DIR', 'VICTORY_DATA_DIR' +Get-ChildItem Env:VICTORY_* | Where-Object { $_.Name -notin $paths } | ForEach-Object { Remove-Item "Env:$($_.Name)" } +foreach ($k in $settings.Keys) { Set-Item "Env:$k" $settings[$k] } +$Exe = (Resolve-Path $Exe).Path +Push-Location (Join-Path $PSScriptRoot '..') # victory.toml is looked for here +try { & $victory run $Exe --execute } finally { Pop-Location } diff --git a/xtask/src/policy.rs b/xtask/src/policy.rs index 056053b..a0dc014 100644 --- a/xtask/src/policy.rs +++ b/xtask/src/policy.rs @@ -10,7 +10,8 @@ use std::process::Command; use anyhow::{Context, Result, bail}; -const MAX_FILE_SIZE: usize = 512 * 1024; +// (The translator's one file is 570 KiB of source.) +const MAX_FILE_SIZE: usize = 640 * 1024; const MAX_ENCODED_RUN: usize = 512; const ALLOWED_EXTENSIONS: &[&str] = &[ From 0a43566532c57b34a5397d6fdc91e419de32e8e9 Mon Sep 17 00:00:00 2001 From: local <local@localhost> Date: Wed, 25 Nov 2026 16:14:34 -0600 Subject: [PATCH 420/445] README: where it is cloned from Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d347b4a..9bc1b7b 100644 --- a/README.md +++ b/README.md @@ -43,8 +43,8 @@ model 6.6 and mesh shaders, Rust (the toolchain is pinned), the MSVC build tools, and your own dump of the title. ```powershell -git clone <this repository> -cd <the folder> +git clone https://github.com/avatarmanz/VIctory-7900XTX +cd VIctory-7900XTX copy victory.example.toml victory.toml # then set your paths, outside this folder cargo build --locked --profile diag -p victory --features diagnostics scripts\play.ps1 -Exe <path of your copy's executable> From 7997a2036311334db7f830773e4ef6a929eace3c Mon Sep 17 00:00:00 2001 From: trustno1-coder <canthuit7@gmail.com> Date: Wed, 25 Nov 2026 15:42:19 -0800 Subject: [PATCH 421/445] NVIDIA: more dynamic descriptor slots; Series S interface plane (compose) - present: VICTORY_COMPOSE=1 lays the Series S interface plane (4K) over the game plane (1080p); without it everything before gameplay is black. Ported from fxceless/victory-gta6 PR #1189 (compose.rs; FSR stand-in not ported, use VICTORY_OWN_UPSCALER=1). - shader cache key includes VICTORY_BVH_MISS. Measured on an RTX 5070, Series S, half scale: about 20-22 fps, no device loss. --- crates/victory-gpu/src/compose.rs | 244 +++++++++++++++++++++++++ crates/victory-gpu/src/host.rs | 21 ++- crates/victory-gpu/src/lib.rs | 3 + crates/victory-gpu/src/queue.rs | 99 +++++++++- crates/victory-gpu/src/shader_cache.rs | 1 + 5 files changed, 363 insertions(+), 5 deletions(-) create mode 100644 crates/victory-gpu/src/compose.rs diff --git a/crates/victory-gpu/src/compose.rs b/crates/victory-gpu/src/compose.rs new file mode 100644 index 0000000..9aa45cb --- /dev/null +++ b/crates/victory-gpu/src/compose.rs @@ -0,0 +1,244 @@ +//! Ported from fxceless/victory-gta6 PR #1189 (Series S interface plane), `VICTORY_COMPOSE=1`. +//! A present's second plane laid over its first. +//! +//! A Series S title presents two planes (run 2026-11-25: plane 0 the +//! game, 1920x1080 or what the display mode makes it, plane 1 the +//! interface, 3840x2160); the console's display lays the second over the +//! first and scales both to the screen. The host shows one texture, so +//! the interface is laid over the game here, at the game plane's size, +//! into a texture of ours that is shown instead (filtered: the interface +//! is scaled down). shortcut: the planes' placement and source rectangles +//! are not read; both cover the screen. The interface's alpha is taken as +//! straight (`VICTORY_PLANE_PREMULTIPLIED=1`: premultiplied). + +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// Frames of descriptors in the ring (three each): presents in flight +/// must not find theirs rewritten. +const SLOTS: u32 = 16; + +const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=3, b0), DescriptorTable(SRV(t0, numDescriptors=2), UAV(u0)), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)" +cbuffer Size : register(b0) { uint w; uint h; uint premultiplied; }; +Texture2D<float4> game : register(t0); +Texture2D<float4> ui : register(t1); +RWTexture2D<float4> outp : register(u0); +SamplerState linear_clamp : register(s0); +[RootSignature(RS)] +[numthreads(8, 8, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= w || id.y >= h) return; + float2 uv = (float2(id.xy) + 0.5) / float2(w, h); + float4 g = game.Load(int3(id.xy, 0)); + float4 u = ui.SampleLevel(linear_clamp, uv, 0); + float3 c = premultiplied != 0 ? g.rgb * (1.0 - u.a) + u.rgb : lerp(g.rgb, u.rgb, u.a); + outp[id.xy] = float4(c, 1.0); +} +"#; + +struct Pass { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + views: ID3D12DescriptorHeap, + cpu: usize, + gpu: u64, + step: u32, + next: u32, + /// The texture shown instead, by size. + out: Option<(u64, u32, ID3D12Resource)>, +} +// SAFETY: D3D12 objects are free-threaded; the pass is used under a lock. +unsafe impl Send for Pass {} + +/// The pass: not tried yet, could not be made, or made. +static PASS: Mutex<Option<Option<Pass>>> = Mutex::new(None); + +fn make(device: &ID3D12Device) -> windows::core::Result<Pass> { + let mut code: Option<ID3DBlob> = None; + // SAFETY: the source and names live through the call; the out pointer + // is ours. + unsafe { + D3DCompile( + SOURCE.as_ptr().cast(), + SOURCE.len(), + windows::core::s!("present planes"), + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + } + let code = code.ok_or_else(windows::core::Error::empty)?; + // SAFETY: the blob's own bytes (the root signature is inside the + // shader); plain object creation and queries. + unsafe { + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; + let pso: ID3D12PipelineState = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + let views: ID3D12DescriptorHeap = device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: SLOTS * 3, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + })?; + Ok(Pass { + cpu: views.GetCPUDescriptorHandleForHeapStart().ptr, + gpu: views.GetGPUDescriptorHandleForHeapStart().ptr, + step: device.GetDescriptorHandleIncrementSize(kind), + root, + pso, + views, + next: 0, + out: None, + }) + } +} + +/// Whether a host texture's format is one this pass reads and writes +/// (8-bit RGBA, typeless or not). +fn rgba8(format: DXGI_FORMAT) -> bool { + matches!(format.0, 27 | 28) +} + +fn premultiplied() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PLANE_PREMULTIPLIED").is_some_and(|v| v == "1")) +} + +/// Records, into the present's `list`, `ui` laid over `game` into a +/// texture of ours, and gives that texture, left in the copy-source +/// state. `game` is in the copy-source state (the present put it there); +/// `ui` is in `ui_state` and is left in it. `None` (nothing recorded) if +/// a format is not 8-bit RGBA or the pass could not be made. +pub(crate) fn record( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + game: &ID3D12Resource, + ui: &ID3D12Resource, + ui_state: u32, +) -> Option<ID3D12Resource> { + // SAFETY: live resources; plain queries. + let (gd, ud) = unsafe { (game.GetDesc(), ui.GetDesc()) }; + if !rgba8(gd.Format) || !rgba8(ud.Format) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(game = gd.Format.0, ui = ud.Format.0, "present planes not laid over each other: a format this pass does not read"); + }); + return None; + } + let mut kept = PASS.lock().unwrap_or_else(|e| e.into_inner()); + if kept.is_none() { + *kept = Some(match make(device) { + Ok(p) => { + tracing::info!(premultiplied = premultiplied(), "present planes: the interface is laid over the game"); + Some(p) + } + Err(e) => { + tracing::warn!(error = %e, "present planes: the pass that lays them over each other could not be made"); + None + } + }); + } + let pass = kept.as_mut()?.as_mut()?; + let (w, h) = (gd.Width, gd.Height); + if pass.out.as_ref().is_none_or(|o| (o.0, o.1) != (w, h)) { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut out: Option<ID3D12Resource> = None; + // SAFETY: plain creation of a device-local texture. + unsafe { + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_SOURCE, None, &mut out) + .ok()?; + } + pass.out = Some((w, h, out?)); + } + let out = pass.out.as_ref()?.2.clone(); + let first = (pass.next % SLOTS) * 3; + pass.next = pass.next.wrapping_add(1); + let cpu = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: pass.cpu + ((first + i) * pass.step) as usize }; + let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: pass.gpu + u64::from(first * pass.step) }; + let srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: 1, + ..Default::default() + }, + }, + }; + let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 }, + }, + }; + let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + let ui_state = D3D12_RESOURCE_STATES(ui_state as i32); + let t = crate::host::transition; + let mut before = vec![ + t(game, D3D12_RESOURCE_STATE_COPY_SOURCE, read), + t(&out, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]; + let mut after = vec![ + t(game, read, D3D12_RESOURCE_STATE_COPY_SOURCE), + t(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + ]; + if ui_state != read { + before.push(t(ui, ui_state, read)); + after.push(t(ui, read, ui_state)); + } + let constants: [u32; 3] = [w as u32, h, u32::from(premultiplied())]; + // SAFETY: an open list (the present's); slots of our heap; live + // resources and objects (the pass's own live as long as the process, + // the texture is kept by the present's list). + unsafe { + device.CreateShaderResourceView(game, Some(&srv), cpu(0)); + device.CreateShaderResourceView(ui, Some(&srv), cpu(1)); + device.CreateUnorderedAccessView(&out, None::<&ID3D12Resource>, Some(&uav), cpu(2)); + list.ResourceBarrier(&before); + list.SetDescriptorHeaps(&[Some(pass.views.clone())]); + list.SetComputeRootSignature(&pass.root); + list.SetPipelineState(&pass.pso); + list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); + list.SetComputeRootDescriptorTable(1, gpu); + list.Dispatch((w as u32).div_ceil(8), h.div_ceil(8), 1); + list.ResourceBarrier(&after); + } + Some(out) +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 1ae56ee..763cefb 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -8804,6 +8804,19 @@ impl Host { /// as frame `frame` (saved if captures are on). `None` if nothing was /// shown; else, in diagnostics builds, whether the frame was black. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> { + self.present_over(texture, state, None, frame) + } + + /// LOCAL (port of fxceless #1189): [`Self::present`], with a second + /// plane laid over `texture` if there is one (`crate::compose`): its + /// texture and its state, which it is left in. + pub(crate) fn present_over( + &self, + texture: &ID3D12Resource, + state: u32, + over: Option<(&ID3D12Resource, u32)>, + frame: u64, + ) -> Option<bool> { // SAFETY: a live resource. let desc = unsafe { texture.GetDesc() }; let Some(format) = swap_format(desc.Format) else { @@ -8887,7 +8900,13 @@ impl Host { D3D12_RESOURCE_STATE_COPY_DEST, ), ]); - list.CopyResource(&back, texture); + // LOCAL (port of fxceless #1189): the second plane laid over the + // first, into a texture of ours shown instead (`crate::compose`). + let laid = over.and_then(|(ui, ui_state)| crate::compose::record(&self.device, list, texture, ui, ui_state)); + if let Some(laid) = &laid { + copy.keep(laid); + } + list.CopyResource(&back, laid.as_ref().unwrap_or(texture)); #[cfg(feature = "diagnostics")] let capture = crate::capture::wanted(frame) .then(|| crate::capture::read_back(&self.device, list, texture)) diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 908dbec..9441fe2 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -20,6 +20,9 @@ mod ambient; #[cfg(all(windows, feature = "diagnostics"))] mod capture; pub mod console; +// LOCAL (port of fxceless #1189): Series S interface plane laid over the game (VICTORY_COMPOSE=1). +#[cfg(windows)] +mod compose; #[cfg(all(windows, feature = "diagnostics"))] mod copystat; #[cfg(all(windows, feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index ede3bb3..0dc2f38 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -924,6 +924,8 @@ extern "system" fn present( crate::capture::dump_targets(frame); } } + #[cfg(all(windows, feature = "diagnostics"))] + note_planes(planes, plane_parameters); #[cfg(windows)] if behind::on() && !this.is_null() { const COPY_SOURCE: u32 = 0x800; @@ -949,7 +951,10 @@ extern "system" fn present( None }; let resource = texture.as_ref().map_or(0, |t| t.0); - behind::present(this, texture.map(|(_, copy, state)| (copy, state)), Shown { frame, resource }); + // LOCAL (port of fxceless #1189): the interface plane, as the first. + let over = second_plane(planes, plane_parameters, resource as This) + .map(|(copy, state)| (copy, if crate::list::thin::wanted() { u32::MAX } else { state })); + behind::present(this, texture.map(|(_, copy, state)| (copy, state)), Shown { frame, resource, over }); called.end(); #[cfg(feature = "diagnostics")] frame_ends(); @@ -969,7 +974,8 @@ extern "system" fn present( const COPY_SOURCE: u32 = 0x800; let state = crate::resource::host_transition(resource, COPY_SOURCE) .map_or(COPY_SOURCE, |(_, before)| before); - show(texture, state, Shown { frame, resource: resource as usize }); + let over = second_plane(planes, plane_parameters, resource); + show(texture, state, Shown { frame, resource: resource as usize, over }); crate::resource::host_transition(resource, state); let _ = host; } @@ -995,10 +1001,91 @@ fn frame_ends() { /// The frame a present shows, and the title's resource it shows. #[cfg(windows)] -#[derive(Clone, Copy)] +#[derive(Clone)] struct Shown { frame: u64, resource: usize, + /// LOCAL (port of fxceless #1189): the second plane to lay over the + /// shown one, and its host state (`u32::MAX`: the state its lists left + /// it in when they ran). + over: Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>, +} + +/// LOCAL (port of fxceless #1189): a present's second plane, to be laid over +/// the first (`crate::compose`), with `VICTORY_COMPOSE=1`. Its host copy and +/// the host state the lists recorded so far leave it in (noted as before). +/// A Series S title presents two planes: the game and the interface +/// (menus, loading screens, the intro), 72-byte descriptions each. +#[cfg(windows)] +fn second_plane(planes: u32, plane_parameters: *const Plane, first: This) -> Option<(std::sync::Arc<crate::resource::HostTexture>, u32)> { + const STRIDE: usize = 72; + const COPY_SOURCE: u32 = 0x800; + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let on = *ON.get_or_init(|| { + let on = std::env::var_os("VICTORY_COMPOSE").is_some_and(|v| v == "1"); + if on { + tracing::warn!("LOCAL present planes: a second plane is laid over the first (VICTORY_COMPOSE=1)"); + } + on + }); + if !on || planes < 2 || plane_parameters.is_null() { + return None; + } + // SAFETY: the title passes `planes` descriptions of `STRIDE` bytes. + let plane = unsafe { plane_parameters.cast::<u8>().add(STRIDE).cast::<Plane>().as_ref() }?; + if plane.count == 0 || plane.resources.is_null() { + return None; + } + // SAFETY: the plane lists `count` resources. + let resource = unsafe { *plane.resources }; + if resource == first { + return None; + } + let copy = crate::resource::host_copy(resource)?; + let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before); + crate::resource::host_transition(resource, state); + Some((copy, state)) +} + +/// Diagnostics (LOCAL, from fxceless #1189): the planes a present asks for, +/// at presents 1, 2, 4, ... up to 4096 and whenever their number changes. +#[cfg(all(windows, feature = "diagnostics"))] +fn note_planes(planes: u32, plane_parameters: *const Plane) { + const STRIDE: usize = 72; + static LAST: AtomicU64 = AtomicU64::new(u64::MAX); + let frame = FRAMES.load(Ordering::Relaxed); + let changed = LAST.swap(u64::from(planes), Ordering::Relaxed) != u64::from(planes); + if !changed && !(frame.is_power_of_two() && frame <= 4096) { + return; + } + if plane_parameters.is_null() { + return; + } + for i in 0..planes.min(4) as usize { + // SAFETY: the title passes `planes` descriptions of `STRIDE` bytes. + let Some(plane) = (unsafe { plane_parameters.cast::<u8>().add(i * STRIDE).cast::<Plane>().as_ref() }) else { + continue; + }; + if plane.resources.is_null() { + tracing::warn!(frame, planes, plane = i, count = plane.count, "present plane without resources"); + continue; + } + for k in 0..plane.count.min(2) as usize { + // SAFETY: the plane lists `count` resources. + let resource = unsafe { *plane.resources.add(k) }; + let desc = crate::resource::texture_memory(resource).map(|m| m.1); + tracing::warn!( + frame, + planes, + plane = i, + count = plane.count, + resource = ?resource, + hosted = crate::resource::host_copy(resource).is_some(), + desc = ?desc, + "present plane" + ); + } + } } /// Shows `texture`, in host state `state`, in our window. @@ -1007,7 +1094,11 @@ fn show(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u let Some(host) = crate::host::host() else { return; }; - let shown = host.present(texture, state, what.frame); + let over = what.over.as_ref().map(|(t, s)| { + let s = if *s == u32::MAX { t.state.load(Ordering::Relaxed) } else { *s }; + (&t.texture, s) + }); + let shown = host.present_over(texture, state, over, what.frame); #[cfg(feature = "diagnostics")] blinks(what.frame, what.resource as This, state, shown); #[cfg(not(feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index b291e11..f5e6482 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -63,6 +63,7 @@ fn build() -> [u8; 32] { // served the translations an earlier run of the same // executable had cached with the switch unset. for name in [ + "VICTORY_BVH_MISS", "VICTORY_WAVE_WIDE", "VICTORY_WAVE_DEEP_SKIPS", "VICTORY_WAVE_OWN_BITS", From a9632bc8de343aa20adf4f1123f16445f5b1b21b Mon Sep 17 00:00:00 2001 From: trustno1-coder <canthuit7@gmail.com> Date: Wed, 25 Nov 2026 15:43:00 -0800 Subject: [PATCH 422/445] NVIDIA: VICTORY_DYNAMIC_SLOTS on a capped view heap (stops dropped draws) NVIDIA caps the shader-visible view heap at 1,000,000 (the title wants 1,245,184), so the dynamic slot pool (2^18) ran out and 1,100-4,800 tables a frame were refused, each a dropped draw (the screen rarely updated). VICTORY_DYNAMIC_SLOTS=524288 takes more of the title's kept-in-place slots (at most half the heap): 0-33 refused a frame. --- crates/victory-gpu/src/descriptor/host.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 1ffdc72..9fd871b 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1430,7 +1430,20 @@ fn dynamic_slots(count: u32, null: u32) -> u32 { .unwrap_or(DYNAMIC << 2) }); if null < PORTABLE_VIEWS { - return DYNAMIC; + // LOCAL (NVIDIA, 11/25): a host heap capped at 1,000,000 views ran + // these out with the fast settings (THIN: 1,100-4,800 of 12,000-16,600 + // tables a frame refused, each a dropped draw). `VICTORY_DYNAMIC_SLOTS` + // takes more of them from the title's slots kept in place (tables + // past those are made afresh here anyway), at most half the heap. + static CAPPED: std::sync::OnceLock<u32> = std::sync::OnceLock::new(); + return *CAPPED.get_or_init(|| { + let asked = std::env::var("VICTORY_DYNAMIC_SLOTS").ok().and_then(|v| v.trim().parse::<u32>().ok()); + let slots = asked.unwrap_or(DYNAMIC).clamp(DYNAMIC, null / 2); + if slots != DYNAMIC { + tracing::warn!(slots, title_in_place = null - slots, "LOCAL dynamic descriptor slots on a capped view heap"); + } + slots + }); } null.saturating_sub(count).min(most).max(DYNAMIC) } From afd84de12f08b3224c4acee16cd95d05343d841a Mon Sep 17 00:00:00 2001 From: trustno1-coder <canthuit7@gmail.com> Date: Wed, 25 Nov 2026 15:43:32 -0800 Subject: [PATCH 423/445] Loader: render scale, own upscaler and watchdog title patches hooks.rs (1.0.2.1 executable only): VICTORY_RENDER_SCALE (0.2-1.0 internal render scale), VICTORY_OWN_UPSCALER=1 (the title's own temporal upscaler on every profile; Series S needs it with a scale below 1), VICTORY_NO_WATCHDOG. Taken from the victory-perf patches. --- crates/victory-loader/src/hooks.rs | 258 +++++++++++++++++++++++++++ crates/victory-loader/src/lib.rs | 3 + crates/victory-loader/src/windows.rs | 16 ++ 3 files changed, 277 insertions(+) create mode 100644 crates/victory-loader/src/hooks.rs diff --git a/crates/victory-loader/src/hooks.rs b/crates/victory-loader/src/hooks.rs new file mode 100644 index 0000000..0e67bb2 --- /dev/null +++ b/crates/victory-loader/src/hooks.rs @@ -0,0 +1,258 @@ +//! Opt-in compatibility hooks for known title builds. +//! +//! LOCAL: copied from vitutu1/victory-perf crates/victory-loader/src/hooks.rs, which ported it from +//! ZigZagBoi1/ScarlettPort (`runtime/victory`, GPL-3.0-or-later). +//! Only per-build offsets and short byte signatures live here (asset policy: +//! nothing of the title itself). Every hook checks the build's hash and the +//! exact bytes it replaces, and does nothing otherwise. + +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; + +/// First 16 hex digits of the BLAKE3 of the Series X 1.0.2.1 executable. +const BUILD_1_0_2_1: &str = "b99f876b74d4a77f"; + +/// Environment variable that turns the watchdog hook on. +pub(crate) const NO_WATCHDOG_ENV: &str = "VICTORY_NO_WATCHDOG"; + +/// One code patch: `rva` must hold exactly `expect` before `new` is written. +struct Patch<'a> { + what: &'static str, + rva: usize, + expect: &'a [u8], + new: &'a [u8], +} + +/// The title's watchdog thread ends the process on purpose when its main +/// thread has not advanced for about 30 one-second ticks. Two places do it: +/// the handler it calls (`mov dword ptr [0], imm32`) and, when the handler +/// returns or is unset, a fallback right after the call (`mov dword ptr [0], +/// 0; int3`). Jumping over the whole block returns the loop to its normal +/// path; the first patch makes the handler harmless if something else calls it. +const WATCHDOG: &[Patch<'static>] = &[ + Patch { + what: "watchdog: skip the call and the fallback fault", + rva: 0x2215c27, + // mov rax, [rip + disp32] (the handler pointer) + expect: &[0x48, 0x8B, 0x05, 0x1A, 0x07, 0xFA, 0x04], + // jmp +0x18 (to the loop's normal continuation), then NOPs + new: &[0xEB, 0x18, 0x90, 0x90, 0x90, 0x90, 0x90], + }, + Patch { + what: "watchdog: handler's deliberate fault", + rva: 0x23cf683, + expect: &[0xC7, 0x04, 0x25, 0, 0, 0, 0, 0x21, 0xD4, 0x8B, 0x4D], + // an eleven-byte NOP + new: &[0x66, 0x66, 0x2E, 0x0F, 0x1F, 0x84, 0, 0, 0, 0, 0], + }, +]; + +/// Applies the watchdog patches whose bytes match. Returns how many applied. +/// +/// # Safety +/// `base` is the mapped image whose original BLAKE3 is `hash`, and no title +/// code is running yet. +pub(crate) unsafe fn disarm_watchdog(base: usize, hash: &blake3::Hash) -> usize { + if !hash.to_hex().starts_with(BUILD_1_0_2_1) { + return 0; + } + WATCHDOG + .iter() + // SAFETY: forwarded from this function's contract. + .filter(|p| unsafe { apply(base, p) }) + .count() +} + +/// Environment variable that pins the title's internal render scale +/// (`0.2..=1.0` of the output size). Testing lever, off by default. +pub(crate) const RENDER_SCALE_ENV: &str = "VICTORY_RENDER_SCALE"; +/// Environment variable that makes the title use its own temporal upscaler +/// on every console profile (Series S otherwise picks FSR). +pub(crate) const OWN_UPSCALER_ENV: &str = "VICTORY_OWN_UPSCALER"; + +/// A patch whose bytes are computed at load time. +struct OwnedPatch { + what: &'static str, + rva: usize, + expect: Vec<u8>, + new: Vec<u8>, +} + +/// The upscaler choice: `mov eax, 6` (own upscaler) then `cmovne eax, ecx` +/// (FSR when the profile asks for it). NOPing the cmovne keeps 6. +const OWN_UPSCALER: Patch<'static> = Patch { + what: "upscaler: always the title's own", + rva: 0x7e9426, + expect: &[0x0F, 0x45, 0xC1], + new: &[0x0F, 0x1F, 0x00], +}; + +/// Read-only float constants of this build usable as the FSR scale: +/// value, RVA. +const FSR_SCALES: [(f32, usize); 4] = [ + (0.5, 0x5fc6edc), + (0.4, 0x5fc6f90), + (1.0 / 3.0, 0x615a240), + (0.75, 0x6159b04), +]; + +/// The render-scale patches for `scale`, with the image at `base`: +/// - the own upscaler's minimum scale (an immediate, 2/3 by default) set to +/// `scale` and its maximum made equal to the minimum (`vmaxss` → `vmovss`), +/// so the scale is fixed; +/// - FSR's scale (a load of 2/3 on Series S) pointed at a constant equal to +/// `scale`, when this build has one, and its maximum size made the scaled +/// size (vtable slot 11 → slot 10's function). +fn render_scale_patches(base: usize, scale: f32, fsr: bool) -> Vec<OwnedPatch> { + let mut patches = vec![ + OwnedPatch { + what: "render scale: own upscaler minimum", + rva: 0x28f1e7e, + expect: vec![0xAB, 0xAA, 0x2A, 0x3F], + new: scale.to_le_bytes().to_vec(), + }, + OwnedPatch { + what: "render scale: own upscaler maximum = minimum", + rva: 0x28f1e87, + expect: vec![0xC5, 0xFA, 0x5F, 0x86, 0x90, 0, 0, 0], + new: vec![0xC5, 0xFA, 0x10, 0x86, 0x90, 0, 0, 0], + }, + ]; + if !fsr { + return patches; + } + match FSR_SCALES.iter().find(|(v, _)| (v - scale).abs() < 1e-3) { + Some(&(_, constant)) => { + // vmovss xmm0, [rip + disp32]; the next instruction is at +8. + const LOAD: usize = 0x28ef6b2; + let disp = (constant as i64 - (LOAD as i64 + 8)) as i32; + let mut new = vec![0xC5, 0xFA, 0x10, 0x05]; + new.extend_from_slice(&disp.to_le_bytes()); + patches.push(OwnedPatch { + what: "render scale: FSR scale", + rva: LOAD, + expect: vec![0xC5, 0xFA, 0x10, 0x05, 0xA2, 0xE2, 0x86, 0x03], + new, + }); + patches.push(OwnedPatch { + what: "render scale: FSR maximum = scaled size", + rva: 0x6300ba8, + expect: ((base + 0x28ef6f0) as u64).to_le_bytes().to_vec(), + new: ((base + 0x28ef680) as u64).to_le_bytes().to_vec(), + }); + } + None => tracing::warn!( + scale, + "no FSR constant for this scale (0.5, 0.4, 1/3, 0.75); FSR keeps its own (use {OWN_UPSCALER_ENV}=1)" + ), + } + patches +} + +/// The scale `VICTORY_RENDER_SCALE` asks for, if valid. +fn parse_scale(text: &str) -> Option<f32> { + let v: f32 = text.trim().parse().ok()?; + (0.2..=1.0).contains(&v).then_some(v) +} + +/// Applies the resolution levers asked for in the environment +/// ([`RENDER_SCALE_ENV`], [`OWN_UPSCALER_ENV`]). Returns how many applied. +/// +/// # Safety +/// As `disarm_watchdog`. +pub(crate) unsafe fn resolution_levers(base: usize, hash: &blake3::Hash) -> usize { + let scale = std::env::var(RENDER_SCALE_ENV).ok(); + let own = std::env::var_os(OWN_UPSCALER_ENV).is_some_and(|v| v != "0"); + if scale.is_none() && !own { + return 0; + } + // Every image the loader maps comes here (the title's DLLs too); only + // the 1.0.2.1 executable has the patched places. + if !hash.to_hex().starts_with(BUILD_1_0_2_1) { + tracing::debug!("resolution levers: not the 1.0.2.1 executable; nothing patched"); + return 0; + } + let mut applied = 0; + if own { + // SAFETY: forwarded from this function's contract. + applied += usize::from(unsafe { apply(base, &OWN_UPSCALER) }); + } + if let Some(text) = scale { + match parse_scale(&text) { + Some(scale) => { + // With the own upscaler forced, FSR is left as it is. + for p in render_scale_patches(base, scale, !own) { + let p = Patch { + what: p.what, + rva: p.rva, + expect: &p.expect, + new: &p.new, + }; + // SAFETY: forwarded from this function's contract. + applied += usize::from(unsafe { apply(base, &p) }); + } + } + None => tracing::warn!(text, "{RENDER_SCALE_ENV} wants a number in 0.2..=1.0"), + } + } + applied +} + +/// # Safety +/// See `disarm_watchdog`. +unsafe fn apply(base: usize, p: &Patch<'_>) -> bool { + let at = (base + p.rva) as *mut u8; + // SAFETY: the offset is inside the mapped .text of this exact build. + let now = unsafe { std::slice::from_raw_parts(at, p.expect.len()) }; + if now != p.expect || p.new.len() != p.expect.len() { + tracing::warn!(what = p.what, "hook skipped: the bytes are not the expected ones"); + return false; + } + let mut old = 0; + // SAFETY: changing the protection of those bytes only, restored below. + if unsafe { VirtualProtect(at as _, p.new.len(), PAGE_EXECUTE_READWRITE, &mut old) } == 0 { + return false; + } + // SAFETY: writable now; the bytes are the ones checked above. + unsafe { + std::ptr::copy_nonoverlapping(p.new.as_ptr(), at, p.new.len()); + VirtualProtect(at as _, p.new.len(), old, &mut old); + FlushInstructionCache(GetCurrentProcess(), at as _, p.new.len()); + } + tracing::info!(what = p.what, "hook applied"); + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scales_outside_the_floor_are_refused() { + assert_eq!(parse_scale("0.5"), Some(0.5)); + assert_eq!(parse_scale(" 1 "), Some(1.0)); + assert_eq!(parse_scale("0.1"), None); + assert_eq!(parse_scale("1.5"), None); + assert_eq!(parse_scale("half"), None); + } + + #[test] + fn half_scale_patches_both_upscalers() { + let base = 0x7ff0_0000_0000; + let p = render_scale_patches(base, 0.5, true); + assert_eq!(p.len(), 4); + assert_eq!(p[0].new, 0.5f32.to_le_bytes()); + // The FSR load now reads 0.5 at 0x5fc6edc: disp from the next instruction. + assert_eq!(p[2].new, [0xC5, 0xFA, 0x10, 0x05, 0x22, 0x78, 0x6D, 0x03]); + assert_eq!(p[3].new, ((base + 0x28ef680) as u64).to_le_bytes()); + assert!(p.iter().all(|p| p.new.len() == p.expect.len())); + } + + #[test] + fn odd_scales_patch_only_the_own_upscaler() { + assert_eq!(render_scale_patches(0, 0.6, true).len(), 2); + assert_eq!(render_scale_patches(0, 0.5, false).len(), 2); + } +} + diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index c99eba4..3994f47 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -24,6 +24,9 @@ #[cfg(windows)] mod console_insn; mod crash; +// LOCAL (victory-perf, via our wt5): VICTORY_RENDER_SCALE / VICTORY_OWN_UPSCALER / VICTORY_NO_WATCHDOG title patches. +#[cfg(windows)] +mod hooks; pub mod prepare; pub(crate) mod publish; pub mod resolve; diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs index a0375ef..0a2897a 100644 --- a/crates/victory-loader/src/windows.rs +++ b/crates/victory-loader/src/windows.rs @@ -84,6 +84,22 @@ pub fn load(prepared: &PreparedImage, dir: &Path) -> Result<LoadedImage> { // SAFETY: just mapped, and no title code has run. unsafe { crate::tls::redirect(loaded.base(), &loaded.info) }?; } + // LOCAL (victory-perf, via our wt5): opt-in title patches, each checked against the 1.0.2.1 hash and its bytes. + if std::env::var_os(crate::hooks::NO_WATCHDOG_ENV).is_some() { + // SAFETY: just mapped, and no title code has run. + let applied = unsafe { crate::hooks::disarm_watchdog(loaded.base(), &prepared.original_hash) }; + tracing::info!(applied, "title watchdog hooks ({})", crate::hooks::NO_WATCHDOG_ENV); + } + // SAFETY: just mapped, and no title code has run. + let levers = unsafe { crate::hooks::resolution_levers(loaded.base(), &prepared.original_hash) }; + if levers > 0 { + tracing::warn!( + applied = levers, + "title resolution levers ({}, {})", + crate::hooks::RENDER_SCALE_ENV, + crate::hooks::OWN_UPSCALER_ENV + ); + } tracing::info!( base = format_args!("{:#x}", loaded.base()), preferred = format_args!("{:#x}", loaded.info.image_base), From 24a479d32946e564efefb07a4ce1b20367adeaf1 Mon Sep 17 00:00:00 2001 From: trustno1-coder <canthuit7@gmail.com> Date: Wed, 25 Nov 2026 15:44:02 -0800 Subject: [PATCH 424/445] Shader: VICTORY_BVH_MISS ends ray walks at the root While the BVH builder is off its nodes are stale: VICTORY_BVH_MISS=1 makes every box and triangle test a miss instead of walking them (no hang, about 10 ms a frame less). It is part of the shader cache key. --- crates/victory-shader/src/emit/intersect.rs | 23 +++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs index b32afa8..66665ef 100644 --- a/crates/victory-shader/src/emit/intersect.rs +++ b/crates/victory-shader/src/emit/intersect.rs @@ -59,6 +59,14 @@ struct Ray { inverse: [V; 3], } +/// LOCAL (from our wt5): `VICTORY_BVH_MISS=1` (off by default): the node test +/// misses every node. While the structure builder is off the structures are +/// never built, and a walk of what lies in their memory is not the console's. +fn bvh_miss() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_MISS").is_some_and(|v| v == "1")) +} + impl<'a> Lower<'a> { /// `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`. pub(super) fn bvh(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { @@ -191,11 +199,22 @@ impl<'a> Lower<'a> { .m .terminate(leaf_block, Term::CondBr(is_triangle, triangle_block, join)); self.cur = box_block; - let boxes = self.bvh_boxes(at, kind, &ray, sort); + // LOCAL (from our wt5): with `VICTORY_BVH_MISS=1` every node is missed + // without being read: a box returns no child and a triangle the + // triangle miss, so a walk ends at its first node. + let boxes = if bvh_miss() { + [self.s.m.i32(bvh::NONE); 4] + } else { + self.bvh_boxes(at, kind, &ray, sort) + }; let box_end = self.cur; self.s.m.terminate(box_end, Term::Br(join)); self.cur = triangle_block; - let triangle = self.bvh_triangle(at, kind, &ray); + let triangle = if bvh_miss() { + bvh::MISS.map(|f| self.s.m.i32(f.to_bits())) + } else { + self.bvh_triangle(at, kind, &ray) + }; let triangle_end = self.cur; self.s.m.terminate(triangle_end, Term::Br(join)); self.cur = join; From a1849fac28d0db89680e05cfb62612310af6134c Mon Sep 17 00:00:00 2001 From: trustno1-coder <canthuit7@gmail.com> Date: Wed, 25 Nov 2026 15:44:30 -0800 Subject: [PATCH 425/445] scripts/play-nvidia.ps1: NVIDIA Series S launcher, Smooth Motion by default scripts\play-nvidia.ps1 -Exe <your copy's executable>: the fork's play set plus PIPELINE_WAIT_MS=10000, DYNAMIC_SLOTS=524288, RENDER_SCALE=0.5, OWN_UPSCALER=1, BVH_MISS=1, CARD_BUFFERS_MIN_MB=1, CARD_BUFFERS_MB=1536, COMPOSE=1, Series S. Starts a victory_sm.exe copy of the build so an NVIDIA App Smooth Motion profile for that exe applies (-NoSmoothMotion: victory.exe; -SeriesX: the Series X profile). --- scripts/play-nvidia.ps1 | 58 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 scripts/play-nvidia.ps1 diff --git a/scripts/play-nvidia.ps1 b/scripts/play-nvidia.ps1 new file mode 100644 index 0000000..2759108 --- /dev/null +++ b/scripts/play-nvidia.ps1 @@ -0,0 +1,58 @@ +# Starts the title on an NVIDIA card with the Series S settings measured on an RTX 5070 (about 20-22 fps, no device loss). +# scripts\play-nvidia.ps1 -Exe <path of your own copy's executable> +# -NoSmoothMotion run target\<build>\victory.exe itself. By default a copy named victory_sm.exe is started instead, +# so a Smooth Motion profile set for that exe in the NVIDIA App applies every time. +# -SeriesX the Series X profile instead (slower: about 7 fps at half scale) +# -Build target\diag (the default, the build all measurements are of) or target\release +# -More other settings: -More @{VICTORY_PANEL='1'} +# Run it from a normal window, not as administrator: the driver then keeps its shader cache elsewhere. +param( + [Parameter(Mandatory)][string]$Exe, + [switch]$NoSmoothMotion, + [switch]$SeriesX, + [ValidateSet('diag', 'release')][string]$Build = 'diag', + [hashtable]$More = @{} +) +$settings = @{ + # This fork's play set (scripts\play.ps1, not -Safe). + VICTORY_TEXTURE_NO_WAIT = '1'; VICTORY_RELAY = '2'; VICTORY_WIDE_BACK = '1'; VICTORY_CARD_REHASH_RUNS = '1' + VICTORY_JOIN_COPIES = '1'; VICTORY_INDIRECT_WINDOW = '1'; VICTORY_RELAY_COPY = '1'; VICTORY_CARD_STEPS = '2' + VICTORY_INDIRECT_BATCH = '2'; VICTORY_MAP_THREADS = '1'; VICTORY_TITLE_PRIORITIES = '0'; VICTORY_CARD_AWAKE = '1' + VICTORY_SHOW_AFTER = '1'; VICTORY_AMBIENT = '0.8'; VICTORY_D3D12_DRED = 'light'; VICTORY_SKIP_PIPELINES = 'none' + VICTORY_THIN = '1'; VICTORY_JOIN_PARTS = '8'; VICTORY_UPLOAD_AHEAD = '1' + # Wait for new shaders rather than skip their draws (a hitch the first time a place is seen). + VICTORY_PIPELINE_WAIT_MS = '10000' + # NVIDIA caps the shader-visible view heap at 1,000,000: without more dynamic slots thousands of draws a frame + # are dropped (descriptor/host.rs dynamic_slots). + VICTORY_DYNAMIC_SLOTS = '524288' + # Half render scale with the title's own upscaler (Series S needs it with a scale below 1; victory-loader hooks.rs). + VICTORY_RENDER_SCALE = '0.5'; VICTORY_OWN_UPSCALER = '1' + # Ray walks end at the root while the structure builder is off (emit/intersect.rs). + VICTORY_BVH_MISS = '1' + # Memory compares on the card instead of the CPU: 11 -> about 22 fps on Series S. + VICTORY_CARD_BUFFERS_MIN_MB = '1'; VICTORY_CARD_BUFFERS_MB = '1536' + # Series S presents the interface as a second plane: laid over the game (compose.rs), else black before gameplay. + VICTORY_COMPOSE = '1' +} +foreach ($k in $More.Keys) { $settings[$k] = $More[$k] } + +$victory = Join-Path $PSScriptRoot "..\target\$Build\victory.exe" +if (-not (Test-Path $victory)) { Write-Host "No $victory. Build it first (README.md)."; return } +if (-not (Test-Path $Exe)) { Write-Host "No $Exe."; return } +if (-not $NoSmoothMotion) { + # A copy under the name the NVIDIA App's Smooth Motion profile is set for, refreshed when the build changes. + $sm = Join-Path (Split-Path $victory) 'victory_sm.exe' + if (-not (Test-Path $sm) -or (Get-Item $sm).LastWriteTime -lt (Get-Item $victory).LastWriteTime) { + Copy-Item $victory $sm -Force + } + $victory = $sm +} +# (Other settings left over in this window go; where your files are stays.) +$paths = 'VICTORY_CONFIG', 'VICTORY_GAME_DIR', 'VICTORY_CACHE_DIR', 'VICTORY_DATA_DIR' +Get-ChildItem Env:VICTORY_* | Where-Object { $_.Name -notin $paths } | ForEach-Object { Remove-Item "Env:$($_.Name)" } +foreach ($k in $settings.Keys) { Set-Item "Env:$k" $settings[$k] } +$Exe = (Resolve-Path $Exe).Path +$runArgs = @('run', $Exe, '--execute') +if (-not $SeriesX) { $runArgs += @('--console', 'series-s') } +Push-Location (Join-Path $PSScriptRoot '..') # victory.toml is looked for here +try { & $victory @runArgs } finally { Pop-Location } From 969843e0d0bfd9177bb5cb88080ba139362beaf6 Mon Sep 17 00:00:00 2001 From: trustno1-coder <canthuit7@gmail.com> Date: Wed, 25 Nov 2026 15:46:43 -0800 Subject: [PATCH 426/445] README: VIctory on NVIDIA What this fork changes for NVIDIA cards, where it stands on an RTX 5070 (Series S, half scale, about 20-22 fps), how to run it with scripts\play-nvidia.ps1, and credits (the 7900 XTX fork first). --- README.md | 106 ++++++++++++++++++++++++++++++------------------------ 1 file changed, 60 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 9bc1b7b..4a42f89 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,10 @@ -# VIctory on an RX 7900 XTX +# VIctory on NVIDIA -A fork of [VIctory](https://github.com/Marvisak/VIctory), a compatibility layer -that runs an Xbox Series title natively on Windows from files the user supplies. -This one is about **speed on AMD RDNA 3**: the world at 30 frames a second on -one PC, without giving up the picture. It is not there yet. +A fork of [avatarmanz/VIctory-7900XTX](https://github.com/avatarmanz/VIctory-7900XTX), +itself a fork of [VIctory](https://github.com/Marvisak/VIctory), a compatibility +layer that runs an Xbox Series title natively on Windows from files the user +supplies. That fork is tuned for an AMD RX 7900 XTX. This one makes it **draw +everything on NVIDIA cards and run fastest there**, using the Series S profile. **This repository contains no game files, code or assets.** You need your own copy of the game. It is not affiliated with or endorsed by the game's developer @@ -11,30 +12,30 @@ or publisher. ## Where it stands (2026-11-25) -Tested on one machine only: Windows 11, Intel i9-12900K, 64 GB RAM, Radeon -RX 7900 XTX, 1440p, the Series X profile. +Tested on one machine only: Windows 11, AMD Ryzen 7 9800X3D, 64 GB RAM, +GeForce RTX 5070 12 GB, the Series S profile at half render scale +(`scripts\play-nvidia.ps1`). | | | |---|---| -| Menus, videos, loading screens | 30 fps | -| Prologue, indoors | 50-75 ms a frame (13-20 fps) | -| First mission with the boat | 46-53 ms (19-22 fps) | -| Street chase with many cars and people | 100-165 ms (6-10 fps), single frames far longer | -| Outdoors on foot, the camp | 60-90 ms | -| Flying | 42-57 ms | -| Longest session so far | 41 minutes, no crash | -| Memory | 40-46 GB of private memory: **64 GB of RAM recommended** | +| Prologue, indoors | about 20-22 fps on average, 24-31 fps in lighter places | +| Device losses | none in the measured runs | +| Menus, loading screens, subtitles | shown (they were black on Series S before) | +| First time a place is seen | slow for a moment while its shaders are made | -It started at 280 ms a frame in the same scenes two days earlier. +On the same card the fork's own settings skipped thousands of draws a frame +(the picture jumped and rarely updated), and the Series X profile at full scale +ran at about 6 fps. What is known to be wrong: -- Trees, plants and far buildings flicker outdoors in some places. -- Rooms with little direct light are too dark without `-RayTracing`. -- Textures of what just came into view appear late while the title streams. -- The first run with a new driver or a new build stutters while the driver makes - pipelines (`victory warm` makes them ahead). -- Recording a frame in the world makes the title's own watchdog end it. +- The picture is softer than Series X: half render scale, upscaled by the + title's own upscaler. +- Rooms with little direct light can be dark: ray walks end at the root while + the title's structure builder is off (`VICTORY_BVH_MISS`). +- Everything listed in the 7900 XTX fork's README still applies (flicker of far + plants outdoors, textures appearing late while the title streams, a stutter on + the first run with a new driver or build). ## How to run it @@ -43,15 +44,18 @@ model 6.6 and mesh shaders, Rust (the toolchain is pinned), the MSVC build tools, and your own dump of the title. ```powershell -git clone https://github.com/avatarmanz/VIctory-7900XTX -cd VIctory-7900XTX +git clone https://github.com/trustno1-coder/VIctory-NVIDIA +cd VIctory-NVIDIA copy victory.example.toml victory.toml # then set your paths, outside this folder cargo build --locked --profile diag -p victory --features diagnostics -scripts\play.ps1 -Exe <path of your copy's executable> +scripts\play-nvidia.ps1 -Exe <path of your copy's executable> ``` -`scripts\play.ps1 -Safe` leaves out the newest, faster ways; try it first when -something is wrong. `-RayTracing` turns the title's ray-traced indirect light on. +`scripts\play-nvidia.ps1` starts a copy of the build named `victory_sm.exe`, so +NVIDIA Smooth Motion applies every time once it is turned on for that exe in the +NVIDIA App. `-NoSmoothMotion` runs `victory.exe` itself; `-SeriesX` uses the +Series X profile (sharper, much slower). The fork's own `scripts\play.ps1` is +still there for AMD cards. Before the first run, ahead of time (both can be stopped and go on later): @@ -66,36 +70,46 @@ described in a comment where it is read. ## What is different here -In short; the reasons and the measurements are in [docs/findings.md](docs/findings.md). +- **No more skipped draws on NVIDIA** (`VICTORY_DYNAMIC_SLOTS=524288`): NVIDIA + caps the shader-visible view heap at 1,000,000 views, below the 1,245,184 the + title asks for. The pool of dynamic descriptor slots then ran out and + 1,100-4,800 descriptor tables a frame were refused, each one a dropped draw. + The pool can now take up to half the heap: 0-33 refused a frame. +- **Series S interface plane** (`VICTORY_COMPOSE=1`): a Series S title presents + the game (1080p) and the interface (4K) as two planes. Only the first was + shown, so menus, loading screens and subtitles were black. The interface is + now laid over the game. Ported from fxceless/victory-gta6 pull request 1189, + without its FSR stand-in. +- **Render scale and upscaler** (`VICTORY_RENDER_SCALE`, `VICTORY_OWN_UPSCALER`, + `VICTORY_NO_WATCHDOG`): patches to the 1.0.2.1 executable, from the + victory-perf patches. Series S needs the title's own upscaler at a scale + below 1. +- **Ray walks end at the root** (`VICTORY_BVH_MISS=1`) while the structure + builder is off. Its nodes are stale, so this avoids a hang and saves about + 10 ms a frame. +- **Memory compares on the card** (`VICTORY_CARD_BUFFERS_MIN_MB=1`, + `VICTORY_CARD_BUFFERS_MB=1536`): this took the Series S profile from 11 to + about 22 fps. -- **List calls are written down, not carried out, on the title's threads** - (`VICTORY_THIN`): eight threads of ours translate them. -- **Submissions are prepared by a thread of ours and joined** - (`VICTORY_ASYNC_SUBMIT`, `VICTORY_JOIN_PARTS`), with what can be spread over - threads spread: refreshes, compares (AVX2), descriptor records, landings. -- **What shaders wrote comes back beside the write guards**, by the dwords that - changed, on a thread of its own (`VICTORY_RELAY`, `VICTORY_LAND`). -- **Buffer fills that need bytes still on the card are done on the card** - (`VICTORY_CARD_STEPS`) instead of waiting for it. -- **The title's writes are caught more cheaply**: one view opened at a fault, - blocks that rest, places in the title's code that look before they write. -- **Textures go up on a copy queue of their own** and a slot shows one only after - its upload ran, which also ended a device loss that came every 15 minutes or so. -- **Boats float**: textures that shaders write and the title's CPU reads go back - to title memory (from fxceless and Geckomacabre, on by default here). -- **Frame record and replay** with per-pass times and shader variants compared - turn by turn ([docs/replay.md](docs/replay.md)). +Everything the 7900 XTX fork added is kept: translation of list calls on threads +of ours, submissions prepared and joined on a thread of ours, the write relay, +fills done on the card, textures on their own copy queue, texture read-back +(boats float), and frame record and replay. Its +[docs/findings.md](docs/findings.md) has the reasons and the measurements. ## Credits This is a tree of other people's work with more on top. The history is kept, and commits taken from elsewhere name the commit and its author. +- **[avatarmanz/VIctory-7900XTX](https://github.com/avatarmanz/VIctory-7900XTX)**: + the fork this one started from, and everything in it. - **[VIctory](https://github.com/Marvisak/VIctory)** by Marvisak and its contributors: the loader, the runtime services, the Direct3D 12 back end and the shader recompiler. - **[fxceless/victory-fork](https://github.com/fxceless/victory-fork)**: the fork - this one started from, and the people whose pull requests it carries. + the 7900 XTX one started from, the people whose pull requests it carries, and + pull request 1189 (Tissma95) for the Series S interface plane. - **[DexNom/VIctory](https://github.com/DexNom/VIctory)**: ray tracing fixes, cube gradients, sparse textures. - **[Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD)**: From 10e87106c2ad0c1e472c90ee4758149901b1d272 Mon Sep 17 00:00:00 2001 From: trustno1-coder <361337194+trustno1-coder@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:48:31 -0800 Subject: [PATCH 427/445] README: what this fork changes and how it gets its frame rate, at the top The settings that lower the picture (Series S profile, half render scale, the title's own upscaler, ray walks ended at the root), the ones that are faster without changing it (memory compares on the card, waiting for shaders, Smooth Motion), and the code changes that make it work on NVIDIA, with the measured frame rates of each step. The old list further down now points to it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 104 ++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 82 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 4a42f89..e94d595 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,85 @@ # VIctory on NVIDIA +## What this fork changes, and how it gets its frame rate + +Everything below is what `scripts\play-nvidia.ps1` turns on. Measured on an +RTX 5070 12 GB with a Ryzen 7 9800X3D, in the prologue: + +| Setup | fps | GPU time a frame | +|---|---|---| +| The 7900 XTX fork's own settings, Series X | high, but thousands of draws a frame skipped (the picture jumps) | - | +| With the descriptor fix, Series X, full scale | 6.0 | 110 ms | +| The same, half render scale | 7.2 | 82-88 ms | +| Series S, half scale, own upscaler, ray walks skipped | 11.0 | 33 ms | +| Plus memory compares on the card | 21.8 | about 6 ms | + +### Settings that lower the picture a bit + +1. **Series S profile** (`--console series-s`). The title believes it runs on + the smaller console and picks that console's settings. The biggest change + is resolution: the game image is 1920x1080 instead of the Series X's + 4K-class target. Menus, the HUD and subtitles are still drawn at 4K on a + separate plane, so they stay sharp. +2. **Half render scale** (`VICTORY_RENDER_SCALE=0.5`). A patch to the title's + 1.0.2.1 executable pins its internal render scale: the 3D world is drawn at + half width and half height (960x540 on Series S), a quarter of the pixels, + then stretched back to 1080p. This is why the world is softer than the menus. +3. **The title's own upscaler** (`VICTORY_OWN_UPSCALER=1`). On Series S the + title upscales with AMD FidelityFX (FSR), whose compute programs cannot be + translated here, so that step drew nothing. A patch makes the title use its + own temporal upscaler on every profile. It is not a quality setting in + itself, but Series S needs it for a scale below 1. +4. **Ray walks end at the root** (`VICTORY_BVH_MISS=1`). The part of the title + that builds its ray-tracing structures is off, so their nodes are stale. + Instead of walking stale nodes, every box and triangle test is a miss. That + avoids a hang and saves about 10 ms a frame, but light bounced off nearby + surfaces is lost, so some dim rooms look darker. + +### Settings that make it faster without changing the picture + +5. **Memory compares on the card** (`VICTORY_CARD_BUFFERS_MIN_MB=1`, + `VICTORY_CARD_BUFFERS_MB=1536`). Once the settings above had cut the GPU's + work, the CPU was the limit: every frame it compared about 190 MB of title + memory to find what the title had changed. These move the compares of copies + of 1 MiB or more to the graphics card. Copying back fell from about 27 to + 10 ms a frame, and the frame rate doubled (11 to 21.8 fps). +6. **Wait for new shaders** (`VICTORY_PIPELINE_WAIT_MS=10000`). Draws wait for + a pipeline still being made instead of being skipped: nothing is missing, + with a short hitch the first time a place is seen. +7. **NVIDIA Smooth Motion** (by default in `play-nvidia.ps1`). The script + starts a copy of the build named `victory_sm.exe`; with Smooth Motion turned + on for that exe in the NVIDIA App, the driver inserts a generated frame + between real ones, so motion looks about twice as smooth. The title still + runs at the real rate underneath, so controls respond at about 20 fps. + +### Code changes (what makes it work on NVIDIA at all) + +8. **No more skipped draws on NVIDIA** (`VICTORY_DYNAMIC_SLOTS=524288`, + `crates/victory-gpu/src/descriptor/host.rs`). NVIDIA caps the shader-visible + view heap at 1,000,000 views, below the 1,245,184 the title asks for. The + pool of dynamic descriptor slots (2^18) then ran out, and 1,100-4,800 + descriptor tables a frame were refused, each one a dropped draw: the screen + rarely updated and the character jumped from place to place. The pool can + now take up to half the heap: 0-33 refused a frame. +9. **Series S interface plane** (`VICTORY_COMPOSE=1`, + `crates/victory-gpu/src/compose.rs`, `host.rs`, `queue.rs`). A Series S + title presents two planes: the game (1080p) and the interface (4K). Only the + first was shown, so menus, loading screens and subtitles were black until + gameplay. One compute pass now lays the interface over the game before it + is shown. Ported from fxceless/victory-gta6 pull request 1189 (Tissma95), + without its FSR stand-in (the own upscaler is used instead). +10. **Title patches** (`crates/victory-loader/src/hooks.rs`, `lib.rs`, + `windows.rs`): render scale, own upscaler, and `VICTORY_NO_WATCHDOG` + (keeps the title's watchdog from ending a slow frame), taken from the + victory-perf patches. +11. **Ray walks end at the root** (`crates/victory-shader/src/emit/intersect.rs`, + `crates/victory-gpu/src/shader_cache.rs`): the `VICTORY_BVH_MISS` switch, made + part of the shader cache key so translated shaders with and without it are + kept apart. +12. **`scripts/play-nvidia.ps1`**: the launcher with all of the above. + +--- + A fork of [avatarmanz/VIctory-7900XTX](https://github.com/avatarmanz/VIctory-7900XTX), itself a fork of [VIctory](https://github.com/Marvisak/VIctory), a compatibility layer that runs an Xbox Series title natively on Windows from files the user @@ -70,28 +150,8 @@ described in a comment where it is read. ## What is different here -- **No more skipped draws on NVIDIA** (`VICTORY_DYNAMIC_SLOTS=524288`): NVIDIA - caps the shader-visible view heap at 1,000,000 views, below the 1,245,184 the - title asks for. The pool of dynamic descriptor slots then ran out and - 1,100-4,800 descriptor tables a frame were refused, each one a dropped draw. - The pool can now take up to half the heap: 0-33 refused a frame. -- **Series S interface plane** (`VICTORY_COMPOSE=1`): a Series S title presents - the game (1080p) and the interface (4K) as two planes. Only the first was - shown, so menus, loading screens and subtitles were black. The interface is - now laid over the game. Ported from fxceless/victory-gta6 pull request 1189, - without its FSR stand-in. -- **Render scale and upscaler** (`VICTORY_RENDER_SCALE`, `VICTORY_OWN_UPSCALER`, - `VICTORY_NO_WATCHDOG`): patches to the 1.0.2.1 executable, from the - victory-perf patches. Series S needs the title's own upscaler at a scale - below 1. -- **Ray walks end at the root** (`VICTORY_BVH_MISS=1`) while the structure - builder is off. Its nodes are stale, so this avoids a hang and saves about - 10 ms a frame. -- **Memory compares on the card** (`VICTORY_CARD_BUFFERS_MIN_MB=1`, - `VICTORY_CARD_BUFFERS_MB=1536`): this took the Series S profile from 11 to - about 22 fps. - -Everything the 7900 XTX fork added is kept: translation of list calls on threads +This fork's own changes are listed at the top of this README. Everything the +7900 XTX fork added is kept: translation of list calls on threads of ours, submissions prepared and joined on a thread of ours, the write relay, fills done on the card, textures on their own copy queue, texture read-back (boats float), and frame record and replay. Its From 0cdad6b35716c8b0dea9dbe0d5a07dac359d563d Mon Sep 17 00:00:00 2001 From: trustno1-coder <361337194+trustno1-coder@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:09:17 -0800 Subject: [PATCH 428/445] README: list the projects this fork was built from Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e94d595..be2c1ea 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,52 @@ # VIctory on NVIDIA +## Built from many projects + +This repository did not come from one place. Over several weeks we built, ran +and measured the work of many projects on the same NVIDIA machine, kept what +worked on this card, and brought the best of each together here. No single one +of them runs this well on NVIDIA by itself; the combination is what gets it to +where it is now. + +Code that is in this repository: + +- [avatarmanz/VIctory-7900XTX](https://github.com/avatarmanz/VIctory-7900XTX): + the base. Its threading, write relay, card fills, copy queue and texture + read-back are all kept. +- [Marvisak/VIctory](https://github.com/Marvisak/VIctory): the original + compatibility layer under everything else (loader, runtime services, + Direct3D 12 back end, shader recompiler). +- [fxceless/victory-fork](https://github.com/fxceless/victory-fork) (formerly + victory-gta6): the fork the 7900 XTX one grew from, and the Series S interface + plane (pull request 1189, Tissma95), which fixed the black menus. +- victory-perf, carrying patches from + [ZigZagBoi1/ScarlettPort](https://github.com/ZigZagBoi1/ScarlettPort): the + title patches for render scale, the title's own upscaler and the watchdog. +- Through the 7900 XTX fork: + [DexNom/VIctory](https://github.com/DexNom/VIctory), + [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD), + [FQY55kai/ZJOU-VICTORY](https://github.com/FQY55kai/ZJOU-VICTORY), + [myokex/victory-amd](https://github.com/myokex/victory-amd), Geckomacabre and + cxy0072019-sketch. + +Projects we ran, tested or studied along the way, whose lessons shaped the +settings and fixes here (none of their code is in this repository unless listed +above): + +- ProjectLeonida/Leonida (no longer public): the first attempt, where the + retail executable's boot was worked through. +- Our own builds of Marvisak/VIctory and fxceless/victory-fork, where the + ray-walk skip, the half render scale and most of the measurements in the + table below came from. +- [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD) + builds with its fixes combined. +- [zm0kiemedia/Neptune_VI](https://github.com/zm0kiemedia/Neptune_VI) (formerly + vicecitybaby). +- [xcl-dev/xcl](https://github.com/xcl-dev/xcl), another layer for the same + title, read for how the title behaves there. + +Full credits, with what each person contributed, are at the end of this README. + ## What this fork changes, and how it gets its frame rate Everything below is what `scripts\play-nvidia.ps1` turns on. Measured on an @@ -179,7 +226,7 @@ commits taken from elsewhere name the commit and its author. every view of a page (with Spexivus, joroyt and tightfall), and Joshua Odom's reads into title memory. - **Geckomacabre** and **cxy0072019-sketch**: the texture read-back. -- **[XCL](https://github.com/ivall/xcl)** (GPL-2.0-only) was read for how the same +- **[XCL](https://github.com/xcl-dev/xcl)** (GPL-2.0-only) was read for how the same title behaves under another layer; no code of it is here. - This fork's changes were made with [Claude Code](https://claude.com/claude-code). From 3e5fb36392796602fce70aa7331f4100be9291af Mon Sep 17 00:00:00 2001 From: trustno1-coder <canthuit7@gmail.com> Date: Wed, 25 Nov 2026 16:19:59 -0800 Subject: [PATCH 429/445] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index be2c1ea..676710f 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ where it is now. Code that is in this repository: - [avatarmanz/VIctory-7900XTX](https://github.com/avatarmanz/VIctory-7900XTX): - the base. Its threading, write relay, card fills, copy queue and texture + Its threading, write relay, card fills, copy queue and texture read-back are all kept. - [Marvisak/VIctory](https://github.com/Marvisak/VIctory): the original compatibility layer under everything else (loader, runtime services, From 77e13a974aed142f5d9f8b80d54ed6de41bfa140 Mon Sep 17 00:00:00 2001 From: trustno1-coder <361337194+trustno1-coder@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:13:08 -0800 Subject: [PATCH 430/445] Faces move, ray tracing mostly off, intro video fix, picture fixes - Faces: the face network's 16-bit values travel through integer views; they were read as floats and came back as zeros on NVIDIA. Port of fxceless/victory-fork pull request 927 (tippythetaidum): emit/halves.rs, lower.rs, descriptor/host.rs, draw.rs. - Ray tracing mostly off: scripts/rt_off_hashes.txt lists the 1,000 CS_RaytracingResolve and 34 traced-shadow shaders, skipped by play-nvidia.ps1 through VICTORY_SKIP_PIPELINES (-RayTracing keeps them). The structure builder cannot run on NVIDIA, so every ray missed and rooms went white depending on the view angle. The screen-probe and visibility traces keep running; skipping them left rainbow glitter. - Intro video flicker: linear one-level R8 video planes always record their copy (texture.rs), so frames of the ring no longer show out of order. - VICTORY_AMBIENT_MOST (ambient.rs), VICTORY_NAN_SCRUB (emit/lower.rs) and VICTORY_PIPELINE_WAIT_ONCE (pipeline/make.rs, on by default). - Off by default: VICTORY_CONSTANT_MARKS (port of fxceless pull request 1216), VICTORY_TARGET_VARIANTS (port of fxceless a35c557393), F9 frame capture (capture.rs). - play-nvidia.ps1: the speed set by default, -Quality for the slower set with fewer stretched bodies and less rainbow skin. README updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 66 ++- crates/victory-gpu/src/ambient.rs | 17 +- crates/victory-gpu/src/capture.rs | 24 +- crates/victory-gpu/src/descriptor.rs | 68 +++ crates/victory-gpu/src/descriptor/host.rs | 400 +++++++++++++- crates/victory-gpu/src/draw.rs | 108 +++- crates/victory-gpu/src/pipeline.rs | 15 + crates/victory-gpu/src/pipeline/host.rs | 78 +++ crates/victory-gpu/src/pipeline/make.rs | 96 +++- crates/victory-gpu/src/shader_cache.rs | 16 + crates/victory-gpu/src/texture.rs | 60 ++- crates/victory-shader/src/emit/diff_tests.rs | 19 +- crates/victory-shader/src/emit/halves.rs | 148 ++++++ crates/victory-shader/src/emit/host.rs | 13 +- .../src/emit/intersect_tests.rs | 1 + crates/victory-shader/src/emit/lower.rs | 233 +++++++-- crates/victory-shader/src/emit/mod.rs | 25 +- .../victory-shader/src/emit/permlane_tests.rs | 1 + crates/victory-shader/src/emit/probe_tests.rs | 1 + crates/victory-shader/src/emit/rect.rs | 1 + crates/victory-shader/src/emit/shader.rs | 19 + crates/victory-shader/src/emit/size_tests.rs | 1 + crates/victory-shader/src/emit/valu_tests.rs | 487 ++++++++++++++++++ .../src/emit/waterfall_tests.rs | 2 + .../victory-shader/src/emit/wave64_tests.rs | 2 + scripts/play-nvidia.ps1 | 39 +- scripts/rt_off_hashes.txt | 1 + 27 files changed, 1868 insertions(+), 73 deletions(-) create mode 100644 crates/victory-shader/src/emit/halves.rs create mode 100644 scripts/rt_off_hashes.txt diff --git a/README.md b/README.md index 676710f..045c30f 100644 --- a/README.md +++ b/README.md @@ -17,8 +17,9 @@ Code that is in this repository: compatibility layer under everything else (loader, runtime services, Direct3D 12 back end, shader recompiler). - [fxceless/victory-fork](https://github.com/fxceless/victory-fork) (formerly - victory-gta6): the fork the 7900 XTX one grew from, and the Series S interface - plane (pull request 1189, Tissma95), which fixed the black menus. + victory-gta6): the fork the 7900 XTX one grew from, the Series S interface + plane (pull request 1189, Tissma95), which fixed the black menus, and the face + network fix (pull request 927, tippythetaidum), which made faces move. - victory-perf, carrying patches from [ZigZagBoi1/ScarlettPort](https://github.com/ZigZagBoi1/ScarlettPort): the title patches for render scale, the title's own upscaler and the watchdog. @@ -123,7 +124,60 @@ RTX 5070 12 GB with a Ryzen 7 9800X3D, in the prologue: `crates/victory-gpu/src/shader_cache.rs`): the `VICTORY_BVH_MISS` switch, made part of the shader cache key so translated shaders with and without it are kept apart. -12. **`scripts/play-nvidia.ps1`**: the launcher with all of the above. +12. **`scripts/play-nvidia.ps1`**: the launcher with all of this list. +13. **Faces move** (`crates/victory-shader/src/emit/halves.rs`, `lower.rs`, + `crates/victory-gpu/src/descriptor/host.rs`, `draw.rs`). Faces are driven by + a network of compute programs whose numbers travel as 16-bit values through + integer views; they were read as floats and came back as zeros on NVIDIA, so + no face moved. They now move as integers. Ported from fxceless/victory-fork + pull request 927 (tippythetaidum). + +14. **Ray tracing mostly off** (`scripts/rt_off_hashes.txt`, used by + `play-nvidia.ps1` through `VICTORY_SKIP_PIPELINES`; `-RayTracing` keeps the + passes). The title's ray-tracing structure builder cannot run on NVIDIA (its + 64-lane programs are refused; Marvisak/VIctory pull request 2311), so every + ray misses. The passes that turn those misses into light made rooms go white + and hazy depending on the view angle. The 1,000 `CS_RaytracingResolve` and + 34 traced-shadow shaders are skipped. The screen-probe and visibility traces + keep running: skipping them too (all 1,052 shaders of fxceless pull request + 465's rule) left their outputs as garbage, rainbow glitter everywhere. Needs + the `diag` build (the skip list is a diagnostics switch). +15. **The intro video no longer flickers** (`crates/victory-gpu/src/texture.rs`). + The movie's planes (linear, one-level R8 textures in a ring of three) were + written by the decoder through another view of the same memory, judged + clean when the frame was recorded, and copied a list late: frames from the + ring showed out of order. Video planes now always record their copy. + +### Settings + +The default set of `play-nvidia.ps1` is the speed set (about 18-22 fps on the +RTX 5070). `-Quality` trades about 7 fps for fewer of the first two faults +below. + +| Fault | Cause | Fix | +|---|---|---| +| Stretched bodies that jump | The relay's second stage and card steps hand skinned meshes back before they are done (avatarmanz issue 13; fxceless issue 89 on an RTX 5070) | `-Quality`: `VICTORY_RELAY=1`, `VICTORY_CARD_STEPS=0` | +| Rainbow, pixelated skin | A texture refresh that does not wait for the runtime's remapping fills its upload from pages not there yet | `-Quality`: `VICTORY_TEXTURE_NO_WAIT=0` | +| Some views far too bright | Without rays the light probes keep the sky's light indoors, and the fog takes it too | Always: `VICTORY_AMBIENT_AIR=1.5` (fog at most 1.5 times the light around), `VICTORY_AMBIENT_MOST=2` (new, `ambient.rs`; was a fixed 4) | +| The picture stops until you look away | A pipeline that takes longer than the wait was waited for again in every frame it was in view | Always: each pipeline is waited for once at most (`VICTORY_PIPELINE_WAIT_ONCE`, on; `pipeline/make.rs`; the problem of fxceless issue 1181) | +| Black blobs on faces and in the air | A NaN that a shader writes is spread by blur and the temporal upscaler | Always: `VICTORY_NAN_SCRUB=1` (new, `emit/lower.rs`): colours and image stores with NaN become 0; NaN in the fog volume is cleared too | + +Known faults left: the common room by its sunlit windows still goes beige and +hazy (sky light in the fog); smearing when the camera moves fast at half scale +(the title's own temporal upscaler); two orange glows on some corridor walls. +Render scale 1.0 on Series S has not been tested. + +Also in, off by default: + +- `VICTORY_CONSTANT_MARKS=1`, a port of fxceless pull request 1216 + (GamingRipperDoc): a slot picked from the heap is read as a constant buffer + only if it holds one (else a texture's descriptor was read as one, in the + meshlet culling passes). +- `VICTORY_TARGET_VARIANTS=1`, a port of fxceless a35c557393: a pipeline is made + again for the render target formats bound at the draw. +- F9 frame capture (`capture.rs`): with `VICTORY_CAPTURE=<folder>` and + `VICTORY_DUMP_TARGETS=1`, F9 saves the next frame's picture, its commands and + every 2D target. --- @@ -215,8 +269,10 @@ commits taken from elsewhere name the commit and its author. contributors: the loader, the runtime services, the Direct3D 12 back end and the shader recompiler. - **[fxceless/victory-fork](https://github.com/fxceless/victory-fork)**: the fork - the 7900 XTX one started from, the people whose pull requests it carries, and - pull request 1189 (Tissma95) for the Series S interface plane. + the 7900 XTX one started from, the people whose pull requests it carries, + pull request 1189 (Tissma95) for the Series S interface plane, 927 + (tippythetaidum) for the face network and 1216 (GamingRipperDoc) for the + marked constant buffer slots. - **[DexNom/VIctory](https://github.com/DexNom/VIctory)**: ray tracing fixes, cube gradients, sparse textures. - **[Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD)**: diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs index 8a3d46e..326b6ef 100644 --- a/crates/victory-gpu/src/ambient.rs +++ b/crates/victory-gpu/src/ambient.rs @@ -112,6 +112,18 @@ fn air() -> f32 { }) } +/// LOCAL: how many times the estimate the title's own result may keep +/// (`VICTORY_AMBIENT_MOST=<multiple>`, 4 when unset). Without rays the +/// probes hold the sky's light indoors too; at 4 times the estimate a room +/// looked towards a window or the sky goes very bright. +fn most() -> f32 { + static SET: OnceLock<f32> = OnceLock::new(); + *SET.get_or_init(|| { + let set = std::env::var("VICTORY_AMBIENT_MOST").unwrap_or_default(); + set.trim().parse().ok().filter(|v: &f32| v.is_finite() && *v > 0.0).unwrap_or(4.0) + }) +} + /// Strength and radius of the creases' shade. fn shade() -> [f32; 2] { static SET: OnceLock<[f32; 2]> = OnceLock::new(); @@ -243,6 +255,9 @@ void clear_air(uint3 at : SV_DispatchThreadID) { 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]; + // LOCAL: a NaN or infinity in the air is summed along every view ray + // through it: black or white patches floating in the room. + if (any(isnan(c)) || any(isinf(c))) { scattered[at] = 0; return; } float has = dot(c, LUMA); if (has > cap) scattered[at] = c * (cap / has); } @@ -459,7 +474,7 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { words[6] = views.size[0]; words[7] = views.size[1]; words[8] = 0.04f32.to_bits(); - words[9] = 4.0f32.to_bits(); + words[9] = most().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 diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index 937f560..9994c3f 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -27,7 +27,8 @@ pub(crate) fn listed(n: u64) -> bool { .filter_map(|f| f.trim().parse().ok()) .collect() }) - .contains(&n); + .contains(&n) + || n == KEY_FRAME.load(std::sync::atomic::Ordering::Relaxed); // `VICTORY_CAPTURE_WORLD`: also the 2nd and the 6th frame after the first // one that ran 500 draws or more (a title's first 3D frames: their // numbers depend on how long the menus were shown), and the 30th and @@ -120,12 +121,33 @@ fn world_on() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_CAPTURE_WORLD").is_some()) } +/// LOCAL: the frame F9 asked for ([`frame_drew`]); `u64::MAX`: none. +static KEY_FRAME: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX); + /// The first frame that ran 500 draws or more (`VICTORY_CAPTURE_WORLD`). static WORLD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX); /// At the present of `frame`: the draws run on the host so far. pub(crate) fn frame_drew(frame: u64, drawn: u64) { use std::sync::atomic::Ordering::Relaxed; + // LOCAL: with a capture folder, F9 captures the next frame as a listed + // one (its picture, its ops and, with VICTORY_DUMP_TARGETS=1, every + // target it drew): to catch a picture fault the moment it shows. + if folder().is_some() { + static WAS_DOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + // SAFETY: a plain query of the keyboard's state. + let down = unsafe { + windows_sys::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState(i32::from( + windows_sys::Win32::UI::Input::KeyboardAndMouse::VK_F9, + )) + } < 0; + if down && !WAS_DOWN.swap(true, Relaxed) { + KEY_FRAME.store(frame + 1, Relaxed); + tracing::info!(frame = frame + 1, "F9: this frame is captured"); + } else if !down { + WAS_DOWN.store(false, Relaxed); + } + } static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let before = LAST.swap(drawn, Relaxed); if world_on() diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 9c3cc2e..26d44d8 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -1588,6 +1588,74 @@ mod tests { ); } + /// A table made afresh for a draw holds the descriptors its shader + /// moves halves through (`HostShader::half_views`), also past the range + /// starts its used-resource entries give: with one entry for a range + /// from dword 0 and a 16-bit float buffer view at dword 8, the table + /// takes two dynamic slots, so the next allocation does not land on the + /// view's. (The case avt0m4t48 found in review on #927.) + #[cfg(windows)] + #[test] + fn a_fresh_table_holds_the_half_views_past_its_range_starts() { + use victory_shader::{ResourceType, RootType, UsedResource}; + let Some(device) = crate::host::host() else { + return; // no host GPU + }; + let list = device.new_list().expect("a host list"); + let desc = HeapDesc { + kind: VIEWS_KIND, + count: 2, + flags: SHADER_VISIBLE, + nodes: 1, + }; + let none = Placement { + address: 0, + size: 0, + }; + let mut h: This = std::ptr::null(); + assert_eq!(create(desc, none, &mut h), S_OK); + let title = heap(h); + let host_heap = title.host().expect("a host view heap"); + let (first, second) = (title.handle(0).unwrap(), title.handle(1).unwrap()); + // An R16G16B16A16_FLOAT buffer view of memory in the second slot. + let memory = [0u64; 64]; + let address = memory.as_ptr() as u64; + let resource = [1, 0, 0, 0, 512, 0, 1, 0x1_0001, 0, 1, 0, 1, 0, 0]; + let mut words = [0u32; 16]; + words[..10].copy_from_slice(&[10, 1, 5768, 0, 0, 0, 64, 0, 0, 0]); + words[10] = address as u32; + words[11] = (address >> 32) as u32; + create_placed_srv(std::ptr::null(), &resource, &words, second); + assert!(view(second).as_ref().and_then(host::half_view).is_some()); + let mut state = crate::draw::State::default(); + state.set_heaps(&[h]); + state.set_table(true, 1, first); + let range = UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 8, + dwords: 4, + user_data: 4, + slot: 1, + }; + let made = state.tables(&list, &[range], &[], &[(1, 8)], true); + let [(1, offset)] = made[..] else { + panic!("one fresh table for root parameter 1, not {:?}", &made[..]); + }; + assert_ne!(offset, u32::MAX, "the table found no dynamic slots"); + let next = host_heap.dynamic(1).expect("a dynamic slot"); + host_heap.release(next, 1); + drop(state); + slot::<extern "system" fn(This) -> u32>(h, 0x10)(h); + assert_eq!( + next, + offset / 32 + 2, + "the next allocation took the table's second slot" + ); + } + #[test] fn heaps_hold_count_descriptors_from_their_start() { let null = std::ptr::null(); diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 9fd871b..b6e8f9c 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -893,6 +893,14 @@ struct Waiting { checked: (u64, u64, u64, u8, u64), } +/// Whether due texture slots are served in turns, a slot looked at before +/// and one never looked at ([`TextureQueue::due`]; on unless +/// `VICTORY_FAIR_DUE=0`). +fn fair_due() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_FAIR_DUE").is_none_or(|v| v != "0")) +} + /// The queue of title slots whose texture view waits to be brought up to /// date for shaders that pick textures by index: which are due, and in /// which order (no host heap needed, so it is tested without one). @@ -926,14 +934,20 @@ impl TextureQueue { /// Up to `max` slots due at `frame`, each with its write number, in /// the order to serve them: - /// - first the ones looked at before (their memory was not mapped, or - /// only part of it): the look is a query, and memory that has - /// arrived since is what the title streamed in last; - /// - then the others, the newest write first and the oldest next, in - /// turns: slot order served the low slots of a backlog of - /// 25,000-40,000 while the textures of the shot on screen waited - /// (run 52: 98% of the drawn pixels had no colour texture in the - /// first 3D frames). + /// - the ones looked at before (their memory was not mapped, or only + /// part of it), newest write first: the look is a query, and memory + /// that has arrived since is what the title streamed in last; + /// - the others, the newest write first and the oldest next, in turns: + /// slot order served the low slots of a backlog of 25,000-40,000 + /// while the textures of the shot on screen waited (run 52: 98% of + /// the drawn pixels had no colour texture in the first 3D frames); + /// - the two kinds one after the other, a slot looked at before first + /// (`VICTORY_FAIR_DUE=0`: all those looked at before first, as + /// before). With them all first, a backlog of thousands of slots + /// streaming in a part at a time filled every pass in the opening + /// cutscene, which the pass's time then cut, and slots never looked + /// at waited 300 to 1,500 frames: faces whose textures are picked by + /// index read an empty slot (black) or an older view (red, noise). fn due(&self, frame: u64, max: usize) -> Vec<(u32, u64)> { let mut again: Vec<(u64, u32, u64)> = Vec::new(); let mut fresh: Vec<(u64, u32, u64)> = Vec::new(); @@ -945,16 +959,33 @@ impl TextureQueue { let newest_first = |a: &(u64, u32, u64), b: &(u64, u32, u64)| b.2.cmp(&a.2); again.sort_unstable_by(newest_first); fresh.sort_unstable_by(newest_first); - let mut order: Vec<(u32, u64)> = again.iter().map(|&(_, index, write)| (index, write)).collect(); + let mut fresh_order: Vec<(u32, u64)> = Vec::with_capacity(fresh.len().min(max)); let (mut new, mut old) = (0, fresh.len()); - while new < old && order.len() < max { - order.push((fresh[new].1, fresh[new].2)); + while new < old && fresh_order.len() < max { + fresh_order.push((fresh[new].1, fresh[new].2)); new += 1; - if new < old && order.len() < max { + if new < old && fresh_order.len() < max { old -= 1; - order.push((fresh[old].1, fresh[old].2)); + fresh_order.push((fresh[old].1, fresh[old].2)); } } + let mut again_order = again.iter().map(|&(_, index, write)| (index, write)); + if !fair_due() { + let mut order: Vec<(u32, u64)> = again_order.collect(); + order.extend(fresh_order); + order.truncate(max); + return order; + } + let mut fresh_order = fresh_order.into_iter(); + let mut order = Vec::with_capacity(max.min(fresh.len() + again.len())); + while order.len() < max { + let (a, b) = (again_order.next(), fresh_order.next()); + if a.is_none() && b.is_none() { + break; + } + order.extend(a); + order.extend(b); + } order.truncate(max); order } @@ -2520,9 +2551,18 @@ impl HostHeap { if let Some((_, _, data)) = &self.strides && index < victory_shader::emit::SLOT_STRIDES_COUNT { + // LOCAL (port of fxceless #1216): constant buffer views marked; + // programs read no other non-buffer slot as one. + let entry = match (stride, view) { + (Some(s), _) => s | kind, + (None, Some(View::Constant(..))) if victory_shader::emit::constant_marks() => { + victory_shader::emit::SLOT_STRIDE_CONSTANT + } + _ => kind, + }; // 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) | kind) }; + unsafe { (*data as *mut u32).add(index as usize).write_volatile(entry) }; } let was = if stride.is_some() { self.buffers.put(index); @@ -3259,6 +3299,76 @@ fn srv_desc(words: &[u32; 10]) -> D3D12_SHADER_RESOURCE_VIEW_DESC { } } +/// The unsigned integer format with the layout of a 16-bit float or +/// signed integer format (one, two or four channels), if `format` is one. +pub(crate) fn half_format(format: u32) -> Option<u32> { + match format { + // R16G16B16A16_FLOAT and _SINT: R16G16B16A16_UINT. + 10 | 14 => Some(12), + // R16G16_FLOAT and _SINT: R16G16_UINT. + 34 | 38 => Some(36), + // R16_FLOAT and _SINT: R16_UINT. + 54 | 59 => Some(57), + _ => None, + } +} + +/// `view` as a shader is shown it where it moves a buffer's 16-bit +/// channels as unsigned integers +/// (`victory_shader::emit::HostShader::half_views`): a buffer view in a +/// 16-bit float or signed format, in the unsigned format of the same +/// layout, through which every 16-bit pattern is read and stored as it +/// is. `None` for every other view: the title's own serves (an unsigned +/// one already carries the bits; a texture can only be viewed in the +/// formats it was made for). +pub(crate) fn half_view(view: &View) -> Option<View> { + // Buffer views: dimension 1 in the title's description of either kind. + const BUFFER: u32 = 1; + match view { + View::Shader(resource, Some(desc)) if desc[1] == BUFFER => { + let mut desc = *desc; + desc[0] = half_format(desc[0])?; + Some(View::Shader(*resource, Some(desc))) + } + View::Unordered(resource, counter, Some(desc)) if desc[1] == BUFFER => { + let mut desc = *desc; + desc[0] = half_format(desc[0])?; + Some(View::Unordered(*resource, *counter, Some(desc))) + } + View::Placed(unordered, resource, desc) if resource[0] == BUFFER && desc[1] == BUFFER => { + let mut desc = *desc; + desc[0] = half_format(desc[0])?; + Some(View::Placed(*unordered, *resource, desc)) + } + _ => None, + } +} + +/// The format of `view`, a buffer view through which a shader moves +/// 16-bit channels as unsigned integers +/// (`victory_shader::emit::HostShader::half_views`), if those integers +/// are not what the console gives: a format of wider channels, a +/// normalised one or a signed 8-bit one, whose values the console converts +/// to and from halves. `None` for the formats the integers serve exactly +/// (16 bits a channel of any kind, through [`half_view`] where needed, and +/// unsigned channels of fewer bits; the title's are 16-bit unsigned) and +/// for any other view. +pub(crate) fn half_inexact(view: &View) -> Option<u32> { + // Buffer views: dimension 1 in the title's description of either kind. + const BUFFER: u32 = 1; + // R16G16B16A16, R16G16 and R16 (float, unsigned, signed), then + // R10G10B10A2, R8G8B8A8, R8G8 and R8 unsigned. + const EXACT: [u32; 13] = [10, 12, 14, 34, 36, 38, 54, 57, 59, 25, 30, 50, 62]; + let format = match view { + View::Shader(_, Some(desc)) | View::Unordered(_, _, Some(desc)) if desc[1] == BUFFER => { + desc[0] + } + View::Placed(_, resource, desc) if resource[0] == BUFFER && desc[1] == BUFFER => desc[0], + _ => return None, + }; + (!EXACT.contains(&format)).then_some(format) +} + fn uav_desc(words: &[u32; 10]) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { let mut words = *words; words[0] = crate::resource::pc_format(words[0]); @@ -4688,6 +4798,243 @@ mod tests { super::read_all(start); } + /// The unsigned twin of a 16-bit float or signed format has its layout, + /// and only buffer views in such a format are shown as another view. + #[test] + fn only_16_bit_float_and_signed_buffer_views_get_an_unsigned_twin() { + for (format, unsigned) in [(10, 12), (14, 12), (34, 36), (38, 36), (54, 57), (59, 57)] { + assert_eq!(half_format(format), Some(unsigned)); + assert_eq!( + crate::resource::element(format), + crate::resource::element(unsigned), + "format {format}" + ); + } + // The unsigned formats themselves, normalised 16-bit formats, and + // wider and narrower ones. + for other in [0, 12, 36, 57, 11, 13, 35, 37, 56, 58, 42, 17, 30, 61] { + assert_eq!(half_format(other), None, "format {other}"); + } + const BUFFER: u32 = 1; + let words = |format: u32, dimension: u32| [format, dimension, 5768, 0, 0, 0, 64, 0, 0, 0]; + // R16G16B16A16_FLOAT: a buffer of halves a program moves as they are. + assert_eq!( + half_view(&View::Unordered(7, 0, Some(words(10, BUFFER)))), + Some(View::Unordered(7, 0, Some(words(12, BUFFER)))) + ); + assert_eq!( + half_view(&View::Shader(7, Some(words(54, BUFFER)))), + Some(View::Shader(7, Some(words(57, BUFFER)))) + ); + let mut placed = [0u32; 16]; + placed[..10].copy_from_slice(&words(38, BUFFER)); + placed[10] = 0x1234_0000; + let mut twin = placed; + twin[0] = 36; + let memory = [BUFFER, 0, 0, 0, 512, 0, 1, 0x1_0001, 0, 1, 0, 1, 0, 0]; + assert_eq!( + half_view(&View::Placed(true, memory, placed)), + Some(View::Placed(true, memory, twin)) + ); + // The title's kind (R16G16B16A16_UINT and R16_UINT buffers), a + // texture view (dimension 4: 2D), a view without a description, a + // constant buffer: the title's own. + assert_eq!( + half_view(&View::Unordered(7, 0, Some(words(12, BUFFER)))), + None + ); + assert_eq!(half_view(&View::Shader(7, Some(words(57, BUFFER)))), None); + assert_eq!(half_view(&View::Unordered(7, 0, Some(words(10, 4)))), None); + assert_eq!(half_view(&View::Shader(7, None)), None); + assert_eq!(half_view(&View::Constant(0x1000, 256)), None); + } + + /// The buffer views through which the integers a shader moves halves + /// as are not what the console gives are named; the title's are not. + #[test] + fn views_whose_values_the_console_would_convert_are_named() { + const BUFFER: u32 = 1; + let words = |format: u32, dimension: u32| [format, dimension, 5768, 0, 0, 0, 64, 0, 0, 0]; + for exact in [10, 12, 14, 34, 36, 38, 54, 57, 59, 25, 30, 50, 62] { + let view = View::Unordered(7, 0, Some(words(exact, BUFFER))); + assert_eq!(half_inexact(&view), None, "format {exact}"); + } + // R32_FLOAT, R32_UINT, R16G16B16A16_UNORM, R8G8B8A8_UNORM, R8_SINT, + // and a structured or raw view (no format). + for inexact in [41, 42, 11, 28, 64, 0] { + let view = View::Shader(7, Some(words(inexact, BUFFER))); + assert_eq!(half_inexact(&view), Some(inexact)); + } + let mut placed = [0u32; 16]; + placed[..10].copy_from_slice(&words(41, BUFFER)); + let memory = [BUFFER, 0, 0, 0, 512, 0, 1, 0x1_0001, 0, 1, 0, 1, 0, 0]; + assert_eq!(half_inexact(&View::Placed(true, memory, placed)), Some(41)); + // Not a buffer view. + assert_eq!(half_inexact(&View::Shader(7, Some(words(41, 4)))), None); + assert_eq!(half_inexact(&View::Constant(0x1000, 256)), None); + } + + /// The two ways a translated `buffer_load_format_d16_xyzw` and + /// `buffer_store_format_d16_xyzw` have moved a typed buffer's 16-bit + /// channels, on the host device, over a buffer that holds every 16-bit + /// pattern. As unsigned integers through an unsigned view (the title's + /// own R16G16B16A16_UINT, or the twin `half_view` gives a float one) + /// every pattern comes back as it was. By way of floats, as before + /// (load as floats, each to its half's bits; each half widened and + /// stored as a float): through the title's integer view that is + /// outside what D3D12 defines, and what the device gives is printed, + /// not checked (1 pattern of 65,536 on the cards tried: the network + /// that moves the title's faces computed zeros). + #[test] + fn halves_cross_an_unsigned_buffer_view_unchanged() { + const MOVES: &str = r#" +#define RS "DescriptorTable(UAV(u0, numDescriptors=2))" +#ifdef BY_FLOATS +RWBuffer<float4> from : register(u0); +RWBuffer<float4> to : register(u1); +#else +RWBuffer<uint4> from : register(u0); +RWBuffer<uint4> to : register(u1); +#endif +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void BY_FLOATS_OR_NOT(uint3 id : SV_DispatchThreadID) { +#ifdef BY_FLOATS + uint4 h = f32tof16(from[id.x]); +#else + uint4 h = from[id.x] & 0xffff; +#endif + uint low = h.x | h.y << 16; + uint high = h.z | h.w << 16; +#ifdef BY_FLOATS + to[id.x] = float4(f16tof32(low), f16tof32(low >> 16), f16tof32(high), f16tof32(high >> 16)); +#else + to[id.x] = uint4(low & 0xffff, low >> 16, high & 0xffff, high >> 16); +#endif +} +"#; + const ELEMENTS: usize = 1 << 14; + const BYTES: u64 = ELEMENTS as u64 * 8; + const TITLES: u32 = 12; // R16G16B16A16_UINT + let Some(host) = host() else { + return; // no host GPU + }; + let heap: ID3D12DescriptorHeap = { + let desc = D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }; + // SAFETY: plain heap creation. + unsafe { host.device.CreateDescriptorHeap(&desc) }.expect("a view heap") + }; + // How many of the 65,536 patterns come back as they were, moved by + // the program `by_floats` or not, through views in `format`. + let moved = |by_floats: bool, format: u32| -> usize { + let source = if by_floats { + MOVES + .replace("BY_FLOATS_OR_NOT", "main") + .replace("#ifdef BY_FLOATS", "#if 1") + } else { + MOVES + .replace("BY_FLOATS_OR_NOT", "main") + .replace("#ifdef BY_FLOATS", "#if 0") + }; + let code = crate::host::compile( + &source, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + ) + .expect("the test's shader"); + let (from, filled) = host.shared_buffer(BYTES).expect("a buffer"); + let (to, result) = host.shared_buffer(BYTES).expect("a buffer"); + // SAFETY: the shader's own root signature and plain creation + // calls; both mappings hold `BYTES` bytes; the views are of + // live buffers, in slots of the heap made above; an open list. + unsafe { + let root: ID3D12RootSignature = host + .device + .CreateRootSignature(0, &code) + .expect("a root signature"); + let pso: ID3D12PipelineState = host + .device + .CreateComputePipelineState(&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() + }) + .expect("a pipeline"); + let filled = std::slice::from_raw_parts_mut(filled.cast::<u16>(), ELEMENTS * 4); + for (pattern, half) in filled.iter_mut().enumerate() { + *half = pattern as u16; + } + std::ptr::write_bytes(result, 0xee, BYTES as usize); + let view = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT(format as i32), + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: ELEMENTS as u32, + ..Default::default() + }, + }, + }; + let start = heap.GetCPUDescriptorHandleForHeapStart(); + let step = host + .device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; + host.device.CreateUnorderedAccessView( + &from, + None::<&ID3D12Resource>, + Some(&view), + start, + ); + let second = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + step, + }; + host.device.CreateUnorderedAccessView( + &to, + None::<&ID3D12Resource>, + Some(&view), + second, + ); + let list = host.new_list().expect("a host list"); + list.list.SetDescriptorHeaps(&[Some(heap.clone())]); + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pso); + list.list + .SetComputeRootDescriptorTable(0, heap.GetGPUDescriptorHandleForHeapStart()); + list.list.Dispatch(ELEMENTS as u32 / 64, 1, 1); + list.close(); + host.execute(&[&list]); + assert!( + host.device.GetDeviceRemovedReason().is_ok(), + "the device, after views in format {format}" + ); + let result = std::slice::from_raw_parts(result.cast::<u16>(), ELEMENTS * 4); + (0..=u16::MAX) + .filter(|&p| result[usize::from(p)] == p) + .count() + } + }; + // A float view of halves is shown as the title's kind of view. + assert_eq!(half_format(10), Some(TITLES)); + let unsigned = moved(false, TITLES); + let by_floats = moved(true, TITLES); + eprintln!( + "halves through an R16G16B16A16_UINT buffer view: {unsigned} of 65536 patterns came back unchanged moved as unsigned integers, {by_floats} moved by way of floats" + ); + assert_eq!( + unsigned, 65_536, + "patterns unchanged, moved as unsigned integers" + ); + } + /// A null texture UAV keeps the title's dimension (3D for the world's /// wind field), and is 2D when the title names none. #[test] @@ -5101,6 +5448,31 @@ mod tests { assert!(q.due(16, 100).iter().any(|d| d.0 == 98)); } + /// Slots looked at before and slots never looked at are served in + /// turns, one looked at before first: a pass that can take only some + /// of a backlog of slots streaming in a part at a time still reaches + /// the slots never looked at. + #[test] + fn the_texture_queue_serves_looked_at_and_fresh_slots_in_turns() { + let mut q = TextureQueue::default(); + // Slots 100..110 looked at before (their memory not there yet). + for i in 0..10u32 { + q.written(100 + i, 1, 0, false); + } + for i in 0..10u32 { + let w = q.due(u64::MAX, 100).iter().find(|d| d.0 == 100 + i).unwrap().1; + q.later(100 + i, w, 1, 1); + } + // Slots 1..4 never looked at. + for i in 1..4u32 { + q.written(i, 2, 0, false); + } + let order: Vec<u32> = q.due(10, 6).into_iter().map(|d| d.0).collect(); + assert_eq!(order.len(), 6); + assert!(order[0] >= 100, "a slot looked at before comes first: {order:?}"); + assert_eq!(order.iter().filter(|&&i| i < 100).count(), 3, "every fresh slot is reached: {order:?}"); + } + /// Slots held back for lack of room on the card are not handed out /// until their frame, keep their place, are not counted as waiting /// for their memory, and all come back at once when the card has room; diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index f04fe53..19e3cc9 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -306,6 +306,10 @@ pub(crate) struct State { target_handles: Vec<u64>, depth_handle: u64, targets_set: bool, + /// LOCAL (fxceless a35c557393): the formats of the views + /// [`State::set_targets`] bound (eight targets, then depth), for the + /// draws' pipelines (`crate::pipeline::host_pipeline_for`). + target_formats: crate::pipeline::host::TargetFormats, /// The render target views and the depth view the host list has, once /// it has any ([`State::set_targets`]): per view the host texture (0: /// a null view) and what its descriptor says. @@ -1060,6 +1064,16 @@ impl State { crate::capture::note_target(record.resource); Some((texture, record)) }); + // The formats of the host views, for the draws' pipelines (before + // the bind cache below, which can return early). + let mut formats = [0u32; 9]; + for (i, (texture, desc)) in views.iter().take(8).enumerate() { + formats[i] = bound_format(*texture, desc.as_ref().map(|d| d.Format)); + } + if let Some((texture, record)) = dsv.as_ref() { + formats[8] = bound_format(Some(*texture), record.depth_desc().as_ref().map(|d| d.Format)); + } + self.target_formats = formats; let now = (keys, dsv.as_ref().map(|(texture, record)| (texture.as_raw() as usize, record.key()))); static CACHE: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); if *CACHE.get_or_init(|| std::env::var("VICTORY_BIND_CACHE").map_or(true, |v| v != "0")) @@ -1336,7 +1350,7 @@ impl State { if crate::pipeline::is_skipped(self.pipeline as This) { return false; } - let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + let Some(p) = crate::pipeline::host_pipeline_for(self.pipeline as This, &self.target_formats) else { return false; }; if p.compute || p.mesh != mesh { @@ -1493,7 +1507,13 @@ impl State { if t.stores && crate::picked::on() && crate::picked::picks(&stage.shader, &t.picks) { crate::picked::runs_in(list); } - let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute); + let made = self.tables( + list, + &t.used, + &t.host.root_indexed_views, + &t.host.half_views, + compute, + ); STORES.set(true); if made.iter().any(|m| m.1 == u32::MAX) { once!("a draw whose descriptor table found no free slots is dropped"); @@ -2198,7 +2218,18 @@ impl State { static PASSED: AtomicU64 = AtomicU64::new(0); let now = crate::host::now_ms(); let took = now.saturating_sub(PASSED.swap(now, Ordering::Relaxed)).max(1); - let most = (4000 / took).clamp(16, 256); + // `VICTORY_RELOOK_MS` (20,000 unless said; 4,000 before): at 4,000 the + // opening cutscene's 4 frames a second looked at its ~20,000 slots + // waiting for their memory every 16 frames, thousands of queries + // a second and most of the pass's time, while slots never looked + // at waited. The runtime's mappings already make a slot due + // (`texture_slots_remapped`); these looks are only for what that + // does not tell. + static RELOOK_MS: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + let relook = *RELOOK_MS.get_or_init(|| { + std::env::var("VICTORY_RELOOK_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(20_000) + }); + let most = (relook / took).clamp(16, 1024); // What a table entry of a texture a shader samples says. let sampled = UsedResource { kind: ResourceType::Srv, @@ -3145,11 +3176,19 @@ impl State { /// once: its constant data is copied at submission either way, and the /// big tables the world binds would otherwise take hundreds of slots per /// draw, wrapping the dynamic slots onto lists not yet submitted. + /// + /// `half`: the table descriptors the shader moves sixteen bits a + /// channel as unsigned integers (`HostShader::half_views`). A table + /// with a 16-bit float or signed buffer view at one of them is made + /// afresh as well, with that view in the unsigned format of the same + /// layout (`descriptor::host::half_view`): the title's own slot keeps + /// the title's format for the shaders that read it as floats. pub(crate) fn tables( &mut self, list: &HostList, used: &[UsedResource], indexed: &[RootIndexedView], + half: &[(u8, u32)], compute: bool, ) -> Few<(u8, u32), 16> { let tables = |u: &&UsedResource| u.root == RootType::Table; @@ -3159,6 +3198,36 @@ impl State { fresh.push(u.slot); } } + // The view shown in place of the title's at dword `at` of the table + // in root parameter `slot`, if the shader moves halves there and + // the title's view is a 16-bit float or signed buffer view. + let halved = |state: &Self, slot: u8, at: u32| -> Option<View> { + if !half.contains(&(slot, at)) { + return None; + } + let Some(&Root::Table(table)) = state.roots_ref(compute).get(usize::from(slot)) else { + return None; + }; + crate::descriptor::host::half_view(&crate::descriptor::view(table + u64::from(at) * 4)?) + }; + for &(slot, at) in half { + let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else { + continue; + }; + let Some(view) = crate::descriptor::view(table + u64::from(at) * 4) else { + continue; + }; + if crate::descriptor::host::half_view(&view).is_some() { + if !fresh.contains(&slot) { + fresh.push(slot); + } + } else if let Some(format) = crate::descriptor::host::half_inexact(&view) { + once!( + format, + "a shader moves a buffer's 16-bit channels as integers through a view whose values the console converts: they are read and written unconverted" + ); + } + } // Tables reaching past a host heap smaller than the title's (the // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the // title's slots there have no host slot of their own. @@ -3220,6 +3289,15 @@ impl State { index.byte_offset.wrapping_add(constant << index.shift) / 32 }) .collect(); + // The descriptors the shader moves halves through are made too, + // and the table reaches them: they may lie past the range starts + // the entries give (a range of several views names only its + // first; review on #927). + selected.extend( + half.iter() + .filter(|&&(s, _)| s == slot) + .map(|&(_, at)| at / 8), + ); selected.sort_unstable(); selected.dedup(); let n = entries() @@ -3242,6 +3320,11 @@ impl State { let at = table + u64::from(k) * 32; // SAFETY: a descriptor slot in title memory. h.add(unsafe { (at as *const [u32; 3]).read_unaligned() }); + // (Another table than the same slots made for a shader + // that reads them in the title's formats.) + if half.contains(&(slot, k * 8)) { + h.add([u32::MAX, slot.into(), k]); + } } (table, n, h.0) }; @@ -3382,7 +3465,10 @@ impl State { host.constant_at(index, &buffer, gpu, size); } Some(view) => { - host.make_at(index, &view); + match halved(self, slot, k * 8) { + Some(shown) => host.make_at(index, &shown), + None => host.make_at(index, &view), + } let kind = used.map(|u| u.kind).or_else(|| { selected.binary_search(&k).ok().and_then(|_| view_kind(&view)) }); @@ -4014,6 +4100,18 @@ pub(crate) fn view_kind(view: &View) -> Option<ResourceType> { } } +/// LOCAL (fxceless a35c557393): the format of a host view of `texture` +/// whose description names `described`: that one, else the texture's own +/// (what the host gives a view without a format); 0 if neither is known. +fn bound_format(texture: Option<&ID3D12Resource>, described: Option<DXGI_FORMAT>) -> u32 { + match (described, texture) { + (Some(format), _) if format.0 != 0 => format.0 as u32, + // SAFETY: a live texture. + (_, Some(texture)) => unsafe { texture.GetDesc() }.Format.0 as u32, + _ => 0, + } +} + /// The host state a depth view needs of its texture: the read state if the /// view writes no plane the format has (the title's read-only flags), else /// the write state. @@ -4044,7 +4142,7 @@ fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_ /// A few things, up to `N` of them without memory of the heap: what a draw's /// tables are gone through with, some six lists a stage. -struct Few<T, const N: usize> { +pub(crate) struct Few<T, const N: usize> { few: [T; N], len: usize, /// All of them, if they are more. diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index e8a9f29..bd5c8bc 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -456,6 +456,21 @@ pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> { make::ready(&pipeline(this).host) } +/// LOCAL (fxceless a35c557393): as [`host_pipeline`], for a draw into views +/// of the formats `bound`: if one has another format than the pipeline +/// declares for its slot, the host pipeline made for the bound formats. +#[cfg(windows)] +pub(crate) fn host_pipeline_for<'a>(this: This, bound: &host::TargetFormats) -> Option<&'a host::HostPipeline> { + if this.is_null() { + return None; + } + let p = &pipeline(this).host; + if p.formats != *bound && host::formats_differ(&p.formats, bound) { + return make::for_formats(p, bound); + } + make::ready(p) +} + /// Host pipelines queued and not made yet. #[cfg(windows)] pub(crate) fn making() -> u64 { diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index f1de86c..0c8c21c 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -150,6 +150,84 @@ fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D1 host } +/// LOCAL (fxceless a35c557393, `VICTORY_TARGET_VARIANTS`): the formats of +/// what a draw draws into, as the host has them: the eight render targets +/// (0 where there is none), then depth (0 for none). +pub(crate) type TargetFormats = [u32; 9]; + +/// Whether a draw into views of the formats `bound` cannot go to the host +/// with a pipeline that declares `declared`: a render target slot for which +/// the pipeline declares a format has a view of another format bound. On +/// the console the view's format rules (fxceless run 289: a full-screen +/// zoom and blur declaring R10G10B10A2_UNORM drawn into R11G11B10_FLOAT); +/// on the host that draw is an invalid call, undefined without the debug +/// layer. Empty slots, views in undeclared slots and depth do not count. +pub(crate) fn formats_differ(declared: &TargetFormats, bound: &TargetFormats) -> bool { + declared[..8].iter().zip(&bound[..8]).any(|(&d, &b)| d != 0 && b != 0 && b != d) +} + +/// The formats a pipeline for a draw into `bound` declares: the title's, +/// but the declared render target slots with a view bound take its format. +pub(crate) fn formats_for(declared: &TargetFormats, bound: &TargetFormats) -> TargetFormats { + let mut formats = *declared; + for i in 0..8 { + if declared[i] != 0 && bound[i] != 0 { + formats[i] = bound[i]; + } + } + formats +} + +impl GraphicsState { + /// The formats the state declares ([`TargetFormats`]). + pub(crate) fn formats(&self) -> TargetFormats { + let mut formats = [0; 9]; + let n = (self.targets.NumRenderTargets as usize).min(8); + for (to, from) in formats.iter_mut().zip(&self.targets.RTFormats[..n]) { + *to = from.0 as u32; + } + formats[8] = self.depth_format.0 as u32; + formats + } + + /// The same state for a draw into views of the formats `bound` (from + /// [`formats_for`]): those render target formats, everything else the + /// title's (blending on integer targets goes off when the host pipeline + /// is made, [`host_blend`]). Its description differs, so it has a name + /// of its own in the library. + pub(crate) fn with_formats(&self, bound: &TargetFormats) -> GraphicsState { + let names = self.names.clone(); + let inputs: Vec<D3D12_INPUT_ELEMENT_DESC> = self + .inputs + .iter() + .zip(&names) + .map(|(e, name)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: windows::core::PCSTR(name.as_ptr().cast()), + ..*e + }) + .collect(); + let mut targets = self.targets; + let n = (targets.NumRenderTargets as usize).min(8); + for (to, &from) in targets.RTFormats[..n].iter_mut().zip(bound) { + *to = DXGI_FORMAT(from as i32); + } + GraphicsState { + blend: self.blend, + sample_mask: self.sample_mask, + rasterizer: self.rasterizer, + depth: self.depth, + depth_bounds: self.depth_bounds, + inputs, + names, + strip_cut: self.strip_cut, + topology: self.topology, + targets, + depth_format: self.depth_format, + samples: self.samples, + } + } +} + 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 diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 5ade89f..a22e80c 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -27,7 +27,7 @@ use std::sync::{Arc, Condvar, Mutex, OnceLock}; use std::time::{Duration, Instant}; use super::Shader; -use super::host::{GraphicsState, HostPipeline}; +use super::host::{GraphicsState, HostPipeline, TargetFormats}; /// What a host pipeline is made from, and the host pipeline once made. pub(crate) struct Pending { @@ -43,6 +43,14 @@ pub(crate) struct Pending { used: AtomicBool, /// A pass over the screen ([`GraphicsState::screen_pass`]). screen: bool, + /// LOCAL: how long draws have waited for it so far, in microseconds + /// ([`wait_once`]). + waited_us: AtomicU64, + /// LOCAL (fxceless a35c557393): the formats its state declares (zeros + /// without a graphics state), and the same shaders and state for other + /// formats bound at a draw ([`for_formats`]): a chain, one link per set. + pub(crate) formats: TargetFormats, + variant: OnceLock<Arc<Pending>>, } // SAFETY: D3D12 objects are free-threaded; the graphics state (whose input @@ -60,6 +68,8 @@ impl Pending { } key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes()); Pending { + formats: graphics.as_ref().map_or([0; 9], |g| g.formats()), + variant: OnceLock::new(), screen: graphics.as_ref().is_some_and(|g| g.screen_pass()), shaders, graphics, @@ -68,6 +78,7 @@ impl Pending { made: OnceLock::new(), key: key.finalize().to_hex()[..32].to_owned(), used: AtomicBool::new(false), + waited_us: AtomicU64::new(0), } } @@ -156,6 +167,52 @@ pub(crate) fn waiting() -> u64 { WAITING.load(Ordering::Relaxed) } +/// Pipelines made again for the formats bound at a draw, since the start. +static VARIANTS: AtomicU64 = AtomicU64::new(0); + +/// Whether a draw into views of other formats than its pipeline declares +/// gets a host pipeline for those formats ([`for_formats`]); on unless +/// `VICTORY_TARGET_VARIANTS=0`. +fn variants_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TARGET_VARIANTS").is_none_or(|v| v != "0")) +} + +/// The host pipeline for a draw with `p` into views of the formats `bound` +/// that `p` does not declare: that of the same shaders and state for those +/// formats, queued and waited for like the title's own. +#[cold] +pub(crate) fn for_formats<'a>(p: &'a Arc<Pending>, bound: &TargetFormats) -> Option<&'a HostPipeline> { + match p.graphics.as_deref() { + Some(g) if variants_on() => ready(variant(p, g, &super::host::formats_for(&p.formats, bound))), + _ => ready(p), + } +} + +/// The pipeline of `p`'s shaders and state `g` for the formats `bound`: +/// found in the chain from `p`, or added to it (logged once per set). +fn variant<'a>(p: &'a Arc<Pending>, g: &GraphicsState, bound: &TargetFormats) -> &'a Arc<Pending> { + let mut at = p; + for _ in 0..64 { + let next = at.variant.get_or_init(|| { + let so_far = VARIANTS.fetch_add(1, Ordering::Relaxed) + 1; + tracing::info!( + pipeline = %hashes(p), + declared = ?p.formats, + bound = ?bound, + so_far, + "a pipeline is made again for the render target formats bound at its draw (VICTORY_TARGET_VARIANTS=0: the draw goes out with the title's pipeline)" + ); + Arc::new(Pending::new(p.shaders.clone(), Some(Box::new(g.with_formats(bound))))) + }); + if next.formats == *bound { + return next; + } + at = next; + } + p +} + /// The host pipeline if it is made (or is made within the frame's budget); /// queues it on first use. pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> { @@ -200,6 +257,21 @@ fn shared_budget() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_WAIT_SHARED").is_none_or(|v| v != "0")) } +/// LOCAL (the problem of fxceless issue #1181): whether one pipeline is +/// waited for at most one budget over the whole run, not one budget every +/// frame. A pipeline whose make takes longer than the budget (a driver +/// compile of tens of seconds, or one that never ends) otherwise cost the +/// whole budget in every frame in which a draw asked for it: with +/// `VICTORY_PIPELINE_WAIT_MS=10000` the picture stood still while the thing +/// drawn with it was in view, and moved again when the camera turned away. +/// After its budget its draws are dropped until it is made, as with any +/// pipeline past the frame's budget. On by default; +/// `VICTORY_PIPELINE_WAIT_ONCE=0` waits as before. +fn wait_once() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_WAIT_ONCE").is_none_or(|v| v != "0")) +} + /// Waits for `p` while frame `frame` has budget left. fn wait(p: &Pending, frame: u64) { let screen = p.screen && screens_first(); @@ -207,6 +279,16 @@ fn wait(p: &Pending, frame: u64) { if budget.is_zero() { return; } + // LOCAL: what is left of this pipeline's own budget ([`wait_once`]). + let own = if wait_once() { + let own = budget.saturating_sub(Duration::from_micros(p.waited_us.load(Ordering::Relaxed))); + if own.is_zero() { + return; + } + own + } else { + Duration::MAX + }; // The frame the budget belongs to, and what was waited of it (or is // 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]; @@ -217,7 +299,7 @@ fn wait(p: &Pending, frame: u64) { if spent.0 != frame { *spent = (frame, Duration::ZERO); } - let left = budget.saturating_sub(spent.1); + let left = budget.saturating_sub(spent.1).min(own); if shared { spent.1 += left; } @@ -238,6 +320,16 @@ fn wait(p: &Pending, frame: u64) { } drop(held); let waited = started.elapsed().min(left); + if wait_once() && p.made.get().is_none() { + let before = p.waited_us.fetch_add(waited.as_micros() as u64, Ordering::Relaxed); + if Duration::from_micros(before) + waited >= budget { + tracing::info!( + shaders = ?p.shaders, + ms = budget.as_millis() as u64, + "a pipeline not made within its wait: its draws are dropped until it is (VICTORY_PIPELINE_WAIT_ONCE=0: waited for every frame)" + ); + } + } if screen && waited > Duration::from_millis(500) { tracing::info!( ms = waited.as_millis() as u64, diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index f5e6482..c395e19 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -64,6 +64,10 @@ fn build() -> [u8; 32] { // executable had cached with the switch unset. for name in [ "VICTORY_BVH_MISS", + // LOCAL: colours and image stores with NaN made 0. + "VICTORY_NAN_SCRUB", + // LOCAL (fxceless #1216): constant buffer slots marked. + "VICTORY_CONSTANT_MARKS", "VICTORY_WAVE_WIDE", "VICTORY_WAVE_DEEP_SKIPS", "VICTORY_WAVE_OWN_BITS", @@ -268,6 +272,11 @@ fn encode(s: &HostShader) -> Vec<u8> { word(&mut out, value); } } + word(&mut out, s.half_views.len() as u32); + for &(slot, dword) in &s.half_views { + word(&mut out, u32::from(slot)); + word(&mut out, dword); + } out } @@ -336,6 +345,11 @@ fn decode(bytes: &[u8]) -> Option<HostShader> { shift: u8::try_from(r.word()?).ok().filter(|&s| s < 32)?, }); } + let n = r.word()? as usize; + let mut half_views = Vec::with_capacity(n.min(256)); + for _ in 0..n { + half_views.push((u8::try_from(r.word()?).ok()?, r.word()?)); + } r.0.is_empty().then_some(HostShader { stage, dxil, @@ -346,6 +360,7 @@ fn decode(bytes: &[u8]) -> Option<HostShader> { root_srvs, root_uavs, root_indexed_views, + half_views, }) } @@ -380,6 +395,7 @@ mod tests { byte_offset: 32, shift: 5, }], + half_views: vec![(0, 8), (4, 0)], } } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 1fbc585..337e7c3 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -65,6 +65,10 @@ pub(crate) struct Staging { /// The staging buffer's bytes (counted in `STAGED` while it lives). bytes: u64, memory: *const u8, + /// Whether the guard may stand for a hash of this texture (LOCAL, + /// fxceless #489): not for a video's picture planes, which the decoder + /// writes through another view of the same pages. + guard_view: bool, last: Mutex<Last>, /// Whether the staging buffer was detiled since a submitted list last /// uploaded it, and whether one has uploaded it at all: a list records @@ -111,6 +115,20 @@ struct Last { /// and after the hash found a change the guard did not see. const HOT_FRAMES: u64 = 64; +/// LOCAL (wt5 build38, bodnjenie14 12457b43 "Bink video flickering"): after +/// the hash finds a change the guard did not see, the texture stays hot this +/// many frames (`VICTORY_VIDEO_HOT_FRAMES`, 1,024 unless said; 64 before). +/// With 64 the intro video's ring slots went cold between their own changes +/// and showed frames from earlier again (wt5 r_fps2; the user confirmed +/// 1,024 fixed it). Only textures caught changing unseen get it, so the +/// world's static textures do not pay for it. +fn blind_hot_frames() -> u64 { + static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *N.get_or_init(|| { + std::env::var("VICTORY_VIDEO_HOT_FRAMES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1024) + }) +} + /// Whether a guarded texture whose memory the hash found changed although /// the guard saw no write is hashed at every check for a while /// ([`HOT_FRAMES`]), not every eighth frame. A title that writes such a @@ -788,7 +806,15 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { // at submission is left, and what it finds changed the next list that // samples the texture uploads (a frame late where every list of the // frame was recorded before that check). - if staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) { + // LOCAL: not for a video's picture planes (`guard_view` false). Their + // check at submission finds the frame the decoder wrote since, but the + // copy came only with the next list that samples the plane: three + // frames later in the video's ring of three, and the brightness and + // colour planes each on their own turn, so the intro showed colour + // ghosts and pictures from earlier (r_avm23, the user's recording). + // With the copy recorded here, it takes what that check puts in the + // staging buffer at this list's submission. + if staging.guard_view && staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexSkipped, 1); list.defer_texture(staging); @@ -1211,6 +1237,7 @@ impl Staging { // The guard saw no write: a change the hash finds came another way. let mut blind = false; if !alone + && self.guard_view && *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true)) { @@ -1235,7 +1262,7 @@ impl Staging { // A change the guard did not see: hashed at every check for a while. let found_blind = |last: &mut Last| { if blind && hot_textures() { - last.hot_until = crate::frame::current() + HOT_FRAMES; + last.hot_until = crate::frame::current() + blind_hot_frames(); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHot, 1); } @@ -1774,6 +1801,34 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O let host = host()?; // SAFETY: a live resource. let d = unsafe { texture.GetDesc() }; + // LOCAL (fxceless #489, "Fix stale frames in the opening video"): the + // software-decoded movie's planes are linear single-level R8 textures + // the decoder can write through another view of the same pages, which + // the guard on the sampled view does not see: with a hash every eighth + // frame the movie replayed its ring of three old frames (A, B, C, A, B, + // C). Those are hashed at every check. `VICTORY_VIDEO_PLANES=0`: as before. + static PLANES: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let guard_view = !(*PLANES.get_or_init(|| std::env::var_os("VICTORY_VIDEO_PLANES").is_none_or(|v| v != "0")) + && d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && d.Format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8_UNORM + && d.MipLevels == 1 + && d.DepthOrArraySize == 1 + && layout.desc.swizzle == victory_formats::texture::Swizzle::LINEAR); + // Which one-level R8 textures count as video planes, to check the rule + // against the title's (the first few only). + if d.Format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8_UNORM && d.MipLevels == 1 { + static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 24 { + tracing::info!( + width = d.Width, + height = d.Height, + layers = d.DepthOrArraySize, + swizzle = ?layout.desc.swizzle, + video_plane = !guard_view, + "a one-level R8 texture staged" + ); + } + } let level0 = copy.base; let mips = level0 + u32::from(d.MipLevels); let first = crate::resource::read_from(&layout, first).max(level0).min(mips - 1); @@ -1834,6 +1889,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O once: std::sync::atomic::AtomicBool::new(once() && !on_demand && PICKING.get().is_some()), bytes: total, memory, + guard_view, last: Mutex::default(), dirty: std::sync::atomic::AtomicBool::new(true), uploaded: std::sync::atomic::AtomicBool::new(false), diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index 21b4d03..8d09700 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -1237,7 +1237,24 @@ fn translated_compute_matches_pc() { }; roots.push((1 + n as u32, Root::View { srv, data })); } - let ours = host.dispatch(&root_t, &pso_t, &dispatch(roots)); + // A buffer of halves the translated program moves as unsigned + // integers is shown to it as its unsigned twin, as the host does + // (`HostShader::half_views`); the PC program keeps the float view. + let twins: Vec<View> = views + .iter() + .map(|&v| match v { + View::HalfUav(n) if !cs_c.half_views.is_empty() => View::HalfUintUav(n), + v => v, + }) + .collect(); + let ours = host.dispatch( + &root_t, + &pso_t, + &Dispatch { + views: &twins, + ..dispatch(roots) + }, + ); if name.starts_with("terminates") { match ours { Ok(_) => eprintln!("{name}: finished"), diff --git a/crates/victory-shader/src/emit/halves.rs b/crates/victory-shader/src/emit/halves.rs new file mode 100644 index 0000000..adf2969 --- /dev/null +++ b/crates/victory-shader/src/emit/halves.rs @@ -0,0 +1,148 @@ +//! Typed buffer loads that move 16-bit halves without the d16 form: a +//! format load of whole dwords whose result the program reads only one +//! half of, as a half float, moves 16-bit integers, like a d16 access +//! ([`super::super::HostShader::half_views`]). + +use std::collections::HashSet; + +use super::{Fields, Inst, Lower, Operand, Reg, Role, RootType, Source, Value}; + +impl<'a> Lower<'a> { + /// Whether every use of `value`, a typed buffer load's result, reads + /// one 16-bit half of it as a half float: a `v_fma_mix*` source with + /// its `op_sel_hi` bit set, or `v_cvt_f32_f16`. A program that takes a + /// format load apart like that reads a 16-bit integer view on the + /// console (the load gives the zero-extended integer, whose bits are a + /// half; a float view's value it would not take apart). A use is a + /// read as an operand ([`crate::ir::operand_reads`]): a later write of + /// the register reads the value only to keep it in the lanes EXEC + /// leaves alone, and a phi carries it on, its own uses counting. False + /// without a use. + pub(super) fn read_only_as_halves(&self, value: Value) -> bool { + let p = self.x.p; + let mut used = false; + let mut seen = HashSet::from([value]); + let mut todo = vec![value]; + while let Some(value) = todo.pop() { + for b in &p.blocks { + for phi in b.phis.iter().filter(|phi| phi.args.contains(&value)) { + if seen.insert(phi.value) { + todo.push(phi.value); + } + } + for i in &b.insts { + if !i.reads.iter().any(|r| r.1 == value) { + continue; + } + let operands = crate::ir::operand_reads(p, i); + let regs: Vec<Reg> = i + .reads + .iter() + .filter(|r| r.1 == value && operands.contains(&r.0)) + .map(|r| r.0) + .collect(); + if regs.is_empty() { + continue; + } + used = true; + let Fields::Valu(v) = &i.fields else { + return false; + }; + match i.name() { + "v_cvt_f32_f16" => {} + "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { + let whole = v.src.iter().enumerate().any(|(k, op)| { + matches!(*op, Operand::Vector { reg, .. } if regs.contains(&Reg::V(reg))) + && v.opsel_hi >> k & 1 == 0 + }); + if whole { + return false; + } + } + _ => return false, + } + } + } + } + used + } + + /// Whether `inst` is a format load of whole dwords (not d16) whose + /// every channel is read only as halves ([`Self::read_only_as_halves`]). + pub(super) fn format_load_read_as_halves(&self, inst: &Inst) -> bool { + let Fields::Buffer { + data: Some(Operand::Vector { reg, .. }), + .. + } = inst.fields + else { + return false; + }; + let name = inst.name(); + let count = match name + .strip_prefix("buffer_load_format_") + .or(name.strip_prefix("tbuffer_load_format_")) + { + Some("x") => 1, + Some("xy") => 2, + Some("xyz") => 3, + Some("xyzw") => 4, + _ => return false, + }; + (0..count).all(|k| { + inst.write(Reg::V(reg + k)) + .is_some_and(|v| self.read_only_as_halves(v)) + }) + } + + /// The table places ([`Self::table_place`]) every access through which + /// moves halves: a d16 access, or a format load read only as halves + /// ([`Self::format_load_read_as_halves`]). A place the program reaches + /// otherwise too is left out (a format load of numbers beside one of + /// halves, a raw or scalar load, a descriptor chosen by control flow), + /// and so is every place of a table the program also picks from at run + /// time: what the program makes of such a view is not halves alone. + pub(super) fn places_read_as_halves(&self) -> std::collections::BTreeSet<(u8, u32)> { + let mut halves = std::collections::BTreeSet::new(); + let mut other = std::collections::BTreeSet::new(); + let mut picked = HashSet::new(); + for d in &self.x.res.descriptors { + if d.role == Role::Sampler { + continue; + } + let inst = self + .x + .p + .blocks + .get(d.site.0) + .and_then(|b| b.insts.get(d.site.1)); + let half = matches!(d.source, Source::Loaded { .. }) + && inst.is_some_and(|i| { + (i.name().starts_with("buffer_") && i.name().contains("_format_d16_")) + || self.format_load_read_as_halves(i) + }); + for leaf in d.source.leaves() { + let Source::Loaded { load, .. } = leaf else { + continue; + }; + let Some(a) = self.scalar.get(load) else { + continue; + }; + if a.dynamic.is_some() { + if let Some(rp) = self.x.native.layout.get(a.param) + && rp.root == RootType::Table + { + picked.insert(rp.slot); + } + } else if let Some(place) = self.table_place(leaf) { + if half { + halves.insert(place); + } else { + other.insert(place); + } + } + } + } + halves.retain(|p| !other.contains(p) && !picked.contains(&p.0)); + halves + } +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 9196f51..3fbc2b9 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -612,6 +612,7 @@ fn stub(pixel: bool, outputs: Vec<SigElement>) -> HostShader { root_srvs: Vec::new(), root_uavs: Vec::new(), root_indexed_views: Vec::new(), + half_views: Vec::new(), } } @@ -991,6 +992,7 @@ fn transition( /// A view in the heap for [`Host::dispatch`]. #[cfg(test)] +#[derive(Clone, Copy)] pub enum View<'a> { /// An RGBA32F texture SRV (width, height, texels). Texture(u32, u32, &'a [[f32; 4]]), @@ -1004,6 +1006,9 @@ pub enum View<'a> { UintTextureUav(u32, u32), /// A typed RGBA16F buffer UAV of this many elements, zeroed. HalfUav(u32), + /// The same buffer viewed as R16G16B16A16_UINT: what a translated + /// program that moves halves is shown ([`super::HostShader::half_views`]). + HalfUintUav(u32), /// A constant buffer of these dwords. Cbv(&'a [u32]), /// A buffer SRV over these dwords. @@ -1240,7 +1245,7 @@ impl Host { ); keep.push(tex); } - View::RawUav(_) | View::HalfUav(_) => { + View::RawUav(_) | View::HalfUav(_) | View::HalfUintUav(_) => { // (dwords, format, elements, flags) let (n, format, elements, flags) = match *v { View::HalfUav(e) => ( @@ -1249,6 +1254,12 @@ impl Host { e, D3D12_BUFFER_UAV_FLAG_NONE, ), + View::HalfUintUav(e) => ( + 2 * e, + DXGI_FORMAT_R16G16B16A16_UINT, + e, + D3D12_BUFFER_UAV_FLAG_NONE, + ), View::RawUav(n) => { (n, DXGI_FORMAT_R32_TYPELESS, n, D3D12_BUFFER_UAV_FLAG_RAW) } diff --git a/crates/victory-shader/src/emit/intersect_tests.rs b/crates/victory-shader/src/emit/intersect_tests.rs index f2eddab..91143f6 100644 --- a/crates/victory-shader/src/emit/intersect_tests.rs +++ b/crates/victory-shader/src/emit/intersect_tests.rs @@ -194,6 +194,7 @@ pub(super) fn build_compute_shader( root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views.clone(), + half_views: lowered.half_views, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 1dc305a..326f88f 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -25,6 +25,11 @@ use crate::structure::{Atom, Bool, LaneExit, Structured}; #[path = "intersect.rs"] pub(super) mod intersect; +/// Format loads that move 16-bit halves without the d16 form, a child +/// module so it shares the emitter's state. +#[path = "halves.rs"] +mod halves; + type Why = &'static str; /// How an interpolation evaluates an input channel. @@ -55,6 +60,8 @@ pub(crate) struct Lowered { pub root_cbvs: Vec<u8>, pub root_srvs: Vec<u8>, pub root_uavs: Vec<u8>, + /// See [`super::HostShader::half_views`]. + pub half_views: Vec<(u8, u32)>, pub user_data: Vec<UserData>, pub samplers: Vec<[u32; 4]>, /// The wave size the shader requires of the host, if any. @@ -96,6 +103,12 @@ pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> { /// and store). Not where a group barrier would wait for lanes that left, nor /// where two host waves of 32 stand for a console wave (they exchange, which /// takes all lanes). +/// LOCAL: `VICTORY_NAN_SCRUB=1` (off by default): see `Lower::scrub_nan`. +pub(crate) fn nan_scrub() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_NAN_SCRUB").is_some_and(|v| v == "1")) +} + fn counted_in_threads(parts: &Parts) -> bool { let crate::native::StageIo::Cs(cs) = &parts.native.io else { return false; @@ -295,6 +308,11 @@ struct Lower<'a> { params: HashMap<Value, (usize, u32)>, user_data: Option<V>, user_reads: BTreeMap<u32, UserData>, + /// Table descriptors read or written sixteen bits a channel + /// ([`super::HostShader::half_views`]): root parameter, dword offset. + half_views: std::collections::BTreeSet<(u8, u32)>, + /// [`Self::places_read_as_halves`], found before the code is lowered. + halves_only: std::collections::BTreeSet<(u8, u32)>, samplers: Vec<[u32; 4]>, descriptors: HashMap<(Site, bool), &'a Source>, scalar: HashMap<Site, Address>, @@ -1635,6 +1653,8 @@ impl<'a> Lower<'a> { params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(), user_data: None, user_reads: BTreeMap::new(), + half_views: Default::default(), + halves_only: Default::default(), samplers: Vec::new(), descriptors: x .res @@ -2335,6 +2355,7 @@ impl<'a> Lower<'a> { self.s.entry = body; } self.find_coherent(); + self.halves_only = self.places_read_as_halves(); let order = crate::ir::reverse_postorder(&p.blocks); for (n, &b) in order.iter().enumerate() { self.rpo[b] = n; @@ -2420,6 +2441,7 @@ impl<'a> Lower<'a> { let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect(); let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect(); let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect(); + let half_views = std::mem::take(&mut self.half_views).into_iter().collect(); let cmp_samplers = self.s.cmp_samplers; let wave_size = self.s.wave_size; Ok(Lowered { @@ -2428,6 +2450,7 @@ impl<'a> Lower<'a> { root_cbvs, root_srvs, root_uavs, + half_views, #[cfg(test)] nonuniform_handles: self.s.nonuniform_handles, #[cfg(test)] @@ -6197,7 +6220,12 @@ impl<'a> Lower<'a> { raw.push((x, zero)); } let raw = self.end_guarded(at, &raw); - let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero); + // LOCAL (fxceless #1216): only a slot marked as a constant + // buffer is read as one; any other non-buffer gives zeros. + let other = match self.slot_is_constant(src)? { + Some(is_constant) => is_constant, + None => self.s.m.cmp(self.cur, pred::EQ, stride, zero), + }; let at = self.begin_guarded(Some(other)); let h = self.handle(site, src, false, (13, 0x1_0000))?; let mut both = Vec::new(); @@ -6482,7 +6510,15 @@ impl<'a> Lower<'a> { let props = if un.starts_with("buffer_load_format") || un.starts_with("buffer_store_format") { - (10 | u, 0x409) + // (Unsigned integers where the access moves halves.) + let halves = self + .table_place(&Source::Loaded { load: site, first }) + .is_some_and(|p| { + self.halves_only.contains(&p) + && (un.contains("_format_d16_") + || self.format_load_read_as_halves(ui)) + }); + (10 | u, if halves { 0x405 } else { 0x409 }) } else if !counted && *idxen && format.is_none() @@ -7122,6 +7158,22 @@ impl<'a> Lower<'a> { (kind == Some(ResourceType::Uav)).then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0)) } + /// The table descriptor `src` is, as (root parameter, dword in the + /// table), when the code loads it from a fixed place in a table: the + /// load's own place, not the start of the range its used-resource + /// entry describes (a range of several descriptors starts before most + /// of them). `None` for a descriptor picked at run time, built in the + /// code or chosen by control flow. + fn table_place(&self, src: &Source) -> Option<(u8, u32)> { + let Source::Loaded { load, first } = src else { + return None; + }; + let a = self.scalar.get(load)?; + let rp = self.x.native.layout.get(a.param)?; + (rp.root == RootType::Table && a.dynamic.is_none()) + .then(|| (rp.slot, a.offset / 4 + u32::from(*first))) + } + /// The used-resource entry a descriptor loaded from a table falls in. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> { if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } = @@ -7477,10 +7529,33 @@ impl<'a> Lower<'a> { 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) + let stride = self.s.m.bin(self.cur, Bin::And, word, bits); + if super::shader::constant_marks() { + // LOCAL (fxceless #1216): the mark of a constant buffer + // slot is no stride. + let mark = self.s.m.i32(super::shader::SLOT_STRIDE_CONSTANT); + let is_constant = self.s.m.cmp(self.cur, pred::EQ, word, mark); + let zero = self.s.m.i32(0); + self.s.m.select(self.cur, is_constant, zero, stride) + } else { + stride + } })) } + /// LOCAL (fxceless #1216): with [`super::shader::constant_marks`], + /// whether the slot `src` names holds a constant buffer view. + fn slot_is_constant(&mut self, src: &Source) -> Result<Option<V>, Why> { + if !super::shader::constant_marks() { + return Ok(None); + } + let Some(word) = self.slot_word(src)? else { + return Ok(None); + }; + let mark = self.s.m.i32(super::shader::SLOT_STRIDE_CONSTANT); + Ok(Some(self.s.m.cmp(self.cur, pred::EQ, word, mark))) + } + /// 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). @@ -10932,6 +11007,10 @@ impl<'a> Lower<'a> { self.float_of(v)? }); } + // LOCAL: `VICTORY_NAN_SCRUB=1` (see `scrub_nan`). + for v in &mut vals { + *v = self.scrub_nan(*v); + } let h = self.handle(site, src, false, props)?; let at = self.begin_guarded(guard); let mut args = vec![h]; @@ -11630,6 +11709,23 @@ impl<'a> Lower<'a> { .copied() .ok_or("an untracked buffer")?; let used = self.used_kind(src); + // Sixteen bits a channel through a view of a table: the bits go as + // they are, as unsigned integers, and the host is told, which shows + // the shader a 16-bit float view there as its unsigned twin + // ([`super::HostShader::half_views`]). + // A format load of whole dwords whose every use reads one half of a + // result as a half float moves 16-bit integers too (the head + // program's reads of the face network's output), where every + // access through its view does ([`Self::places_read_as_halves`]). + // A d16 access too only where every access does: a whole float + // read through the same place would see the unsigned twin. + let place = typed.then(|| self.table_place(src)).flatten().filter(|p| { + self.halves_only.contains(p) && (d16 || self.format_load_read_as_halves(inst)) + }); + let halves = place.is_some(); + if let Some(place) = place { + self.half_views.insert(place); + } let (base, extra) = self.built_offset(src)?; if base != 0 { let b = self.s.m.i32(base); @@ -11861,14 +11957,16 @@ impl<'a> Lower<'a> { let mut vals = self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?; if d16 { - // 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 + // Through a view of a table each half is stored as it is + // (`halves`, fxceless #927). Reached another way, 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 }; + // picks from the heap; and the handle stays a float one, + // whose bits the drivers pass. + let integer = if typed && !halves { self.integer_view(src)? } else { None }; let mut wide = Vec::new(); for k in 0..count { let mut x = vals[(k / 2) as usize]; @@ -11876,6 +11974,11 @@ impl<'a> Lower<'a> { let k16 = self.s.m.i32(16); x = self.s.m.bin(c, Bin::LShr, x, k16); } + if halves { + let low = self.s.m.i32(0xffff); + wide.push(self.s.m.bin(c, Bin::And, x, low)); + continue; + } let f32t = self.s.t.f32; let f = self .s @@ -11900,12 +12003,21 @@ impl<'a> Lower<'a> { if count != 4 || *offen || *offset != 0 { return Err("a typed buffer store of some channels or at an offset"); } - args.push(self.handle(site, src, false, (10 | u, 0x409))?); + // Four unsigned integers for halves, four floats otherwise. + let component = if halves { 0x405 } else { 0x409 }; + args.push(self.handle(site, src, false, (10 | u, component))?); args.extend([index.unwrap_or(self.s.m.i32(0)), iu]); for x in vals { - args.push(self.as_float(x)); + args.push(if halves { x } else { self.as_float(x) }); } - (69, "bufferStore.f32") + ( + 69, + if halves { + "bufferStore.i32" + } else { + "bufferStore.f32" + }, + ) } else { match index { // A raw buffer (stride 1) written by index: the index is the byte. @@ -11965,16 +12077,30 @@ impl<'a> Lower<'a> { if uav { self.s.flags |= flags::TYPED_UAV_LOADS; } - let h = self.handle(site, src, false, (10 | u, 0x409))?; let index = index.unwrap_or(self.s.m.i32(0)); - self.s.op( - c, - "bufferLoad.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 68, - &[h, index, iu], - ) + if halves { + let h = self.handle(site, src, false, (10 | u, 0x405))?; + let i32t = self.s.t.i32; + let ret = self.s.m.named_struct("dx.types.ResRet.i32", vec![i32t; 5]); + self.s.op( + c, + "bufferLoad.i32", + Attr::ReadOnly, + ret, + 68, + &[h, index, iu], + ) + } else { + let h = self.handle(site, src, false, (10 | u, 0x409))?; + self.s.op( + c, + "bufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 68, + &[h, index, iu], + ) + } } else { let mask = self.s.m.i8((1u8 << count) - 1); let align = self.s.m.i32(4); @@ -12024,24 +12150,32 @@ impl<'a> Lower<'a> { return Err("a buffer result"); }; if d16 { - // 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 }; + // Two f16 channels per VGPR (an odd last high half 0); through + // a view of a table, the 16 bits of each as they are (fxceless + // #927); the low 16 bits of an integer view's picked from the + // heap (see the stores above). + let integer = if typed && !halves { 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 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); - } + let h = if halves { + let low = self.s.m.i32(0xffff); + self.s.m.bin(c, Bin::And, f, low) + } else { + 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); + } + h + }; x = Some(match x { Some(hi) => { let hi = self.s.m.bin(c, Bin::Shl, hi, k16); @@ -12056,12 +12190,34 @@ impl<'a> Lower<'a> { } for k in 0..count { let x = self.s.m.extract(c, r, k); - let x = self.as_int(x); + // (Integers already where the load moved halves.) + let x = if halves { x } else { self.as_int(x) }; self.write(inst, Reg::V(reg + k as u8), x, guard); } Ok(()) } + /// LOCAL: with `VICTORY_NAN_SCRUB=1` (off by default), `f` or 0 where it + /// is NaN. Used on the colours pixel shaders write and on float image + /// stores: a NaN that reaches the title's bloom, blur or temporal + /// upscaler spreads into black patches that stay in its history (seen on + /// NVIDIA as black blobs on faces and in the air). Not what the console + /// does, so it is a switch; part of the shader cache key. + fn scrub_nan(&mut self, f: V) -> V { + if !nan_scrub() { + return f; + } + // NaN or an infinity (11/26: the whole picture went white at one + // angle with only NaN scrubbed: an infinity through bloom or the + // exposure does the same). |f| >= inf, unordered: true for NaN too. + let c = self.cur; + let a = self.unary(6, f); + let inf = self.s.m.f32(0x7f80_0000); + let bad = self.s.m.cmp(c, pred::UGE, a, inf); + let zero = self.s.m.f32(0); + self.s.m.select(c, bad, zero, f) + } + fn export(&mut self, b: usize, i: usize) -> Result<(), Why> { let e = *self .exports @@ -12247,6 +12403,8 @@ impl<'a> Lower<'a> { (true, false) => ("storeVertexOutput", 171), (true, true) => ("storePrimitiveOutput", 172), }; + // LOCAL: a colour a pixel shader writes (`VICTORY_NAN_SCRUB`). + let colour = self.s.pixel && matches!(e.target, Target::Color(_)); for (id, col, value, half) in stores { let mut x = self.i32_of(value)?; if let Some(high) = half { @@ -12265,12 +12423,19 @@ impl<'a> Lower<'a> { let el = &mut elements(self, primitive)[id]; el.usage |= 1 << col; let (suffix, x) = match el.comp { - 9 if half.is_some() => (".f32", self.as_float(x)), + 9 if half.is_some() => { + let f = self.as_float(x); + (".f32", if colour { self.scrub_nan(f) } else { f }) + } 9 => { let f = match self.floats.get(&value) { Some(&f) => f, None => self.as_float(x), }; + // LOCAL: `VICTORY_NAN_SCRUB=1`: a colour a pixel shader + // writes is 0 where it is NaN, so one bad value does not + // spread through the title's blur and temporal passes. + let f = if colour { self.scrub_nan(f) } else { f }; (".f32", f) } _ => (".i32", x), diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index baf9226..85a9e0f 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -122,8 +122,8 @@ pub use lower::{host_settings, set_host_max_wave, set_host_rdna}; 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, 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, + SLOT_STRIDE_CONSTANT, 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, + constant_marks, raw_views, set_raw_views, set_view_heap_limit, view_heap_limit, }; /// The loop limit without an override: 2^20. @@ -354,6 +354,21 @@ pub struct HostShader { pub root_uavs: Vec<u8>, /// Heap descriptors that can be selected from root state at bind time. pub root_indexed_views: Vec<crate::resource::RootIndexedView>, + /// Table descriptors (root parameter, dword offset in the table) whose + /// buffer the shader reads or writes sixteen bits a channel + /// (`buffer_load_format_d16_*`, `buffer_store_format_d16_*`), in + /// order. On the console each channel's 16 bits move as they are + /// through a 16-bit float view and through a 16-bit integer one alike + /// (the title keeps half floats, and indices beside them, in + /// `R16G16B16A16_UINT` and `R16_UINT` buffers). The DXIL moves them as + /// unsigned integers, which an unsigned 16-bit view carries unchanged; + /// the host shows the shader a 16-bit float or signed buffer view at + /// these places as the unsigned format of the same layout. + /// shortcut: a view in a normalised 16-bit format, whose values the + /// console would convert to halves, is read as its integers; a + /// descriptor picked at run time keeps the float path (its slot, and so + /// its format, is known only then). + pub half_views: Vec<(u8, u32)>, } impl HostShader { @@ -796,6 +811,7 @@ fn emit_program( root_srvs: l.root_srvs, root_uavs: l.root_uavs, root_indexed_views: res.root_indexed_views.clone(), + half_views: l.half_views, }; Ok((shader, wave_size)) } @@ -1578,6 +1594,7 @@ mod tests { root_srvs: Vec::new(), root_uavs: Vec::new(), root_indexed_views: Vec::new(), + half_views: Vec::new(), }; let file = |var: &str, stage| { std::env::var(var).ok().map(|p| super::HostShader { @@ -1590,6 +1607,7 @@ mod tests { root_srvs: Vec::new(), root_uavs: Vec::new(), root_indexed_views: Vec::new(), + half_views: Vec::new(), }) }; let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps); @@ -2199,6 +2217,7 @@ mod tests { root_srvs: l.root_srvs, root_uavs: l.root_uavs, root_indexed_views: Vec::new(), + half_views: Vec::new(), }; let (root, pso) = host.compute_pipeline(&cs).unwrap(); // Twelve dwords: the loads below run across the view's end. @@ -2352,6 +2371,7 @@ mod tests { root_srvs: l.root_srvs, root_uavs: l.root_uavs, root_indexed_views: Vec::new(), + half_views: l.half_views, }; let (root, pso) = host.compute_pipeline(&cs).unwrap(); let inputs: Vec<u32> = [ @@ -2768,6 +2788,7 @@ mod barycentric_tests { root_srvs: Vec::new(), root_uavs: Vec::new(), root_indexed_views: Vec::new(), + half_views: Vec::new(), }; validate(&vs); // One triangle covers an 8x8 target, with attribute values 2, 6, 10. diff --git a/crates/victory-shader/src/emit/permlane_tests.rs b/crates/victory-shader/src/emit/permlane_tests.rs index 3e6826c..a72b559 100644 --- a/crates/victory-shader/src/emit/permlane_tests.rs +++ b/crates/victory-shader/src/emit/permlane_tests.rs @@ -106,6 +106,7 @@ fn lowered(native: &NativeProgram, host_wave: u32) -> Result<HostShader, ShaderE root_srvs: result.root_srvs, root_uavs: result.root_uavs, root_indexed_views: res.root_indexed_views, + half_views: Vec::new(), }; match validator::Validator::load(validator::Validator::default_path().as_deref()) { Ok(mut v) => { diff --git a/crates/victory-shader/src/emit/probe_tests.rs b/crates/victory-shader/src/emit/probe_tests.rs index fd109ba..c12009d 100644 --- a/crates/victory-shader/src/emit/probe_tests.rs +++ b/crates/victory-shader/src/emit/probe_tests.rs @@ -34,6 +34,7 @@ fn probe() { root_srvs: Vec::new(), root_uavs: Vec::new(), root_indexed_views: Vec::new(), + half_views: Vec::new(), }; let (root, pso) = match host.compute_pipeline(&shader) { Ok(made) => made, diff --git a/crates/victory-shader/src/emit/rect.rs b/crates/victory-shader/src/emit/rect.rs index 9ec80fd..ba2f4b9 100644 --- a/crates/victory-shader/src/emit/rect.rs +++ b/crates/victory-shader/src/emit/rect.rs @@ -415,6 +415,7 @@ mod tests { root_srvs: Vec::new(), root_uavs: Vec::new(), root_indexed_views: Vec::new(), + half_views: Vec::new(), }; ( host(crate::native::HwStage::Vs, vs), diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 1f6585f..4a44a92 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -34,6 +34,25 @@ pub const VIEW_INTEGER: u32 = 1 << 31; 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; +/// LOCAL (port of fxceless/victory-fork PR #1216, GamingRipperDoc): the +/// [`SLOT_STRIDES`] dword of a slot that holds a constant buffer view (a +/// stride no buffer has, no kind bits). A program reads a slot it picks as a +/// constant buffer only where this mark is; a slot whose dword is 0 holds +/// neither a buffer nor a constant buffer, and the read gives zeros. Read as +/// a constant buffer, a texture's descriptor is taken as a buffer's: the +/// meshlet culling `_Prev` passes then read whatever lies at a made-up +/// address (a page fault on AMD). +/// `VICTORY_CONSTANT_MARKS=1` turns it on. Off by default here (on in the +/// PR): not yet run in the game on this tree, where a constant buffer slot +/// whose mark is not written yet would read zeros. +pub const SLOT_STRIDE_CONSTANT: u32 = VIEW_STRIDE_BITS; + +/// Whether [`SLOT_STRIDE_CONSTANT`] is in use: read once, by the host and +/// the translator alike. +pub fn constant_marks() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CONSTANT_MARKS").is_some_and(|v| v == "1")) +} /// Title memory by address (`resource::MEMORY`): console code reads and /// writes through raw 40-bit addresses it takes from root constants, diff --git a/crates/victory-shader/src/emit/size_tests.rs b/crates/victory-shader/src/emit/size_tests.rs index 9c78bf4..391e48d 100644 --- a/crates/victory-shader/src/emit/size_tests.rs +++ b/crates/victory-shader/src/emit/size_tests.rs @@ -73,6 +73,7 @@ fn build(words: &[u32], srv: (u8, u32)) -> Result<HostShader, ShaderError> { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), + half_views: Vec::new(), }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 4a2d829..f3067d2 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -181,6 +181,7 @@ fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, + half_views: lowered.half_views, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -1918,6 +1919,7 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), + half_views: lowered.half_views, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); @@ -2057,3 +2059,488 @@ fn rdna_forms_give_what_the_spelled_out_ones_give() { } } } + +/// A program that moves a typed buffer's 16-bit channels +/// (`buffer_load_format_d16_xyzw` from the table's first view, +/// `buffer_store_format_d16_xyzw` to its second) names both places for the +/// host (`HostShader::half_views`) and moves every pattern as it is through +/// unsigned views: half floats, the not-a-number ones among them, and +/// plain 16-bit integers (the title keeps both in such buffers; the +/// network that moves its faces reads indices this way). A program that +/// moves no halves names nothing. +#[test] +fn halves_go_through_a_table_as_they_are_and_name_their_views() { + use super::host::Stride; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_UINT; + /// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`. + const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { + [ + 0x38 << 26 | op << 18 | 1 << 13, + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, + ] + } + const LOAD_D16_XYZW: u32 = 0x83; + const STORE_D16_XYZW: u32 = 0x87; + const THREADS: u32 = 32; + // The table's second descriptor, 0x20 bytes on. + let mut second = s_load_dwordx4(12, 4); + second[1] |= 0x20; + let mut words = vec![s_mov_b32(5, 0x80)]; + words.extend_from_slice(&s_load_dwordx4(8, 4)); + words.extend_from_slice(&second); + // v[1:2] = first[thread] (four halves), second[thread] = v[1:2]. + words.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8)); + words.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12)); + words.push(S_ENDPGM); + let view = |kind: ResourceType, table_offset_dwords: u32| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: table_offset_dwords / 8, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![view(ResourceType::Srv, 0), view(ResourceType::Uav, 8)], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [THREADS, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + 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)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + assert_eq!(lowered.half_views, [(1, 0), (1, 8)]); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views, + half_views: lowered.half_views, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut dxil = shader.dxil.clone(); + v.validate(&mut dxil).expect("DXIL validation failed"); + } + // A raw store through the same table: no halves, nothing named. + assert!(build_valu_cs(&[]).half_views.is_empty()); + + // Four halves a thread: numbers, both zeros, subnormals, infinities, + // not-a-numbers of both signs, and integers past the largest number's + // pattern, as indices are. + const SPECIAL: [u16; 16] = [ + 0x0000, 0x0001, 0x03ff, 0x0400, 0x3c00, 0x7bff, 0x7c00, 0x7c01, 0x7e00, 0x7fff, 0x8000, + 0x8001, 0xbc00, 0xfc00, 0xfc01, 0xffff, + ]; + let halves: Vec<u16> = (0..4 * THREADS as usize) + .map(|i| match i { + 0..16 => SPECIAL[i], + _ => (i as u16).wrapping_mul(0x0203).wrapping_add(0x7b00), + }) + .collect(); + let data: Vec<u32> = halves + .chunks(2) + .map(|pair| u32::from(pair[0]) | u32::from(pair[1]) << 16) + .collect(); + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.slot) { + (RootType::Table, 1) => 0, + other => panic!("unexpected user data {other:?}"), + }; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[ + View::Buffer { + data: &data, + stride: Stride::Format(DXGI_FORMAT_R16G16B16A16_UINT, 8), + }, + View::HalfUintUav(THREADS), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!( + out[0], data, + "{label}: the halves stored are the halves loaded" + ); + ran += 1; + } + assert!(ran > 0, "no SM 6.6 device available"); +} + +/// The places a program that moves halves names are the descriptors it +/// loads, not the start of the range their used-resource entry describes: +/// with one entry for a range from dword 0, a load at byte 0x20 names +/// dword 8 (a host view there in a 16-bit float format is the one shown +/// as its unsigned twin). A descriptor picked at run time (the load's +/// offset in an SGPR) names nothing and keeps the float path: which slot +/// it reads, and in which format, is known only then. +#[test] +fn half_places_are_the_descriptors_the_program_loads() { + /// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`. + const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { + [ + 0x38 << 26 | op << 18 | 1 << 13, + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, + ] + } + const LOAD_D16_XYZW: u32 = 0x83; + const STORE_D16_XYZW: u32 = 0x87; + let lowered = |words: &[u32]| { + let range = |kind: ResourceType, table_offset_dwords: u32| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: table_offset_dwords / 8, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + // One entry for a range of views from dword 0, one at 16. + used: vec![range(ResourceType::Srv, 0), range(ResourceType::Uav, 16)], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [32, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + 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)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower") + }; + // `s_load_dwordx4 s[dst:dst+3], s[4:5], offset` (soffset null), or with + // the offset in `soffset` instead. + let at = |dst: u8, offset: u32| { + let mut w = s_load_dwordx4(dst, 4); + w[1] |= offset; + w + }; + let picked = |dst: u8, soffset: u8| { + let mut w = s_load_dwordx4(dst, 4); + w[1] = u32::from(soffset) << 25; + w + }; + let mut fixed = vec![s_mov_b32(5, 0x80)]; + fixed.extend_from_slice(&at(8, 0x20)); + fixed.extend_from_slice(&at(12, 0x40)); + fixed.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8)); + fixed.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12)); + fixed.push(S_ENDPGM); + assert_eq!(lowered(&fixed).half_views, [(1, 8), (1, 16)]); + // The load's offset in s20, from the first lane's thread index + // (`v_readfirstlane_b32 s20, v0`): picked at run time. The pick may land + // on the store's place too, so no place of that table is named: the d16 + // accesses there take the float path, as before half views. + let mut runtime = vec![s_mov_b32(5, 0x80), vop1(0x02, 20, vgpr(0))]; + runtime.extend_from_slice(&picked(8, 20)); + runtime.extend_from_slice(&at(12, 0x40)); + runtime.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8)); + runtime.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12)); + runtime.push(S_ENDPGM); + assert!(lowered(&runtime).half_views.is_empty()); +} + +/// A format load of whole dwords (`buffer_load_format_x`, not d16) whose +/// result the program only reads one half of as a half float +/// (`v_cvt_f32_f16`) is moving 16-bit integers: the head program reads the +/// face network's output so, from an `R16_UINT` view. It names its view for +/// the host and loads the integer: 0x3c00 comes through as 1.0. Used as a +/// whole float instead (`v_add_f32`), the load stays a float load and names +/// nothing; so does a load of halves beside a load of the same view read as +/// a whole float (a view of numbers the program also picks one half float +/// out of, as hundreds of the title's pixel programs do). +#[test] +fn a_format_load_read_as_halves_loads_the_integer() { + use super::host::Stride; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16_UINT; + /// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`. + const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { + [ + 0x38 << 26 | op << 18 | 1 << 13, + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, + ] + } + const LOAD_FORMAT_X: u32 = 0x00; + const V_CVT_F32_F16: u16 = 0x0B; + const V_ADD_F32: u8 = 0x03; + let lowered = |body: &[u32]| { + let view = |kind: ResourceType, table_offset_dwords: u32, stride: u32| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: table_offset_dwords / 8, + stride, + dwords: 4, + user_data: 4, + slot: 1, + }; + let mut second = s_load_dwordx4(12, 4); + second[1] |= 0x20; + let mut words = vec![s_mov_b32(5, 0x80)]; + words.extend_from_slice(&s_load_dwordx4(8, 4)); + words.extend_from_slice(&second); + // `body` leaves v2, stored raw. + words.extend_from_slice(body); + words.extend_from_slice(&buffer_store_dword(2, 12, 0)); + words.push(S_ENDPGM); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![view(ResourceType::Srv, 0, 4), view(ResourceType::Uav, 8, 0)], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + 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)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let l = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + HostShader { + stage: HwStage::Cs, + dxil: l.dxil, + user_data: l.user_data, + samplers: l.samplers, + static_samplers: Vec::new(), + root_cbvs: l.root_cbvs, + root_srvs: l.root_srvs, + root_uavs: l.root_uavs, + root_indexed_views: res.root_indexed_views, + half_views: l.half_views, + } + }; + // v1 = first[v0] (one channel). + let load = mubuf_idxen(LOAD_FORMAT_X, 1, 0, 8); + let half = vop1(V_CVT_F32_F16, 2, vgpr(1)); + let as_halves = lowered(&[&load[..], &[half]].concat()); + assert_eq!(as_halves.half_views, [(1, 0)]); + let as_float = lowered(&[&load[..], &[vop2(V_ADD_F32, 2, vgpr(1), 1)]].concat()); + assert!(as_float.half_views.is_empty()); + // v3 = first[v0] too, read as a whole float: v2 = half(v1) + v3. + let mut beside = load.to_vec(); + beside.extend_from_slice(&mubuf_idxen(LOAD_FORMAT_X, 3, 0, 8)); + beside.push(half); + beside.push(vop2(V_ADD_F32, 2, vgpr(3), 2)); + assert!(lowered(&beside).half_views.is_empty()); + // Behind a branch, as the head program has it: where the lanes meet + // again the loaded value goes on through a phi, and a later write of + // v1 under EXEC reads it only to keep it in the lanes it leaves alone. + const SAVE_EXEC: u32 = 0xBE90_037E; // s_mov_b32 s16, exec_lo + const ONLY_LANE_0: u32 = 0x7DA4_0080; // v_cmpx_eq_u32 exec_lo, 0, v0 + const SKIP_3: u32 = 0xBF88_0003; // s_cbranch_execz over the next 3 words + const RESTORE_EXEC: u32 = 0xBEFE_0310; // s_mov_b32 exec_lo, s16 + let zero = vop1(0x01, 2, 128); // v_mov_b32 v2, 0 + let rewrite = vop1(0x01, 1, 128); // v_mov_b32 v1, 0 + let branched = lowered( + &[ + &[zero, SAVE_EXEC, ONLY_LANE_0, SKIP_3][..], + &load, + &[ + half, + RESTORE_EXEC, + SAVE_EXEC, + ONLY_LANE_0, + rewrite, + RESTORE_EXEC, + ], + ] + .concat(), + ); + assert_eq!(branched.half_views, [(1, 0)]); + // A d16 load names its place where it is the only access there... + const LOAD_FORMAT_D16_X: u32 = 0x80; + let d16 = mubuf_idxen(LOAD_FORMAT_D16_X, 1, 0, 8); + let d16_alone = lowered(&[&d16[..], &[half]].concat()); + assert_eq!(d16_alone.half_views, [(1, 0)]); + // ...and not beside a whole float read through the same place, which + // would see the unsigned twin: v2 = half(d16 v1) + v3. + let mut d16_beside = d16.to_vec(); + d16_beside.extend_from_slice(&mubuf_idxen(LOAD_FORMAT_X, 3, 0, 8)); + d16_beside.push(half); + d16_beside.push(vop2(V_ADD_F32, 2, vgpr(3), 2)); + assert!(lowered(&d16_beside).half_views.is_empty()); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + for shader in [&as_halves, &branched, &d16_alone] { + let mut dxil = shader.dxil.clone(); + v.validate(&mut dxil).expect("DXIL validation failed"); + } + } + // Element 0 of an R16_UINT buffer holds the half 1.0 (0x3c00). + let data = [0x0000_3c00u32, 0]; + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + for (name, shader) in [("straight", &as_halves), ("branched", &branched)] { + let (root, pso) = host + .compute_pipeline(shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.slot) { + (RootType::Table, 1) => 0, + other => panic!("unexpected user data {other:?}"), + }; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[ + View::Buffer { + data: &data, + stride: Stride::Format(DXGI_FORMAT_R16_UINT, 2), + }, + View::RawUav(1), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!( + out[0][0], + 1.0f32.to_bits(), + "{label}, {name}: the half read as an integer's bits" + ); + } + ran += 1; + } + assert!(ran > 0, "no SM 6.6 device available"); +} diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 85e2b1a..b25f684 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -84,6 +84,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), + half_views: lowered.half_views, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) @@ -386,6 +387,7 @@ fn immediate_sampler_chosen_by_control_flow() { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), + half_views: Vec::new(), }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index 5d1557b..f3fe382 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -142,6 +142,7 @@ fn lowered_counted( root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, + half_views: lowered.half_views, }) } @@ -281,6 +282,7 @@ fn on_64_lanes(native: &NativeProgram, p: &ir::Program) -> HostShader { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, + half_views: Vec::new(), }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); diff --git a/scripts/play-nvidia.ps1 b/scripts/play-nvidia.ps1 index 2759108..f0b559a 100644 --- a/scripts/play-nvidia.ps1 +++ b/scripts/play-nvidia.ps1 @@ -1,26 +1,40 @@ -# Starts the title on an NVIDIA card with the Series S settings measured on an RTX 5070 (about 20-22 fps, no device loss). +# Starts the title on an NVIDIA card with the Series S settings measured on an RTX 5070 (about 18-22 fps, no device loss). # scripts\play-nvidia.ps1 -Exe <path of your own copy's executable> # -NoSmoothMotion run target\<build>\victory.exe itself. By default a copy named victory_sm.exe is started instead, # so a Smooth Motion profile set for that exe in the NVIDIA App applies every time. # -SeriesX the Series X profile instead (slower: about 7 fps at half scale) +# -Quality fewer stretched/jumping bodies and less rainbow skin, at about 13 fps instead of about 20 +# -RayTracing keep the title's ray-tracing passes (off by default: see below) # -Build target\diag (the default, the build all measurements are of) or target\release +# (the release build ignores the ray-tracing skip list: VICTORY_SKIP_PIPELINES is a diagnostics switch) # -More other settings: -More @{VICTORY_PANEL='1'} # Run it from a normal window, not as administrator: the driver then keeps its shader cache elsewhere. param( [Parameter(Mandatory)][string]$Exe, [switch]$NoSmoothMotion, [switch]$SeriesX, + [switch]$Quality, + [switch]$RayTracing, [ValidateSet('diag', 'release')][string]$Build = 'diag', [hashtable]$More = @{} ) $settings = @{ - # This fork's play set (scripts\play.ps1, not -Safe). - VICTORY_TEXTURE_NO_WAIT = '1'; VICTORY_RELAY = '2'; VICTORY_WIDE_BACK = '1'; VICTORY_CARD_REHASH_RUNS = '1' - VICTORY_JOIN_COPIES = '1'; VICTORY_INDIRECT_WINDOW = '1'; VICTORY_RELAY_COPY = '1'; VICTORY_CARD_STEPS = '2' + # This fork's play set (scripts\play.ps1, not -Safe): the speed set. + VICTORY_TEXTURE_NO_WAIT = '1'; VICTORY_RELAY = '2'; VICTORY_CARD_STEPS = '2' + VICTORY_WIDE_BACK = '1'; VICTORY_CARD_REHASH_RUNS = '1' + VICTORY_JOIN_COPIES = '1'; VICTORY_INDIRECT_WINDOW = '1'; VICTORY_RELAY_COPY = '1' VICTORY_INDIRECT_BATCH = '2'; VICTORY_MAP_THREADS = '1'; VICTORY_TITLE_PRIORITIES = '0'; VICTORY_CARD_AWAKE = '1' VICTORY_SHOW_AFTER = '1'; VICTORY_AMBIENT = '0.8'; VICTORY_D3D12_DRED = 'light'; VICTORY_SKIP_PIPELINES = 'none' VICTORY_THIN = '1'; VICTORY_JOIN_PARTS = '8'; VICTORY_UPLOAD_AHEAD = '1' - # Wait for new shaders rather than skip their draws (a hitch the first time a place is seen). + # Cheap picture fixes, on in both sets: + # - Overbright views: without rays the light probes keep the sky's light indoors. The fog is bounded by 1.5 times + # the light around, and what the title left by 2 times the estimate (was 4; ambient.rs). + VICTORY_AMBIENT_AIR = '1.5'; VICTORY_AMBIENT_MOST = '2' + # - Black blobs: a NaN a shader writes is made 0 before blur and the temporal upscaler spread it (emit/lower.rs). + VICTORY_NAN_SCRUB = '1' + # Wait for new shaders rather than skip their draws (a hitch the first time a place is seen). Each pipeline is + # waited for at most once (VICTORY_PIPELINE_WAIT_ONCE, on by default): one that takes longer no longer stops the + # picture in every frame it is in view (pipeline/make.rs). VICTORY_PIPELINE_WAIT_MS = '10000' # NVIDIA caps the shader-visible view heap at 1,000,000: without more dynamic slots thousands of draws a frame # are dropped (descriptor/host.rs dynamic_slots). @@ -34,6 +48,21 @@ $settings = @{ # Series S presents the interface as a second plane: laid over the game (compose.rs), else black before gameplay. VICTORY_COMPOSE = '1' } +# Ray tracing mostly off. The structure builder cannot run on NVIDIA (its 64-lane programs are refused; upstream +# Marvisak/VIctory pull request 2311), so every ray misses, and the passes that turn misses into light made rooms go +# white depending on the view angle. rt_off_hashes.txt lists the 1,000 CS_RaytracingResolve and 34 traced-shadow +# shaders, which are skipped. The screen-probe and visibility traces keep running: skipping those too left their +# outputs as garbage (rainbow glitter everywhere). +$rtList = Join-Path $PSScriptRoot 'rt_off_hashes.txt' +if (-not $RayTracing -and (Test-Path $rtList)) { + $settings.VICTORY_SKIP_PIPELINES = (Get-Content $rtList -Raw).Trim() +} +if ($Quality) { + # Stretched/jumping bodies: relay stage 1 and no card steps (avatarmanz/VIctory-7900XTX issue 13, + # fxceless/victory-fork issue 89). Rainbow skin: texture refreshes wait for the runtime's remapping. + # Costs about 7 fps (the submitting thread waits about 30 ms a frame for the card). + $settings.VICTORY_RELAY = '1'; $settings.VICTORY_CARD_STEPS = '0'; $settings.VICTORY_TEXTURE_NO_WAIT = '0' +} foreach ($k in $More.Keys) { $settings[$k] = $More[$k] } $victory = Join-Path $PSScriptRoot "..\target\$Build\victory.exe" diff --git a/scripts/rt_off_hashes.txt b/scripts/rt_off_hashes.txt new file mode 100644 index 0000000..b02eb62 --- /dev/null +++ b/scripts/rt_off_hashes.txt @@ -0,0 +1 @@ +002f8eb4802deb36,008f3e09ac72b1e0,009411de14bdaf7c,015832d72477fb26,015ccbad26579e10,019bbbc14964fa81,01a0989ded2608aa,01cceb8d45b52bf8,024fc71d30ecf62b,029e551efc53f959,02a4ed10c682ac3a,02af016b81284952,02f7c70b1180ad08,031a0cdf7eea05e4,03c593f1296c249a,03eb4074242a6013,043df98be0270424,04d46e7934e1fe24,04f90cb19f940759,0512c381f84c2ae9,05b939a0705f27ed,05ba183058112919,05d0579c2cacd393,05ef21a2132db12d,06989306fb3b54c2,069933f119b8dc40,071749f385c35640,072f5fe96efd27e1,0753e7f1ebeb1681,075e4d20a54baa28,077869cd9b1456ee,07c6ecf2f7ff4e69,0801d2ce0fa5e5e0,08ef5b2aa4d1f252,08f914eec26d44e7,091c5b9715bf60ca,0926a680fc26dcba,09361790d2954b37,09a142d26deecbba,09b0be1e60364b47,0a12de46c4d5db08,0ab92d33b2800cac,0ac6717164281c2d,0ad5f672524dbdbc,0ae69044bfd15035,0aed4662a44cdf61,0b07d50b76014236,0b3d156291158496,0bb64e3e583c4899,0bcea570530f53d9,0c0120fcb5aac198,0c3f84cfd614b0df,0cdb904653133be0,0d0e7097e89fd890,0e82ddb656aab93d,0e8ba5f65adaded2,0ee452e79fc5b98c,0efa55e3d4952b26,0f0996fee0545c14,0f0defdf30b9ba7d,0f1395e5942ca3b2,0f1ea383d368b3c9,0f5d12d14d22e848,0f6878cf07be69b5,0fbd0340052ebeb6,0fe3c05d0fc8c074,110e0d0bac2f89a9,11bb63dffff08dcc,11d153b2f0b807ee,11f60daa85075500,12277d3fe5b09f57,1261271b20a35d1b,12e375a4a2ddb4eb,12efa84143ac3f9c,12fd000b7df7f35d,1351f0efaa452416,135237a5f20fc8c4,1378934c8174f649,137de2f8a7ef881c,138715fe4ad3f11a,1459863b79e1c6c1,146934cd6e55dac6,1472200ca409949b,149cb3508b989d0e,14d57d8f0cf5f2d8,1512b6b81c4072ed,154b14f2e16015a1,154cad3e8a014898,157d961dc763b8a4,15c8f09950ba2980,164e0145dabd887d,16622000e3a30bf0,168ac102b4088dc9,16e698c250d4e48e,173eb108a2e8ad07,17abf892ce45874a,17e32bc9dbc554e2,1807bb5832825166,18406421ee8b6e8f,185fca8fe0f3c45b,18acf73cb543f66c,19c48e8df2525284,19de2179f549fd39,1a1089a18f7ff5f8,1a72961fb4e91af0,1a83504bcee28c3b,1a919da0e04bb9cc,1b0893dbeea49285,1b20028fc5fae124,1b72691c45556780,1bbf44423a524038,1be5f31a9bf45d93,1bea280ac0b0105d,1c02f8131c508c75,1c13258774db7662,1c268875ec1ae9b3,1c2888d0f2ee3578,1c6050da9b536890,1c6ca57774390d61,1c7d12f61284dde9,1cc4a387e7ab270f,1d495a6ae4665a95,1d85ce5cf0645144,1e05feba773151c1,1e0af7527af3431b,1e1d0a4971e46f74,1e225eb5a582051a,1e4947eada3d9ee3,1f55c45de66dc2c4,1f7d589e25ac7ae7,1f8e2bb1d26f9a53,1ff05fa9d6793947,2006d876c438c7f2,2007e47e566d5ca3,20117840e7be70c8,203f78efece5bbdf,209db98c2610b1f2,20ed134dfe212910,210b038b2c2a6589,2133abe5e36f8449,214d84759c294d11,21925d87ec794b3c,21976b76134eb419,2208774ed8919ab6,223451eebd6061a8,228e926c4faac818,22e10ac0ddb8bb73,22f2cc5708df88be,230256e20bfd61ab,230a91c3826aaad8,230dfb08f981ce7b,231d2daa66789312,231f97ce8c51460e,2331e6a5c3f4dc73,245c03778498b495,249d03a504be80d3,254d39dc062ccbd2,2582aab1c7e668e5,25994ba679ebf4ee,25a77d8c961f70c3,25ec3eb56b6b4711,264c19e1f1c9ae60,26c37a5db50197e6,26d721e2d277c03b,26fbf87d883e1381,2706619ccc47630b,27a41d4c85829617,27ce027e7188bed3,27d1334b3958bd4c,27f379458a4387e7,28158d322104bce2,29093f0853881fc3,291be4e50b1272f1,293ad39389e70011,2964f72e06633f7c,29b2a8ec6424f269,29be03ccaa4e353a,29cc57bb8d704fdc,2a227f58578215a1,2a49e9ee73aac24d,2a4d50f2e99ccc76,2a5bd654ed830e72,2a5cb98cf0749a82,2a948292aaf20bee,2ab2457ed7617293,2b7f74908db2fd5e,2bb02bd91627418d,2bb23624d292d127,2bf91065944bcff4,2c2cefe06f048390,2c3c2602cf51d780,2c6eff2fd3d967c3,2c8ee60bfd04125f,2cc6decf9a73aedd,2d3c50b5aff0f7fb,2d6cbd167e79f48a,2d985a6fd3ae6e5d,2de05f43518e9170,2def80b5a6667abc,2e1c7a0a104906f7,2e28ea6fb9dad3c2,2e55d67003435c14,2ec1dd27e95fdd16,2ef28b3f055cf523,2ef7ed9bfc249bff,2f12d0f639fb7ed0,30727a8e4a68fc64,310a75ecf7e2c0e6,31bc42e2ea163a1a,326652d23fe73e99,32738648a576fea0,32b601132a13cff4,32eae53ef2498b71,32ff8b2fc21b2b61,334cf8d4ab5e2968,33e4acc94ea85bab,34121970d8a2e435,345cd62173c375c7,349493bfe6b68a87,34e028869986bcaf,35256c370615e650,353b2ff8b1040ce4,355f182eb23a2ccf,356b9eb924b82c31,365a74ae25a02341,368098738d8f1936,369e1cf9bc7dc155,36a631c57b93f93b,36bcbae3c6ee20b3,371f8ece65314945,371fc6b7dad5f271,37801617a570a3c1,37d324dbc6c86d16,37d9c18c015bc7f3,380028daa2706e89,38047b50e3443232,385afa7d556e39e8,38925291c659560f,389d2a50fc6e6018,38a52b258e5d26bb,38e48f628d308bce,38e7dedf37c90130,38f64f73d01d25cb,3934246fb674f317,39613a32023e4def,398d972280d662ef,3a22184f3b17f637,3a59b63b97ad1abd,3a6594961b9247e7,3ad0a1c1e5f591d2,3b168eb06ebd1f89,3b47ec04e064477f,3b741eb770b99f1f,3b7b226a0af45f46,3b9d6c2ddaae83d8,3bc3bfd1cec35a7f,3be66cd8abe8095d,3c5edc2725a39f30,3cf8a8fc81e6458d,3d03a8a88ad6670e,3d10c5ac254b9a3d,3d547602bdedb4eb,3d7af3f375b862bd,3db6a8cd5178b215,3e0536ff12f1a0fa,3e7e04c03727b40c,3ec37174114f18dc,3fa1fda35402c93f,40769e6c239f937d,40a32233402db4cb,40a8893aaeffa08b,40be578998668a29,4121071b5398393a,41217059b1eb768a,412868f442f3638e,415285668412204e,41819a1d0f885f45,422a5efe85d59e6a,422ae0b850e3624e,42aa89d313e7188c,4342a5c16979a53f,438b12b60f5db630,439716b7afba87b0,43a9fcb6c2636c61,43c72d85c4d86ffe,44a63aac0ea89a86,44ab1bd3cd6459a6,44dfb4c9f4f58355,45d25d3d28d7248a,464f5ba0daa4d1bb,46539424133f9b74,4697ffef97840f87,46a7f7fae3d2a65c,46c25132e6d22a04,46dc6c870454c7a6,470abab5c440c9c8,476446edcac7d521,479975ca9ff7e370,482d518532477e6f,4831be51e2ddbb5b,48654f1a6ce7f688,48ecc7b4d0968151,49935789e06a9b08,49c9aea86d416b02,49f2638c5dde0b23,4a51115a275d6335,4a55d212cc63c4ad,4a94c9adf5b2a83d,4adb3993b5a32e6d,4b4661fd9113cd4a,4b89a97ed9dfbe2d,4c573a76d2eeba04,4c780a471589d843,4c939cff28c2e1d6,4ca60aafca490f58,4da404cec3b5774d,4dfd5ed22314b4ba,4e0e2e2be4aec51c,4e69dc8770bf27fc,4e7ee9410ff16d57,4e86768ecb577cf9,4eaca33ef0b5c5ac,4f0d3d0c96a754f7,4f24ef2eee54fa06,4f895b74b86ac34f,4f93dfc3d999393f,4f9e4161d703f789,5002dc855d7c1bdd,501f0865fdf45dfd,503cf21ee3992b39,50477cd6f2bd62e8,5068b601735705a4,50949ebfee9eb51d,50fe6dbe276e004f,511b165e8c6f13f1,51340b4703f0e042,514b2105ad3d15de,51529682c38a2bc1,515371262d6da9f5,517535025e084ebd,51b4b1881981e654,52018f93785d6723,523dd9fe1a846c57,52ab310c43b9f99c,52b84c47ea411af2,533ff93b7c9adbf2,535f8a954d8ec638,537522c620805a34,53dbd04f3cafb88f,5439a8ec4be90032,54c8e6597f9cb705,54db209c0e1bb317,55153ab821a66fce,55858df1827ed9d0,55f2a4d171c8eeba,569d5818db7555f3,56e546e08e2e0bf5,571bf6d258f65ed0,5746e8eb5fc789a6,57a3fad03cac36af,57a89b3e2e61ac25,57a99301636eec5a,58a085bb8210cccc,5904bb0bd887a152,592680ab38031b20,595f2141e585c320,59792d2b282b4b29,598ea65d783fa12d,5a06550bbac79916,5b07cf102c5fb661,5b47ab4f89743d00,5b9f648fb54238f9,5bb4f587ecce90c4,5c10a56026ce13dd,5c7115296f0a8c41,5c82b79526ec2376,5c9d6316a51968c5,5d061e6aed59c57d,5d14dbfb09c8184f,5d4ad8bda6371f79,5da27dcac8ccd11c,5dc7c4abc75d1545,5ddd2ca380fd74d8,5e5b5c98afaa1753,5e92d32fd0c115f1,5e98acb32ee72e90,5eb1fc8c755bca61,5ececdeb8cd235c2,5f534ee8ed14f12f,5f8cf29b763648eb,5f970e9e47594541,5fdbc49b328e81d2,60009ff452b7bb54,6043a5c6d7e9545c,604a8deeada90f0c,615e4b316a3f8294,6180e67625d71b41,61d7c3333b73892d,62d2680b4de77b54,631d7f5bc2692fd2,63cb9879559651fa,63dcd49361dd8ec4,63f30685a64914f7,64291515aee9dee9,6441aa82da422799,649850fad69f9228,64ccfcf6dbda1152,64fd06f748cfa1e1,6507b6807f522057,65080b29d91a422f,65e3b4b0759b4d0a,65f802ba40eb4a87,66404798a567d7db,664a24a19f9df45a,6741171642c93081,67c3552004aca7aa,67fb9cddcf543d91,680b9fab03f54e4f,681f89eedac269a3,687a6c8dbd8d7389,690ea04f96a14884,695febfd5efced05,69d7fb6958502e4e,6a00947adb9651a9,6a19b6c520023886,6a20509b65f9a5f1,6a608f2053e604b5,6a7b41a73fab3f66,6a7fcb54bf246310,6b5f333e886b1030,6c86597c4a6c9c5a,6ce22dd14d876fc0,6d1f1af87409128d,6debf18bceee5f8d,6e23ac3f428905c3,6ea325014572ed8d,6ecb5deb3af40c9c,6f3efe76389642cc,6f859da7a88802de,6f8ba6961490ebb5,7007ec7e2ae00712,7019cc71ca384dc7,706c4f9cb0f4cbfd,70a3734bb266ce43,70b1e13de6df8585,70e78ff3961d953a,710a6eca5746445e,71961bdd346c45f8,719796c2b324593d,71ac5a0b99a51edd,71d5752d4d13974c,71ed96a64e932f76,721c6b98cc129aa5,72ee7db2a361ed65,72f84d6cdf836fe5,72ffc690df101ebb,7364921ed673344b,738c1f4089f14c47,73cabe666a66b4ed,741a9dbb11726187,7477b30d3a90be1a,747cbfa17dd7b24d,74930ddd74e36464,74cb99ceb454f355,74d0ebdf42728160,74f02289c9df5432,7514cdc54e3c9502,755edfc1003acdc6,75835efd55ca7167,758398ef7c32ee31,759aade8ac03d23d,75cbdae3b2da61bf,7658f1433b3ee4b8,76cfc8733e521f35,77102d53e4c12acd,7722237b2d9f9568,775864f2dfc88998,775d94fa817efe16,77615112be1fc7e3,77af7adee63083f5,77b7d7f05b292d27,781855483aad9a70,781e845d3e7ddced,7855309698000643,7871917ea1ba35d6,788d85601b22821f,78be9c2cfee2766d,79547b8d831bbcb0,797b90880091722f,79d3f9f9b164ec42,79e8f0811d07f017,7a0d42aefcee50a4,7b956e1f6d56609f,7bc5a66f3fe54503,7c7c52f59ed8d8d8,7c8010dfa98a4a9e,7cb338ecaeac0aa9,7ce830739b018ff3,7d30d09632fe7230,7d3d547e81d1d118,7dcd3a412a157e2c,7e23fb9a6be471fa,7e272e404d9a61d1,7e36d2a6d7c6a341,7e39630e36c59e15,7e666b54122429fb,7ea1d4d3aca20da4,7f05ddab771799a9,7f0b6f363e03b1fb,7f4ef84f10ee483b,7f67edba322d461f,7f6c3d8d319e6d29,7fb216a0c6dee3a9,8035d76170689f4b,810e4e3cf4237f07,811ec8279c97c1f6,81a798b379f98105,81b1a23c9de4ac3e,81c7c8d1bd09a944,82d469a7fec64cb4,83547e5a9e0581a7,8374e8bd3adaa914,842de0c32bc8dcc5,848707be5ef2843c,84a06428e6e455ab,84d6f253344db38e,85499d8904c05f47,858cb9984a20a09d,8592f1d4f8035dc0,85c42c66489010c0,85df3e0b2a2e72af,86380b036b00d3fc,869415c2d19e36f6,86ec5195c2fa82af,871583f211e7dae3,871f1215f671882c,87479c005e2b4043,8777116ab8279358,87e73d580fe6a492,88d648c905124388,88ef12094a20a42c,88f6e5d9344943be,891bd7a5134bf22d,896cd6b48e0b735e,89cc3adb9b3b587e,89d4abe49e730d80,8a068d3c7bcccc01,8a13d3da7f64b8d1,8aae6058589bedbc,8aeb634cd7c272d2,8b566eecfb71cacc,8b789540787ce9b8,8ba13a8355a53b91,8c9910d177e922b6,8cb9738c65481189,8cd8c8520c791196,8cf104b72e4a464b,8d5d3f97369050bd,8d6542a554c1147a,8d7bf99583310094,8da50e10dd1d5cdf,8dc919cddcf1ee78,8ddb224ef5dd08ab,8dfdf0d1c35ecea8,8e6fe95e600f3430,8e8696b916e3b141,8e91532497eb4ddc,8eca0d5db8dc7455,8f8dd4e691330c74,901ea5039cef0f12,909600eff697581d,90b02e69b90016a6,90d8df75aee69274,9118e859d349ab3f,9211a9c1bb57341b,92646708c3651a59,92bf545af3758416,92d4fbf3c4420b32,93c727ebeb0a414e,9422aad366692af1,9453e092e33f7f9c,945faaed7eda27dd,9494f1b99c92c281,94ba76b4f1e267dd,94ca5843379047d8,94f50b5020a69895,9506d52d41abfd92,9588ffb2478b45fc,95ad77412a88f3f5,9638c0c03cca4c6c,965b1fd9c61467ee,96744a8cd6c0588f,9693500202657a6b,96f043b62d77793b,96fad987a10d2178,9730c147304b8039,974a9d7e98c8472b,97c8165dc4f77bea,9837bec0c04f3746,9898a993d4896967,98b28a028bb1ab2a,9a13e9c13c57411f,9a6eb0b35e956927,9aa51ebb679b4e36,9aa61fc93f91d095,9b1235ce3bb3d161,9b18e7f333c1d4f9,9b484cbedc2d7cfc,9b5c4b6fc3e08c7a,9baa27bb65889d34,9c077417ffd3fa41,9cdbbfa2055ac39a,9cfd9c092e1d5a97,9d180fa0ccd52a27,9d4962b03185c07b,9dc1b86497754e73,9dd28e16445d6477,9e5deb7cc4c2e068,9e644939640669fc,9e88ce6227492d86,9e93ea4abd276eb3,9edf8a8267e77699,9eeba5c4a5cc1bff,9f1e01df5796c330,9fb1ebea2c1a32d4,9fd538515af9fc60,a06f4e4a750d260a,a0a074e2d868e618,a0ce4bef0ae97c3f,a0feba02e6cf0ebb,a1266cc7391ae0d6,a17ec51447e9b9f1,a1bbb095cb9ba1c2,a2352b9e2e9687eb,a2d880ad5dea1f45,a30ae8cc148ea059,a34d8ba7899e5277,a356d933075c6552,a374b2c962e658ae,a39ae7824fe671cc,a3c8adc23ab13eb3,a3f168d1790bbff9,a4169662a3549d17,a428c56efe5410fe,a438ee47aaa88b91,a47d0bb7c7e1e8ca,a4df980a1c65fdbe,a5399b214713f180,a57b5ad32276f8c0,a5ce23ef6a443dbd,a5dcdb5ab74beaeb,a5ed733fcbc9048d,a60f2ec7c2ff300b,a62731e90739f195,a65398c11dbc32ca,a664ce85c7ed8514,a7063551ab31b18b,a73284b60aa303ed,a7aef9e157ccc7fb,a7bbeaedc8e63360,a7d9b706b3465142,a7e6e0c9658aa904,a81de501c6f6ddcd,a87c63103cbe8249,a88748f4d223a920,a97b0de6386eca68,a98b2d2aa2acfffe,a9da8d8c21873245,aa107f09071811ca,aa221f469520e809,aac91f96d7555409,aae143ad4554b35b,ab19eae07e101c34,ab2765c008e8f04e,ab82aab9b599caac,ac8b0f8a8a9e0c79,ad17f5c4f7acac25,ad1cf51b8a6c7096,ad66a7c4bb2a77d9,ad8767d2da8435b8,ada19c97379f54bc,adc76ddaa3a13d20,add2d88b887885ee,aefb9a3ccd87421f,af3033548d076333,af4285d1da44a96e,afc5e62226ffbbc0,afca4e7816c70b95,afe3fb6e266aa5d1,b01e713adfd1b66a,b0226cc73c654742,b05d94d34dca4d2b,b084beb3ae6e27e3,b0b6a2622d6e72f0,b1b90a2b3a76dbaa,b2433b5b9845e711,b24ff5260e7c73cd,b2610b50166271d1,b2a79b56df1b85a1,b2ff2ef0d6c98dd7,b33899c67f22fa73,b3642a96ba443130,b3a428c1444c8e47,b3d19bbfbe971a8b,b40b3d8b444ada08,b42133da5f18f92a,b5075976aab8a28f,b51198aeaa434f1a,b55f324fb9f9fd51,b56cb5227f57e719,b671c90cad4a71ee,b69ef139ecd3b757,b6a28de7790e0a7e,b740639a48e688c6,b74ef432b1989b12,b7a7fb5ba5934a89,b7c35ddedb2c5cc3,b7fc9aa161dbdff0,b8042ca0af2f51c7,b829a51c2c2d4551,b83683e48abab9bd,b849f3f75c47a541,b967e77f0832eab9,ba0853e333e60933,ba1d9b18a9a571c1,ba6db671f79ae2d7,bb9c70158c1e22f8,bba66bbd55cbd9a0,bc3013e09410e5b1,bc7613a38819a1f2,bd232dec3bec4319,bd2f4c284a45b3bc,bd48d109e0b65217,bd673df5f240bee5,bddfcc3248f51318,be254519c3e15f64,be85f65a58656cec,be87288ad49b521b,be91ff7eef5b7852,becf87ccd8fdc1d7,bf1a5424e1b24d5b,bff3758517ad9142,c07b4d9d12a670b8,c0b9134fa622f802,c11581d638466192,c18e21e30faad154,c1b787327704c7f3,c1c7f6c2e8d5d2a5,c1d216bbc48bc9b4,c1e947806a47ee4b,c2f48c284c426430,c2fed64ee9b4bf23,c3117eb7dc3df471,c3864e62b7ffedb6,c3cb00c582d26394,c4023b5da8f2ce0d,c41429a8461b2032,c45fe32380ec2ef4,c47848abe71e05bb,c4a6e4fcf36a2033,c59bba942079b5d6,c5a3550ade4c767e,c5bf838f820fcc2e,c5eea4706e290002,c5fc2bc7f3d416f4,c60a8cc2683470c3,c60f282e136b76c7,c629ea495ad5be01,c69690deef0df358,c723729ad62ec697,c7b5d2d6e4e79e98,c8168a63471484b5,c896e7b54e00286a,c898bcae5656e417,c8a92fb86f31447f,c8d82097d68afeae,c9158941815aee62,c985aaf507dd3152,ca20fb3e42f84692,ca27a20b691326fa,ca3962cb8c674650,cb1006bb4ef510ad,cbf484655edb8a33,ccb2ef0f61223a15,ccc6eb3a3ef3e935,cdfefd6c8bb5dddd,ce0986e922fd40d1,ce4aa8c4600d85c5,ce4cf9d5b637a014,cea6cddd5326f6f0,cf0000f4537adc5e,cf4ce294accdd428,cf6868feac4b57ba,cf9bc2ab0b87e572,cfb21609d5f6a845,cfbf210830540a52,d0130073bb6f7a7d,d03d2f08eac22af2,d06b9d11b9265d12,d07589ad1eee4789,d0e8017ad28dfe19,d159096c20e5be8d,d21ae5d0eaaac74c,d282bd3d228df25d,d295a7bb8b39cd5d,d2b073bdd272bda7,d2c52fcd936985b4,d2eeffa9f876f56a,d2f6e544053acf55,d37ee2c1b91eb44a,d3917417a4e4f05d,d3a9cedce74d91ce,d3c2bcd69864ab66,d43289c11944a7a1,d4343b9a6e4f2717,d44e7912d7c1bab1,d46dfa0a902264ca,d46f9bb80b40a33f,d4f67ba4e4e695fa,d5131e7000dad14f,d5784d991f3164ab,d5b9c94a30d7cf28,d5c18b9fbcd08f36,d5ef4f2bb16d9fa3,d66a8e12bc1b27f9,d69f75770edf6e01,d6a371025bcf7e02,d6dba265fd10bc2b,d6e3a104264dd4c6,d7792cca59ed128f,d7ad7fcacbe52893,d7eff81efdc96061,d84645aebf8dca8f,d84c0ca92452e526,d8b41c72e52111ff,d8dde91b9e50a4cc,d9075dd50b1cca09,d91b2ffb8db48ce4,d96e054e72a72ab2,d9748ab66d9903f1,d9960eda3ab4c793,d9befe585a53610f,d9c73fe683ef7785,d9efdb70d39c1c86,da441db0e9fce769,dab8612ea72ac214,db0b0fd02ddc8a93,db40744873920422,dbba7e080e26ec20,dbdad6ff83aadb1c,dbdf9f9df42b2c69,dc65695e569ab466,dc6ef2687950428a,dc901b90d0633a00,dd002690745ec22d,dd17c8da5c1cc0d5,dd18ab2b9c21b361,dd66eddf464f4bb1,de314b30ec34ee35,de4e3af66d68d980,de63a341789daddc,df1c34cb6d9dbcfa,df28ea82c24dc056,df3c6b6f46100a6e,df68734027b2d0c3,dfa0cc44b45911d6,dfeef669b85178f5,dffafa6052629c85,e05a2c1364dd1988,e09b484b7400df95,e0ba27015903a5f3,e107201b7701a928,e148ad14c65c1dfd,e14ca2879156a091,e14ff49747e43acb,e1a6549a4718256b,e1b73b0e1f8d3c72,e211ec7b25919742,e2b858e568731a51,e2bbb611de6511d4,e2d427b0b6dff0d3,e30d21f0d7cc0880,e31587e8b64a7e25,e374fb548aae0ef8,e45baebc6a72e818,e4714debf856a402,e4804e5d87537072,e4b98007c374f061,e500d9c67eb7cec1,e50ee1165aac96b3,e5742545a3591526,e5929e833978d558,e596f88f20c3ec8f,e5b42ce7dd14cc41,e5c6b41bb2adb46c,e5d41b7e3006b249,e5fca2b95c853817,e62845424338161f,e685f0080b144a9c,e6cefb06155dac34,e74c876bd581859b,e758676dd153dff5,e79b0196ae5e27d5,e79dd4bd900b4200,e81277c8be37103b,e82463dae16a79ee,e90b8dcb8b4cfc6b,e920d92582cb15f1,e932a28baa58153e,e995747c51da17f0,ea2754446fe2e1d0,ea55f4b164fa2fb0,eaeb10a22b9d6d7d,eb0472e1f9299d59,eb47e845b2cb0eba,eb62e8e10b72f527,ebd66fe3453f755d,ec5bcfd7dd20c68d,ec8170ec97875620,ec8544c3b04dde27,ec992130e4f7387e,ecd67a438c64e75d,ecdc3a46f8db7a5d,ed9df95f1d43fd4f,edd6b83325de97ca,ee0f481da4520f33,ee4c89fea116872c,ee636271b480f425,eeb352e9ab670763,ef166f5e4a1e04cc,ef9f08487c8cc9c3,efc770e7f2c27b03,efdb8133aabc37fe,f0072e7d6d922b51,f018c205b5199d39,f0641885a8311319,f09b1760a72a26af,f0afa89ecfb6944e,f0d5c40a8c448a86,f0ded3c8f537287b,f0fad1ae48adb805,f140b29a240488c8,f1690b766e32ad76,f170f74128b85209,f1914c6c99d9577d,f1d566c1e044b018,f1e90a572946abda,f26cef5385572630,f2b05cae4e26c094,f32e9279590aa073,f33e805895d6dd30,f38d99b7a22477c9,f3c00fa863debb3b,f3c50f940f5b3106,f3c72658d0a642e1,f4215fc6f4a11aa9,f429d6151c64ce9e,f447e1cda168409b,f5f8da18803c22f3,f606667fe7c6b893,f60ea2c9d69cac35,f639f0fc07d7a39b,f63bfed4d7317be1,f655d7219b8023ec,f6a0d66f51a08d1f,f6da51317fcef92e,f73607ad12ab905d,f753717509f8ea20,f770aa1780a8878e,f7a5d494c618be5d,f7abaa39145df433,f7b588a6cdd60598,f8858586452e1ae7,f90f441cc9311f33,f91ef42e5b381cb9,f93a3a0da36147c7,f96d5cb8d72d9461,f9870b59c6d3c45b,fa056dc3e38cde75,faa6852385b8d530,fb666fb12f337286,fbdcc8e04b7f68d6,fc0cd9b89adde3ab,fc0dcb1f5312423f,fc311dcf2edb1fe9,fc40d61585d7a20a,fcd45c3d0020311b,fcdd5aab1f58e5ee,fce7d2cbef0f4a24,fcf879f8a407a4a9,fd9778f48ea9e227,fdfd1675ebbd57bc,fe0c502f0ee290a7,fea276ef543c780c,feb207119a4a496c,ff26243811447aed,ffa23aec3187f880,ffa98fdac87e91cb,ffb89aac3c3bd89c,ffeb489faf8be584,0275bde6a28e48ad,08ef61b38bdc988b,1250dc0656b3c091,17829ac71aab4e8d,221925bf9ed4e06e,22f3f0f74693bff9,43ce3255529b200a,534b3645dd344ab2,693d1d787d4a22eb,7ec122fc9eedf367,813783478ebb80e6,881646f629ed5b13,9701445db7a7e2f9,9ad3577822ed8af2,a0544eac81df1fc8,a1b20bc47e3c9597,a1e563ed5a217ebb,a41f0b553a07e79d,a96bb7e19625fc8d,afeea48bbb9913ad,b1e1f8b58b12a8bb,b53dd5baea7ac7da,ba263b6ab4b6d619,c2d3fdeffa839418,c331a83aa58c3d33,d2f4f8e0e2610d8c,d4c32d1ea3b676be,d50c03da6d935d87,e8c962358d862e3f,e9c39e7efe3c508d,f656e96a62bb116b,fb515ca95d694c18,ff6a098566877642,ffd9788ba9fec033 From d3cd650c1291948cd95310e62f38461a4a2d436b Mon Sep 17 00:00:00 2001 From: trustno1-coder <361337194+trustno1-coder@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:20:45 -0800 Subject: [PATCH 431/445] Launchers per console and resolution play-nvidia.ps1 takes -Resolution (2160, 1440, 1080, 720, 540, 480): the height the world is drawn at before the title's own upscaler. The render scale is that height over the output height (Series S 1080, Series X 2160); Series S refuses heights above 1080. The script prints the console and resolution it starts with. scripts\play-S-{1080,720,540,480}p.ps1 and play-X-{2160,1440,1080,720,540,480}p.ps1 call it with each, passing -Exe and other switches through. README: "Picking a resolution", with what each draws, its render scale, which were measured on the RTX 5070 and what to expect. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 57 +++++++++++++++++++++++++++++++++++++++- scripts/play-S-1080p.ps1 | 3 +++ scripts/play-S-480p.ps1 | 3 +++ scripts/play-S-540p.ps1 | 3 +++ scripts/play-S-720p.ps1 | 3 +++ scripts/play-X-1080p.ps1 | 3 +++ scripts/play-X-1440p.ps1 | 3 +++ scripts/play-X-2160p.ps1 | 3 +++ scripts/play-X-480p.ps1 | 3 +++ scripts/play-X-540p.ps1 | 3 +++ scripts/play-X-720p.ps1 | 3 +++ scripts/play-nvidia.ps1 | 16 +++++++++++ 12 files changed, 102 insertions(+), 1 deletion(-) create mode 100644 scripts/play-S-1080p.ps1 create mode 100644 scripts/play-S-480p.ps1 create mode 100644 scripts/play-S-540p.ps1 create mode 100644 scripts/play-S-720p.ps1 create mode 100644 scripts/play-X-1080p.ps1 create mode 100644 scripts/play-X-1440p.ps1 create mode 100644 scripts/play-X-2160p.ps1 create mode 100644 scripts/play-X-480p.ps1 create mode 100644 scripts/play-X-540p.ps1 create mode 100644 scripts/play-X-720p.ps1 diff --git a/README.md b/README.md index 045c30f..8d981f8 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ RTX 5070 12 GB with a Ryzen 7 9800X3D, in the prologue: 1.0.2.1 executable pins its internal render scale: the 3D world is drawn at half width and half height (960x540 on Series S), a quarter of the pixels, then stretched back to 1080p. This is why the world is softer than the menus. + Other resolutions: see [Picking a resolution](#picking-a-resolution). 3. **The title's own upscaler** (`VICTORY_OWN_UPSCALER=1`). On Series S the title upscales with AMD FidelityFX (FSR), whose compute programs cannot be translated here, so that step drew nothing. A patch makes the title use its @@ -235,9 +236,63 @@ scripts\play-nvidia.ps1 -Exe <path of your copy's executable> `scripts\play-nvidia.ps1` starts a copy of the build named `victory_sm.exe`, so NVIDIA Smooth Motion applies every time once it is turned on for that exe in the NVIDIA App. `-NoSmoothMotion` runs `victory.exe` itself; `-SeriesX` uses the -Series X profile (sharper, much slower). The fork's own `scripts\play.ps1` is +Series X profile (sharper, much slower); `-Quality` gives fewer stretched bodies +and less rainbow skin for about 7 fps. The fork's own `scripts\play.ps1` is still there for AMD cards. +### Picking a resolution + +There is one script per console and resolution in `scripts\`. Each one runs +`play-nvidia.ps1` with `-Resolution` set, and takes the same `-Exe` path and +other switches: + +```powershell +scripts\play-S-720p.ps1 -Exe <path of your copy's executable> +scripts\play-X-1080p.ps1 -Exe <path of your copy's executable> -Quality +``` + +The resolution is the height the 3D world is drawn at. The title's own +upscaler then stretches it to the console's output, and menus, the HUD and +subtitles stay sharp either way. Series S outputs 1920x1080 and Series X +3840x2160, so the same height is a different render scale on each: + +| Script | Console | World drawn at | Render scale | Tested on the RTX 5070 | +|---|---|---|---|---| +| `play-S-1080p.ps1` | Series S | 1920x1080 | 1.0 | not yet (one report of a crash on an RTX 2080 8 GB) | +| `play-S-720p.ps1` | Series S | 1280x720 | 0.667 | not yet | +| `play-S-540p.ps1` | Series S | 960x540 | 0.5 | yes: the default, about 18-22 fps | +| `play-S-480p.ps1` | Series S | 853x480 | 0.444 | not yet | +| `play-X-2160p.ps1` | Series X | 3840x2160 | 1.0 | yes, about 6 fps | +| `play-X-1440p.ps1` | Series X | 2560x1440 | 0.667 | not yet | +| `play-X-1080p.ps1` | Series X | 1920x1080 | 0.5 | yes: the `-SeriesX` default, about 7 fps | +| `play-X-720p.ps1` | Series X | 1280x720 | 0.333 | not yet | +| `play-X-540p.ps1` | Series X | 960x540 | 0.25 | not yet | +| `play-X-480p.ps1` | Series X | 853x480 | 0.222 | not yet | + +What to expect: + +- **Lower is faster, up to a point.** On this machine the frame time is mostly + the CPU preparing the GPU's work (about 33 ms a frame on Series S), not the + GPU drawing pixels. Going below 540p saves GPU time, but the frame rate stops + rising once the CPU is the limit. +- **Series S is much faster than Series X at the same resolution.** The console + profile changes far more than resolution: the title picks the smaller + console's level of detail, effects and memory budgets. `play-S-540p` and + `play-X-540p` draw the same number of pixels, but the Series X one does + more work for each frame. +- **Lower is softer and smears more.** The title's temporal upscaler rebuilds + detail from earlier frames. At low resolutions and low frame rates, fast + camera moves (driving, turning quickly) leave visible trails. +- **Higher needs more video memory.** At 1.0 the title's targets are at full + size on top of the 1.5 GB set aside for memory compares. On an 8 GB card, + stay at 720p or lower if 1080p crashes. +- Series S cannot go above 1080p: its output is 1080p, and the script says so + and stops if asked for more. + +`-Resolution` works on `play-nvidia.ps1` itself too +(`-Resolution 720 -SeriesX`), and `-More @{VICTORY_RENDER_SCALE='0.6'}` still +sets any scale from 0.2 to 1.0. + Before the first run, ahead of time (both can be stopped and go on later): ```powershell diff --git a/scripts/play-S-1080p.ps1 b/scripts/play-S-1080p.ps1 new file mode 100644 index 0000000..ed3f961 --- /dev/null +++ b/scripts/play-S-1080p.ps1 @@ -0,0 +1,3 @@ +# Series S, rendering at 1080p (then the title's own upscaler). +# scripts\play-S-1080p.ps1 -Exe <path of your own copy's executable> [other play-nvidia.ps1 switches, e.g. -Quality] +& "$PSScriptRoot\play-nvidia.ps1" -Resolution 1080 @args diff --git a/scripts/play-S-480p.ps1 b/scripts/play-S-480p.ps1 new file mode 100644 index 0000000..5a3c6c4 --- /dev/null +++ b/scripts/play-S-480p.ps1 @@ -0,0 +1,3 @@ +# Series S, rendering at 480p (then the title's own upscaler). +# scripts\play-S-480p.ps1 -Exe <path of your own copy's executable> [other play-nvidia.ps1 switches, e.g. -Quality] +& "$PSScriptRoot\play-nvidia.ps1" -Resolution 480 @args diff --git a/scripts/play-S-540p.ps1 b/scripts/play-S-540p.ps1 new file mode 100644 index 0000000..92c8ec3 --- /dev/null +++ b/scripts/play-S-540p.ps1 @@ -0,0 +1,3 @@ +# Series S, rendering at 540p (then the title's own upscaler). +# scripts\play-S-540p.ps1 -Exe <path of your own copy's executable> [other play-nvidia.ps1 switches, e.g. -Quality] +& "$PSScriptRoot\play-nvidia.ps1" -Resolution 540 @args diff --git a/scripts/play-S-720p.ps1 b/scripts/play-S-720p.ps1 new file mode 100644 index 0000000..5b46a0c --- /dev/null +++ b/scripts/play-S-720p.ps1 @@ -0,0 +1,3 @@ +# Series S, rendering at 720p (then the title's own upscaler). +# scripts\play-S-720p.ps1 -Exe <path of your own copy's executable> [other play-nvidia.ps1 switches, e.g. -Quality] +& "$PSScriptRoot\play-nvidia.ps1" -Resolution 720 @args diff --git a/scripts/play-X-1080p.ps1 b/scripts/play-X-1080p.ps1 new file mode 100644 index 0000000..42f2d01 --- /dev/null +++ b/scripts/play-X-1080p.ps1 @@ -0,0 +1,3 @@ +# Series X, rendering at 1080p (then the title's own upscaler). +# scripts\play-X-1080p.ps1 -Exe <path of your own copy's executable> [other play-nvidia.ps1 switches, e.g. -Quality] +& "$PSScriptRoot\play-nvidia.ps1" -SeriesX -Resolution 1080 @args diff --git a/scripts/play-X-1440p.ps1 b/scripts/play-X-1440p.ps1 new file mode 100644 index 0000000..6ac3b13 --- /dev/null +++ b/scripts/play-X-1440p.ps1 @@ -0,0 +1,3 @@ +# Series X, rendering at 1440p (then the title's own upscaler). +# scripts\play-X-1440p.ps1 -Exe <path of your own copy's executable> [other play-nvidia.ps1 switches, e.g. -Quality] +& "$PSScriptRoot\play-nvidia.ps1" -SeriesX -Resolution 1440 @args diff --git a/scripts/play-X-2160p.ps1 b/scripts/play-X-2160p.ps1 new file mode 100644 index 0000000..92281d2 --- /dev/null +++ b/scripts/play-X-2160p.ps1 @@ -0,0 +1,3 @@ +# Series X, rendering at 2160p (then the title's own upscaler). +# scripts\play-X-2160p.ps1 -Exe <path of your own copy's executable> [other play-nvidia.ps1 switches, e.g. -Quality] +& "$PSScriptRoot\play-nvidia.ps1" -SeriesX -Resolution 2160 @args diff --git a/scripts/play-X-480p.ps1 b/scripts/play-X-480p.ps1 new file mode 100644 index 0000000..471f573 --- /dev/null +++ b/scripts/play-X-480p.ps1 @@ -0,0 +1,3 @@ +# Series X, rendering at 480p (then the title's own upscaler). +# scripts\play-X-480p.ps1 -Exe <path of your own copy's executable> [other play-nvidia.ps1 switches, e.g. -Quality] +& "$PSScriptRoot\play-nvidia.ps1" -SeriesX -Resolution 480 @args diff --git a/scripts/play-X-540p.ps1 b/scripts/play-X-540p.ps1 new file mode 100644 index 0000000..df3c50b --- /dev/null +++ b/scripts/play-X-540p.ps1 @@ -0,0 +1,3 @@ +# Series X, rendering at 540p (then the title's own upscaler). +# scripts\play-X-540p.ps1 -Exe <path of your own copy's executable> [other play-nvidia.ps1 switches, e.g. -Quality] +& "$PSScriptRoot\play-nvidia.ps1" -SeriesX -Resolution 540 @args diff --git a/scripts/play-X-720p.ps1 b/scripts/play-X-720p.ps1 new file mode 100644 index 0000000..88f60f8 --- /dev/null +++ b/scripts/play-X-720p.ps1 @@ -0,0 +1,3 @@ +# Series X, rendering at 720p (then the title's own upscaler). +# scripts\play-X-720p.ps1 -Exe <path of your own copy's executable> [other play-nvidia.ps1 switches, e.g. -Quality] +& "$PSScriptRoot\play-nvidia.ps1" -SeriesX -Resolution 720 @args diff --git a/scripts/play-nvidia.ps1 b/scripts/play-nvidia.ps1 index f0b559a..32ebc6b 100644 --- a/scripts/play-nvidia.ps1 +++ b/scripts/play-nvidia.ps1 @@ -5,6 +5,9 @@ # -SeriesX the Series X profile instead (slower: about 7 fps at half scale) # -Quality fewer stretched/jumping bodies and less rainbow skin, at about 13 fps instead of about 20 # -RayTracing keep the title's ray-tracing passes (off by default: see below) +# -Resolution the height the game renders at before the title's own upscaler: 2160, 1440, 1080, 720, 540 or 480. +# Series S outputs 1080p (so up to 1080 there), Series X 2160p. Default: half the output (540 on S, +# 1080 on X). The play-S-*.ps1 and play-X-*.ps1 scripts next to this one call it with each. # -Build target\diag (the default, the build all measurements are of) or target\release # (the release build ignores the ray-tracing skip list: VICTORY_SKIP_PIPELINES is a diagnostics switch) # -More other settings: -More @{VICTORY_PANEL='1'} @@ -15,6 +18,7 @@ param( [switch]$SeriesX, [switch]$Quality, [switch]$RayTracing, + [ValidateSet('2160', '1440', '1080', '720', '540', '480')][string]$Resolution, [ValidateSet('diag', 'release')][string]$Build = 'diag', [hashtable]$More = @{} ) @@ -63,7 +67,19 @@ if ($Quality) { # Costs about 7 fps (the submitting thread waits about 30 ms a frame for the card). $settings.VICTORY_RELAY = '1'; $settings.VICTORY_CARD_STEPS = '0'; $settings.VICTORY_TEXTURE_NO_WAIT = '0' } +# The render scale is the rendered height over the output height (Series S 1080, Series X 2160). +$outHeight = if ($SeriesX) { 2160 } else { 1080 } +$console = if ($SeriesX) { 'X' } else { 'S' } +if ($Resolution) { + if ([int]$Resolution -gt $outHeight) { + Write-Host "Series $console outputs ${outHeight}p: ${Resolution}p is above it." + return + } + $settings.VICTORY_RENDER_SCALE = ([int]$Resolution / $outHeight).ToString('0.####', [Globalization.CultureInfo]::InvariantCulture) +} foreach ($k in $More.Keys) { $settings[$k] = $More[$k] } +$scale = [double]::Parse($settings.VICTORY_RENDER_SCALE, [Globalization.CultureInfo]::InvariantCulture) +Write-Host "Series $console, rendering at $([int]($outHeight * $scale))p (render scale $($settings.VICTORY_RENDER_SCALE))" $victory = Join-Path $PSScriptRoot "..\target\$Build\victory.exe" if (-not (Test-Path $victory)) { Write-Host "No $victory. Build it first (README.md)."; return } From 033be27f336e395745667df5fe20160e375209ca Mon Sep 17 00:00:00 2001 From: trustno1-coder <361337194+trustno1-coder@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:41:22 -0800 Subject: [PATCH 432/445] Pick the card (VICTORY_ADAPTER); RTX 5060 Ti results; Series S 1080p crashes - host.rs: VICTORY_ADAPTER=<part of a card's name, or #index> creates the host device on that card instead of Windows' default; the log names the card, or lists the cards when nothing matches. play-nvidia.ps1 -Adapter. - README: RTX 5060 Ti 16 GB vs RTX 5070 12 GB on the same PC, same build and settings (Series S 540p): 14.9 vs 19.3 fps. The GPU work is close; the 5060 Ti's slot is PCIe 4.0 x4 with no display, and this layer's copies dominate. - README: Series S at 1080p (render scale 1.0) stops at a breakpoint at start on a 12 GB card too, so it is not video memory; use 720p or lower. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 32 ++++++++++++++++++++--- crates/victory-gpu/src/host.rs | 48 ++++++++++++++++++++++++++++++++++ scripts/play-nvidia.ps1 | 4 +++ 3 files changed, 80 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8d981f8..2ad8090 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,8 @@ Also in, off by default: - F9 frame capture (`capture.rs`): with `VICTORY_CAPTURE=<folder>` and `VICTORY_DUMP_TARGETS=1`, F9 saves the next frame's picture, its commands and every 2D target. +- `VICTORY_ADAPTER=<part of a card's name, or #index>` (`host.rs`): the card to + run on when there is more than one (`play-nvidia.ps1 -Adapter`). --- @@ -258,7 +260,7 @@ subtitles stay sharp either way. Series S outputs 1920x1080 and Series X | Script | Console | World drawn at | Render scale | Tested on the RTX 5070 | |---|---|---|---|---| -| `play-S-1080p.ps1` | Series S | 1920x1080 | 1.0 | not yet (one report of a crash on an RTX 2080 8 GB) | +| `play-S-1080p.ps1` | Series S | 1920x1080 | 1.0 | **crashes at start** (the title stops at a breakpoint; also reported on an RTX 2080) | | `play-S-720p.ps1` | Series S | 1280x720 | 0.667 | not yet | | `play-S-540p.ps1` | Series S | 960x540 | 0.5 | yes: the default, about 18-22 fps | | `play-S-480p.ps1` | Series S | 853x480 | 0.444 | not yet | @@ -283,12 +285,34 @@ What to expect: - **Lower is softer and smears more.** The title's temporal upscaler rebuilds detail from earlier frames. At low resolutions and low frame rates, fast camera moves (driving, turning quickly) leave visible trails. -- **Higher needs more video memory.** At 1.0 the title's targets are at full - size on top of the 1.5 GB set aside for memory compares. On an 8 GB card, - stay at 720p or lower if 1080p crashes. +- **Series S at 1080p (render scale 1.0) does not work yet.** The title stops + at a breakpoint as soon as it starts, on a 12 GB card too, so it is not video + memory. Use 720p or lower on Series S. - Series S cannot go above 1080p: its output is 1080p, and the script says so and stops if asked for more. +### More than one card, and other cards + +On a PC with two cards, `-Adapter` picks one by part of its name or its index +(`-Adapter 5060`, `-Adapter '#1'`); it sets `VICTORY_ADAPTER`, and the log says +which card the game is on. Without it the game uses Windows' default card, the +one the main display is on. + +Measured on the same PC (Ryzen 7 9800X3D), same build and settings +(`play-S-540p`, the default), one run each in the prison prologue: + +| Card | Slot it sits in | fps | Preparing a frame (CPU) | On the GPU | +|---|---|---|---|---| +| RTX 5070 12 GB | PCIe 5.0 x16, drives the display | 19.3 | 34 ms | 4.6 ms | +| RTX 5060 Ti 16 GB | PCIe 4.0 x4, no display attached | 14.9 | 50 ms | 5.4 ms | + +The GPU work itself is close; the gap is in preparing frames, mostly copies of +title memory to and from the card. This layer moves tens of MB a frame, so the +link to the card matters: the 5060 Ti here has about an eighth of the 5070's +bandwidth, and its finished frames are also copied to the 5070 to be shown. +In a full-speed slot with the display on it, a 5060 Ti should land closer to +the 5070. Neither run lost the device; both refused the same 7 programs. + `-Resolution` works on `play-nvidia.ps1` itself too (`-Resolution 720 -SeriesX`), and `-More @{VICTORY_RENDER_SCALE='0.6'}` still sets any scale from 0.2 to 1.0. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 763cefb..71cde63 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -884,6 +884,9 @@ fn create() -> windows::core::Result<Host> { let adapter = warp_adapter()?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; tracing::info!("host device on the software adapter (WARP)"); + } else if let Some(adapter) = chosen_adapter() { + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; + crate::tdr::log(); } else { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; // Whether a GPU hang ends the run or freezes the PC (#1054). @@ -982,6 +985,51 @@ impl Host { /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). /// Reject it before creating a device in diagnostics' software-only mode. +/// LOCAL: the card `VICTORY_ADAPTER` names, for a PC with more than one. +/// The value is part of the card's name, any case (`5060`, `RTX 5070`), or +/// its index in DXGI's order (`#1`). Unset: Windows' default card. A value +/// that matches no hardware card is logged with the list and ignored. +fn chosen_adapter() -> Option<IDXGIAdapter1> { + let want = std::env::var("VICTORY_ADAPTER").ok()?; + let want = want.trim(); + if want.is_empty() { + return None; + } + // SAFETY: plain DXGI adapter queries. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let index = want.strip_prefix('#').and_then(|n| n.parse::<u32>().ok()); + let mut seen = Vec::new(); + for i in 0.. { + let Ok(adapter) = factory.EnumAdapters1(i) else { break }; + let Ok(desc) = adapter.GetDesc1() else { continue }; + let len = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); + let name = String::from_utf16_lossy(&desc.Description[..len]); + let software = desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0; + let hit = match index { + Some(n) => n == i, + None => name.to_lowercase().contains(&want.to_lowercase()), + }; + if hit && !software { + tracing::warn!( + adapter = %name, + index = i, + memory_mb = desc.DedicatedVideoMemory / (1024 * 1024), + "host device on the card VICTORY_ADAPTER names" + ); + return Some(adapter); + } + seen.push(format!("#{i} {name}")); + } + tracing::warn!( + want, + cards = %seen.join(", "), + "VICTORY_ADAPTER names no hardware card; Windows' default card is used" + ); + None + } +} + pub(crate) fn warp_adapter() -> windows::core::Result<IDXGIAdapter> { // SAFETY: plain DXGI adapter queries. unsafe { diff --git a/scripts/play-nvidia.ps1 b/scripts/play-nvidia.ps1 index 32ebc6b..277b845 100644 --- a/scripts/play-nvidia.ps1 +++ b/scripts/play-nvidia.ps1 @@ -8,6 +8,8 @@ # -Resolution the height the game renders at before the title's own upscaler: 2160, 1440, 1080, 720, 540 or 480. # Series S outputs 1080p (so up to 1080 there), Series X 2160p. Default: half the output (540 on S, # 1080 on X). The play-S-*.ps1 and play-X-*.ps1 scripts next to this one call it with each. +# -Adapter on a PC with more than one card, the one to use: part of its name (-Adapter 5060) or its index +# (-Adapter '#1'). Default: Windows' default card (the one the main display is on). # -Build target\diag (the default, the build all measurements are of) or target\release # (the release build ignores the ray-tracing skip list: VICTORY_SKIP_PIPELINES is a diagnostics switch) # -More other settings: -More @{VICTORY_PANEL='1'} @@ -19,6 +21,7 @@ param( [switch]$Quality, [switch]$RayTracing, [ValidateSet('2160', '1440', '1080', '720', '540', '480')][string]$Resolution, + [string]$Adapter, [ValidateSet('diag', 'release')][string]$Build = 'diag', [hashtable]$More = @{} ) @@ -77,6 +80,7 @@ if ($Resolution) { } $settings.VICTORY_RENDER_SCALE = ([int]$Resolution / $outHeight).ToString('0.####', [Globalization.CultureInfo]::InvariantCulture) } +if ($Adapter) { $settings.VICTORY_ADAPTER = $Adapter } foreach ($k in $More.Keys) { $settings[$k] = $More[$k] } $scale = [double]::Parse($settings.VICTORY_RENDER_SCALE, [Globalization.CultureInfo]::InvariantCulture) Write-Host "Series $console, rendering at $([int]($outHeight * $scale))p (render scale $($settings.VICTORY_RENDER_SCALE))" From d1fe0bd0151a5f17574dab750e6e684494818d01 Mon Sep 17 00:00:00 2001 From: Jeremy Goldberg <goldberg.jeremy02@gmail.com> Date: Thu, 26 Nov 2026 01:11:05 -0500 Subject: [PATCH 433/445] fix(gpu): submit buffer comparisons after state decay Submit the comparison list separately before signaling the fence so implicitly promoted title buffers can decay to COMMON. This fixes D3D12 error 538. --- crates/victory-gpu/src/host.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 71cde63..9bdf299 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -5649,9 +5649,10 @@ impl Host { for (shadow, at, bytes) in batch.placed.drain(..) { shadow.placed_copy(at, &bytes); } - if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) { - lists.push(Some(check)); - } + // A title list can leave a buffer promoted to COPY_DEST. Buffers + // decay to COMMON between ExecuteCommandLists calls, so submit + // the compare separately before signalling this submission's fence. + let check = card.as_ref().and_then(|c| c.check.clone()).map(|list| [Some(list)]); #[cfg(feature = "diagnostics")] split.part(4); stage.next("submit: waiting for the heaps' records"); @@ -5690,6 +5691,9 @@ impl Host { self.queue.ExecuteCommandLists(&lists[from..to]); from = to; } + if let Some(check) = &check { + self.queue.ExecuteCommandLists(check); + } self.queue.Signal(&self.fence, *submitted) }; awake::sent(&self.device); @@ -5743,6 +5747,9 @@ impl Host { // SAFETY: closed lists; the fence and event are ours. unsafe { self.queue.ExecuteCommandLists(group); + if i + 1 == groups.len() && let Some(check) = &check { + self.queue.ExecuteCommandLists(check); + } self.card_sent(); let waited = self .queue @@ -5762,8 +5769,7 @@ impl Host { Err(e) => tracing::warn!(error = %e, "host submission not waited for"), } } - // With timing on each group is one of `runs` (and the compare - // of copies in the card's memory, with the last): every + // With timing on each group is one of `runs`: every // command's time on the card goes to the sums by pipeline. #[cfg(feature = "diagnostics")] if timing() { From c05b44b34a52a22092e3fddcbd1d2e850561d61b Mon Sep 17 00:00:00 2001 From: Jeremy Goldberg <goldberg.jeremy02@gmail.com> Date: Thu, 26 Nov 2026 01:11:05 -0500 Subject: [PATCH 434/445] fix(gpu): bind ambient depth only to a matching SRV Only the resolve pass uses depth. Require the correct descriptor type and matching dimensions to prevent D3D12 error 646. --- crates/victory-gpu/src/ambient.rs | 6 ++++-- crates/victory-gpu/src/draw.rs | 30 ++++++++++++++++++++---------- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs index 326b6ef..a714aa2 100644 --- a/crates/victory-gpu/src/ambient.rs +++ b/crates/victory-gpu/src/ambient.rs @@ -430,7 +430,7 @@ 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, + pub(crate) depth: Option<D3D12_GPU_DESCRIPTOR_HANDLE>, /// The size of the image, and how many slices it has. pub(crate) size: [u32; 2], pub(crate) slices: u32, @@ -484,7 +484,9 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { uav_barrier(l); l.SetComputeRootSignature(&pass.root); l.SetComputeRoot32BitConstants(0, 12, words.as_ptr().cast(), 0); - l.SetComputeRootDescriptorTable(1, views.depth); + if let Some(depth) = views.depth { + l.SetComputeRootDescriptorTable(1, depth); + } l.SetComputeRootDescriptorTable(2, views.image); l.SetComputeRootUnorderedAccessView(3, pass.cells.GetGPUVirtualAddress()); l.SetComputeRootUnorderedAccessView(4, pass.points.GetGPUVirtualAddress()); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 19e3cc9..567e472 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2735,8 +2735,9 @@ impl State { 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, + let resource = match (kind, crate::descriptor::view(table + u64::from(offset) * 4)?) { + (ResourceType::Srv, View::Shader(r, _)) + | (ResourceType::Uav, View::Unordered(r, ..)) => r, _ => return None, }; let start = match self.ambient_tables.iter().find(|m| m.0 == slot) { @@ -2753,19 +2754,28 @@ impl State { Role::Radiance => RADIANCE, Role::Air => AIR, }; - let image = entry(ResourceType::Uav, at); - let depth = match role { - Role::Resolve => entry(ResourceType::Srv, DEPTH), - 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"); + let Some((of, image)) = entry(ResourceType::Uav, at) else { + once!(?role, "no stand-in for the indirect light: missing image UAV"); return false; }; + let depth = match role { + Role::Resolve => { + let Some((seen, depth)) = entry(ResourceType::Srv, DEPTH) else { + once!(?role, "no stand-in for the indirect light: missing depth SRV"); + return false; + }; + if (seen.Width, seen.Height) != (of.Width, of.Height) { + once!(?role, "no stand-in for the indirect light: depth dimensions differ"); + return false; + } + Some(depth) + } + Role::Radiance | Role::Air => None, + }; // (R32_UINT holding R9G9B9E5; R11G11B10_FLOAT.) let format = if role == Role::Resolve { 42 } else { 26 }; 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) { + if of.Format.0 != format || volume != (role == Role::Air) { once!(?role, format = of.Format.0, "no stand-in for the indirect light: another image"); return false; } From fdc8bbc5667074440fe3baaa42fb61eb37a082bc Mon Sep 17 00:00:00 2001 From: Jeremy Goldberg <goldberg.jeremy02@gmail.com> Date: Thu, 26 Nov 2026 09:44:27 -0500 Subject: [PATCH 435/445] fix(gpu): include buffer comparisons in GPU timings Keep diagnostic end markers after the comparison while retaining its separate queue call and the existing fence. Refs: #1 --- crates/victory-gpu/src/host.rs | 39 +++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 9bdf299..8ddee02 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -5652,7 +5652,12 @@ impl Host { // A title list can leave a buffer promoted to COPY_DEST. Buffers // decay to COMMON between ExecuteCommandLists calls, so submit // the compare separately before signalling this submission's fence. - let check = card.as_ref().and_then(|c| c.check.clone()).map(|list| [Some(list)]); + // Keep it in the list array so the timing end markers follow it. + let compare_at = card.as_ref().and_then(|c| c.check.clone()).map(|list| { + let at = lists.len(); + lists.push(Some(list)); + at + }); #[cfg(feature = "diagnostics")] split.part(4); stage.next("submit: waiting for the heaps' records"); @@ -5668,21 +5673,28 @@ impl Host { #[cfg(feature = "diagnostics")] let stamp = stamps::take(); #[cfg(feature = "diagnostics")] - if let Some((ahead, behind)) = stamp.and_then(stamps::lists) { + let compare_at = if let Some((ahead, behind)) = stamp.and_then(stamps::lists) { lists.insert(0, Some(ahead)); lists.push(Some(behind)); firsts.iter_mut().for_each(|first| *first += 1); - } + compare_at.map(|at| at + 1) + } else { + compare_at + }; #[cfg(feature = "diagnostics")] let sending = crate::timeline::ticks(); if late { *submitted += 1; #[cfg(feature = "diagnostics")] - if let Some([front, behind]) = self.span_lists() { + let compare_at = 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); - } + compare_at.map(|at| at + 1) + } else { + compare_at + }; + let (lists, compare) = lists.split_at(compare_at.unwrap_or(lists.len())); let cuts: Vec<usize> = parts.iter().filter_map(|&n| firsts.get(n).copied()).collect(); // SAFETY: closed lists; the fence is ours. let signalled = unsafe { @@ -5691,8 +5703,8 @@ impl Host { self.queue.ExecuteCommandLists(&lists[from..to]); from = to; } - if let Some(check) = &check { - self.queue.ExecuteCommandLists(check); + if !compare.is_empty() { + self.queue.ExecuteCommandLists(compare); } self.queue.Signal(&self.fence, *submitted) }; @@ -5727,19 +5739,22 @@ impl Host { working(was_working); return Some((submitted, sent)); } + let (lists, compare) = lists.split_at(compare_at.unwrap_or(lists.len())); // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`). #[cfg(feature = "diagnostics")] let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() { firsts .iter() + .enumerate() .zip(firsts.iter().skip(1).chain([&lists.len()])) - .map(|(&a, &b)| &lists[a..b]) + // Include any leading timeline marker in the first timed group. + .map(|((i, &a), &b)| &lists[if i == 0 { 0 } else { a }..b]) .collect() } else { - vec![&lists[..]] + vec![lists] }; #[cfg(not(feature = "diagnostics"))] - let groups = [&lists[..]]; + let groups = [lists]; submitting(2, runs.len()); for (i, group) in groups.iter().enumerate() { *submitted += 1; @@ -5747,8 +5762,8 @@ impl Host { // SAFETY: closed lists; the fence and event are ours. unsafe { self.queue.ExecuteCommandLists(group); - if i + 1 == groups.len() && let Some(check) = &check { - self.queue.ExecuteCommandLists(check); + if i + 1 == groups.len() && !compare.is_empty() { + self.queue.ExecuteCommandLists(compare); } self.card_sent(); let waited = self From f110b5775b4992487164a53f5009d76d593e09e9 Mon Sep 17 00:00:00 2001 From: Jeremy Goldberg <goldberg.jeremy02@gmail.com> Date: Thu, 26 Nov 2026 10:17:31 -0500 Subject: [PATCH 436/445] feat(diagnostics): load matching paired Wave32 shaders Allow local paired compute bytecode on the supported Wave32 host when the normal translation confirms that the shader bindings match. Keep the normal translator and cache as the fallback. --- crates/victory-gpu/src/shader_cache.rs | 43 +++++++++++++++++++++++++- docs/README-fxceless.md | 1 + 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index c395e19..00e3777 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -121,10 +121,51 @@ pub fn precompile(container: &[u8]) -> Result<bool, String> { /// there is one. pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> { let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); - match CACHE.get() { + let shader = match CACHE.get() { Some(cache) => cached(cache, &build(), container, translate), None => translate(container), + }?; + #[cfg(feature = "diagnostics")] + let shader = paired_override(container, shader); + Ok(shader) +} + +/// Try cache entries made by the paired-wave translator for the 32-lane, +/// one-million-descriptor host. The normal translation remains our source +/// of binding metadata and remains in the translation cache. +#[cfg(feature = "diagnostics")] +fn paired_override(container: &[u8], mut shader: HostShader) -> HostShader { + static DIR: OnceLock<Option<PathBuf>> = OnceLock::new(); + let Some(dir) = DIR.get_or_init(|| std::env::var_os("VICTORY_PAIRED_SHADER_DIR").map(PathBuf::from)) else { + return shader; + }; + if shader.stage != HwStage::Cs || victory_shader::emit::host_settings() != [32, 999_999, 0, 0] { + return shader; } + let digest = blake3::hash(container).to_hex(); + let hash = &digest[..16]; + let path = dir.join(format!("{hash}.vsh")); + let mut bytes = match std::fs::read(&path) { + Ok(bytes) => bytes, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return shader, + Err(e) => { + tracing::warn!(hash, error = %e, "could not read paired shader"); + return shader; + } + }; + // Paired VSH1 entries predate the half-view list. These programs have + // none. The equality check includes the list on our side. + bytes.extend_from_slice(&0u32.to_le_bytes()); + if let Some(mut paired) = decode(&bytes) { + let dxil = std::mem::replace(&mut paired.dxil, shader.dxil.clone()); + if paired == shader && dxil.starts_with(b"DXBC") { + shader.dxil = dxil; + tracing::info!(hash, "using paired Wave32 bytecode with matching shader bindings"); + return shader; + } + } + tracing::warn!(hash, "paired shader entry did not match the translated shader bindings"); + shader } /// The cache entry's converter: the build and the container in, the diff --git a/docs/README-fxceless.md b/docs/README-fxceless.md index 44885da..62a5cdf 100644 --- a/docs/README-fxceless.md +++ b/docs/README-fxceless.md @@ -316,6 +316,7 @@ The on/off switches below (`...=1`) are off when unset or set to `0`. | `VICTORY_CRASH_SAVE=<rva>:<len>,...` | saves title memory to the cache folder on a crash | | `VICTORY_CAPTURE=<dir>` | saves presented frames (powers of two, or `VICTORY_CAPTURE_FRAMES=<list>`) | | `VICTORY_DUMP_TARGETS=1` | with the two above, saves every render target of those frames | +| `VICTORY_PAIRED_SHADER_DIR=<dir>` | opt-in local paired-translator VSH1 compute shaders for 32-lane hosts with a 1,000,000-slot view heap. Loads `<16-digit-shader-hash>.vsh` only when its bindings match the normal translation. Missing or incompatible entries use the normal translation. With `play-nvidia.ps1`, pass the directory through `-More @{VICTORY_PAIRED_SHADER_DIR = 'C:\path\to\paired'}`. | | `VICTORY_D3D12_DEBUG=1` | host debug layer | | `VICTORY_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) | | `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | From b8fcd99b98b00a98a60d654f4591161e15558754 Mon Sep 17 00:00:00 2001 From: Local Test <test@local> Date: Thu, 26 Nov 2026 16:50:08 +0100 Subject: [PATCH 437/445] feat(diagnostics): report descriptor view table usage by kind Add a per-kind breakdown to the periodic descriptor memory log. Report occupied and free table slots and their flat memory footprint for all six view kinds (constant buffer, shader resource, unordered access, sampler, console sampler, placed memory). Free slots retain their last occupant's kind until reuse. Both the existing summary and the new breakdown come from one read of the table, in one pass over `list` plus one over `free`, with no extra lock acquisition and no temporary allocation sized by the table. Two isolated tests (their own local table, no shared state, no raw pointers, no unsafe code) verify the counts, byte attribution, and cross-kind reuse: that a freed slot reused for a different kind moves its count from the old kind's total to the new kind's without affecting the table's overall size. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> --- crates/victory-gpu/src/copystat.rs | 21 ++- crates/victory-gpu/src/descriptor.rs | 252 +++++++++++++++++++++++++-- 2 files changed, 262 insertions(+), 11 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 3bbb9dd..a7e559a 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -857,7 +857,7 @@ fn log_memory() { // code has allocated. let alive: Vec<u64> = crate::host::ALIVE.iter().map(|a| a.load(Relaxed)).collect(); let window = crate::shadow::window_use(); - let views = crate::descriptor::views_kept(); + let (views, views_by_kind) = crate::descriptor::views_kept(); let own: Vec<u64> = (0..8).map(owned).collect(); tracing::info!( "memory, what holds it: {} host lists alive; their scratch memory: {} chunks {:.0} MB, of them {} chunks {:.0} MB spare ({} taken from the spare ones so far); their other upload buffers: {} alive {:.0} MB; windows outside buffers (grid {} KiB): {:.0} MB of their pages ever copied, {} shown by descriptor slots {:.0} MB, {} held by lists or the pass over the heap {:.0} MB, {} asked for without a length {:.0} MB; buffer views of the heap whose slot showed another copy than the one brought up to date: {}; distinct views kept: {} ({} free) {:.0} MB; our own allocations: {:.0} MB in {} blocks (under 4 KiB {:.0} MB in {}, to 64 KiB {:.0} MB in {}, to 1 MiB {:.0} MB in {}, larger {:.0} MB in {})", @@ -919,6 +919,25 @@ fn log_memory() { mb(kept[6]), big_blocks(), ); + // The view table's entries by kind: how many of each are occupied + // versus on the free list now (a freed one, by what it last held), and + // that kind's flat share of bytes (one list slot each -- this does NOT + // include index/shapes' own tree overhead or spare Vec capacity, which + // the estimate above folds in undivided on top of the same flat share; + // by_resource's own memory is in neither number, and never was -- see + // `descriptor::kept`'s doc comment for the full scope of what this + // breakdown does and does not attribute). + tracing::info!( + "memory, view table by kind (occupied+free, flat MB -- not the whole byte estimate \ + above): constant {}+{} {:.0} MB, shader {}+{} {:.0} MB, unordered {}+{} {:.0} MB, \ + sampler {}+{} {:.0} MB, console sampler {}+{} {:.0} MB, placed {}+{} {:.0} MB", + views_by_kind[0][0], views_by_kind[0][1], mb(views_by_kind[0][2]), + views_by_kind[1][0], views_by_kind[1][1], mb(views_by_kind[1][2]), + views_by_kind[2][0], views_by_kind[2][1], mb(views_by_kind[2][2]), + views_by_kind[3][0], views_by_kind[3][1], mb(views_by_kind[3][2]), + views_by_kind[4][0], views_by_kind[4][1], mb(views_by_kind[4][2]), + views_by_kind[5][0], views_by_kind[5][1], mb(views_by_kind[5][2]), + ); // Round 3: whether windows hold the same memory more than once (they // can, once they are cut finer than 4 MiB), and how many host lists // the title made and never used. diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 26d44d8..57474d4 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -1058,6 +1058,40 @@ fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> { VIEWS.write().unwrap_or_else(|e| e.into_inner()) } +/// Which of six kinds [`kept`] counts a view under: [`KIND_CONSTANT`], +/// [`KIND_SHADER`], [`KIND_UNORDERED`], [`KIND_SAMPLER`], +/// [`KIND_CONSOLE_SAMPLER`], [`KIND_PLACED`]. Plain indices, not an enum, so +/// the breakdown can be a plain array. +/// +/// Gated the same as [`kept`]/[`views_kept`], their only callers (besides +/// the tests that check them directly): with `diagnostics` off, nothing +/// else in the file would use these, which `-D warnings` turns into a hard +/// error, not just a warning, in configurations that enable it. +#[cfg(all(windows, feature = "diagnostics"))] +const KIND_CONSTANT: usize = 0; +#[cfg(all(windows, feature = "diagnostics"))] +const KIND_SHADER: usize = 1; +#[cfg(all(windows, feature = "diagnostics"))] +const KIND_UNORDERED: usize = 2; +#[cfg(all(windows, feature = "diagnostics"))] +const KIND_SAMPLER: usize = 3; +#[cfg(all(windows, feature = "diagnostics"))] +const KIND_CONSOLE_SAMPLER: usize = 4; +#[cfg(all(windows, feature = "diagnostics"))] +const KIND_PLACED: usize = 5; + +#[cfg(all(windows, feature = "diagnostics"))] +fn kind_index(view: &View) -> usize { + match view { + View::Constant(..) => KIND_CONSTANT, + View::Shader(..) => KIND_SHADER, + View::Unordered(..) => KIND_UNORDERED, + View::Sampler(..) => KIND_SAMPLER, + View::ConsoleSampler(..) => KIND_CONSOLE_SAMPLER, + View::Placed(..) => KIND_PLACED, + } +} + /// For the memory line: the distinct views kept ([`Views`]), those of them /// free for reuse, and the bytes the table and its index hold for them (an /// estimate: an entry of the table, and one of the index with its share of @@ -1066,21 +1100,73 @@ fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> { /// record, or all of them with `VICTORY_VIEW_INLINE=0`), the shapes of /// placed views kept, and the views named whole in their records since the /// start: constant buffer views, views of placed memory. +/// +/// The second element is the same table, by [`kind_index`]: for each of the +/// six `View` kinds, how many of its entries are occupied (named in +/// [`Views::index`] right now) versus sitting on [`Views::free`] (a freed +/// slot keeps its *last* occupant's kind — [`Views::entry`] only overwrites +/// `list[i].0` when the slot is reused — so a freed entry is counted by +/// what it last held, never by a "current" kind it no longer has), and that +/// kind's flat share of bytes: one `list` slot each, nothing more. That +/// share deliberately does **not** include: any spare `Vec` capacity beyond +/// `list.len()`, or `index`/`shapes`/`shape_index`'s own tree overhead — +/// none of those three are attributable to one kind, since the index does +/// not record which kind a key belongs to; **the first element's byte +/// estimate above folds those three in, undivided, on top of the same flat +/// per-entry share this breakdown also counts.** `by_resource`'s own +/// memory is not in either number — the first element's formula never +/// accounted for it either, so this breakdown is not omitting something +/// the original estimate had; neither number has ever included it. +/// Nothing the GPU/driver itself holds is in either number. **The six +/// kinds' third column does not sum to the first element's byte estimate +/// above, and is not meant to** — it answers "how many slots, of which +/// kind, and their flat share," not "where did every byte go." This +/// identifies which kinds hold entries; it says nothing about which +/// specific entries are still meaningful to the title, only how many there +/// are and whether the table itself still considers them occupied. +/// +/// One pass over `Views::list`, plus one over the normally much smaller +/// `Views::free` (no separate scan, no temporary allocation sized by +/// `list.len()`, no second lock acquisition) — the same order of work the +/// first element alone already did. [`crate::copystat::log_memory`] calls +/// this once and logs both parts; nothing on the write path +/// ([`Views::entry`], [`forget`], [`words_for`]) is touched. `log_memory` +/// itself runs no more than once every 5 seconds +/// (`Host`'s `self.logged.elapsed() >= Duration::from_secs(5)` gate in +/// `host.rs`) — not "every sixth line," which is a different, unrelated +/// cadence belonging to [`log_memory_map`](crate::copystat) alone. #[cfg(all(windows, feature = "diagnostics"))] -pub(crate) fn views_kept() -> [u64; 8] { +pub(crate) fn views_kept() -> ([u64; 8], [[u64; 3]; 6]) { + kept(&views_read()) +} + +/// The counting itself, taking `views` directly rather than through +/// [`views_read`]: a pure function of one snapshot, so a test can check its +/// arithmetic against a `Views` value it builds and owns, with no shared +/// state and nothing to race against (see `kind_breakdown_is_exact_for_a_\ +/// known_table` below). [`views_kept`] is the only real caller. +#[cfg(all(windows, feature = "diagnostics"))] +fn kept(views: &Views) -> ([u64; 8], [[u64; 3]; 6]) { use std::sync::atomic::Ordering::Relaxed; - let views = views_read(); let each = size_of::<(View, u32)>() as u64; let shape = size_of::<Shape>() as u64; - let (mut constants, mut placed) = (0, 0); + // Pass 1, over `list`: every kind's total (occupied and free alike). + let mut by_kind = [[0u64; 3]; 6]; for (view, _) in &views.list { - match view { - View::Constant(..) => constants += 1, - View::Placed(..) => placed += 1, - _ => {} - } + let k = kind_index(view); + by_kind[k][0] += 1; + by_kind[k][2] += each; } - [ + // Pass 2, over the normally much smaller `free`: move each freed + // index's count from "occupied" to "free" within its own kind. + for &i in &views.free { + let k = kind_index(&views.list[i as usize].0); + by_kind[k][0] -= 1; + by_kind[k][1] += 1; + } + let constants = by_kind[KIND_CONSTANT][0] + by_kind[KIND_CONSTANT][1]; + let placed = by_kind[KIND_PLACED][0] + by_kind[KIND_PLACED][1]; + let summary = [ views.list.len() as u64, views.free.len() as u64, views.list.capacity() as u64 * each @@ -1092,7 +1178,8 @@ pub(crate) fn views_kept() -> [u64; 8] { views.shapes.len() as u64, NAMED_WHOLE[0].load(Relaxed), NAMED_WHOLE[1].load(Relaxed), - ] + ]; + (summary, by_kind) } impl View { @@ -1892,4 +1979,149 @@ mod tests { assert_eq!(create(desc, Placement { address, size: 7 }, &mut h), S_OK); assert_ne!(slot::<extern "system" fn(This) -> u64>(h, 0x48)(h), address); } + + // --- Memory-validation pass (MEMORY_VALIDATION.md): the two tests below + // check [`kept`]'s per-kind counting arithmetic -- the contribution's + // own scope, per a later review round that narrowed it to exactly this. + // Both build and own a local `Views` value; neither touches the real, + // shared `VIEWS` static, a raw pointer, or any unsafe code, so neither + // can race another test or any hot-path call, and both need + // `feature = "diagnostics"` to exist at all (the same gate `kept` + // itself has). Earlier revisions of this pass also carried tests that + // validated specific `MEMORY_DEEP_RESEARCH.md` §1.5 hypotheses + // (`Sampler`/`ConsoleSampler`/overflow-`Constant` entries being + // unreachable by `forget`; distinct descriptions of one live resource + // accumulating) and a timing benchmark -- removed from this + // contribution after a review found real soundness issues in them (an + // undefined-behavior `transmute` of a partially-initialized struct, + // writes through pointers derived from `as_ptr()` rather than + // `as_mut_ptr()`, and a race on `Views::free`'s exact membership + // between dropping one lock and taking another, under this file's + // real parallel test execution). Those findings were already reached + // and recorded honestly in `MEMORY_VALIDATION.md` before their tests + // existed; removing the tests does not retract the findings, only the + // since-judged-unnecessary extra surface of carrying them as committed, + // unsafe-code-adjacent tests for a contribution scoped to the + // breakdown's own counters. See `MEMORY_VALIDATION.md`'s "Update, + // round 3" for the full reasoning. + + /// [`kept`]'s per-kind arithmetic, checked against a `Views` value this + /// test builds and owns — no shared state, nothing to race against. + /// Three `Shader` entries (one on the free list), one `Sampler`, two + /// `Placed`, and one freed slot whose last occupant was a `Constant` + /// (freed slots keep their last view's word until reused, so they are + /// still classified by it — see [`kept`]'s doc comment). + #[cfg(all(windows, feature = "diagnostics"))] + #[test] + fn kind_breakdown_is_exact_for_a_known_table() { + let list = vec![ + (View::Shader(1, None), 1), + (View::Shader(2, None), 1), + (View::Shader(3, None), 1), // index 2: on the free list below + (View::Sampler([0; 13]), 1), + (View::Placed(false, [0; 14], [0; 16]), 1), + (View::Placed(true, [1; 14], [1; 16]), 1), + (View::Constant(0x1000, 256), 2), // index 6: on the free list below + ]; + let free = vec![6, 2]; + let views = Views { + list, + index: Default::default(), + by_resource: Default::default(), + free, + shapes: Vec::new(), + shape_index: Default::default(), + }; + let (summary, by_kind) = kept(&views); + let each = size_of::<(View, u32)>() as u64; + assert_eq!(by_kind[KIND_CONSTANT], [0, 1, each], "Constant: none occupied, one freed"); + assert_eq!(by_kind[KIND_SHADER], [2, 1, 3 * each], "Shader: two occupied, one freed"); + assert_eq!(by_kind[KIND_UNORDERED], [0, 0, 0], "Unordered: none at all"); + assert_eq!(by_kind[KIND_SAMPLER], [1, 0, each], "Sampler: one occupied, none freed"); + assert_eq!(by_kind[KIND_CONSOLE_SAMPLER], [0, 0, 0], "ConsoleSampler: none at all"); + assert_eq!(by_kind[KIND_PLACED], [2, 0, 2 * each], "Placed: two occupied, none freed"); + // The breakdown must account for every entry exactly once: this is + // the property that would catch a kind miscounted or double-counted + // if this test's per-kind numbers above were ever wrong together. + let (total_occupied, total_free): (u64, u64) = + by_kind.iter().fold((0, 0), |(o, f), k| (o + k[0], f + k[1])); + assert_eq!(total_occupied + total_free, views.list.len() as u64); + assert_eq!(total_free, views.free.len() as u64); + // Cross-checked against the existing summary's own Constant/Placed + // totals (occupied + free, same definition `kept` always used). + assert_eq!(summary[0], views.list.len() as u64); + assert_eq!(summary[1], views.free.len() as u64); + assert_eq!(summary[3], by_kind[KIND_CONSTANT][0] + by_kind[KIND_CONSTANT][1], "constants"); + assert_eq!(summary[4], by_kind[KIND_PLACED][0] + by_kind[KIND_PLACED][1], "placed"); + } + + /// A second, isolated fixture (its own `Views`, no shared state), + /// requested after an independent review of the first one noted it + /// left `index` empty despite having "occupied" entries, and checked + /// `Unordered`/`ConsoleSampler` only at zero. This one gives every one + /// of the six kinds a real occupied entry (not just a zero case), then + /// exercises the exact property the now-removed "a kind's entry count + /// never shrinks" assertion got wrong: reusing a freed index for a + /// *different* kind — exactly what [`Views::entry`]'s `free.pop()` + /// path does, overwriting `list[i].0` in place — moves one unit from + /// the old kind's total to the new kind's, with nothing actually + /// removed from the table as a whole. + #[cfg(all(windows, feature = "diagnostics"))] + #[test] + fn kind_breakdown_covers_all_six_kinds_and_cross_kind_recycling() { + let each = size_of::<(View, u32)>() as u64; + // One occupied entry of every kind; nothing free yet. + let before = Views { + list: vec![ + (View::Shader(0x9_1000, None), 1), // index 0: recycled below + (View::Unordered(0x9_2000, 0, None), 1), // index 1 + (View::Sampler([7; 13]), 1), // index 2 + (View::ConsoleSampler([8; 27]), 1), // index 3 + (View::Placed(false, [0; 14], [0; 16]), 1), // index 4: freed below + (View::Constant(0x9_3000, 256), 1), // index 5 + ], + index: Default::default(), + by_resource: Default::default(), + free: Vec::new(), + shapes: Vec::new(), + shape_index: Default::default(), + }; + let (_, before_kind) = kept(&before); + for (k, name) in [ + (KIND_CONSTANT, "Constant"), + (KIND_SHADER, "Shader"), + (KIND_UNORDERED, "Unordered"), + (KIND_SAMPLER, "Sampler"), + (KIND_CONSOLE_SAMPLER, "ConsoleSampler"), + (KIND_PLACED, "Placed"), + ] { + assert_eq!(before_kind[k], [1, 0, each], "{name}: exactly one occupied entry, none free"); + } + + // Index 0 (a Shader) is recycled for an Unordered view -- the same + // in-place overwrite `Views::entry`'s `free.pop()` branch performs + // (`self.list[i as usize].0 = view.clone()`) -- and index 4 (the + // Placed entry) is freed and left that way. + let before_len = before.list.len(); + let mut after = before; + after.list[0] = (View::Unordered(0x9_4000, 0, None), 2); + after.free = vec![4]; + let (_, after_kind) = kept(&after); + assert_eq!(after_kind[KIND_SHADER], [0, 0, 0], "Shader's only entry is gone -- recycled into a different kind, not freed as Shader"); + assert_eq!(after_kind[KIND_UNORDERED], [2, 0, 2 * each], "Unordered now holds its own entry plus the recycled one"); + assert_eq!(after_kind[KIND_PLACED], [0, 1, each], "Placed's one entry is now on the free list, still counted as Placed"); + // The two kinds untouched by either change are exactly unchanged. + assert_eq!(after_kind[KIND_SAMPLER], before_kind[KIND_SAMPLER]); + assert_eq!(after_kind[KIND_CONSOLE_SAMPLER], before_kind[KIND_CONSOLE_SAMPLER]); + assert_eq!(after_kind[KIND_CONSTANT], before_kind[KIND_CONSTANT]); + // The property the removed assertion got wrong, stated directly: + // Shader's total (occupied + free) dropped from 1 to 0 even though + // nothing was freed FOR Shader -- its slot was recycled away + // entirely into a different kind. A real "nothing shrinks" check + // only holds for `list.len()` as a whole (unchanged here, 6 either + // way), never for one kind's own total. + let shader_total = |k: &[[u64; 3]; 6]| k[KIND_SHADER][0] + k[KIND_SHADER][1]; + assert!(shader_total(&after_kind) < shader_total(&before_kind)); + assert_eq!(before_len, after.list.len(), "list.len() itself is unaffected by recycling"); + } } From 2d1dc3826f331007a3b4ee0d89cecaa73695816e Mon Sep 17 00:00:00 2001 From: Indy2l <muas2109@gmail.com> Date: Thu, 26 Nov 2026 17:14:15 +0100 Subject: [PATCH 438/445] Texture read-backs: written by a thread of their own; landing timing split "read-backs and lists" in the landing line is split into texture read-backs, buffer read-backs and the flights' card plans and own work. On a 16 GB machine with an RTX 3060 (Series S, 540p) the texture part stood at 1-2 ms a frame, and at 124-416 ms in the frames where the world streamed: texback::land waits for the lock against mapping changes (watch::title_memory_reading), which the title changes all the time then, and the landing of every submission waited with it. The landing thread now only copies a read-back's texels out of its buffer; waiting for the locks, tiling and writing into title memory go to a thread of their own, which writes only the newest of several copies of one allocation (the title reads the frame before at most). VICTORY_TEXBACK_ASYNC=0 writes them where they land, as before. A new line gives the writer's waits and work per frame. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- crates/victory-gpu/src/host.rs | 9 ++ crates/victory-gpu/src/land.rs | 40 ++++++- crates/victory-gpu/src/texback.rs | 167 +++++++++++++++++++++++++----- 3 files changed, 188 insertions(+), 28 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 9bdf299..07c976e 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3837,12 +3837,18 @@ pub(crate) fn walls_trace() -> bool { /// without it, so the title read a buffer nobody wrote, as before read-backs /// were made (the exposure metering's two small float targets, every frame). fn read_backs(list: &HostList) { + use crate::land::{count, spent, stat}; + let started = std::time::Instant::now(); // Textures shaders wrote that the title reads on the CPU // ([`crate::texback`]). for back in &list.deferred().texture_backs { crate::texback::land(back); + count(stat::RB_TEXTURE_COUNT, 1); } + let textures_done = spent(stat::RB_TEXTURES, started); for (buffer, at, [row, rows, pitch]) in &list.deferred().backs { + count(stat::RB_BUFFER_COUNT, 1); + count(stat::RB_BUFFER_BYTES, (*row * *rows) as u64); let mut data = std::ptr::null_mut(); // SAFETY: a read-back buffer of ours, written by the list that has // run; the title's destination holds every row (checked when the @@ -3870,6 +3876,7 @@ fn read_backs(list: &HostList) { } } } + spent(stat::RB_BUFFERS, textures_done); } /// After the card ran what declared `back`: what shaders wrote there goes @@ -4904,12 +4911,14 @@ impl Host { for &i in &flight.order { read_backs(flight.lists[i].host()); } + let done_from = std::time::Instant::now(); if let Some(card) = flight.card { self.card_done(card); } if let Some(own) = flight.own { own.landed(); } + crate::land::spent(crate::land::stat::RB_DONE, done_from); landed.push((flight.lists, flight.order)); crate::land::spent(crate::land::stat::READ_BACKS, telling) } diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 2bde585..2197db3 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -115,7 +115,26 @@ pub(crate) mod stat { pub(crate) const HAD_BYTES: usize = 24; /// Jobs. pub(crate) const JOBS: usize = 25; - pub(crate) const COUNT: usize = 26; + /// Parts of [`READ_BACKS`]: textures shaders wrote that the title reads + /// (`texback::land`), buffer read-backs (map and copy into title memory), + /// and the flight's card plan and own work told done. + pub(crate) const RB_TEXTURES: usize = 26; + pub(crate) const RB_BUFFERS: usize = 27; + pub(crate) const RB_DONE: usize = 28; + /// Counts for those: texture read-backs landed, buffer read-backs and + /// their bytes. + pub(crate) const RB_TEXTURE_COUNT: usize = 29; + pub(crate) const RB_BUFFER_COUNT: usize = 30; + pub(crate) const RB_BUFFER_BYTES: usize = 31; + /// Writing texture read-backs into title memory (`texback::write`, on + /// its own thread unless `VICTORY_TEXBACK_ASYNC=0`): waiting for the + /// locks against mapping changes, the work after, read-backs written, + /// and those replaced by a newer one before they were. + pub(crate) const TB_WAIT: usize = 32; + pub(crate) const TB_WORK: usize = 33; + pub(crate) const TB_WRITTEN: usize = 34; + pub(crate) const TB_REPLACED: usize = 35; + pub(crate) const COUNT: usize = 36; } static STATS: [AtomicU64; stat::COUNT] = [const { AtomicU64::new(0) }; stat::COUNT]; @@ -172,6 +191,25 @@ pub(crate) fn log(frames: f64) { ms(stat::TOLD), ms(stat::REST), ); + tracing::info!( + "read-backs and lists per frame: textures shaders wrote {:.2} ms ({:.1} landed), buffer read-backs {:.2} ms \ + ({:.1} of them, {:.2} MB), card plans and own work done {:.2} ms", + ms(stat::RB_TEXTURES), + s[stat::RB_TEXTURE_COUNT], + ms(stat::RB_BUFFERS), + s[stat::RB_BUFFER_COUNT], + mb(s[stat::RB_BUFFER_BYTES]), + ms(stat::RB_DONE), + ); + tracing::info!( + "texture read-backs written per frame (VICTORY_TEXBACK_ASYNC={}): {:.1}, {:.1} replaced by a newer one first; \ + waiting for the mapping locks {:.2} ms, tiling and writing {:.2} ms", + u8::from(std::env::var_os("VICTORY_TEXBACK_ASYNC").is_none_or(|v| v != "0")), + s[stat::TB_WRITTEN], + s[stat::TB_REPLACED], + ms(stat::TB_WAIT), + ms(stat::TB_WORK), + ); tracing::info!( "landed per frame: {:.0} pieces, {:.0} with a new byte; of their {:.0} pages of 4 KiB {:.0} with a new byte ({:.1} MB), \ {:.1} MB in blocks of 32 bytes with one, {:.2} MB put as dwords; {:.0} pieces through a view of ours \ diff --git a/crates/victory-gpu/src/texback.rs b/crates/victory-gpu/src/texback.rs index cf7b0e3..36e5d6b 100644 --- a/crates/victory-gpu/src/texback.rs +++ b/crates/victory-gpu/src/texback.rs @@ -197,57 +197,170 @@ pub(crate) fn record(list: &ID3D12GraphicsCommandList, target: Target) -> Option Some(Back { buffer, footprints, rows, mips, layout: target.layout, ticket: target.ticket }) } -/// Once the list has run, tile its texels back into the same title allocation. +/// Whether texture read-backs are written into title memory by a thread of +/// their own (`VICTORY_TEXBACK_ASYNC`; on unless `0`). +/// +/// Writing one takes the lock against mapping changes +/// ([`crate::watch::title_memory_reading`]), and while the title streams the +/// world it changes mappings all the time: on the thread that lands +/// submissions the wait for that lock stood 100-400 ms in some frames +/// (run 5 of the 16 GB machine, RTX 3060: "textures shaders wrote" in the +/// read-backs line, two to ten 350 KB water maps a frame), and with it the +/// landing of everything else. Here the landing thread only copies the +/// texels out of the read-back buffer; the waiting, tiling and writing go to +/// [`writer`]. Of several copies of one texture waiting there only the newest +/// is written: the title reads the frame before at most, which it may on the +/// console too. +fn asynchronous() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXBACK_ASYNC").is_none_or(|v| v != "0")) +} + +/// A read-back's texels taken out of its buffer, to be tiled into title memory. +struct Landing { + footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>, + rows: Vec<u32>, + mips: u32, + layout: victory_formats::texture::Layout, + ticket: Arc<Ticket>, + /// The read-back buffer's bytes, from 0 to the end of its last subresource. + data: Vec<u8>, +} + +/// Once the list has run, tile its texels back into the same title allocation +/// (on [`writer`]'s thread when [`asynchronous`]). pub(crate) fn land(back: &Back) { - static COPIED: AtomicU64 = AtomicU64::new(0); - static STALE: AtomicU64 = AtomicU64::new(0); - let _mapping = crate::watch::title_memory_reading(); - let _ticket_guard = TICKETS.lock().unwrap_or_else(|e| e.into_inner()); if !back.ticket.valid.load(Ordering::Acquire) { - let skipped = STALE.fetch_add(1, Ordering::Relaxed) + 1; - if skipped.is_power_of_two() { - tracing::info!(skipped, "skipping texture readbacks whose title allocation changed"); - } + stale(); return; } - let (at, end) = back.range(); + let len = back + .footprints + .iter() + .zip(&back.rows) + .map(|(f, &rows)| f.Offset as usize + f.Footprint.RowPitch as usize * rows as usize * f.Footprint.Depth as usize) + .max() + .unwrap_or(0); + let mut mapped = std::ptr::null_mut(); + // SAFETY: our read-back buffer, written by the list that has run; `len` + // ends with its last subresource, which it holds. + let data = unsafe { + if back.buffer.Map(0, None, Some(&mut mapped)).is_err() || mapped.is_null() { + return; + } + let data = std::slice::from_raw_parts(mapped.cast::<u8>().cast_const(), len).to_vec(); + back.buffer.Unmap(0, None); + data + }; + let landing = Landing { + footprints: back.footprints.clone(), + rows: back.rows.clone(), + mips: back.mips, + layout: back.layout.clone(), + ticket: back.ticket.clone(), + data, + }; + match asynchronous().then(writer).flatten() { + Some(writer) => writer.send(landing), + None => write(&landing), + } +} + +fn stale() { + static STALE: AtomicU64 = AtomicU64::new(0); + let skipped = STALE.fetch_add(1, Ordering::Relaxed) + 1; + if skipped.is_power_of_two() { + tracing::info!(skipped, "skipping texture readbacks whose title allocation changed"); + } +} + +/// Tiles a read-back's texels into its title allocation. +fn write(landing: &Landing) { + use crate::land::{count, spent, stat}; + static COPIED: AtomicU64 = AtomicU64::new(0); + let asked = std::time::Instant::now(); + let _mapping = crate::watch::title_memory_reading(); + let _ticket_guard = TICKETS.lock().unwrap_or_else(|e| e.into_inner()); + let working = spent(stat::TB_WAIT, asked); + if !landing.ticket.valid.load(Ordering::Acquire) { + stale(); + return; + } + let (at, end) = (landing.ticket.at, landing.ticket.end); let size = end - at; let mut tiled = vec![0u8; size]; // Keep title bytes the subresources do not cover. if !crate::host::read_into(at as *const u8, &mut tiled) { return; } - let mut data = std::ptr::null_mut(); - // SAFETY: our read-back buffer, written by the list that has run. - unsafe { - if back.buffer.Map(0, None, Some(&mut data)).is_err() || data.is_null() { - return; - } - } - for (i, (footprint, &rows)) in back.footprints.iter().zip(&back.rows).enumerate() { - let (mip, slice) = (i as u32 % back.mips, i as u32 / back.mips); + for (i, (footprint, &rows)) in landing.footprints.iter().zip(&landing.rows).enumerate() { + let (mip, slice) = (i as u32 % landing.mips, i as u32 / landing.mips); let f = footprint.Footprint; let pitch = f.RowPitch as usize; - let len = pitch * rows as usize * f.Depth as usize; - // SAFETY: the subresource's part of the mapped buffer. - let linear = unsafe { std::slice::from_raw_parts(data.cast::<u8>().add(footprint.Offset as usize), len) }; - if let Err(e) = back.layout.tile(&mut tiled, mip, slice, linear, pitch, pitch * rows as usize) { + let from = footprint.Offset as usize; + let linear = &landing.data[from..from + pitch * rows as usize * f.Depth as usize]; + if let Err(e) = landing.layout.tile(&mut tiled, mip, slice, linear, pitch, pitch * rows as usize) { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| tracing::warn!(?e, mip, slice, "a texture copied back could not be tiled")); - // SAFETY: mapped above. - unsafe { back.buffer.Unmap(0, None) }; return; } } - // SAFETY: mapped above. - unsafe { back.buffer.Unmap(0, None) }; crate::host::copy_mapped(at as *mut u8, tiled.as_ptr(), size, true); + spent(stat::TB_WORK, working); + count(stat::TB_WRITTEN, 1); let copied = COPIED.fetch_add(1, Ordering::Relaxed) + 1; if copied == 1 || copied.is_multiple_of(128) { tracing::info!(copied, bytes = size, "texture readback landed"); } } +/// The thread that writes read-backs into title memory, and what waits for it. +struct Writer { + /// By title address: the newest landing for that allocation. + waiting: Mutex<std::collections::HashMap<usize, Landing>>, + more: std::sync::Condvar, +} + +impl Writer { + fn send(&self, landing: Landing) { + let mut waiting = self.waiting.lock().unwrap_or_else(|e| e.into_inner()); + if waiting.insert(landing.ticket.at, landing).is_some() { + crate::land::count(crate::land::stat::TB_REPLACED, 1); + } + drop(waiting); + self.more.notify_one(); + } +} + +/// The writer, if its thread could be started (if not, landings are written +/// where they are made, as before). +fn writer() -> Option<&'static Writer> { + static WRITER: OnceLock<Option<&'static Writer>> = OnceLock::new(); + *WRITER.get_or_init(|| { + let writer: &'static Writer = + Box::leak(Box::new(Writer { waiting: Mutex::new(std::collections::HashMap::new()), more: std::sync::Condvar::new() })); + let started = std::thread::Builder::new().name("texture read-backs".into()).spawn(move || loop { + let batch: Vec<Landing> = { + let mut waiting = writer.waiting.lock().unwrap_or_else(|e| e.into_inner()); + while waiting.is_empty() { + waiting = writer.more.wait(waiting).unwrap_or_else(|e| e.into_inner()); + } + waiting.drain().map(|(_, landing)| landing).collect() + }; + for landing in &batch { + write(landing); + } + }); + match started { + Ok(_) => Some(writer), + Err(e) => { + tracing::warn!(error = %e, "no thread for texture read-backs: they are written where they land"); + None + } + } + }) +} + #[cfg(test)] mod tests { From cda4987aa4331f44a4a9d7511a72184be6208935 Mon Sep 17 00:00:00 2001 From: Indy2l <muas2109@gmail.com> Date: Thu, 26 Nov 2026 17:52:23 +0100 Subject: [PATCH 439/445] fix(scripts): windows in card memory the CPU maps, for 16 GB PCs On a PC with 16 GB of RAM (RTX 3060 12 GB, i5-12400F, Series S at 540p) every run with play-nvidia.ps1 ended a minute or so into the world: the card's shared memory (the PC's, capped by Windows at half the RAM) reached 7.5 GB, a host list failed to close or be made with 0x8007000E, and the driver faulted in CopyTextureRegion. About two thirds of that memory were the windows of title memory outside buffers. VICTORY_WINDOWS_BAR_MB=3072 puts them in card memory the CPU maps (D3D12_HEAP_TYPE_GPU_UPLOAD) while the card has room. Same machine: no crash in 5+ minute runs, shared memory flat at about 4.4 GB, 10-12 fps in the world instead of 1.6-3. Without a resizable BAR, mapped_card_buffer returns None and windows stay where they were. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- README.md | 8 ++++++++ scripts/play-nvidia.ps1 | 6 ++++++ 2 files changed, 14 insertions(+) diff --git a/README.md b/README.md index 2ad8090..62e049c 100644 --- a/README.md +++ b/README.md @@ -290,6 +290,14 @@ What to expect: memory. Use 720p or lower on Series S. - Series S cannot go above 1080p: its output is 1080p, and the script says so and stops if asked for more. +- **16 GB of RAM works, with a resizable BAR.** Windows lets a card share at + most half the PC's memory, and the copies of title memory the GPU reads + filled that on a 16 GB PC about a minute into the world (`0x8007000E`, then a + driver fault). `play-nvidia.ps1` now puts them in the card's memory the CPU + maps (`VICTORY_WINDOWS_BAR_MB`) when the BIOS has resizable BAR on; + `nvidia-smi -q -d MEMORY` shows a BAR1 total about the card's size if so. + Without it, close what else uses memory. Expect stutters while the world + streams in: the game's own memory is then partly in the paging file. ### More than one card, and other cards diff --git a/scripts/play-nvidia.ps1 b/scripts/play-nvidia.ps1 index 277b845..74419d2 100644 --- a/scripts/play-nvidia.ps1 +++ b/scripts/play-nvidia.ps1 @@ -54,6 +54,12 @@ $settings = @{ VICTORY_CARD_BUFFERS_MIN_MB = '1'; VICTORY_CARD_BUFFERS_MB = '1536' # Series S presents the interface as a second plane: laid over the game (compose.rs), else black before gameplay. VICTORY_COMPOSE = '1' + # Windows of title memory outside buffers in card memory the CPU maps (resizable BAR), up to 3 GB, while the + # card has room (shadow.rs window_mapped_for). Otherwise they live in the PC's memory shared with the card, + # which Windows caps at half the RAM: on a 16 GB PC (RTX 3060) the shared memory reached 7.5 GB about a minute + # into the world and every run ended in 0x8007000E, then a fault in the driver. With this: no crash, the shared + # memory flat at about 4.4 GB, 10-12 fps instead of 2-3. Without a resizable BAR it changes nothing. + VICTORY_WINDOWS_BAR_MB = '3072' } # Ray tracing mostly off. The structure builder cannot run on NVIDIA (its 64-lane programs are refused; upstream # Marvisak/VIctory pull request 2311), so every ray misses, and the passes that turn misses into light made rooms go From 1b0fd752a5b8c13f6bf53ce14f9b54a574494b70 Mon Sep 17 00:00:00 2001 From: Jeremy Goldberg <goldberg.jeremy02@gmail.com> Date: Thu, 26 Nov 2026 12:40:48 -0500 Subject: [PATCH 440/445] fix(scripts): make the NVIDIA BAR window cap opt-in Expose the cap in MiB as a launcher parameter and keep the existing More override. Restore the runtime default for launches that omit the cap. Refs: #6 --- README.md | 16 ++++++++-------- scripts/play-nvidia.ps1 | 13 ++++++------- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 62e049c..42f4787 100644 --- a/README.md +++ b/README.md @@ -290,14 +290,14 @@ What to expect: memory. Use 720p or lower on Series S. - Series S cannot go above 1080p: its output is 1080p, and the script says so and stops if asked for more. -- **16 GB of RAM works, with a resizable BAR.** Windows lets a card share at - most half the PC's memory, and the copies of title memory the GPU reads - filled that on a 16 GB PC about a minute into the world (`0x8007000E`, then a - driver fault). `play-nvidia.ps1` now puts them in the card's memory the CPU - maps (`VICTORY_WINDOWS_BAR_MB`) when the BIOS has resizable BAR on; - `nvidia-smi -q -d MEMORY` shows a BAR1 total about the card's size if so. - Without it, close what else uses memory. Expect stutters while the world - streams in: the game's own memory is then partly in the paging file. +- **On 16 GB PCs, try `-WindowsBarMB 3072` with resizable BAR enabled.** + On the tested 16 GB PC with an RTX 3060, shared GPU memory approached its + limit about a minute into the world (`0x8007000E`, then a driver fault). + The 3072 MiB cap from [PR #6](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/6) + let eligible title memory windows use CPU-mapped VRAM while the card had room. + The launcher leaves this off by default. Pass a cap in MiB to + `play-nvidia.ps1` or any resolution wrapper. `-WindowsBarMB 0` disables it, + and `-More @{VICTORY_WINDOWS_BAR_MB='...'}` takes precedence. ### More than one card, and other cards diff --git a/scripts/play-nvidia.ps1 b/scripts/play-nvidia.ps1 index 74419d2..ba79f40 100644 --- a/scripts/play-nvidia.ps1 +++ b/scripts/play-nvidia.ps1 @@ -12,6 +12,7 @@ # (-Adapter '#1'). Default: Windows' default card (the one the main display is on). # -Build target\diag (the default, the build all measurements are of) or target\release # (the release build ignores the ray-tracing skip list: VICTORY_SKIP_PIPELINES is a diagnostics switch) +# -WindowsBarMB maximum MiB of title memory windows in CPU-mapped VRAM (0 by default). # -More other settings: -More @{VICTORY_PANEL='1'} # Run it from a normal window, not as administrator: the driver then keeps its shader cache elsewhere. param( @@ -23,7 +24,8 @@ param( [ValidateSet('2160', '1440', '1080', '720', '540', '480')][string]$Resolution, [string]$Adapter, [ValidateSet('diag', 'release')][string]$Build = 'diag', - [hashtable]$More = @{} + [hashtable]$More = @{}, + [uint32]$WindowsBarMB ) $settings = @{ # This fork's play set (scripts\play.ps1, not -Safe): the speed set. @@ -54,12 +56,6 @@ $settings = @{ VICTORY_CARD_BUFFERS_MIN_MB = '1'; VICTORY_CARD_BUFFERS_MB = '1536' # Series S presents the interface as a second plane: laid over the game (compose.rs), else black before gameplay. VICTORY_COMPOSE = '1' - # Windows of title memory outside buffers in card memory the CPU maps (resizable BAR), up to 3 GB, while the - # card has room (shadow.rs window_mapped_for). Otherwise they live in the PC's memory shared with the card, - # which Windows caps at half the RAM: on a 16 GB PC (RTX 3060) the shared memory reached 7.5 GB about a minute - # into the world and every run ended in 0x8007000E, then a fault in the driver. With this: no crash, the shared - # memory flat at about 4.4 GB, 10-12 fps instead of 2-3. Without a resizable BAR it changes nothing. - VICTORY_WINDOWS_BAR_MB = '3072' } # Ray tracing mostly off. The structure builder cannot run on NVIDIA (its 64-lane programs are refused; upstream # Marvisak/VIctory pull request 2311), so every ray misses, and the passes that turn misses into light made rooms go @@ -87,6 +83,9 @@ if ($Resolution) { $settings.VICTORY_RENDER_SCALE = ([int]$Resolution / $outHeight).ToString('0.####', [Globalization.CultureInfo]::InvariantCulture) } if ($Adapter) { $settings.VICTORY_ADAPTER = $Adapter } +if ($PSBoundParameters.ContainsKey('WindowsBarMB')) { + $settings.VICTORY_WINDOWS_BAR_MB = $WindowsBarMB.ToString([Globalization.CultureInfo]::InvariantCulture) +} foreach ($k in $More.Keys) { $settings[$k] = $More[$k] } $scale = [double]::Parse($settings.VICTORY_RENDER_SCALE, [Globalization.CultureInfo]::InvariantCulture) Write-Host "Series $console, rendering at $([int]($outHeight * $scale))p (render scale $($settings.VICTORY_RENDER_SCALE))" From 85a529b61a8e825810cc39ec1db1e80ca5329759 Mon Sep 17 00:00:00 2001 From: trustno1-coder <361337194+trustno1-coder@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:57:50 -0800 Subject: [PATCH 441/445] play-nvidia.ps1: windows BAR cap on by itself under 24 GB of RAM PR #8 made VICTORY_WINDOWS_BAR_MB opt-in (-WindowsBarMB). Without the switch, a 16 GB PC was back to the 0x8007000E crash about a minute into the world that PR #6 fixed: Windows lets the card share at most half the RAM, and the windows fill that. Now, when -WindowsBarMB is not given, PCs with under 24 GB of RAM get 3072 and larger ones keep the runtime default (off). -WindowsBarMB (0 included) and -More still decide when given; if the RAM can't be read, nothing is set. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 10 ++++++---- scripts/play-nvidia.ps1 | 12 +++++++++++- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 42f4787..53a6c1c 100644 --- a/README.md +++ b/README.md @@ -290,14 +290,16 @@ What to expect: memory. Use 720p or lower on Series S. - Series S cannot go above 1080p: its output is 1080p, and the script says so and stops if asked for more. -- **On 16 GB PCs, try `-WindowsBarMB 3072` with resizable BAR enabled.** +- **16 GB PCs: turned on for you, best with resizable BAR enabled.** On the tested 16 GB PC with an RTX 3060, shared GPU memory approached its limit about a minute into the world (`0x8007000E`, then a driver fault). The 3072 MiB cap from [PR #6](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/6) let eligible title memory windows use CPU-mapped VRAM while the card had room. - The launcher leaves this off by default. Pass a cap in MiB to - `play-nvidia.ps1` or any resolution wrapper. `-WindowsBarMB 0` disables it, - and `-More @{VICTORY_WINDOWS_BAR_MB='...'}` takes precedence. + The launcher sets it by itself on PCs with under 24 GB of RAM (Windows lets + the card share half the RAM) and leaves it off on larger ones. Pass a cap in + MiB to `play-nvidia.ps1` or any resolution wrapper to choose for yourself: + `-WindowsBarMB 0` disables it, and `-More @{VICTORY_WINDOWS_BAR_MB='...'}` + takes precedence. ### More than one card, and other cards diff --git a/scripts/play-nvidia.ps1 b/scripts/play-nvidia.ps1 index ba79f40..3918918 100644 --- a/scripts/play-nvidia.ps1 +++ b/scripts/play-nvidia.ps1 @@ -12,7 +12,8 @@ # (-Adapter '#1'). Default: Windows' default card (the one the main display is on). # -Build target\diag (the default, the build all measurements are of) or target\release # (the release build ignores the ray-tracing skip list: VICTORY_SKIP_PIPELINES is a diagnostics switch) -# -WindowsBarMB maximum MiB of title memory windows in CPU-mapped VRAM (0 by default). +# -WindowsBarMB maximum MiB of title memory windows in CPU-mapped VRAM (by default 3072 on PCs with under +# 24 GB of RAM, else 0; -WindowsBarMB 0 turns it off). # -More other settings: -More @{VICTORY_PANEL='1'} # Run it from a normal window, not as administrator: the driver then keeps its shader cache elsewhere. param( @@ -85,6 +86,15 @@ if ($Resolution) { if ($Adapter) { $settings.VICTORY_ADAPTER = $Adapter } if ($PSBoundParameters.ContainsKey('WindowsBarMB')) { $settings.VICTORY_WINDOWS_BAR_MB = $WindowsBarMB.ToString([Globalization.CultureInfo]::InvariantCulture) +} else { + # Without -WindowsBarMB, PCs with under 24 GB of RAM get 3072 (PR #6). Windows lets a card share at most half + # the RAM, and the windows filled that on a 16 GB PC (RTX 3060) about a minute into the world (0x8007000E, then + # a driver fault). 32 GB and more never got there, so they keep the runtime default (0, off). + $ram = try { (Get-CimInstance Win32_ComputerSystem -ErrorAction Stop).TotalPhysicalMemory } catch { 0 } + if ($ram -gt 0 -and $ram -lt 24GB) { + $settings.VICTORY_WINDOWS_BAR_MB = '3072' + Write-Host "$([math]::Round($ram / 1GB)) GB of RAM: title memory windows in the card's memory the CPU maps, up to 3 GB (-WindowsBarMB 0 turns this off)" + } } foreach ($k in $More.Keys) { $settings[$k] = $More[$k] } $scale = [double]::Parse($settings.VICTORY_RENDER_SCALE, [Globalization.CultureInfo]::InvariantCulture) From 12b1d16d3b6b0c839f642c000c833a0666026027 Mon Sep 17 00:00:00 2001 From: superboynick <superboynick@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:35:46 +0800 Subject: [PATCH 442/445] HLE: a mouse device, so the camera follows the mouse GameInput in this layer offered four XInput pads, a stand-in pad driven by the keyboard, and the keyboard, but no mouse. The title polls GameInput for mouse movement, reads nothing, and never turns the camera while the keyboard works. The new device reports position deltas taken from the host cursor inside our own window and the three buttons. It exists only while our window is in the foreground and goes away with a disconnect callback when focus leaves, so moving the pointer elsewhere does not spin the camera. Wheel rotation is not reported: the host call used here cannot see it. `VICTORY_GAMEPAD_MOUSE=0` leaves the device out entirely, which is what the layer did before. Verified in a run: with the window in front the device appears (kind 0x20) and it does not appear while another window has focus. --- crates/victory-hle/Cargo.toml | 1 + crates/victory-hle/src/modules/gameinput.rs | 193 +++++++++++++++++--- 2 files changed, 172 insertions(+), 22 deletions(-) diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index d91f14f..6d86b03 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -20,6 +20,7 @@ tracing.workspace = true windows-sys = { workspace = true, features = [ "Win32_Foundation", "Win32_Globalization", + "Win32_Graphics_Gdi", "Win32_Media", "Win32_Security", "Win32_Security_Cryptography", diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index d0b0bf9..424c0ed 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1,7 +1,7 @@ //! `gameinput.dll`: input devices from the host. Gamepads come from XInput //! (host slots 0-3); while none is connected, the keyboard drives one //! stand-in gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own -//! too. A poll thread turns host state into readings (a new one per change) +//! too. A focused window also has a mouse. A poll thread records changes //! and runs device callbacks on connect and disconnect. #![allow(non_snake_case)] // Title code calls these through the objects, passing pointers the real API @@ -30,6 +30,7 @@ const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32; /// Input kinds (bits) our devices have. const KEYBOARD_KIND: u32 = 0x10; +const MOUSE_KIND: u32 = 0x20; const GAMEPAD_KIND: u32 = 0x4_0000; /// Device status of a connected device: connected, input enabled. const STATUS_CONNECTED: u32 = 0x3; @@ -51,11 +52,12 @@ const RIGHT_SHOULDER: u32 = 0x800; const LEFT_STICK: u32 = 0x1000; const RIGHT_STICK: u32 = 0x2000; -/// Devices: host pad slots, the keyboard's stand-in pad, the keyboard. +/// Devices: host pad slots, the keyboard's stand-in pad, keyboard and mouse. const PADS: usize = 4; const FALLBACK: usize = PADS; const KEYBOARD: usize = PADS + 1; -const DEVICES: usize = PADS + 2; +const MOUSE: usize = PADS + 2; +const DEVICES: usize = MOUSE + 1; /// Readings kept per device for next/previous lookups. const HISTORY: usize = 256; @@ -105,12 +107,46 @@ struct KeyState { const _: () = assert!(size_of::<KeyState>() == 12 && size_of::<PadState>() == 28); +/// GameInput v0 reports cumulative relative motion. Scroll axes stay at zero. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct MouseState { + buttons: u32, + position_x: i64, + position_y: i64, + wheel_x: i64, + wheel_y: i64, +} +const _: () = assert!(size_of::<MouseState>() == 40); + +/// The next cursor reference and the motion since the previous focused sample. +#[cfg(any(windows, test))] +fn mouse_delta( + previous: Option<(i32, i32)>, + position: Option<(i32, i32)>, + size: (i32, i32), +) -> (Option<(i32, i32)>, (i64, i64)) { + let current = position + .filter(|_| size.0 > 0 && size.1 > 0) + .map(|(x, y)| (x.clamp(0, size.0 - 1), y.clamp(0, size.1 - 1))); + let delta = match (previous, current) { + (Some((x, y)), Some((nx, ny))) => { + (i64::from(nx) - i64::from(x), i64::from(ny) - i64::from(y)) + } + _ => (0, 0), + }; + (current, delta) +} + /// Host input, or a fake in tests. trait Source: Send { /// The pad in host slot `slot`, `None` when the slot is empty. fn pad(&mut self, slot: usize) -> Option<PadState>; /// Keys held down; none while the title's window lacks focus. fn keys(&mut self) -> Vec<KeyState>; + fn mouse(&mut self) -> Option<MouseState> { + None + } /// Motor speeds: low frequency (left), high frequency (right). fn rumble(&mut self, slot: usize, low: u16, high: u16); } @@ -210,10 +246,10 @@ struct DeviceInfo { const _: () = assert!(std::mem::offset_of!(DeviceInfo, id) == 0x20); fn kind(index: usize) -> u32 { - if index == KEYBOARD { - KEYBOARD_KIND - } else { - GAMEPAD_KIND + match index { + KEYBOARD => KEYBOARD_KIND, + MOUSE => MOUSE_KIND, + _ => GAMEPAD_KIND, } } @@ -249,6 +285,7 @@ impl Device { enum Value { Pad(PadState), Keys(Vec<KeyState>), + Mouse(MouseState), } #[repr(C)] @@ -266,6 +303,7 @@ impl Reading { match self.value { Value::Pad(_) => GAMEPAD_KIND, Value::Keys(_) => KEYBOARD_KIND, + Value::Mouse(_) => MOUSE_KIND, } } } @@ -430,12 +468,14 @@ impl Hub { /// Reads the host once; device callbacks run on the calling thread. fn poll(&self) { - let (pads, keys) = { + let (pads, keys, mouse) = { let mut source = lock(&self.source); let pads: [_; PADS] = std::array::from_fn(|slot| source.pad(slot)); - (pads, source.keys()) + (pads, source.keys(), source.mouse()) }; - let events = self.state().poll(&self.devices, self.one_pad, pads, keys); + let events = self + .state() + .poll(&self.devices, self.one_pad, pads, keys, mouse); self.deliver(events); } @@ -481,9 +521,11 @@ impl State { one_pad: bool, pads: [Option<PadState>; PADS], keys: Vec<KeyState>, + mouse: Option<MouseState>, ) -> Vec<Event> { let now = now(); let mut events = std::mem::take(&mut self.pending); + self.update(devices, MOUSE, mouse.map(Value::Mouse), now, &mut events); if one_pad { let pad = pads.into_iter().flatten().fold(fallback(&keys), merged); self.update(devices, FALLBACK, Some(Value::Pad(pad)), now, &mut events); @@ -530,7 +572,10 @@ impl State { })); } if was != slot.connected { - tracing::info!(device = index, connected = !was, "input device"); + tracing::info!(device = index, kind = kind(index), connected = !was, "input device"); + if index == MOUSE && !slot.connected { + slot.history.clear(); + } let (current, previous) = if was { (0, STATUS_CONNECTED) } else { @@ -881,7 +926,10 @@ extern "system" fn find_by_id(this: This, id: *const [u8; 32], out: Out) -> HRES } // SAFETY: checked non-null; the title passes a device id. let id = unsafe { &*id }; - match hub(this).devices.iter().find(|d| d.info.id == *id) { + let hub = hub(this); + match hub.devices.iter().find(|d| { + d.info.id == *id && (d.index != MOUSE || hub.state().slots[MOUSE].connected) + }) { Some(device) => { // SAFETY: checked non-null. unsafe { out.write((device as *const Device).cast()) }; @@ -1044,7 +1092,7 @@ extern "system" fn reading_device(this: *const Reading, out: *mut *const Device) extern "system" fn key_count(this: *const Reading) -> u32 { match &reading(this).value { Value::Keys(keys) => keys.len() as u32, - Value::Pad(_) => 0, + _ => 0, } } extern "system" fn key_state(this: *const Reading, count: u32, out: *mut KeyState) -> u32 { @@ -1069,6 +1117,16 @@ extern "system" fn gamepad_state(this: *const Reading, out: *mut PadState) -> bo _ => false, } } +extern "system" fn mouse_state(this: *const Reading, out: *mut MouseState) -> bool { + match &reading(this).value { + Value::Mouse(state) if !out.is_null() => { + // SAFETY: the caller supplies room for the v0 state. + unsafe { out.write(*state) }; + true + } + _ => false, + } +} /// Kinds our devices do not have: no count, no state. extern "system" fn nothing(_: *const c_void) -> usize { 0 @@ -1091,7 +1149,7 @@ static READING: Table<25> = Table([ nothing as *const (), // 0x68 key_count as *const (), // 0x70 key_state as *const (), // 0x78 - nothing as *const (), // 0x80 mouse + mouse_state as *const (), // 0x80 mouse nothing as *const (), // 0x88 touch nothing as *const (), // 0x90 nothing as *const (), // 0x98 motion @@ -1114,14 +1172,16 @@ pub(crate) fn module() -> HleModule { } } -/// Host input: XInput pads, the keyboard while our process has focus. +/// Host input: XInput pads, and keyboard and mouse while our process has focus. #[cfg(windows)] mod host { use std::time::{Duration, Instant}; + use windows_sys::Win32::Foundation::{HWND, POINT, RECT}; + use windows_sys::Win32::Graphics::Gdi::ScreenToClient; use windows_sys::Win32::System::Threading::GetCurrentProcessId; use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ - GetAsyncKeyState, MAPVK_VK_TO_VSC_EX, MapVirtualKeyW, + GetAsyncKeyState, MAPVK_VK_TO_VSC_EX, MapVirtualKeyW, VK_LBUTTON, VK_MBUTTON, VK_RBUTTON, }; use windows_sys::Win32::UI::Input::XboxController::{ XINPUT_GAMEPAD, XINPUT_GAMEPAD_A, XINPUT_GAMEPAD_B, XINPUT_GAMEPAD_BACK, @@ -1132,7 +1192,7 @@ mod host { XInputSetState, }; use windows_sys::Win32::UI::WindowsAndMessaging::{ - GetForegroundWindow, GetWindowThreadProcessId, + GetClientRect, GetCursorPos, GetForegroundWindow, GetWindowThreadProcessId, }; use super::*; @@ -1177,6 +1237,8 @@ mod host { #[derive(Default)] pub(super) struct Host { empty_until: [Option<Instant>; PADS], + previous_cursor: Option<(i32, i32)>, + mouse: MouseState, } impl Source for Host { @@ -1213,7 +1275,7 @@ mod host { let mut down = scripted(); #[cfg(not(feature = "diagnostics"))] let mut down = Vec::new(); - if focused() { + if focused_window().is_some() { // Left/right modifier keys only, as devices report them; no // mouse buttons (below 0x08). let held: Vec<u8> = (0x08..=0xFE_u8) @@ -1235,6 +1297,42 @@ mod host { .collect() } + fn mouse(&mut self) -> Option<MouseState> { + static ENABLED: LazyLock<bool> = + LazyLock::new(|| std::env::var_os("VICTORY_GAMEPAD_MOUSE").is_none_or(|v| v != "0")); + if !*ENABLED { + return None; + } + let (mut point, mut rect) = (POINT::default(), RECT::default()); + let position = focused_window().and_then(|window| { + // SAFETY: all outputs are local and all coordinates use the same window. + let sampled = unsafe { + GetCursorPos(&mut point) != 0 + && ScreenToClient(window, &mut point) != 0 + && GetClientRect(window, &mut rect) != 0 + && GetForegroundWindow() == window + }; + sampled.then_some((point.x, point.y)) + }); + let (cursor, (dx, dy)) = + mouse_delta(self.previous_cursor, position, (rect.right, rect.bottom)); + self.previous_cursor = cursor; + if cursor.is_none() { + self.mouse = MouseState::default(); + return None; + } + self.mouse.position_x += dx; + self.mouse.position_y += dy; + self.mouse.buttons = 0; + for (bit, vk) in [VK_LBUTTON, VK_RBUTTON, VK_MBUTTON].into_iter().enumerate() { + // SAFETY: virtual-key state query. + if unsafe { GetAsyncKeyState(i32::from(vk)) } < 0 { + self.mouse.buttons |= 1 << bit; + } + } + Some(self.mouse) + } + fn rumble(&mut self, slot: usize, low: u16, high: u16) { let speeds = XINPUT_VIBRATION { wLeftMotorSpeed: low, @@ -1288,12 +1386,13 @@ mod host { } /// The foreground window is one of ours (the title's or our fallback). - fn focused() -> bool { + fn focused_window() -> Option<HWND> { let mut process = 0; // SAFETY: plain queries; a null window gives process 0. unsafe { - GetWindowThreadProcessId(GetForegroundWindow(), &mut process); - process == GetCurrentProcessId() + let window = GetForegroundWindow(); + GetWindowThreadProcessId(window, &mut process); + (process == GetCurrentProcessId()).then_some(window) } } @@ -1334,6 +1433,7 @@ mod tests { struct FakeHost { pads: [Option<PadState>; PADS], keys: Vec<KeyState>, + mouse: Option<MouseState>, rumble: Vec<(usize, u16, u16)>, } @@ -1346,6 +1446,9 @@ mod tests { fn keys(&mut self) -> Vec<KeyState> { self.0.lock().unwrap().keys.clone() } + fn mouse(&mut self) -> Option<MouseState> { + self.0.lock().unwrap().mouse + } fn rumble(&mut self, slot: usize, low: u16, high: u16) { self.0.lock().unwrap().rumble.push((slot, low, high)); } @@ -1480,6 +1583,52 @@ mod tests { assert_eq!(r.classify("GameInput.dll", &ImportSymbol::Ordinal(2)), None); } + #[test] + fn mouse_motion_clamps_to_client_and_resets_on_focus_loss() { + let mut previous = None; + for (point, delta) in [ + (Some((50, 40)), (0, 0)), + (Some((30, 10)), (-20, -30)), + (Some((200, -5)), (69, -10)), + (Some((201, -8)), (0, 0)), + (None, (0, 0)), + (Some((7, 9)), (0, 0)), + ] { + let (cursor, motion) = mouse_delta(previous, point, (100, 80)); + assert_eq!(motion, delta); + previous = cursor; + } + } + + #[test] + fn mouse_readings_and_callbacks_in_both_pad_modes() { + for one_pad in [false, true] { + let (hub, host) = fake_with(one_pad); + let log = Log::default(); + register(hub, MOUSE_KIND, 2, &log); + let sample = MouseState { + buttons: 5, + position_x: -3, + ..Default::default() + }; + host.lock().unwrap().mouse = Some(sample); + hub.poll(); + let r = current(hub, MOUSE_KIND, MOUSE).unwrap(); + let get = + slot::<extern "system" fn(*const Reading, *mut MouseState) -> bool, _>(r, 0x80); + let mut got = MouseState::default(); + assert!(get(r, &mut got)); + assert_eq!(got, sample); + release(r); + + host.lock().unwrap().mouse = None; + hub.poll(); + assert_eq!(current(hub, MOUSE_KIND, MOUSE), Err(DEVICE_DISCONNECTED)); + assert!(hub.state().slots[MOUSE].history.is_empty()); + assert_eq!(*log.lock().unwrap(), [(MOUSE, 3, 0), (MOUSE, 0, 3)]); + } + } + #[test] fn pads_connect_report_and_disconnect() { let (hub, host) = fake(); @@ -1585,7 +1734,7 @@ mod tests { assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]); let pad = |hub: &Hub| match &hub.state().slots[FALLBACK].history.back().unwrap().value { Value::Pad(p) => *p, - Value::Keys(_) => unreachable!(), + _ => unreachable!(), }; host.lock().unwrap().keys = vec![key(b'D')]; hub.poll(); From 5b36758982a248c4e6d12d1b2406503de7a37419 Mon Sep 17 00:00:00 2001 From: Local Test <test@local> Date: Fri, 27 Nov 2026 01:18:17 +0100 Subject: [PATCH 443/445] perf(resource): gate filler-twins statistics behind diagnostics texture_at's filler-twins tracking (PLACED_RAW, PLACED_TWINS, and the per-call block in texture_at that takes PLACED_RAW's own mutex and scans previously-seen raw descriptions at the same address) exists solely to feed placed_filler_twins(), whose only caller is copystat::log_memory -- itself compiled only with feature = "diagnostics". A build without that feature paid for the second mutex, the BTreeSet, and an O(seen-so-far) scan on every placed-texture lookup (hit or miss) with no consumer for the result. Gates PLACED_RAW, PLACED_TWINS, placed_filler_twins(), the `raw` binding, and the tracking block itself behind feature = "diagnostics". The functional cache (PLACED_TEXTURES) and its key (`key`, built from VICTORY_PLACED_FILLER the same way as before) are untouched -- this candidate never reads or writes PLACED_TEXTURES. Independently reviewed before implementing (see research/reviews/OPTIMIZATION_CANDIDATE_B_REVIEW.md): re-ran the existing experiments/optimization-validation/filler.rs equivalence tests myself (6/6 pass, both configs), confirmed the eliminated block has no path into the functional cache, confirmed no equivalent change exists upstream (checked ZJOU 477c395a directly -- it gates only the getter, not the producer -- and did a fresh PR search). Verified after implementing: cargo test --workspace --locked (27 result lines) and cargo test -p victory-gpu --features diagnostics --lib (381 tests) are byte-for-byte identical in pass/fail/ignored counts between this branch and an unpatched origin/main worktree. cargo clippy, both CI invocations (with and without --all-features), produce an identical error set to the same unpatched worktree (a pre-existing, unrelated victory-formats issue blocks the workspace-wide command in both). Does not implement candidate A (incremental VIEWS census) or the shapes segmentation candidate, per instruction. No game files used, no push, no PR. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> --- crates/victory-gpu/src/resource.rs | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 437e3ca..32ef56a 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -2932,19 +2932,25 @@ static PLACED_TEXTURES: std::sync::Mutex<std::collections::BTreeMap<(u64, [u32; std::sync::Mutex::new(std::collections::BTreeMap::new()); /// The placed textures asked for with filler words set, as asked -/// (address and description): for [`PLACED_TWINS`]. -#[cfg(windows)] +/// (address and description): for [`PLACED_TWINS`]. Diagnostics builds +/// only: nothing outside `copystat` (itself diagnostics-only) consumes +/// [`placed_filler_twins`], so a build without that feature carries +/// neither this set nor its own mutex, nor the per-call tracking in +/// [`texture_at`] that would otherwise take it on every placed-texture +/// lookup, hit or not. +#[cfg(all(windows, feature = "diagnostics"))] static PLACED_RAW: std::sync::Mutex<std::collections::BTreeSet<(u64, [u32; 14])>> = std::sync::Mutex::new(std::collections::BTreeSet::new()); /// Placed textures asked for a second time with other filler words in /// their description: each was a second resource and host copy before the -/// filler was left out of the key ([`texture_at`]). -#[cfg(windows)] +/// filler was left out of the key ([`texture_at`]). Diagnostics builds +/// only; see [`PLACED_RAW`]. +#[cfg(all(windows, feature = "diagnostics"))] static PLACED_TWINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// See [`PLACED_TWINS`]. -#[cfg(windows)] +#[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn placed_filler_twins() -> u64 { PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed) } @@ -3025,6 +3031,9 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> { // that fills at world entry. They are not part of what a texture is. // `VICTORY_PLACED_FILLER=1`: kept in the key, as before. static KEPT: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + // Only the diagnostics-only filler-twins tracking below reads `raw`; + // the functional cache key is `key` alone. + #[cfg(feature = "diagnostics")] let raw = *desc; let mut key = *desc; if !*KEPT.get_or_init(|| std::env::var_os("VICTORY_PLACED_FILLER").is_some_and(|v| v == "1")) { @@ -3034,7 +3043,11 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> { let desc = &key; let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); // How many resources the filler alone would have added (a count for - // the log: `placed_filler_twins`). + // the log: `placed_filler_twins`). Diagnostics builds only: without + // that feature this whole block -- its mutex, its set, and its O(seen + // so far at this address) scan on every new raw description -- does + // not exist, not just "does nothing"; see `PLACED_RAW`. + #[cfg(feature = "diagnostics")] if raw != key { let mut seen = PLACED_RAW.lock().unwrap_or_else(|e| e.into_inner()); if seen.insert((address, raw)) { From 63957271cdd1783da4164f398d6ed75270035b74 Mon Sep 17 00:00:00 2001 From: trustno1-coder <361337194+trustno1-coder@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:56:14 -0800 Subject: [PATCH 444/445] CGBJ's renderer, DLSS, an F1 settings menu, frame generation, ray tracing switch The default of scripts\play-nvidia.ps1 changes: the game renders its own 720p and DLSS takes it to 1080p (Series S), in place of the half render scale and the title's upscaler. -Resolution still reaches the older path. - Renderer: codec-d/cool_fox f4b48ad (GPL-3.0) with this fork's NVIDIA fixes on top (residency.rs, stretch.rs, the ffx upscale dispatch). - DLSS for the title's upscale, from avatarmanz/VIctory-7900XTX pull request 203 (feature `dlss`, VICTORY_UPSCALE=dlss), with VICTORY_DLSS_PRESET and a live sharpness setting. - F1 settings menu in the game (host/menu.rs): saved to victory-settings.txt, applied by the launcher at the next start, "save and restart" from the menu. F3: the panel, now with the generated frame rate beside the real one. - DLSS frame generation through NVIDIA Streamline (streamline.rs, fg.rs), 2x to 6x, the amount changed while playing. Constants and the depth and motion vector tags are handed over at each present. - VICTORY_FPS_CAP: the title's own 30 frames a second can be lifted (60, 120, none), live from the menu. - Real ray tracing as an option (-RayTracing, VICTORY_BVH_BUILDER=1): on this renderer the structure builder runs on NVIDIA. Frame generation is left off with it: the two together run at about 0.1 fps, cause not found. - VICTORY_HEAP_RECHECK_EVERY: textures picked by index looked at again for the whole run (a test against the posterized look). - Get-NVIDIA-DLSS.cmd / scripts\get-nvidia-sdks.ps1: fetch the few NVIDIA files DLSS and frame generation need (about 70 MB) from NVIDIA's GitHub into nvidia-sdk\ (git-ignored). They are NVIDIA's, under NVIDIA's licences, and are not part of this repository. Without them the picture is stretched and there is no frame generation. - scripts\build-nvidia.ps1; the launcher builds the layer when it is not built, and again with DLSS once those files are there. Measured on an RTX 5070 (Series S, DLSS, opening rooms): about 15-17 fps without ray tracing, 13-15 with it, before generated frames. What is known to be wrong is in the README's new section. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .gitignore | 5 + Cargo.lock | 1 + Get-NVIDIA-DLSS.cmd | 11 + README.md | 70 +- apps/victory/Cargo.toml | 3 + apps/victory/src/run.rs | 31 +- crates/victory-gpu/Cargo.toml | 3 + crates/victory-gpu/build.rs | 9 + crates/victory-gpu/src/ambient.rs | 17 +- crates/victory-gpu/src/compose.rs | 491 ++-- crates/victory-gpu/src/descriptor/host.rs | 519 ++++- crates/victory-gpu/src/dlss.rs | 318 +++ crates/victory-gpu/src/draw.rs | 851 +++++-- crates/victory-gpu/src/fence.rs | 33 +- crates/victory-gpu/src/fg.rs | 405 ++++ crates/victory-gpu/src/frame.rs | 47 +- crates/victory-gpu/src/host.rs | 429 +++- crates/victory-gpu/src/host/card_steps.rs | 6 + crates/victory-gpu/src/host/menu.rs | 528 +++++ crates/victory-gpu/src/host/panel.rs | 27 +- crates/victory-gpu/src/host/place.rs | 1 + crates/victory-gpu/src/host/upcheck.rs | 42 + crates/victory-gpu/src/indirect.rs | 10 +- crates/victory-gpu/src/lib.rs | 16 +- crates/victory-gpu/src/list.rs | 165 ++ crates/victory-gpu/src/list/thin.rs | 20 + crates/victory-gpu/src/pipeline.rs | 3 + crates/victory-gpu/src/pipeline/host.rs | 1 + crates/victory-gpu/src/pipeline/make.rs | 94 +- crates/victory-gpu/src/pool.rs | 93 +- crates/victory-gpu/src/queue.rs | 188 +- crates/victory-gpu/src/queue/behind.rs | 25 +- crates/victory-gpu/src/residency.rs | 201 ++ crates/victory-gpu/src/resource.rs | 9 + crates/victory-gpu/src/shadow.rs | 6 + crates/victory-gpu/src/streamline.rs | 2184 ++++++++++++++++++ crates/victory-gpu/src/stretch.rs | 292 +++ crates/victory-gpu/src/texture.rs | 254 +- crates/victory-gpu/src/texture/ahead.rs | 72 +- crates/victory-hle/src/modules/audio.rs | 24 +- crates/victory-hle/src/modules/dstorage.rs | 15 +- crates/victory-hle/src/modules/ffx.rs | 250 ++ crates/victory-hle/src/modules/gameinput.rs | 9 +- crates/victory-hle/src/modules/mod.rs | 1 + crates/victory-shader/src/emit/diff_tests.rs | 39 +- crates/victory-shader/src/emit/host.rs | 46 + crates/victory-shader/src/emit/intersect.rs | 23 +- crates/victory-shader/src/emit/lower.rs | 90 +- crates/victory-shader/src/emit/mod.rs | 131 +- crates/victory-shader/src/emit/shader.rs | 5 + crates/victory-shader/src/emit/valu_tests.rs | 693 +++--- crates/victory-shader/src/resource.rs | 129 +- scripts/build-nvidia.ps1 | 25 + scripts/get-nvidia-sdks.ps1 | 154 ++ scripts/play-nvidia.ps1 | 229 +- 55 files changed, 8030 insertions(+), 1313 deletions(-) create mode 100644 Get-NVIDIA-DLSS.cmd create mode 100644 crates/victory-gpu/src/dlss.rs create mode 100644 crates/victory-gpu/src/fg.rs create mode 100644 crates/victory-gpu/src/host/menu.rs create mode 100644 crates/victory-gpu/src/residency.rs create mode 100644 crates/victory-gpu/src/streamline.rs create mode 100644 crates/victory-gpu/src/stretch.rs create mode 100644 crates/victory-hle/src/modules/ffx.rs create mode 100644 scripts/build-nvidia.ps1 create mode 100644 scripts/get-nvidia-sdks.ps1 diff --git a/.gitignore b/.gitignore index ac9edc3..a089e99 100644 --- a/.gitignore +++ b/.gitignore @@ -76,3 +76,8 @@ *.swp Thumbs.db .DS_Store + +# NVIDIA's own files (scripts/get-nvidia-sdks.ps1 fetches them from NVIDIA; never part of this repository) +/nvidia-sdk/ +# What the F1 menu saved +/victory-settings.txt diff --git a/Cargo.lock b/Cargo.lock index 29bab8c..b0b1c77 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -638,6 +638,7 @@ dependencies = [ "memchr", "victory-core", "victory-game", + "victory-gpu", "victory-hle", "victory-loader", "victory-pe", diff --git a/Get-NVIDIA-DLSS.cmd b/Get-NVIDIA-DLSS.cmd new file mode 100644 index 0000000..9c03370 --- /dev/null +++ b/Get-NVIDIA-DLSS.cmd @@ -0,0 +1,11 @@ +@echo off +rem Downloads the NVIDIA files that DLSS and DLSS frame generation need (about 70 MB) from NVIDIA's own +rem GitHub and puts them where the launcher looks for them (nvidia-sdk\ in this folder). Run it once. +rem They are NVIDIA's files under NVIDIA's licences, which are saved beside them; this repository does +rem not contain them. Without them the game still runs: its picture is stretched instead of going +rem through DLSS, and there is no DLSS frame generation. +rem Get-NVIDIA-DLSS.cmd DLSS and frame generation +rem Get-NVIDIA-DLSS.cmd -NoStreamline DLSS only (about 60 MB) +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0scripts\get-nvidia-sdks.ps1" %* +echo. +pause diff --git a/README.md b/README.md index 53a6c1c..1b2b054 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,51 @@ everything on NVIDIA cards and run fastest there**, using the Series S profile. copy of the game. It is not affiliated with or endorsed by the game's developer or publisher. +## New on 2026-11-26: another renderer, DLSS, a settings menu + +The default of `scripts\play-nvidia.ps1` changed. What is below this section +was written on 2026-11-25 for the settings before it, which `-Resolution` +still reaches. + +- **The renderer is CGBJ's** ([codec-d/cool_fox](https://github.com/codec-d/cool_fox) + `f4b48ad`, GPL-3.0 like this fork), with this fork's NVIDIA fixes on top. +- **DLSS does the title's upscale** (from pull request 203 of + [avatarmanz/VIctory-7900XTX](https://github.com/avatarmanz/VIctory-7900XTX)): + the game renders its own 720p and DLSS takes it to 1080p, in place of the + render scale and the title's upscaler. Series S only. +- **F1 in the game opens a settings menu** (arrows pick and change, Enter + does it): upscaler, DLSS model and sharpness, frame generation, frame rate + cap, ray tracing, Smooth Motion, console profile, graphics card, and the + speed switches. Lines marked LIVE change at once; the others are saved to + `victory-settings.txt` and apply at the next start, which "SAVE AND RESTART + NOW" does for you. F3 shows the numbers panel. +- **DLSS frame generation** (NVIDIA Streamline), 2x to 6x, from the menu. The + amount changes while playing. Frames are only generated while the game's + window has the focus. +- **Frame rate cap**: the title asks for 30 frames a second; the menu's FRAME + RATE CAP lifts that (60, 120 or none). +- **Real ray tracing**, off by default: `-RayTracing` or the menu. On this + renderer the title's structure builder runs on NVIDIA (53 programs), and + the draws dropped for it go from hundreds or thousands a frame to one. + +Measured on the RTX 5070 below (Series S, DLSS, opening rooms): about 15-17 +fps without ray tracing and 13-15 with it, before generated frames. + +Known to be wrong with it: + +- **Ray tracing and DLSS frame generation together do not work**: about 0.1 + fps and a white picture. Each alone is fine. The launcher and the layer + leave frame generation off when ray tracing is on (Smooth Motion can do the + extra frames then). The cause is not found. +- **Without ray tracing, lit places further into the game blow out to white + with black holes** (the bank, outdoors): the lighting runs with every ray + missing. With ray tracing on, that has not been checked that far yet. +- **With ray tracing, shaders build for minutes** the first time a place is + seen (about 1,700 pipelines for the opening alone). +- **A posterized "oil paint" look** comes in some runs and not in others. +- "SAVE AND RESTART NOW" can leave the old game's process behind without a + window; it goes when the PC restarts. + ## Where it stands (2026-11-25) Tested on one machine only: Windows 11, AMD Ryzen 7 9800X3D, 64 GB RAM, @@ -231,16 +276,33 @@ tools, and your own dump of the title. git clone https://github.com/trustno1-coder/VIctory-NVIDIA cd VIctory-NVIDIA copy victory.example.toml victory.toml # then set your paths, outside this folder -cargo build --locked --profile diag -p victory --features diagnostics scripts\play-nvidia.ps1 -Exe <path of your copy's executable> ``` +The first start builds the layer by itself (`scripts\build-nvidia.ps1`: the +`diag` profile with `diagnostics`). + +**For DLSS and DLSS frame generation, run `Get-NVIDIA-DLSS.cmd` once** (double +click it, or `Get-NVIDIA-DLSS.cmd -NoStreamline` for DLSS alone). It downloads +the few NVIDIA files they need, about 70 MB, from NVIDIA's own GitHub +([NVIDIA/DLSS](https://github.com/NVIDIA/DLSS), +[NVIDIA-RTX/Streamline](https://github.com/NVIDIA-RTX/Streamline)) into +`nvidia-sdk\` (git-ignored), and the next start builds the layer again with +DLSS in it (about a minute). Those files are NVIDIA's, under NVIDIA's licences, +which are saved beside them; this repository does not carry them and may not. +A build with DLSS links NVIDIA's loader library: it is for your own use, not +for passing on. + +Without that step the game runs all the same: its 720p picture is stretched to +the screen instead of going through DLSS (softer), and there is no DLSS frame +generation. Nothing is downloaded unless you run that file. + `scripts\play-nvidia.ps1` starts a copy of the build named `victory_sm.exe`, so NVIDIA Smooth Motion applies every time once it is turned on for that exe in the NVIDIA App. `-NoSmoothMotion` runs `victory.exe` itself; `-SeriesX` uses the -Series X profile (sharper, much slower); `-Quality` gives fewer stretched bodies -and less rainbow skin for about 7 fps. The fork's own `scripts\play.ps1` is -still there for AMD cards. +Series X profile (sharper, much slower, no DLSS); `-Quality` gives fewer +stretched bodies, slower; `-RayTracing` turns the title's real ray tracing on. +The fork's own `scripts\play.ps1` is still there for AMD cards. ### Picking a resolution diff --git a/apps/victory/Cargo.toml b/apps/victory/Cargo.toml index 5fddd5b..86fcf7d 100644 --- a/apps/victory/Cargo.toml +++ b/apps/victory/Cargo.toml @@ -12,6 +12,7 @@ victory-core.workspace = true victory-pe.workspace = true victory-loader.workspace = true victory-hle.workspace = true +victory-gpu.workspace = true victory-shader = { workspace = true, features = ["host"] } victory-game.workspace = true anyhow.workspace = true @@ -21,6 +22,8 @@ clap.workspace = true walkdir.workspace = true [features] +# NVIDIA DLSS for the title's upscale (VICTORY_UPSCALE=dlss); needs VICTORY_DLSS_SDK. +dlss = ["victory-gpu/dlss"] # Debug-level logs and the debugging switches (frame capture, stack dumps, # the host debug layer, scripted keys). Off in a plain release build. diagnostics = [ diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 6706904..5e3f35a 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -108,6 +108,11 @@ pub fn run( println!("console {}", victory_hle::console::current().name()); let dlls = victory_loader::load_title_dlls(image.info(), title_dir, &images, &wanted)?; for (name, dll) in &dlls { + if name.eq_ignore_ascii_case(victory_hle::modules::ffx::LOADER) + && let Some(real) = dll.export("ffxDispatch") + { + victory_hle::modules::ffx::set_real_dispatch(real); + } println!("title dll {name} at {:#x}", dll.base()); victory_hle::runtime::set_image_path(dll.base(), &title_dir.join(name)); } @@ -162,7 +167,31 @@ pub fn run( show(name, dll.bind_imports(&with_dlls, policy)?); } let exe_name = exe.file_name().unwrap_or_default().to_string_lossy(); - show(&exe_name, image.bind_imports(&with_dlls, policy)?); + // `VICTORY_UPSCALE=stretch` (Series S): the upscale dispatch is ours + // (`victory_hle::modules::ffx`, a plain stretch) instead of the title's + // own FidelityFX passes, which are slow translated on 32-lane hosts; the + // rest of that DLL stays the title's. Unset: the title's own, as before. + struct TakeDispatch<'a>(&'a dyn victory_loader::ImportResolver, bool); + impl victory_loader::ImportResolver for TakeDispatch<'_> { + fn resolve(&self, dll: &str, symbol: &victory_pe::ImportSymbol) -> victory_loader::Resolution { + let ours = self.1 + && dll.eq_ignore_ascii_case(victory_hle::modules::ffx::LOADER) + && matches!(symbol, victory_pe::ImportSymbol::Name { name, .. } if name == "ffxDispatch"); + if ours { + return victory_loader::Resolution::Found { + address: victory_hle::modules::ffx::dispatch_address(), + provenance: victory_loader::Provenance::Hle, + }; + } + self.0.resolve(dll, symbol) + } + } + let take = victory_hle::console::current() == victory_hle::console::Console::SeriesS + && std::env::var_os("VICTORY_UPSCALE").is_some_and(|v| v == "stretch" || v == "dlss"); + if take { + println!("upscale the title's ffxDispatch is ours (VICTORY_UPSCALE=stretch|dlss)"); + } + show(&exe_name, image.bind_imports(&TakeDispatch(&with_dlls, take), policy)?); if execute { let size = image.info().size_of_image as usize; // SAFETY: the image stays mapped, and nothing of it has run yet. diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index 16c7495..d98532e 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -25,6 +25,9 @@ tempfile.workspace = true [features] # Debugging switches (frame capture, the host debug layer, per-draw data). diagnostics = [] +# NVIDIA DLSS for the title's upscale (`VICTORY_UPSCALE=dlss`); needs the DLSS +# SDK (NVIDIA/DLSS: include, lib/Windows_x86_64) at `VICTORY_DLSS_SDK`. +dlss = [] [lints] workspace = true diff --git a/crates/victory-gpu/build.rs b/crates/victory-gpu/build.rs index 9dcfa61..591d003 100644 --- a/crates/victory-gpu/build.rs +++ b/crates/victory-gpu/build.rs @@ -42,4 +42,13 @@ fn main() { } println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rustc-env=VICTORY_TRANSLATOR={}", hash.finalize().to_hex()); + // The `dlss` feature links the DLSS SDK's loader (`nvsdk_ngx_d.lib`, the + // dynamic-CRT one) from `VICTORY_DLSS_SDK`. + println!("cargo:rerun-if-env-changed=VICTORY_DLSS_SDK"); + if std::env::var_os("CARGO_FEATURE_DLSS").is_some() { + let sdk = std::env::var_os("VICTORY_DLSS_SDK") + .map(PathBuf::from) + .expect("the dlss feature needs VICTORY_DLSS_SDK (the NVIDIA/DLSS checkout)"); + println!("cargo:rustc-link-search=native={}", sdk.join("lib/Windows_x86_64/x64").display()); + } } diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs index a714aa2..e868476 100644 --- a/crates/victory-gpu/src/ambient.rs +++ b/crates/victory-gpu/src/ambient.rs @@ -112,18 +112,6 @@ fn air() -> f32 { }) } -/// LOCAL: how many times the estimate the title's own result may keep -/// (`VICTORY_AMBIENT_MOST=<multiple>`, 4 when unset). Without rays the -/// probes hold the sky's light indoors too; at 4 times the estimate a room -/// looked towards a window or the sky goes very bright. -fn most() -> f32 { - static SET: OnceLock<f32> = OnceLock::new(); - *SET.get_or_init(|| { - let set = std::env::var("VICTORY_AMBIENT_MOST").unwrap_or_default(); - set.trim().parse().ok().filter(|v: &f32| v.is_finite() && *v > 0.0).unwrap_or(4.0) - }) -} - /// Strength and radius of the creases' shade. fn shade() -> [f32; 2] { static SET: OnceLock<[f32; 2]> = OnceLock::new(); @@ -255,9 +243,6 @@ void clear_air(uint3 at : SV_DispatchThreadID) { 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]; - // LOCAL: a NaN or infinity in the air is summed along every view ray - // through it: black or white patches floating in the room. - if (any(isnan(c)) || any(isinf(c))) { scattered[at] = 0; return; } float has = dot(c, LUMA); if (has > cap) scattered[at] = c * (cap / has); } @@ -474,7 +459,7 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { words[6] = views.size[0]; words[7] = views.size[1]; words[8] = 0.04f32.to_bits(); - words[9] = most().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 diff --git a/crates/victory-gpu/src/compose.rs b/crates/victory-gpu/src/compose.rs index 9aa45cb..dfcf50b 100644 --- a/crates/victory-gpu/src/compose.rs +++ b/crates/victory-gpu/src/compose.rs @@ -1,244 +1,325 @@ -//! Ported from fxceless/victory-gta6 PR #1189 (Series S interface plane), `VICTORY_COMPOSE=1`. -//! A present's second plane laid over its first. -//! -//! A Series S title presents two planes (run 2026-11-25: plane 0 the -//! game, 1920x1080 or what the display mode makes it, plane 1 the -//! interface, 3840x2160); the console's display lays the second over the -//! first and scales both to the screen. The host shows one texture, so -//! the interface is laid over the game here, at the game plane's size, -//! into a texture of ours that is shown instead (filtered: the interface -//! is scaled down). shortcut: the planes' placement and source rectangles -//! are not read; both cover the screen. The interface's alpha is taken as -//! straight (`VICTORY_PLANE_PREMULTIPLIED=1`: premultiplied). - -use std::sync::Mutex; +//! Two presented planes as one image: the console's display puts the second +//! (the interface) over the first (the scene), each scaled to the screen. +//! Grand Theft Auto VI presents so on Series S. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; +use windows::core::{PCSTR, s}; -/// Frames of descriptors in the ring (three each): presents in flight -/// must not find theirs rewritten. -const SLOTS: u32 = 16; +use crate::host::Host; const SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=3, b0), DescriptorTable(SRV(t0, numDescriptors=2), UAV(u0)), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)" -cbuffer Size : register(b0) { uint w; uint h; uint premultiplied; }; -Texture2D<float4> game : register(t0); -Texture2D<float4> ui : register(t1); -RWTexture2D<float4> outp : register(u0); -SamplerState linear_clamp : register(s0); +#define RS "DescriptorTable(SRV(t0, numDescriptors=2), visibility=SHADER_VISIBILITY_PIXEL), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)" +Texture2D<float4> scene : register(t0); +Texture2D<float4> over : register(t1); +SamplerState smooth_ : register(s0); +struct V { float4 at : SV_Position; float2 uv : TEXCOORD0; }; [RootSignature(RS)] -[numthreads(8, 8, 1)] -void main(uint3 id : SV_DispatchThreadID) { - if (id.x >= w || id.y >= h) return; - float2 uv = (float2(id.xy) + 0.5) / float2(w, h); - float4 g = game.Load(int3(id.xy, 0)); - float4 u = ui.SampleLevel(linear_clamp, uv, 0); - float3 c = premultiplied != 0 ? g.rgb * (1.0 - u.a) + u.rgb : lerp(g.rgb, u.rgb, u.a); - outp[id.xy] = float4(c, 1.0); +V vs(uint id : SV_VertexID) { + V v; + v.uv = float2((id << 1) & 2, id & 2); + v.at = float4(v.uv * float2(2, -2) + float2(-1, 1), 0, 1); + return v; +} +[RootSignature(RS)] +float4 ps(V v) : SV_Target { + float4 s = scene.SampleLevel(smooth_, v.uv, 0); + float4 o = over.SampleLevel(smooth_, v.uv, 0); + return float4(saturate(o.rgb + s.rgb * (1 - saturate(o.a))), 1); } "#; -struct Pass { +pub(crate) struct Composer { root: ID3D12RootSignature, pso: ID3D12PipelineState, - views: ID3D12DescriptorHeap, - cpu: usize, - gpu: u64, + views: Vec<ID3D12DescriptorHeap>, step: u32, - next: u32, - /// The texture shown instead, by size. - out: Option<(u64, u32, ID3D12Resource)>, } -// SAFETY: D3D12 objects are free-threaded; the pass is used under a lock. -unsafe impl Send for Pass {} +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Composer {} +// SAFETY: as above. +unsafe impl Sync for Composer {} -/// The pass: not tried yet, could not be made, or made. -static PASS: Mutex<Option<Option<Pass>>> = Mutex::new(None); - -fn make(device: &ID3D12Device) -> windows::core::Result<Pass> { +fn compile(entry: PCSTR, target: PCSTR) -> windows::core::Result<ID3DBlob> { let mut code: Option<ID3DBlob> = None; - // SAFETY: the source and names live through the call; the out pointer - // is ours. + // SAFETY: the source and names live through the call; the out pointer is + // ours. unsafe { D3DCompile( SOURCE.as_ptr().cast(), SOURCE.len(), - windows::core::s!("present planes"), + s!("compose"), None, None, - windows::core::s!("main"), - windows::core::s!("cs_5_1"), + entry, + target, 0, 0, &mut code, None, )?; } - let code = code.ok_or_else(windows::core::Error::empty)?; - // SAFETY: the blob's own bytes (the root signature is inside the - // shader); plain object creation and queries. - unsafe { - let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); - let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; - let pso: ID3D12PipelineState = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), - CS: D3D12_SHADER_BYTECODE { - pShaderBytecode: bytes.as_ptr().cast(), - BytecodeLength: bytes.len(), - }, - ..Default::default() - })?; - let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; - let views: ID3D12DescriptorHeap = device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: kind, - NumDescriptors: SLOTS * 3, - Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, - NodeMask: 0, - })?; - Ok(Pass { - cpu: views.GetCPUDescriptorHandleForHeapStart().ptr, - gpu: views.GetGPUDescriptorHandleForHeapStart().ptr, - step: device.GetDescriptorHandleIncrementSize(kind), - root, - pso, - views, - next: 0, - out: None, - }) + code.ok_or_else(windows::core::Error::empty) +} + +impl Composer { + pub(crate) fn new(host: &Host, format: DXGI_FORMAT) -> windows::core::Result<Self> { + let (vs, ps) = ( + compile(s!("vs"), s!("vs_5_1"))?, + compile(s!("ps"), s!("ps_5_1"))?, + ); + // SAFETY: the blobs' own bytes, alive through the calls. + unsafe { + let bytes = |b: &ID3DBlob| { + std::slice::from_raw_parts(b.GetBufferPointer().cast::<u8>(), b.GetBufferSize()) + }; + let device = &host.device; + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes(&vs))?; + let code = |b: &ID3DBlob| D3D12_SHADER_BYTECODE { + pShaderBytecode: b.GetBufferPointer(), + BytecodeLength: b.GetBufferSize(), + }; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: code(&vs), + PS: code(&ps), + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + desc.RTVFormats[0] = format; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = + D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + let pso = device.CreateGraphicsPipelineState(&desc)?; + Ok(Composer { + root, + pso, + views: Vec::new(), + step: device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), + }) + } + } + + /// Each presenter command-list slot owns its own pair of SRVs. The swap + /// chain may have several outstanding presents; the slot is selected by + /// the completion fence, and its descriptors are only overwritten on reuse. + pub(crate) fn record( + &mut self, + host: &Host, + slot: usize, + list: &ID3D12GraphicsCommandList, + planes: [(&ID3D12Resource, DXGI_FORMAT); 2], + back: &ID3D12Resource, + (width, height): (u32, u32), + ) -> windows::core::Result<()> { + while self.views.len() <= slot { + let heap = unsafe { + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + })? + }; + self.views.push(heap); + } + let views = &self.views[slot]; + // SAFETY: an open list; the views are made in slots no frame in flight + // reads; live textures. + unsafe { + let (cpu, gpu) = ( + views.GetCPUDescriptorHandleForHeapStart(), + views.GetGPUDescriptorHandleForHeapStart(), + ); + for (i, plane) in planes.iter().enumerate() { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: cpu.ptr + (i * self.step as usize), + }; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: plane.1, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MipLevels: 1, + ..Default::default() + }, + }, + }; + host.device + .CreateShaderResourceView(Some(plane.0), Some(&desc), at); + } + let rtv = host.rtv(Some(back), None); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.SetDescriptorHeaps(&[Some(views.clone())]); + list.SetGraphicsRootSignature(&self.root); + list.SetPipelineState(&self.pso); + list.SetGraphicsRootDescriptorTable(0, gpu); + list.IASetPrimitiveTopology( + windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + ); + list.RSSetViewports(&[D3D12_VIEWPORT { + Width: width as f32, + Height: height as f32, + MaxDepth: 1.0, + ..Default::default() + }]); + list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }]); + list.DrawInstanced(3, 1, 0, 0); + } + Ok(()) } } -/// Whether a host texture's format is one this pass reads and writes -/// (8-bit RGBA, typeless or not). -fn rgba8(format: DXGI_FORMAT) -> bool { - matches!(format.0, 27 | 28) -} - -fn premultiplied() -> bool { - static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_PLANE_PREMULTIPLIED").is_some_and(|v| v == "1")) -} - -/// Records, into the present's `list`, `ui` laid over `game` into a -/// texture of ours, and gives that texture, left in the copy-source -/// state. `game` is in the copy-source state (the present put it there); -/// `ui` is in `ui_state` and is left in it. `None` (nothing recorded) if -/// a format is not 8-bit RGBA or the pass could not be made. -pub(crate) fn record( - device: &ID3D12Device, - list: &ID3D12GraphicsCommandList, - game: &ID3D12Resource, - ui: &ID3D12Resource, - ui_state: u32, -) -> Option<ID3D12Resource> { - // SAFETY: live resources; plain queries. - let (gd, ud) = unsafe { (game.GetDesc(), ui.GetDesc()) }; - if !rgba8(gd.Format) || !rgba8(ud.Format) { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!(game = gd.Format.0, ui = ud.Format.0, "present planes not laid over each other: a format this pass does not read"); - }); +/// Select a legal float-sampled view of a display plane, preserving a typed +/// resource's format. Typeless resources use the corresponding display type. +pub(crate) fn view(d: &D3D12_RESOURCE_DESC) -> Option<DXGI_FORMAT> { + if d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D + || d.DepthOrArraySize != 1 + || d.SampleDesc.Count != 1 + || d.Flags.contains(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) + { return None; } - let mut kept = PASS.lock().unwrap_or_else(|e| e.into_inner()); - if kept.is_none() { - *kept = Some(match make(device) { - Ok(p) => { - tracing::info!(premultiplied = premultiplied(), "present planes: the interface is laid over the game"); - Some(p) + match d.Format.0 { + 9 => Some(DXGI_FORMAT_R16G16B16A16_FLOAT), + 23 => Some(DXGI_FORMAT_R10G10B10A2_UNORM), + 27 => Some(DXGI_FORMAT_R8G8B8A8_UNORM), + 90 => Some(DXGI_FORMAT_B8G8R8A8_UNORM), + 10 | 11 | 13 | 24 | 26 | 28 | 29 | 31 | 67 | 87 | 91 => Some(d.Format), + _ => None, + } +} + +#[cfg(all(test, feature = "diagnostics"))] +mod tests { + use super::*; + + #[test] + fn composes_scaled_premultiplied_plane_on_gpu() { + let Some(host) = crate::host::host() else { + eprintln!("skipping display-plane readback: no D3D12 device"); + return; + }; + let format = DXGI_FORMAT_R8G8B8A8_UNORM; + let mut compositor = Composer::new(host, format).unwrap(); + let list = host.new_list().unwrap(); + let texture = |width: u64| -> ID3D12Resource { + let mut resource = None; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: width, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + unsafe { + host.device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut resource, + ) + .unwrap() + }; + resource.unwrap() + }; + // A half-red base at one resolution. The overlay at output resolution + // contains transparent, half-opaque green and fully opaque blue pixels. + let base = texture(1); + let overlay = texture(3); + let output = texture(3); + let target = D3D12_RESOURCE_STATE_RENDER_TARGET; + let read = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + let cmds = &list.list; + unsafe { + cmds.ClearRenderTargetView(host.rtv(Some(&base), None), &[0.5, 0.0, 0.0, 1.0], None); + let overlay_rtv = host.rtv(Some(&overlay), None); + let colors = [ + [0.0, 0.0, 0.0, 0.0], + [0.0, 0.5, 0.0, 0.5], + [0.0, 0.0, 1.0, 1.0], + ]; + for (i, color) in colors.iter().enumerate() { + let rect = windows::Win32::Foundation::RECT { + left: i as i32, + right: i as i32 + 1, + top: 0, + bottom: 1, + }; + cmds.ClearRenderTargetView(overlay_rtv, color, Some(&[rect])); } - Err(e) => { - tracing::warn!(error = %e, "present planes: the pass that lays them over each other could not be made"); - None + cmds.ResourceBarrier(&[ + crate::host::transition(&base, target, read), + crate::host::transition(&overlay, target, read), + ]); + compositor + .record( + host, + 0, + cmds, + [(&base, format), (&overlay, format)], + &output, + (3, 1), + ) + .unwrap(); + cmds.ResourceBarrier(&[crate::host::transition( + &output, + target, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let (buffer, footprint) = + crate::capture::read_back(&host.device, cmds, &output).unwrap(); + list.close(); + host.execute(&[&list]); + host.device.GetDeviceRemovedReason().unwrap(); + let mut mapped = std::ptr::null_mut(); + buffer.Map(0, None, Some(&mut mapped)).unwrap(); + let start = mapped.cast::<u8>().add(footprint.Offset as usize); + let pixels: [u8; 12] = std::slice::from_raw_parts(start, 12).try_into().unwrap(); + buffer.Unmap(0, None); + for (actual, expected) in pixels + .iter() + .zip([128, 0, 0, 255, 64, 128, 0, 255, 0, 0, 255, 255]) + { + assert!( + actual.abs_diff(expected) <= 1, + "unexpected composite {pixels:?}" + ); } - }); + eprintln!("D3D12 display-plane readback RGBA: {pixels:?}"); + } } - let pass = kept.as_mut()?.as_mut()?; - let (w, h) = (gd.Width, gd.Height); - if pass.out.as_ref().is_none_or(|o| (o.0, o.1) != (w, h)) { - let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_DEFAULT, - ..Default::default() - }; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, - Width: w, - Height: h, - DepthOrArraySize: 1, - MipLevels: 1, - Format: DXGI_FORMAT_R8G8B8A8_UNORM, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, - Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, - ..Default::default() - }; - let mut out: Option<ID3D12Resource> = None; - // SAFETY: plain creation of a device-local texture. - unsafe { - device - .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_SOURCE, None, &mut out) - .ok()?; - } - pass.out = Some((w, h, out?)); - } - let out = pass.out.as_ref()?.2.clone(); - let first = (pass.next % SLOTS) * 3; - pass.next = pass.next.wrapping_add(1); - let cpu = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: pass.cpu + ((first + i) * pass.step) as usize }; - let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: pass.gpu + u64::from(first * pass.step) }; - let srv = D3D12_SHADER_RESOURCE_VIEW_DESC { - Format: DXGI_FORMAT_R8G8B8A8_UNORM, - ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, - Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, - Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { - Texture2D: D3D12_TEX2D_SRV { - MostDetailedMip: 0, - MipLevels: 1, - ..Default::default() - }, - }, - }; - let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { - Format: DXGI_FORMAT_R8G8B8A8_UNORM, - ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, - Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { - Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 }, - }, - }; - let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - let ui_state = D3D12_RESOURCE_STATES(ui_state as i32); - let t = crate::host::transition; - let mut before = vec![ - t(game, D3D12_RESOURCE_STATE_COPY_SOURCE, read), - t(&out, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - ]; - let mut after = vec![ - t(game, read, D3D12_RESOURCE_STATE_COPY_SOURCE), - t(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), - ]; - if ui_state != read { - before.push(t(ui, ui_state, read)); - after.push(t(ui, read, ui_state)); - } - let constants: [u32; 3] = [w as u32, h, u32::from(premultiplied())]; - // SAFETY: an open list (the present's); slots of our heap; live - // resources and objects (the pass's own live as long as the process, - // the texture is kept by the present's list). - unsafe { - device.CreateShaderResourceView(game, Some(&srv), cpu(0)); - device.CreateShaderResourceView(ui, Some(&srv), cpu(1)); - device.CreateUnorderedAccessView(&out, None::<&ID3D12Resource>, Some(&uav), cpu(2)); - list.ResourceBarrier(&before); - list.SetDescriptorHeaps(&[Some(pass.views.clone())]); - list.SetComputeRootSignature(&pass.root); - list.SetPipelineState(&pass.pso); - list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); - list.SetComputeRootDescriptorTable(1, gpu); - list.Dispatch((w as u32).div_ceil(8), h.div_ceil(8), 1); - list.ResourceBarrier(&after); - } - Some(out) } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index b6e8f9c..305145a 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -112,6 +112,8 @@ impl Made { } pub(crate) struct HostHeap { + pub(crate) buffer_sweep: Mutex<crate::draw::BufferSweep>, + pub(crate) buffer_frame: std::sync::atomic::AtomicU64, pub(crate) heap: ID3D12DescriptorHeap, cpu: usize, step: u32, @@ -424,6 +426,48 @@ fn neutral_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<ID3D12Res static FLIPS: Mutex<Vec<Flip>> = Mutex::new(Vec::new()); +/// Deferred slot flips recorded into an open or not-yet-submitted command +/// list (`HostHeap::flip`), tracked so a one-shot decoration bake draw can +/// promote them out of the `neutral()` gray stand-in before sampling them. +pub(crate) struct PendingListFlip { + id: u64, + pub(crate) origin: (usize, u64), + flip: Flip, +} + +impl PendingListFlip { + pub(crate) fn index(&self) -> u32 { + self.flip.index + } + + pub(crate) fn handle(&self) -> u64 { + self.flip.handle + } + + pub(crate) fn key(&self) -> u64 { + self.flip.key + } +} + +static NEXT_PENDING_FLIP: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); +static PENDING_LIST_FLIPS: Mutex<Vec<PendingListFlip>> = Mutex::new(Vec::new()); +static PENDING_LIST_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +fn take_pending_list_flip(id: u64) -> Option<Flip> { + if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) == 0 { + return None; + } + let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + let pos = pending.iter().position(|p| p.id == id)?; + let entry = pending.swap_remove(pos); + PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release); + Some(entry.flip) +} + +fn remove_pending_list_flip(id: u64) { + let _ = take_pending_list_flip(id); +} + /// 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. @@ -712,6 +756,12 @@ impl Spans { /// pass last took the ranges ([`page_written`]). Kept apart from /// [`REMAPPED`] so that what such writes do is counted by itself. static PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new()); +/// Physical-page writes retained specifically for one-shot decoration/ped +/// texture bakes when `VICTORY_PAGE_WRITES` bit 2 is off (the default): normal +/// frames stay free of queue flooding while every bake still sees freshly +/// DirectStorage-streamed texture bytes immediately instead of waiting on +/// `RECHECK_FRAMES`. +static BAKE_PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new()); /// Since the start: such ranges kept for a pass; ranges dropped because no /// pass took them; slots of placed textures that held bytes of them when a @@ -1134,29 +1184,46 @@ pub(crate) fn device_removed() -> Option<String> { pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -/// Bytes per element of a buffer view, as the console's descriptor holds -/// them for indexed reads (structured: the stride; raw: 1, the index is the -/// byte; typed: the format's); `None` if `view` is not a buffer view. -fn view_stride(view: &View) -> Option<u32> { - let (stride, raw, format) = view_elements(view)?; - Some(if stride > 0 { +/// Bytes per element and typed integer format bits of a buffer view, decoded +/// in a single pass over the view descriptor; `(None, 0)` if not a buffer view. +fn view_stride_and_kind(view: &View) -> (Option<u32>, u32) { + use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; + let Some((stride, raw, format)) = view_elements(view) else { + return (None, 0); + }; + let bytes = if stride > 0 { stride } else if raw { 1 } else { crate::resource::element(format).map_or(0, |(bytes, _)| bytes as u32) - }) + }; + let kind = if stride == 0 && !raw { + match format { + 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => VIEW_INTEGER, + 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => VIEW_INTEGER | VIEW_SIGNED, + _ => 0, + } + } else { + 0 + }; + (Some(bytes), kind) } -/// 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. +/// Packed [`victory_shader::emit::SLOT_STRIDES`] word for `view`. +fn view_stride_word(view: &View) -> u32 { + let (stride, kind) = view_stride_and_kind(view); + stride.unwrap_or(0) | kind +} + +#[cfg(test)] +fn view_stride(view: &View) -> Option<u32> { + view_stride_and_kind(view).0 +} + +#[cfg(test)] 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, - } + view_stride_and_kind(view).1 } /// A buffer view's structure stride, whether it is raw, and its format; @@ -1568,6 +1635,8 @@ impl HostHeap { }) .flatten(); let h = HostHeap { + buffer_sweep: Mutex::default(), + buffer_frame: std::sync::atomic::AtomicU64::new(u64::MAX), heap, cpu, step, @@ -1675,10 +1744,16 @@ impl HostHeap { } /// A plain point sampler at `at`. +/// LOCAL (11/26, `VICTORY_NULL_SAMPLER_LINEAR=1`): a linear one instead. The +/// oil-painting look of some runs is posterization (colour bands), as from a +/// colour-grading LUT read with a point sampler: a sampler slot whose +/// description was missed at start would read as this one all run. fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; + static LINEAR: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let linear = *LINEAR.get_or_init(|| std::env::var_os("VICTORY_NULL_SAMPLER_LINEAR").is_some_and(|v| v == "1")); let desc = D3D12_SAMPLER_DESC { - Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + Filter: if linear { D3D12_FILTER_MIN_MAG_MIP_LINEAR } else { D3D12_FILTER_MIN_MAG_MIP_POINT }, AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, @@ -1780,7 +1855,7 @@ impl HostHeap { pub(crate) fn texture_news(&self) -> (u64, bool) { let writes = self.textures.lock().unwrap_or_else(|e| e.into_inner()).writes; let noted = |ranges: &Mutex<Vec<(u64, u64)>>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty(); - (writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN)) + (writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN) || noted(&BAKE_PAGE_WRITTEN)) } /// Every title slot of the queue that is due at `frame`, and whether @@ -1928,7 +2003,48 @@ impl HostHeap { if ranges.is_empty() { return 0; } - self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2] + let due = crate::watch::page_writes() & 2 != 0; + let made_due = self.slots_written_under(&ranges, frame, due)[2]; + if !due { + let mut kept = BAKE_PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + kept.extend(ranges); + if kept.len() > 256 { + join(&mut kept); + const MOST: usize = 1 << 14; + if kept.len() > MOST { + let drop_n = kept.len() - MOST; + kept.drain(..drop_n); + } + } + } + made_due + } + + /// Wakes uploaded placed-texture slots touched by recent physical-page + /// writes (DirectStorage completions) immediately (`due = frame`) right + /// before a one-shot ped/decoration bake draw. + pub(crate) fn texture_slots_bake_written(&self, frame: u64) -> usize { + let mut ranges = std::mem::take(&mut *BAKE_PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner())); + if ranges.is_empty() { + return 0; + } + join(&mut ranges); + let mut slots: Vec<u32> = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect() + }; + if slots.is_empty() { + return 0; + } + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0)); + for &slot in &slots { + textures.changed(slot, frame, frame); + } + slots.len() } /// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end): @@ -2223,6 +2339,7 @@ impl HostHeap { /// reads the table's dynamic slots). pub(crate) fn mirror_after(&self, list: &crate::host::HostList, index: u32, handle: u64) { if show_after() + && !crate::texture::BAKING.get() && index < self.count && !self.texture_slot_made_from(index, handle) && let Some(view) = super::view(handle) @@ -2237,14 +2354,143 @@ impl HostHeap { } fn flip(&self, list: &crate::host::HostList, index: u32, handle: u64, late: Option<u64>) { + use std::sync::atomic::Ordering::{Relaxed, Release}; let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle)); + let id = NEXT_PENDING_FLIP.fetch_add(1, Relaxed); + let origin = (std::ptr::from_ref(list) as usize, list.epoch()); + { + let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + pending.push(PendingListFlip { + id, + origin, + flip: Flip { after: 0, heap, index, handle, key, late }, + }); + PENDING_LIST_COUNT.store(pending.len(), Release); + } + struct PendingGuard(u64); + impl PendingGuard { + fn id(&self) -> u64 { + self.0 + } + } + impl Drop for PendingGuard { + fn drop(&mut self) { + remove_pending_list_flip(self.0); + } + } + let guard = PendingGuard(id); list.defer_host(move || { - let after = crate::host::submissions().0; - let flip = Flip { after, heap, index, handle, key, late }; + // Call a `&self` method so Rust 2021+ moves the whole `guard` + // into this closure rather than copying `guard.0` and dropping + // `guard` immediately at the end of `flip()`. + let Some(mut flip) = take_pending_list_flip(guard.id()) else { + return; + }; + flip.after = crate::host::submissions().0; FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip); }); } + /// Whether any deferred slot flip or view remake for this heap requires + /// settling in-flight GPU submissions before exposing real textures to a + /// one-shot decoration bake draw. + pub(crate) fn needs_gpu_settle_for_bake(&self) -> bool { + let own = std::ptr::from_ref(self) as usize; + let finished = crate::host::submissions().1; + if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) > 0 { + let pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + if pending.iter().any(|p| p.flip.heap == own) { + return true; + } + } + { + let flips = FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + if flips.iter().any(|f| f.heap == own && f.after > finished) { + return true; + } + } + let after = RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner()); + after.iter().any(|&(at, _)| at > finished) + } + + /// Drains deferred flips still sitting in unsubmitted command lists for + /// this heap so a decoration bake can mirror them out of `neutral()`. + /// Entries that cannot be promoted yet (unmapped memory or deferred + /// staging) must be returned via [`HostHeap::restore_pending_list_flip`]. + pub(crate) fn take_pending_list_flips(&self) -> Vec<PendingListFlip> { + if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) == 0 { + return Vec::new(); + } + let own = std::ptr::from_ref(self) as usize; + let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + let (mine, rest): (Vec<PendingListFlip>, Vec<PendingListFlip>) = + pending.drain(..).partition(|p| p.flip.heap == own); + *pending = rest; + PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release); + mine + } + + /// Re-queues an unpromoted deferred flip drained by + /// [`HostHeap::take_pending_list_flips`] so its originating command list + /// still flips it out of `neutral()` once submitted. + pub(crate) fn restore_pending_list_flip(&self, item: PendingListFlip) { + let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + pending.push(item); + PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release); + } + + /// Whether title descriptor slot `handle` still holds record `key`. + pub(crate) fn slot_still_at(&self, handle: u64, key: u64) -> bool { + key != 0 && record_key(handle) == key + } + + /// Looks up `(view, key)` for slot `index` prior to a synchronous bake + /// upload without replacing its current host descriptor with `neutral()`; + /// [`HostHeap::publish_uploaded_slot`] exposes the real descriptor and + /// updates `Spans`/stride tracking once the GPU copy finishes. + pub(crate) fn prepare_bake_slot(&self, index: u32, handle: u64) -> Option<(View, u64)> { + if index >= self.count { + return None; + } + let key = record_key(handle); + let view = (key != 0).then(|| view_at(key as u32, (key >> 32) as u32)).flatten()?; + Some((view, key)) + } + + /// Exposes the real host descriptor for slot `index` after its synchronous + /// bake upload has completed on the GPU, updating `Spans`/stride tracking + /// without re-queuing the slot in `TextureQueue`. + pub(crate) fn publish_uploaded_slot(&self, index: u32, handle: u64, key: u64) -> bool { + if index >= self.count || key == 0 { + return false; + } + let (published, stale) = { + let _made = self.made.lock(index); + if self.made.get(index) == Some(key) { + return false; + } + if record_key(handle) != key { + return false; + } + let Some(view) = view_at(key as u32, (key >> 32) as u32) else { + return false; + }; + let stale = self.note_buffer(index, Some(&view), true); + if let Some(kept) = make(&view, self.at(index)) { + self.put(index); + self.quick_is(index, 0); + self.clear_twin(index); + self.made.set(index, key); + self.keep(index, kept); + (true, stale) + } else { + (false, stale) + } + }; + self.unmake_stale(index, stale); + published + } + /// Makes the slots whose new view's upload has run /// ([`HostHeap::texture_slot_flip`]); returns how many. pub(crate) fn texture_slots_flip(&self) -> usize { @@ -2262,6 +2508,7 @@ impl HostHeap { ready }; let mut flipped = 0; + let mut late_flipped = 0; for f in ready { let _made = self.made.lock(f.index); let Some(shown) = self.made.get(f.index) else { @@ -2304,6 +2551,7 @@ impl HostHeap { same_bytes(was, f.key); } if let Some(since) = f.late { + late_flipped += 1; let frames = crate::frame::current().saturating_sub(since); let n = LATE[0].fetch_add(1, Relaxed) + 1; let all = LATE[1].fetch_add(frames, Relaxed) + frames; @@ -2322,7 +2570,7 @@ impl HostHeap { } } FLIPPED[0].fetch_add(flipped as u64, Relaxed); - flipped + flipped + late_flipped } /// The memory of the texture title slot `index` views is there (again): @@ -2351,6 +2599,7 @@ impl HostHeap { } self.put(index); self.clear_twin(index); + self.write_stride(index, 0); self.keep(index, None); } @@ -2546,24 +2795,17 @@ impl HostHeap { textures.remove(slot); } } - 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 - { - // LOCAL (port of fxceless #1216): constant buffer views marked; - // programs read no other non-buffer slot as one. - let entry = match (stride, view) { - (Some(s), _) => s | kind, - (None, Some(View::Constant(..))) if victory_shader::emit::constant_marks() => { - victory_shader::emit::SLOT_STRIDE_CONSTANT - } - _ => kind, - }; - // 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(entry) }; - } + let (stride, kind) = view.map_or((None, 0), view_stride_and_kind); + // LOCAL (port of fxceless #1216): constant buffer views marked; + // programs read no other non-buffer slot as one. + let entry = match (stride, view) { + (Some(s), _) => s | kind, + (None, Some(View::Constant(..))) if victory_shader::emit::constant_marks() => { + victory_shader::emit::SLOT_STRIDE_CONSTANT + } + _ => kind, + }; + self.write_stride(index, entry); let was = if stride.is_some() { self.buffers.put(index); true @@ -2576,6 +2818,20 @@ impl HostHeap { stale } + /// Writes `word` (stride | format kind) for view-heap slot `index` into + /// the host's [`victory_shader::emit::SLOT_STRIDES`] table. + #[inline] + fn write_stride(&self, index: u32, word: u32) { + if let Some((_, _, data)) = &self.strides + && index < victory_shader::emit::SLOT_STRIDES_COUNT + { + // SAFETY: inside the mapping; shaders read it while we write (a + // single aligned dword: either value is one the slot had, and + // dynamic slots are exclusively owned until submission finishes). + unsafe { (*data as *mut u32).add(index as usize).write_volatile(word) }; + } + } + /// Gives back `n` dynamic slots from `first` (an index [`dynamic`] /// returned). /// @@ -2603,6 +2859,7 @@ impl HostHeap { } self.put(index); self.twin_made(index, kept.is_some() && twinned(view)); + self.write_stride(index, if kept.is_some() { view_stride_word(view) } else { 0 }); self.keep(index, kept.flatten()); } @@ -2635,13 +2892,14 @@ impl HostHeap { } let twin = twinned(&view); let kept = make_twinned(&view, views.slot(at), Some(views.slot(at + 1)))?; + let stride_word = view_stride_word(&view); let listed = Listed { kind: crate::draw::view_kind(&view), texture: is_texture_view(&view), ready: (0, 0, false), tabled: None, }; - views.made.insert(words, ListView { view, at, twin, kept, listed }); + views.made.insert(words, ListView { view, at, twin, stride_word, kept, listed }); } let made = &views.made[&words]; self.copy_from(index, views.slot(made.at)); @@ -2651,6 +2909,7 @@ impl HostHeap { } else { self.clear_twin(index); } + self.write_stride(index, made.stride_word); self.keep(index, made.kept.clone()); Some(made.listed) }) @@ -2675,6 +2934,7 @@ impl HostHeap { } else { null_view(self.at(index)); self.put(index); + self.write_stride(index, 0); } self.clear_twin(index); self.keep(index, None); @@ -2761,6 +3021,7 @@ impl HostHeap { self.put(index); // (Bound by its handle, not read by index.) self.clear_twin(index); + self.write_stride(index, 1); self.keep(index, Some(buffer.clone())); } @@ -2770,6 +3031,7 @@ impl HostHeap { null_buffer_view(self.at(index)); self.put(index); self.clear_twin(index); + self.write_stride(index, 0); self.keep(index, None); } @@ -2804,6 +3066,7 @@ impl HostHeap { }; self.put(index); self.clear_twin(index); + self.write_stride(index, 1); self.keep(index, Some(buffer.clone())); } @@ -2833,6 +3096,7 @@ impl HostHeap { }; self.put(index); self.clear_twin(index); + self.write_stride(index, 0); self.keep(index, None); } @@ -2890,6 +3154,7 @@ impl HostHeap { unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) }; } self.twin_made(index, twin.is_some()); + self.write_stride(index, 0); // After the descriptor: what it showed is let go when nothing shows // it any more. self.keep(index, holds.then(|| buffer.clone())); @@ -4203,24 +4468,27 @@ fn make_twinned( } const BUFFER: u32 = 1; if resource[0] != BUFFER { - // shortcut: unordered access to a texture the title placed - // itself is not mirrored; give it a resource as shader - // views of such textures get when a dispatch writes one. - // Each texture is said once (the first 64), with how many times - // such a view was asked for so far: what shaders write through - // them is lost. - static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new()); - static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; let at = u64::from(desc[10]) | u64::from(desc[11]) << 32; - let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); - if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() { - tracing::warn!( - address = format_args!("{at:#x}"), - times, - "placed unordered texture view not mirrored (null: writes through it are lost): resource {resource:?}, view {:?}", - &desc[..10] - ); + if *unordered || at != 0 { + // shortcut: unordered access to a texture the title placed + // itself is not mirrored; give it a resource as shader + // views of such textures get when a dispatch writes one. + // Each texture is said once (the first 64), with how many times + // such a view was asked for so far: what shaders write through + // them is lost. + static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new()); + static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); + if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() { + tracing::warn!( + address = format_args!("{at:#x}"), + unordered = *unordered, + times, + "placed texture view not mirrored (null): resource {resource:?}, view {:?}", + &desc[..10] + ); + } } return None; } @@ -5827,6 +6095,71 @@ void BY_FLOATS_OR_NOT(uint3 id : SV_DispatchThreadID) { heap.release(last, 1); assert_eq!(heap.dynamic(2), None); } + + #[test] + fn dynamic_slots_populate_and_clear_stride_table() { + use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; + let Some(heap) = HostHeap::new(false, 4) else { + return; // no host GPU + }; + let Some((_, _, data)) = heap.strides else { + panic!("view heap should allocate strides table"); + }; + let read_stride = |slot: u32| -> u32 { + // SAFETY: inside `SLOT_STRIDES_COUNT` mapping of `heap.strides`. + unsafe { *(data as *const u32).add(slot as usize) } + }; + let memory = vec![0u64; 1 << 11]; + let addr = (memory.as_ptr() as u64).next_multiple_of(4096); + let placed_typed = |uav: bool, dxgi_fmt: u32, elems: u32| { + let resource: [u32; 14] = [1, 0, 0, 0, 4096, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0]; + let mut desc = [0u32; 16]; + // [format, dim=1 (buffer), mapping/pad, ..., num_elements @6, stride @7, flags @8] + let words = if uav { + [dxgi_fmt, 1, 0, 0, elems, 0, 0, 0, 0, 0] + } else { + [dxgi_fmt, 1, 5768, 0, 0, 0, elems, 0, 0, 0] + }; + desc[..10].copy_from_slice(&words); + (desc[10], desc[11]) = (addr as u32, (addr >> 32) as u32); + View::Placed(uav, resource, desc) + }; + + let s0 = heap.dynamic(4).unwrap(); + // R16G16B16A16_UINT (12): 8 bytes + VIEW_INTEGER + let u16x4 = placed_typed(true, 12, 64); + heap.make_at(s0, &u16x4); + assert_eq!(read_stride(s0), 8 | VIEW_INTEGER); + + // R16_SINT (59): 2 bytes + VIEW_INTEGER | VIEW_SIGNED + let s16 = placed_typed(false, 59, 64); + heap.make_at(s0 + 1, &s16); + assert_eq!(read_stride(s0 + 1), 2 | VIEW_INTEGER | VIEW_SIGNED); + + // R16G16B16A16_FLOAT (10): 8 bytes, no integer bits + let f16x4 = placed_typed(true, 10, 64); + heap.make_at(s0 + 2, &f16x4); + assert_eq!(read_stride(s0 + 2), 8); + + // Clearing / nulling / raw views overwrite stale bits cleanly. + heap.make_null(s0); + assert_eq!(read_stride(s0), 0); + heap.null_raw_at(s0 + 1); + assert_eq!(read_stride(s0 + 1), 0); + heap.null_raw_uav_at(s0 + 2); + assert_eq!(read_stride(s0 + 2), 0); + + // `make_listed` (both cold creation and cached copy hit) must populate strides. + let mut slot_mem = [0u32; 8]; + crate::descriptor::record(slot_mem.as_mut_ptr() as u64, u16x4); + let rec = [slot_mem[0], slot_mem[1], slot_mem[2]]; + assert!(heap.make_listed(0x1234, rec, s0).is_some()); + assert_eq!(read_stride(s0), 8 | VIEW_INTEGER); + heap.make_null(s0 + 3); + assert_eq!(read_stride(s0 + 3), 0); + assert!(heap.make_listed(0x1234, rec, s0 + 3).is_some()); + assert_eq!(read_stride(s0 + 3), 8 | VIEW_INTEGER); + } } /// What is known of a record a list's tables hold, in that recording of the @@ -5847,6 +6180,7 @@ struct ListView { /// Its descriptor's slot in [`ListViews`]; its raw twin's is the next. at: u32, twin: bool, + stride_word: u32, kept: Kept, listed: Listed, } @@ -5925,3 +6259,74 @@ pub(crate) fn note_listed(recording: u64, words: [u32; 3], listed: Listed) { pub(crate) fn list_views() -> bool { crate::toggled!("VICTORY_LIST_VIEWS") } + +#[cfg(test)] +mod bake_flip_tests { + use super::*; + + #[test] + fn pending_list_flips_promote_once_and_clean_up() { + let heap = 0xdead_beefusize; + let id1 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let id2 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + { + let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + pending.push(PendingListFlip { + id: id1, + origin: (1, 1), + flip: Flip { after: 0, heap, index: 7, handle: 0, key: 11, late: Some(1) }, + }); + pending.push(PendingListFlip { + id: id2, + origin: (2, 1), + flip: Flip { after: 0, heap, index: 8, handle: 0, key: 12, late: Some(1) }, + }); + PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release); + } + let taken = take_pending_list_flip(id1).expect("id1 should be present"); + assert_eq!(taken.index, 7); + assert!(take_pending_list_flip(id1).is_none(), "second take must be a no-op"); + remove_pending_list_flip(id2); + assert!(take_pending_list_flip(id2).is_none(), "removed entry must be gone"); + } + + #[test] + fn deferred_flip_closure_keeps_pending_entry_alive_until_called_or_dropped() { + let heap = 0xcafe_babeusize; + let id1 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let id2 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + { + let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + for (id, idx) in [(id1, 10), (id2, 11)] { + pending.push(PendingListFlip { + id, + origin: (3, 1), + flip: Flip { after: 0, heap, index: idx, handle: 0, key: 20, late: Some(1) }, + }); + } + PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release); + } + struct TestGuard(u64); + impl TestGuard { + fn id(&self) -> u64 { + self.0 + } + } + impl Drop for TestGuard { + fn drop(&mut self) { + remove_pending_list_flip(self.0); + } + } + let make_cb = |id: u64| -> Box<dyn Fn() -> Option<u32> + Send + 'static> { + let guard = TestGuard(id); + Box::new(move || take_pending_list_flip(guard.id()).map(|f| f.index)) + }; + let cb1 = make_cb(id1); + let cb2 = make_cb(id2); + // Must still be present after make_cb returns (guard moved, not dropped). + assert_eq!(cb1(), Some(10)); + assert_eq!(cb1(), None); + drop(cb2); + assert!(take_pending_list_flip(id2).is_none(), "dropping uncalled closure cleans up entry"); + } +} diff --git a/crates/victory-gpu/src/dlss.rs b/crates/victory-gpu/src/dlss.rs new file mode 100644 index 0000000..3133846 --- /dev/null +++ b/crates/victory-gpu/src/dlss.rs @@ -0,0 +1,318 @@ +//! NVIDIA DLSS in place of the title's FidelityFX upscale (Series S, +//! `VICTORY_UPSCALE=dlss`, builds with the `dlss` feature). +//! +//! The title renders below its output size and asks its upscaler to make the +//! output from the colour, depth and motion vectors it rendered, with the +//! camera's jitter: what DLSS takes as well. The title's own FidelityFX passes +//! are slow translated for 32-lane cards (about 150 ms of card time a frame on +//! an RTX 3070 Ti); DLSS runs on the card's tensor cores in a millisecond or +//! two. +//! +//! The SDK (NVIDIA/DLSS on GitHub: `include`, `lib/Windows_x86_64`) is not part +//! of this repository: the build links `nvsdk_ngx_d.lib` from +//! `VICTORY_DLSS_SDK`, and `nvngx_dlss.dll` is looked for in `VICTORY_DLSS_DIR` +//! (else beside the executable). Any failure leaves the caller to stretch. +//! +//! Switches: `VICTORY_DLSS_QUALITY` (0 performance .. 2 quality, 5 DLAA; 2 by +//! default), `VICTORY_DLSS_MV_SIGN=-1` (motion vectors the other way), +//! `VICTORY_DLSS_JITTER_SIGN=-1`, `VICTORY_DLSS_HDR=0|1` (default: by the colour +//! format), `VICTORY_DLSS_DEPTH_INVERTED=0|1` (default: by near > far), +//! `VICTORY_DLSS_SHARPNESS=<0..1>`. + +use std::ffi::{CString, c_char, c_int, c_uint, c_void}; +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::Interface; + +type Result = c_int; +const SUCCESS: Result = 1; +const FEATURE_SUPER_SAMPLING: c_int = 1; +const ENGINE_CUSTOM: c_int = 0; +const VERSION_API: c_int = 0x15; + +const FLAG_HDR: c_int = 1 << 0; +const FLAG_MV_LOW_RES: c_int = 1 << 1; +const FLAG_MV_JITTERED: c_int = 1 << 2; +const FLAG_DEPTH_INVERTED: c_int = 1 << 3; +const FLAG_AUTO_EXPOSURE: c_int = 1 << 6; + +#[repr(C)] +struct PathList { + path: *const *const u16, + length: c_uint, +} + +#[repr(C)] +struct Logging { + callback: *const c_void, + minimum: c_int, + disable_other_sinks: bool, +} + +#[repr(C)] +struct CommonInfo { + paths: PathList, + internal: *const c_void, + logging: Logging, +} + +#[link(name = "nvsdk_ngx_d", kind = "static")] +unsafe extern "C" { + fn NVSDK_NGX_D3D12_Init_with_ProjectID( + project: *const c_char, + engine: c_int, + engine_version: *const c_char, + data_path: *const u16, + device: *mut c_void, + info: *const CommonInfo, + version: c_int, + ) -> Result; + fn NVSDK_NGX_D3D12_GetCapabilityParameters(out: *mut *mut c_void) -> Result; + fn NVSDK_NGX_D3D12_CreateFeature(list: *mut c_void, feature: c_int, params: *mut c_void, out: *mut *mut c_void) -> Result; + fn NVSDK_NGX_D3D12_ReleaseFeature(handle: *mut c_void) -> Result; + fn NVSDK_NGX_D3D12_EvaluateFeature_C(list: *mut c_void, handle: *const c_void, params: *const c_void, callback: *const c_void) -> Result; + fn NVSDK_NGX_Parameter_SetUI(p: *mut c_void, name: *const c_char, value: c_uint); + fn NVSDK_NGX_Parameter_SetI(p: *mut c_void, name: *const c_char, value: c_int); + fn NVSDK_NGX_Parameter_SetF(p: *mut c_void, name: *const c_char, value: f32); + fn NVSDK_NGX_Parameter_SetD3d12Resource(p: *mut c_void, name: *const c_char, value: *mut c_void); + fn NVSDK_NGX_Parameter_GetI(p: *mut c_void, name: *const c_char, out: *mut c_int) -> Result; +} + +/// A parameter name as the SDK spells it. +macro_rules! name { + ($s:literal) => { + concat!($s, "\0").as_ptr().cast::<c_char>() + }; +} + +/// What the title gives an upscale, as the host's resources. +pub(crate) struct Inputs<'a> { + pub colour: &'a ID3D12Resource, + pub depth: Option<&'a ID3D12Resource>, + pub motion: Option<&'a ID3D12Resource>, + pub exposure: Option<&'a ID3D12Resource>, + pub output: &'a ID3D12Resource, + pub jitter: [f32; 2], + pub motion_scale: [f32; 2], + pub render: [u32; 2], + pub reset: bool, + pub pre_exposure: f32, + pub near: f32, + pub far: f32, + pub frame_ms: f32, +} + +struct Feature { + handle: *mut c_void, + /// render width and height the feature was made for, output size, flags + key: [u32; 5], +} + +struct Dlss { + params: *mut c_void, + feature: Option<Feature>, +} + +// SAFETY: the SDK's objects are used under the mutex only. +unsafe impl Send for Dlss {} + +/// `None` until tried; `Some(None)`: unavailable, never tried again. +static DLSS: Mutex<Option<Option<Dlss>>> = Mutex::new(None); + +fn env_f(name: &str, default: f32) -> f32 { + std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default) +} + +fn env_flag(name: &str) -> Option<bool> { + std::env::var(name).ok().map(|v| v.trim() == "1") +} + +fn wide(s: &std::ffi::OsStr) -> Vec<u16> { + use std::os::windows::ffi::OsStrExt; + s.encode_wide().chain([0]).collect() +} + +fn init(device: &ID3D12Device) -> Option<Dlss> { + let dir = std::env::var_os("VICTORY_DLSS_DIR") + .map(std::path::PathBuf::from) + .or_else(|| std::env::current_exe().ok()?.parent().map(|p| p.to_path_buf()))?; + let data = std::env::temp_dir().join("victory-ngx"); + let _ = std::fs::create_dir_all(&data); + let dir_w = wide(dir.as_os_str()); + let data_w = wide(data.as_os_str()); + let paths = [dir_w.as_ptr()]; + let info = CommonInfo { + paths: PathList { path: paths.as_ptr(), length: 1 }, + internal: std::ptr::null(), + logging: Logging { callback: std::ptr::null(), minimum: 0, disable_other_sinks: false }, + }; + let project = CString::new("5e2f9a3c-1b7d-4c8e-9a6f-0d3b2c1e4f57").ok()?; + let version = CString::new("1.0").ok()?; + // SAFETY: live strings and device; the SDK copies what it keeps. + let r = unsafe { + NVSDK_NGX_D3D12_Init_with_ProjectID( + project.as_ptr(), + ENGINE_CUSTOM, + version.as_ptr(), + data_w.as_ptr(), + device.as_raw(), + &info, + VERSION_API, + ) + }; + if r != SUCCESS { + tracing::warn!(result = format_args!("{r:#x}"), dir = %dir.display(), "DLSS: the SDK did not start; the upscale stays a stretch"); + return None; + } + let mut params = std::ptr::null_mut(); + // SAFETY: an out pointer. + let r = unsafe { NVSDK_NGX_D3D12_GetCapabilityParameters(&mut params) }; + if r != SUCCESS || params.is_null() { + tracing::warn!(result = format_args!("{r:#x}"), "DLSS: no capability parameters"); + return None; + } + let mut available = 0; + // SAFETY: live parameters. + unsafe { NVSDK_NGX_Parameter_GetI(params, name!("SuperSampling.Available"), &mut available) }; + if available == 0 { + tracing::warn!("DLSS: super sampling is not available on this card or driver"); + return None; + } + tracing::info!(dir = %dir.display(), "DLSS: started; the title's upscale is DLSS (VICTORY_UPSCALE=dlss)"); + Some(Dlss { params, feature: None }) +} + +/// Records DLSS over `inputs` into `list`; false if it could not (the caller +/// stretches instead). The list's descriptor heaps and root state are the +/// SDK's afterwards: the caller replays the title's. +pub(crate) fn record(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, inputs: &Inputs<'_>) -> bool { + let mut guard = DLSS.lock().unwrap_or_else(|e| e.into_inner()); + let dlss = match guard.get_or_insert_with(|| init(device)) { + Some(d) => d, + None => return false, + }; + // SAFETY: live resources. + let (out, colour) = unsafe { (inputs.output.GetDesc(), inputs.colour.GetDesc()) }; + let render = [ + if inputs.render[0] == 0 { colour.Width as u32 } else { inputs.render[0] }, + if inputs.render[1] == 0 { colour.Height } else { inputs.render[1] }, + ]; + // The feature's input size is the largest the colour texture holds, so + // that a dynamic render size inside it needs no new feature. + let (in_w, in_h) = (colour.Width as u32, colour.Height); + let hdr = env_flag("VICTORY_DLSS_HDR").unwrap_or(matches!(colour.Format.0, 2 | 10 | 26 | 24 | 9)); + let inverted = env_flag("VICTORY_DLSS_DEPTH_INVERTED").unwrap_or(inputs.near > inputs.far); + let mut flags = FLAG_MV_LOW_RES | FLAG_MV_JITTERED; + if hdr { + flags |= FLAG_HDR; + } + if inverted { + flags |= FLAG_DEPTH_INVERTED; + } + if inputs.exposure.is_none() { + flags |= FLAG_AUTO_EXPOSURE; + } + let key = [in_w, in_h, out.Width as u32, out.Height, flags as u32]; + let p = dlss.params; + if dlss.feature.as_ref().is_none_or(|f| f.key != key) { + if let Some(old) = dlss.feature.take() { + // SAFETY: a handle the SDK made. + unsafe { NVSDK_NGX_D3D12_ReleaseFeature(old.handle) }; + } + let quality = env_f("VICTORY_DLSS_QUALITY", 2.0) as c_int; + let mut handle = std::ptr::null_mut(); + // SAFETY: live parameters and an open list. + let r = unsafe { + NVSDK_NGX_Parameter_SetUI(p, name!("CreationNodeMask"), 1); + NVSDK_NGX_Parameter_SetUI(p, name!("VisibilityNodeMask"), 1); + NVSDK_NGX_Parameter_SetUI(p, name!("Width"), in_w); + NVSDK_NGX_Parameter_SetUI(p, name!("Height"), in_h); + NVSDK_NGX_Parameter_SetUI(p, name!("OutWidth"), out.Width as u32); + NVSDK_NGX_Parameter_SetUI(p, name!("OutHeight"), out.Height); + NVSDK_NGX_Parameter_SetI(p, name!("PerfQualityValue"), quality); + NVSDK_NGX_Parameter_SetI(p, name!("DLSS.Feature.Create.Flags"), flags); + NVSDK_NGX_Parameter_SetI(p, name!("DLSS.Enable.Output.Subrects"), 0); + // LOCAL (11/26): `VICTORY_DLSS_PRESET=J|K|L|M`: the model, for every mode (unset: + // the DLL's default; 310.9.16 uses K, the DLSS 4 transformer model, for Quality). + let preset: c_uint = match std::env::var("VICTORY_DLSS_PRESET").as_deref().map(str::trim) { + Ok("J") => 10, + Ok("K") => 11, + Ok("L") => 12, + Ok("M") => 13, + _ => 0, + }; + if preset != 0 { + for mode in [ + name!("DLSS.Hint.Render.Preset.DLAA"), + name!("DLSS.Hint.Render.Preset.Quality"), + name!("DLSS.Hint.Render.Preset.Balanced"), + name!("DLSS.Hint.Render.Preset.Performance"), + name!("DLSS.Hint.Render.Preset.UltraPerformance"), + name!("DLSS.Hint.Render.Preset.UltraQuality"), + ] { + NVSDK_NGX_Parameter_SetUI(p, mode, preset); + } + } + NVSDK_NGX_D3D12_CreateFeature(list.as_raw(), FEATURE_SUPER_SAMPLING, p, &mut handle) + }; + if r != SUCCESS || handle.is_null() { + tracing::warn!(result = format_args!("{r:#x}"), ?key, "DLSS: no feature for these sizes; the upscale stays a stretch"); + *guard = Some(None); + return false; + } + tracing::info!( + input = ?(in_w, in_h), + output = ?(out.Width, out.Height), + hdr, + depth_inverted = inverted, + auto_exposure = inputs.exposure.is_none(), + quality, + colour_format = colour.Format.0, + "DLSS: feature made" + ); + dlss.feature = Some(Feature { handle, key }); + } + let Some(feature) = dlss.feature.as_ref() else { return false }; + let mv = env_f("VICTORY_DLSS_MV_SIGN", 1.0); + let jit = env_f("VICTORY_DLSS_JITTER_SIGN", 1.0); + let raw = |r: Option<&ID3D12Resource>| r.map_or(std::ptr::null_mut(), |r| r.as_raw()); + let scale = |s: f32| if s == 0.0 { 1.0 } else { s }; + // SAFETY: live parameters, resources and feature; an open list. + let r = unsafe { + NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("Color"), inputs.colour.as_raw()); + NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("Output"), inputs.output.as_raw()); + NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("Depth"), raw(inputs.depth)); + NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("MotionVectors"), raw(inputs.motion)); + NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("ExposureTexture"), raw(inputs.exposure)); + NVSDK_NGX_Parameter_SetF(p, name!("Jitter.Offset.X"), jit * inputs.jitter[0]); + NVSDK_NGX_Parameter_SetF(p, name!("Jitter.Offset.Y"), jit * inputs.jitter[1]); + NVSDK_NGX_Parameter_SetF(p, name!("MV.Scale.X"), mv * scale(inputs.motion_scale[0])); + NVSDK_NGX_Parameter_SetF(p, name!("MV.Scale.Y"), mv * scale(inputs.motion_scale[1])); + NVSDK_NGX_Parameter_SetI(p, name!("Reset"), inputs.reset as c_int); + NVSDK_NGX_Parameter_SetF(p, name!("Sharpness"), env_f("VICTORY_DLSS_SHARPNESS", 0.0)); + NVSDK_NGX_Parameter_SetF(p, name!("DLSS.Pre.Exposure"), if inputs.pre_exposure > 0.0 { inputs.pre_exposure } else { 1.0 }); + NVSDK_NGX_Parameter_SetF(p, name!("FrameTimeDeltaInMsec"), inputs.frame_ms); + NVSDK_NGX_Parameter_SetUI(p, name!("DLSS.Render.Subrect.Dimensions.Width"), render[0].min(in_w)); + NVSDK_NGX_Parameter_SetUI(p, name!("DLSS.Render.Subrect.Dimensions.Height"), render[1].min(in_h)); + NVSDK_NGX_D3D12_EvaluateFeature_C(list.as_raw(), feature.handle, p, std::ptr::null()) + }; + if r != SUCCESS { + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| tracing::warn!(result = format_args!("{r:#x}"), "DLSS: an evaluation failed; that upscale is a stretch")); + return false; + } + // LOCAL (11/26): DLSS Frame Generation's inputs (`VICTORY_FRAME_GEN`), in the state the + // upscale read them in. + if crate::fg::active() { + crate::fg::tag( + [render[0].min(in_w), render[1].min(in_h)], + [jit * inputs.jitter[0], jit * inputs.jitter[1]], + [mv * scale(inputs.motion_scale[0]), mv * scale(inputs.motion_scale[1])], + inputs.near, + inputs.far, + inputs.reset, + ); + } + true +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 567e472..c97e032 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -24,6 +24,94 @@ use crate::host::HostList; use crate::object::This; use crate::pipeline::host::HostPipeline; +/// Shader interface metadata shared by every pipeline variant and draw. +pub(crate) struct TablePlan { + groups: Vec<TableGroup>, + // Direct entries can interleave slots. Preserve their declaration order + // when recording resource reads, writes, and transitions. + direct: Vec<(usize, usize)>, +} + +struct TableGroup { + slot: u8, + has_cbv: bool, + has_uav: bool, + max_dword: u32, + entries: Vec<UsedResource>, + indexed: Vec<RootIndexedView>, + // Descriptor number -> first declaration, matching the bind-time search. + by_descriptor: Vec<(u32, usize)>, +} + +impl TablePlan { + pub(crate) fn new(used: &[UsedResource], indexed: &[RootIndexedView]) -> Self { + let mut slots: Vec<_> = used + .iter() + .filter(|u| u.root == RootType::Table) + .map(|u| u.slot) + .collect(); + slots.sort_unstable(); + slots.dedup(); + let mut groups: Vec<_> = slots + .iter() + .map(|&slot| TableGroup { + slot, + has_cbv: false, + has_uav: false, + max_dword: 0, + entries: Vec::new(), + by_descriptor: Vec::new(), + indexed: indexed.iter().filter(|v| v.table_slot == slot).copied().collect(), + }) + .collect(); + let mut direct = Vec::new(); + for &u in used.iter().filter(|u| u.root == RootType::Table) { + let i = slots + .binary_search(&u.slot) + .expect("table slot collected from these declarations"); + let group = &mut groups[i]; + group.has_cbv |= u.kind == ResourceType::Cbv; + group.has_uav |= u.kind == ResourceType::Uav; + group.max_dword = group.max_dword.max(u.table_offset_dwords); + direct.push((i, group.entries.len())); + group + .by_descriptor + .push((u.table_offset_dwords / 8, group.entries.len())); + group.entries.push(u); + } + for group in &mut groups { + group.by_descriptor.sort_unstable(); + group.by_descriptor.dedup_by_key(|item| item.0); + } + Self { groups, direct } + } +} + +impl TableGroup { + fn entry(&self, descriptor: u32) -> Option<&UsedResource> { + let i = self + .by_descriptor + .binary_search_by_key(&descriptor, |item| item.0) + .ok()?; + Some(&self.entries[self.by_descriptor[i].1]) + } + + fn needs_snapshot(&self, heap: &crate::descriptor::Heap, host_count: u32, table: u64) -> bool { + let index_at = |dword: u32| { + table + .checked_add(u64::from(dword) * 4) + .and_then(|end| heap.index(end)) + }; + match index_at(self.max_dword) { + Some(i) => i >= host_count, + None => self + .entries + .iter() + .any(|u| index_at(u.table_offset_dwords).is_some_and(|i| i >= host_count)), + } + } +} + /// A root argument as the title set it. #[derive(Debug, Clone, Default)] enum Root { @@ -69,7 +157,7 @@ thread_local! { /// While `State::early_textures` runs the texture pass: the /// milliseconds and the bytes that run may take, in place of the /// pass's own per frame. - static PASS_BUDGET: std::cell::Cell<Option<(u64, u64)>> = const { std::cell::Cell::new(None) }; + static PASS_BUDGET: std::cell::Cell<Option<(u64, u64, bool)>> = const { std::cell::Cell::new(None) }; } /// The milliseconds of every frame the pass that uploads textures picked @@ -129,12 +217,45 @@ const BAKE_AHEAD: [u64; 2] = [12, 2]; /// until something is new, the next bakes of the frame need no pass. static BAKE_SERVED: AtomicU64 = AtomicU64::new(0); +/// Free-threaded wrapper around a reusable upload-only [`HostList`] protected +/// by [`BAKE_UPLOAD`]. D3D12 command allocators, lists, and retained COM +/// resources are free-threaded when externally synchronized. +struct BakeList(HostList); +// SAFETY: accessed exclusively under `BAKE_UPLOAD`'s mutex. +unsafe impl Send for BakeList {} + +/// Serializes synchronous one-shot ped/decoration bake uploads across +/// concurrent `VICTORY_THIN=1` recording threads and owns the reusable +/// upload-only host command list. +static BAKE_UPLOAD: std::sync::Mutex<Option<BakeList>> = std::sync::Mutex::new(None); + +/// Pending descriptor publications for a synchronous bake upload pass: slots +/// stay on `neutral()` (or their previous compatible view) until the dedicated +/// upload list has finished executing on the host GPU. +struct BakeSync { + publish: Vec<(u32, u64, u64)>, + keep: Vec<std::sync::Arc<crate::resource::HostTexture>>, +} + /// The pixel shaders of the title's decoration bake (the title: /// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the /// frame listings print it. They draw into a 256x256 corner of 2048x2048 /// targets and name no texture in a table. -const BAKE_PIXEL_SHADERS: [&str; 4] = - ["c0a7fe77b1862e10", "0d1575a396dfe513", "b7cfd8dda91ebb6b", "280967ad158cee0b"]; +pub(crate) const BAKE_PIXEL_SHADERS: [&str; 7] = [ + "c0a7fe77b1862e10", + "0d1575a396dfe513", + "b7cfd8dda91ebb6b", + "280967ad158cee0b", + "fa455c8a3c32577b", + "d126bcae5d5d8d26", + "fcee612943c008e0", +]; + +/// Geometry stages shared by every ped texture compositor / decoration bake +/// permutation (`vertex 089d6271be6650ef` fullscreen-triangle ped baker and +/// `mesh d4111a6e6ea49d91` decoration projection mesh), catching pixel-shader +/// permutations beyond `BAKE_PIXEL_SHADERS`. +const BAKE_GEOMETRY_SHADERS: [&str; 2] = ["089d6271be6650ef", "d4111a6e6ea49d91"]; /// Since the start: early runs of the texture pass, and those of them /// made for a bake draw. @@ -338,6 +459,7 @@ pub(crate) struct State { /// Graphics, compute. host_roots: [usize; 2], host_heaps: [usize; 2], + host_heaps_set: bool, /// Tables made afresh in this list: (table, slot count, contents) → first /// dynamic slot. fresh_tables: std::collections::HashMap<(u64, u32, u64), FreshTable, std::hash::BuildHasherDefault<crate::host::AddressHash>>, @@ -515,6 +637,20 @@ fn heap_spread() -> bool { #[derive(Default)] struct HeapRanges<T>(Vec<Option<(T, u64, u64)>>); +/// Descriptor-derived references belong to the heap that produced them. +pub(crate) struct BufferSweep { + passes: u64, + ranges: HeapRanges<std::sync::Arc<crate::shadow::Shadow>>, + // Last refresh frame and covered interval for throttled, unwatched copies. + unwatched: std::collections::HashMap<u64, (u64, u64, u64)>, +} + +impl Default for BufferSweep { + fn default() -> Self { + Self { passes: 0, ranges: HeapRanges(Vec::new()), unwatched: Default::default() } + } +} + impl<T> HeapRanges<T> { fn set(&mut self, slot: u32, range: Option<(T, u64, u64)>) { let slot = slot as usize; @@ -655,6 +791,16 @@ fn reupload_when_full() -> bool { /// Whether textures picked by index are looked at again after their upload /// (`VICTORY_HEAP_RECHECK=0`: no). +/// LOCAL (11/26): `VICTORY_HEAP_RECHECK_EVERY=<frames>`: textures picked by index are looked at +/// again that often after the usual looks (`RECHECK_FRAMES`), all run; 0 or unset: not. +fn heap_recheck_every() -> u64 { + static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *EVERY.get_or_init(|| std::env::var("VICTORY_HEAP_RECHECK_EVERY").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) +} + +/// LOCAL (11/26): changes found by those later looks, since the start. +pub(crate) static HEAP_TEXTURES_LATE: AtomicU64 = AtomicU64::new(0); + fn heap_recheck() -> bool { static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_RECHECK").is_none_or(|v| v != "0")) @@ -754,14 +900,8 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho // at best); all of them every 16 passes, because a view of a // released resource goes stale without a write, and a slot written // before its memory had a host copy is only made then. - type Ranges = HeapRanges<std::sync::Arc<crate::shadow::Shadow>>; - static RANGES: std::sync::Mutex<Option<std::collections::HashMap<usize, (u64, Ranges)>>> = - std::sync::Mutex::new(None); - let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); - let (passes, ranges) = kept - .get_or_insert_with(Default::default) - .entry(std::ptr::from_ref(host) as usize) - .or_insert_with(|| (0, HeapRanges(Vec::new()))); + let mut kept = host.buffer_sweep.lock().unwrap_or_else(|e| e.into_inner()); + let BufferSweep { passes, ranges, unwatched } = &mut *kept; let changed = host.buffer_changes(); let all = *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread()); let slots = if all { @@ -857,7 +997,6 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho span.1 = span.1.min(*from); span.2 = span.2.max(*to); } - drop(kept); let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum(); // Memory that is not write-watched is copied whole by every refresh. // It was once refreshed only every 120 frames (unmapped pages read @@ -866,32 +1005,27 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho // the garbage ended runs (the card stopped answering 14-90 frames // into the opening cutscene; with every frame it ran on). The pass // costs some 30 ms a frame this way. - static WHOLE: std::sync::Mutex<Option<std::collections::HashMap<usize, u64>>> = std::sync::Mutex::new(None); - let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); - let whole = whole.get_or_insert_with(Default::default); + static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + let every = *EVERY.get_or_init(|| { + std::env::var("VICTORY_UNWATCHED_FRAMES").ok().and_then(|v| v.parse().ok()).unwrap_or(1) + }); let mut found = Vec::with_capacity(spans.len()); + let mut next_unwatched = std::collections::HashMap::new(); for (shadow, from, to) in spans.values() { - if shadow.unwatched() { - // By the copy's number: a copy made where one let go was - // (`shadow::let_go_idle`) has never been refreshed. - let key = shadow.id() as usize; - // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame). - static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); - let every = *EVERY.get_or_init(|| { - std::env::var("VICTORY_UNWATCHED_FRAMES") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(1) - }); - match whole.get(&key) { - Some(&last) if frame < last + every => continue, - _ => { - whole.insert(key, frame); - } + if every > 1 && shadow.unwatched() { + let id = shadow.id(); + if let Some(&(last, low, high)) = unwatched.get(&id) + && frame >= last && frame - last < every && low <= *from && *to <= high + { + next_unwatched.insert(id, (last, low, high)); + continue; } + next_unwatched.insert(id, (frame, *from, *to)); } found.push((shadow.clone(), *from, (*to).min(*from + shadow.left(*from)))); } + *unwatched = next_unwatched; + drop(kept); #[cfg(feature = "diagnostics")] let refreshed = std::time::Instant::now(); crate::watch::look_at_holes(); @@ -1157,6 +1291,7 @@ impl State { self.host_pipeline = 0; self.host_roots = [0; 2]; self.host_heaps = [0; 2]; + self.host_heaps_set = false; if self.topology_set { self.set_topology(list, self.topology); } @@ -1457,19 +1592,44 @@ impl State { self.heaps[0] = heap; } // Heaps first: a root signature with directly indexed heaps must be - // set after them. - if self.host_heaps != self.heaps { - let heaps: Vec<Option<ID3D12DescriptorHeap>> = self - .heaps - .iter() - .filter(|&&h| h != 0) - .filter_map(|&h| crate::descriptor::heap(h as This).host()) - .map(|h| Some(h.heap.clone())) - .collect(); - heaps.iter().flatten().for_each(|h| list.keep(h)); - // SAFETY: an open list and shader-visible heaps. - unsafe { l.SetDescriptorHeaps(&heaps) }; + // set after them, with both a view heap and a sampler heap bound. + if !self.host_heaps_set || self.host_heaps != self.heaps { + let mut view_heap: Option<ID3D12DescriptorHeap> = None; + let mut sampler_heap: Option<ID3D12DescriptorHeap> = None; + for &h in &self.heaps { + if h == 0 { + continue; + } + let title_heap = crate::descriptor::heap(h as This); + if let Some(host_heap) = title_heap.host() { + if title_heap.samplers() { + sampler_heap = Some(host_heap.heap.clone()); + } else { + view_heap = Some(host_heap.heap.clone()); + } + } + } + if view_heap.is_none() { + view_heap = crate::host::host().and_then(|h| h.fallback_view_heap().cloned()); + } + if sampler_heap.is_none() { + sampler_heap = crate::host::host().and_then(|h| h.fallback_sampler_heap().cloned()); + } + let mut heaps: Vec<Option<ID3D12DescriptorHeap>> = Vec::with_capacity(2); + if let Some(h) = view_heap { + list.keep(&h); + heaps.push(Some(h)); + } + if let Some(h) = sampler_heap { + list.keep(&h); + heaps.push(Some(h)); + } + if !heaps.is_empty() { + // SAFETY: an open list and shader-visible heaps. + unsafe { l.SetDescriptorHeaps(&heaps) }; + } self.host_heaps = self.heaps; + self.host_heaps_set = true; self.host_roots = [0; 2]; } // The depth target a draw only tests, for the views of it that the @@ -1507,13 +1667,7 @@ impl State { if t.stores && crate::picked::on() && crate::picked::picks(&stage.shader, &t.picks) { crate::picked::runs_in(list); } - let made = self.tables( - list, - &t.used, - &t.host.root_indexed_views, - &t.host.half_views, - compute, - ); + let made = self.tables(list, &t.tables, &t.host.half_views, compute); STORES.set(true); if made.iter().any(|m| m.1 == u32::MAX) { once!("a draw whose descriptor table found no free slots is dropped"); @@ -1617,6 +1771,24 @@ impl State { } continue; } + if srv && slot == victory_shader::emit::SLOT_TABLE_STRIDES { + // Ours: the shader inspects typed view kinds for its + // descriptor tables only (already mirrored by `tables`), + // so bind the strides buffer without sweeping the heap. + match self.heap_strides(list) { + // SAFETY: an open list; the table lives as long + // as the heap the list holds. + Some(gpu) => unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, gpu); + } else { + l.SetGraphicsRootShaderResourceView(param, gpu); + } + }, + None => once!("a shader inspects table view kinds without a view heap set"), + } + continue; + } let tabled = srv && crate::pipeline::host::bounded_root_srvs(); let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) else { @@ -1775,7 +1947,10 @@ impl State { Some((index, shadow)) => (*index, address.zip(shadow.clone())), None => { let shadow = address.and_then(|a| find(a).map(|s| (a, s))); - let Some(index) = host.dynamic(1) else { + let Some(index) = host.dynamic(1).or_else(|| { + crate::host::settle_for_fence(); + host.dynamic(1) + }) else { return false; }; self.dynamic.push((key.0, index, 1)); @@ -1846,7 +2021,10 @@ impl State { Some((index, shadow)) => (*index, address.zip(shadow.clone())), None => { let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s))); - let Some(index) = host.dynamic(1) else { + let Some(index) = host.dynamic(1).or_else(|| { + crate::host::settle_for_fence(); + host.dynamic(1) + }) else { return false; }; self.dynamic.push((key.0, index, 1)); @@ -1917,9 +2095,9 @@ impl State { .find(|h| !h.samplers())?; let host = heap.host()?; let gpu = host.strides_gpu()?; - // One key per list, as textures have: no title resource is there. - const ONCE: usize = usize::MAX - 0x5e; - if !list.first_use(ONCE) { + // Stride buffers have aligned GPU addresses. Tag the list key so it + // is distinct from aligned guest resource pointers. + if !list.first_use(gpu as usize | 1) { return Some(gpu); } // The list may outlive the title's heap object, which owns the table. @@ -1931,9 +2109,8 @@ impl State { // frame (2026-11-24, run 11). // shortcut: what the title writes into such buffers between lists // of one frame is seen a frame late. - static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); let frame = crate::frame::current(); - if FRAME.swap(frame, Ordering::Relaxed) == frame { + if host.buffer_frame.swap(frame, Ordering::Relaxed) == frame { return Some(gpu); } let started = std::time::Instant::now(); @@ -1941,7 +2118,11 @@ impl State { if crate::host::aside::on() { let at = std::ptr::from_ref(heap) as usize; list.refreshes_coming(move || { - crate::descriptor::with_heap(at, |heap| heap.host().map(|host| heap_buffer_pass(heap, host, frame))) + crate::descriptor::with_heap(at, |heap| { + // The list retains the original stride buffer. A newly + // allocated heap at the same CPU address has another one. + heap.host().filter(|h| h.strides_gpu() == Some(gpu)).map(|h| heap_buffer_pass(heap, h, frame)) + }) .flatten() .unwrap_or_default() }); @@ -1953,7 +2134,7 @@ impl State { #[cfg(feature = "diagnostics")] let refreshed = std::time::Instant::now(); stage.next("the heap pass: textures"); - self.heap_textures(list, heap, host); + let _ = self.heap_textures(list, heap, host, None); stage.end(); #[cfg(feature = "diagnostics")] HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed); @@ -1962,20 +2143,179 @@ impl State { Some(gpu) } + /// The GPU address of the bound view heap's stride/kind table without + /// running the bindless heap buffer/texture sweep (for shaders that only + /// inspect descriptors already mirrored via their descriptor tables). + fn heap_strides(&self, list: &HostList) -> Option<u64> { + let heap = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers())?; + let host = heap.host()?; + let gpu = host.strides_gpu()?; + // Tag bit 1 (distinct from `heap_buffers`'s `| 1` and aligned guest pointers). + if list.first_use(gpu as usize | 2) + && let Some(buffer) = host.strides_buffer() + { + list.keep(buffer); + } + Some(gpu) + } + + /// Ensures textures claimed by background copy-queue uploads + /// (`VICTORY_UPLOAD_AHEAD=1`) or deferred behind the `neutral()` gray + /// stand-in (`VICTORY_SHOW_AFTER=1` / `shows_other`) have finished + /// uploading and flipped to their real descriptors before a one-shot + /// decoration bake draw samples them. + fn flush_for_bake( + &self, + list: &HostList, + host: &crate::descriptor::host::HostHeap, + mut sync: Option<&mut BakeSync>, + ) { + static RESCUED: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + let drained = crate::texture::ahead::drain(); + let mut settled = false; + let mut flipped = 0usize; + for _ in 0..4 { + let need_settle = host.needs_gpu_settle_for_bake(); + if need_settle { + settled = true; + crate::host::settle_for_fence(); + } + flipped += host.texture_views_remade(); + flipped += host.texture_slots_flip(); + if !need_settle || !host.needs_gpu_settle_for_bake() { + break; + } + } + let pending = host.take_pending_list_flips(); + let mut promoted = 0usize; + if !pending.is_empty() { + let this_list = (std::ptr::from_ref(list) as usize, list.epoch()); + let sampled = UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }; + for item in pending { + let (origin, index, handle, key) = (item.origin, item.index(), item.handle(), item.key()); + if !host.slot_still_at(handle, key) { + continue; + } + let Some(view) = crate::descriptor::view(handle) else { + continue; + }; + if let View::Placed(_, resource, desc) = &view { + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let len = crate::resource::placed_bytes(resource).unwrap_or(1); + if crate::texture::mapped_bytes(address as *const u8, len as usize) == 0 { + host.restore_pending_list_flip(item); + continue; + } + } + if sync.is_some() || origin != this_list { + let placed = crate::descriptor::host::placed_texture(&view); + if let Some(&View::Shader(resource, _)) = placed.as_ref().or(Some(&view)) { + let resource = resource as This; + let texture = crate::resource::host_resource(resource); + let title_fills = texture.is_some_and(crate::texture::title_written); + let first = match (&placed, &view) { + (Some(_), View::Placed(_, _, desc)) => crate::resource::first_mip(desc), + _ => 0, + }; + if let (Some(sync), Some(copy)) = (sync.as_deref_mut(), crate::resource::host_copy(resource)) { + sync.keep.push(copy); + } + if title_fills + && !crate::texture::ahead::there(resource) + && (sync.is_some() || !crate::texture::unchanged(resource, first)) + { + let was_staged = crate::texture::is_staged(resource); + let _ = crate::residency::take_staging_deferred(); + readable(list, sampled.kind, &view); + let failed = crate::residency::take_staging_deferred() || crate::residency::upload_refused(); + if !was_staged { + crate::texture::unstage(resource); + } + if failed { + host.restore_pending_list_flip(item); + continue; + } + } + } + } + if let Some(sync) = sync.as_deref_mut() { + sync.publish.push((index, handle, key)); + } else { + let _ = host.mirror(index, handle, true); + } + promoted += 1; + } + } + if drained > 0 || settled || flipped > 0 || promoted > 0 { + let n = RESCUED[0].fetch_add(1, Ordering::Relaxed) + 1; + let all_drained = RESCUED[1].fetch_add(drained as u64, Ordering::Relaxed) + drained as u64; + let all_flipped = RESCUED[2].fetch_add(flipped as u64, Ordering::Relaxed) + flipped as u64; + let all_promoted = RESCUED[3].fetch_add(promoted as u64, Ordering::Relaxed) + promoted as u64; + if n.is_power_of_two() { + tracing::info!( + frame = crate::frame::current(), + flushes = n, + drained_ahead = all_drained, + flipped = all_flipped, + promoted_from_lists = all_promoted, + settled, + "flushed deferred texture stand-ins before decoration bake" + ); + } + } + } + + /// Whether a graphics draw is a one-shot texture compositor / decoration + /// bake whose bindless texture inputs must be flushed and up to date + /// before recording the draw. Matches known bake pixel/geometry shaders + /// and structurally detects depth-less 4+ MRT square atlas bakes + /// (`>= 512x512`) so unseen NPC/head/clothing shader permutations never + /// bake `neutral()` or `null` stand-ins into permanent ped textures. + fn is_bake_draw(&self, p: &HostPipeline) -> bool { + if p.stages.iter().any(|s| { + let h = s.shader.hash.as_str(); + BAKE_PIXEL_SHADERS.contains(&h) || BAKE_GEOMETRY_SHADERS.contains(&h) + }) { + return true; + } + self.depth == 0 + && self.targets.len() >= 4 + && self + .targets + .first() + .and_then(|&t| crate::resource::texture_kind(t as This)) + .is_some_and(|(w, h, _)| w >= 512 && w == u64::from(h)) + } + /// Runs the pass that uploads textures picked by index /// ([`State::heap_textures`]) where nothing has asked for it yet /// ([`early_budgets`]): once a frame for a few milliseconds, at the /// frame's first draw with a view heap set, and with a larger budget /// of its own before every draw whose pixel shader is one of the - /// title's bake programs. The uploads are recorded into `list` ahead - /// of the draw being bound, as the world's pass records them. + /// title's bake programs. For decoration bakes, uploads run synchronously + /// on a dedicated internal command list and descriptors are published only + /// after the GPU copy finishes so concurrent `VICTORY_THIN=1` lists can + /// never submit a bake draw ahead of its texture uploads. fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) { let (early_ms, bake_ms) = early_budgets(); if compute || (early_ms == 0 && bake_ms == 0) { return; } - let bake = bake_ms > 0 - && p.stages.iter().any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str())); + let is_bake = bake_ms > 0 && self.is_bake_draw(p); static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); // The milliseconds this frame's bake draws have taken so far: a // frame has several, and together they get `bake_ms`. @@ -1985,15 +2325,9 @@ impl State { if first { BAKED_MS.store(0, Ordering::Relaxed); } - let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); - let budget = if bake && left > 0 { - // What a bake may read must be there now: up to 2 GiB. - (left, 2 << 30) - } else if first && early_ms > 0 { - (early_ms, 64 << 20) - } else { + if !is_bake && !(first && early_ms > 0) { return; - }; + } let Some(heap) = self .heaps .iter() @@ -2006,34 +2340,102 @@ impl State { let Some(host) = heap.host() else { return; }; - let bake = bake && left > 0; - if bake && !first && bake_exact() { - let (writes, noted) = host.texture_news(); - if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 { + if is_bake { + let began = std::time::Instant::now(); + let mut bake_slot = BAKE_UPLOAD.lock().unwrap_or_else(|e| e.into_inner()); + let gpu = crate::host::host(); + if bake_slot.is_none() + && let Some(gpu) = gpu + { + match gpu.new_list() { + Ok(upload_list) => *bake_slot = Some(BakeList(upload_list)), + Err(e) => tracing::warn!(error = %e, "no host list for synchronous bake uploads"), + } + } + let exact = bake_exact(); + if let (Some(gpu), Some(BakeList(bake_list))) = (gpu, bake_slot.as_ref()) { + let mut sync = BakeSync { publish: Vec::new(), keep: Vec::new() }; + crate::texture::BAKING.set(exact); + self.flush_for_bake(bake_list, host, Some(&mut sync)); + let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); + let run_pass = left > 0 + && (first + || !exact + || { + let (writes, noted) = host.texture_news(); + noted || BAKE_SERVED.load(Ordering::Relaxed) != writes + 1 + }); + let mut served = false; + if run_pass { + let n = EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); + tracing::info!( + frame, + bakes = n, + queued_at_the_last_pass = slots, + due_at_the_last_pass = due, + uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed), + "a draw of the title's decoration bake: textures picked by index are uploaded synchronously first (VICTORY_BAKE_TEXTURES_MS=0: not)" + ); + } + BAKE_SERVED.store(0, Ordering::Relaxed); + PASS_BUDGET.set(Some((left, 2 << 30, true))); + served = self.heap_textures(bake_list, heap, host, Some(&mut sync)); + PASS_BUDGET.set(None); + } + crate::texture::BAKING.set(false); + if bake_list.has_recorded_work() { + bake_list.close(); + gpu.execute_sync_internal(bake_list); + bake_list.reset(); + } else if !sync.publish.is_empty() { + crate::host::settle_for_fence(); + } + for (index, handle, key) in sync.publish { + let _ = host.publish_uploaded_slot(index, handle, key); + } + host.texture_views_remade(); + host.texture_slots_flip(); + drop(sync.keep); + if run_pass && served && exact { + BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed); + } + BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); return; } - } - let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1; - if bake && n.is_power_of_two() { - let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); - tracing::info!( - frame, - bakes = n, - queued_at_the_last_pass = slots, - due_at_the_last_pass = due, - uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed), - "a draw of the title's decoration bake: textures picked by index are uploaded first (VICTORY_BAKE_TEXTURES_MS=0: not)" - ); - } - let began = std::time::Instant::now(); - PASS_BUDGET.set(Some(budget)); - crate::texture::BAKING.set(bake && bake_exact()); - self.heap_textures(list, heap, host); - crate::texture::BAKING.set(false); - PASS_BUDGET.set(None); - if bake { + // Fallback when no host GPU list can be created (e.g. headless tests). + crate::texture::BAKING.set(exact); + self.flush_for_bake(list, host, None); + crate::texture::BAKING.set(false); + let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); + if left == 0 { + return; + } + if !first && exact { + let (writes, noted) = host.texture_news(); + if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 { + return; + } + } + EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed); + PASS_BUDGET.set(Some((left, 2 << 30, true))); + crate::texture::BAKING.set(exact); + let _ = self.heap_textures(list, heap, host, None); + crate::texture::BAKING.set(false); + PASS_BUDGET.set(None); BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); + return; } + let budget = if first && early_ms > 0 { + (early_ms, 64 << 20) + } else { + return; + }; + EARLY_TEXTURE_PASSES[0].fetch_add(1, Ordering::Relaxed); + PASS_BUDGET.set(Some((budget.0, budget.1, false))); + let _ = self.heap_textures(list, heap, host, None); + PASS_BUDGET.set(None); } /// The queue's side of the card accounting line @@ -2130,10 +2532,11 @@ impl State { list: &HostList, heap: &crate::descriptor::Heap, host: &crate::descriptor::host::HostHeap, - ) { + mut sync: Option<&mut BakeSync>, + ) -> bool { static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) { - return; + return true; } let memory = crate::host::host().and_then(|h| h.video_memory()); // `VICTORY_TEXTURE_STAGE_MB` sets it: a backlog of tens of thousands of @@ -2144,7 +2547,14 @@ impl State { }); let per_frame = match asked { Some(mb) => mb << 20, - None => staging_budget_per_frame(memory.map(|[budget, ..]| budget)), + None => { + let base = staging_budget_per_frame(memory.map(|[budget, ..]| budget)); + if crate::residency::limited_host_ram() { + base.min(128 << 20) + } else { + base + } + } }; static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); static SPENT: AtomicU64 = AtomicU64::new(0); @@ -2178,6 +2588,10 @@ impl State { // Slots whose texture's memory the runtime mapped, unmapped or // wrote since the last pass are due again. host.texture_slots_remapped(frame); + let baking = crate::texture::BAKING.get(); + if baking { + host.texture_slots_bake_written(frame); + } host.texture_slots_short(frame); // The slots of textures whose first level with memory (levels on // demand), or whose host copy for one with more levels, changed since @@ -2190,7 +2604,7 @@ impl State { if room { host.texture_slots_waiting(frame); } - let baking = crate::texture::BAKING.get(); + let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake); let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 }); // (Those that are due later after all that are due.) let on_time = due.len(); @@ -2259,13 +2673,29 @@ impl State { // own: its bytes on top of what the frame has spent so far. // (Not `most`: that is the longest wait between looks, used below.) let (span, bytes_at_most) = match PASS_BUDGET.get() { - Some((ms, bytes)) => { + Some((ms, bytes, _)) => { (std::time::Duration::from_millis(ms), SPENT.load(Ordering::Relaxed).saturating_add(bytes)) } None => (span, per_frame), }; + // Apply the shared frame ceiling after early-pass and catch-up budgets. + // A bake samples its inputs immediately and cannot retry that draw. + let bytes_at_most = if required || asked.is_some() { + bytes_at_most + } else { + crate::residency::prefetch_limit( + bytes_at_most, + crate::residency::pressured(), + crate::residency::critical_commit(), + crate::residency::limited_host_ram(), + crate::texture::live_staging_bytes(), + ) + }; + let began = std::time::Instant::now(); - BAKE_SERVED.store(0, Ordering::Relaxed); + if sync.is_none() { + BAKE_SERVED.store(0, Ordering::Relaxed); + } let mut served = true; for (index, write) in due { if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span { @@ -2304,10 +2734,36 @@ impl State { Some(wait) => { host.texture_slot_recheck(index, write, frame + wait, (at, len), print, looks + 1, uploaded) } + // LOCAL (11/26, oil hunt): `VICTORY_HEAP_RECHECK_EVERY=<frames>`: after the + // last look, looked at again that often for the rest of the run. + None if heap_recheck_every() > 0 => host.texture_slot_recheck( + index, + write, + frame + heap_recheck_every(), + (at, len), + print, + looks, + uploaded, + ), None => host.texture_slot_done(index, write, None), } continue; } + if usize::from(looks) + 1 >= RECHECK_FRAMES.len() { + // A change after the last of the usual looks: one the build kept from + // the screen for the rest of the run before. + let n = HEAP_TEXTURES_LATE.fetch_add(1, Ordering::Relaxed); + if n < 300 { + tracing::warn!( + slot = index, + address = format_args!("{at:#x}"), + bytes = len, + frames_after_upload = frame.saturating_sub(uploaded), + late = n + 1, + "a texture picked by index changed after the last usual look (VICTORY_HEAP_RECHECK_EVERY): uploaded again" + ); + } + } if recheck_soon() { again_in = 1; } @@ -2412,27 +2868,49 @@ impl State { ); } } + // Gate new host texture creation / staging on commit reserve after + // `mapped == 0` reclamation (`texture_slot_gone`) has run, and + // before mirroring a slot to an unuploaded texture. + if !crate::residency::admit_texture_pass(required) { + served = false; + break; + } // A slot that shows the texture by an earlier view of it (one // from another level) goes on doing so until the upload of what // the new one shows has run. + let sync_bake = sync.is_some(); let shows_other = !baking + && !sync_bake && crate::resource::held_only() && heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle)); // A slot that shows nothing of it yet, or something else, shows it // when the upload has run too. let late = !shows_other && !baking + && !sync_bake && crate::descriptor::host::show_after() && heap.handle(index).is_some_and(|handle| !host.texture_slot_made_from(index, handle)); - let view = heap.handle(index).and_then(|handle| { - if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) } - }); + let (view, bake_key) = if sync_bake { + match heap.handle(index).and_then(|handle| host.prepare_bake_slot(index, handle)) { + Some((view, key)) => (Some(view), Some(key)), + None => (None, None), + } + } else { + let view = heap.handle(index).and_then(|handle| { + if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) } + }); + (view, None) + }; let at_once = || { - if late && let Some(handle) = heap.handle(index) { + if (late || bake_key.is_some()) && let Some(handle) = heap.handle(index) { let _ = host.mirror(index, handle, true); } }; let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); + if crate::residency::upload_refused() { + served = false; + break; + } let resource = match placed.as_ref().or(view.as_ref()) { Some(&View::Shader(resource, _)) => resource as This, _ => { @@ -2442,6 +2920,10 @@ impl State { } }; let texture = crate::resource::host_resource(resource); + if crate::residency::upload_refused() { + served = false; + break; + } let title_fills = texture.is_some_and(crate::texture::title_written); if !title_fills { at_once(); @@ -2461,16 +2943,23 @@ impl State { let same = !tabled && crate::texture::unchanged(resource, first); if same { HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed); - if shows_other && let Some(handle) = heap.handle(index) { - 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) && !crate::texture::ahead::there(resource) { - if let Some(handle) = heap.handle(index) { - host.texture_slot_show_after(list, index, handle); + if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) { + if let Some(copy) = crate::resource::host_copy(resource) { + sync.keep.push(copy); } + sync.publish.push((index, handle, key)); } else { - at_once(); + if shows_other && let Some(handle) = heap.handle(index) { + 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) && !crate::texture::ahead::there(resource) { + if let Some(handle) = heap.handle(index) { + host.texture_slot_show_after(list, index, handle); + } + } else { + at_once(); + } } let again = partly.map(|mapped| (frame + 1, mapped)); let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None }; @@ -2500,7 +2989,12 @@ impl State { crate::texture::ahead::send(job); } } + if ahead.is_none() && crate::residency::upload_refused() { + served = false; + break; + } let late = late && ahead.is_none(); + let _ = crate::residency::take_staging_deferred(); if let Some(view) = &view && ahead.is_none() { @@ -2510,6 +3004,21 @@ impl State { readable(list, sampled.kind, view); crate::texture::PICKING.set(None); } + // A failed or deferred staging allocation leaves this slot due. + // Publishing it or marking it served would lose the only retry for + // some materials. + if ahead.is_none() + && (crate::residency::take_staging_deferred() || crate::residency::upload_refused()) + { + served = false; + break; + } + if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) { + if let Some(copy) = crate::resource::host_copy(resource) { + sync.keep.push(copy); + } + sync.publish.push((index, handle, key)); + } if shows_other && let Some(handle) = heap.handle(index) { host.texture_slot_flip(list, index, handle); } @@ -2542,7 +3051,7 @@ impl State { let text: String = format!("{view:?}").chars().take(300).collect(); tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}"); crate::host::log_removal_context(); - return; + return false; } let (bytes, whole) = crate::texture::staged(resource, there.is_none()).unwrap_or((0, true)); // Not all of it there: looked at again next frame, and from @@ -2593,9 +3102,10 @@ impl State { None => host.texture_slot_done(index, write, again), } } - if baking && served { + if sync.is_none() && baking && served { BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed); } + served } /// For the frame listing, after a dropped dispatch's line: its group @@ -3196,21 +3706,29 @@ impl State { pub(crate) fn tables( &mut self, list: &HostList, - used: &[UsedResource], - indexed: &[RootIndexedView], + plan: &TablePlan, half: &[(u8, u32)], compute: bool, ) -> Few<(u8, u32), 16> { - let tables = |u: &&UsedResource| u.root == RootType::Table; - let mut fresh: Few<u8, 16> = Few::default(); - for u in used.iter().filter(tables).filter(|u| u.kind == ResourceType::Cbv) { - if !fresh.contains(&u.slot) { - fresh.push(u.slot); + let mut fresh = [0u64; 4]; + let selected_slot = |mask: &[u64; 4], slot: u8| mask[usize::from(slot / 64)] & (1u64 << (slot % 64)) != 0; + for group in &plan.groups { + let slot = group.slot; + let needs_snapshot = group.has_cbv + || match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::Table(table)) => self.heap_of(table).is_some_and(|heap| { + heap.host() + .is_some_and(|host| group.needs_snapshot(heap, host.count(), table)) + }), + _ => false, + }; + if needs_snapshot { + fresh[usize::from(slot / 64)] |= 1u64 << (slot % 64); } } - // The view shown in place of the title's at dword `at` of the table - // in root parameter `slot`, if the shader moves halves there and - // the title's view is a 16-bit float or signed buffer view. + // LOCAL (faces): the view shown in place of the title's at dword `at` + // of the table in root parameter `slot`, if the shader moves halves + // there and the title's view is a 16-bit float or signed buffer view. let halved = |state: &Self, slot: u8, at: u32| -> Option<View> { if !half.contains(&(slot, at)) { return None; @@ -3228,9 +3746,7 @@ impl State { continue; }; if crate::descriptor::host::half_view(&view).is_some() { - if !fresh.contains(&slot) { - fresh.push(slot); - } + fresh[usize::from(slot / 64)] |= 1u64 << (slot % 64); } else if let Some(format) = crate::descriptor::host::half_inexact(&view) { once!( format, @@ -3238,44 +3754,22 @@ impl State { ); } } - // Tables reaching past a host heap smaller than the title's (the - // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the - // title's slots there have no host slot of their own. - for u in used.iter().filter(tables) { - if fresh.contains(&u.slot) { - continue; - } - let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else { - continue; - }; - let end = table + u64::from(u.table_offset_dwords) * 4; - let Some(heap) = self.heap_of(table) else { - continue; - }; - let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else { - continue; - }; - if index >= host.count() { - fresh.push(u.slot); - } - } - fresh.sort_unstable(); - for u in used.iter().filter(tables) { - if !fresh.contains(&u.slot) { - self.table_entry(list, u, compute); + for &(g, e) in &plan.direct { + let group = &plan.groups[g]; + if !selected_slot(&fresh, group.slot) { + self.table_entry(list, &group.entries[e], compute); } } let mut made = Few::default(); - for &slot in fresh.iter() { + for group in &plan.groups { + let slot = group.slot; + if !selected_slot(&fresh, slot) { + continue; + } let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else { continue; }; - // (Their places among `used`.) - let mut places: Few<u16, 32> = Few::default(); - for (i, _) in used.iter().enumerate().filter(|(_, u)| tables(u) && u.slot == slot) { - places.push(i as u16); - } - let entries = || places.iter().map(|&i| &used[usize::from(i)]); + let entries = &group.entries; let Some(heap) = self.heap_of(table) else { continue; }; @@ -3285,9 +3779,9 @@ impl State { let Some(host) = heap.host() else { continue; }; - let mut selected: Vec<u32> = indexed + let mut selected: Vec<u32> = group + .indexed .iter() - .filter(|index| index.table_slot == slot) .map(|index| { let constant = self.user_value( compute, @@ -3310,12 +3804,7 @@ impl State { ); selected.sort_unstable(); selected.dedup(); - let n = entries() - .map(|u| u.table_offset_dwords / 8) - .chain(selected.last().copied()) - .max() - .unwrap_or(0) - + 1; + let n = (group.max_dword / 8).max(selected.last().copied().unwrap_or(0)) + 1; let last = table.checked_add(u64::from(n - 1) * 32); if n > crate::descriptor::host::DYNAMIC || last.and_then(|handle| heap.index(handle)).is_none() @@ -3339,12 +3828,12 @@ impl State { (table, n, h.0) }; // Who reads of it, and as what, as far as [`readable`] goes by it. - let reader = (used.as_ptr() as usize, used.len(), STORES.get(), TESTED_DEPTH.get().0); + let reader = (std::ptr::from_ref(plan) as usize, plan.direct.len(), STORES.get(), TESTED_DEPTH.get().0); if let Some(known) = self.fresh_tables.get_mut(&key) { let first = known.first; // This reader had it brought up to date, and nothing in the // list changed since: nothing to do again. - let once = ready_once() && selected.is_empty() && entries().all(|u| u.kind != ResourceType::Uav); + let once = ready_once() && selected.is_empty() && !group.has_uav; if once && known.epoch == list.epoch() && let Some((_, depth)) = known.ready.iter().find(|(r, _)| *r == reader) @@ -3357,14 +3846,14 @@ impl State { } let depth_before = TESTED_DEPTH.get(); TESTED_DEPTH.set((depth_before.0, false)); - for u in entries().filter(|u| u.kind != ResourceType::Cbv) { + for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { let handle = table + u64::from(u.table_offset_dwords) * 4; if let Some(view) = crate::descriptor::view(handle) { readable(list, u.kind, &view); } } for k in selected { - if entries().any(|u| u.table_offset_dwords / 8 == k) { + if group.entry(k).is_some() { continue; } let handle = table + u64::from(k) * 32; @@ -3391,7 +3880,10 @@ impl State { made.push((slot, first * 32)); continue; } - let Some(first) = host.dynamic(n) else { + let Some(first) = host.dynamic(n).or_else(|| { + crate::host::settle_for_fence(); + host.dynamic(n) + }) else { // No room: the draw must not run with the title's own // offsets (slots never made for it); `bind` drops it. made.push((slot, u32::MAX)); @@ -3407,7 +3899,7 @@ impl State { // which may lie over slots shaders pick by index, only the ones // the shader names.) if let Some(title) = title_first { - for k in (0..n).filter(|&k| n <= 64 || entries().any(|u| u.table_offset_dwords / 8 == k)) { + for k in (0..n).filter(|&k| n <= 64 || group.entry(k).is_some()) { host.slot_tabled(title + k); } } @@ -3427,8 +3919,8 @@ impl State { && let Some(words) = crate::descriptor::record_at(table + u64::from(k) * 32) && let Some(mut listed) = host.make_listed(recording, words, index) { - let kind = entries() - .find(|u| u.table_offset_dwords / 8 == k) + let kind = group + .entry(k) .map(|u| u.kind) .or_else(|| selected.binary_search(&k).ok().and(listed.kind)); let was = (listed.ready, listed.tabled); @@ -3439,11 +3931,12 @@ impl State { TESTED_DEPTH.set((tested.0, true)); } } else if let Some(view) = crate::descriptor::host::listed_view(recording, words) { + let _ = crate::residency::take_staging_deferred(); TESTED_DEPTH.set((tested.0, false)); readable(list, kind, &view); let depth = TESTED_DEPTH.get().1; TESTED_DEPTH.set((tested.0, tested.1 || depth)); - if kind == ResourceType::Srv { + if kind == ResourceType::Srv && !crate::residency::take_staging_deferred() { listed.ready = (list.epoch(), tested.0, depth); } } @@ -3463,7 +3956,7 @@ impl State { } continue; } - let used = entries().find(|u| u.table_offset_dwords / 8 == k); + let used = group.entry(k); match crate::descriptor::view(table + u64::from(k) * 32) { Some(View::Constant(address, size)) => { let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else { diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 10a9e93..3ca3d41 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -115,7 +115,32 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c if fence.value.load(Ordering::Acquire) >= value { return S_OK; } - tracing::warn!(value, "blocking fence wait not implemented"); + let deadline = std::time::Instant::now() + std::time::Duration::from_millis(250); + loop { + let current = fence.value.load(Ordering::Acquire); + if current >= value { + return S_OK; + } + let now = std::time::Instant::now(); + if now >= deadline { + break; + } + let ms = (deadline - now).as_millis().min(10) as u32; + // SAFETY: wait on the atomic u64 until woken by WakeByAddressAll or timeout. + unsafe { + windows_sys::Win32::System::Threading::WaitOnAddress( + (&raw const fence.value).cast(), + (&raw const current).cast(), + size_of::<u64>(), + ms.max(1), + ); + } + crate::queue::release_held(false); + } + if fence.value.load(Ordering::Acquire) >= value { + return S_OK; + } + tracing::warn!(value, "blocking fence wait timed out"); return E_NOTIMPL; } // shortcut: a null event means "block until reached"; nothing can @@ -140,6 +165,12 @@ pub(crate) fn set(this: This, value: u64) { } !reached }); + drop(waiters); + #[cfg(windows)] + // SAFETY: wake any guest thread polling/blocking via WaitOnAddress on the fence's GPU VA. + unsafe { + windows_sys::Win32::System::Threading::WakeByAddressAll((&raw const fence.value).cast()); + } } pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { let _called = crate::timeline::span("a fence set"); diff --git a/crates/victory-gpu/src/fg.rs b/crates/victory-gpu/src/fg.rs new file mode 100644 index 0000000..ac511c2 --- /dev/null +++ b/crates/victory-gpu/src/fg.rs @@ -0,0 +1,405 @@ +//! LOCAL (11/26): DLSS Frame Generation through NVIDIA Streamline (manual hooking). +//! +//! `VICTORY_FRAME_GEN=2|3|4` (frames shown per rendered one; unset or 1: off) with the SDK's +//! signed DLLs in `VICTORY_STREAMLINE_DIR` (sl.interposer, sl.common, sl.dlss_g, sl.reflex, +//! sl.pcl, nvngx_dlssg). NVIDIA's licence: for own use only, never pushed. +//! +//! - [`start`] (from the presenter, before its swap chain): `slInit`, `slSetD3DDevice`, Reflex +//! low latency, and the factory upgraded to Streamline's proxy, so that the swap chain made +//! from it is the proxy that generates frames at `Present`. +//! - [`tag`] (from the DLSS upscale, `crate::dlss::record`): the frame's constants and its depth +//! and motion vectors (copied by Streamline on that list: `eOnlyValidNow`). +//! - [`present_start`] / [`present_end`] around the proxy's `Present`. +//! +//! The title gives no camera matrices: they are made from a 60 degree field of view, the +//! upscale's near/far and the render size, the camera standing still (its motion is in the +//! motion vectors). Frame indices are the presents so far: the upscale of a frame is recorded +//! before its present. + +use std::ffi::CString; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::IDXGIFactory2; +use windows::core::Interface; + +use crate::streamline as sl; + +/// Frames to generate per rendered frame (1 = 2x .. 5 = 6x), 0: off, as `VICTORY_FRAME_GEN` +/// says now (the F1 menu changes it while running). +fn wanted_now() -> u32 { + std::env::var("VICTORY_FRAME_GEN").ok().and_then(|v| v.trim().parse::<u32>().ok()).map_or(0, |n| n.clamp(1, 6) - 1) +} + +/// [`wanted_now`] at the start: whether Streamline is started at all (its proxy swap chain is +/// made once; with it, the amount and off/on change while running). +pub(crate) fn wanted() -> u32 { + static N: OnceLock<u32> = OnceLock::new(); + *N.get_or_init(|| { + let n = wanted_now(); + // Not together with the ray-tracing structure builder: each runs at about 15 frames a + // second alone and the two at 0.1 (11/26 r_rtE/F/G: from the moment Streamline has its + // first constants in the world, recording takes seconds a frame; Reflex off and no + // generated frames change nothing). `VICTORY_FG_WITH_RT=1` starts it anyway. + let rt = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1"); + let forced = std::env::var_os("VICTORY_FG_WITH_RT").is_some_and(|v| v == "1"); + if n > 0 && rt && !forced { + tracing::warn!("frame generation: not started with ray tracing on (together they run at 0.1 frames a second); VICTORY_FG_WITH_RT=1 starts it anyway"); + return 0; + } + n + }) +} + +/// `VICTORY_FG_REFLEX=0`: Reflex left off and its sleep not taken (to tell its cost from the rest). +fn reflex_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_FG_REFLEX").is_none_or(|v| v != "0")) +} + +struct State { + sl: sl::Sl, + /// Frames to generate as last given to DLSS-G (0: turned off); none before the first present. + set: Option<u32>, + /// The most frames this card generates per rendered one, as DLSS-G says; 0: not asked yet. + most: u32, + told: u32, +} + +static STATE: OnceLock<Option<Mutex<State>>> = OnceLock::new(); +/// Presents so far: the index of the frame being made. +static FRAME: AtomicU32 = AtomicU32::new(1); +/// A frame was tagged since the last present. +static TAGGED: AtomicBool = AtomicBool::new(false); + +const VIEWPORT: sl::ViewportHandle = sl::ViewportHandle::new(0); + +fn state() -> Option<&'static Mutex<State>> { + STATE.get().and_then(|s| s.as_ref()) +} + +fn init(device: &ID3D12Device) -> anyhow::Result<State> { + let dir = std::env::var_os("VICTORY_STREAMLINE_DIR") + .ok_or_else(|| anyhow::anyhow!("VICTORY_STREAMLINE_DIR is not set"))?; + // SAFETY: NVIDIA's signed interposer from the SDK folder the launcher names. + let mut s = unsafe { sl::Sl::load(std::path::Path::new(&dir)) }?; + let features = sl::FG_FEATURES; + static ENGINE: OnceLock<(CString, CString)> = OnceLock::new(); + let (version, project) = ENGINE.get_or_init(|| { + (CString::new("1.0").unwrap_or_default(), CString::new("5e2f9a3c-1b7d-4c8e-9a6f-0d3b2c1e4f57").unwrap_or_default()) + }); + let logs: Vec<u16> = std::env::temp_dir().join("victory-sl").as_os_str().encode_wide_z(); + let _ = std::fs::create_dir_all(std::env::temp_dir().join("victory-sl")); + let pref = sl::Preferences { + logLevel: sl::LogLevel::eDefault, + pathToLogsAndData: logs.as_ptr(), + logMessageCallback: Some(sl::log_to_tracing), + flags: sl::PreferenceFlags::MANUAL_HOOKING_FRAME_TAGS, + featuresToLoad: features.as_ptr(), + numFeaturesToLoad: features.len() as u32, + engine: sl::EngineType::eCustom, + engineVersion: version.as_ptr(), + projectId: project.as_ptr(), + renderAPI: sl::RenderAPI::eD3D12, + ..Default::default() + }; + // SAFETY: every pointer in `pref` lives through the call (SL copies them); the log + // callback is a static function. + unsafe { s.init(&pref) }.ok().map_err(|e| anyhow::anyhow!("slInit: {e}"))?; + // SAFETY: the host's live native device. + unsafe { s.set_d3d_device(device.as_raw()) }.ok().map_err(|e| anyhow::anyhow!("slSetD3DDevice: {e}"))?; + // SAFETY: a plain query of a live device. + let luid = unsafe { device.GetAdapterLuid() }; + let mut bytes = [0u8; 8]; + bytes[..4].copy_from_slice(&luid.LowPart.to_le_bytes()); + bytes[4..].copy_from_slice(&luid.HighPart.to_le_bytes()); + let supported = s.is_feature_supported(sl::kFeatureDLSS_G, Some(&bytes)); + if !supported.is_ok() { + anyhow::bail!("DLSS-G is not supported here: {supported}"); + } + s.resolve_feature_functions()?; + let reflex = sl::ReflexOptions { + mode: if reflex_on() { sl::ReflexMode::eLowLatency } else { sl::ReflexMode::eOff }, + ..Default::default() + }; + let r = s.reflex_set_options(&reflex); + if !r.is_ok() { + tracing::warn!(result = %r, "frame generation: Reflex not set"); + } + Ok(State { sl: s, set: None, most: 0, told: 0 }) +} + +trait WideZ { + fn encode_wide_z(&self) -> Vec<u16>; +} +impl WideZ for std::ffi::OsStr { + fn encode_wide_z(&self) -> Vec<u16> { + use std::os::windows::ffi::OsStrExt; + self.encode_wide().chain([0]).collect() + } +} + +/// Before the presenter's swap chain is made: starts Streamline (once) and gives back the +/// factory to make it from, the proxy if frame generation is wanted and could start. +pub(crate) fn start(device: &ID3D12Device, factory: IDXGIFactory2) -> IDXGIFactory2 { + if wanted() == 0 { + return factory; + } + let state = STATE.get_or_init(|| match init(device) { + Ok(s) => { + tracing::info!(frames = wanted() + 1, "frame generation: Streamline started"); + Some(Mutex::new(s)) + } + Err(e) => { + tracing::warn!(error = %e, "frame generation: Streamline did not start; presenting without it"); + None + } + }); + let Some(state) = state else { return factory }; + let s = state.lock().unwrap_or_else(|e| e.into_inner()); + let mut raw = factory.as_raw(); + // SAFETY: a live factory; the call puts a new proxy (with its own reference) in `raw` and + // leaves ours to the native one. + let r = unsafe { s.sl.upgrade_interface(&mut raw) }; + if !r.is_ok() || raw.is_null() { + tracing::warn!(result = %r, "frame generation: the factory was not upgraded"); + return factory; + } + // SAFETY: SL's proxy, an IDXGIFactory2 with one reference, now ours. + unsafe { IDXGIFactory2::from_raw(raw) } +} + +/// What the last DLSS upscale read: the frame's numbers and its depth and motion vectors (title +/// resources, whose host copies and states are looked up at the present). +struct Latest { + depth: usize, + motion: usize, + render: [u32; 2], + jitter: [f32; 2], + mv_pixels: [f32; 2], + near: f32, + far: f32, + reset: bool, +} + +static LATEST: Mutex<Option<Latest>> = Mutex::new(None); + +/// With frame generation on: the numbers of the DLSS upscale just recorded ([`crate::dlss::record`]). +/// The upscale of a frame is recorded after its present has been asked for (the lists are recorded +/// at submission), so everything is handed to Streamline at the next present, whose index is the +/// one the constants and tags carry. +#[allow(clippy::too_many_arguments)] +pub(crate) fn tag(render: [u32; 2], jitter: [f32; 2], mv_pixels: [f32; 2], near: f32, far: f32, reset: bool) { + if state().is_none() { + return; + } + let mut latest = LATEST.lock().unwrap_or_else(|e| e.into_inner()); + let (depth, motion) = latest.as_ref().map_or((0, 0), |l| (l.depth, l.motion)); + *latest = Some(Latest { depth, motion, render, jitter, mv_pixels, near, far, reset }); + TAGGED.store(true, Ordering::Relaxed); +} + +/// The title's depth and motion vectors the DLSS upscale read (`crate::list::upscale_now`). +pub(crate) fn note_titles(depth: u64, motion: u64) { + if state().is_none() { + return; + } + let mut latest = LATEST.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(l) = latest.as_mut() { + (l.depth, l.motion) = (depth as usize, motion as usize); + } +} + +fn constants(l: &Latest) -> sl::Constants { + let (w, h) = (l.render[0].max(1) as f32, l.render[1].max(1) as f32); + let inverted = l.near > l.far; + let (n, f) = (l.near.min(l.far).max(1e-3), l.near.max(l.far).min(1e6).max(l.near.min(l.far) + 1.0)); + let fov = 60f32.to_radians(); + let ys = 1.0 / (fov / 2.0).tan(); + let xs = ys / (w / h); + let (c, d) = if inverted { (n / (n - f), -n * f / (n - f)) } else { (f / (f - n), -n * f / (f - n)) }; + sl::Constants { + cameraViewToClip: sl::float4x4::from_rows([[xs, 0.0, 0.0, 0.0], [0.0, ys, 0.0, 0.0], [0.0, 0.0, c, 1.0], [0.0, 0.0, d, 0.0]]), + clipToCameraView: sl::float4x4::from_rows([ + [1.0 / xs, 0.0, 0.0, 0.0], + [0.0, 1.0 / ys, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0 / d], + [0.0, 0.0, 1.0, -c / d], + ]), + clipToPrevClip: sl::float4x4::identity(), + prevClipToClip: sl::float4x4::identity(), + jitterOffset: sl::float2::new(l.jitter[0], l.jitter[1]), + mvecScale: sl::float2::new(l.mv_pixels[0] / w, l.mv_pixels[1] / h), + cameraPinholeOffset: sl::float2::new(0.0, 0.0), + cameraPos: sl::float3::new(0.0, 0.0, 0.0), + cameraUp: sl::float3::new(0.0, 1.0, 0.0), + cameraRight: sl::float3::new(1.0, 0.0, 0.0), + cameraFwd: sl::float3::new(0.0, 0.0, 1.0), + cameraNear: n, + cameraFar: f, + cameraFOV: fov, + cameraAspectRatio: w / h, + depthInverted: inverted.into(), + cameraMotionIncluded: sl::Boolean::eTrue, + motionVectors3D: sl::Boolean::eFalse, + reset: l.reset.into(), + motionVectorsJittered: sl::Boolean::eTrue, + ..Default::default() + } +} + +/// Right before the proxy's `Present`: generation on (once), and for a frame the upscale ran in, +/// its constants and its depth and motion vectors (valid until this present: the next frame's +/// lists come after it on the queue). +pub(crate) fn present_start() { + let Some(state) = state() else { return }; + let mut s = state.lock().unwrap_or_else(|e| e.into_inner()); + let index = FRAME.load(Ordering::Relaxed); + // The amount, at the first present and whenever the menu changed it (looked at twice a second + // or so): no restart, the proxy swap chain stays. + if s.set.is_none() || index % 8 == 0 { + let asked = wanted_now(); + // No more than the card and driver generate (DLSS 4.5 gives up to 5 here: 6x). + // Asked once here (each question restarts Streamline's count of presented frames). + if s.most == 0 { + s.most = match s.sl.dlssg_get_state(&VIEWPORT, None) { + Ok(st) if st.numFramesToGenerateMax > 0 => st.numFramesToGenerateMax, + _ => 1, + }; + } + let want = asked.min(s.most); + if s.set != Some(want) { + if want != asked { + tracing::warn!(asked = asked + 1, given = want + 1, "frame generation: more than this card generates; its most is used"); + } + let options = sl::DLSSGOptions { + mode: if want == 0 { sl::DLSSGMode::eOff } else { sl::DLSSGMode::eOn }, + numFramesToGenerate: want.max(1), + flags: sl::DLSSGFlags::eRetainResourcesWhenOff, + ..Default::default() + }; + let r = s.sl.dlssg_set_options(&VIEWPORT, &options); + tracing::info!(result = %r, frames = want + 1, "frame generation: amount set (1 = off)"); + s.set = Some(want); + if want == 0 { + SHOWN.store(1, Ordering::Relaxed); + } + } + } + let Ok(token) = s.sl.new_frame_token(Some(index)) else { return }; + for marker in [ + sl::PCLMarker::eSimulationStart, + sl::PCLMarker::eSimulationEnd, + sl::PCLMarker::eRenderSubmitStart, + sl::PCLMarker::eRenderSubmitEnd, + ] { + let _ = s.sl.pcl_set_marker(marker, token); + } + // Every present carries the last upscale's numbers and buffers, a present with no new + // upscale since the last one too (DLSS-G drops a frame that has none). + let fresh = TAGGED.swap(false, Ordering::Relaxed); + { + let latest = LATEST.lock().unwrap_or_else(|e| e.into_inner()); + let found = latest.as_ref().and_then(|l| { + // Only a title resource that is still one, and only its copy as it is: the handles + // are a frame old at a present with no new upscale, and the title may have let the + // resource go since (with ray tracing on it makes and frees buffers all the time); + // `host_copy` would make a copy of whatever lies there now. + let look = |title: usize| { + let this = title as crate::object::This; + if this.is_null() || !crate::resource::is_resource(this) { + return None; + } + let copy = crate::resource::made_copy(this)?; + let state = crate::host::legal_state(©.texture, copy.state.load(Ordering::Relaxed)); + Some((copy, state)) + }; + Some((l, look(l.depth)?, look(l.motion)?)) + }); + if let Some((l, (depth, depth_state), (motion, motion_state))) = found { + let r = s.sl.set_constants(&constants(l), token, &VIEWPORT); + let mut depth_res = sl::Resource::d3d12_tex2d(depth.texture.as_raw(), depth_state); + let mut motion_res = sl::Resource::d3d12_tex2d(motion.texture.as_raw(), motion_state); + let extent = Some(sl::Extent { top: 0, left: 0, width: l.render[0], height: l.render[1] }); + let tags = [ + sl::ResourceTag::new(&mut depth_res, sl::kBufferTypeDepth, sl::ResourceLifecycle::eValidUntilPresent, extent), + sl::ResourceTag::new(&mut motion_res, sl::kBufferTypeMotionVectors, sl::ResourceLifecycle::eValidUntilPresent, extent), + ]; + // SAFETY: live resources (their host copies are held through the call), in the + // states they will be in at the present; no list needed for eValidUntilPresent. + let t = unsafe { s.sl.set_tag_for_frame(token, &VIEWPORT, &tags, std::ptr::null_mut()) }; + if (!r.is_ok() || !t.is_ok()) && s.told < 5 { + s.told += 1; + tracing::warn!(constants = %r, tags = %t, index, "frame generation: constants or tags refused"); + } + PRESENT_TAGGED.store(fresh, Ordering::Relaxed); + } + } + let _ = s.sl.pcl_set_marker(sl::PCLMarker::ePresentStart, token); +} + +/// The present now ending had constants and tags. +static PRESENT_TAGGED: AtomicBool = AtomicBool::new(false); + +/// Right after the proxy's `Present`: the next frame's index, Reflex's sleep, and now and then +/// what the generator says of itself. +pub(crate) fn present_end() { + let Some(state) = state() else { return }; + let s = state.lock().unwrap_or_else(|e| e.into_inner()); + let index = FRAME.load(Ordering::Relaxed); + if let Ok(token) = s.sl.new_frame_token(Some(index)) { + let _ = s.sl.pcl_set_marker(sl::PCLMarker::ePresentEnd, token); + } + let tagged = PRESENT_TAGGED.swap(false, Ordering::Relaxed); + // For the frame-rate texts: frames shown per rendered one, as Streamline says of the last + // present (r_cgbj41: 1 over 30 presents with the window not focused, so not a running count; + // DLSS-G generates nothing while the window is not focused). + const POLL: u32 = 10; + if index % POLL == 0 { + match s.sl.dlssg_get_state(&VIEWPORT, None) { + Ok(st) => { + let per = if st.status.0 == 0 { st.numFramesActuallyPresented.clamp(1, 6) } else { 1 }; + SHOWN.store(per, Ordering::Relaxed); + if index % 600 == 0 || (index / POLL).is_power_of_two() { + tracing::info!( + index, + tagged, + status = st.status.0, + presented = st.numFramesActuallyPresented, + per, + max = st.numFramesToGenerateMax, + "frame generation: state (status 0 = working; 2 Reflex, 8 constants)" + ); + } + } + Err(e) => { + SHOWN.store(1, Ordering::Relaxed); + if index % 600 == 0 { + tracing::warn!(error = %e, "frame generation: no state"); + } + } + } + } + let next = index + 1; + FRAME.store(next, Ordering::Relaxed); + // Reflex paces the next frame here. + if reflex_on() + && let Ok(token) = s.sl.new_frame_token(Some(next)) + { + let _ = s.sl.reflex_sleep(token); + } +} +/// Frames shown per frame rendered (1 without generation working), as Streamline last said. +static SHOWN: AtomicU32 = AtomicU32::new(1); + +/// For the frame-rate texts: frames shown per frame rendered; 1 when generation is off or failing. +pub(crate) fn shown_per_frame() -> u32 { + if state().is_some() { SHOWN.load(Ordering::Relaxed).max(1) } else { 1 } +} + +/// Whether Streamline is presenting (the presenter's swap chain is its proxy). +pub(crate) fn active() -> bool { + state().is_some() +} + diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 8bf432f..91cf709 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -25,8 +25,47 @@ const ORIGIN: u32 = 0; const TOKEN_ON_TIMEOUT: u32 = 2; const SIXTIETH: Duration = Duration::from_micros(16_667); +/// LOCAL (11/26): `VICTORY_FPS_CAP`. Unset: the title's own interval (30 frames a second on a +/// Series S); `0`: none (ticks half a millisecond apart); `n`: n frames a second. The F1 menu +/// changes it while running ([`set_cap`]). -1: not read yet; 0: the title's; else microseconds. +static CAP_US: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(-1); + +fn parse_cap(value: Option<&str>) -> i64 { + match value.map(str::trim).and_then(|v| v.parse::<u32>().ok()) { + None => 0, + Some(0) => 500, + Some(n) => (1_000_000 / i64::from(n)).max(500), + } +} + +/// The interval ticks are apart: the title's, or the cap's when one is set. +fn capped(asked: Duration) -> Duration { + let mut us = CAP_US.load(Ordering::Relaxed); + if us < 0 { + us = parse_cap(std::env::var("VICTORY_FPS_CAP").ok().as_deref()); + CAP_US.store(us, Ordering::Relaxed); + } + if us == 0 { asked } else { Duration::from_micros(us as u64) } +} + +/// The cap changed (the F1 menu): the clock goes on from now with the new interval. +#[allow(dead_code)] +pub(crate) fn set_cap(value: &str) { + CAP_US.store(parse_cap(Some(value).filter(|v| !v.is_empty())), Ordering::Relaxed); + let first = LAST.iter().map(|t| t.load(Ordering::Relaxed)).max().unwrap_or(0); + if let Some(c) = clock().as_mut() { + c.start = Instant::now(); + c.first = first; + c.interval = capped(c.asked); + tracing::info!(asked = ?c.asked, interval = ?c.interval, "frame interval: the cap changed"); + } +} + struct Clock { start: Instant, + /// What the title asked for. + asked: Duration, + /// What ticks are apart ([`capped`]). interval: Duration, /// The tick number at `start` (ticks go on across interval changes). first: u64, @@ -53,7 +92,9 @@ pub(crate) extern "system" fn set_interval( 0 => SIXTIETH, us => Duration::from_micros(u64::from(us)), }; - tracing::info!(?interval, "frame interval"); + let asked = interval; + let interval = capped(asked); + tracing::info!(?asked, ?interval, "frame interval (VICTORY_FPS_CAP: unset the title's, 0 none, n frames a second)"); // A new interval starts from now, after the last tick handed out. let first = LAST .iter() @@ -62,6 +103,7 @@ pub(crate) extern "system" fn set_interval( .unwrap_or(0); *clock() = Some(Clock { start: Instant::now(), + asked, interval, first, }); @@ -105,7 +147,8 @@ fn next_tick(kind: u32) -> (u64, Duration) { let mut clock = clock(); let c = clock.get_or_insert_with(|| Clock { start: Instant::now(), - interval: SIXTIETH, + asked: SIXTIETH, + interval: capped(SIXTIETH), first: 0, }); let elapsed = c.start.elapsed().as_nanos(); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 1aceb9c..98ddda3 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -57,6 +57,10 @@ pub(crate) struct Host { /// The adapter the device is on, for its memory budget /// ([`Host::video_memory`]); `None` if the system does not name it. adapter: Option<IDXGIAdapter3>, + /// 1-descriptor shader-visible fallback heaps bound when a command list + /// omits a view or sampler heap while using directly-indexed root signatures. + fallback_view: OnceLock<Option<ID3D12DescriptorHeap>>, + fallback_sampler: OnceLock<Option<ID3D12DescriptorHeap>>, } // SAFETY: D3D12 devices, queues, fences and descriptor heaps are @@ -368,7 +372,11 @@ pub(crate) fn keep_freed() -> bool { /// when free physical RAM is low. Never returns less than 2,000 ms. /// With plenty of it five minutes ([`keep_freed`]). pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 { - ram_idle_for(avail_phys, keep_freed()) + let effective = match (avail_phys, crate::residency::headroom()) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + }; + ram_idle_for(effective, keep_freed() && !crate::residency::limited_host_ram()) } fn ram_idle_for(avail_phys: Option<u64>, keep: bool) -> u64 { @@ -432,6 +440,10 @@ fn sweep() { } #[cfg(feature = "diagnostics")] crate::book::check(); + crate::residency::refresh(); + if crate::residency::pressured() { + trim_spare_chunks(); + } crate::pool::room(host().and_then(|h| h.video_memory())); crate::pipeline::trim_library(); crate::shadow::let_go_idle(); @@ -484,7 +496,10 @@ pub(crate) fn retire_resource(object: ID3D12Resource) { /// recorded and not yet sent may name them. `VICTORY_BURY_LAG=0`: not. fn bury_lag() -> u64 { static LAG: OnceLock<u64> = OnceLock::new(); - *LAG.get_or_init(|| std::env::var("VICTORY_BURY_LAG").ok().and_then(|v| v.parse().ok()).unwrap_or(64)) + *LAG.get_or_init(|| { + let default = if crate::residency::limited_host_ram() { 16 } else { 64 }; + std::env::var("VICTORY_BURY_LAG").ok().and_then(|v| v.parse().ok()).unwrap_or(default) + }) } /// Drops what waited for submissions up to `finished` ([`bury_lag`]). The @@ -970,6 +985,8 @@ fn create() -> windows::core::Result<Host> { next_rtv: AtomicU32::new(0), presenter: Mutex::new(None), adapter, + fallback_view: OnceLock::new(), + fallback_sampler: OnceLock::new(), }) } } @@ -1963,7 +1980,12 @@ fn give_chunks(chunks: Vec<(Chunk, u64)>) { let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); for (chunk, size) in chunks { let back = if scratch_pool() { - spare.give(chunk, size, if keep_freed() { SPARE_KEPT } else { SPARE_MOST }) + let limit = if keep_freed() && !crate::residency::limited_host_ram() { + SPARE_KEPT + } else { + SPARE_MOST + }; + spare.give(chunk, size, limit) } else { Some(chunk) }; @@ -1984,6 +2006,25 @@ fn give_chunks(chunks: Vec<(Chunk, u64)>) { drop(freed); } +/// Drops spare scratch chunks kept idle when host memory is pressured. +fn trim_spare_chunks() { + let freed: Vec<(Chunk, u64)> = { + let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + if spare.kept.is_empty() { + return; + } + spare.bytes = 0; + std::mem::take(&mut spare.kept) + }; + let count = freed.len() as u64; + let bytes: u64 = freed.iter().map(|(_, s)| *s).sum(); + ALIVE[1].fetch_sub(count, Ordering::Relaxed); + ALIVE[2].fetch_sub(bytes, Ordering::Relaxed); + ALIVE[3].fetch_sub(count, Ordering::Relaxed); + ALIVE[4].fetch_sub(bytes, Ordering::Relaxed); + drop(freed); +} + /// What the host keeps for copies in the card's own memory /// ([`crate::shadow::cards`]): three lists of ours and the compare. struct CardWork { @@ -2243,6 +2284,8 @@ enum Step { /// Brings a texture's staging buffer up to date: once per submission, /// whichever lists sample it, until a `Copy` or `Run` intervenes. Texture(std::sync::Arc<crate::texture::Staging>), + /// Reads a CPU-written linear movie plane into a per-list upload buffer. + Plane((usize, usize), Box<dyn Fn() + Send>), /// A title buffer copy that the list does on the card ([`place`]): what /// is done on the CPU for it. Placed(place::Placed), @@ -2256,6 +2299,8 @@ struct Deferred { /// Destination, source, bytes. copies: Vec<Step>, uploads: Vec<ID3D12Resource>, + /// Standalone upload footprints kept through this list's fence (movie planes). + plane_uploads: Vec<(Chunk, u64)>, /// The bytes of `uploads` (counted in [`ALIVE`] while they are held). upload_bytes: u64, /// Host objects the list's commands name (pipelines, root signatures, @@ -2320,6 +2365,7 @@ impl Deferred { impl Drop for Deferred { fn drop(&mut self) { + give_chunks(std::mem::take(&mut self.plane_uploads)); ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed); ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed); } @@ -2733,6 +2779,10 @@ const WHY_FENCE: usize = 10; /// copy, a fill of upload memory, a texture). static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18]; +/// LOCAL (11/26): settles for refreshes of memory a flight writes through +/// another copy (`upcheck::crossed`), since the last frame-rate line. +static CROSS_SETTLES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + /// Since the last frame-rate line: the microseconds settles waited for the /// card, by why they settled (the `WHY_` places). static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11]; @@ -2998,6 +3048,16 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op return Some(WHY_READ); } } + &Step::Plane((at, len), _) => { + if touches(written, at, at.saturating_add(len)) { + if count { + LATE_STATS[17].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + blame("a movie plane", written, at, len); + } + return Some(WHY_READ); + } + } Step::Run(_) => return Some(WHY_RUN), Step::Placed(p) => match p.waits(written) { place::Waits::No => {} @@ -3566,6 +3626,10 @@ fn late_line(frames: f64) { if !late() { return; } + if upcheck::cross_on() { + let n = CROSS_SETTLES.swap(0, Ordering::Relaxed) as f64 / frames; + tracing::info!("relay cross settles per frame (VICTORY_RELAY_CROSS=1): {n:.1}"); + } let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); tracing::info!( "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \ @@ -3676,6 +3740,8 @@ mod card_steps; pub(crate) mod indirects; #[cfg(feature = "diagnostics")] mod panel; +#[cfg(feature = "diagnostics")] +mod menu; mod place; mod send; pub(crate) use send::{goes_as_words, words_under}; @@ -4313,6 +4379,7 @@ impl Host { // pass: a wait between each copy and its pass had the // card do them one after the other. let mut sent = Vec::new(); + let mut transitioned = Vec::new(); if let Some(own) = &own { own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow))); } @@ -4331,11 +4398,15 @@ impl Host { #[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, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - )); + let raw = shadow.buffer.as_raw(); + if !transitioned.contains(&raw) { + transitioned.push(raw); + sent.push(transition( + &shadow.buffer, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )); + } } } if !sent.is_empty() { @@ -4906,7 +4977,7 @@ impl Host { let mut telling = std::time::Instant::now(); for item in items { telling = match item { - Late::Run(flight) => { + Late::Run(mut flight) => { last = flight.number; for &i in &flight.order { read_backs(flight.lists[i].host()); @@ -4918,6 +4989,9 @@ impl Host { if let Some(own) = flight.own { own.landed(); } + for detached in &mut flight.lists { + detached.release_tables(); + } crate::land::spent(crate::land::stat::RB_DONE, done_from); landed.push((flight.lists, flight.order)); crate::land::spent(crate::land::stat::READ_BACKS, telling) @@ -5121,6 +5195,14 @@ impl Host { let _ = self.submit(runs, &[], false); } + /// Runs a closed internal upload-only host list synchronously without + /// draining title queues (`queue::before_sync`), so it is deadlock-safe + /// when invoked from `VICTORY_THIN=1` worker threads. Settles in-flight + /// GPU work and waits for the upload list's fence before returning. + pub(crate) fn execute_sync_internal(&self, list: &HostList) { + let _ = self.submit(&[list], &[], false); + } + /// A queue's submission with [`late`]: the host lists `lists`, taken /// from the title's, go to the card in `order` and are not waited for. /// They join the line of flights and are settled, with the others in @@ -5378,7 +5460,7 @@ impl Host { let mut landed = Vec::new(); for item in items { match item { - Late::Run(flight) => { + Late::Run(mut flight) => { last = flight.number; for &i in &flight.order { read_backs(flight.lists[i].host()); @@ -5386,6 +5468,9 @@ impl Host { if let Some(card) = flight.card { self.card_done(card); } + for detached in &mut flight.lists { + detached.release_tables(); + } landed.push((flight.lists, flight.order)); } Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), @@ -5592,10 +5677,24 @@ impl Host { self.settle_stale(&mut submitted, runs, stale, &ranges); settled += settling.elapsed(); } + // LOCAL (11/26): refreshes of memory a flight writes through + // another copy wait for that flight (`upcheck::cross_on`). + if behind && upcheck::cross_on() && flying() && upcheck::crossed(runs) { + let settling = std::time::Instant::now(); + CROSS_SETTLES.fetch_add(1, Ordering::Relaxed); + self.settle(&mut submitted, WHY_STALE); + crate::watch::ask_once(&ranges); + settled += settling.elapsed(); + } } else if behind && !stale_under_flights(runs).is_empty() { let settling = std::time::Instant::now(); self.settle(&mut submitted, WHY_STALE); settled += settling.elapsed(); + } else if behind && upcheck::cross_on() && flying() && upcheck::crossed(runs) { + let settling = std::time::Instant::now(); + CROSS_SETTLES.fetch_add(1, Ordering::Relaxed); + self.settle(&mut submitted, WHY_STALE); + settled += settling.elapsed(); } #[cfg(feature = "diagnostics")] split.part(1); @@ -6120,6 +6219,71 @@ impl Host { handle } } + + /// 1-descriptor shader-visible CBV/SRV/UAV fallback heap for directly-indexed root signatures. + pub(crate) fn fallback_view_heap(&self) -> Option<&ID3D12DescriptorHeap> { + self.fallback_view + .get_or_init(|| { + // SAFETY: plain 1-descriptor shader-visible heap + null SRV initialization. + unsafe { + let heap: ID3D12DescriptorHeap = self + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .ok()?; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV::default(), + }, + }; + self.device.CreateShaderResourceView( + None, + Some(&desc), + heap.GetCPUDescriptorHandleForHeapStart(), + ); + Some(heap) + } + }) + .as_ref() + } + + /// 1-descriptor shader-visible Sampler fallback heap for directly-indexed root signatures. + pub(crate) fn fallback_sampler_heap(&self) -> Option<&ID3D12DescriptorHeap> { + self.fallback_sampler + .get_or_init(|| { + // SAFETY: plain 1-descriptor shader-visible sampler heap initialization. + unsafe { + let heap: ID3D12DescriptorHeap = self + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .ok()?; + let desc = D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxLOD: f32::MAX, + ..Default::default() + }; + self.device + .CreateSampler(&desc, heap.GetCPUDescriptorHandleForHeapStart()); + Some(heap) + } + }) + .as_ref() + } } impl HostList { @@ -6300,6 +6464,13 @@ impl HostList { self.epoch.load(Ordering::Relaxed) } + /// Whether any deferred steps or texture state transitions have been + /// recorded into this list since creation or its last [`HostList::reset`]. + pub(crate) fn has_recorded_work(&self) -> bool { + !self.deferred().copies.is_empty() + || !self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + } + /// Moves a title texture's host copy to `wanted` (a host state) in this /// list: the host texture and the state it leaves, if that is a change. /// The list's first use of a texture records nothing: its prelude brings @@ -7209,6 +7380,23 @@ impl HostList { self.deferred().copies.push(Step::Texture(staging)); } + /// A copy source owned exclusively by this list until reset after its + /// last execution. A different list can prepare its movie plane concurrently. + pub(crate) fn plane_upload( + &self, + size: u64, + read: (usize, usize), + fill: impl Fn(usize) + Send + 'static, + ) -> Option<ID3D12Resource> { + let chunk = take_chunk(host()?, size)?; + let source = chunk.buffer.clone(); + let destination = chunk.data; + let mut deferred = self.deferred(); + deferred.plane_uploads.push((chunk, size)); + deferred.copies.push(Step::Plane(read, Box::new(move || fill(destination)))); + Some(source) + } + /// Runs the list's submission-time steps; refreshes go into `batch` /// (the title's big buffers, a 174 MB one among them, are read by most /// lists of a submission, through many ranges). Copies and fills that @@ -7327,6 +7515,13 @@ impl HostList { } continue; } + Step::Plane((_, len), fill) => { + let started = std::time::Instant::now(); + fill(); + PREPARING[2].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + PREPARING[3].fetch_add(*len as u64, Ordering::Relaxed); + continue; + } }; us += started.elapsed(); bytes += copied as u64; @@ -8525,6 +8720,7 @@ impl Host { match made { Ok(()) => Some((buffer?, data.cast())), Err(e) => { + crate::residency::allocation_error(&e); tracing::warn!(error = %e, size, "no upload buffer"); None } @@ -8558,8 +8754,11 @@ struct Presenter { ahead: Vec<(HostList, u64)>, hwnd: HWND, meter: Meter, + composer: Option<crate::compose::Composer>, #[cfg(feature = "diagnostics")] panel: panel::Panel, + #[cfg(feature = "diagnostics")] + menu: menu::Menu, } /// The frame rate, shown in the window's caption every second and logged @@ -8849,7 +9048,13 @@ impl Meter { self.caption = Some(buffer); } let Some(caption) = &self.caption else { return }; - let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame"); + // LOCAL (11/26): with frame generation, the frames shown too. + let shown = crate::fg::shown_per_frame(); + let text = if shown > 1 { + format!(" | VIctory {fps:.0} fps (frame gen {:.0} fps) {ms:.1} ms/frame {draws:.0} draws/frame", fps * f64::from(shown)) + } else { + format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame") + }; let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect(); text.push(0); // Setting the text waits for the window's thread (a title thread, @@ -8881,25 +9086,40 @@ impl Host { /// Shows `texture`, which is in `state` (a host state) and stays in it, /// as frame `frame` (saved if captures are on). `None` if nothing was /// shown; else, in diagnostics builds, whether the frame was black. + #[allow(dead_code)] pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> { - self.present_over(texture, state, None, frame) + self.present_planes(texture, state, None, frame) } - /// LOCAL (port of fxceless #1189): [`Self::present`], with a second - /// plane laid over `texture` if there is one (`crate::compose`): its - /// texture and its state, which it is left in. - pub(crate) fn present_over( + /// Shows `texture`, optionally alpha-compositing a second `overlay` plane + /// over it (Series S two-plane presentation), and returns them to their states. + pub(crate) fn present_planes( &self, texture: &ID3D12Resource, state: u32, - over: Option<(&ID3D12Resource, u32)>, + overlay: Option<(&ID3D12Resource, u32)>, frame: u64, ) -> Option<bool> { // SAFETY: a live resource. let desc = unsafe { texture.GetDesc() }; - let Some(format) = swap_format(desc.Format) else { - tracing::warn!(format = desc.Format.0, "cannot present this format"); - return None; + let planes = overlay.and_then(|(over, over_state)| { + // SAFETY: a live overlay resource. + let over_desc = unsafe { over.GetDesc() }; + Some(( + over, + D3D12_RESOURCE_STATES(over_state as i32), + crate::compose::view(&desc)?, + crate::compose::view(&over_desc)?, + )) + }); + let format = if planes.is_some() { + DXGI_FORMAT_R8G8B8A8_UNORM + } else { + let Some(format) = swap_format(desc.Format) else { + tracing::warn!(format = desc.Format.0, "cannot present this format"); + return None; + }; + format }; let (width, height) = (desc.Width as u32, desc.Height); let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner()); @@ -8912,7 +9132,18 @@ impl Host { } }; } + let state_u32 = state; let p = presenter.as_mut()?; + if planes.is_some() && p.composer.is_none() { + match crate::compose::Composer::new(self, format) { + Ok(c) => p.composer = Some(c), + Err(e) => { + tracing::warn!(error = %e, "two-plane composer not made; showing base plane only"); + drop(presenter); + return self.present_planes(texture, state_u32, None, frame); + } + } + } if (p.width, p.height, p.format) != (width, height, format) { // Presents sent ahead hold back buffers until they have run. settle_now(WHY_SYNC); @@ -8923,6 +9154,9 @@ impl Host { }; match resized { Ok(()) => { + if p.format != format { + p.composer = None; + } (p.width, p.height, p.format) = (width, height, format); tracing::info!( width, @@ -8939,8 +9173,18 @@ impl Host { } } } - let state = D3D12_RESOURCE_STATES(state as i32); - // SAFETY: our swap chain, list and a live source texture. + if planes.is_some() && p.composer.is_none() { + match crate::compose::Composer::new(self, format) { + Ok(c) => p.composer = Some(c), + Err(e) => { + tracing::warn!(error = %e, "two-plane composer not made after resize; showing base plane only"); + drop(presenter); + return self.present_planes(texture, state_u32, None, frame); + } + } + } + let state = D3D12_RESOURCE_STATES(state_u32 as i32); + // SAFETY: our swap chain, list and live source texture(s). unsafe { let index = p.swap_chain.GetCurrentBackBufferIndex(); let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else { @@ -8969,42 +9213,136 @@ impl Host { None => &p.copy, }; copy.reset(); + copy.keep(texture); let list = ©.list; - list.ResourceBarrier(&[ - transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), - transition( + let composed = if let Some((over, over_state, base_fmt, over_fmt)) = planes { + copy.keep(over); + if let Some(composer) = p.composer.as_mut() { + let mut pre = Vec::with_capacity(3); + if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + pre.push(transition(texture, state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); + } + if over_state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + pre.push(transition(over, over_state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); + } + pre.push(transition(&back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)); + list.ResourceBarrier(&pre); + let compose_slot = slot.map_or(0, |i| i + 1); + if let Err(err) = composer.record( + self, + compose_slot, + list, + [(texture, base_fmt), (over, over_fmt)], + &back, + (width, height), + ) { + copy.close(); + drop(back); + drop(presenter); + tracing::warn!(%err, "could not record display composite; presenting the base plane"); + return self.present_planes(texture, state_u32, None, frame); + } + static ONCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !ONCE.swap(true, Ordering::Relaxed) { + tracing::info!( + frame, + width, + height, + base_format = base_fmt.0, + overlay_format = over_fmt.0, + "display output: compositing two planes (overlay active)" + ); + } + let mut post = Vec::with_capacity(3); + if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + post.push(transition(texture, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, state)); + } + if over_state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + post.push(transition(over, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, over_state)); + } + post.push(transition( + &back, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_DEST, + )); + list.ResourceBarrier(&post); + true + } else { + false + } + } else { + false + }; + if !composed { + let mut pre = Vec::with_capacity(2); + if state != D3D12_RESOURCE_STATE_COPY_SOURCE { + pre.push(transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE)); + } + pre.push(transition( &back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST, - ), - ]); - // LOCAL (port of fxceless #1189): the second plane laid over the - // first, into a texture of ours shown instead (`crate::compose`). - let laid = over.and_then(|(ui, ui_state)| crate::compose::record(&self.device, list, texture, ui, ui_state)); - if let Some(laid) = &laid { - copy.keep(laid); + )); + list.ResourceBarrier(&pre); + list.CopyResource(&back, texture); } - list.CopyResource(&back, laid.as_ref().unwrap_or(texture)); #[cfg(feature = "diagnostics")] let capture = crate::capture::wanted(frame) - .then(|| crate::capture::read_back(&self.device, list, texture)) + .then(|| { + if composed { + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let res = crate::capture::read_back(&self.device, list, &back); + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); + res + } else { + crate::capture::read_back(&self.device, list, texture) + } + }) .flatten(); #[cfg(feature = "diagnostics")] - let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) }; + let probe = if slot.is_some() || composed { + None + } else { + crate::capture::probe(&self.device, list, texture) + }; #[cfg(feature = "diagnostics")] - let watched = crate::popwatch::take(&self.device, list, texture); + let watched = if composed { + None + } else { + crate::popwatch::take(&self.device, list, texture) + }; #[cfg(feature = "diagnostics")] p.panel.draw(self, copy, &back, (width, height), format); + #[cfg(feature = "diagnostics")] + p.menu.draw(self, copy, &back, (width, height), format); #[cfg(not(feature = "diagnostics"))] let _ = frame; - list.ResourceBarrier(&[ - transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), - transition( + if composed { + list.ResourceBarrier(&[transition( &back, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT, - ), - ]); + )]); + } else { + let mut post = Vec::with_capacity(2); + if state != D3D12_RESOURCE_STATE_COPY_SOURCE { + post.push(transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state)); + } + post.push(transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PRESENT, + )); + list.ResourceBarrier(&post); + } copy.close(); let flown = match slot { Some(i) => { @@ -9030,10 +9368,14 @@ impl Host { #[cfg(feature = "diagnostics")] crate::replay::record::present(texture, state); let mut showing = crate::timeline::span("the host's Present"); + crate::fg::present_start(); let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + crate::fg::present_end(); showing.next("the frame meter"); #[cfg(feature = "diagnostics")] p.panel.frame(p.meter.line_due()); + #[cfg(feature = "diagnostics")] + p.menu.frame(); p.meter.frame(p.hwnd); showing.end(); #[cfg(feature = "diagnostics")] @@ -9057,6 +9399,8 @@ impl Host { // SAFETY: plain object creation for our window. unsafe { let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + // LOCAL (11/26): with `VICTORY_FRAME_GEN`, Streamline's proxy factory (crate::fg). + let factory = crate::fg::start(&self.device, factory); let desc = DXGI_SWAP_CHAIN_DESC1 { Width: width, Height: height, @@ -9086,8 +9430,11 @@ impl Host { ahead: Vec::new(), hwnd, meter: Meter::new(), + composer: None, #[cfg(feature = "diagnostics")] panel: panel::Panel::new(), + #[cfg(feature = "diagnostics")] + menu: menu::Menu::new(), }) } } diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 9ee1494..166addd 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -201,6 +201,7 @@ pub(super) fn copied_read(copies: &[Writer], runs: &[&HostList]) -> bool { .iter() .any(|w| w.from < *at + *len && *at < w.to && w.shadow.as_ref().is_none_or(|s| !Arc::ptr_eq(s, shadow))), Step::Host(_, (from, to)) => copies.iter().any(|w| w.from < *to && *from < w.to), + Step::Plane((at, len), _) => copies.iter().any(|w| w.from < at.saturating_add(*len) && *at < w.to), _ => false, }) }) @@ -440,6 +441,11 @@ fn does_of(written: &[(usize, usize)], runs: &[&HostList]) -> (Vec<Does>, Vec<(u asked: touches(written, at, at + len), } } + &Step::Plane((at, len), _) => Does::Read { + from: at, + to: at.saturating_add(len), + asked: touches(written, at, at.saturating_add(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, diff --git a/crates/victory-gpu/src/host/menu.rs b/crates/victory-gpu/src/host/menu.rs new file mode 100644 index 0000000..837995a --- /dev/null +++ b/crates/victory-gpu/src/host/menu.rs @@ -0,0 +1,528 @@ +//! LOCAL (11/26): the F1 settings menu. F1 shows and hides it while our +//! window has the focus; Up/Down pick a setting, Left/Right change it, Enter +//! runs the line picked (save, save and restart, reset, close), Esc closes. +//! While it is shown the title sees no keyboard (`crate::SETTINGS_MENU_OPEN`, +//! read by the input module); a pad still works. +//! +//! Most settings are read once at start, so a change is saved to the file +//! `VICTORY_MENU_FILE` names (play.ps1 sets it to the play folder's +//! settings.txt and applies it at every start) and takes effect at the next +//! start; "SAVE AND RESTART" starts play.ps1 again (`VICTORY_MENU_PLAY`, +//! with `VICTORY_MENU_ARGS`) and ends this run. Lines marked LIVE change at +//! once. +//! +//! Drawn as the stats panel is (`super::panel`): white text on a black box, +//! copied onto the swap chain's buffer, in the middle of the picture. + +use std::sync::atomic::Ordering; +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + GetAsyncKeyState, VK_DOWN, VK_ESCAPE, VK_F1, VK_LEFT, VK_RETURN, VK_RIGHT, VK_UP, +}; +use windows_sys::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId}; + +use super::panel::{colours, glyph}; +use super::{Host, HostList, transition}; + +const GLYPH: (u32, u32) = (5, 7); +const CELL: (u32, u32) = (6, 9); +const COLUMNS: u32 = 60; +/// Lines of the box: a title, a help line, a blank, the settings shown, a +/// blank and a note. +const ROWS: usize = 20; +const LINES: u32 = ROWS as u32 + 5; +const RIM: u32 = 4; +const UPLOADS: usize = 4; + +/// A setting: the variable, its name in the menu, the values it takes +/// (`""`: not set, the build's own default), and whether a change applies at once. +struct Item { + var: &'static str, + label: &'static str, + values: &'static [(&'static str, &'static str)], + live: bool, +} + +const OFF_ON: &[(&str, &str)] = &[("0", "OFF"), ("1", "ON")]; +const UNSET_ON: &[(&str, &str)] = &[("", "OFF"), ("1", "ON")]; + +#[rustfmt::skip] +const ITEMS: &[Item] = &[ + Item { var: "VICTORY_UPSCALE", label: "UPSCALER", values: &[("dlss", "DLSS"), ("stretch", "STRETCH"), ("", "GAME FSR4 (SLOW)")], live: false }, + Item { var: "VICTORY_FRAME_GEN", label: "FRAME GEN (NOT WITH RAY TR.)", values: &[("", "OFF"), ("2", "2X"), ("3", "3X"), ("4", "4X"), ("5", "5X"), ("6", "6X (MOST)")], live: false }, + Item { var: "VICTORY_FPS_CAP", label: "FRAME RATE CAP", values: &[("", "GAME (30)"), ("60", "60"), ("120", "120"), ("0", "NONE")], live: true }, + Item { var: "VICTORY_BVH_BUILDER", label: "RAY TRACING (REAL LIGHTING)", values: &[("", "OFF"), ("1", "ON")], live: false }, + Item { var: "VICTORY_DLSS_PRESET", label: "DLSS MODEL", values: &[("", "DEFAULT (K)"), ("K", "K TRANSFORMER"), ("J", "J TRANSFORMER"), ("M", "M TRANSFORMER"), ("L", "L TRANSFORMER")], live: false }, + Item { var: "VICTORY_DLSS_SHARPNESS", label: "DLSS SHARPNESS", values: &[("0", "0"), ("0.25", "0.25"), ("0.5", "0.5"), ("0.75", "0.75"), ("1", "1")], live: true }, + Item { var: "VICTORY_MENU_SMOOTH_MOTION", label: "SMOOTH MOTION", values: &[("1", "ON"), ("0", "OFF")], live: false }, + Item { var: "VICTORY_MENU_CONSOLE", label: "CONSOLE", values: &[("series-s", "SERIES S"), ("series-x", "SERIES X")], live: false }, + Item { var: "VICTORY_ADAPTER", label: "GRAPHICS CARD", values: &[("", "WINDOWS DEFAULT"), ("#0", "CARD 0"), ("#1", "CARD 1"), ("#2", "CARD 2")], live: false }, + Item { var: "VICTORY_PANEL", label: "STATS PANEL (F3)", values: UNSET_ON, live: true }, + Item { var: "VICTORY_RELAY", label: "RELAY (SPEED, TRIANGLES)", values: &[("2", "2"), ("1", "1"), ("0", "0 OFF")], live: false }, + Item { var: "VICTORY_RELAY_COPY", label: "RELAY COPY QUEUE", values: OFF_ON, live: false }, + Item { var: "VICTORY_FETCH_CHECK", label: "FETCH CHECK", values: OFF_ON, live: false }, + Item { var: "VICTORY_WIDE_BACK", label: "WIDE COPY BACK", values: OFF_ON, live: false }, + Item { var: "VICTORY_CARD_STEPS", label: "CARD STEPS", values: &[("2", "2"), ("1", "1"), ("0", "0 OFF")], live: false }, + Item { var: "VICTORY_TEXTURE_NO_WAIT", label: "TEXTURE NO WAIT", values: OFF_ON, live: false }, + Item { var: "VICTORY_HEAP_RECHECK_EVERY", label: "TEXTURE RECHECK (OIL TEST)", values: &[("", "OFF"), ("60", "EVERY 60 FRAMES"), ("15", "EVERY 15 FRAMES")], live: false }, + Item { var: "VICTORY_NULL_SAMPLER_LINEAR", label: "LINEAR STAND-IN SAMPLER", values: UNSET_ON, live: false }, + Item { var: "VICTORY_AMBIENT", label: "AMBIENT STAND-IN", values: OFF_ON, live: false }, + Item { var: "VICTORY_AMBIENT_AIR", label: "FOG CAP", values: &[("1.5", "1.5"), ("1", "1"), ("2", "2"), ("", "NONE")], live: false }, + Item { var: "VICTORY_NAN_SCRUB", label: "NAN SCRUB (SHADERS REBUILD)", values: OFF_ON, live: false }, + Item { var: "VICTORY_THIN", label: "THIN", values: OFF_ON, live: false }, + Item { var: "VICTORY_JOIN_PARTS", label: "JOIN PARTS", values: &[("8", "8"), ("4", "4"), ("16", "16"), ("1", "1")], live: false }, + Item { var: "VICTORY_JOIN_COPIES", label: "JOIN COPIES", values: OFF_ON, live: false }, + Item { var: "VICTORY_UPLOAD_AHEAD", label: "UPLOAD AHEAD", values: OFF_ON, live: false }, + Item { var: "VICTORY_INDIRECT_WINDOW", label: "INDIRECT WINDOW", values: OFF_ON, live: false }, + Item { var: "VICTORY_INDIRECT_BATCH", label: "INDIRECT BATCH", values: &[("2", "2"), ("1", "1"), ("0", "0 OFF")], live: false }, + Item { var: "VICTORY_CARD_REHASH_RUNS", label: "CARD REHASH RUNS", values: OFF_ON, live: false }, + Item { var: "VICTORY_MAP_THREADS", label: "MAP THREADS", values: OFF_ON, live: false }, + Item { var: "VICTORY_TITLE_PRIORITIES", label: "TITLE THREAD PRIORITIES", values: OFF_ON, live: false }, + Item { var: "VICTORY_CARD_AWAKE", label: "KEEP CARD AWAKE", values: OFF_ON, live: false }, + Item { var: "VICTORY_SHOW_AFTER", label: "SHOW AFTER", values: OFF_ON, live: false }, + Item { var: "VICTORY_PIPELINE_WAIT_MS", label: "SHADER WAIT MS", values: &[("10000", "10000"), ("30000", "30000"), ("1000", "1000"), ("0", "0 SKIP")], live: false }, + Item { var: "VICTORY_DYNAMIC_SLOTS", label: "DESCRIPTOR SLOTS", values: &[("524288", "524288"), ("262144", "262144"), ("1000000", "1000000")], live: false }, + Item { var: "VICTORY_CARD_BUFFERS_MB", label: "CARD BUFFERS MB", values: &[("1536", "1536"), ("1024", "1024"), ("2048", "2048"), ("512", "512"), ("0", "0 OFF")], live: false }, + Item { var: "VICTORY_RENDER_SCALE", label: "RENDER SCALE", values: &[("", "GAME (720P)"), ("0.5", "0.5 (540P)"), ("0.75", "0.75")], live: false }, + Item { var: "VICTORY_OWN_UPSCALER", label: "OWN UPSCALER", values: UNSET_ON, live: false }, + Item { var: "VICTORY_D3D12_DRED", label: "CRASH BREADCRUMBS", values: &[("light", "LIGHT"), ("", "OFF")], live: false }, +]; + +/// The lines after the settings. +const ACTIONS: [&str; 4] = ["SAVE AND RESTART NOW", "SAVE FOR NEXT START", "RESET ALL TO PLAY DEFAULTS", "CLOSE"]; + +fn get(var: &str) -> String { + std::env::var(var).unwrap_or_default() +} + +/// Whether a change of `item` shows at once. +fn live(item: &Item) -> bool { + item.live || (item.var == "VICTORY_FRAME_GEN" && crate::fg::active()) +} + +/// The index of `value` among the item's values (an unknown value: shown as +/// itself, at the end). +fn index_of(item: &Item, value: &str) -> Option<usize> { + item.values.iter().position(|(v, _)| *v == value) +} + +/// Keys pressed, gathered on a thread of their own every 10 ms: a frame +/// lasts 50 ms and more, and a short press would fall between two frames. +fn keys() -> &'static Mutex<Vec<u16>> { + static KEYS: OnceLock<Mutex<Vec<u16>>> = OnceLock::new(); + KEYS.get_or_init(|| { + let _ = std::thread::Builder::new().name("settings menu keys".into()).spawn(|| { + const WATCHED: [u16; 7] = [VK_F1, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT, VK_RETURN, VK_ESCAPE]; + let mut was = [false; WATCHED.len()]; + loop { + std::thread::sleep(Duration::from_millis(10)); + let mut process = 0; + // SAFETY: plain queries; room for the answer. + unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) }; + let ours = process == std::process::id(); + for (i, &vk) in WATCHED.iter().enumerate() { + // SAFETY: a plain query. + let down = ours && unsafe { GetAsyncKeyState(i32::from(vk)) } < 0; + if down && !was[i] { + keys().lock().unwrap_or_else(|e| e.into_inner()).push(vk); + } + was[i] = down; + } + } + }); + Mutex::new(Vec::new()) + }) +} + +/// The box's size in pixels. +const fn size(scale: u32) -> (u32, u32) { + ((COLUMNS * CELL.0 + 2 * RIM) * scale, (LINES * CELL.1 + 2 * RIM) * scale) +} + +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 +} + +fn painted(lines: &[String], scale: u32, colours: [&[u8]; 2], pitch: usize) -> Vec<u8> { + 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 +} + +struct Buffers { + format: DXGI_FORMAT, + scale: u32, + pitch: u32, + uploads: Vec<(ID3D12Resource, *mut u8)>, + card: ID3D12Resource, + turn: usize, + fresh: bool, + /// The card's buffer was copied into before (it is in the copy-source state; + /// at first it is in the common state, promoted by the first copy). + used: 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<Buffers> { + 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::<Option<Vec<_>>>()?; + 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<ID3D12Resource> = 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, used: 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 frames ago. + unsafe { std::ptr::copy_nonoverlapping(picture.as_ptr(), self.uploads[self.turn].1, picture.len()) }; + self.fresh = true; + } +} + +/// The menu of a presenter. +pub(super) struct Menu { + /// The values chosen, by item (as at start until changed). + values: Vec<String>, + /// The values at start. + started: Vec<String>, + /// The line picked: an item, or an action after them. + at: usize, + note: String, + changed: bool, + buffers: Option<Buffers>, + failed: bool, +} + +impl Menu { + pub(super) fn new() -> Menu { + // Start the key thread now: F1 must be seen while the menu is closed. + let _ = keys(); + let values: Vec<String> = ITEMS.iter().map(|i| get(i.var)).collect(); + Menu { started: values.clone(), values, at: 0, note: String::new(), changed: true, buffers: None, failed: false } + } + + fn open() -> bool { + crate::SETTINGS_MENU_OPEN.load(Ordering::Relaxed) + } + + fn lines(&self) -> Vec<String> { + let total = ITEMS.len() + ACTIONS.len(); + let first = self.at.saturating_sub(ROWS / 2).min(total.saturating_sub(ROWS)); + let mut out = vec![ + "SETTINGS F1 OR ESC CLOSES".to_owned(), + "UP/DOWN PICK LEFT/RIGHT CHANGE ENTER DOES IT".to_owned(), + String::new(), + ]; + for row in first..(first + ROWS).min(total) { + let cursor = if row == self.at { '>' } else { ' ' }; + let line = if let Some(item) = ITEMS.get(row) { + let value = &self.values[row]; + let shown = index_of(item, value).map_or(value.to_ascii_uppercase(), |i| item.values[i].1.to_owned()); + let mark = if *value != self.started[row] { if live(item) { " *LIVE" } else { " *" } } else if live(item) { " LIVE" } else { "" }; + format!("{cursor} {:<27} < {shown} >{mark}", item.label) + } else { + format!("{cursor} {}", ACTIONS[row - ITEMS.len()]) + }; + out.push(line.chars().take(COLUMNS as usize).collect()); + } + while out.len() < 3 + ROWS { + out.push(String::new()); + } + out.push(String::new()); + out.push(if self.note.is_empty() { "* = CHANGED: APPLIES AT THE NEXT START UNLESS LIVE".to_owned() } else { self.note.clone() }); + out + } + + /// Changes item `i` by `step` (+1 / -1) through its values. + fn change(&mut self, i: usize, step: isize) { + let item = &ITEMS[i]; + let n = item.values.len() as isize; + let now = index_of(item, &self.values[i]).map_or(-1, |x| x as isize); + let next = if now < 0 { if step > 0 { 0 } else { n - 1 } } else { (now + step).rem_euclid(n) }; + self.values[i] = item.values[next as usize].0.to_owned(); + if live(item) { + self.apply_live(i); + } + self.note.clear(); + } + + /// With a start that had frame generation on, its amount (and off) changes while running; + /// from a start without it, turning it on needs the restart (Streamline's swap chain). + fn apply_live(&self, i: usize) { + let (var, value) = (ITEMS[i].var, &self.values[i]); + // SAFETY: the variables changed here are read by this build with + // std::env::var at each use; Windows' environment block is locked by + // the process heap's routines, and std holds its own lock. + unsafe { + if value.is_empty() { + std::env::remove_var(var); + } else { + std::env::set_var(var, value); + } + } + if var == "VICTORY_FPS_CAP" { + crate::frame::set_cap(value); + } + if var == "VICTORY_PANEL" { + super::panel::shown().store(!value.is_empty(), Ordering::Relaxed); + } + } + + /// Writes the changed values over those in the settings file. + fn save(&mut self) -> bool { + let Some(path) = std::env::var_os("VICTORY_MENU_FILE") else { + self.note = "NO SETTINGS FILE: START THE GAME WITH PLAY.PS1".to_owned(); + return false; + }; + let mut kept: Vec<(String, String)> = std::fs::read_to_string(&path) + .unwrap_or_default() + .lines() + .filter_map(|l| l.split_once('=').map(|(k, v)| (k.trim().to_owned(), v.trim().to_owned()))) + .filter(|(k, _)| k.starts_with("VICTORY_")) + .collect(); + for (i, item) in ITEMS.iter().enumerate() { + if self.values[i] == self.started[i] { + continue; + } + kept.retain(|(k, _)| k != item.var); + kept.push((item.var.to_owned(), self.values[i].clone())); + } + let mut text = String::from("# Saved by the F1 menu; play.ps1 applies these after its own settings (an empty value: unset).\r\n"); + for (k, v) in &kept { + text.push_str(&format!("{k}={v}\r\n")); + } + match std::fs::write(&path, text) { + Ok(()) => { + tracing::info!(path = %std::path::Path::new(&path).display(), "settings menu: saved"); + self.started = self.values.clone(); + self.note = "SAVED. APPLIES AT THE NEXT START".to_owned(); + true + } + Err(e) => { + tracing::warn!(error = %e, "settings menu: not saved"); + self.note = "COULD NOT SAVE THE SETTINGS FILE".to_owned(); + false + } + } + } + + /// Starts play.ps1 again in a new console, a few seconds on, and ends this run. + fn restart(&mut self) { + use std::os::windows::process::CommandExt; + let Some(play) = std::env::var_os("VICTORY_MENU_PLAY") else { + self.note = "SAVED. RESTART PLAY.PS1 YOURSELF".to_owned(); + return; + }; + let play = play.to_string_lossy().replace('\'', "''"); + let args = get("VICTORY_MENU_ARGS"); + let command = format!("Start-Sleep 3; & '{play}' {args}"); + const CREATE_NEW_CONSOLE: u32 = 0x10; + match std::process::Command::new("powershell.exe") + .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &command]) + .creation_flags(CREATE_NEW_CONSOLE) + .spawn() + { + Ok(_) => { + tracing::info!(command, "settings menu: restarting"); + // Ended at once: std::process::exit runs the DLLs' unloading, and with Streamline + // loaded that never came back (11/26: a windowless leftover with one thread + // and 27 GB, which also kept the new build from being put in place). + // SAFETY: this process, with nothing of its own left to save. + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; + TerminateProcess(GetCurrentProcess(), 0); + } + std::process::exit(0); + } + Err(e) => { + tracing::warn!(error = %e, "settings menu: restart failed"); + self.note = "SAVED, BUT THE RESTART FAILED".to_owned(); + } + } + } + + /// Empties the settings file: play.ps1's own settings at the next start. + fn reset(&mut self) { + if let Some(path) = std::env::var_os("VICTORY_MENU_FILE") { + let _ = std::fs::remove_file(path); + } + self.note = "RESET. PLAY DEFAULTS AT THE NEXT START".to_owned(); + } + + /// A frame was presented: the keys pressed since the last one. + pub(super) fn frame(&mut self) { + let pressed = std::mem::take(&mut *keys().lock().unwrap_or_else(|e| e.into_inner())); + if pressed.is_empty() { + return; + } + let total = ITEMS.len() + ACTIONS.len(); + for vk in pressed { + let open = Self::open(); + if vk == VK_F1 || (open && vk == VK_ESCAPE) { + crate::SETTINGS_MENU_OPEN.store(!open && vk == VK_F1, Ordering::Relaxed); + self.note.clear(); + self.changed = true; + continue; + } + if !open { + continue; + } + match vk { + VK_UP => self.at = (self.at + total - 1) % total, + VK_DOWN => self.at = (self.at + 1) % total, + VK_LEFT if self.at < ITEMS.len() => self.change(self.at, -1), + VK_RIGHT if self.at < ITEMS.len() => self.change(self.at, 1), + VK_RETURN if self.at < ITEMS.len() => self.change(self.at, 1), + VK_RETURN => match self.at - ITEMS.len() { + 0 => { + if self.save() { + self.restart(); + } + } + 1 => { + self.save(); + } + 2 => self.reset(), + _ => crate::SETTINGS_MENU_OPEN.store(false, Ordering::Relaxed), + }, + _ => {} + } + self.changed = true; + } + } + + /// Records the copy of the box onto `back` (in the copy-destination state). + pub(super) fn draw(&mut self, host: &Host, list: &HostList, back: &ID3D12Resource, (width, height): (u32, u32), format: DXGI_FORMAT) { + if !Self::open() || self.failed { + return; + } + let _ours = crate::replay::record::unrecorded(); + let scale = (height / 540).max(1); + if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) { + std::mem::forget(self.buffers.take()); + self.buffers = Buffers::new(host, format, scale); + self.failed = self.buffers.is_none(); + self.changed = true; + } + let lines = if self.changed { Some(self.lines()) } else { None }; + let Some(buffers) = &mut self.buffers else { return }; + if let Some(lines) = lines { + self.changed = false; + buffers.write(&lines); + } + let (w, h) = size(scale); + let (w, h) = (w.min(width), h.min(height)); + let (x, y) = ((width - w) / 2, (height - h) / 2); + let list = &list.list; + // SAFETY: an open list and live resources; the box lies within both. + unsafe { + if std::mem::take(&mut buffers.fresh) { + if std::mem::replace(&mut buffers.used, true) { + list.ResourceBarrier(&[transition(&buffers.card, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST)]); + } + 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: size(scale).0, Height: size(scale).1, 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, bottom: h, back: 1 }; + list.CopyTextureRegion(&to, x, y, 0, &from, Some(&part)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_line_fits_and_every_character_has_a_picture() { + let mut menu = Menu { values: ITEMS.iter().map(|_| String::new()).collect(), started: Vec::new(), at: 0, note: String::new(), changed: false, buffers: None, failed: false }; + menu.started = menu.values.clone(); + for at in 0..ITEMS.len() + ACTIONS.len() { + menu.at = at; + for line in menu.lines() { + assert!(line.len() <= COLUMNS as usize, "{line}"); + for c in line.bytes() { + assert_ne!(glyph(c.to_ascii_uppercase()), glyph(b'#'), "{line}: {}", c as char); + } + } + } + } + + #[test] + fn values_cycle_both_ways() { + let mut menu = Menu { values: ITEMS.iter().map(|i| i.values[0].0.to_owned()).collect(), started: Vec::new(), at: 0, note: String::new(), changed: false, buffers: None, failed: false }; + menu.started = menu.values.clone(); + let n = ITEMS[0].values.len(); + for _ in 0..n { + menu.change(0, 1); + } + assert_eq!(menu.values[0], ITEMS[0].values[0].0); + menu.change(0, -1); + assert_eq!(menu.values[0], ITEMS[0].values[n - 1].0); + } +} diff --git a/crates/victory-gpu/src/host/panel.rs b/crates/victory-gpu/src/host/panel.rs index a3d2f9b..808bc52 100644 --- a/crates/victory-gpu/src/host/panel.rs +++ b/crates/victory-gpu/src/host/panel.rs @@ -40,7 +40,7 @@ fn asked() -> bool { } /// Whether it is shown now. -fn shown() -> &'static AtomicBool { +pub(super) fn shown() -> &'static AtomicBool { static SHOWN: OnceLock<AtomicBool> = OnceLock::new(); SHOWN.get_or_init(|| AtomicBool::new(asked())) } @@ -61,7 +61,7 @@ fn pressed() -> bool { /// Seven rows of five dots, the leftmost the highest bit. #[rustfmt::skip] -const fn glyph(c: u8) -> [u8; 7] { +pub(super) 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], @@ -103,6 +103,19 @@ const fn glyph(c: u8) -> [u8; 7] { b'/' => [0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000], b'-' => [0, 0, 0, 0b11111, 0, 0, 0], b' ' => [0; 7], + // LOCAL (11/26): for the F1 settings menu (menu.rs). + b'>' => [0b01000, 0b00100, 0b00010, 0b00001, 0b00010, 0b00100, 0b01000], + b'<' => [0b00010, 0b00100, 0b01000, 0b10000, 0b01000, 0b00100, 0b00010], + b'*' => [0, 0b00100, 0b10101, 0b01110, 0b10101, 0b00100, 0], + b':' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0], + b'_' => [0, 0, 0, 0, 0, 0, 0b11111], + b'=' => [0, 0, 0b11111, 0, 0b11111, 0, 0], + b'(' => [0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010], + b')' => [0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000], + b'+' => [0, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0], + b',' => [0, 0, 0, 0, 0b01100, 0b00100, 0b01000], + b'!' => [0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0, 0b00100], + b'?' => [0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0, 0b00100], _ => [0b11111, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11111], } } @@ -133,7 +146,7 @@ fn lit(lines: &[String], x: u32, y: u32) -> bool { } /// The bytes of a black and a white pixel of a swap chain's format. -fn colours(format: DXGI_FORMAT) -> Option<[&'static [u8]; 2]> { +pub(super) 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]], @@ -213,8 +226,12 @@ fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, host: &Host) -> Vec let [budget, used, _, shared] = host.video_memory().unwrap_or_default(); 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 {:.0}", c[10], c[8]), + // LOCAL (11/26): with frame generation, the frames shown beside those rendered. + match crate::fg::shown_per_frame() { + 1 => format!("FPS {:.1} FRAME {ms:.1} MS", 1e3 / ms.max(0.001)), + n => format!("FPS {:.1} FG {:.1} FRAME {ms:.1} MS", 1e3 / ms.max(0.001), f64::from(n) * 1e3 / ms.max(0.001)), + }, + format!("DRAWS {:.0} DROPPED {:.0} LONGEST {worst:.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), diff --git a/crates/victory-gpu/src/host/place.rs b/crates/victory-gpu/src/host/place.rs index 9e815d4..b5a7bb7 100644 --- a/crates/victory-gpu/src/host/place.rs +++ b/crates/victory-gpu/src/host/place.rs @@ -119,6 +119,7 @@ pub(super) fn read_by(runs: &[&HostList], mut ranges: Vec<(usize, usize)>) -> bo let (at, len) = staging.memory(); touches(&ranges, at, at + len) } + &Step::Plane((at, len), _) => touches(&ranges, at, at.saturating_add(len)), Step::Host(_, (from, to)) => touches(&ranges, *from, *to), Step::Placed(p) => p.from.is_some() && touches(&ranges, p.src, p.src + p.len), _ => false, diff --git a/crates/victory-gpu/src/host/upcheck.rs b/crates/victory-gpu/src/host/upcheck.rs index d82a0c9..56ff942 100644 --- a/crates/victory-gpu/src/host/upcheck.rs +++ b/crates/victory-gpu/src/host/upcheck.rs @@ -317,6 +317,48 @@ fn known(copy: u64, at: usize) -> String { type Crossed = BTreeMap<((u64, u64), (u64, u64)), (u64, usize, usize)>; static CROSSED: Mutex<(u64, Crossed)> = Mutex::new((0, BTreeMap::new())); +/// LOCAL (11/26, `VICTORY_RELAY_CROSS=1`): whether a refresh of `runs` reads +/// title memory that a flight in the air may be writing through another copy +/// of it ([`reads`] counts those). Such a refresh sends the bytes from before +/// the flight, and draws of that submission read them: one frame of stale +/// vertices and indices (triangles flung across the screen with the relay on, +/// none with `VICTORY_RELAY=0`). The caller settles the flights first. +pub(crate) fn cross_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_CROSS").is_some_and(|v| v == "1")) +} + +pub(super) fn crossed(runs: &[&HostList]) -> bool { + let mut writes: Vec<(std::sync::Arc<Shadow>, usize, usize)> = Vec::new(); + let mut all = Vec::new(); + for item in &super::line().line { + if let Late::Run(flight) = item { + for (shadow, ranges) in &flight.back { + writes.extend(ranges.iter().map(|&(a, b)| (shadow.clone(), a, b))); + join_ranges(&mut all, ranges.iter().copied()); + } + } + } + if writes.is_empty() { + return false; + } + for list in runs { + for step in &list.deferred().copies { + let Step::Refresh(shadow, at, len) = step else { + continue; + }; + let (from, to) = (*at, *at + *len); + if !touches(&all, from, to) { + continue; + } + if writes.iter().any(|(writer, a, b)| *a < to && from < *b && !std::sync::Arc::ptr_eq(writer, shadow)) { + return true; + } + } + } + false +} + /// Flights are in the air and `runs` are about to be prepared: which /// refreshes of theirs read title memory that a flight may be writing through /// another copy of it. Such a refresh takes what was there before the flight diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 5c13842..e50f572 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -295,12 +295,10 @@ pub(crate) fn amd(device: &ID3D12Device) -> bool { /// Whether a record that does not fit in what is left of its list's budget /// takes the rest, so that every record after it runs empty too -/// (`VICTORY_INDIRECT_REST=0`: it takes nothing, and the next one that fits -/// runs). A list whose budget one garbage record empties loses all its later -/// draws, and which record that is may differ from frame to frame. The frame -/// line says how many records a frame are refused. +/// (`VICTORY_INDIRECT_REST=1`; off by default so one oversized record takes +/// nothing and later valid draws still run). fn rest() -> u32 { - u32::from(std::env::var("VICTORY_INDIRECT_REST").map_or(true, |v| v != "0")) + u32::from(std::env::var("VICTORY_INDIRECT_REST").is_ok_and(|v| v == "1")) } /// The clamp compiled from `source` (ours, or in the benchmark the one it @@ -2607,7 +2605,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { /// left then, and the records as clamped. fn four_records_of_a_group(rest: bool) -> Option<(u32, Vec<u32>)> { let mut warp = WarpHarness::new()?; - let source = if rest { SOURCE.to_owned() } else { SOURCE.replace("REST ?", "false ?") }; + let source = SOURCE.replace("REST ?", if rest { "true ?" } else { "false ?" }); let clamp = make_from(&warp.device, &source).expect("the clamp must compile on WARP"); const KIND_DRAW: u32 = 0; const STRIDE: u32 = 16; diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 9441fe2..4ae200b 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -19,10 +19,9 @@ mod ambient; #[cfg(all(windows, feature = "diagnostics"))] mod capture; -pub mod console; -// LOCAL (port of fxceless #1189): Series S interface plane laid over the game (VICTORY_COMPOSE=1). #[cfg(windows)] mod compose; +pub mod console; #[cfg(all(windows, feature = "diagnostics"))] mod copystat; #[cfg(all(windows, feature = "diagnostics"))] @@ -40,6 +39,13 @@ pub mod frame; mod book; #[cfg(windows)] mod host; + +/// LOCAL (11/26): the F1 settings menu is shown (host/menu.rs): the title gets no keyboard. +pub static SETTINGS_MENU_OPEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +#[cfg(windows)] +pub mod streamline; +#[cfg(windows)] +mod fg; #[cfg(windows)] mod indirect; #[cfg(windows)] @@ -61,9 +67,15 @@ pub mod query; pub mod queue; #[cfg(all(windows, feature = "diagnostics"))] pub mod replay; +#[cfg(windows)] +mod residency; pub mod resource; pub mod root; #[cfg(windows)] +mod stretch; +#[cfg(all(windows, feature = "dlss"))] +mod dlss; +#[cfg(windows)] mod safecopy; #[cfg(windows)] mod sampler; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 8a17ddb..1622bb6 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -203,6 +203,12 @@ impl Detached { pub(crate) fn host(&self) -> &crate::host::HostList { &self.host } + + /// Releases this list's dynamic descriptor slots once its GPU submission + /// has completed, without waiting for the full `bury_lag` allocator delay. + pub(crate) fn release_tables(&mut self) { + self._state.tables_done(); + } } /// A host list that has run and waits to be used again, and the bytes of @@ -811,6 +817,165 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> 0 } +/// What the title gives its upscale (`ffxDispatch`, Series S), as plain words +/// so that a list whose calls are only written down (`VICTORY_THIN=1`) can +/// carry it to the thread that records. +#[derive(Clone, Copy, Debug, Default)] +pub struct Upscale { + pub colour: u64, + pub depth: u64, + pub motion: u64, + pub exposure: u64, + pub output: u64, + pub render: [u32; 2], + pub jitter: [f32; 2], + pub motion_scale: [f32; 2], + pub reset: bool, + pub pre_exposure: f32, + pub near: f32, + pub far: f32, + pub frame_ms: f32, + /// DLSS where it can (`crate::dlss`, the `dlss` feature), else a stretch. + pub dlss: bool, +} + +impl Upscale { + pub(crate) const WORDS: usize = 11; + + pub(crate) fn to_words(self) -> [u64; Self::WORDS] { + let pair = |a: f32, b: f32| u64::from(a.to_bits()) | u64::from(b.to_bits()) << 32; + [ + self.colour, + self.depth, + self.motion, + self.exposure, + self.output, + u64::from(self.render[0]) | u64::from(self.render[1]) << 32, + pair(self.jitter[0], self.jitter[1]), + pair(self.motion_scale[0], self.motion_scale[1]), + pair(self.pre_exposure, self.frame_ms), + pair(self.near, self.far), + u64::from(self.reset) | u64::from(self.dlss) << 1, + ] + } + + pub(crate) fn from_words(w: &[u64]) -> Option<Self> { + if w.len() < Self::WORDS { + return None; + } + let pair = |v: u64| [f32::from_bits(v as u32), f32::from_bits((v >> 32) as u32)]; + let [pre_exposure, frame_ms] = pair(w[8]); + let [near, far] = pair(w[9]); + Some(Self { + colour: w[0], + depth: w[1], + motion: w[2], + exposure: w[3], + output: w[4], + render: [w[5] as u32, (w[5] >> 32) as u32], + jitter: pair(w[6]), + motion_scale: pair(w[7]), + pre_exposure, + frame_ms, + near, + far, + reset: w[10] & 1 != 0, + dlss: w[10] & 2 != 0, + }) + } +} + +/// The title's upscale in place of its own FidelityFX passes (slow translated +/// for 32-lane cards): DLSS if asked for and it can, else a plain stretch of +/// the colour input over the output (`crate::stretch`, from +/// CuteBooty/victory-8gb). With `VICTORY_THIN=1` it is written down with the +/// list's other calls and recorded by the thread that records them. False if +/// it could not be recorded or written down. +#[cfg(windows)] +pub fn upscale(this: *const std::ffi::c_void, up: &Upscale) -> bool { + let this: This = this.cast(); + if this.is_null() || up.colour == 0 || up.output == 0 { + return false; + } + if thin::on() { + return thin::upscale(this, up); + } + upscale_now(this, up) +} + +/// [`upscale`], recorded now on the host list behind `this`. +#[cfg(windows)] +pub(super) fn upscale_now(this: This, up: &Upscale) -> bool { + const SHADER_READ: u32 = 0x40; + const UNORDERED: u32 = 0x8; + let t = |a: u64| -> This { a as This }; + let (colour, output) = (t(up.colour), t(up.output)); + let mut done = false; + with_state(this, |list, state| { + let (Some(to), Some(from), Some(host)) = ( + crate::resource::host_resource(output), + crate::resource::host_resource(colour), + crate::host::host(), + ) else { + return; + }; + ensure_state(list, colour, SHADER_READ); + ensure_state(list, output, UNORDERED); + #[cfg(feature = "dlss")] + if up.dlss { + let input = |a: u64| { + let r = t(a); + crate::resource::host_resource(r).inspect(|_| ensure_state(list, r, SHADER_READ)) + }; + let inputs = crate::dlss::Inputs { + colour: from, + depth: input(up.depth), + motion: input(up.motion), + exposure: input(up.exposure), + output: to, + jitter: up.jitter, + motion_scale: up.motion_scale, + render: up.render, + reset: up.reset, + pre_exposure: up.pre_exposure, + near: up.near, + far: up.far, + frame_ms: up.frame_ms, + }; + done = crate::dlss::record(&host.device, &list.list, &inputs); + if done { + // LOCAL (11/26): frame generation's depth and motion vectors (crate::fg). + crate::fg::note_titles(up.depth, up.motion); + } + } + if !done { + done = crate::stretch::record_stretch(&host.device, &list.list, to, from, up.render); + } + if done { + crate::texture::host_written(output); + } + state.replay(list); + }); + done +} + +/// For the upscale probe (`VICTORY_UPSCALE_PROBE=1`): each title texture's +/// host copy as `WxH fmt N` (DXGI format number), or `none`. +#[cfg(windows)] +pub fn upscale_inputs(textures: &[*const std::ffi::c_void]) -> Vec<String> { + textures + .iter() + .map(|&t| match crate::resource::host_resource(t.cast()) { + Some(r) => { + // SAFETY: a live host resource. + let d = unsafe { r.GetDesc() }; + format!("{}x{} fmt {}", d.Width, d.Height, d.Format.0) + } + None => "none".to_owned(), + }) + .collect() +} + /// Moves a title texture's host copy to `state` in the list, if needed. #[cfg(windows)] pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) { diff --git a/crates/victory-gpu/src/list/thin.rs b/crates/victory-gpu/src/list/thin.rs index fe9277d..cfc7aab 100644 --- a/crates/victory-gpu/src/list/thin.rs +++ b/crates/victory-gpu/src/list/thin.rs @@ -469,6 +469,18 @@ const TARGETS: u64 = after(13); const CLEAR_RTV: u64 = after(14); const CLEAR_DSV: u64 = after(15); const COPY_TEXTURE: u64 = after(16); +const UPSCALE: u64 = after(17); + +/// Writes the title's upscale down with the list's calls (`super::upscale`); +/// false if the list has no recording being written. +pub(super) fn upscale(this: This, up: &super::Upscale) -> bool { + let front = front(this); + if front.closed || front.recording.is_none() { + return false; + } + front.put(UPSCALE, &(*up).to_words()); + true +} /// The bytes of `count` things at `items` (none if null). fn bytes_of<'a, T>(items: *const T, count: usize) -> &'a [u8] { @@ -779,6 +791,14 @@ fn translate(list: This, stream: &[u64], left: impl Fn() -> bool) -> (u64, bool) at(w, 2 + 2 * step, boxed), ); } + UPSCALE => { + if let Some(up) = super::Upscale::from_words(w) + && !super::upscale_now(list, &up) + { + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| tracing::warn!("a written-down upscale could not be recorded: its output stays as it is")); + } + } _ => {} } } diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index bd5c8bc..a900e6a 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -130,6 +130,7 @@ pub(crate) struct Translated { /// A compute program's threads in a group. pub(crate) threads: Option<[u32; 3]>, pub(crate) used: Vec<victory_shader::UsedResource>, + pub(crate) tables: crate::draw::TablePlan, /// Whether the shader's code can store to buffer memory ([`stores`]); /// true when its code is not known. pub(crate) stores: bool, @@ -222,10 +223,12 @@ fn translate(container: &[u8]) -> Result<Translated, String> { }) .map(|p| p.used) .unwrap_or_default(); + let tables = crate::draw::TablePlan::new(&used, &host.root_indexed_views); Ok(Translated { host, threads, used, + tables, stores, stores_by_address, picks: Default::default(), diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 0c8c21c..3ed2259 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -602,6 +602,7 @@ impl HostPipeline { slot == victory_shader::emit::SLOT_FAULTS } else { slot == victory_shader::emit::SLOT_STRIDES + || slot == victory_shader::emit::SLOT_TABLE_STRIDES || slot == victory_shader::emit::SLOT_MEMORY }; if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() { diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index a22e80c..979a223 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -41,8 +41,13 @@ 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`]). + /// A pass over the screen ([`GraphicsState::screen_pass`]) or a confirmed + /// opening-scene / bake producer that must never sit behind cold RT shaders. screen: bool, + /// Confirmed first-scene / bake producer prepared early even on a cold cache. + scene_input: bool, + /// Why this pipeline is intentionally skipped (e.g. RT resolve without BVH). + left_out: Option<&'static str>, /// LOCAL: how long draws have waited for it so far, in microseconds /// ([`wait_once`]). waited_us: AtomicU64, @@ -53,6 +58,56 @@ pub(crate) struct Pending { variant: OnceLock<Arc<Pending>>, } +fn named(shaders: &[Arc<Shader>], name: &[u8]) -> bool { + shaders + .iter() + .any(|s| s.stage == "compute" && s.container.windows(name.len()).any(|w| w == name)) +} + +fn left_out(shaders: &[Arc<Shader>]) -> Option<&'static str> { + static SKIP_RT_RESOLVE: OnceLock<bool> = OnceLock::new(); + let skip_rt = *SKIP_RT_RESOLVE.get_or_init(|| { + let builder = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1"); + if builder { + return false; + } + // Without BVH, ~1,000 CS_RaytracingResolve shaders shade no hits while + // clogging the cold compiler queue; skip unless VICTORY_RT_RESOLVE=1. + std::env::var_os("VICTORY_RT_RESOLVE").is_none_or(|v| v == "0") + }); + if skip_rt && named(shaders, b"CS_RaytracingResolve") { + return Some("shades ray-tracing hits without BVH, left out"); + } + static SKIP_ACTIVATE_RAYS: OnceLock<bool> = OnceLock::new(); + let skip_activate = *SKIP_ACTIVATE_RAYS.get_or_init(|| { + let builder = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1"); + if builder { + return std::env::var_os("VICTORY_ACTIVATE_RAYS").is_some_and(|v| v == "0"); + } + std::env::var_os("VICTORY_ACTIVATE_RAYS").is_none_or(|v| v == "0") + }); + if skip_activate && named(shaders, b"CS_ScreenProbes_ActivateRays") { + return Some("ray activation shader without BVH, left out"); + } + None +} + +/// Confirmed first-scene producers. Prepare these at creation even on a cold +/// launch so cutscene lighting, tiling, and bakes never miss their first frame. +fn scene_input(shaders: &[Arc<Shader>]) -> bool { + shaders.iter().any(|s| { + matches!( + s.hash.as_str(), + "970c4fbb3b017c0e" + | "068c90badc86f1fd" + | "e4a7e088c7780ce8" + | "ebe4e53f031f5249" + | "2cc4c197ee29e291" + | "369cbe906ea72764" + ) || crate::draw::BAKE_PIXEL_SHADERS.contains(&s.hash.as_str()) + }) +} + // SAFETY: D3D12 objects are free-threaded; the graphics state (whose input // elements point into its own names) is only read after creation. unsafe impl Send for Pending {} @@ -67,10 +122,17 @@ impl Pending { key.update(s.hash.as_bytes()); } key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes()); + let scene_input = scene_input(&shaders); + let screen = (graphics.as_ref().is_some_and(|g| g.screen_pass()) + && shaders.iter().all(|s| s.stage != "mesh")) + || scene_input; + let left_out = left_out(&shaders); Pending { + screen, + scene_input, + left_out, formats: graphics.as_ref().map_or([0; 9], |g| g.formats()), variant: OnceLock::new(), - screen: graphics.as_ref().is_some_and(|g| g.screen_pass()), shaders, graphics, queue_state: AtomicU8::new(NOT_QUEUED), @@ -216,6 +278,9 @@ fn variant<'a>(p: &'a Arc<Pending>, g: &GraphicsState, bound: &TargetFormats) -> /// The host pipeline if it is made (or is made within the frame's budget); /// queues it on first use. pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> { + if p.left_out.is_some() { + return None; + } // A still-pending pipeline was requested by the title too. Prewarm it // on the next launch, even if this run never got to use it. if !p.used.load(Ordering::Relaxed) && !p.used.swap(true, Ordering::Relaxed) { @@ -231,16 +296,23 @@ pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> { /// Makes `p` on this thread if it is not made yet (waiting for a worker /// that is making it); whether it has a host pipeline. pub(crate) fn now(p: &Arc<Pending>) -> bool { + if p.left_out.is_some() { + return false; + } p.make(); p.made.get().is_some_and(|made| made.is_some()) } /// At the title's creation of a pipeline: starts it at once if an earlier -/// run drew with it (during loading, so the world's first frames find it). +/// run drew with it (during loading, so the world's first frames find it), +/// or if it is a confirmed opening-scene / bake producer. pub(crate) fn early(p: &Arc<Pending>) { - if !p.shaders.is_empty() && super::library::wanted_early(&p.key) { + if p.left_out.is_some() { + return; + } + if !p.shaders.is_empty() && (p.scene_input || super::library::wanted_early(&p.key)) { super::library::EARLY.fetch_add(1, Ordering::Relaxed); - start(p, EARLY); + start(p, if p.scene_input { REQUESTED } else { EARLY }); } } @@ -492,8 +564,13 @@ fn next(screens_only: bool) -> Arc<Pending> { /// 64), else two thirds of the logical processors, 2 to 16. They run below the /// title's own threads, and a cold cache queues hundreds at once. fn worker_count(asked: Option<usize>, processors: usize) -> usize { + worker_count_for(asked, processors, false) +} + +fn worker_count_for(asked: Option<usize>, processors: usize, limited_ram: bool) -> usize { match asked { Some(n) => n.clamp(1, 64), + None if limited_ram => (processors * 3 / 4).clamp(2, 8), None => (processors * 2 / 3).clamp(2, 16), } } @@ -503,11 +580,12 @@ fn workers() -> bool { static RUNNING: OnceLock<bool> = OnceLock::new(); *RUNNING.get_or_init(|| { let mut running = false; - let workers = worker_count( + let workers = worker_count_for( std::env::var("VICTORY_PIPELINE_WORKERS") .ok() .and_then(|v| v.trim().parse().ok()), std::thread::available_parallelism().map_or(2, |n| n.get()), + crate::residency::limited_host_ram(), ); tracing::info!(workers, "pipeline workers"); let screens = if screens_first() { SCREEN_WORKERS } else { 0 }; @@ -580,6 +658,10 @@ mod tests { assert_eq!(worker_count(None, 64), 16); assert_eq!(worker_count(Some(0), 24), 1); assert_eq!(worker_count(Some(20), 24), 20); + assert_eq!(worker_count_for(None, 8, true), 6); + assert_eq!(worker_count_for(None, 16, true), 8); + assert_eq!(worker_count_for(None, 24, true), 8); + assert_eq!(worker_count_for(Some(12), 8, true), 12); } /// A first use queues the pipeline and, within the budget, gets the diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index 4d6a92d..cde4cdb 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -42,7 +42,25 @@ static SPARES: AtomicUsize = AtomicUsize::new(SPARE); /// [`SPARE_KEPT`] below 85 % ([`crate::host::keep_freed`]), else [`SPARE`]. /// Asked once a second. pub(crate) fn room(memory: Option<[u64; 4]>) { - SPARES.store(spares(memory, crate::host::keep_freed()), Ordering::Relaxed); + let pressure = crate::residency::pressured(); + let limit = spares(memory, crate::host::keep_freed() && !pressure); + SPARES.store(limit, Ordering::Relaxed); + let tick = now(); + // A full pool can become idle while another subsystem needs the VRAM. + // A busy allocator observes the new limit on its next allocation or tick. + if let Ok(mut pool) = TEXTURES.try_lock() { + pool.reclaim(tick, limit, true); + } + if let Ok(mut pool) = STAGING.try_lock() { + let staging_limit = if crate::residency::critical_commit() { + 0 + } else if pressure { + 1 + } else { + limit + }; + pool.reclaim(tick, staging_limit, true); + } } fn spares(memory: Option<[u64; 4]>, keep: bool) -> usize { @@ -180,11 +198,12 @@ struct Pool<B> { /// The empty blocks it was last told to keep, and the most it keeps. spare: usize, most: usize, + retry_growth_at: u64, } impl<B: Clone> Pool<B> { const fn new(most: usize) -> Pool<B> { - Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most } + Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most, retry_growth_at: 0 } } /// A piece of `len` bytes and the memory it lies in, and whether that @@ -226,10 +245,13 @@ impl<B: Clone> Pool<B> { unripe.sort_unstable(); found = unripe.into_iter().find_map(|(_, i)| Some((i, self.blocks[i].as_mut()?.free.take(len, align)?))); } + // A failed 64 MiB block must not trigger another driver call for each + // small texture. Existing free ranges remain usable during backoff. let (i, start) = match found { Some(found) => found, None => { - let i = self.add(make()?, ripe.started); + let memory = self.grow(now, &mut make)?; + let i = self.add(memory, ripe.started); (i, self.blocks[i].as_mut()?.free.take(len, align)?) } }; @@ -242,7 +264,7 @@ impl<B: Clone> Pool<B> { } let empty = self.blocks.iter().flatten().filter(|b| b.free.whole(BLOCK)).count(); if empty < ripe.ahead - && let Some(memory) = make() + && let Some(memory) = self.grow(now, &mut make) { self.add(memory, ripe.started); } @@ -253,6 +275,17 @@ impl<B: Clone> Pool<B> { Some((Piece { block: i, start, len }, block.memory.clone(), again)) } + fn grow(&mut self, now: u64, make: &mut impl FnMut() -> Option<B>) -> Option<B> { + if now < self.retry_growth_at { + return None; + } + let block = make(); + if block.is_none() { + self.retry_growth_at = now.saturating_add(500); + } + block + } + fn add(&mut self, memory: B, made: u64) -> usize { let i = match self.blocks.iter().position(Option::is_none) { Some(i) => i, @@ -272,6 +305,10 @@ impl<B: Clone> Pool<B> { /// Makes the pieces that rested long enough free, and lets go of empty /// blocks past [`SPARE`]. fn rested(&mut self, now: u64) { + self.reclaim(now, SPARES.load(Ordering::Relaxed), false); + } + + fn reclaim(&mut self, now: u64, limit: usize, sweep: bool) { let mut any = false; while let Some(&(ready, piece)) = self.resting.front() && ready <= now @@ -283,9 +320,9 @@ impl<B: Clone> Pool<B> { } } // (Without a piece given back too, once there is less room.) - let most = SPARES.load(Ordering::Relaxed).min(self.most); - if any || most < self.spare { - self.spare = most; + let most = limit.min(self.most); + let previous = std::mem::replace(&mut self.spare, most); + if sweep || any || most < previous { let mut spare = 0; for block in &mut self.blocks { if block.as_ref().is_some_and(|b| b.free.whole(BLOCK)) { @@ -349,6 +386,13 @@ pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPi // Copies from a buffer begin at multiples of 512. let bytes = bytes.next_multiple_of(512); let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || { + // Only gate speculative bindless prefetch on staging-pool growth + // headroom; table-bound textures and decoration bakes are sampled + // immediately and would otherwise read uninitialized/reused VRAM. + let speculative = crate::texture::PICKING.get().is_some() && !crate::texture::BAKING.get(); + if speculative && !crate::residency::allow_staging_growth(false) { + return None; + } let (buffer, data) = host.upload_buffer(BLOCK)?; crate::host::name(&buffer, || "staging of textures (a block)".into()); Some(Upload(buffer, data)) @@ -488,6 +532,7 @@ pub(crate) unsafe fn texture( let mut heap: Option<ID3D12Heap> = None; // SAFETY: plain creation. if let Err(e) = unsafe { device.CreateHeap(&desc, &mut heap) } { + crate::residency::allocation_error(&e); tracing::warn!(error = %e, "no block of texture memory"); } if let Some(h) = &heap @@ -560,6 +605,40 @@ mod tests { assert_eq!(spares(None, true), SPARE); } + #[test] + fn a_failed_block_is_not_retried_for_each_small_upload() { + let mut pool: Pool<u32> = Pool::new(2); + let calls = std::cell::Cell::new(0); + let refuse = || { calls.set(calls.get() + 1); None }; + for size in [704008, 179720, 179720, 24080, 48648, 524288, 89616, 351760] { + assert!(pool.take(size, 512, 12, refuse).is_none()); + } + assert_eq!(calls.get(), 1); + assert!(pool.take(24080, 512, 1012, || Some(1)).is_some()); + } + + #[test] + fn budget_tick_reclaims_idle_blocks_without_reusing_live_or_resting_pieces() { + let mut pool = Pool::new(STAGING_KEPT); + let (held, _, _) = pool.take(BLOCK / 2, 1, 0, || Some(1)).unwrap(); + let (resting, _, _) = pool.take(BLOCK / 2, 1, 0, || Some(2)).unwrap(); + pool.give(resting, 0); + for i in 0..12 { + pool.add(i, 0); + } + pool.reclaim(0, SPARE_KEPT, true); + assert_eq!(pool.blocks(), STAGING_KEPT + 1); + pool.reclaim(REST - 1, SPARE, true); + assert_eq!(pool.blocks(), SPARE + 1); + assert_eq!(pool.resting.len(), 1); + pool.reclaim(REST, 0, true); + assert_eq!(pool.blocks(), 1); + assert!(pool.resting.is_empty()); + pool.give(held, REST); + pool.reclaim(2 * REST, 0, true); + assert_eq!(pool.blocks(), 0); + } + #[test] fn pieces_never_overlap_and_rest_before_they_are_used_again() { let mut pool: Pool<u32> = Pool::new(SPARE); diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 0dc2f38..2a908ec 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -651,6 +651,42 @@ pub(crate) struct Plane { count: u32, resources: *const This, } +/// Retail PresentX adds source-rectangle and destination pointers, a color +/// space and seven option words after the common prefix. Older callers pass +/// only the prefix for single-plane presents. +#[cfg(windows)] +#[repr(C)] +struct RetailPlane { + prefix: Plane, + source_rects: *const (), + destination: *const (), + color_space: u32, + options: [u32; 7], +} +#[cfg(windows)] +const _: () = assert!(size_of::<RetailPlane>() == 72); + +#[cfg(windows)] +fn overlay_resource(parameters: *const Plane) -> Option<This> { + // Read only the second prefix at the 72-byte retail PresentX stride. A + // caller using a different layout can still present its base plane safely. + let second = parameters.cast::<RetailPlane>().wrapping_add(1).cast::<u8>(); + let mut prefix = [0; size_of::<Plane>()]; + if !crate::host::read_into(second, &mut prefix) { + return None; + } + // SAFETY: the prefix has the C layout above and its bytes were copied. + let plane = unsafe { prefix.as_ptr().cast::<Plane>().read_unaligned() }; + let mut pointer = [0; size_of::<This>()]; + if plane.count == 0 + || plane.resources.is_null() + || !crate::host::read_into(plane.resources.cast(), &mut pointer) + { + return None; + } + let resource = usize::from_ne_bytes(pointer) as This; + crate::resource::is_resource(resource).then_some(resource) +} /// Submission tagged with the frame it belongs to `(count, lists, frame /// token, flags)`; frames are paced elsewhere, so it runs as a plain one. extern "system" fn execute_x(this: This, count: u32, lists: *const This, _token: u64, _flags: u32) { @@ -801,6 +837,8 @@ impl Written { } else { at.cast::<u64>().write_unaligned(value); } + #[cfg(windows)] + windows_sys::Win32::System::Threading::WakeByAddressAll(at.cast()); } } } @@ -924,21 +962,21 @@ extern "system" fn present( crate::capture::dump_targets(frame); } } - #[cfg(all(windows, feature = "diagnostics"))] - note_planes(planes, plane_parameters); #[cfg(windows)] if behind::on() && !this.is_null() { const COPY_SOURCE: u32 = 0x800; - let texture = if planes > 0 + let base_res = if planes > 0 // SAFETY: the title passes `planes` plane descriptions. && let Some(plane) = unsafe { plane_parameters.as_ref() } && plane.count > 0 && !plane.resources.is_null() { // SAFETY: the plane lists `count` resources. - let resource = unsafe { *plane.resources }; - // The state the lists recorded so far leave it in (the next - // frame's, recorded before this is shown, go on from there). + Some(unsafe { *plane.resources }) + } else { + None + }; + let take_copy = |resource: This| { crate::resource::host_copy(resource).map(|copy| { let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before); crate::resource::host_transition(resource, state); @@ -947,14 +985,20 @@ extern "system" fn present( let state = if crate::list::thin::wanted() { u32::MAX } else { state }; (resource as usize, copy, state) }) - } else { - None }; + let texture = base_res.and_then(take_copy); + let overlay = (planes > 1 && !plane_parameters.is_null()) + .then(|| overlay_resource(plane_parameters)) + .flatten() + .filter(|&over_res| base_res != Some(over_res)) + .and_then(take_copy); let resource = texture.as_ref().map_or(0, |t| t.0); - // LOCAL (port of fxceless #1189): the interface plane, as the first. - let over = second_plane(planes, plane_parameters, resource as This) - .map(|(copy, state)| (copy, if crate::list::thin::wanted() { u32::MAX } else { state })); - behind::present(this, texture.map(|(_, copy, state)| (copy, state)), Shown { frame, resource, over }); + behind::present( + this, + texture.map(|(_, copy, state)| (copy, state)), + overlay.map(|(_, copy, state)| (copy, state)), + Shown { frame, resource }, + ); called.end(); #[cfg(feature = "diagnostics")] frame_ends(); @@ -974,9 +1018,27 @@ extern "system" fn present( const COPY_SOURCE: u32 = 0x800; let state = crate::resource::host_transition(resource, COPY_SOURCE) .map_or(COPY_SOURCE, |(_, before)| before); - let over = second_plane(planes, plane_parameters, resource); - show(texture, state, Shown { frame, resource: resource as usize, over }); + let overlay = (planes > 1) + .then(|| overlay_resource(plane_parameters)) + .flatten() + .filter(|&over_res| over_res != resource) + .and_then(|over_res| { + crate::resource::host_resource(over_res).map(|over_tex| { + let over_state = crate::resource::host_transition(over_res, COPY_SOURCE) + .map_or(COPY_SOURCE, |(_, before)| before); + (over_res, over_tex, over_state) + }) + }); + show_planes( + texture, + state, + overlay.as_ref().map(|(_, tex, st)| (*tex, *st)), + Shown { frame, resource: resource as usize }, + ); crate::resource::host_transition(resource, state); + if let Some((over_res, _, over_state)) = overlay { + crate::resource::host_transition(over_res, over_state); + } let _ = host; } #[cfg(not(windows))] @@ -1001,104 +1063,24 @@ fn frame_ends() { /// The frame a present shows, and the title's resource it shows. #[cfg(windows)] -#[derive(Clone)] +#[derive(Clone, Copy)] struct Shown { frame: u64, resource: usize, - /// LOCAL (port of fxceless #1189): the second plane to lay over the - /// shown one, and its host state (`u32::MAX`: the state its lists left - /// it in when they ran). - over: Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>, } -/// LOCAL (port of fxceless #1189): a present's second plane, to be laid over -/// the first (`crate::compose`), with `VICTORY_COMPOSE=1`. Its host copy and -/// the host state the lists recorded so far leave it in (noted as before). -/// A Series S title presents two planes: the game and the interface -/// (menus, loading screens, the intro), 72-byte descriptions each. +/// Shows `texture` (with optional `overlay` plane blended over it) in our window. #[cfg(windows)] -fn second_plane(planes: u32, plane_parameters: *const Plane, first: This) -> Option<(std::sync::Arc<crate::resource::HostTexture>, u32)> { - const STRIDE: usize = 72; - const COPY_SOURCE: u32 = 0x800; - static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - let on = *ON.get_or_init(|| { - let on = std::env::var_os("VICTORY_COMPOSE").is_some_and(|v| v == "1"); - if on { - tracing::warn!("LOCAL present planes: a second plane is laid over the first (VICTORY_COMPOSE=1)"); - } - on - }); - if !on || planes < 2 || plane_parameters.is_null() { - return None; - } - // SAFETY: the title passes `planes` descriptions of `STRIDE` bytes. - let plane = unsafe { plane_parameters.cast::<u8>().add(STRIDE).cast::<Plane>().as_ref() }?; - if plane.count == 0 || plane.resources.is_null() { - return None; - } - // SAFETY: the plane lists `count` resources. - let resource = unsafe { *plane.resources }; - if resource == first { - return None; - } - let copy = crate::resource::host_copy(resource)?; - let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before); - crate::resource::host_transition(resource, state); - Some((copy, state)) -} - -/// Diagnostics (LOCAL, from fxceless #1189): the planes a present asks for, -/// at presents 1, 2, 4, ... up to 4096 and whenever their number changes. -#[cfg(all(windows, feature = "diagnostics"))] -fn note_planes(planes: u32, plane_parameters: *const Plane) { - const STRIDE: usize = 72; - static LAST: AtomicU64 = AtomicU64::new(u64::MAX); - let frame = FRAMES.load(Ordering::Relaxed); - let changed = LAST.swap(u64::from(planes), Ordering::Relaxed) != u64::from(planes); - if !changed && !(frame.is_power_of_two() && frame <= 4096) { - return; - } - if plane_parameters.is_null() { - return; - } - for i in 0..planes.min(4) as usize { - // SAFETY: the title passes `planes` descriptions of `STRIDE` bytes. - let Some(plane) = (unsafe { plane_parameters.cast::<u8>().add(i * STRIDE).cast::<Plane>().as_ref() }) else { - continue; - }; - if plane.resources.is_null() { - tracing::warn!(frame, planes, plane = i, count = plane.count, "present plane without resources"); - continue; - } - for k in 0..plane.count.min(2) as usize { - // SAFETY: the plane lists `count` resources. - let resource = unsafe { *plane.resources.add(k) }; - let desc = crate::resource::texture_memory(resource).map(|m| m.1); - tracing::warn!( - frame, - planes, - plane = i, - count = plane.count, - resource = ?resource, - hosted = crate::resource::host_copy(resource).is_some(), - desc = ?desc, - "present plane" - ); - } - } -} - -/// Shows `texture`, in host state `state`, in our window. -#[cfg(windows)] -fn show(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32, what: Shown) { +fn show_planes( + texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, + state: u32, + overlay: Option<(&windows::Win32::Graphics::Direct3D12::ID3D12Resource, u32)>, + what: Shown, +) { let Some(host) = crate::host::host() else { return; }; - let over = what.over.as_ref().map(|(t, s)| { - let s = if *s == u32::MAX { t.state.load(Ordering::Relaxed) } else { *s }; - (&t.texture, s) - }); - let shown = host.present_over(texture, state, over, what.frame); + let shown = host.present_planes(texture, state, overlay, what.frame); #[cfg(feature = "diagnostics")] blinks(what.frame, what.resource as This, state, shown); #[cfg(not(feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/queue/behind.rs b/crates/victory-gpu/src/queue/behind.rs index b5624eb..813155c 100644 --- a/crates/victory-gpu/src/queue/behind.rs +++ b/crates/victory-gpu/src/queue/behind.rs @@ -391,8 +391,12 @@ enum Job { Joined(usize, Vec<crate::list::Detached>, Vec<usize>, Vec<usize>, 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. - Present(Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>, super::Shown), + /// A frame is shown: the base texture (and optional overlay plane) and the states their lists leave them in. + Present( + Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>, + Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>, + super::Shown, + ), } // SAFETY: D3D12 objects are free-threaded; a job is touched by whoever put it @@ -569,12 +573,16 @@ impl Work for Job { crate::fence::set(fence as This, value); } } - Job::Present(texture, shown) => { + Job::Present(texture, overlay, shown) => { if let Some((texture, state)) = texture { // (Where its lists were not translated when the title // presented: the state they left it in.) let state = if state == u32::MAX { texture.state.load(Relaxed) } else { state }; - super::show(&texture.texture, state, shown); + let over = overlay.as_ref().map(|(ov, ov_state)| { + let st = if *ov_state == u32::MAX { ov.state.load(Relaxed) } else { *ov_state }; + (&ov.texture, st) + }); + super::show_planes(&texture.texture, state, over, shown); } QUEUED.fetch_sub(1, Relaxed); } @@ -811,10 +819,15 @@ pub(super) fn wait(this: This, fence: This, value: u64) { /// A present on queue `this` of `texture`, in the state the lists recorded so /// far leave it in. -pub(super) fn present(this: This, texture: Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>, shown: super::Shown) { +pub(super) fn present( + this: This, + texture: Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>, + overlay: Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>, + shown: super::Shown, +) { QUEUED.fetch_add(1, Relaxed); STATS[PRESENTS].fetch_add(1, Relaxed); - LANE.push(this as usize, [Job::Present(texture, shown)]); + LANE.push(this as usize, [Job::Present(texture, overlay, shown)]); let began = Instant::now(); let _waiting = crate::timeline::span("a present waits for the one before it to be sent"); LANE.wait_presents(frames_most()); diff --git a/crates/victory-gpu/src/residency.rs b/crates/victory-gpu/src/residency.rs new file mode 100644 index 0000000..0e701e5 --- /dev/null +++ b/crates/victory-gpu/src/residency.rs @@ -0,0 +1,201 @@ +//! Host-memory admission for speculative texture work and reusable upload storage. +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + +const MIB: u64 = 1 << 20; +const GIB: u64 = 1 << 30; +static PRESSURED: AtomicBool = AtomicBool::new(false); +static HEADROOM: AtomicU64 = AtomicU64::new(u64::MAX); + +fn memory_status() -> Option<MEMORYSTATUSEX> { + // SAFETY: the API initializes the fields of a correctly sized structure. + let mut status: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + status.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32; + (unsafe { GlobalMemoryStatusEx(&mut status) } != 0).then_some(status) +} + +// The texture sweep may run for seconds inside a single submitted frame. +static NEXT_COMMIT_SAMPLE: AtomicU64 = AtomicU64::new(0); +static AVAILABLE_COMMIT: AtomicU64 = AtomicU64::new(u64::MAX); +static RETRY_UPLOAD_AT: AtomicU64 = AtomicU64::new(0); + +pub(crate) fn allocation_error(error: &windows::core::Error) { + if error.code() == windows::Win32::Foundation::E_OUTOFMEMORY { + RETRY_UPLOAD_AT.fetch_max(crate::host::coarse_ms().saturating_add(500), Ordering::Relaxed); + } +} + +thread_local! { + static STAGING_DEFERRED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +pub(crate) fn note_staging_deferred() { + STAGING_DEFERRED.set(true); +} + +pub(crate) fn take_staging_deferred() -> bool { + STAGING_DEFERRED.replace(false) +} + +pub(crate) fn upload_refused() -> bool { + crate::host::coarse_ms() < RETRY_UPLOAD_AT.load(Ordering::Relaxed) +} + +fn sample_commit(now: u64) -> u64 { + let next = NEXT_COMMIT_SAMPLE.load(Ordering::Relaxed); + if now >= next + && NEXT_COMMIT_SAMPLE + .compare_exchange(next, now.saturating_add(32), Ordering::Relaxed, Ordering::Relaxed) + .is_ok() + && let Some(status) = memory_status() + { + AVAILABLE_COMMIT.store(status.ullAvailPageFile, Ordering::Relaxed); + } + AVAILABLE_COMMIT.load(Ordering::Relaxed) +} + +fn has_upload_reserve(commit: u64, bake: bool) -> bool { + // Keep a protective floor against Rust/game OOM aborts without starving + // bindless world textures or one-shot ped decoration bakes when steady-state + // commit headroom sits in the 1-4 GiB range on 32 GiB hosts. + commit >= if bake { 256 * MIB } else { 512 * MIB } +} + +fn has_growth_reserve(commit: u64, bake: bool) -> bool { + // Growing a fresh 64 MiB upload block for speculative bindless prefetch + // requires more headroom than reusing slices already committed inside the + // staging pool. + commit >= if bake { 256 * MIB } else { 1024 * MIB } +} + +/// Leave commit for game allocations and submissions already in flight while +/// still letting bindless textures and one-shot material bakes upload. +pub(crate) fn admit_texture_pass(bake: bool) -> bool { + let now = crate::host::coarse_ms(); + if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) { + return false; + } + has_upload_reserve(sample_commit(now), bake) +} + +/// Whether the staging allocator may commit a brand-new OS upload buffer +/// (reusing existing free ranges in already-committed pool blocks stays open +/// whenever `admit_texture_pass` is true). +pub(crate) fn allow_staging_growth(bake: bool) -> bool { + let now = crate::host::coarse_ms(); + if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) { + return false; + } + has_growth_reserve(sample_commit(now), bake) +} + +pub(crate) fn limited_host_ram() -> bool { + static LIMITED: OnceLock<bool> = OnceLock::new(); + *LIMITED.get_or_init(|| memory_status().is_some_and(|s| s.ullTotalPhys <= 32 * GIB)) +} + +fn next_pressure(was: bool, physical: u64, commit: u64) -> bool { + if was { + physical < 5 * GIB || commit < 6 * GIB + } else { + physical <= 3 * GIB || commit <= 4 * GIB + } +} + +/// Called by the once-per-second submission sweep. A failed sample keeps the last good state. +pub(crate) fn refresh() { + let Some(status) = memory_status() else { return }; + let (physical, commit) = (status.ullAvailPhys, status.ullAvailPageFile); + HEADROOM.store(physical.min(commit), Ordering::Relaxed); + let was = pressured(); + let pressure = next_pressure(was, physical, commit); + if pressure != was { + PRESSURED.store(pressure, Ordering::Relaxed); + if pressure { + tracing::warn!( + pid = std::process::id(), + frame = crate::frame::current(), + physical_free_mib = physical >> 20, + available_commit_mib = commit >> 20, + buffer_mirror_span_mib = crate::shadow::live_span_bytes() >> 20, + texture_staging_mib = crate::texture::live_staging_bytes() >> 20, + spare_scratch_mib = crate::host::ALIVE[4].load(Ordering::Relaxed) >> 20, + game_filled_gpu_texture_mib = crate::resource::KINDS[1].load(Ordering::Relaxed) >> 20, + "host memory pressure: limiting texture prefetch and idle upload storage" + ); + } else { + tracing::info!(physical_free_mib = physical >> 20, available_commit_mib = commit >> 20, "host memory pressure cleared"); + } + } +} + +pub(crate) fn headroom() -> Option<u64> { + let bytes = HEADROOM.load(Ordering::Relaxed); + (bytes != u64::MAX).then_some(bytes) +} + +pub(crate) fn pressured() -> bool { + PRESSURED.load(Ordering::Relaxed) +} + +/// True when OS commit headroom is critically low (< 1.5 GiB) or an allocation +/// just failed with `E_OUTOFMEMORY`, requiring emergency throttling. +pub(crate) fn critical_commit() -> bool { + let now = crate::host::coarse_ms(); + now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) || sample_commit(now) < 1536 * MIB +} + +/// A soft per-frame admission limit. A single texture can cross it. The +/// queue retains unserved slots so they can be retried on later frames. +pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, critical: bool, limited: bool, staging: u64) -> u64 { + if critical { + bytes.min(16 << 20) + } else if pressure || (limited && staging >= GIB) { + bytes.min(64 << 20) + } else { + bytes + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bake_and_lookahead_leave_room_for_live_game_allocations() { + for (commit, bake, lookahead, growth) in [ + (128 * MIB, false, false, false), + (256 * MIB, true, false, false), + (512 * MIB, true, true, false), + (768 * MIB, true, true, false), + (1024 * MIB, true, true, true), + ] { + assert_eq!(has_upload_reserve(commit, true), bake); + assert_eq!(has_upload_reserve(commit, false), lookahead); + assert_eq!(has_growth_reserve(commit, false), growth); + } + } + + #[test] + fn either_constraint_enters_pressure_and_both_must_recover() { + assert!(next_pressure(false, 12 * GIB, 4 * GIB)); + assert!(next_pressure(false, 3 * GIB, 16 * GIB)); + assert!(next_pressure(true, 4 * GIB, 7 * GIB)); + assert!(next_pressure(true, 6 * GIB, 5 * GIB)); + assert!(!next_pressure(true, 5 * GIB, 6 * GIB)); + assert!(!next_pressure(false, 4 * GIB, 5 * GIB)); + } + + #[test] + fn prefetch_respects_existing_budgets_and_resumes_after_recovery() { + assert_eq!(prefetch_limit(512 << 20, false, false, true, GIB), 64 << 20); + assert_eq!(prefetch_limit(512 << 20, false, false, true, GIB - 1), 512 << 20); + assert_eq!(prefetch_limit(512 << 20, false, false, false, 2 * GIB), 512 << 20); + assert_eq!(prefetch_limit(0, true, true, false, 0), 0); + assert_eq!(prefetch_limit(8 << 20, true, true, false, 0), 8 << 20); + assert_eq!(prefetch_limit(512 << 20, true, false, false, 0), 64 << 20); + assert_eq!(prefetch_limit(512 << 20, true, true, false, 0), 16 << 20); + assert_eq!(prefetch_limit(192 << 20, false, false, false, 0), 192 << 20); + } +} diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 32ef56a..e6c8b65 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -2379,6 +2379,14 @@ pub(crate) fn host_resource<'a>( Some(unsafe { &*std::ptr::from_ref(&host.texture) }) } +/// Whether `this` is a valid title resource created by this runtime. +#[cfg(windows)] +pub(crate) fn is_resource(this: This) -> bool { + let mut table = [0; size_of::<usize>()]; + crate::host::read_into(this.cast(), &mut table) + && usize::from_ne_bytes(table) == RESOURCE_FUNCTIONS.0.as_ptr() as usize +} + /// A title texture's host copy, shared, for a list to hold. #[cfg(windows)] pub(crate) fn host_copy(this: This) -> Option<std::sync::Arc<HostTexture>> { @@ -2525,6 +2533,7 @@ fn host_texture_as( } }; if let Err(e) = &made { + crate::residency::allocation_error(&e); tracing::warn!(error = %e, desc = ?d, reserved, "no host texture"); } if !reserved diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 43d1b76..14dc160 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -314,6 +314,12 @@ static CARDED: Mutex<Vec<std::sync::Weak<Shadow>>> = Mutex::new(Vec::new()); /// bytes; the waits for the card the fetches added and their microseconds. pub(crate) static CARD_STATS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; +pub(crate) fn live_span_bytes() -> u64 { + CARD_BYTES[0].load(Ordering::Relaxed) + + WINDOW_CARD_BYTES.load(Ordering::Relaxed) + + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed) +} + /// [`CARD_STATS`], taken; then the copies in the card's memory, their /// bytes and their "before" twins' bytes. pub(crate) fn card_stats() -> [u64; 10] { diff --git a/crates/victory-gpu/src/streamline.rs b/crates/victory-gpu/src/streamline.rs new file mode 100644 index 0000000..daf182b --- /dev/null +++ b/crates/victory-gpu/src/streamline.rs @@ -0,0 +1,2184 @@ +//! NVIDIA Streamline (SL) 2.14.16 FFI: DLSS Frame Generation (DLSS-G), Reflex and PC Latency (PCL). +//! +//! Hand-written mirrors of the SDK headers (`sl.h`, `sl_struct.h`, `sl_core_types.h`, +//! `sl_core_api.h`, `sl_consts.h`, `sl_dlss_g.h`, `sl_reflex.h`, `sl_pcl.h`, `sl_version.h`, +//! `sl_result.h`, `sl_appidentity.h`, `sl_device_wrappers.h`) plus a runtime loader for +//! `sl.interposer.dll`. Nothing links against `sl.interposer.lib`; every core entry point is +//! resolved with `GetProcAddress`, every feature entry point with `slGetFeatureFunction`. +//! Layouts are x64 MSVC and are checked by the `const` asserts at the bottom of the file. +//! +//! The headers mirrored here are NVIDIA's, published under the MIT licence +//! (github.com/NVIDIA-RTX/Streamline, `license.txt`), whose notice follows: +//! +//! ```text +//! Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved +//! +//! Permission is hereby granted, free of charge, to any person obtaining a copy +//! of this software and associated documentation files (the "Software"), to deal +//! in the Software without restriction, including without limitation the rights +//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +//! copies of the Software, and to permit persons to whom the Software is +//! furnished to do so, subject to the following conditions: +//! +//! The above copyright notice and this permission notice shall be included in all +//! copies or substantial portions of the Software. +//! +//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +//! SOFTWARE. +//! ``` +//! +//! # Call sequence for a D3D12 app using MANUAL HOOKING with DLSS-G +//! +//! (from ProgrammingGuide.md, ProgrammingGuideManualHooking.md, ProgrammingGuideDLSS_G.md, +//! ProgrammingGuideReflex.md, ProgrammingGuidePCL.md, cross-checked against the interposer source) +//! +//! ## Start-up +//! +//! 1. `Sl::load(dir)` (LoadLibraryW of `<dir>\sl.interposer.dll` by full path). +//! 2. `slInit` before any hooked DXGI call can happen (before swap-chain creation). Not from +//! `DllMain`. With manual hooking the D3D12 device may be created before or after `slInit`. +//! * `flags = eDisableCLStateTracking | eUseManualHooking | eUseFrameBasedResourceTagging` +//! (`PreferenceFlags::MANUAL_HOOKING_FRAME_TAGS`). `eUseFrameBasedResourceTagging` is +//! required to use `slSetTagForFrame`. The C++ default also has `eAllowOTA | +//! eLoadDownloadedPlugins` (internet updates of SL/NGX); add them back if wanted. +//! * `featuresToLoad = [kFeatureDLSS_G, kFeatureReflex]` (`FG_FEATURES`). sl.dlss_g's manifest +//! lists `required_plugins: ["sl.common", "sl.reflex"]`. `sl.common` and `sl.pcl` are always +//! added by the plugin manager (`kFeatureCommon`, `kFeaturePCL`), they need not be listed. +//! Add `kFeatureDLSS` only if DLSS-SR is also driven through SL. +//! * `renderAPI = eD3D12`, `engine = eCustom`. +//! * App identity: without an NVIDIA application id, `applicationId = 0` makes SL use +//! `kTemporaryAppId` (100721531, `source/core/sl.api/internal.h`). In the signed +//! (SL_PRODUCTION) build sl.common then REFUSES to start NGX ("Please provide correct +//! application id ... NGX based features will be disabled") unless BOTH `engineVersion` and +//! `projectId` are non-empty, in which case it uses `NVSDK_NGX_D3D12_Init_with_ProjectID`. +//! DLSS-G is NGX-based, so set `engine = eCustom`, `engineVersion = c"..."` and +//! `projectId = c"<a GUID string>"` (see `commonEntry.cpp`, `hasProjectId`). +//! * `pathsToPlugins`: by default plugins are searched next to `sl.interposer.dll` itself +//! (`file::getModulePath()`), not next to the exe. Give an absolute path to override. +//! * Pass `sdkVersion = kSDKVersion`. +//! 3. Create the native `ID3D12Device`, then `slSetD3DDevice(nativeDevice)` "IMMEDIATELY after the +//! main device is created" (with manual hooking this is what initialises the plugins). +//! 4. `slIsFeatureSupported(kFeatureDLSS_G / kFeatureReflex / kFeaturePCL, AdapterInfo{LUID})`, +//! optionally `slGetFeatureRequirements` (OS/driver, `eHardwareSchedulingRequired`, ...). +//! 5. `Sl::resolve_feature_functions()` - `slGetFeatureFunction` only works AFTER the device is set. +//! 6. Proxies (sl_hooks.h list; everything NOT in that list must use native interfaces): +//! * `slUpgradeInterface(&device)` -> proxy `ID3D12Device`. Create the PRESENT queue through +//! the proxy (`eID3D12Device_CreateCommandQueue` is "Mandatory" and sl.dlss_g's embedded +//! manifest hooks `ID3D12Device::CreateCommandQueue`); the result is a proxy queue. The +//! interposer's factory proxy also accepts a native queue but logs "Detected base interface +//! 'ID3D12CommandQueue' while expecting SL proxy" when a plugin wants the proxy. +//! `ExecuteCommandLists` etc. may go to the native queue (`slGetNativeInterface`). +//! * `CreateDXGIFactory2` (native) then `slUpgradeInterface(&factory)` BEFORE +//! `CreateSwapChainForHwnd`; call `CreateSwapChainForHwnd(proxyQueue, ...)` on the PROXY +//! factory. The returned `IDXGISwapChain1` is the SL proxy (needs IDXGISwapChain3 support). +//! * Route `Present`, `Present1`, `GetBuffer`, `GetDesc`, `ResizeBuffers`, `ResizeBuffers1`, +//! `GetCurrentBackBufferIndex`, `SetFullscreenState` through the proxy swap chain; other +//! swap-chain calls may use `slGetNativeInterface(proxySwapChain)`. Calling +//! `GetCurrentBackBufferIndex` on the proxy is mandatory (`eFailGetCurrentBackBufferIndexNotCalled`). +//! With DLSS-G loaded the proxy's back buffers are off-screen copies owned by SL. +//! * Ref counts: `slUpgradeInterface` replaces the pointer in place with a NEW proxy object +//! (ref count 1) that AddRefs the base; the caller still owns its original native ref. +//! `slGetNativeInterface` returns an AddRef'd native pointer. +//! * Use native interfaces for NVAPI / 3rd party SDKs. +//! * Presenting through the proxy is also what makes sl.common's `presentCommon()` run once per +//! frame (garbage collection; memory grows across resizes if it does not run). +//! 7. `slReflexSetOptions(ReflexOptions{ mode: eLowLatency, .. })` at least once (even if Reflex is +//! "off"). DLSS-G reports `eFailReflexNotDetectedAtRuntime` when Reflex is not ACTIVE while +//! DLSS-G is on, so keep mode `eLowLatency`/`eLowLatencyWithBoost` while FG is on. +//! 8. `slDLSSGSetOptions(viewport, DLSSGOptions{ mode: eOn, numFramesToGenerate: 1, .. })`; +//! takes effect at the next `Present`; call it on the presenting thread. Loading the plugin +//! and tagging does NOT enable interpolation by itself. `numFramesToGenerate` (1 = 2x) must +//! be <= `DLSSGState::numFramesToGenerateMax` (from `slDLSSGGetState`). Recommended flag: +//! `eRetainResourcesWhenOff` (no realloc stutter when toggling off/on). +//! +//! ## Per frame (one `FrameToken`, one viewport; no `slEvaluateFeature` for DLSS-G - Present is the marker) +//! +//! 1. `slGetNewFrameToken(&token, Some(frameIndex))` where the simulation of the frame starts. +//! 2. `slReflexSleep(token)` (always, regardless of Reflex mode), then PCL markers with the same +//! token: `eSimulationStart` .. `eSimulationEnd`, `eRenderSubmitStart` .. `eRenderSubmitEnd`, +//! `ePresentStart` / proxy `Present` / `ePresentEnd`. The index on the present markers must be +//! the index of the frame being presented and match the one used for `slSetConstants` +//! (otherwise "common constants cannot be found for frame N"). Optional: `ePCLatencyPing` when +//! the `PCLState::statsWindowMessage` window message arrives, `eTriggerFlash` on left click. +//! 3. `slSetConstants(consts, token, viewport)` ONCE per frame, as early as possible. All +//! non-optional fields must be valid (defaults are `INVALID_FLOAT` / `Boolean::eInvalid`): +//! `cameraViewToClip`, `clipToCameraView`, `clipToPrevClip`, `prevClipToClip` (row-major, NO +//! jitter), `jitterOffset` (pixels), `mvecScale` (scales MV to [-1,1]; `1/renderWidth, +//! 1/renderHeight` for pixel-space MVs), `cameraPos/Up/Right/Fwd` (Up/Right/Fwd must be +//! orthonormal or auto scene-change detection disables itself), `cameraNear/Far/FOV(radians)/ +//! AspectRatio`, `depthInverted`, `cameraMotionIncluded`, `motionVectors3D`, `reset`. +//! Optional: `clipToLensClip`, `cameraPinholeOffset`, `motionVectorsInvalidValue` (only if +//! camera motion is not included). Invalid constants -> `eFailCommonConstantsInvalid`. +//! 4. `slSetTagForFrame(token, viewport, tags, cmdList)`: +//! * Required: `kBufferTypeDepth` (or `kBufferTypeLinearDepth`) and `kBufferTypeMotionVectors` +//! (dense: camera + object motion). The final colour comes from the proxy swap chain. +//! * Strongly recommended for UI quality: `kBufferTypeHUDLessColor` (same size / colour space / +//! post-processing as the back buffer, no UI) plus `kBufferTypeUIAlpha` (preferred) or +//! `kBufferTypeUIColorAndAlpha` (premultiplied; alpha precision > 2 bits). Sizes must +//! exactly match the back buffer (or its extent). +//! * `kBufferTypeBackbuffer` only to pass a sub-rect (resource pointer may be null). +//! * Lifecycle: tagged buffers are consumed during `Present`. If the resource is untouched +//! until Present use `eValidUntilPresent` (cmdList may be null; `Resource::state` must be +//! the state at Present time; SL keeps a reference until a null tag is set). If it will be +//! overwritten/reused before Present (typical when tagging on a command list right after +//! rendering a transient target) use `eOnlyValidNow` with that command list: SL records a +//! copy on it, `state` must be the state the resource is in ON THAT LIST at that point, and +//! the producing GPU work must already be on that list or on one executed before it. +//! NVIDIA advises trying `eValidUntilPresent` first (copies cost VRAM). +//! * Manual hooking: `Resource::state` (D3D12_RESOURCE_STATES) is mandatory - SL cannot track +//! it. No transitions are needed; SL restores states. +//! * Loading/menus/cut-scenes: set the tags to null (`resource = null`) and/or turn DLSS-G off. +//! 5. Viewport: an app-chosen integer (`ViewportHandle::new(0)`; the checklist says "Tag buffers +//! with unique id 0"); the SAME handle for constants, tags, `slDLSSGSetOptions/GetState`. +//! 6. Optionally `slDLSSGGetState(viewport, null options)` after Present: `status` must be `eOk` +//! (else turn FG off; an invalid FG draws a pink overlay), `numFramesActuallyPresented`, +//! `minWidthOrHeight` (FG must be off below it). Never pass `eRequestVRAMEstimate` per frame. +//! +//! ## Swap chain, resize, auto-disable +//! +//! * Docs do not prescribe a swap effect / buffer count / flags beyond D3D12's flip model and the +//! IDXGISwapChain3 requirement of the interposer proxy. `DLSSGOptions::numBackBuffers` is optional. +//! * Frame latency: SL's internal swap chain always uses +//! `DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT`. If the app does NOT request that flag +//! (recommended) it must not call `GetFrameLatencyWaitableObject` / `SetMaximumFrameLatency` +//! (applies whenever sl.dlss_g is loaded, even with FG off); pace with `slReflexSleep` / +//! `ReflexOptions::frameLimitUs`. If it requests the flag it owns the waitable. +//! * HDR: only UINT10/RGB10 + HDR10/BT.2100. FP16 (R16G16B16A16_FLOAT) back buffers / scRGB are +//! NOT supported (`eFailHDRFormatNotSupported`). +//! * VSync: `SyncInterval` 0 or 1 only (D3D12), check `DLSSGState::bIsVsyncSupportAvailable`. +//! * Turn FG off (`mode = eOff`) before resizing, minimise/maximise, full-screen transitions or any +//! operation that could deadlock `Present` (FG presents on its own thread), and in pause/full +//! screen menus. Recreate the swap chain whenever FG is switched on/off (and use +//! `slSetFeatureLoaded(kFeatureDLSS_G, false)` + recreate to remove the off-screen copy and +//! queue sync overhead while off). `slSetFeatureLoaded` = unload/unhook, not on/off. +//! * Auto-off: `eAuto` mode disables FG when it would lower FPS; `eEnableFullscreenMenuDetection` +//! (needs `kBufferTypeUIColorAndAlpha`) turns it off in full-screen menus; FG is unusable when +//! a `DLSSGStatus` failure bit is set (resolution too low, Reflex not active, HDR format, +//! invalid constants, GetCurrentBackBufferIndex not called). +//! * OS: Windows 10 20H1 (build 19041+) and Hardware-accelerated GPU Scheduling ON. +//! * Multiple swap chains are not supported by DLSS-G; with manual hooking only the upgraded one +//! is attached. +//! * `slShutdown()` before releasing the DXGI/D3D12 objects. +//! +//! ## DLLs (all from `sdk\bin\x64`, same directory) +//! +//! `sl.interposer.dll`, `sl.common.dll` (mandatory), `sl.dlss_g.dll` + `nvngx_dlssg.dll`, +//! `sl.reflex.dll`, `sl.pcl.dll`. (`sl.dlss.dll` + `nvngx_dlss.dll` only for DLSS-SR, +//! `NvLowLatencyVk.dll` only for Vulkan.) `sdk\bin\x64\development` holds unsigned dev builds. +//! +//! ## Signatures +//! +//! The production `sl.interposer.dll` loads every plugin through `sl::security::loadLibrary`, +//! which under `SL_PRODUCTION` calls `verifyEmbeddedSignature` (WinVerifyTrust + NVIDIA's second +//! signature) on the plugin's full path and silently refuses unsigned modules. There is no +//! location check: NVIDIA-signed plugins load from any folder (next to the interposer or +//! `pathsToPlugins`). Mixing in the unsigned `development` plugins with the production +//! interposer will make them fail to load. The docs ask the HOST to verify the signature of +//! `sl.interposer.dll` before loading it; this module does not (that needs WinTrust bindings). +//! OTA-downloaded plugins are only loaded by production builds with `eLoadDownloadedPlugins`. + +#![allow( + dead_code, + non_snake_case, + non_camel_case_types, + non_upper_case_globals, + clippy::missing_safety_doc, + clippy::too_many_arguments +)] + +use core::ffi::{CStr, c_char, c_void}; +use core::ptr::{self, NonNull}; +use std::os::windows::ffi::OsStrExt; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, anyhow, bail}; +use windows::Win32::Foundation::HMODULE; +use windows::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; +use windows::core::{PCSTR, PCWSTR}; + +// --------------------------------------------------------------------------------------------- +// Versions (sl_version.h, sl_struct.h) +// --------------------------------------------------------------------------------------------- + +pub const SL_VERSION_MAJOR: u64 = 2; +pub const SL_VERSION_MINOR: u64 = 14; +pub const SL_VERSION_PATCH: u64 = 16; +pub const kSDKVersionMagic: u64 = 0xfedc; +/// `sl::kSDKVersion`, the second argument of `slInit`. +pub const kSDKVersion: u64 = + (SL_VERSION_MAJOR << 48) | (SL_VERSION_MINOR << 32) | (SL_VERSION_PATCH << 16) | kSDKVersionMagic; + +pub const kStructVersion1: u32 = 1; +pub const kStructVersion2: u32 = 2; +pub const kStructVersion3: u32 = 3; +pub const kStructVersion4: u32 = 4; +pub const kStructVersion5: u32 = 5; +pub const kStructVersion6: u32 = 6; +pub const kStructVersion7: u32 = 7; + +/// What SL substitutes when `Preferences::applicationId == 0` +/// (`source/core/sl.api/internal.h`, `pluginManager.cpp`). Not in the public headers. Leaving +/// `applicationId` at 0 is equivalent to passing this; see the module docs for why +/// `engineVersion` + `projectId` must then be set for NGX features (DLSS-G) in production builds. +pub const kTemporaryAppId: u32 = 100721531; + +/// `sl::INVALID_FLOAT` (== FLT_MAX), the "not provided" value of the float defaults. +pub const INVALID_FLOAT: f32 = f32::MAX; +pub const INVALID_UINT: u32 = 0xffff_ffff; +pub const MAX_FRAMES_IN_FLIGHT: u32 = 6; + +pub const INTERPOSER_DLL: &str = "sl.interposer.dll"; + +/// DLLs that must sit next to `sl.interposer.dll` (or in `pathsToPlugins`) for DLSS-G + Reflex. +pub const FG_DLLS: [&str; 6] = [ + "sl.interposer.dll", + "sl.common.dll", + "sl.dlss_g.dll", + "nvngx_dlssg.dll", + "sl.reflex.dll", + "sl.pcl.dll", +]; + +// --------------------------------------------------------------------------------------------- +// StructType / BaseStructure (sl_struct.h) +// --------------------------------------------------------------------------------------------- + +/// `sl::StructType` - a GUID. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct StructType { + pub data1: u32, + pub data2: u16, + pub data3: u16, + pub data4: [u8; 8], +} + +impl StructType { + pub const fn new(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Self { + Self { data1, data2, data3, data4 } + } +} + +/// `sl::BaseStructure`: `BaseStructure* next{}; StructType structType{}; size_t structVersion;` +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct BaseStructure { + pub next: *mut BaseStructure, + pub structType: StructType, + pub structVersion: usize, +} + +impl BaseStructure { + pub const fn new(structType: StructType, structVersion: u32) -> Self { + Self { next: ptr::null_mut(), structType, structVersion: structVersion as usize } + } +} + +/// `SL_STRUCT_BEGIN(name, guid, version)`: the GUID / version constants plus helpers. Every +/// struct using it has `base: BaseStructure` as its first field. +macro_rules! sl_struct { + ($name:ident, $guid:expr, $version:expr) => { + impl $name { + pub const STRUCT_TYPE: StructType = $guid; + pub const STRUCT_VERSION: u32 = $version; + /// Header exactly as the C++ constructor fills it (next = null). + #[inline] + pub const fn header() -> BaseStructure { + BaseStructure::new(Self::STRUCT_TYPE, Self::STRUCT_VERSION) + } + /// For `next` chains and `slEvaluateFeature` inputs. + #[inline] + pub fn as_base(&self) -> *const BaseStructure { + (self as *const Self).cast() + } + #[inline] + pub fn as_base_mut(&mut self) -> *mut BaseStructure { + (self as *mut Self).cast() + } + } + }; +} + +/// A C/C++ enum as a transparent integer (an FFI-returned value outside the known set must not +/// be UB, so these are newtypes rather than Rust enums). +macro_rules! c_enum { + ($(#[$m:meta])* $name:ident : $repr:ty { $($(#[$vm:meta])* $variant:ident = $value:expr),* $(,)? }) => { + $(#[$m])* + #[repr(transparent)] + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] + pub struct $name(pub $repr); + impl $name { + $($(#[$vm])* pub const $variant: Self = Self($value);)* + } + }; +} + +/// A `c_enum!` that is used as a bit set (`SL_ENUM_OPERATORS_32/64`). +macro_rules! c_flags { + ($name:ident : $repr:ty) => { + impl $name { + #[inline] + pub const fn bits(self) -> $repr { + self.0 + } + #[inline] + pub const fn contains(self, other: Self) -> bool { + (self.0 & other.0) == other.0 + } + #[inline] + pub const fn intersects(self, other: Self) -> bool { + (self.0 & other.0) != 0 + } + #[inline] + pub const fn union(self, other: Self) -> Self { + Self(self.0 | other.0) + } + } + impl core::ops::BitOr for $name { + type Output = Self; + fn bitor(self, rhs: Self) -> Self { + Self(self.0 | rhs.0) + } + } + impl core::ops::BitOrAssign for $name { + fn bitor_assign(&mut self, rhs: Self) { + self.0 |= rhs.0; + } + } + impl core::ops::BitAnd for $name { + type Output = Self; + fn bitand(self, rhs: Self) -> Self { + Self(self.0 & rhs.0) + } + } + impl core::ops::Not for $name { + type Output = Self; + fn not(self) -> Self { + Self(!self.0) + } + } + }; +} + +// --------------------------------------------------------------------------------------------- +// Result (sl_result.h) - `enum class Result` (no underlying type => int) +// --------------------------------------------------------------------------------------------- + +/// `sl::Result`. +#[repr(transparent)] +#[must_use] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct SlResult(pub i32); + +const RESULT_NAMES: [&str; 40] = [ + "eOk", + "eErrorIO", + "eErrorDriverOutOfDate", + "eErrorOSOutOfDate", + "eErrorOSDisabledHWS", + "eErrorDeviceNotCreated", + "eErrorNoSupportedAdapterFound", + "eErrorAdapterNotSupported", + "eErrorNoPlugins", + "eErrorVulkanAPI", + "eErrorDXGIAPI", + "eErrorD3DAPI", + "eErrorNRDAPI", + "eErrorNVAPI", + "eErrorReflexAPI", + "eErrorNGXFailed", + "eErrorJSONParsing", + "eErrorMissingProxy", + "eErrorMissingResourceState", + "eErrorInvalidIntegration", + "eErrorMissingInputParameter", + "eErrorNotInitialized", + "eErrorComputeFailed", + "eErrorInitNotCalled", + "eErrorExceptionHandler", + "eErrorInvalidParameter", + "eErrorMissingConstants", + "eErrorDuplicatedConstants", + "eErrorMissingOrInvalidAPI", + "eErrorCommonConstantsMissing", + "eErrorUnsupportedInterface", + "eErrorFeatureMissing", + "eErrorFeatureNotSupported", + "eErrorFeatureMissingHooks", + "eErrorFeatureFailedToLoad", + "eErrorFeatureWrongPriority", + "eErrorFeatureMissingDependency", + "eErrorFeatureManagerInvalidState", + "eErrorInvalidState", + "eWarnOutOfVRAM", +]; + +impl SlResult { + pub const eOk: Self = Self(0); + pub const eErrorIO: Self = Self(1); + pub const eErrorDriverOutOfDate: Self = Self(2); + pub const eErrorOSOutOfDate: Self = Self(3); + pub const eErrorOSDisabledHWS: Self = Self(4); + pub const eErrorDeviceNotCreated: Self = Self(5); + pub const eErrorNoSupportedAdapterFound: Self = Self(6); + pub const eErrorAdapterNotSupported: Self = Self(7); + pub const eErrorNoPlugins: Self = Self(8); + pub const eErrorVulkanAPI: Self = Self(9); + pub const eErrorDXGIAPI: Self = Self(10); + pub const eErrorD3DAPI: Self = Self(11); + pub const eErrorNRDAPI: Self = Self(12); + pub const eErrorNVAPI: Self = Self(13); + pub const eErrorReflexAPI: Self = Self(14); + pub const eErrorNGXFailed: Self = Self(15); + pub const eErrorJSONParsing: Self = Self(16); + pub const eErrorMissingProxy: Self = Self(17); + pub const eErrorMissingResourceState: Self = Self(18); + pub const eErrorInvalidIntegration: Self = Self(19); + pub const eErrorMissingInputParameter: Self = Self(20); + pub const eErrorNotInitialized: Self = Self(21); + pub const eErrorComputeFailed: Self = Self(22); + pub const eErrorInitNotCalled: Self = Self(23); + pub const eErrorExceptionHandler: Self = Self(24); + pub const eErrorInvalidParameter: Self = Self(25); + pub const eErrorMissingConstants: Self = Self(26); + pub const eErrorDuplicatedConstants: Self = Self(27); + pub const eErrorMissingOrInvalidAPI: Self = Self(28); + pub const eErrorCommonConstantsMissing: Self = Self(29); + pub const eErrorUnsupportedInterface: Self = Self(30); + pub const eErrorFeatureMissing: Self = Self(31); + pub const eErrorFeatureNotSupported: Self = Self(32); + pub const eErrorFeatureMissingHooks: Self = Self(33); + pub const eErrorFeatureFailedToLoad: Self = Self(34); + pub const eErrorFeatureWrongPriority: Self = Self(35); + pub const eErrorFeatureMissingDependency: Self = Self(36); + pub const eErrorFeatureManagerInvalidState: Self = Self(37); + pub const eErrorInvalidState: Self = Self(38); + pub const eWarnOutOfVRAM: Self = Self(39); + + #[inline] + pub const fn is_ok(self) -> bool { + self.0 == 0 + } + #[inline] + pub fn ok(self) -> Result<(), SlResult> { + if self.is_ok() { Ok(()) } else { Err(self) } + } + pub fn name(self) -> &'static str { + usize::try_from(self.0) + .ok() + .and_then(|i| RESULT_NAMES.get(i).copied()) + .unwrap_or("<unknown sl::Result>") + } +} + +impl core::fmt::Debug for SlResult { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{}({})", self.name(), self.0) + } +} + +impl core::fmt::Display for SlResult { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "sl::Result::{} ({})", self.name(), self.0) + } +} + +impl std::error::Error for SlResult {} + +/// Returned by the wrappers when an optional / feature function pointer was not resolved. +pub const MISSING_FUNCTION: SlResult = SlResult::eErrorMissingOrInvalidAPI; + +// --------------------------------------------------------------------------------------------- +// Ids and enums (sl_core_types.h, sl_consts.h, sl_appidentity.h, sl_device_wrappers.h) +// --------------------------------------------------------------------------------------------- + +/// `using Feature = uint32_t;` +pub type Feature = u32; +pub const kFeatureDLSS: Feature = 0; +pub const kFeatureNRD_INVALID: Feature = 1; +pub const kFeatureNIS: Feature = 2; +pub const kFeatureReflex: Feature = 3; +pub const kFeaturePCL: Feature = 4; +pub const kFeatureDeepDVC: Feature = 5; +pub const kFeatureLatewarp: Feature = 6; +pub const kFeatureDLSS_G: Feature = 1000; +pub const kFeatureDLSS_RR: Feature = 1001; +pub const kFeatureNvPerf: Feature = 1002; +pub const kFeatureDirectSR: Feature = 1003; +pub const kFeatureDLSS_NR: Feature = 1004; +pub const kFeatureImGUI: Feature = 9999; +/// sl.common (UINT_MAX), "NOT intended to be used directly"; always loaded. +pub const kFeatureCommon: Feature = u32::MAX; + +/// `featuresToLoad` for frame generation. sl.dlss_g requires sl.common + sl.reflex; sl.common and +/// sl.pcl are added by SL itself. +pub const FG_FEATURES: [Feature; 2] = [kFeatureDLSS_G, kFeatureReflex]; + +/// `using BufferType = uint32_t;` (subset; the header has 0..=72) +pub type BufferType = u32; +pub const kBufferTypeDepth: BufferType = 0; +pub const kBufferTypeMotionVectors: BufferType = 1; +pub const kBufferTypeHUDLessColor: BufferType = 2; +pub const kBufferTypeScalingInputColor: BufferType = 3; +pub const kBufferTypeScalingOutputColor: BufferType = 4; +pub const kBufferTypeExposure: BufferType = 13; +pub const kBufferTypeUIColorAndAlpha: BufferType = 23; +pub const kBufferTypeHiResDepth: BufferType = 48; +pub const kBufferTypeLinearDepth: BufferType = 49; +pub const kBufferTypeBidirectionalDistortionField: BufferType = 50; +pub const kBufferTypeBackbuffer: BufferType = 53; +pub const kBufferTypeNoWarpMask: BufferType = 54; +pub const kBufferTypeUIAlpha: BufferType = 69; + +c_enum! { + /// `enum class LogLevel : uint32_t` + LogLevel: u32 { eOff = 0, eDefault = 1, eVerbose = 2, eCount = 3 } +} + +c_enum! { + /// `enum class LogType : uint32_t` + LogType: u32 { eInfo = 0, eWarn = 1, eError = 2, eCount = 3 } +} + +c_enum! { + /// `enum class ResourceType : char` + ResourceType: u8 { + eTex2d = 0, + eBuffer = 1, + eCommandQueue = 2, + eCommandBuffer = 3, + eCommandPool = 4, + eFence = 5, + eSwapchain = 6, + eHostFence = 7, + eUnknown = 8, + eCount = 9, + } +} + +c_enum! { + /// `enum ResourceLifecycle` (unscoped, no fixed type => int) + ResourceLifecycle: i32 { eOnlyValidNow = 0, eValidUntilPresent = 1, eValidUntilEvaluate = 2 } +} + +c_enum! { + /// `enum Boolean : char` + Boolean: u8 { eFalse = 0, eTrue = 1, eInvalid = 2 } +} + +impl From<bool> for Boolean { + fn from(b: bool) -> Self { + if b { Self::eTrue } else { Self::eFalse } + } +} + +c_enum! { + /// `enum class PreferenceFlags : uint64_t` + PreferenceFlags: u64 { + eDisableCLStateTracking = 1 << 0, + eDisableDebugText = 1 << 1, + eUseManualHooking = 1 << 2, + eAllowOTA = 1 << 3, + eBypassOSVersionCheck = 1 << 4, + eUseDXGIFactoryProxy = 1 << 5, + eLoadDownloadedPlugins = 1 << 6, + eUseFrameBasedResourceTagging = 1 << 7, + eAll = 0xff, + } +} +c_flags!(PreferenceFlags: u64); + +impl PreferenceFlags { + /// The C++ default member initializer of `Preferences::flags`. + pub const DEFAULT: Self = Self( + Self::eDisableCLStateTracking.0 | Self::eAllowOTA.0 | Self::eLoadDownloadedPlugins.0, + ); + /// Manual hooking + `slSetTagForFrame` (no OTA). + pub const MANUAL_HOOKING_FRAME_TAGS: Self = Self( + Self::eDisableCLStateTracking.0 + | Self::eUseManualHooking.0 + | Self::eUseFrameBasedResourceTagging.0, + ); +} + +c_enum! { + /// `enum class EngineType : uint32_t` + EngineType: u32 { eCustom = 0, eUnreal = 1, eUnity = 2, eCount = 3 } +} + +c_enum! { + /// `enum class RenderAPI : uint32_t` + RenderAPI: u32 { eD3D11 = 0, eD3D12 = 1, eVulkan = 2, eCount = 3 } +} + +c_enum! { + /// `enum class FeatureRequirementFlags : uint32_t` + FeatureRequirementFlags: u32 { + eD3D11Supported = 1 << 0, + eD3D12Supported = 1 << 1, + eVulkanSupported = 1 << 2, + eVSyncOffRequired = 1 << 3, + eHardwareSchedulingRequired = 1 << 4, + eAll = 0x1f, + } +} +c_flags!(FeatureRequirementFlags: u32); + +// DLSS-G (sl_dlss_g.h) + +c_enum! { + /// `enum class DLSSGMode : uint32_t` + DLSSGMode: u32 { eOff = 0, eOn = 1, eAuto = 2, eDynamic = 3, eCount = 4 } +} + +c_enum! { + /// `enum class DLSSGFlags : uint32_t` + DLSSGFlags: u32 { + eShowOnlyInterpolatedFrame = 1 << 0, + eDynamicResolutionEnabled = 1 << 1, + eRequestVRAMEstimate = 1 << 2, + eRetainResourcesWhenOff = 1 << 3, + eEnableFullscreenMenuDetection = 1 << 4, + eAll = 0x1f, + } +} +c_flags!(DLSSGFlags: u32); + +c_enum! { + /// `enum class DLSSGQueueParallelismMode : uint32_t` (eBlockNoClientQueues is Vulkan-only) + DLSSGQueueParallelismMode: u32 { eBlockPresentingClientQueue = 0, eBlockNoClientQueues = 1, eCount = 2 } +} + +c_enum! { + /// `enum class DLSSGStatus : uint32_t` + DLSSGStatus: u32 { + eOk = 0, + eFailResolutionTooLow = 1 << 0, + eFailReflexNotDetectedAtRuntime = 1 << 1, + eFailHDRFormatNotSupported = 1 << 2, + eFailCommonConstantsInvalid = 1 << 3, + eFailGetCurrentBackBufferIndexNotCalled = 1 << 4, + eReserved5 = 1 << 5, + eAll = 0x3f, + } +} +c_flags!(DLSSGStatus: u32); + +// Reflex (sl_reflex.h) + +c_enum! { + /// `enum ReflexMode` (unscoped, no fixed type => int) + ReflexMode: i32 { eOff = 0, eLowLatency = 1, eLowLatencyWithBoost = 2, ReflexMode_eCount = 3 } +} + +pub const kReflexFrameReportCount: usize = 64; + +// PCL (sl_pcl.h) + +c_enum! { + /// `enum class PCLHotKey : int16_t` + PCLHotKey: i16 { eUsePingMessage = 0, eVK_F13 = 0x7C, eVK_F14 = 0x7D, eVK_F15 = 0x7E } +} + +c_enum! { + /// `enum class PCLMarker : uint32_t` + PCLMarker: u32 { + eSimulationStart = 0, + eSimulationEnd = 1, + eRenderSubmitStart = 2, + eRenderSubmitEnd = 3, + ePresentStart = 4, + ePresentEnd = 5, + // 6 = eInputSample, deprecated/removed + eTriggerFlash = 7, + ePCLatencyPing = 8, + eOutOfBandRenderSubmitStart = 9, + eOutOfBandRenderSubmitEnd = 10, + eOutOfBandPresentStart = 11, + eOutOfBandPresentEnd = 12, + eControllerInputSample = 13, + eDeltaTCalculation = 14, + eLateWarpPresentStart = 15, + eLateWarpPresentEnd = 16, + eCameraConstructed = 17, + eLateWarpRenderSubmitStart = 18, + eLateWarpRenderSubmitEnd = 19, + eVendorInternalAsyncPresentStart = 20, + eVendorInternalAsyncPresentEnd = 21, + eNumPresentsInBatch = 22, + eMaximum = 23, + } +} + +// --------------------------------------------------------------------------------------------- +// Math types (sl_consts.h) - default-constructed to INVALID_FLOAT like the C++ constructors +// --------------------------------------------------------------------------------------------- + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct float2 { + pub x: f32, + pub y: f32, +} +impl float2 { + pub const fn new(x: f32, y: f32) -> Self { + Self { x, y } + } +} +impl Default for float2 { + fn default() -> Self { + Self::new(INVALID_FLOAT, INVALID_FLOAT) + } +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct float3 { + pub x: f32, + pub y: f32, + pub z: f32, +} +impl float3 { + pub const fn new(x: f32, y: f32, z: f32) -> Self { + Self { x, y, z } + } +} +impl Default for float3 { + fn default() -> Self { + Self::new(INVALID_FLOAT, INVALID_FLOAT, INVALID_FLOAT) + } +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct float4 { + pub x: f32, + pub y: f32, + pub z: f32, + pub w: f32, +} +impl float4 { + pub const fn new(x: f32, y: f32, z: f32, w: f32) -> Self { + Self { x, y, z, w } + } +} +impl Default for float4 { + fn default() -> Self { + Self::new(INVALID_FLOAT, INVALID_FLOAT, INVALID_FLOAT, INVALID_FLOAT) + } +} + +/// Row-major 4x4 (`float4 row[4]`). +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Default)] +pub struct float4x4 { + pub row: [float4; 4], +} +impl float4x4 { + pub const fn from_rows(r: [[f32; 4]; 4]) -> Self { + Self { + row: [ + float4::new(r[0][0], r[0][1], r[0][2], r[0][3]), + float4::new(r[1][0], r[1][1], r[1][2], r[1][3]), + float4::new(r[2][0], r[2][1], r[2][2], r[2][3]), + float4::new(r[3][0], r[3][1], r[3][2], r[3][3]), + ], + } + } + pub const fn identity() -> Self { + Self::from_rows([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]) + } +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct uint2 { + pub x: u32, + pub y: u32, +} + +/// `sl::Extent { top, left, width, height }` (all zero = whole resource). +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Extent { + pub top: u32, + pub left: u32, + pub width: u32, + pub height: u32, +} + +/// `sl::Version { major, minor, build }`. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Version { + pub major: u32, + pub minor: u32, + pub build: u32, +} + +/// `struct APIError { union { HRESULT hres; SL_VKResult vkRes; }; }` (both 32-bit). +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct APIError { + pub hres: i32, +} + +// --------------------------------------------------------------------------------------------- +// Callbacks +// --------------------------------------------------------------------------------------------- + +/// `Resource(const ResourceAllocationDesc* desc, void* device)` +pub type PFun_ResourceAllocateCallback = + unsafe extern "C" fn(desc: *const ResourceAllocationDesc, device: *mut c_void) -> Resource; +/// `void(Resource* resource, void* device)` +pub type PFun_ResourceReleaseCallback = unsafe extern "C" fn(resource: *mut Resource, device: *mut c_void); +/// `void(LogType type, const char* msg)` +pub type PFun_LogMessageCallback = unsafe extern "C" fn(ty: LogType, msg: *const c_char); +/// `void(const APIError& lastError)` - called on the present thread, must return quickly. +pub type PFunOnAPIErrorCallback = unsafe extern "C" fn(lastError: *const APIError); + +/// A ready-made `logMessageCallback` that forwards SL's log to `tracing`. +pub unsafe extern "C" fn log_to_tracing(ty: LogType, msg: *const c_char) { + if msg.is_null() { + return; + } + // SAFETY: SL passes a NUL-terminated string valid for the duration of the call. + let text = unsafe { CStr::from_ptr(msg) }.to_string_lossy(); + let text = text.trim_end(); + match ty { + LogType::eError => tracing::error!(target: "streamline", "{text}"), + LogType::eWarn => tracing::warn!(target: "streamline", "{text}"), + _ => tracing::info!(target: "streamline", "{text}"), + } +} + +// --------------------------------------------------------------------------------------------- +// Core structs (sl_core_types.h) +// --------------------------------------------------------------------------------------------- + +/// `sl::Preferences` {1CA10965-BF8E-432B-8DA1-6716D879FB14}, kStructVersion1. All fields of the +/// 2.14.16 header, in order. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct Preferences { + pub base: BaseStructure, + pub showConsole: bool, + pub logLevel: LogLevel, + /// `const wchar_t** pathsToPlugins` - absolute paths, first has highest priority. + pub pathsToPlugins: *const *const u16, + pub numPathsToPlugins: u32, + /// `const wchar_t*` - null disables file logging. + pub pathToLogsAndData: *const u16, + pub allocateCallback: Option<PFun_ResourceAllocateCallback>, + pub releaseCallback: Option<PFun_ResourceReleaseCallback>, + pub logMessageCallback: Option<PFun_LogMessageCallback>, + pub flags: PreferenceFlags, + pub featuresToLoad: *const Feature, + pub numFeaturesToLoad: u32, + pub applicationId: u32, + pub engine: EngineType, + pub engineVersion: *const c_char, + pub projectId: *const c_char, + pub renderAPI: RenderAPI, +} +sl_struct!( + Preferences, + StructType::new(0x1ca10965, 0xbf8e, 0x432b, [0x8d, 0xa1, 0x67, 0x16, 0xd8, 0x79, 0xfb, 0x14]), + kStructVersion1 +); +impl Default for Preferences { + fn default() -> Self { + Self { + base: Self::header(), + showConsole: false, + logLevel: LogLevel::eDefault, + pathsToPlugins: ptr::null(), + numPathsToPlugins: 0, + pathToLogsAndData: ptr::null(), + allocateCallback: None, + releaseCallback: None, + logMessageCallback: None, + flags: PreferenceFlags::DEFAULT, + featuresToLoad: ptr::null(), + numFeaturesToLoad: 0, + applicationId: 0, + engine: EngineType::eCustom, + engineVersion: ptr::null(), + projectId: ptr::null(), + renderAPI: RenderAPI::eD3D12, + } + } +} + +/// `sl::ResourceAllocationDesc` {00BB57E5-49A2-4C23-A519-AB9286E74014}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct ResourceAllocationDesc { + pub base: BaseStructure, + pub r#type: ResourceType, + /// D3D12_RESOURCE_DESC* + pub desc: *mut c_void, + /// D3D12_RESOURCE_STATES + pub state: u32, + /// D3D12_HEAP_PROPERTIES* or null + pub heap: *mut c_void, +} +sl_struct!( + ResourceAllocationDesc, + StructType::new(0x00bb57e5, 0x49a2, 0x4c23, [0xa5, 0x19, 0xab, 0x92, 0x86, 0xe7, 0x40, 0x14]), + kStructVersion1 +); +impl Default for ResourceAllocationDesc { + fn default() -> Self { + Self { base: Self::header(), r#type: ResourceType::eTex2d, desc: ptr::null_mut(), state: 0, heap: ptr::null_mut() } + } +} + +/// `sl::Resource` {3A9D70CF-2418-4B72-8391-13F8721C7261}, kStructVersion1. +/// +/// For D3D12 only `type`, `native` and `state` are needed (state is MANDATORY with manual hooking). +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct Resource { + pub base: BaseStructure, + pub r#type: ResourceType, + /// ID3D12Resource* + pub native: *mut c_void, + /// Vulkan only + pub memory: *mut c_void, + /// Vulkan only + pub view: *mut c_void, + /// D3D12_RESOURCE_STATES (UINT_MAX = not provided) + pub state: u32, + pub width: u32, + pub height: u32, + pub nativeFormat: u32, + pub mipLevels: u32, + pub arrayLayers: u32, + pub gpuVirtualAddress: u64, + /// VkImageCreateFlags (no initializer in C++; zeroed here) + pub flags: u32, + pub usage: u32, + /// `enum InternalFlags : uint16_t` - do not modify + pub internalFlags: u16, + pub reserved: u16, +} +sl_struct!( + Resource, + StructType::new(0x3a9d70cf, 0x2418, 0x4b72, [0x83, 0x91, 0x13, 0xf8, 0x72, 0x1c, 0x72, 0x61]), + kStructVersion1 +); +impl Default for Resource { + fn default() -> Self { + Self { + base: Self::header(), + r#type: ResourceType::eTex2d, + native: ptr::null_mut(), + memory: ptr::null_mut(), + view: ptr::null_mut(), + state: u32::MAX, + width: 0, + height: 0, + nativeFormat: 0, + mipLevels: 0, + arrayLayers: 0, + gpuVirtualAddress: 0, + flags: 0, + usage: 0, + internalFlags: 0, + reserved: 0, + } + } +} +impl Resource { + /// `Resource(ResourceType::eTex2d, native, state)` for an `ID3D12Resource*`. + pub fn d3d12_tex2d(native: *mut c_void, state: u32) -> Self { + Self { native, state, ..Self::default() } + } +} + +/// `sl::ResourceTag` {4C6A5AAD-B445-496C-87FF-1AF3845BE653}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct ResourceTag { + pub base: BaseStructure, + /// Null removes the tag (releases SL's reference for eValidUntilPresent). + pub resource: *mut Resource, + pub r#type: BufferType, + pub lifecycle: ResourceLifecycle, + /// All zero = whole resource. + pub extent: Extent, +} +sl_struct!( + ResourceTag, + StructType::new(0x4c6a5aad, 0xb445, 0x496c, [0x87, 0xff, 0x1a, 0xf3, 0x84, 0x5b, 0xe6, 0x53]), + kStructVersion1 +); +impl Default for ResourceTag { + fn default() -> Self { + Self { + base: Self::header(), + resource: ptr::null_mut(), + r#type: 0, + lifecycle: ResourceLifecycle::eOnlyValidNow, + extent: Extent::default(), + } + } +} +impl ResourceTag { + /// `ResourceTag(Resource* r, BufferType t, ResourceLifecycle l, const Extent* e = nullptr)` + pub fn new(resource: *mut Resource, ty: BufferType, lifecycle: ResourceLifecycle, extent: Option<Extent>) -> Self { + Self { resource, r#type: ty, lifecycle, extent: extent.unwrap_or_default(), ..Self::default() } + } + /// A null tag for `ty` (removes it). + pub fn null(ty: BufferType) -> Self { + Self::new(ptr::null_mut(), ty, ResourceLifecycle::eValidUntilPresent, None) + } +} + +/// `sl::FrameToken` {830A0F35-DB84-4171-A804-59B206499B18}, kStructVersion1 - OPAQUE. +/// +/// It is an abstract C++ class (`virtual operator uint32_t() const = 0`), so the object starts +/// with a vtable pointer and is only ever handled by pointer, as obtained from +/// `slGetNewFrameToken`. SL owns it (a small ring of tokens). +#[repr(C)] +pub struct FrameToken { + _opaque: [u8; 0], + _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>, +} +impl FrameToken { + pub const STRUCT_TYPE: StructType = + StructType::new(0x830a0f35, 0xdb84, 0x4171, [0xa8, 0x04, 0x59, 0xb2, 0x06, 0x49, 0x9b, 0x18]); + pub const STRUCT_VERSION: u32 = kStructVersion1; +} + +/// A frame token handle returned by [`Sl::new_frame_token`]. Copyable; the docs allow handing a +/// copy to other threads ("Store a copy of the handle and use that in any async tasks"). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Frame(NonNull<FrameToken>); +// SAFETY: the token is SL-owned, immutable from our side and documented as usable from any thread. +unsafe impl Send for Frame {} +// SAFETY: as above. +unsafe impl Sync for Frame {} + +impl Frame { + #[inline] + pub fn as_ptr(self) -> *const FrameToken { + self.0.as_ptr() + } + + /// The frame index SL associates with the token (the C++ `operator uint32_t()`), read through + /// vtable slot 0 (MSVC x64: vfptr at offset 0, `this` in RCX, result in EAX). + /// + /// Prefer remembering the index you passed to `slGetNewFrameToken`. + pub unsafe fn sl_index(self) -> u32 { + type IndexFn = unsafe extern "C" fn(this: *const FrameToken) -> u32; + let this = self.as_ptr(); + // SAFETY: caller guarantees the token is alive (before slShutdown); slot 0 of the + // vtable of every FrameToken implementation is `operator uint32_t() const`. + unsafe { + let vtable = *(this as *const *const IndexFn); + (*vtable)(this) + } + } +} + +/// `sl::ViewportHandle` {171B6435-9B3C-4FC8-9994-FBE52569AAA4}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct ViewportHandle { + pub base: BaseStructure, + /// Private in C++; default UINT_MAX. + pub value: u32, +} +sl_struct!( + ViewportHandle, + StructType::new(0x171b6435, 0x9b3c, 0x4fc8, [0x99, 0x94, 0xfb, 0xe5, 0x25, 0x69, 0xaa, 0xa4]), + kStructVersion1 +); +impl ViewportHandle { + pub const fn new(value: u32) -> Self { + Self { base: Self::header(), value } + } +} +impl Default for ViewportHandle { + fn default() -> Self { + Self::new(u32::MAX) + } +} + +/// `sl::FeatureRequirements` {66714097-AC6D-4BC6-8915-1E0F55A6B61F}, kStructVersion2. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct FeatureRequirements { + pub base: BaseStructure, + pub flags: FeatureRequirementFlags, + pub maxNumCPUThreads: u32, + pub maxNumViewports: u32, + pub numRequiredTags: u32, + pub requiredTags: *const BufferType, + pub osVersionDetected: Version, + pub osVersionRequired: Version, + pub driverVersionDetected: Version, + pub driverVersionRequired: Version, + pub vkNumComputeQueuesRequired: u32, + pub vkNumGraphicsQueuesRequired: u32, + pub vkNumDeviceExtensions: u32, + pub vkDeviceExtensions: *const *const c_char, + pub vkNumInstanceExtensions: u32, + pub vkInstanceExtensions: *const *const c_char, + pub vkNumFeatures12: u32, + pub vkFeatures12: *const *const c_char, + pub vkNumFeatures13: u32, + pub vkFeatures13: *const *const c_char, + pub vkNumOpticalFlowQueuesRequired: u32, +} +sl_struct!( + FeatureRequirements, + StructType::new(0x66714097, 0xac6d, 0x4bc6, [0x89, 0x15, 0x1e, 0x0f, 0x55, 0xa6, 0xb6, 0x1f]), + kStructVersion2 +); +impl Default for FeatureRequirements { + fn default() -> Self { + Self { + base: Self::header(), + flags: FeatureRequirementFlags(0), + maxNumCPUThreads: 0, + maxNumViewports: 0, + numRequiredTags: 0, + requiredTags: ptr::null(), + osVersionDetected: Version::default(), + osVersionRequired: Version::default(), + driverVersionDetected: Version::default(), + driverVersionRequired: Version::default(), + vkNumComputeQueuesRequired: 0, + vkNumGraphicsQueuesRequired: 0, + vkNumDeviceExtensions: 0, + vkDeviceExtensions: ptr::null(), + vkNumInstanceExtensions: 0, + vkInstanceExtensions: ptr::null(), + vkNumFeatures12: 0, + vkFeatures12: ptr::null(), + vkNumFeatures13: 0, + vkFeatures13: ptr::null(), + vkNumOpticalFlowQueuesRequired: 0, + } + } +} +impl FeatureRequirements { + /// The required buffer tags (pointer owned by SL). + pub unsafe fn required_tags(&self) -> &[BufferType] { + if self.requiredTags.is_null() || self.numRequiredTags == 0 { + &[] + } else { + // SAFETY: SL guarantees `numRequiredTags` entries. + unsafe { core::slice::from_raw_parts(self.requiredTags, self.numRequiredTags as usize) } + } + } +} + +/// `sl::FeatureVersion` {6D5B51F0-076B-486D-9995-5A561043F5C1}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct FeatureVersion { + pub base: BaseStructure, + pub versionSL: Version, + pub versionNGX: Version, +} +sl_struct!( + FeatureVersion, + StructType::new(0x6d5b51f0, 0x076b, 0x486d, [0x99, 0x95, 0x5a, 0x56, 0x10, 0x43, 0xf5, 0xc1]), + kStructVersion1 +); +impl Default for FeatureVersion { + fn default() -> Self { + Self { base: Self::header(), versionSL: Version::default(), versionNGX: Version::default() } + } +} + +/// `sl::AdapterInfo` {0677315F-A746-4492-9F42-CB6142C9C3D4}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct AdapterInfo { + pub base: BaseStructure, + /// Points at a `LUID` (DXGI_ADAPTER_DESC::AdapterLuid). + pub deviceLUID: *mut u8, + /// `sizeof(LUID)` = 8 + pub deviceLUIDSizeInBytes: u32, + pub vkPhysicalDevice: *mut c_void, +} +sl_struct!( + AdapterInfo, + StructType::new(0x0677315f, 0xa746, 0x4492, [0x9f, 0x42, 0xcb, 0x61, 0x42, 0xc9, 0xc3, 0xd4]), + kStructVersion1 +); +impl Default for AdapterInfo { + fn default() -> Self { + Self { base: Self::header(), deviceLUID: ptr::null_mut(), deviceLUIDSizeInBytes: 0, vkPhysicalDevice: ptr::null_mut() } + } +} + +// --------------------------------------------------------------------------------------------- +// Constants (sl_consts.h) +// --------------------------------------------------------------------------------------------- + +/// `sl::Constants` {DCD35AD7-4E4A-4BAD-A90C-E0C49EB23AFE}, kStructVersion2. +/// Defaults match C++: every matrix/vector element INVALID_FLOAT. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct Constants { + pub base: BaseStructure, + pub cameraViewToClip: float4x4, + pub clipToCameraView: float4x4, + /// Optional + pub clipToLensClip: float4x4, + pub clipToPrevClip: float4x4, + pub prevClipToClip: float4x4, + /// Pixel space + pub jitterOffset: float2, + pub mvecScale: float2, + /// Optional + pub cameraPinholeOffset: float2, + pub cameraPos: float3, + pub cameraUp: float3, + pub cameraRight: float3, + pub cameraFwd: float3, + pub cameraNear: f32, + pub cameraFar: f32, + /// Radians + pub cameraFOV: f32, + pub cameraAspectRatio: f32, + /// Only needed if `cameraMotionIncluded` is false + pub motionVectorsInvalidValue: f32, + pub depthInverted: Boolean, + pub cameraMotionIncluded: Boolean, + pub motionVectors3D: Boolean, + pub reset: Boolean, + pub orthographicProjection: Boolean, + pub motionVectorsDilated: Boolean, + pub motionVectorsJittered: Boolean, + // Version 2 + pub minRelativeLinearDepthObjectSeparation: f32, +} +sl_struct!( + Constants, + StructType::new(0xdcd35ad7, 0x4e4a, 0x4bad, [0xa9, 0x0c, 0xe0, 0xc4, 0x9e, 0xb2, 0x3a, 0xfe]), + kStructVersion2 +); +impl Default for Constants { + fn default() -> Self { + Self { + base: Self::header(), + cameraViewToClip: float4x4::default(), + clipToCameraView: float4x4::default(), + clipToLensClip: float4x4::default(), + clipToPrevClip: float4x4::default(), + prevClipToClip: float4x4::default(), + jitterOffset: float2::default(), + mvecScale: float2::default(), + cameraPinholeOffset: float2::default(), + cameraPos: float3::default(), + cameraUp: float3::default(), + cameraRight: float3::default(), + cameraFwd: float3::default(), + cameraNear: INVALID_FLOAT, + cameraFar: INVALID_FLOAT, + cameraFOV: INVALID_FLOAT, + cameraAspectRatio: INVALID_FLOAT, + motionVectorsInvalidValue: INVALID_FLOAT, + depthInverted: Boolean::eInvalid, + cameraMotionIncluded: Boolean::eInvalid, + motionVectors3D: Boolean::eInvalid, + reset: Boolean::eInvalid, + orthographicProjection: Boolean::eFalse, + motionVectorsDilated: Boolean::eFalse, + motionVectorsJittered: Boolean::eFalse, + minRelativeLinearDepthObjectSeparation: 40.0, + } + } +} + +// --------------------------------------------------------------------------------------------- +// DLSS-G (sl_dlss_g.h) +// --------------------------------------------------------------------------------------------- + +/// `sl::DLSSGOptions` {FAC5F1CB-2DFD-4F36-A1E6-3A9E865256C5}, kStructVersion5. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct DLSSGOptions { + pub base: BaseStructure, + pub mode: DLSSGMode, + /// 1 = 2x, 2 = 3x, 3 = 4x; <= DLSSGState::numFramesToGenerateMax + pub numFramesToGenerate: u32, + pub flags: DLSSGFlags, + pub dynamicResWidth: u32, + pub dynamicResHeight: u32, + pub numBackBuffers: u32, + pub mvecDepthWidth: u32, + pub mvecDepthHeight: u32, + pub colorWidth: u32, + pub colorHeight: u32, + /// DXGI_FORMAT values + pub colorBufferFormat: u32, + pub mvecBufferFormat: u32, + pub depthBufferFormat: u32, + pub hudLessBufferFormat: u32, + pub uiBufferFormat: u32, + pub onErrorCallback: Option<PFunOnAPIErrorCallback>, + // kStructVersion2 + pub bReserved15: Boolean, + // kStructVersion3 + pub queueParallelismMode: DLSSGQueueParallelismMode, + // kStructVersion4 + pub enableUserInterfaceRecomposition: Boolean, + // kStructVersion5 + /// 0 = display refresh rate (eDynamic only) + pub dynamicTargetFrameRate: f32, +} +sl_struct!( + DLSSGOptions, + StructType::new(0xfac5f1cb, 0x2dfd, 0x4f36, [0xa1, 0xe6, 0x3a, 0x9e, 0x86, 0x52, 0x56, 0xc5]), + kStructVersion5 +); +impl Default for DLSSGOptions { + fn default() -> Self { + Self { + base: Self::header(), + mode: DLSSGMode::eOff, + numFramesToGenerate: 1, + flags: DLSSGFlags(0), + dynamicResWidth: 0, + dynamicResHeight: 0, + numBackBuffers: 0, + mvecDepthWidth: 0, + mvecDepthHeight: 0, + colorWidth: 0, + colorHeight: 0, + colorBufferFormat: 0, + mvecBufferFormat: 0, + depthBufferFormat: 0, + hudLessBufferFormat: 0, + uiBufferFormat: 0, + onErrorCallback: None, + bReserved15: Boolean::eInvalid, + queueParallelismMode: DLSSGQueueParallelismMode::eBlockPresentingClientQueue, + enableUserInterfaceRecomposition: Boolean::eFalse, + dynamicTargetFrameRate: 0.0, + } + } +} + +/// `sl::DLSSGState` {CC8AC8E1-A179-44F5-97FA-E74112F9BC61}, kStructVersion4. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct DLSSGState { + pub base: BaseStructure, + pub estimatedVRAMUsageInBytes: u64, + pub status: DLSSGStatus, + pub minWidthOrHeight: u32, + pub numFramesActuallyPresented: u32, + // kStructVersion2 + pub numFramesToGenerateMax: u32, + pub bReserved4: Boolean, + pub bIsVsyncSupportAvailable: Boolean, + /// Internal fence (ID3D12Fence*) for eBlockNoClientQueues / cross-queue input reuse + pub inputsProcessingCompletionFence: *mut c_void, + pub lastPresentInputsProcessingCompletionFenceValue: u64, + // kStructVersion4 + pub bIsDynamicMFGSupported: Boolean, +} +sl_struct!( + DLSSGState, + StructType::new(0xcc8ac8e1, 0xa179, 0x44f5, [0x97, 0xfa, 0xe7, 0x41, 0x12, 0xf9, 0xbc, 0x61]), + kStructVersion4 +); +impl Default for DLSSGState { + fn default() -> Self { + Self { + base: Self::header(), + estimatedVRAMUsageInBytes: 0, + status: DLSSGStatus::eOk, + minWidthOrHeight: 0, + numFramesActuallyPresented: 0, + numFramesToGenerateMax: 0, + bReserved4: Boolean::eFalse, + bIsVsyncSupportAvailable: Boolean::eFalse, + inputsProcessingCompletionFence: ptr::null_mut(), + lastPresentInputsProcessingCompletionFenceValue: 0, + bIsDynamicMFGSupported: Boolean::eFalse, + } + } +} + +// --------------------------------------------------------------------------------------------- +// Reflex (sl_reflex.h) +// --------------------------------------------------------------------------------------------- + +/// `sl::ReflexOptions` {F03AF81A-6D0B-4902-A651-C4965E215434}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct ReflexOptions { + pub base: BaseStructure, + pub mode: ReflexMode, + /// 0 = no cap, else microseconds per frame + pub frameLimitUs: u32, + /// Leave false unless told otherwise by NVIDIA + pub useMarkersToOptimize: bool, + /// VK_F13/14/15 or 0 + pub virtualKey: u16, + pub idThread: u32, +} +sl_struct!( + ReflexOptions, + StructType::new(0xf03af81a, 0x6d0b, 0x4902, [0xa6, 0x51, 0xc4, 0x96, 0x5e, 0x21, 0x54, 0x34]), + kStructVersion1 +); +impl Default for ReflexOptions { + fn default() -> Self { + Self { base: Self::header(), mode: ReflexMode::eOff, frameLimitUs: 0, useMarkersToOptimize: false, virtualKey: 0, idThread: 0 } + } +} + +/// `sl::ReflexReport` {0D569B37-A1C8-4453-BE4D-40F4DE57952B}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct ReflexReport { + pub base: BaseStructure, + pub frameID: u64, + pub inputSampleTime: u64, + pub simStartTime: u64, + pub simEndTime: u64, + pub renderSubmitStartTime: u64, + pub renderSubmitEndTime: u64, + pub presentStartTime: u64, + pub presentEndTime: u64, + pub driverStartTime: u64, + pub driverEndTime: u64, + pub osRenderQueueStartTime: u64, + pub osRenderQueueEndTime: u64, + pub gpuRenderStartTime: u64, + pub gpuRenderEndTime: u64, + pub gpuActiveRenderTimeUs: u32, + pub gpuFrameTimeUs: u32, +} +sl_struct!( + ReflexReport, + StructType::new(0x0d569b37, 0xa1c8, 0x4453, [0xbe, 0x4d, 0x40, 0xf4, 0xde, 0x57, 0x95, 0x2b]), + kStructVersion1 +); +impl Default for ReflexReport { + fn default() -> Self { + Self { + base: Self::header(), + frameID: 0, + inputSampleTime: 0, + simStartTime: 0, + simEndTime: 0, + renderSubmitStartTime: 0, + renderSubmitEndTime: 0, + presentStartTime: 0, + presentEndTime: 0, + driverStartTime: 0, + driverEndTime: 0, + osRenderQueueStartTime: 0, + osRenderQueueEndTime: 0, + gpuRenderStartTime: 0, + gpuRenderEndTime: 0, + gpuActiveRenderTimeUs: 0, + gpuFrameTimeUs: 0, + } + } +} + +/// `sl::ReflexReport2` {68BB0632-5E1C-402B-899D-B49F633C56C2}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct ReflexReport2 { + pub base: BaseStructure, + pub cameraConstructedTime: u64, + pub crossAdapterCopyTimeUs: u32, +} +sl_struct!( + ReflexReport2, + StructType::new(0x68bb0632, 0x5e1c, 0x402b, [0x89, 0x9d, 0xb4, 0x9f, 0x63, 0x3c, 0x56, 0xc2]), + kStructVersion1 +); +impl Default for ReflexReport2 { + fn default() -> Self { + Self { base: Self::header(), cameraConstructedTime: 0, crossAdapterCopyTimeUs: 0 } + } +} + +/// `sl::ReflexState` {F0BB5985-DAF9-4728-B2FD-AE80A2BD7989}, kStructVersion2 (12848 bytes). +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct ReflexState { + pub base: BaseStructure, + /// Show the Reflex UI only if true; everything else is done regardless. + pub lowLatencyAvailable: bool, + pub latencyReportAvailable: bool, + /// No initializer in C++; zeroed here + pub statsWindowMessage: u32, + pub frameReport: [ReflexReport; kReflexFrameReportCount], + pub flashIndicatorDriverControlled: bool, + // kStructVersion2 + pub frameReport2: [ReflexReport2; kReflexFrameReportCount], +} +sl_struct!( + ReflexState, + StructType::new(0xf0bb5985, 0xdaf9, 0x4728, [0xb2, 0xfd, 0xae, 0x80, 0xa2, 0xbd, 0x79, 0x89]), + kStructVersion2 +); +impl Default for ReflexState { + fn default() -> Self { + Self { + base: Self::header(), + lowLatencyAvailable: false, + latencyReportAvailable: false, + statsWindowMessage: 0, + frameReport: [ReflexReport::default(); kReflexFrameReportCount], + flashIndicatorDriverControlled: false, + frameReport2: [ReflexReport2::default(); kReflexFrameReportCount], + } + } +} + +// --------------------------------------------------------------------------------------------- +// PCL (sl_pcl.h) +// --------------------------------------------------------------------------------------------- + +/// `sl::PCLOptions` {CFA32F9B-023C-420E-9056-6832B74F89B4}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct PCLOptions { + pub base: BaseStructure, + pub virtualKey: PCLHotKey, + pub idThread: u32, +} +sl_struct!( + PCLOptions, + StructType::new(0xcfa32f9b, 0x023c, 0x420e, [0x90, 0x56, 0x68, 0x32, 0xb7, 0x4f, 0x89, 0xb4]), + kStructVersion1 +); +impl Default for PCLOptions { + fn default() -> Self { + Self { base: Self::header(), virtualKey: PCLHotKey::eUsePingMessage, idThread: 0 } + } +} + +/// `sl::PCLState` {CFA32F9B-023C-420E-9056-6832B74F89B5}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct PCLState { + pub base: BaseStructure, + /// Window message id of the PCL ping (send `ePCLatencyPing` when it arrives) + pub statsWindowMessage: u32, +} +sl_struct!( + PCLState, + StructType::new(0xcfa32f9b, 0x023c, 0x420e, [0x90, 0x56, 0x68, 0x32, 0xb7, 0x4f, 0x89, 0xb5]), + kStructVersion1 +); +impl Default for PCLState { + fn default() -> Self { + Self { base: Self::header(), statsWindowMessage: 0 } + } +} + +// --------------------------------------------------------------------------------------------- +// Function pointer types (sl_core_api.h, sl_dlss_g.h, sl_reflex.h, sl_pcl.h) +// C++ references are passed as pointers; `bool` is the 1-byte C++ bool. +// --------------------------------------------------------------------------------------------- + +pub type PFun_slInit = unsafe extern "C" fn(pref: *const Preferences, sdkVersion: u64) -> SlResult; +pub type PFun_slShutdown = unsafe extern "C" fn() -> SlResult; +pub type PFun_slIsFeatureSupported = unsafe extern "C" fn(feature: Feature, adapterInfo: *const AdapterInfo) -> SlResult; +pub type PFun_slIsFeatureLoaded = unsafe extern "C" fn(feature: Feature, loaded: *mut bool) -> SlResult; +pub type PFun_slSetFeatureLoaded = unsafe extern "C" fn(feature: Feature, loaded: bool) -> SlResult; +pub type PFun_slEvaluateFeature = unsafe extern "C" fn( + feature: Feature, + frame: *const FrameToken, + inputs: *const *const BaseStructure, + numInputs: u32, + cmdBuffer: *mut c_void, +) -> SlResult; +pub type PFun_slAllocateResources = + unsafe extern "C" fn(cmdBuffer: *mut c_void, feature: Feature, viewport: *const ViewportHandle) -> SlResult; +pub type PFun_slFreeResources = unsafe extern "C" fn(feature: Feature, viewport: *const ViewportHandle) -> SlResult; +/// Deprecated; cannot be mixed with slSetTagForFrame. +pub type PFun_slSetTag = unsafe extern "C" fn( + viewport: *const ViewportHandle, + tags: *const ResourceTag, + numTags: u32, + cmdBuffer: *mut c_void, +) -> SlResult; +pub type PFun_slSetTagForFrame = unsafe extern "C" fn( + frame: *const FrameToken, + viewport: *const ViewportHandle, + tags: *const ResourceTag, + numTags: u32, + cmdBuffer: *mut c_void, +) -> SlResult; +pub type PFun_slGetFeatureRequirements = + unsafe extern "C" fn(feature: Feature, requirements: *mut FeatureRequirements) -> SlResult; +pub type PFun_slGetFeatureVersion = unsafe extern "C" fn(feature: Feature, version: *mut FeatureVersion) -> SlResult; +pub type PFun_slUpgradeInterface = unsafe extern "C" fn(baseInterface: *mut *mut c_void) -> SlResult; +pub type PFun_slSetConstants = unsafe extern "C" fn( + values: *const Constants, + frame: *const FrameToken, + viewport: *const ViewportHandle, +) -> SlResult; +pub type PFun_slGetNativeInterface = + unsafe extern "C" fn(proxyInterface: *mut c_void, baseInterface: *mut *mut c_void) -> SlResult; +pub type PFun_slGetFeatureFunction = + unsafe extern "C" fn(feature: Feature, functionName: *const c_char, function: *mut *mut c_void) -> SlResult; +pub type PFun_slGetNewFrameToken = unsafe extern "C" fn(token: *mut *mut FrameToken, frameIndex: *const u32) -> SlResult; +pub type PFun_slSetD3DDevice = unsafe extern "C" fn(d3dDevice: *mut c_void) -> SlResult; + +pub type PFun_slDLSSGGetState = unsafe extern "C" fn( + viewport: *const ViewportHandle, + state: *mut DLSSGState, + options: *const DLSSGOptions, +) -> SlResult; +pub type PFun_slDLSSGSetOptions = + unsafe extern "C" fn(viewport: *const ViewportHandle, options: *const DLSSGOptions) -> SlResult; + +pub type PFun_slReflexGetState = unsafe extern "C" fn(state: *mut ReflexState) -> SlResult; +pub type PFun_slReflexSleep = unsafe extern "C" fn(frame: *const FrameToken) -> SlResult; +pub type PFun_slReflexSetOptions = unsafe extern "C" fn(options: *const ReflexOptions) -> SlResult; + +pub type PFun_slPCLGetState = unsafe extern "C" fn(state: *mut PCLState) -> SlResult; +pub type PFun_slPCLSetMarker = unsafe extern "C" fn(marker: PCLMarker, frame: *const FrameToken) -> SlResult; +pub type PFun_slPCLSetOptions = unsafe extern "C" fn(options: *const PCLOptions) -> SlResult; + +// --------------------------------------------------------------------------------------------- +// Runtime loader +// --------------------------------------------------------------------------------------------- + +/// `GetProcAddress(module, name)` typed as `$ty`, or `None`. +macro_rules! proc_address { + ($module:expr, $name:literal, $ty:ty) => {{ + // SAFETY: `module` is a loaded module and the name is a NUL-terminated literal. + let raw = unsafe { GetProcAddress($module, PCSTR(concat!($name, "\0").as_ptr())) }; + // SAFETY: the export has the C signature declared by `$ty` (sl_core_api.h). + raw.map(|f| unsafe { core::mem::transmute::<unsafe extern "system" fn() -> isize, $ty>(f) }) + }}; +} + +/// `slGetFeatureFunction(feature, name, ptr)` typed as `$ty`; failures are pushed to `$missing`. +macro_rules! feature_function { + ($get:expr, $feature:expr, $name:literal, $ty:ty, $missing:ident) => {{ + let mut p: *mut c_void = ptr::null_mut(); + // SAFETY: NUL-terminated literal name and a valid out pointer. + let r = unsafe { ($get)($feature, concat!($name, "\0").as_ptr().cast::<c_char>(), &mut p) }; + if r.is_ok() && !p.is_null() { + // SAFETY: SL hands out the function declared as `$ty` in the feature header. + Some(unsafe { core::mem::transmute::<*mut c_void, $ty>(p) }) + } else { + $missing.push(format!("{} ({})", $name, r)); + None + } + }}; +} + +/// Function table for `sl.interposer.dll`. Core functions are resolved by [`Sl::load`]; feature +/// functions by [`Sl::resolve_feature_functions`] (only after `slSetD3DDevice`). +/// +/// The module is never unloaded (SL keeps hooks and threads alive until process exit). +pub struct Sl { + pub module: HMODULE, + /// Absolute directory `sl.interposer.dll` was loaded from. + pub dir: PathBuf, + + pub slInit: PFun_slInit, + pub slShutdown: PFun_slShutdown, + pub slSetD3DDevice: PFun_slSetD3DDevice, + pub slIsFeatureSupported: PFun_slIsFeatureSupported, + pub slIsFeatureLoaded: PFun_slIsFeatureLoaded, + pub slSetFeatureLoaded: PFun_slSetFeatureLoaded, + pub slGetNewFrameToken: PFun_slGetNewFrameToken, + pub slSetConstants: PFun_slSetConstants, + pub slSetTagForFrame: PFun_slSetTagForFrame, + pub slEvaluateFeature: PFun_slEvaluateFeature, + pub slUpgradeInterface: PFun_slUpgradeInterface, + pub slGetNativeInterface: PFun_slGetNativeInterface, + pub slGetFeatureRequirements: PFun_slGetFeatureRequirements, + pub slGetFeatureFunction: PFun_slGetFeatureFunction, + pub slAllocateResources: PFun_slAllocateResources, + pub slFreeResources: PFun_slFreeResources, + /// Optional exports. + pub slGetFeatureVersion: Option<PFun_slGetFeatureVersion>, + pub slSetTag: Option<PFun_slSetTag>, + + // Feature functions (slGetFeatureFunction) + pub slDLSSGSetOptions: Option<PFun_slDLSSGSetOptions>, + pub slDLSSGGetState: Option<PFun_slDLSSGGetState>, + pub slReflexSetOptions: Option<PFun_slReflexSetOptions>, + pub slReflexGetState: Option<PFun_slReflexGetState>, + pub slReflexSleep: Option<PFun_slReflexSleep>, + pub slPCLSetMarker: Option<PFun_slPCLSetMarker>, + pub slPCLGetState: Option<PFun_slPCLGetState>, + pub slPCLSetOptions: Option<PFun_slPCLSetOptions>, +} + +// SAFETY: the table only holds immutable function pointers and a module handle; thread safety of +// each call is SL's (documented per function in sl_core_api.h / feature headers). +unsafe impl Send for Sl {} +// SAFETY: as above. +unsafe impl Sync for Sl {} + +impl core::fmt::Debug for Sl { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Sl") + .field("dir", &self.dir) + .field("dlssg", &self.slDLSSGSetOptions.is_some()) + .field("reflex", &self.slReflexSetOptions.is_some()) + .field("pcl", &self.slPCLSetMarker.is_some()) + .finish_non_exhaustive() + } +} + +impl Sl { + /// Loads `<dir>\sl.interposer.dll` (full path) and resolves the core exports. + /// + /// # Safety + /// Loading the DLL runs its initialisation code. The caller should have verified the + /// signature of the file if that matters (see module docs). + pub unsafe fn load(dir: &Path) -> anyhow::Result<Self> { + let dir = std::path::absolute(dir).with_context(|| format!("resolving {}", dir.display()))?; + let dll = dir.join(INTERPOSER_DLL); + if !dll.is_file() { + bail!("{} not found", dll.display()); + } + let wide: Vec<u16> = dll.as_os_str().encode_wide().chain(Some(0)).collect(); + // SAFETY: NUL-terminated full path; the caller accepts running the DLL's init code. + let module = unsafe { LoadLibraryW(PCWSTR(wide.as_ptr())) } + .with_context(|| format!("LoadLibraryW({})", dll.display()))?; + + macro_rules! need { + ($name:literal, $ty:ty) => { + proc_address!(module, $name, $ty) + .ok_or_else(|| anyhow!("{} does not export {}", dll.display(), $name))? + }; + } + + Ok(Self { + module, + slInit: need!("slInit", PFun_slInit), + slShutdown: need!("slShutdown", PFun_slShutdown), + slSetD3DDevice: need!("slSetD3DDevice", PFun_slSetD3DDevice), + slIsFeatureSupported: need!("slIsFeatureSupported", PFun_slIsFeatureSupported), + slIsFeatureLoaded: need!("slIsFeatureLoaded", PFun_slIsFeatureLoaded), + slSetFeatureLoaded: need!("slSetFeatureLoaded", PFun_slSetFeatureLoaded), + slGetNewFrameToken: need!("slGetNewFrameToken", PFun_slGetNewFrameToken), + slSetConstants: need!("slSetConstants", PFun_slSetConstants), + slSetTagForFrame: need!("slSetTagForFrame", PFun_slSetTagForFrame), + slEvaluateFeature: need!("slEvaluateFeature", PFun_slEvaluateFeature), + slUpgradeInterface: need!("slUpgradeInterface", PFun_slUpgradeInterface), + slGetNativeInterface: need!("slGetNativeInterface", PFun_slGetNativeInterface), + slGetFeatureRequirements: need!("slGetFeatureRequirements", PFun_slGetFeatureRequirements), + slGetFeatureFunction: need!("slGetFeatureFunction", PFun_slGetFeatureFunction), + slAllocateResources: need!("slAllocateResources", PFun_slAllocateResources), + slFreeResources: need!("slFreeResources", PFun_slFreeResources), + slGetFeatureVersion: proc_address!(module, "slGetFeatureVersion", PFun_slGetFeatureVersion), + slSetTag: proc_address!(module, "slSetTag", PFun_slSetTag), + slDLSSGSetOptions: None, + slDLSSGGetState: None, + slReflexSetOptions: None, + slReflexGetState: None, + slReflexSleep: None, + slPCLSetMarker: None, + slPCLGetState: None, + slPCLSetOptions: None, + dir, + }) + } + + /// Resolves the DLSS-G / Reflex / PCL functions with `slGetFeatureFunction`. + /// Must be called AFTER `slSetD3DDevice`. Keeps whatever resolved; errors list the rest. + pub fn resolve_feature_functions(&mut self) -> anyhow::Result<()> { + let get = self.slGetFeatureFunction; + let mut missing: Vec<String> = Vec::new(); + self.slDLSSGSetOptions = + feature_function!(get, kFeatureDLSS_G, "slDLSSGSetOptions", PFun_slDLSSGSetOptions, missing); + self.slDLSSGGetState = feature_function!(get, kFeatureDLSS_G, "slDLSSGGetState", PFun_slDLSSGGetState, missing); + self.slReflexSetOptions = + feature_function!(get, kFeatureReflex, "slReflexSetOptions", PFun_slReflexSetOptions, missing); + self.slReflexGetState = feature_function!(get, kFeatureReflex, "slReflexGetState", PFun_slReflexGetState, missing); + self.slReflexSleep = feature_function!(get, kFeatureReflex, "slReflexSleep", PFun_slReflexSleep, missing); + self.slPCLSetMarker = feature_function!(get, kFeaturePCL, "slPCLSetMarker", PFun_slPCLSetMarker, missing); + self.slPCLGetState = feature_function!(get, kFeaturePCL, "slPCLGetState", PFun_slPCLGetState, missing); + self.slPCLSetOptions = feature_function!(get, kFeaturePCL, "slPCLSetOptions", PFun_slPCLSetOptions, missing); + if missing.is_empty() { + Ok(()) + } else { + Err(anyhow!("Streamline feature functions not available: {}", missing.join(", "))) + } + } + + // ---- core wrappers ---------------------------------------------------------------------- + + /// `slInit(pref, kSDKVersion)`. + /// + /// # Safety + /// Every pointer in `pref` must be valid for the call (SL copies paths, features and strings). + /// The log callback must stay valid until `slShutdown`. + pub unsafe fn init(&self, pref: &Preferences) -> SlResult { + // SAFETY: caller upholds the pointer requirements of `pref`. + unsafe { (self.slInit)(pref, kSDKVersion) } + } + + /// `slShutdown()` - before releasing DXGI/D3D objects. + pub fn shutdown(&self) -> SlResult { + // SAFETY: no arguments. + unsafe { (self.slShutdown)() } + } + + /// `slSetD3DDevice(nativeDevice)`. + /// + /// # Safety + /// `native_device` must be a live NATIVE `ID3D12Device*` (not the SL proxy). + pub unsafe fn set_d3d_device(&self, native_device: *mut c_void) -> SlResult { + // SAFETY: caller guarantees a live device. + unsafe { (self.slSetD3DDevice)(native_device) } + } + + /// `slIsFeatureSupported(feature, AdapterInfo{LUID})`; `None` checks OS/driver only. + pub fn is_feature_supported(&self, feature: Feature, adapter_luid: Option<&[u8; 8]>) -> SlResult { + let mut luid = adapter_luid.copied().unwrap_or_default(); + let mut info = AdapterInfo::default(); + if adapter_luid.is_some() { + info.deviceLUID = luid.as_mut_ptr(); + info.deviceLUIDSizeInBytes = 8; + } + // SAFETY: `info` and `luid` outlive the call. + unsafe { (self.slIsFeatureSupported)(feature, &info) } + } + + /// `slIsFeatureLoaded(feature, loaded)`. + pub fn is_feature_loaded(&self, feature: Feature) -> Result<bool, SlResult> { + let mut loaded = false; + // SAFETY: valid out pointer. + unsafe { (self.slIsFeatureLoaded)(feature, &mut loaded) }.ok()?; + Ok(loaded) + } + + /// `slSetFeatureLoaded(feature, loaded)` - load/unload (unhook) a feature. Flush the GPU and + /// make no DXGI/D3D calls in parallel. + pub fn set_feature_loaded(&self, feature: Feature, loaded: bool) -> SlResult { + // SAFETY: plain values. + unsafe { (self.slSetFeatureLoaded)(feature, loaded) } + } + + /// `slGetNewFrameToken(token, frameIndex)`. Passing your own index bypasses SL's counter. + pub fn new_frame_token(&self, frame_index: Option<u32>) -> Result<Frame, SlResult> { + let mut token: *mut FrameToken = ptr::null_mut(); + let index = frame_index.unwrap_or(0); + let index_ptr = if frame_index.is_some() { &index as *const u32 } else { ptr::null() }; + // SAFETY: valid out pointer; `index` outlives the call. + unsafe { (self.slGetNewFrameToken)(&mut token, index_ptr) }.ok()?; + NonNull::new(token).map(Frame).ok_or(SlResult::eErrorInvalidState) + } + + /// `slSetConstants(values, frame, viewport)` - once per frame. + pub fn set_constants(&self, values: &Constants, frame: Frame, viewport: &ViewportHandle) -> SlResult { + // SAFETY: references are valid; the token came from SL. + unsafe { (self.slSetConstants)(values, frame.as_ptr(), viewport) } + } + + /// `slSetTagForFrame(frame, viewport, tags, numTags, cmdList)`. + /// + /// # Safety + /// Every non-null `tags[i].resource` must point at a valid `Resource` whose `native` is a live + /// `ID3D12Resource*`; `cmd_list` is a NATIVE open `ID3D12GraphicsCommandList*` or null (null + /// only if all tags are null or `eValidUntilPresent`). + pub unsafe fn set_tag_for_frame( + &self, + frame: Frame, + viewport: &ViewportHandle, + tags: &[ResourceTag], + cmd_list: *mut c_void, + ) -> SlResult { + // SAFETY: caller guarantees the resource and command list pointers. + unsafe { (self.slSetTagForFrame)(frame.as_ptr(), viewport, tags.as_ptr(), tags.len() as u32, cmd_list) } + } + + /// Deprecated `slSetTag` (only without `eUseFrameBasedResourceTagging`). + /// + /// # Safety + /// As [`Sl::set_tag_for_frame`]. + pub unsafe fn set_tag(&self, viewport: &ViewportHandle, tags: &[ResourceTag], cmd_list: *mut c_void) -> SlResult { + match self.slSetTag { + // SAFETY: caller guarantees the resource and command list pointers. + Some(f) => unsafe { f(viewport, tags.as_ptr(), tags.len() as u32, cmd_list) }, + None => MISSING_FUNCTION, + } + } + + /// `slEvaluateFeature` (not needed for DLSS-G). + /// + /// # Safety + /// `inputs` must point at live SL structs; `cmd_list` a native command list. + pub unsafe fn evaluate_feature( + &self, + feature: Feature, + frame: Frame, + inputs: &[*const BaseStructure], + cmd_list: *mut c_void, + ) -> SlResult { + // SAFETY: caller guarantees the inputs. + unsafe { (self.slEvaluateFeature)(feature, frame.as_ptr(), inputs.as_ptr(), inputs.len() as u32, cmd_list) } + } + + /// `slUpgradeInterface(&iface)` - replaces `*iface` in place with a new SL proxy + /// (`ID3D12Device`, `IDXGIFactory*`, `IDXGISwapChain*`). The proxy has its own reference + /// (count 1) and AddRefs the base; the caller's reference to the native object is NOT consumed. + /// + /// # Safety + /// `*iface` must be a live COM pointer of a supported interface. + pub unsafe fn upgrade_interface(&self, iface: &mut *mut c_void) -> SlResult { + // SAFETY: caller guarantees a live COM pointer. + unsafe { (self.slUpgradeInterface)(iface) } + } + + /// `slGetNativeInterface(proxy, &base)` - returns an AddRef'd native pointer. + /// + /// # Safety + /// `proxy` must be a live COM pointer. + pub unsafe fn get_native_interface(&self, proxy: *mut c_void) -> Result<*mut c_void, SlResult> { + let mut base: *mut c_void = ptr::null_mut(); + // SAFETY: caller guarantees a live COM pointer; valid out pointer. + unsafe { (self.slGetNativeInterface)(proxy, &mut base) }.ok()?; + Ok(base) + } + + /// `slGetFeatureRequirements(feature, requirements)`. + pub fn get_feature_requirements(&self, feature: Feature) -> Result<FeatureRequirements, SlResult> { + let mut req = FeatureRequirements::default(); + // SAFETY: valid out struct with a correct header. + unsafe { (self.slGetFeatureRequirements)(feature, &mut req) }.ok()?; + Ok(req) + } + + /// `slGetFeatureVersion(feature, version)`. + pub fn get_feature_version(&self, feature: Feature) -> Result<FeatureVersion, SlResult> { + let f = self.slGetFeatureVersion.ok_or(MISSING_FUNCTION)?; + let mut v = FeatureVersion::default(); + // SAFETY: valid out struct. + unsafe { f(feature, &mut v) }.ok()?; + Ok(v) + } + + /// `slGetFeatureFunction(feature, name, &fn)` (raw). + /// + /// # Safety + /// The caller must transmute the pointer to the exact signature of `name`. + pub unsafe fn get_feature_function(&self, feature: Feature, name: &CStr) -> Result<*mut c_void, SlResult> { + let mut p: *mut c_void = ptr::null_mut(); + // SAFETY: NUL-terminated name, valid out pointer. + unsafe { (self.slGetFeatureFunction)(feature, name.as_ptr(), &mut p) }.ok()?; + Ok(p) + } + + /// `slAllocateResources(cmdList, feature, viewport)`. + /// + /// # Safety + /// `cmd_list` is a native command list on the SL device, or null. + pub unsafe fn allocate_resources(&self, cmd_list: *mut c_void, feature: Feature, viewport: &ViewportHandle) -> SlResult { + // SAFETY: caller guarantees the command list. + unsafe { (self.slAllocateResources)(cmd_list, feature, viewport) } + } + + /// `slFreeResources(feature, viewport)` - flush pending work first. + pub fn free_resources(&self, feature: Feature, viewport: &ViewportHandle) -> SlResult { + // SAFETY: valid reference. + unsafe { (self.slFreeResources)(feature, viewport) } + } + + // ---- DLSS-G ----------------------------------------------------------------------------- + + /// `slDLSSGSetOptions(viewport, options)` - applies at the next Present; call on the present thread. + pub fn dlssg_set_options(&self, viewport: &ViewportHandle, options: &DLSSGOptions) -> SlResult { + match self.slDLSSGSetOptions { + // SAFETY: valid references; `onErrorCallback` (if any) is a valid fn pointer. + Some(f) => unsafe { f(viewport, options) }, + None => MISSING_FUNCTION, + } + } + + /// `slDLSSGGetState(viewport, state, options)`. Pass `None` for the cheap per-frame query. + pub fn dlssg_get_state(&self, viewport: &ViewportHandle, options: Option<&DLSSGOptions>) -> Result<DLSSGState, SlResult> { + let f = self.slDLSSGGetState.ok_or(MISSING_FUNCTION)?; + let mut state = DLSSGState::default(); + let opts = options.map_or(ptr::null(), |o| o as *const DLSSGOptions); + // SAFETY: valid references / out struct. + unsafe { f(viewport, &mut state, opts) }.ok()?; + Ok(state) + } + + // ---- Reflex ----------------------------------------------------------------------------- + + /// `slReflexSetOptions(options)` - at least once, even with Reflex off. + pub fn reflex_set_options(&self, options: &ReflexOptions) -> SlResult { + match self.slReflexSetOptions { + // SAFETY: valid reference. + Some(f) => unsafe { f(options) }, + None => MISSING_FUNCTION, + } + } + + /// `slReflexGetState(state)` (boxed: 12.8 KB). + pub fn reflex_get_state(&self) -> Result<Box<ReflexState>, SlResult> { + let f = self.slReflexGetState.ok_or(MISSING_FUNCTION)?; + let mut state = Box::<ReflexState>::default(); + // SAFETY: valid out struct. + unsafe { f(&mut *state) }.ok()?; + Ok(state) + } + + /// `slReflexSleep(frame)` - every frame, regardless of Reflex mode. + pub fn reflex_sleep(&self, frame: Frame) -> SlResult { + match self.slReflexSleep { + // SAFETY: token from SL. + Some(f) => unsafe { f(frame.as_ptr()) }, + None => MISSING_FUNCTION, + } + } + + // ---- PCL -------------------------------------------------------------------------------- + + /// `slPCLSetMarker(marker, frame)` (thread safe). + pub fn pcl_set_marker(&self, marker: PCLMarker, frame: Frame) -> SlResult { + match self.slPCLSetMarker { + // SAFETY: token from SL. + Some(f) => unsafe { f(marker, frame.as_ptr()) }, + None => MISSING_FUNCTION, + } + } + + /// `slPCLGetState(state)` - `statsWindowMessage` for the ping. + pub fn pcl_get_state(&self) -> Result<PCLState, SlResult> { + let f = self.slPCLGetState.ok_or(MISSING_FUNCTION)?; + let mut state = PCLState::default(); + // SAFETY: valid out struct. + unsafe { f(&mut state) }.ok()?; + Ok(state) + } + + /// `slPCLSetOptions(options)`. + pub fn pcl_set_options(&self, options: &PCLOptions) -> SlResult { + match self.slPCLSetOptions { + // SAFETY: valid reference. + Some(f) => unsafe { f(options) }, + None => MISSING_FUNCTION, + } + } +} + +// --------------------------------------------------------------------------------------------- +// Layout checks (x64 MSVC sizes/offsets computed from the 2.14.16 headers) +// --------------------------------------------------------------------------------------------- + +#[cfg(target_pointer_width = "64")] +const _: () = { + use core::mem::{align_of, offset_of, size_of}; + + assert!(size_of::<StructType>() == 16); + assert!(size_of::<BaseStructure>() == 32); + assert!(offset_of!(BaseStructure, structType) == 8); + assert!(offset_of!(BaseStructure, structVersion) == 24); + + assert!(size_of::<Preferences>() == 144); + assert!(offset_of!(Preferences, showConsole) == 32); + assert!(offset_of!(Preferences, logLevel) == 36); + assert!(offset_of!(Preferences, pathsToPlugins) == 40); + assert!(offset_of!(Preferences, numPathsToPlugins) == 48); + assert!(offset_of!(Preferences, pathToLogsAndData) == 56); + assert!(offset_of!(Preferences, logMessageCallback) == 80); + assert!(offset_of!(Preferences, flags) == 88); + assert!(offset_of!(Preferences, featuresToLoad) == 96); + assert!(offset_of!(Preferences, numFeaturesToLoad) == 104); + assert!(offset_of!(Preferences, applicationId) == 108); + assert!(offset_of!(Preferences, engine) == 112); + assert!(offset_of!(Preferences, engineVersion) == 120); + assert!(offset_of!(Preferences, projectId) == 128); + assert!(offset_of!(Preferences, renderAPI) == 136); + + assert!(size_of::<ResourceAllocationDesc>() == 64); + + assert!(size_of::<Resource>() == 112); + assert!(offset_of!(Resource, r#type) == 32); + assert!(offset_of!(Resource, native) == 40); + assert!(offset_of!(Resource, state) == 64); + assert!(offset_of!(Resource, gpuVirtualAddress) == 88); + assert!(offset_of!(Resource, flags) == 96); + assert!(offset_of!(Resource, internalFlags) == 104); + + assert!(size_of::<Extent>() == 16); + assert!(size_of::<ResourceTag>() == 64); + assert!(offset_of!(ResourceTag, resource) == 32); + assert!(offset_of!(ResourceTag, r#type) == 40); + assert!(offset_of!(ResourceTag, lifecycle) == 44); + assert!(offset_of!(ResourceTag, extent) == 48); + + assert!(size_of::<ViewportHandle>() == 40); + assert!(size_of::<AdapterInfo>() == 56); + assert!(size_of::<Version>() == 12); + assert!(size_of::<FeatureRequirements>() == 184); + assert!(offset_of!(FeatureRequirements, osVersionDetected) == 56); + assert!(offset_of!(FeatureRequirements, vkNumComputeQueuesRequired) == 104); + assert!(offset_of!(FeatureRequirements, vkNumOpticalFlowQueuesRequired) == 176); + assert!(size_of::<FeatureVersion>() == 56); + + assert!(size_of::<float4x4>() == 64); + assert!(size_of::<Constants>() == 456); + assert!(offset_of!(Constants, jitterOffset) == 352); + assert!(offset_of!(Constants, mvecScale) == 360); + assert!(offset_of!(Constants, cameraPos) == 376); + assert!(offset_of!(Constants, cameraFwd) == 412); + assert!(offset_of!(Constants, cameraNear) == 424); + assert!(offset_of!(Constants, motionVectorsInvalidValue) == 440); + assert!(offset_of!(Constants, depthInverted) == 444); + assert!(offset_of!(Constants, motionVectorsJittered) == 450); + assert!(offset_of!(Constants, minRelativeLinearDepthObjectSeparation) == 452); + + assert!(size_of::<DLSSGOptions>() == 120); + assert!(offset_of!(DLSSGOptions, mode) == 32); + assert!(offset_of!(DLSSGOptions, uiBufferFormat) == 88); + assert!(offset_of!(DLSSGOptions, onErrorCallback) == 96); + assert!(offset_of!(DLSSGOptions, bReserved15) == 104); + assert!(offset_of!(DLSSGOptions, queueParallelismMode) == 108); + assert!(offset_of!(DLSSGOptions, enableUserInterfaceRecomposition) == 112); + assert!(offset_of!(DLSSGOptions, dynamicTargetFrameRate) == 116); + + assert!(size_of::<DLSSGState>() == 88); + assert!(offset_of!(DLSSGState, status) == 40); + assert!(offset_of!(DLSSGState, numFramesToGenerateMax) == 52); + assert!(offset_of!(DLSSGState, bIsVsyncSupportAvailable) == 57); + assert!(offset_of!(DLSSGState, inputsProcessingCompletionFence) == 64); + assert!(offset_of!(DLSSGState, bIsDynamicMFGSupported) == 80); + + assert!(size_of::<ReflexOptions>() == 48); + assert!(offset_of!(ReflexOptions, useMarkersToOptimize) == 40); + assert!(offset_of!(ReflexOptions, virtualKey) == 42); + assert!(offset_of!(ReflexOptions, idThread) == 44); + assert!(size_of::<ReflexReport>() == 152); + assert!(size_of::<ReflexReport2>() == 48); + assert!(size_of::<ReflexState>() == 12848); + assert!(offset_of!(ReflexState, frameReport) == 40); + assert!(offset_of!(ReflexState, flashIndicatorDriverControlled) == 9768); + assert!(offset_of!(ReflexState, frameReport2) == 9776); + + assert!(size_of::<PCLOptions>() == 40); + assert!(offset_of!(PCLOptions, idThread) == 36); + assert!(size_of::<PCLState>() == 40); + + assert!(size_of::<Boolean>() == 1 && size_of::<ResourceType>() == 1); + assert!(size_of::<SlResult>() == 4 && align_of::<SlResult>() == 4); + assert!(size_of::<Option<PFun_LogMessageCallback>>() == 8); +}; diff --git a/crates/victory-gpu/src/stretch.rs b/crates/victory-gpu/src/stretch.rs new file mode 100644 index 0000000..0c5da95 --- /dev/null +++ b/crates/victory-gpu/src/stretch.rs @@ -0,0 +1,292 @@ +//! The upscaler's output by a plain stretch of its colour input (from CuteBooty/victory-8gb over.rs), +//! for builds that otherwise run the title's own FidelityFX upscaler, whose translated passes are slow +//! on 32-lane hosts. Taken by `victory_hle::modules::ffx` in Series S. + +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; + +/// A bilinear, clamping sampler at `s0` for the stages `visibility` names. +fn bilinear(visibility: D3D12_SHADER_VISIBILITY) -> D3D12_STATIC_SAMPLER_DESC { + D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, + MaxLOD: f32::MAX, + ShaderRegister: 0, + RegisterSpace: 0, + ShaderVisibility: visibility, + ..Default::default() + } +} + +/// A root signature of `parameters` and one bilinear sampler, serialized by +/// the runtime and not taken from a shader: the system compiler under Wine +/// compiles a `[RootSignature]` attribute without writing the signature +/// into the shader, and `CreateRootSignature` then fails on it (#188). +fn root_signature( + device: &ID3D12Device, + parameters: &[D3D12_ROOT_PARAMETER], + sampler: D3D12_SHADER_VISIBILITY, + flags: D3D12_ROOT_SIGNATURE_FLAGS, +) -> windows::core::Result<ID3D12RootSignature> { + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let samplers = [bilinear(sampler)]; + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: parameters.len() as u32, + pParameters: parameters.as_ptr(), + NumStaticSamplers: 1, + pStaticSamplers: samplers.as_ptr(), + Flags: flags, + }; + let mut blob: Option<ID3DBlob> = None; + // SAFETY: the description points at live slices; the blob is the + // runtime's own, read while it lives. + unsafe { + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None)?; + let blob = blob.ok_or_else(windows::core::Error::empty)?; + let bytes = + std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize()); + device.CreateRootSignature(0, bytes) + } +} + +/// One descriptor range of one view at register 0, at `offset` in its table. +fn range(kind: D3D12_DESCRIPTOR_RANGE_TYPE, offset: u32) -> D3D12_DESCRIPTOR_RANGE { + D3D12_DESCRIPTOR_RANGE { + RangeType: kind, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: offset, + } +} + +/// A root parameter that is a table of `ranges`, for the stages `visibility` +/// names. +fn table(ranges: &[D3D12_DESCRIPTOR_RANGE], visibility: D3D12_SHADER_VISIBILITY) -> D3D12_ROOT_PARAMETER { + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { + NumDescriptorRanges: ranges.len() as u32, + pDescriptorRanges: ranges.as_ptr(), + }, + }, + ShaderVisibility: visibility, + } +} + +// --------------------------------------------------------------------------- +// The upscaler's output, by a plain stretch +// --------------------------------------------------------------------------- + +/// The title in its Series S mode renders below its output size and has the +/// console's upscaler (its `ffxDispatch`) write the output. That upscaler's +/// passes are compute pipelines in a container we do not translate, so the +/// output stayed black. This pass stands in for it: each output texel is the +/// bilinear sample of the rendered part of the colour input. +/// +/// shortcut: no temporal accumulation, sharpening or use of the depth and +/// motion inputs: an image, not the upscaler's quality. +const STRETCH: &str = r#" +cbuffer Sizes : register(b0) { float2 scale; float2 texel; }; +Texture2D<float4> source : register(t0); +RWTexture2D<float4> target : register(u0); +SamplerState bilinear : register(s0); +[numthreads(8, 8, 1)] +void stretch(uint3 id : SV_DispatchThreadID) { + // Groups are 8 by 8: the last ones reach past a size that is not a + // multiple of 8. + uint width, height; + target.GetDimensions(width, height); + if (id.x >= width || id.y >= height) return; + float2 at = (float2(id.xy) + 0.5) * texel * scale; + // The rendered size can be the top left of a larger texture: stay half a + // texel inside it, or the filter takes in what is beside it. + uint sw, sh; + source.GetDimensions(sw, sh); + at = min(at, scale - 0.5 / float2(sw, sh)); + target[id.xy] = source.SampleLevel(bilinear, at, 0); +} +"#; + +struct Stretch { + root: ID3D12RootSignature, + pipeline: ID3D12PipelineState, + views: ID3D12DescriptorHeap, + step: u32, + next: u32, +} + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Stretch {} + +static STRETCHER: Mutex<Option<Stretch>> = Mutex::new(None); + +/// Views of a stretch are kept this many stretches (two views each). +/// +/// shortcut: a fixed count. The title dispatches the upscaler once a frame +/// and a list runs within the frames the title keeps in flight; 64 frames +/// is far more than it keeps. +const STRETCH_RING: u32 = 64; + +fn make_stretch(device: &ID3D12Device) -> windows::core::Result<Stretch> { + use windows::core::s; + let cs = crate::host::compile(STRETCH, s!("stretch"), s!("cs_5_1"))?; + let views = [ + range(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0), + range(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1), + ]; + let sizes = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: 0, + Num32BitValues: 4, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let root = root_signature( + device, + &[sizes, table(&views, D3D12_SHADER_VISIBILITY_ALL)], + D3D12_SHADER_VISIBILITY_ALL, + D3D12_ROOT_SIGNATURE_FLAG_NONE, + )?; + // SAFETY: the description points at live data and never releases its + // pointer. + unsafe { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }; + let pipeline: ID3D12PipelineState = device.CreateComputePipelineState(&desc)?; + let views: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: STRETCH_RING * 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + })?; + Ok(Stretch { + root, + pipeline, + step: device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), + views, + next: 0, + }) + } +} + +/// A typeless colour format as the typed one shaders read and write. +fn typed(format: DXGI_FORMAT) -> DXGI_FORMAT { + DXGI_FORMAT(match format.0 { + 1 => 2, + 9 => 10, + 23 => 24, + 27 => 28, + f => f, + }) +} + +/// Records into `list` the stretch of the top-left `render` texels of +/// `source` (readable by compute shaders) over the whole of `target` (in +/// the unordered-access state). False if nothing was recorded. +/// +/// The pass sets the list's descriptor heap, compute root signature and +/// pipeline and puts none of them back: the caller replays the title's. +pub(crate) fn record_stretch( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + target: &ID3D12Resource, + source: &ID3D12Resource, + render: [u32; 2], +) -> bool { + // SAFETY: live resources. + let (to, from) = unsafe { (target.GetDesc(), source.GetDesc()) }; + if to.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 + || to.Width == 0 + || from.Width == 0 + { + return false; + } + let mut made = STRETCHER.lock().unwrap_or_else(|e| e.into_inner()); + if made.is_none() { + // Tried again at the next dispatch if it fails, as the pass over a + // present is: a failure need not last. + *made = match make_stretch(device) { + Ok(p) => { + tracing::info!("the upscaler's output is made by a plain stretch of its colour input"); + Some(p) + } + Err(e) => { + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| { + tracing::warn!(error = %e, "no pass to stretch the upscaler's input: its output stays as it is"); + }); + None + } + }; + } + let Some(p) = made.as_mut() else { return false }; + let slot = (p.next % STRETCH_RING) * 2; + p.next = p.next.wrapping_add(1); + let (width, height) = (to.Width as u32, to.Height); + let rendered = [ + if render[0] == 0 { from.Width as u32 } else { render[0].min(from.Width as u32) }, + if render[1] == 0 { from.Height } else { render[1].min(from.Height) }, + ]; + let sizes = [ + rendered[0] as f32 / from.Width as f32, + rendered[1] as f32 / from.Height as f32, + 1.0 / width as f32, + 1.0 / height as f32, + ]; + let read = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: typed(from.Format), + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: 1, + ..Default::default() + }, + }, + }; + let written = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: typed(to.Format), + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + // SAFETY: an open list; slots of our heap; live resources and objects + // (the pass's own live as long as the process). + unsafe { + let cpu = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: p.views.GetCPUDescriptorHandleForHeapStart().ptr + ((slot + i) * p.step) as usize, + }; + let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: p.views.GetGPUDescriptorHandleForHeapStart().ptr + u64::from(slot * p.step), + }; + device.CreateShaderResourceView(source, Some(&read), cpu(0)); + device.CreateUnorderedAccessView(target, None, Some(&written), cpu(1)); + list.SetDescriptorHeaps(&[Some(p.views.clone())]); + list.SetComputeRootSignature(&p.root); + list.SetPipelineState(&p.pipeline); + list.SetComputeRoot32BitConstants(0, 4, sizes.as_ptr().cast(), 0); + list.SetComputeRootDescriptorTable(1, gpu); + list.Dispatch(width.div_ceil(8), height.div_ceil(8), 1); + } + true +} + diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 337e7c3..9df7533 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -95,6 +95,11 @@ pub(crate) struct Staging { /// recorded again about a second later if the card has room by then /// ([`upload`]). waiting: std::sync::atomic::AtomicU64, + /// Recorded for a one-shot decoration bake (`BAKING`): submission-time + /// refresh must wait for title memory to stop remapping + /// (`title_memory_reading`) instead of taking `no_wait()` / + /// `refresh_unlocked()` or the 30-frame partial-read throttle. + exact: std::sync::atomic::AtomicBool, } /// What a texture's staging buffer holds: the hash of the memory detiled @@ -485,6 +490,10 @@ fn with_title<R>(memory: *const u8, size: usize, f: impl FnOnce(&[u8]) -> R) -> /// bytes. static STAGED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +pub(crate) fn live_staging_bytes() -> u64 { + STAGED[1].load(std::sync::atomic::Ordering::Relaxed) +} + impl Drop for Staging { fn drop(&mut self) { use std::sync::atomic::Ordering::Relaxed; @@ -533,7 +542,7 @@ pub(crate) fn let_go_idle() { if map.is_empty() { return; } - let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); + let idle_ms = crate::host::ram_idle_ms(crate::residency::headroom()); // A list that recorded an upload or a check holds the staging until it // is reset: one only the table holds is named by no list, recorded or // running. @@ -770,6 +779,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { return; }; use std::sync::atomic::Ordering::Relaxed; + let baking = BAKING.get(); + if baking { + staging.exact.store(true, Relaxed); + } let picking = PICKING.get(); if picking.is_none() { // A draw samples it through a table: kept and checked from here on. @@ -802,10 +815,31 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { } } } + // The video decoder cycles CPU-written linear plane buffers. Keep a + // dedicated per-list upload buffer through the list's GPU fence so + // concurrent frames never overwrite each other or stall on staging hashes. + if staging.movie_plane() { + let (at, len) = staging.memory(); + let footprint = staging.footprints[0].Footprint; + let pitch = footprint.RowPitch as usize; + let bytes = pitch * staging.rows[0] as usize; + let plane = staging.clone(); + let Some(source) = list.plane_upload(bytes as u64, (at, len), move |dst| { + fill_plane(&plane.layout, at, len, dst, bytes, pitch); + }) else { + once!("no upload buffer for a CPU-written movie plane"); + return; + }; + record_upload(list, resource, texture, &staging, &source, 0); + staging.uploaded.store(true, Relaxed); + return; + } // The host texture has the staging buffer's contents: only the check // at submission is left, and what it finds changed the next list that // samples the texture uploads (a frame late where every list of the - // frame was recorded before that check). + // frame was recorded before that check). During a one-shot bake we + // always record the copy so any change found at submission lands in + // VRAM before the bake draw executes. // LOCAL: not for a video's picture planes (`guard_view` false). Their // check at submission finds the frame the decoder wrote since, but the // copy came only with the next list that samples the plane: three @@ -814,7 +848,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { // ghosts and pictures from earlier (r_avm23, the user's recording). // With the copy recorded here, it takes what that check puts in the // staging buffer at this list's submission. - if staging.guard_view && staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) { + if !baking && staging.guard_view && staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexSkipped, 1); list.defer_texture(staging); @@ -829,77 +863,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { }; staging.expected.store(there, Relaxed); } - const COPY_DEST: u32 = 0x400; - // A texture cut from a block may lie where another did: what the card - // holds of that one is done with before the first upload into this one. - if crate::pool::on() && !staging.uploaded.load(Relaxed) { - let aliasing = D3D12_RESOURCE_BARRIER { - Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, - Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, - Anonymous: D3D12_RESOURCE_BARRIER_0 { - Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { - pResourceBefore: std::mem::ManuallyDrop::new(None), - // SAFETY: a borrowed pointer the barrier never releases. - pResourceAfter: unsafe { std::mem::transmute_copy(texture) }, - }), - }, - }; - // SAFETY: an open list and a live texture. - unsafe { list.list.ResourceBarrier(&[aliasing]) }; - } - crate::list::ensure_state(list, resource, COPY_DEST); - // The staging buffer lives as long as `staging`, which the deferred - // refresh below holds until the list is reset. - for (i, footprint) in staging.footprints.iter().enumerate() { - #[cfg(feature = "diagnostics")] - { - let f = footprint.Footprint; - // SAFETY: live resources. - let (gpu, d) = unsafe { (staging.buffer.GetGPUVirtualAddress(), texture.GetDesc()) }; - let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth); - list.note_read( - || { - format!( - "texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", - d.Width, - d.Height, - d.DepthOrArraySize, - d.Format.0, - d.MipLevels, - staging.footprints.len(), - staging.size, - staging.base + footprint.Offset, - f.Width, - f.Height, - f.Depth, - f.RowPitch - ) - }, - (gpu + staging.base + footprint.Offset, len), - ); - } - 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: staging.first - staging.level0 + i as u32, - }, - }; - let from = D3D12_TEXTURE_COPY_LOCATION { - // SAFETY: as above. - pResource: unsafe { std::mem::transmute_copy(&staging.buffer) }, - Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { - Offset: staging.base + footprint.Offset, - ..*footprint - }, - }, - }; - // SAFETY: an open list; both locations name live resources. - unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; - } + record_upload(list, resource, texture, &staging, &staging.buffer, staging.base); // When the list is submitted, its copy takes what the staging buffer // holds by then: noted before the check below, which sets `dirty` // again if it detiles (the next list then uploads once more). @@ -943,6 +907,115 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { }); } +fn record_upload( + list: &HostList, + resource: This, + texture: &ID3D12Resource, + staging: &Staging, + source: &ID3D12Resource, + base: u64, +) { + use std::sync::atomic::Ordering::Relaxed; + const COPY_DEST: u32 = 0x400; + // A texture cut from a block may lie where another did: what the card + // holds of that one is done with before the first upload into this one. + if crate::pool::on() && !staging.uploaded.load(Relaxed) { + let aliasing = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::ManuallyDrop::new(None), + // SAFETY: a borrowed pointer the barrier never releases. + pResourceAfter: unsafe { std::mem::transmute_copy(texture) }, + }), + }, + }; + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[aliasing]) }; + } + crate::list::ensure_state(list, resource, COPY_DEST); + // The staging/plane upload buffer lives until the list is reset. + for (i, footprint) in staging.footprints.iter().enumerate() { + #[cfg(feature = "diagnostics")] + { + let f = footprint.Footprint; + // SAFETY: live resources. + let (gpu, d) = unsafe { (source.GetGPUVirtualAddress(), texture.GetDesc()) }; + let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth); + list.note_read( + || { + format!( + "texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", + d.Width, + d.Height, + d.DepthOrArraySize, + d.Format.0, + d.MipLevels, + staging.footprints.len(), + staging.size, + base + footprint.Offset, + f.Width, + f.Height, + f.Depth, + f.RowPitch + ) + }, + (gpu + base + footprint.Offset, len), + ); + } + 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: staging.first - staging.level0 + i as u32, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(source) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: base + footprint.Offset, + ..*footprint + }, + }, + }; + // SAFETY: an open list; both locations name live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } +} + +fn fill_plane( + layout: &victory_formats::texture::Layout, + at: usize, + len: usize, + dst: usize, + bytes: usize, + pitch: usize, +) { + let _pin = crate::watch::title_memory_reading(); + // SAFETY: the list owns this full upload allocation until its GPU work completes. + let out = unsafe { std::slice::from_raw_parts_mut(dst as *mut u8, bytes) }; + let mip = &layout.mips[0]; + if mip.offset == 0 + && mip.pitch as usize * layout.desc.element_bytes as usize == pitch + && bytes <= len + && crate::host::read_into(at as *const _, out) + { + return; + } + with_read(len, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), at as *const u8, len, false); + if let Err(error) = layout.detile(read, 0, 0, out, pitch, bytes) { + out.fill(0); + once!("could not copy the linear plane into the list's upload buffer: {error:?}"); + } + }); +} + /// Levels on demand: the levels a list claimed for its zeros /// (`crate::tiles::Tiled::claim`), held by the list's submission-time /// step. A list that is reset without having been submitted gives the @@ -1191,6 +1264,20 @@ impl Staging { preparing[3].fetch_add(read as u64, Relaxed); } + fn movie_plane(&self) -> bool { + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8_UNORM; + let desc = &self.layout.desc; + !self.on_demand + && desc.dimension == victory_formats::texture::Dimension::Tex2d + && desc.swizzle.0 == 0 + && desc.depth == 1 + && desc.mips == 1 + && desc.samples == 1 + && self.footprints.len() == 1 + && self.footprints[0].Offset == 0 + && self.footprints[0].Footprint.Format == DXGI_FORMAT_R8_UNORM + } + /// Returns the bytes of title memory read. fn refresh_now(&self) -> usize { let whole = std::time::Instant::now(); @@ -1204,12 +1291,13 @@ impl Staging { let start = self.memory as usize; let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); let last = &mut *last; + let exact = self.exact.swap(false, std::sync::atomic::Ordering::Relaxed); let alone = self.once.load(std::sync::atomic::Ordering::Relaxed); - if alone && last.hash.is_some() { + if alone && !exact && last.hash.is_some() { return 0; } if !alone && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) { - if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { + if !exact && last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { return 0; } last.asked = now; @@ -1254,7 +1342,7 @@ impl Staging { last.hot_until = frame + HOT_FRAMES; } let hot = hot_textures() && frame < last.hot_until; - if unwritten && !turn && !hot { + if !exact && unwritten && !turn && !hot { return 0; } blind = unwritten; @@ -1273,7 +1361,7 @@ impl Staging { // stays mapped (see `crate::watch::title_memory_reading`; without // it a page went between the asking and the read in runs 71 and // 74). - let _mapped = if no_wait() { + let _mapped = if no_wait() && !exact { // Not waited for: while the runtime remaps title memory the // texture is read through the kernel instead, whole or not at // all (`no_wait`). @@ -1293,7 +1381,7 @@ impl Staging { // unmapped pages is slow, and nothing tells us when pages // arrive): a mip that streams in shows up to 30 frames late. let frame = crate::frame::current(); - if last.partial.is_some_and(|at| frame < at + 30) { + if !exact && last.partial.is_some_and(|at| frame < at + 30) { return 0; } last.partial = Some(frame); @@ -1857,6 +1945,13 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O let (piece, buffer, base, data) = match crate::pool::staging(host, total) { Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data), None => { + let speculative = PICKING.get().is_some() && !BAKING.get(); + if crate::residency::upload_refused() + || (speculative && !crate::residency::allow_staging_growth(false)) + { + crate::residency::note_staging_deferred(); + return None; + } let (buffer, data) = host.upload_buffer(total)?; crate::host::name(&buffer, || { format!( @@ -1899,6 +1994,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O detiled: std::sync::atomic::AtomicU32::new(0), judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2], waiting: std::sync::atomic::AtomicU64::new(0), + exact: std::sync::atomic::AtomicBool::new(BAKING.get()), }); map.insert(resource as usize, s.clone()); Some(s) diff --git a/crates/victory-gpu/src/texture/ahead.rs b/crates/victory-gpu/src/texture/ahead.rs index 4474435..2cfdde6 100644 --- a/crates/victory-gpu/src/texture/ahead.rs +++ b/crates/victory-gpu/src/texture/ahead.rs @@ -13,7 +13,7 @@ //! it as any texture. use std::collections::VecDeque; -use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed}; +use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering::Relaxed}; use std::sync::{Arc, Condvar, Mutex, OnceLock}; use windows::Win32::Graphics::Direct3D12::*; @@ -80,6 +80,7 @@ pub(crate) enum Taken { static QUEUE: (Mutex<VecDeque<Arc<Job>>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new()); /// Those on their way, by host copy ([`HostTexture::serial`]). static ON_THEIR_WAY: Mutex<Vec<(u64, Arc<Job>)>> = Mutex::new(Vec::new()); +static IN_FLIGHT: AtomicUsize = AtomicUsize::new(0); static LANDED: Condvar = Condvar::new(); static BYTES: AtomicU64 = AtomicU64::new(0); /// Since the start: uploads, bytes, microseconds from the asking until the @@ -103,7 +104,9 @@ fn claim(resource: This, first: u32, there: u64) -> Option<Taken> { 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 + let most = if crate::residency::limited_host_ram() { 32 << 20 } else { MOST }; + if !crate::residency::allow_staging_growth(false) + || BYTES.load(Relaxed) >= most || copy.flags() & 0x7 != 0 || copy.state.load(Relaxed) != 0 || copy.grown.load(Relaxed) @@ -132,7 +135,11 @@ fn claim(resource: This, first: u32, there: u64) -> Option<Taken> { } 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())); + { + let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()); + way.push((job.copy.serial, job.clone())); + IN_FLIGHT.store(way.len(), std::sync::atomic::Ordering::Release); + } Some(Taken::New(job)) } @@ -142,6 +149,25 @@ pub(crate) fn send(job: &Arc<Job>) { QUEUE.1.notify_one(); } +/// Waits until every upload currently on its way here has finished copying +/// and run its completion callbacks (queuing slot flips into `FLIPS`). +/// Returns how many jobs were waited for. +pub(crate) fn drain() -> usize { + if IN_FLIGHT.load(std::sync::atomic::Ordering::Acquire) == 0 { + return 0; + } + let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()); + let waiting = way.len(); + let started = std::time::Instant::now(); + while !way.is_empty() && started.elapsed().as_millis() < 2000 { + way = LANDED + .wait_timeout(way, std::time::Duration::from_millis(50)) + .unwrap_or_else(|e| e.into_inner()) + .0; + } + waiting +} + /// 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) { @@ -291,11 +317,6 @@ fn finish(jobs: Vec<Arc<Job>>) { 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; @@ -317,6 +338,14 @@ fn finish(jobs: Vec<Arc<Job>>) { f(); } } + // Remove from `ON_THEIR_WAY` only after `job.then` callbacks have queued + // their `FLIPS` entries so `drain()` observes every flip ready to apply. + { + 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)); + IN_FLIGHT.store(way.len(), std::sync::atomic::Ordering::Release); + LANDED.notify_all(); + } crate::descriptor::host::flip_now(); } @@ -414,4 +443,31 @@ mod tests { back.Unmap(0, None); } } + + #[test] + fn drain_waits_until_then_callbacks_have_run() { + use std::sync::atomic::AtomicBool; + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + let Some(_host) = crate::host::host() else { return }; + let desc = [3u32, 0, 0, 0, 128, 0, 128, 0x8_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = crate::resource::placed_bytes(&desc).unwrap() as usize; + // SAFETY: memory of our own that stays for the test. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>(); + // SAFETY: as above. + unsafe { std::ptr::write_bytes(at, 0x5a, whole) }; + 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; + } + let Some(Taken::New(job)) = claim(texture, 0, u64::MAX) else { panic!("not taken") }; + let ran = Arc::new(AtomicBool::new(false)); + let flag = ran.clone(); + job.then(move || flag.store(true, std::sync::atomic::Ordering::Release)); + send(&job); + assert!(drain() >= 1); + assert!(ran.load(std::sync::atomic::Ordering::Acquire), "job.then callback must run before drain() returns"); + assert_eq!(drain(), 0); + } } diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index 8da3346..0951144 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -517,7 +517,16 @@ fn pump(context: Context, voice: &mut Voice) { return; } while context.field(1, 31, 1) == 1 { - if voice.pcm.len() < SAMPLES_PER_BLOCK && !decode(context, voice) { + // A skipped frame or an input boundary can advance the decoder without + // producing samples. Publish only complete blocks, except the final + // padded tail. Limit empty steps so a broken looping voice cannot hold + // its lock or stall other voices for the whole decoding pass. + for _ in 0..8 { + if voice.pcm.len() >= SAMPLES_PER_BLOCK || !decode(context, voice) { + break; + } + } + if voice.pcm.is_empty() || (voice.pcm.len() < SAMPLES_PER_BLOCK && !voice.ended) { return; } // The write block is the title's too: taken modulo the ring before @@ -549,12 +558,21 @@ fn pump(context: Context, voice: &mut Voice) { /// Decodes the next frame of the current input into `voice.pcm`; false /// when there is nothing left to decode. fn decode(context: Context, voice: &mut Voice) -> bool { + let valid = context.field(0, 20, 2); if voice.ended { - return false; + // The title can refill either input while the context stays enabled. + // Flush the previous tail once and leave the ring idle until a valid + // buffer is published. The decoder resets its overlap when flushed. + if valid == 0 { + return false; + } + voice.ended = false; + if context.field(2, 26, 5) == INPUT_INVALID { + context.set_field(2, 26, 6, 0); + } } let channels = context.channels(); let mut current = context.field(4, 31, 1); - let valid = context.field(0, 20, 2); if valid & (1 << current) == 0 { if valid & (1 << (1 - current)) == 0 { // Out of input: the overlap tail, then nothing. diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index a44d599..14911cd 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -227,11 +227,20 @@ extern "system" fn create_queue( ) } -/// The title asks for 32 MiB and stops if this fails. +/// The title asks for 32 MiB and stops if this fails. Give PC worker threads +/// enough staging headroom (default 256 MiB) so multi-MB RPF chunks don't +/// starve the remaining cores. extern "system" fn set_staging_buffer_size(_: Factory, size: u32) -> HRESULT { - tracing::info!(size, "dstorage: staging buffer size"); + static FLOOR_MB: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + let floor = *FLOOR_MB.get_or_init(|| { + std::env::var("VICTORY_DSTORAGE_STAGING_MB") + .ok() + .and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(256) + }) << 20; + tracing::info!(size, floor, "dstorage: staging buffer size"); if let Some(scheduler) = scheduler() { - scheduler.lock().staging = u64::from(size); + scheduler.lock().staging = u64::from(size).max(floor); } S_OK } diff --git a/crates/victory-hle/src/modules/ffx.rs b/crates/victory-hle/src/modules/ffx.rs new file mode 100644 index 0000000..0611f4a --- /dev/null +++ b/crates/victory-hle/src/modules/ffx.rs @@ -0,0 +1,250 @@ +//! `amd_fidelityfx_loader_xbox.dll`: the upscale dispatch. +//! +//! The title's Series S mode renders below its output size and calls the +//! console's FidelityFX upscaler to make the output. The loader and the +//! upscaler are the title's own DLLs and run as they are, but the +//! upscaler's passes are compute pipelines in a container we do not +//! translate: its output stayed black. `ffxDispatch` alone is taken here: +//! an upscale dispatch becomes a plain stretch of the colour input +//! (`victory_gpu::list::upscale_stretch`); anything else, and an upscale we +//! could not stretch, goes to the title's DLL. +//! +//! The structures are the public FidelityFX API's (`ffx_api.h`, +//! `ffx_upscale.h`): a header of a type and a next pointer, and resources of +//! a pointer, a 32-byte description and a state. + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; + + +/// The DLL whose `ffxDispatch` is taken. +pub const LOADER: &str = "amd_fidelityfx_loader_xbox.dll"; + +static REAL: AtomicUsize = AtomicUsize::new(0); + +/// The title's own `ffxDispatch`, for what is not stretched here. +pub fn set_real_dispatch(address: usize) { + REAL.store(address, Ordering::Relaxed); +} + +#[repr(C)] +struct Header { + kind: u64, + next: *const Header, +} + +#[repr(C)] +struct Resource { + resource: *const c_void, + description: [u32; 8], + state: u32, +} + +#[repr(C)] +struct Upscale { + header: Header, + list: *const c_void, + colour: Resource, + depth: Resource, + motion: Resource, + exposure: Resource, + reactive: Resource, + composition: Resource, + output: Resource, + jitter: [f32; 2], + motion_scale: [f32; 2], + render: [u32; 2], + upscale: [u32; 2], + // The rest of `ffxDispatchDescUpscale` (`ffx_upscale.h`), read by the + // probe only. + enable_sharpening: u8, + sharpness: f32, + frame_time_delta: f32, + pre_exposure: f32, + reset: u8, + camera_near: f32, + camera_far: f32, + camera_fov: f32, + view_to_meters: f32, + flags: u32, +} + +/// `VICTORY_UPSCALE_PROBE=1`: logs what the title gives each upscale (the +/// inputs a temporal upscaler such as DLSS or FSR 2 needs), now and then. +fn probe() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_UPSCALE_PROBE").is_some_and(|v| v == "1")) +} + +const _: () = assert!(size_of::<Resource>() == 48); +const _: () = assert!(std::mem::offset_of!(Upscale, output) == 0x138); + +/// `FFX_API_RETURN_ERROR`: what a dispatch nothing could answer returns. +const ERROR: u32 = 1; + +/// `FFX_API_DISPATCH_DESC_TYPE_UPSCALE`. +const UPSCALE: u64 = 0x0001_0001; + +type Dispatch = extern "system" fn(*mut *mut c_void, *const Header) -> u32; + +extern "system" fn dispatch(context: *mut *mut c_void, desc: *const Header) -> u32 { + // SAFETY: the title passes a dispatch description, whose header says + // what follows it. + if let Some(header) = unsafe { desc.as_ref() } { + static SEEN: AtomicU32 = AtomicU32::new(0); + let first = SEEN.fetch_add(1, Ordering::Relaxed) < 4; + if header.kind == UPSCALE { + // SAFETY: an upscale description, by its type. + let d = unsafe { &*desc.cast::<Upscale>() }; + if first { + tracing::info!( + list = ?d.list, + colour = ?d.colour.resource, + colour_size = ?(d.colour.description[2], d.colour.description[3]), + output = ?d.output.resource, + output_size = ?(d.output.description[2], d.output.description[3]), + render = ?d.render, + upscale = ?d.upscale, + "upscale dispatch" + ); + } + #[cfg(windows)] + if probe() { + static N: AtomicU32 = AtomicU32::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + // the first 12 upscales, then one in 300 + if n < 12 || n.is_multiple_of(300) { + let inputs = victory_gpu::list::upscale_inputs(&[ + d.colour.resource, + d.depth.resource, + d.motion.resource, + d.exposure.resource, + d.reactive.resource, + d.composition.resource, + d.output.resource, + ]); + tracing::info!( + n, + colour = %inputs[0], + depth = %inputs[1], + motion = %inputs[2], + exposure = %inputs[3], + reactive = %inputs[4], + composition = %inputs[5], + output = %inputs[6], + jitter = ?d.jitter, + motion_scale = ?d.motion_scale, + render = ?d.render, + upscale = ?d.upscale, + sharpening = d.enable_sharpening, + sharpness = d.sharpness, + frame_time_delta = d.frame_time_delta, + pre_exposure = d.pre_exposure, + reset = d.reset, + near = d.camera_near, + far = d.camera_far, + fov = d.camera_fov, + meters = d.view_to_meters, + flags = format_args!("{:#x}", d.flags), + "upscale probe" + ); + } + } + #[cfg(windows)] + { + let up = victory_gpu::list::Upscale { + colour: d.colour.resource as u64, + depth: d.depth.resource as u64, + motion: d.motion.resource as u64, + exposure: d.exposure.resource as u64, + output: d.output.resource as u64, + render: d.render, + jitter: d.jitter, + motion_scale: d.motion_scale, + reset: d.reset != 0, + pre_exposure: d.pre_exposure, + near: d.camera_near, + far: d.camera_far, + frame_ms: d.frame_time_delta, + dlss: std::env::var_os("VICTORY_UPSCALE").is_some_and(|v| v == "dlss"), + }; + if victory_gpu::list::upscale(d.list, &up) { + return 0; + } + } + if first { + tracing::warn!("upscale dispatch not stretched: left to the title's upscaler"); + } + } else if first { + tracing::info!( + kind = format_args!("{:#x}", header.kind), + "another FidelityFX dispatch" + ); + } + } + match REAL.load(Ordering::Relaxed) { + // Neither stretched nor passed on: the output was not written, and + // the title is told so instead of presenting it as it is. + 0 => { + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| { + tracing::error!( + "a FidelityFX dispatch was not answered: no stretch was recorded and the title's own ffxDispatch was not found" + ); + }); + ERROR + } + // SAFETY: the title's own `ffxDispatch`, with its own arguments. + real => unsafe { std::mem::transmute::<usize, Dispatch>(real)(context, desc) }, + } +} + +/// What the title's import of `ffxDispatch` is bound to. The DLL is not an +/// HLE module: the title's own must load, for its other entry points and +/// for the dispatches passed on. +pub fn dispatch_address() -> usize { + dispatch as *const () as usize +} + +#[cfg(test)] +mod tests { + use super::*; + use std::mem::offset_of; + + /// The upscale description as the public API lays it out: what the + /// stretch reads sits where the title wrote it. + #[test] + fn the_upscale_description_is_laid_out_as_the_public_api() { + assert_eq!(size_of::<Header>(), 16); + assert_eq!(offset_of!(Upscale, list), 0x10); + assert_eq!(offset_of!(Upscale, colour), 0x18); + assert_eq!(offset_of!(Upscale, depth), 0x48); + assert_eq!(offset_of!(Upscale, motion), 0x78); + assert_eq!(offset_of!(Upscale, output), 0x138); + assert_eq!(offset_of!(Upscale, jitter), 0x168); + assert_eq!(offset_of!(Upscale, motion_scale), 0x170); + assert_eq!(offset_of!(Upscale, render), 0x178); + assert_eq!(offset_of!(Upscale, upscale), 0x180); + assert_eq!(offset_of!(Upscale, enable_sharpening), 0x188); + assert_eq!(offset_of!(Upscale, sharpness), 0x18c); + assert_eq!(offset_of!(Upscale, reset), 0x198); + assert_eq!(offset_of!(Upscale, camera_near), 0x19c); + assert_eq!(offset_of!(Upscale, flags), 0x1ac); + assert_eq!(offset_of!(Resource, description), 8); + assert_eq!(offset_of!(Resource, state), 40); + } + + /// A dispatch that is not an upscale, with no DLL of the title's to + /// pass it to, is an error and not a silent success. + #[test] + fn a_dispatch_nothing_answers_is_an_error() { + let before = REAL.swap(0, Ordering::Relaxed); + let other = Header { + kind: 0x0002_0001, + next: std::ptr::null(), + }; + assert_eq!(dispatch(std::ptr::null_mut(), &other), ERROR); + assert_eq!(dispatch(std::ptr::null_mut(), std::ptr::null()), ERROR); + REAL.store(before, Ordering::Relaxed); + } +} diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 424c0ed..5d78b80 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1259,7 +1259,6 @@ mod host { // pad's buttons, by the stand-in pad's table: with a real pad // connected the stand-in is not there, and a title that listens // to the pad (the title's start screen) saw nothing. - #[cfg(feature = "diagnostics")] if slot == 0 { for vk in scripted() { if let Some(&(_, button)) = super::FALLBACK_BUTTONS.iter().find(|(key, _)| *key == vk) { @@ -1271,10 +1270,11 @@ mod host { } fn keys(&mut self) -> Vec<KeyState> { - #[cfg(feature = "diagnostics")] let mut down = scripted(); - #[cfg(not(feature = "diagnostics"))] - let mut down = Vec::new(); + // LOCAL (11/26): the F1 settings menu takes the keyboard while shown. + if victory_gpu::SETTINGS_MENU_OPEN.load(std::sync::atomic::Ordering::Relaxed) { + return Vec::new(); + } if focused_window().is_some() { // Left/right modifier keys only, as devices report them; no // mouse buttons (below 0x08). @@ -1348,7 +1348,6 @@ mod host { /// time), with or without focus. A key is a /// letter, a digit, or `Enter`, `Esc`, `Tab`, `Back`, `Up`, `Down`, /// `Left`, `Right` (the stand-in pad's table maps them to buttons). - #[cfg(feature = "diagnostics")] fn scripted() -> Vec<u8> { static SCRIPT: LazyLock<(Instant, Vec<(Duration, Duration, u8)>)> = LazyLock::new(|| { let list = std::env::var("VICTORY_KEYS").unwrap_or_default(); diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs index 7f8a931..7efb196 100644 --- a/crates/victory-hle/src/modules/mod.rs +++ b/crates/victory-hle/src/modules/mod.rs @@ -17,6 +17,7 @@ pub mod dsp; #[cfg(windows)] pub mod dstorage; #[cfg(windows)] +pub mod ffx; pub mod files; pub mod gameinput; pub mod kernel; diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index 8d09700..f3582c9 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -1228,12 +1228,43 @@ fn translated_compute_matches_pc() { let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect(); root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true))); root_views.sort_unstable(); + let view_strides: Vec<u32> = views + .iter() + .map(|v| match *v { + View::RawUav(_) => 1, + View::HalfUav(_) => 8, + View::Buffer { stride, .. } => match stride { + Stride::Raw => 1, + Stride::Typed => 16, + Stride::Structured(s) => s, + Stride::Format(f, bytes) => { + let kind = match f.0 as u32 { + 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => { + super::VIEW_INTEGER + } + 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => { + super::VIEW_INTEGER | super::VIEW_SIGNED + } + _ => 0, + }; + bytes | kind + } + }, + _ => 0, + }) + .collect(); for (n, (slot, srv)) in root_views.into_iter().enumerate() { - assert_eq!(slot, 4 + u8::from(srv), "{name}: root view"); - let data = if srv { - root_srv.clone() + let data = if srv + && (slot == super::SLOT_STRIDES || slot == super::SLOT_TABLE_STRIDES) + { + view_strides.clone() } else { - root_cbv.clone() + assert_eq!(slot, 4 + u8::from(srv), "{name}: root view"); + if srv { + root_srv.clone() + } else { + root_cbv.clone() + } }; roots.push((1 + n as u32, Root::View { srv, data })); } diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 3fbc2b9..9fbf373 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -1006,6 +1006,12 @@ pub enum View<'a> { UintTextureUav(u32, u32), /// A typed RGBA16F buffer UAV of this many elements, zeroed. HalfUav(u32), + /// A typed buffer UAV pre-filled with `data` (`format`, bytes per element). + TypedUav { + data: &'a [u32], + format: DXGI_FORMAT, + elem_bytes: u32, + }, /// The same buffer viewed as R16G16B16A16_UINT: what a translated /// program that moves halves is shown ([`super::HostShader::half_views`]). HalfUintUav(u32), @@ -1290,6 +1296,46 @@ impl Host { )?; uavs.push((b, None, n, rb)); } + View::TypedUav { + data, + format, + elem_bytes, + } => { + let n = data.len() as u32; + let bytes = u64::from(n) * 4; + let elements = (bytes / u64::from(elem_bytes)) as u32; + let b = make( + D3D12_HEAP_TYPE_DEFAULT, + &buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + let up = upload(data)?; + list.CopyBufferRegion(&b, 0, &up, 0, bytes); + list.ResourceBarrier(&[transition( + &b, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + keep.push(up); + let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: format, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: elements, + Flags: D3D12_BUFFER_UAV_FLAG_NONE, + ..Default::default() + }, + }, + }; + dev.CreateUnorderedAccessView(&b, None, Some(&desc), at); + let rb = make( + D3D12_HEAP_TYPE_READBACK, + &buffer(bytes, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + uavs.push((b, None, n, rb)); + } View::TextureUav(w, h) => { let t = make( D3D12_HEAP_TYPE_DEFAULT, diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs index 66665ef..b32afa8 100644 --- a/crates/victory-shader/src/emit/intersect.rs +++ b/crates/victory-shader/src/emit/intersect.rs @@ -59,14 +59,6 @@ struct Ray { inverse: [V; 3], } -/// LOCAL (from our wt5): `VICTORY_BVH_MISS=1` (off by default): the node test -/// misses every node. While the structure builder is off the structures are -/// never built, and a walk of what lies in their memory is not the console's. -fn bvh_miss() -> bool { - static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_MISS").is_some_and(|v| v == "1")) -} - impl<'a> Lower<'a> { /// `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`. pub(super) fn bvh(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { @@ -199,22 +191,11 @@ impl<'a> Lower<'a> { .m .terminate(leaf_block, Term::CondBr(is_triangle, triangle_block, join)); self.cur = box_block; - // LOCAL (from our wt5): with `VICTORY_BVH_MISS=1` every node is missed - // without being read: a box returns no child and a triangle the - // triangle miss, so a walk ends at its first node. - let boxes = if bvh_miss() { - [self.s.m.i32(bvh::NONE); 4] - } else { - self.bvh_boxes(at, kind, &ray, sort) - }; + let boxes = self.bvh_boxes(at, kind, &ray, sort); let box_end = self.cur; self.s.m.terminate(box_end, Term::Br(join)); self.cur = triangle_block; - let triangle = if bvh_miss() { - bvh::MISS.map(|f| self.s.m.i32(f.to_bits())) - } else { - self.bvh_triangle(at, kind, &ray) - }; + let triangle = self.bvh_triangle(at, kind, &ray); let triangle_end = self.cur; self.s.m.terminate(triangle_end, Term::Br(join)); self.cur = join; diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 326f88f..e242e19 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -441,6 +441,7 @@ enum MaskData { /// What a value holding a lane mask read as a number stops with. pub(super) const LANE_MASK: Why = "a lane mask read as data"; +pub(super) const DIVERGENT_MASK_EXCHANGE: Why = "a lane mask exchanged where not every lane runs"; /// A mask with lanes outside EXEC where it is written, read as a number where the lanes that /// run that block are not all of the wave. pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data"; @@ -564,7 +565,7 @@ fn need(block: usize) { /// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`. /// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes /// run (no lane branch can have split the arriving lanes); loop-carried values never do. -fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> { +fn lane_uniform(p: &Program, st: &Structured, all: &[bool], ordered_lds: bool) -> HashSet<Value> { let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); let mut same: HashSet<Value> = HashSet::new(); for b in crate::ir::reverse_postorder(&p.blocks) { @@ -577,6 +578,9 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> { } for (i, inst) in block.insts.iter().enumerate() { let name = inst.name(); + if st.guards[b][i].is_some() { + continue; // lanes outside EXEC keep another value + } let ops: Vec<Operand> = match &inst.fields { Fields::Valu(v) if v.dpp.is_none() @@ -587,11 +591,18 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> { { v.src.clone() } + Fields::Ds { + addr: Some(Operand::Vector { reg, dwords: 1 }), + gds: false, + .. + } if ordered_lds && name == "ds_read_b32" => { + if inst.read(Reg::V(*reg)).is_some_and(|a| same.contains(&a)) { + same.extend(inst.writes.iter().map(|w| w.1)); + } + continue; + } _ => continue, }; - if st.guards[b][i].is_some() { - continue; // lanes outside EXEC keep another value - } let alike = ops.iter().all(|op| match *op { Operand::Vector { reg, .. } => { // every dword of the operand the instruction reads from that register on @@ -1193,6 +1204,13 @@ thread_local! { } pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { + // A scalar select uses the condition of the whole guest wave, even + // when the preceding mask operation has no scalar-dword consumers. + if matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_)) + && i.read(Reg::Scc).is_some_and(|s| st.scc_some.contains_key(&s)) + { + return true; + } let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); let ops: Vec<&Operand> = match &i.fields { // A mask operation (its result a mask) is no data use. @@ -1698,7 +1716,9 @@ impl<'a> Lower<'a> { local_ok: false, local_any: LOCAL_ANY.get(), uniform: match &exchange { - Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all), + Some((_, false, all)) if !LOCAL_WAVES.get() => { + lane_uniform(p, x.st, all, split_lds && super::group_sync() != 0) + } _ => HashSet::new(), }, own_bits: match &exchange { @@ -3549,7 +3569,7 @@ impl<'a> Lower<'a> { } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) { // (a group of 32 or fewer has no other half to exchange with) need(b.unwrap_or(0)); - return Err("a lane mask exchanged where not every lane runs"); + return Err(DIVERGENT_MASK_EXCHANGE); } xy = self.exchange_halves(at, xy.0); } @@ -4250,7 +4270,7 @@ impl<'a> Lower<'a> { } if !made.is_none_or(|b| self.all_lanes(b)) { need(made.unwrap_or(0)); - return Err("a lane mask exchanged where not every lane runs"); + return Err(DIVERGENT_MASK_EXCHANGE); } let some = self.s.m.cast(at, Cast::ZExt, some, i32t); let (lo, hi) = self.exchange_halves(at, some); @@ -6049,6 +6069,13 @@ impl<'a> Lower<'a> { fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> { let v = inst.read(Reg::Scc).ok_or("an unread SCC")?; + if self.x.st.scc_some.contains_key(&v) + && matches!(self.vals.get(&v), None | Some(Val::Missing(_))) + { + let x = self.scc_some(v)?; + self.vals.insert(v, Val::Bit(x)); + return Ok(x); + } match self.get(v) { Ok(Val::Bit(x)) => Ok(x), Ok(_) => Err("SCC without a value"), @@ -7526,7 +7553,7 @@ 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<Option<V>, Why> { - let word = self.slot_word(src)?; + let word = self.slot_word(src, false)?; Ok(word.map(|word| { let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS); let stride = self.s.m.bin(self.cur, Bin::And, word, bits); @@ -7549,18 +7576,17 @@ impl<'a> Lower<'a> { if !super::shader::constant_marks() { return Ok(None); } - let Some(word) = self.slot_word(src)? else { + let Some(word) = self.slot_word(src, false)? else { return Ok(None); }; - let mark = self.s.m.i32(super::shader::SLOT_STRIDE_CONSTANT); + let mark =self.s.m.i32(super::shader::SLOT_STRIDE_CONSTANT); Ok(Some(self.s.m.cmp(self.cur, pred::EQ, word, mark))) } /// 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). + /// and whether a signed one (`ResourceHeap` or `Table`). fn integer_view(&mut self, src: &Source) -> Result<Option<(V, V)>, Why> { - let Some(word) = self.slot_word(src)? else { + let Some(word) = self.slot_word(src, true)? else { return Ok(None); }; let c = self.cur; @@ -7574,19 +7600,22 @@ impl<'a> Lower<'a> { } /// 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<Option<V>, Why> { + /// format kind ([`super::shader::SLOT_STRIDES`] for `ResourceHeap`, + /// [`super::shader::SLOT_TABLE_STRIDES`] for `Table` when `allow_table`). + fn slot_word(&mut self, src: &Source, allow_table: bool) -> Result<Option<V>, Why> { let Source::Loaded { load, first } = src else { return Ok(None); }; - let heap = self + let srv_slot = match self .scalar .get(load) .and_then(|a| self.x.native.layout.get(a.param)) - .is_some_and(|p| p.root == RootType::ResourceHeap); - if !heap { - return Ok(None); - } + .map(|p| p.root) + { + Some(RootType::ResourceHeap) => super::shader::SLOT_STRIDES, + Some(RootType::Table) if allow_table => super::shader::SLOT_TABLE_STRIDES, + _ => return Ok(None), + }; let key = (self.cur, *load, *first); if let Some(&v) = self.strides.get(&key) { return Ok(Some(v)); @@ -7601,7 +7630,7 @@ impl<'a> Lower<'a> { self.s.m.tag(slot, Tag::Clamp); let two = self.s.m.i32(2); let byte = self.s.m.bin(c, Bin::Shl, slot, two); - let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES); + let h = self.s.root_srv_handle(srv_slot); let iu = self.s.m.undef(self.s.t.i32); let mask = self.s.m.i8(1); let align = self.s.m.i32(4); @@ -7769,6 +7798,15 @@ impl<'a> Lower<'a> { unreachable!() }; let name = inst.name(); + if let Some(&source) = self.x.res.restored_lanes.get(&(b, i)) { + // This lane was overwritten by a uniform scalar. The previous + // contents of other lanes can be unknown (a reduction scratch). + let word = match source { + crate::resource::Moved::Value(v) => self.i32_of(v)?, + crate::resource::Moved::Const(k) => self.s.m.i32(k), + }; + return self.write_i(inst, word, None); + } if self.x.res.waterfall.compares.contains(&(b, i)) { // The first lane's dwords of a waterfall loop are each lane's // own (see `resource::Waterfall`). @@ -11963,9 +12001,13 @@ impl<'a> Lower<'a> { // 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; and the handle stays a float one, - // whose bits the drivers pass. + // noise). Both `ResourceHeap` (`SLOT_STRIDES`) and `Table` + // (`SLOT_TABLE_STRIDES`, dynamic table snapshots included) + // populate the view-kind bits, while the handle stays a float + // one (`0x409`), whose raw bits RTX and WARP pass bit-exact + // without extra CFG blocks or touching non-d16 shaders. + // LOCAL (faces): not where the program moves halves as + // integers (`halves`): those views are shown as UINT already. let integer = if typed && !halves { self.integer_view(src)? } else { None }; let mut wide = Vec::new(); for k in 0..count { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 85a9e0f..8404cc9 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -122,7 +122,7 @@ pub use lower::{host_settings, set_host_max_wave, set_host_rdna}; 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_STRIDE_CONSTANT, 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, + SLOT_STRIDE_CONSTANT, SLOT_STRIDES_COUNT, SLOT_TABLE_STRIDES, 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, constant_marks, raw_views, set_raw_views, set_view_heap_limit, view_heap_limit, }; @@ -500,17 +500,45 @@ pub fn emit( }; // The program in two other forms: without its early-outs, and // without any branch that only skips code no lane is left for. - let form = |p: Option<ir::Program>| { - p.and_then(|p| { - let st = structure::structure(&p).ok()?; - let io = io::raise(&p, native).ok()?; - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?; - Some((p, st, io, res)) - }) + let form = |label: &str, p: Option<ir::Program>| { + let Some(p) = p else { + if why { + eprintln!("WAVE64-FORM {label}: ir returned None"); + } + return None; + }; + let st = match structure::structure(&p) { + Ok(st) => st, + Err(e) => { + if why { + eprintln!("WAVE64-FORM {label}: structure failed: {e}"); + } + return None; + } + }; + let io = match io::raise(&p, native) { + Ok(io) => io, + Err(e) => { + if why { + eprintln!("WAVE64-FORM {label}: io::raise failed: {e}"); + } + return None; + } + }; + let res = match resource::track(&p, &native.layout, native.stage, Some(&st)) { + Ok(res) => res, + Err(e) => { + if why { + eprintln!("WAVE64-FORM {label}: resource::track failed: {e}"); + } + return None; + } + }; + Some((p, st, io, res)) }; let forms = [ - ("without early-outs", form(ir::without_early_outs(p))), - ("without skips", form(ir::without_skips(p, false))), + ("without early-outs", form("without early-outs", ir::without_early_outs(p))), + ("without skips", form("without skips", ir::without_skips(p, false))), ]; for (name, f) in &forms { if let Some((p, st, io, res)) = f { @@ -526,7 +554,24 @@ pub fn emit( // lost the card in a submission of two programs that had just moved to it // (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which // has no barrier, stays on. - let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_some_and(|v| v == "1"); + let wide_option = std::env::var_os("VICTORY_WAVE_WIDE"); + // Both archived kernels use one logical wave per group and have + // validated wave32 PSOs on RTX. Explicit policy wins. + let scene_kernel = matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 64) + && matches!( + c.digest, + [0x58, 0x1d, 0xab, 0x2c, 0xd8, 0xbc, 0xf2, 0x2e, 0x5c, 0x96, 0x4b, 0x98, 0xe9, 0x03, 0x48, 0xd1] + | [0x24, 0x31, 0xbb, 0xe7, 0xdc, 0x15, 0x4a, 0xd7, 0x59, 0xd2, 0x0b, 0xc9, 0x54, 0x82, 0x9c, 0x1c] + ); + let wide_on = wide_option.as_ref().map_or(scene_kernel, |v| v == "1"); + // A single guest wave can iterate an active-lane loop until both host + // halves have finished. The precise latch and convergence conditions + // for the driver compute route are checked by widen(). + let driver_loop = wide_option.is_none() + && c.part(FourCC::DXIL).is_none() + && c.part(FourCC::ACCC).is_some() + && matches!(&original, Err(ShaderError::Unsupported { what, .. }) + if *what == lower::DIVERGENT_MASK_EXCHANGE); // exact first: each host wave on its own where that is exact (the idiom, every // form; no barriers), then the other exact forms; then approximate for exact in [true, false] { @@ -537,7 +582,7 @@ pub fn emit( // lane runs, where the two host waves can exchange. // (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.) let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0"); - let deep = if deep_on { form(ir::without_skips(p, true)) } else { None }; + let deep = if deep_on { form("without skips, scalars followed", ir::without_skips(p, true)) } else { None }; if let Some((p, st, io, res)) = &deep { let again = emit_program(c, native, p, st, io, res); report("without skips, scalars followed", &again); @@ -548,7 +593,7 @@ pub fn emit( // Still stopped where not every lane runs: the per-lane branches around // those places taken as the console takes them, by the whole wave at once // ([`widen`]), at two group barriers per such branch. - if wide_on { + if wide_on || driver_loop { let bases = [ deep.as_ref().map(|f| &f.0), forms[1].1.as_ref().map(|f| &f.0), @@ -556,7 +601,7 @@ pub fn emit( Some(p), ]; if let Some(base) = bases.into_iter().flatten().next() { - let again = widen(c, native, base, why); + let again = widen(c, native, base, why, driver_loop); report("wave-wide branches", &again); if done(&again) { return again.map(|(shader, _)| shader); @@ -618,7 +663,7 @@ pub fn emit( && what == lower::LANE_MASK && std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") => { - let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some()); + let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some(), false); match again { Ok(_) => again, Err(_) => emit_program(c, native, p, st, io, res), @@ -626,7 +671,17 @@ pub fn emit( } other => other, }; - let original = original.map(|(shader, _)| shader); + let supported = |(shader, wave): (HostShader, Option<u32>)| { + if wave == Some(64) && lower::host_max_wave() == 32 { + Err(ShaderError::Unsupported { + offset: 0, + what: "no wave32 lowering for this wave64 program", + }) + } else { + Ok(shader) + } + }; + let original = original.and_then(supported); // Retry unsupported programs only. Threading can separate an unknown // register value from its apparent use on a mutually exclusive path. if !matches!(original, Err(ShaderError::Unsupported { .. })) { @@ -640,7 +695,7 @@ pub fn emit( let st = structure::structure(&p)?; let io = io::raise(&p, native)?; let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader) + emit_program(c, native, &p, &st, &io, &res).and_then(supported) } /// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane @@ -655,6 +710,7 @@ fn widen( native: &NativeProgram, p: &ir::Program, why: bool, + active_loop_only: bool, ) -> Result<(HostShader, Option<u32>), ShaderError> { const NOT: ShaderError = ShaderError::Unsupported { offset: 0, @@ -687,7 +743,22 @@ fn widen( || matches!(&r, Ok((_, Some(64)))) && !needs.is_empty(); if !stuck { if why { - eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len()); + let order = ir::reverse_postorder(&p.blocks); + let mut rpo = vec![0usize; p.blocks.len()]; + for (i, &b) in order.iter().enumerate() { + rpo[b] = i; + } + let mut sorted: Vec<usize> = wide.iter().copied().collect(); + sorted.sort_unstable(); + let desc: Vec<String> = sorted + .iter() + .map(|&b| { + let back = matches!(p.blocks[b].exit, ir::Exit::Branch { taken, not_taken } if rpo[taken] <= rpo[b] || rpo[not_taken] <= rpo[b]); + let nm = p.blocks[b].insts.last().map_or("?", |i| i.name()); + format!("B{b}({nm}{})", if back { ",BACK" } else { "" }) + }) + .collect(); + eprintln!("WAVE64-WIDE {} branches taken wave-wide: [{}]", wide.len(), desc.join(", ")); } return r; } @@ -702,6 +773,30 @@ fn widen( } return r; } + if active_loop_only { + // Only a single backward branch on the SCC just set by + // s_andn2_wrexec_b64. This instruction restricts EXEC to the + // unfinished lanes. The guest repeats the loop if *either* + // half still has work, while individual vector writes retain + // their EXEC predicates. + let [latch] = more.as_slice() else { + return r; + }; + let block = &p.blocks[*latch]; + let [.., update, branch] = block.insts.as_slice() else { + return r; + }; + if !wide.is_empty() + || update.name() != "s_andn2_wrexec_b64" + || branch.name() != "s_cbranch_scc1" + || !matches!( + block.exit, + ir::Exit::Branch { taken, not_taken } if taken <= *latch && not_taken > *latch + ) + { + return r; + } + } wide.extend(more); } } diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 4a44a92..34f0e2c 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -24,6 +24,11 @@ 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 same table of strides and format kinds as [`SLOT_STRIDES`], bound for +/// shaders that only inspect views from descriptor tables (`RootType::Table`). +/// Kept distinct from [`SLOT_STRIDES`] so the host binds the table without +/// running the full bindless heap buffer sweep. +pub const SLOT_TABLE_STRIDES: u8 = 252; /// 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 diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index f3067d2..6622452 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -181,7 +181,6 @@ fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, - half_views: lowered.half_views, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -1919,7 +1918,6 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), - half_views: lowered.half_views, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); @@ -2060,76 +2058,48 @@ fn rdna_forms_give_what_the_spelled_out_ones_give() { } } -/// A program that moves a typed buffer's 16-bit channels -/// (`buffer_load_format_d16_xyzw` from the table's first view, -/// `buffer_store_format_d16_xyzw` to its second) names both places for the -/// host (`HostShader::half_views`) and moves every pattern as it is through -/// unsigned views: half floats, the not-a-number ones among them, and -/// plain 16-bit integers (the title keeps both in such buffers; the -/// network that moves its faces reads indices this way). A program that -/// moves no halves names nothing. -#[test] -fn halves_go_through_a_table_as_they_are_and_name_their_views() { - use super::host::Stride; - use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_UINT; - /// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`. - const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { - [ - 0x38 << 26 | op << 18 | 1 << 13, - 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, - ] - } - const LOAD_D16_XYZW: u32 = 0x83; - const STORE_D16_XYZW: u32 = 0x87; - const THREADS: u32 = 32; - // The table's second descriptor, 0x20 bytes on. - let mut second = s_load_dwordx4(12, 4); - second[1] |= 0x20; - let mut words = vec![s_mov_b32(5, 0x80)]; - words.extend_from_slice(&s_load_dwordx4(8, 4)); - words.extend_from_slice(&second); - // v[1:2] = first[thread] (four halves), second[thread] = v[1:2]. - words.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8)); - words.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12)); +/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`. +const fn mubuf_idxen(op: u8, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { + [ + 0x38 << 26 | (op as u32) << 18 | 1 << 13, + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, + ] +} + +/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], byte_offset` (soffset = null). +const fn s_load_dwordx4_off(dst: u8, base: u8, byte_offset: u32) -> [u32; 2] { + [ + 0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1), + (125 << 25) | (byte_offset & 0x1F_FFFF), + ] +} + +/// Builds a compute shader whose descriptors live in a `RootType::Table` at +/// `s4` (like `compute_graph_ops` and `ped_standard_head_cs`). +fn build_table_typed_cs(body: &[u32], used: Vec<UsedResource>) -> HostShader { + let mut words = Vec::new(); + words.push(s_mov_b32(5, 0x80)); // s5 = 0 + words.extend_from_slice(body); words.push(S_ENDPGM); - let view = |kind: ResourceType, table_offset_dwords: u32| UsedResource { - kind, - root: RootType::Table, - table_offset_dwords, - lower_bound: table_offset_dwords / 8, - stride: 4, - dwords: 4, - user_data: 4, - slot: 1, - }; + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let native = NativeProgram { stage: HwStage::Cs, wave64: false, vgprs: 8, - layout: vec![ - RootParam { - root: RootType::Constants, - table_offset_dwords: 0, - sgprs: 4, - base_register: 0, - user_data: 0, - slot: 0, - }, - RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 4, - slot: 1, - }, - ], - used: vec![view(ResourceType::Srv, 0), view(ResourceType::Uav, 8)], + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 0, + }], + used, io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, - threads: [THREADS, 1, 1], + rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 + threads: [4, 1, 1], }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + code, }; let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); let st = structure::structure(&p).expect("structure"); @@ -2148,7 +2118,6 @@ fn halves_go_through_a_table_as_they_are_and_name_their_views() { mesh_stride: 0, }) .expect("lower"); - assert_eq!(lowered.half_views, [(1, 0), (1, 8)]); let shader = HostShader { stage: HwStage::Cs, dxil: lowered.dxil, @@ -2159,362 +2128,252 @@ fn halves_go_through_a_table_as_they_are_and_name_their_views() { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, - half_views: lowered.half_views, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { - let mut dxil = shader.dxil.clone(); - v.validate(&mut dxil).expect("DXIL validation failed"); + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); } - // A raw store through the same table: no halves, nothing named. - assert!(build_valu_cs(&[]).half_views.is_empty()); - - // Four halves a thread: numbers, both zeros, subnormals, infinities, - // not-a-numbers of both signs, and integers past the largest number's - // pattern, as indices are. - const SPECIAL: [u16; 16] = [ - 0x0000, 0x0001, 0x03ff, 0x0400, 0x3c00, 0x7bff, 0x7c00, 0x7c01, 0x7e00, 0x7fff, 0x8000, - 0x8001, 0xbc00, 0xfc00, 0xfc01, 0xffff, - ]; - let halves: Vec<u16> = (0..4 * THREADS as usize) - .map(|i| match i { - 0..16 => SPECIAL[i], - _ => (i as u16).wrapping_mul(0x0203).wrapping_add(0x7b00), - }) - .collect(); - let data: Vec<u32> = halves - .chunks(2) - .map(|pair| u32::from(pair[0]) | u32::from(pair[1]) << 16) - .collect(); - let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); - let mut ran = 0; - for (label, warp) in [("hardware", false), ("warp", true)] { - let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); - continue; - }; - let (root, pso) = host - .compute_pipeline(&shader) - .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); - let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; - for u in &shader.user_data { - ud[u.index as usize] = match (u.root, u.slot) { - (RootType::Table, 1) => 0, - other => panic!("unexpected user data {other:?}"), - }; - } - let out = host - .dispatch( - &root, - &pso, - &Dispatch { - roots: vec![(0, Root::Constants(ud))], - views: &[ - View::Buffer { - data: &data, - stride: Stride::Format(DXGI_FORMAT_R16G16B16A16_UINT, 8), - }, - View::HalfUintUav(THREADS), - ], - samplers: &[], - groups: [1, 1, 1], - }, - ) - .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); - assert_eq!( - out[0], data, - "{label}: the halves stored are the halves loaded" - ); - ran += 1; - } - assert!(ran > 0, "no SM 6.6 device available"); + shader } -/// The places a program that moves halves names are the descriptors it -/// loads, not the start of the range their used-resource entry describes: -/// with one entry for a range from dword 0, a load at byte 0x20 names -/// dword 8 (a host view there in a 16-bit float format is the one shown -/// as its unsigned twin). A descriptor picked at run time (the load's -/// offset in an SGPR) names nothing and keeps the float path: which slot -/// it reads, and in which format, is known only then. +/// `compute_graph_ops` (facial lip-sync & wrapped submesh solver) binds +/// `R16G16B16A16_UINT` / `R16_UINT` UAVs via `RootType::Table` (which on NVIDIA +/// are snapshotted into dynamic descriptor slots) and reads/writes FP16 bit +/// patterns with `buffer_load_format_d16_xyzw` and `buffer_store_format_d16_xyzw`. +/// Verify bit-exact round-trips for UINT, SINT, and FLOAT views (including +/// non-zero table offsets matching dynamic descriptor snapshots) on hardware +/// GPU and WARP. #[test] -fn half_places_are_the_descriptors_the_program_loads() { - /// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`. - const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { - [ - 0x38 << 26 | op << 18 | 1 << 13, - 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, - ] - } - const LOAD_D16_XYZW: u32 = 0x83; - const STORE_D16_XYZW: u32 = 0x87; - let lowered = |words: &[u32]| { - let range = |kind: ResourceType, table_offset_dwords: u32| UsedResource { - kind, +fn typed_d16_table_uav_roundtrip_uint_sint_and_float() { + use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_SINT, + DXGI_FORMAT_R16G16B16A16_UINT, + }; + let _serial = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut body = Vec::new(); + // s[8:11] = table[0] (src typed UAV), s[12:15] = table[1] (dst typed UAV), + // s[16:19] = table[2] (raw UAV dump of loaded v[2:3]). + body.extend_from_slice(&s_load_dwordx4_off(8, 4, 0)); + body.extend_from_slice(&s_load_dwordx4_off(12, 4, 32)); + body.extend_from_slice(&s_load_dwordx4_off(16, 4, 64)); + // buffer_load_format_d16_xyzw v[2:3], v0, s[8:11], 0 idxen (op 0x83) + body.extend_from_slice(&mubuf_idxen(0x83, 2, 0, 8)); + // buffer_store_format_d16_xyzw v[2:3], v0, s[12:15], 0 idxen (op 0x87) + body.extend_from_slice(&mubuf_idxen(0x87, 2, 0, 12)); + // Also dump thread 0's loaded v[2:3] into raw UAV (table[2]) to verify the load itself. + // v4 = v0 << 3 (byte offset = thread * 8) + body.push(0x3408_0083); // v_lshlrev_b32 v4, 3, v0 + // buffer_store_dwordx2 v[2:3], v4, s[16:19], 0 offen (op 0x1D, offen bit 12) + body.extend_from_slice(&[ + 0x38 << 26 | 0x1D << 18 | 1 << 12, + 0x80 << 24 | (16u32 >> 2) << 16 | (2u32 << 8) | 4u32, + ]); + let used = (0..3u32) + .map(|k| UsedResource { + kind: ResourceType::Uav, root: RootType::Table, - table_offset_dwords, - lower_bound: table_offset_dwords / 8, + table_offset_dwords: k * 8, + lower_bound: k, stride: 4, dwords: 4, user_data: 4, - slot: 1, - }; - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 8, - layout: vec![ - RootParam { - root: RootType::Constants, - table_offset_dwords: 0, - sgprs: 4, - base_register: 0, - user_data: 0, - slot: 0, - }, - RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 4, - slot: 1, - }, - ], - // One entry for a range of views from dword 0, one at 16. - used: vec![range(ResourceType::Srv, 0), range(ResourceType::Uav, 16)], - io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, - threads: [32, 1, 1], - }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - 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)).expect("resource::track"); - let io = io::raise(&p, &native).expect("io::raise"); - lower::lower(&lower::Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: Vec::new(), - outputs: Vec::new(), - prims: Vec::new(), - mesh_stride: 0, + slot: 0, }) - .expect("lower") - }; - // `s_load_dwordx4 s[dst:dst+3], s[4:5], offset` (soffset null), or with - // the offset in `soffset` instead. - let at = |dst: u8, offset: u32| { - let mut w = s_load_dwordx4(dst, 4); - w[1] |= offset; - w - }; - let picked = |dst: u8, soffset: u8| { - let mut w = s_load_dwordx4(dst, 4); - w[1] = u32::from(soffset) << 25; - w - }; - let mut fixed = vec![s_mov_b32(5, 0x80)]; - fixed.extend_from_slice(&at(8, 0x20)); - fixed.extend_from_slice(&at(12, 0x40)); - fixed.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8)); - fixed.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12)); - fixed.push(S_ENDPGM); - assert_eq!(lowered(&fixed).half_views, [(1, 8), (1, 16)]); - // The load's offset in s20, from the first lane's thread index - // (`v_readfirstlane_b32 s20, v0`): picked at run time. The pick may land - // on the store's place too, so no place of that table is named: the d16 - // accesses there take the float path, as before half views. - let mut runtime = vec![s_mov_b32(5, 0x80), vop1(0x02, 20, vgpr(0))]; - runtime.extend_from_slice(&picked(8, 20)); - runtime.extend_from_slice(&at(12, 0x40)); - runtime.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8)); - runtime.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12)); - runtime.push(S_ENDPGM); - assert!(lowered(&runtime).half_views.is_empty()); -} - -/// A format load of whole dwords (`buffer_load_format_x`, not d16) whose -/// result the program only reads one half of as a half float -/// (`v_cvt_f32_f16`) is moving 16-bit integers: the head program reads the -/// face network's output so, from an `R16_UINT` view. It names its view for -/// the host and loads the integer: 0x3c00 comes through as 1.0. Used as a -/// whole float instead (`v_add_f32`), the load stays a float load and names -/// nothing; so does a load of halves beside a load of the same view read as -/// a whole float (a view of numbers the program also picks one half float -/// out of, as hundreds of the title's pixel programs do). -#[test] -fn a_format_load_read_as_halves_loads_the_integer() { - use super::host::Stride; - use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16_UINT; - /// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`. - const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { - [ - 0x38 << 26 | op << 18 | 1 << 13, - 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, - ] - } - const LOAD_FORMAT_X: u32 = 0x00; - const V_CVT_F32_F16: u16 = 0x0B; - const V_ADD_F32: u8 = 0x03; - let lowered = |body: &[u32]| { - let view = |kind: ResourceType, table_offset_dwords: u32, stride: u32| UsedResource { - kind, - root: RootType::Table, - table_offset_dwords, - lower_bound: table_offset_dwords / 8, - stride, - dwords: 4, - user_data: 4, - slot: 1, - }; - let mut second = s_load_dwordx4(12, 4); - second[1] |= 0x20; - let mut words = vec![s_mov_b32(5, 0x80)]; - words.extend_from_slice(&s_load_dwordx4(8, 4)); - words.extend_from_slice(&second); - // `body` leaves v2, stored raw. - words.extend_from_slice(body); - words.extend_from_slice(&buffer_store_dword(2, 12, 0)); - words.push(S_ENDPGM); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 8, - layout: vec![ - RootParam { - root: RootType::Constants, - table_offset_dwords: 0, - sgprs: 4, - base_register: 0, - user_data: 0, - slot: 0, - }, - RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 4, - slot: 1, - }, - ], - used: vec![view(ResourceType::Srv, 0, 4), view(ResourceType::Uav, 8, 0)], - io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, - threads: [1, 1, 1], - }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - 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)).expect("resource::track"); - let io = io::raise(&p, &native).expect("io::raise"); - let l = lower::lower(&lower::Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: Vec::new(), - outputs: Vec::new(), - prims: Vec::new(), - mesh_stride: 0, - }) - .expect("lower"); - HostShader { - stage: HwStage::Cs, - dxil: l.dxil, - user_data: l.user_data, - samplers: l.samplers, - static_samplers: Vec::new(), - root_cbvs: l.root_cbvs, - root_srvs: l.root_srvs, - root_uavs: l.root_uavs, - root_indexed_views: res.root_indexed_views, - half_views: l.half_views, - } - }; - // v1 = first[v0] (one channel). - let load = mubuf_idxen(LOAD_FORMAT_X, 1, 0, 8); - let half = vop1(V_CVT_F32_F16, 2, vgpr(1)); - let as_halves = lowered(&[&load[..], &[half]].concat()); - assert_eq!(as_halves.half_views, [(1, 0)]); - let as_float = lowered(&[&load[..], &[vop2(V_ADD_F32, 2, vgpr(1), 1)]].concat()); - assert!(as_float.half_views.is_empty()); - // v3 = first[v0] too, read as a whole float: v2 = half(v1) + v3. - let mut beside = load.to_vec(); - beside.extend_from_slice(&mubuf_idxen(LOAD_FORMAT_X, 3, 0, 8)); - beside.push(half); - beside.push(vop2(V_ADD_F32, 2, vgpr(3), 2)); - assert!(lowered(&beside).half_views.is_empty()); - // Behind a branch, as the head program has it: where the lanes meet - // again the loaded value goes on through a phi, and a later write of - // v1 under EXEC reads it only to keep it in the lanes it leaves alone. - const SAVE_EXEC: u32 = 0xBE90_037E; // s_mov_b32 s16, exec_lo - const ONLY_LANE_0: u32 = 0x7DA4_0080; // v_cmpx_eq_u32 exec_lo, 0, v0 - const SKIP_3: u32 = 0xBF88_0003; // s_cbranch_execz over the next 3 words - const RESTORE_EXEC: u32 = 0xBEFE_0310; // s_mov_b32 exec_lo, s16 - let zero = vop1(0x01, 2, 128); // v_mov_b32 v2, 0 - let rewrite = vop1(0x01, 1, 128); // v_mov_b32 v1, 0 - let branched = lowered( - &[ - &[zero, SAVE_EXEC, ONLY_LANE_0, SKIP_3][..], - &load, - &[ - half, - RESTORE_EXEC, - SAVE_EXEC, - ONLY_LANE_0, - rewrite, - RESTORE_EXEC, - ], - ] - .concat(), + .collect(); + let shader = build_table_typed_cs(&body, used); + assert!( + shader.root_srvs.contains(&super::SLOT_TABLE_STRIDES), + "table typed d16 shader should request SLOT_TABLE_STRIDES" ); - assert_eq!(branched.half_views, [(1, 0)]); - // A d16 load names its place where it is the only access there... - const LOAD_FORMAT_D16_X: u32 = 0x80; - let d16 = mubuf_idxen(LOAD_FORMAT_D16_X, 1, 0, 8); - let d16_alone = lowered(&[&d16[..], &[half]].concat()); - assert_eq!(d16_alone.half_views, [(1, 0)]); - // ...and not beside a whole float read through the same place, which - // would see the unsigned twin: v2 = half(d16 v1) + v3. - let mut d16_beside = d16.to_vec(); - d16_beside.extend_from_slice(&mubuf_idxen(LOAD_FORMAT_X, 3, 0, 8)); - d16_beside.push(half); - d16_beside.push(vop2(V_ADD_F32, 2, vgpr(3), 2)); - assert!(lowered(&d16_beside).half_views.is_empty()); - if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { - for shader in [&as_halves, &branched, &d16_alone] { - let mut dxil = shader.dxil.clone(); - v.validate(&mut dxil).expect("DXIL validation failed"); - } - } - // Element 0 of an R16_UINT buffer holds the half 1.0 (0x3c00). - let data = [0x0000_3c00u32, 0]; - let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); - let mut ran = 0; - for (label, warp) in [("hardware", false), ("warp", true)] { - let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); - continue; - }; - for (name, shader) in [("straight", &as_halves), ("branched", &branched)] { - let (root, pso) = host - .compute_pipeline(shader) - .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + assert!( + !shader.root_srvs.contains(&super::SLOT_STRIDES), + "table-only shader must not trigger the bindless SLOT_STRIDES sweep" + ); + + // 4 elements x 4 u16 channels = 8 u32 dwords. + // Includes FP16 subnormal (0x0001), -0.0 (0x8000), 1.0 (0x3C00), -1.0 (0xBC00), + // NaN (0x7E00), max u16 (0xFFFF), and arbitrary patterns. + let uint_bits: [u32; 8] = [ + 0x3C00_0001, 0x7E00_BC00, + 0xFFFF_8000, 0xABCD_1234, + 0x0002_0000, 0x7BFF_FBFF, + 0xDEAD_BEEF, 0xCAFE_BABE, + ]; + let sint_bits: [u32; 8] = [ + 0xFFFF_8000, 0x7FFF_0001, + 0xC000_0000, 0x8001_7FFE, + 0xFFFF_FFFF, 0x0000_0000, + 0xFEDC_BA98, 0x7654_3210, + ]; + // Normal finite FP16 values that round-trip cleanly through f32. + let float_bits: [u32; 8] = [ + 0x4000_3C00, 0x3800_BC00, // 1.0, 2.0, -1.0, 0.5 + 0xC200_3400, 0x4500_0000, // 0.25, -3.0, 0.0, 5.0 + 0x3E00_BE00, 0x4400_C400, // -1.5, 1.5, -4.0, 4.0 + 0x3C00_0000, 0x4200_C000, // 0.0, 1.0, -2.0, 3.0 + ]; + let zeros = [0u32; 8]; + + let cases = [ + ("R16G16B16A16_UINT @0", DXGI_FORMAT_R16G16B16A16_UINT, 8 | super::VIEW_INTEGER, &uint_bits, 0u32), + ("R16G16B16A16_UINT @3 (dynamic offset)", DXGI_FORMAT_R16G16B16A16_UINT, 8 | super::VIEW_INTEGER, &uint_bits, 3u32), + ("R16G16B16A16_SINT @0", DXGI_FORMAT_R16G16B16A16_SINT, 8 | super::VIEW_INTEGER | super::VIEW_SIGNED, &sint_bits, 0u32), + ("R16G16B16A16_FLOAT @0", DXGI_FORMAT_R16G16B16A16_FLOAT, 8, &float_bits, 0u32), + ]; + + for (backend, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { continue }; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{backend}: compute_pipeline failed: {e}")); + for &(label, format, stride_word, input, base_slot) in &cases { + let mut views = Vec::new(); + let mut strides = Vec::new(); + for _ in 0..base_slot { + views.push(View::RawUav(1)); + strides.push(0u32); + } + let uav_base = base_slot as usize; + views.push(View::TypedUav { data: input, format, elem_bytes: 8 }); + strides.push(stride_word); + views.push(View::TypedUav { data: &zeros, format, elem_bytes: 8 }); + strides.push(stride_word); + views.push(View::RawUav(8)); + strides.push(1); + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; for u in &shader.user_data { - ud[u.index as usize] = match (u.root, u.slot) { - (RootType::Table, 1) => 0, - other => panic!("unexpected user data {other:?}"), - }; + if u.root == RootType::Table && u.slot == 0 { + ud[u.index as usize] = base_slot * 32; + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(ud)), + (1, Root::View { srv: true, data: strides }), + ], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{backend} {label}: dispatch failed: {e}")); + assert_eq!( + out[uav_base + 2], + input, + "{backend} {label}: buffer_load_format_d16_xyzw mismatch" + ); + assert_eq!( + out[uav_base + 1], + input, + "{backend} {label}: buffer_store_format_d16_xyzw mismatch" + ); + } + } +} + +/// Non-`d16` typed loads (`buffer_load_format_x`) are used by +/// `CS_BlendshapeTranslationsHSSGraphOutputExtract` (reading `HSSGraphOut` +/// `R16_UINT`) and `CS_PedStandardSkinning_*` (reading bone indices). Verify +/// exact integer bits for `R16_UINT`, `R16_SINT`, and `R32_UINT`. +#[test] +fn typed_non_d16_table_load_preserves_integer_bits() { + use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT_R16_SINT, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R32_UINT, + }; + let _serial = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut body = Vec::new(); + // s[8:11] = table[0] (src typed SRV), s[12:15] = table[1] (raw UAV out) + body.extend_from_slice(&s_load_dwordx4_off(8, 4, 0)); + body.extend_from_slice(&s_load_dwordx4_off(12, 4, 32)); + // buffer_load_format_x v2, v0, s[8:11], 0 idxen (op 0x00) + body.extend_from_slice(&mubuf_idxen(0x00, 2, 0, 8)); + // v4 = v0 << 2 (byte offset = thread * 4) + body.push(0x3408_0082); // v_lshlrev_b32 v4, 2, v0 + // buffer_store_dword v2, v4, s[12:15], 0 offen (op 0x1C, offen bit 12) + body.extend_from_slice(&[ + 0x38 << 26 | 0x1C << 18 | 1 << 12, + 0x80 << 24 | (12u32 >> 2) << 16 | (2u32 << 8) | 4u32, + ]); + let used = vec![ + UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 4, + slot: 0, + }, + UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 8, + lower_bound: 1, + stride: 4, + dwords: 4, + user_data: 4, + slot: 0, + }, + ]; + let shader = build_table_typed_cs(&body, used); + // Non-d16 typed loads stay untouched (no SLOT_TABLE_STRIDES root SRV, no + // CFG branches) so non-d16 pixel/mesh/particle/skinning shaders keep + // identical DXIL and pipeline cache keys while still preserving raw bits. + assert!( + !shader.root_srvs.contains(&super::SLOT_TABLE_STRIDES), + "non-d16 typed load should not add SLOT_TABLE_STRIDES" + ); + + let r16_data = [0x3C00_0001u32, 0xFFFF_BC00u32]; + let r32_data = [0xDEAD_BEEFu32, 0x0000_0001, 0x8000_0000, 0x7FFF_FFFF]; + let cases: [(&str, _, u32, &[u32], [u32; 4]); 3] = [ + ( + "R16_UINT", + DXGI_FORMAT_R16_UINT, + 2, + &r16_data, + [0x0001, 0x3C00, 0xBC00, 0xFFFF], + ), + ( + "R16_SINT", + DXGI_FORMAT_R16_SINT, + 2, + &r16_data, + [0x0001, 0x3C00, 0xFFFF_BC00, 0xFFFF_FFFF], + ), + ( + "R32_UINT", + DXGI_FORMAT_R32_UINT, + 4, + &r32_data, + r32_data, + ), + ]; + + for (backend, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { continue }; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{backend}: compute_pipeline failed: {e}")); + for &(label, format, elem_bytes, input, want) in &cases { + let views = [ + View::Buffer { + data: input, + stride: super::host::Stride::Format(format, elem_bytes), + }, + View::RawUav(4), + ]; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if u.root == RootType::Table && u.slot == 0 { + ud[u.index as usize] = 0; + } } let out = host .dispatch( @@ -2522,25 +2381,13 @@ fn a_format_load_read_as_halves_loads_the_integer() { &pso, &Dispatch { roots: vec![(0, Root::Constants(ud))], - views: &[ - View::Buffer { - data: &data, - stride: Stride::Format(DXGI_FORMAT_R16_UINT, 2), - }, - View::RawUav(1), - ], + views: &views, samplers: &[], groups: [1, 1, 1], }, ) - .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); - assert_eq!( - out[0][0], - 1.0f32.to_bits(), - "{label}, {name}: the half read as an integer's bits" - ); + .unwrap_or_else(|e| panic!("{backend} {label}: dispatch failed: {e}")); + assert_eq!(out[0], want, "{backend} {label}: buffer_load_format_x mismatch"); } - ran += 1; } - assert!(ran > 0, "no SM 6.6 device available"); } diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 835c067..ddc03dd 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -138,6 +138,9 @@ pub struct RootIndexedView { #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Resources { + /// Scalar values saved to a constant VGPR lane and restored within one + /// block, even if that VGPR is also used in ordinary vector operations. + pub(crate) restored_lanes: std::collections::HashMap<Site, Moved>, /// Every scalar memory access by address (`s_load_*`, `s_store_*`), and /// every global memory access (`global_*`, the dynamic term per lane). pub scalar: Vec<(Site, Address)>, @@ -224,9 +227,12 @@ pub fn track( let mut offset_at = std::collections::BTreeMap::<usize, (Vec<usize>, Vec<Value>, Vec<Site>)>::new(); for (b, block) in p.blocks.iter().enumerate() { - t.at.set(Some(b)); for (i, inst) in block.insts.iter().enumerate() { let site = (b, i); + t.at.set(Some(site)); + if let Some(value) = t.restored(inst, Some(b)) { + out.restored_lanes.insert(site, value); + } let fail = |what| ShaderError::Unsupported { offset: inst.machine.offset, what, @@ -234,7 +240,7 @@ pub fn track( let mut first_lane = Vec::new(); let mut offset = Vec::new(); let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> { - let source = t.descriptor(inst, op, b).map_err(fail)?; + let source = t.descriptor(inst, op, site).map_err(fail)?; // A descriptor the code keeps per lane ([`Tracer::lane_copies`]) // is the same in every lane: its loop is lowered as it stands // and needs no proof. @@ -411,8 +417,8 @@ struct Tracer<'a> { meets: std::cell::RefCell<Meets>, /// Reverse-postorder index per block. rpo: Vec<usize>, - /// The block of the access being traced ([`Self::live`]). - at: std::cell::Cell<Option<usize>>, + /// The instruction site of the access being traced ([`Self::live`]). + at: std::cell::Cell<Option<Site>>, } /// What lanes are known to satisfy: each [`Bool`] where its flag is set, @@ -514,7 +520,7 @@ impl<'a> Tracer<'a> { } for inst in &block.insts { for (k, &(_, v)) in inst.writes.iter().enumerate() { - let new = match copy_source(inst, k).or_else(|| self.restored(inst)) { + let new = match copy_source(inst, k).or_else(|| self.restored(inst, None)) { Some(Moved::Const(c)) => Some(Term::Const(c)), Some(Moved::Value(s)) => o[s.0 as usize], None => Some(Term::Value(v)), @@ -1113,8 +1119,8 @@ impl<'a> Tracer<'a> { self.address(lo, hi, extra) } - /// The source of the descriptor operand `op` of `inst`, in block `at`. - fn descriptor(&self, inst: &Inst, op: &Operand, at: usize) -> Result<Source, &'static str> { + /// The source of the descriptor operand `op` of `inst`, at `at`. + fn descriptor(&self, inst: &Inst, op: &Operand, at: Site) -> Result<Source, &'static str> { let Operand::Scalar { code, dwords } = *op else { return Err("a descriptor not in SGPRs"); }; @@ -1129,8 +1135,14 @@ impl<'a> Tracer<'a> { { words = raw.to_vec(); } - // Only the lanes that reach the access read the descriptor. - let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true))); + // Only the lanes that reach and run the access read the descriptor. + let mut known = Vec::new(); + if let Some(l) = self.lanes { + known.push((l.reach[at.0], true)); + if let Some(guard) = l.guards[at.0][at.1] { + known.push((guard, true)); + } + } self.classify(&words, &mut Vec::new(), &mut known) } @@ -1282,7 +1294,10 @@ impl<'a> Tracer<'a> { let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else { return t; }; - let mut known = vec![(lanes.reach[at], true)]; + let mut known = vec![(lanes.reach[at.0], true)]; + if let Some(guard) = lanes.guards[at.0][at.1] { + known.push((guard, true)); + } for _ in 0..MAX_JOINS { let Term::Value(v) = t else { break }; let Some((block, i)) = self.phis[v.0 as usize] else { @@ -2292,41 +2307,64 @@ impl<'a> Tracer<'a> { } } -#[derive(Clone, Copy, PartialEq, Eq)] -enum Moved { +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Moved { Const(u32), Value(Value), } +fn plain_lane(v: &crate::gfx10::Valu) -> bool { + v.abs == 0 + && v.neg == 0 + && v.opsel == 0 + && !v.clamp + && v.omod == 0 + && v.sdwa.is_none() + && v.dpp.is_none() +} + impl Tracer<'_> { /// For `v_readlane_b32` of a constant lane: the SGPR spilled to that /// lane, found by following the VGPR's `v_writelane_b32` writes. - fn restored(&self, inst: &Inst) -> Option<Moved> { + fn restored(&self, inst: &Inst, block: Option<usize>) -> Option<Moved> { let Fields::Valu(v) = &inst.fields else { return None; }; - if inst.name() != "v_readlane_b32" { + if inst.name() != "v_readlane_b32" || !plain_lane(v) { return None; } let [Operand::Vector { reg, .. }, lane] = v.src[..] else { return None; }; - self.spilled(inst.read(Reg::V(reg))?, lane_of(lane)?, &mut Vec::new()) + let lane = lane_of(lane)?; + if lane >= if self.p.wave64 { 64 } else { 32 } { + return None; + } + self.spilled(inst.read(Reg::V(reg))?, lane, block, &mut Vec::new()) .ok() .flatten() } /// What lane `lane` of VGPR value `v` holds: `Ok(None)` for a phi in /// `seen` (already being resolved), `Err` if not a spilled SGPR. - fn spilled(&self, v: Value, lane: u32, seen: &mut Vec<Value>) -> Result<Option<Moved>, ()> { + fn spilled( + &self, + v: Value, + lane: u32, + block: Option<usize>, + seen: &mut Vec<Value>, + ) -> Result<Option<Moved>, ()> { if let Some((b, i)) = self.phis[v.0 as usize] { + if block.is_some() { + return Err(()); + } if seen.contains(&v) { return Ok(None); } seen.push(v); let mut found = None; for &a in &self.p.blocks[b].phis[i].args { - if let Some(m) = self.spilled(a, lane, seen)? { + if let Some(m) = self.spilled(a, lane, block, seen)? { if found.is_some_and(|f| f != m) { return Err(()); } @@ -2335,18 +2373,26 @@ impl Tracer<'_> { } return Ok(found); } - let inst = self.def(v).ok_or(())?; + let site = self.defs[v.0 as usize].ok_or(())?; + if block.is_some_and(|b| site.0 != b) { + return Err(()); + } + let inst = self.inst(site); let Fields::Valu(w) = &inst.fields else { return Err(()); }; let (Some(Operand::Vector { reg, .. }), [value, at]) = (w.dst, &w.src[..]) else { return Err(()); }; - if inst.name() != "v_writelane_b32" { + if inst.name() != "v_writelane_b32" || !plain_lane(w) { return Err(()); } - if lane_of(*at).ok_or(())? != lane { - return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, seen); + let written = lane_of(*at).ok_or(())?; + if written >= if self.p.wave64 { 64 } else { 32 } { + return Err(()); + } + if written != lane { + return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, block, seen); } match *value { Operand::Scalar { code, .. } if code != NULL => { @@ -4061,4 +4107,45 @@ pub(crate) mod tests { assert_eq!(r.waterfall.compares.len(), 2); assert_eq!(r.waterfall.reads.len(), 4); } + + #[test] + fn a_guarded_access_excludes_dead_lane_edges_at_a_join() { + // Lanes failing `v_cmp_gt_u32` clear EXEC and take `s_cbranch_execz` + // directly to the join block without initializing the immediate + // sampler `s[8:11]`. The join's `image_sample_lz` is guarded by EXEC, + // so only the arm where `s[8:11]` was built can execute it. + let code: Vec<u8> = [ + 0xBE84_0300u32, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x877E_6A7E, // s_and_b32 exec_lo, exec_lo, vcc_lo + 0xBF88_0004, // s_cbranch_execz -> join (skips 4 dwords) + 0xBE88_0380, // s_mov_b32 s8, 0 + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] + S_ENDPGM, + ] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let structured = lanes(&p).expect("structured form"); + assert!(structured.guards[2][0].is_some(), "join access must carry an EXEC guard"); + let r = track(&p, &[param(Table, 0, 1)], HwStage::Cs, Some(&structured)).unwrap(); + assert!( + r.descriptors + .iter() + .any(|d| d.role == Role::Sampler && d.source == Source::Constant(vec![0; 4])), + "guarded join should resolve the immediate sampler from the live arm: {:?}", + r.descriptors + ); + } } diff --git a/scripts/build-nvidia.ps1 b/scripts/build-nvidia.ps1 new file mode 100644 index 0000000..41e864a --- /dev/null +++ b/scripts/build-nvidia.ps1 @@ -0,0 +1,25 @@ +# Builds the layer the way scripts\play-nvidia.ps1 expects it (the diag profile with diagnostics: the F1 menu, +# the F3 panel and several NVIDIA settings are diagnostics switches). +# scripts\build-nvidia.ps1 with DLSS when nvidia-sdk\DLSS is there (Get-NVIDIA-DLSS.cmd fetches it), +# without it otherwise +# scripts\build-nvidia.ps1 -NoDlss without DLSS even then +# scripts\build-nvidia.ps1 -DlssSdk <your checkout of github.com/NVIDIA/DLSS> +# A build with DLSS links NVIDIA's loader library: it is for your own use, not for passing on. +param( + [string]$DlssSdk, + [switch]$NoDlss +) +$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +if (-not $DlssSdk) { $DlssSdk = Join-Path $root 'nvidia-sdk\DLSS' } +$features = 'diagnostics' +if (-not $NoDlss -and (Test-Path (Join-Path $DlssSdk 'lib\Windows_x86_64\x64\nvsdk_ngx_d.lib'))) { + $env:VICTORY_DLSS_SDK = (Resolve-Path $DlssSdk).Path + $features = 'diagnostics,dlss' + Write-Host "Building with DLSS (SDK: $env:VICTORY_DLSS_SDK)" +} else { + Write-Host 'Building without DLSS (Get-NVIDIA-DLSS.cmd fetches its files; without them the picture is stretched to the screen)' +} +Push-Location $root +try { cargo build --locked --profile diag -p victory --features $features } finally { Pop-Location } +if ($LASTEXITCODE -eq 0) { Set-Content -Path (Join-Path $root 'target\diag\built-with.txt') -Value $features -Encoding ascii } +if ($LASTEXITCODE -eq 0) { Write-Host "Built: $(Join-Path $root 'target\diag\victory.exe'). Next: scripts\play-nvidia.ps1 -Exe <your copy's executable>" } diff --git a/scripts/get-nvidia-sdks.ps1 b/scripts/get-nvidia-sdks.ps1 new file mode 100644 index 0000000..4c333f8 --- /dev/null +++ b/scripts/get-nvidia-sdks.ps1 @@ -0,0 +1,154 @@ +# Fetches the few NVIDIA files DLSS and DLSS frame generation need (about 70 MB) from NVIDIA's own GitHub +# into nvidia-sdk\ here (git-ignored). They are NVIDIA's, under NVIDIA's licences (saved beside them: read +# them); this repository does not and may not carry them, so each person gets them from NVIDIA directly. +# Get-NVIDIA-DLSS.cmd in the repository's folder runs this. +# scripts\get-nvidia-sdks.ps1 DLSS and frame generation +# scripts\get-nvidia-sdks.ps1 -NoStreamline DLSS only (about 60 MB) +# Then: scripts\build-nvidia.ps1 (scripts\play-nvidia.ps1 does it by itself at its next start). +param( + [string]$DlssTag = 'v310.9.16', + [string]$StreamlineTag = 'v2.14.16', + [switch]$NoStreamline +) +$ProgressPreference = 'SilentlyContinue' # Invoke-WebRequest's progress bar makes it many times slower +[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 +$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +$sdk = Join-Path $root 'nvidia-sdk' + +# One file from a URL, with curl's progress line where Windows has curl (it has since Windows 10 1803). +function Get-File([string]$Url, [string]$To) { + New-Item -ItemType Directory -Force (Split-Path $To) | Out-Null + $part = "$To.part" + if (Get-Command curl.exe -ErrorAction SilentlyContinue) { + & curl.exe --location --fail --silent --show-error --progress-bar --output $part $Url + if ($LASTEXITCODE -ne 0) { Remove-Item $part -ErrorAction SilentlyContinue; throw "could not get $Url" } + } else { + Invoke-WebRequest -Uri $Url -OutFile $part -UseBasicParsing -ErrorAction Stop + } + Move-Item $part $To -Force +} + +# Bytes first..last of a URL. +function Get-Range([string]$Url, [long]$First, [long]$Last) { + $q = [Net.HttpWebRequest]::Create($Url) + $q.UserAgent = 'get-nvidia-sdks' + $q.AddRange($First, $Last) + $r = $q.GetResponse() + try { + if ([int]$r.StatusCode -ne 206) { throw 'the server does not give parts of the file' } + $m = New-Object IO.MemoryStream + $r.GetResponseStream().CopyTo($m) + , $m.ToArray() + } finally { $r.Close() } +} + +# Takes the named files out of a zip on a server without downloading the whole zip: its directory is at +# its end, and each file in it can be asked for by its place. $Want: a regex on the paths in the zip. +# Each goes into $Into under the part of its path after the SDK's top folder. +function Get-FromZip([string]$Url, [string]$Want, [string]$Into) { + # Where the file really is (the download address redirects), and how long it is. + $h = [Net.HttpWebRequest]::Create($Url); $h.Method = 'HEAD'; $h.UserAgent = 'get-nvidia-sdks' + $r = $h.GetResponse(); $real = $r.ResponseUri.AbsoluteUri; $length = $r.ContentLength; $r.Close() + $tailLen = [Math]::Min($length, 2MB) + $tail = Get-Range $real ($length - $tailLen) ($length - 1) + $end = -1 + for ($i = $tail.Length - 22; $i -ge 0; $i--) { + if ($tail[$i] -eq 0x50 -and $tail[$i + 1] -eq 0x4b -and $tail[$i + 2] -eq 5 -and $tail[$i + 3] -eq 6) { $end = $i; break } + } + if ($end -lt 0) { throw 'no zip directory found' } + $dirSize = [BitConverter]::ToUInt32($tail, $end + 12) + $dirAt = [BitConverter]::ToUInt32($tail, $end + 16) + if ($dirAt -eq [uint32]::MaxValue) { throw 'a zip64 archive' } + $dir = if ($dirAt -ge $length - $tailLen) { + $from = [int]($dirAt - ($length - $tailLen)); , $tail[$from..($from + $dirSize - 1)] + } else { Get-Range $real $dirAt ($dirAt + $dirSize - 1) } + $got = 0 + $at = 0 + while ($at + 46 -le $dir.Length -and [BitConverter]::ToUInt32($dir, $at) -eq 0x02014b50) { + $method = [BitConverter]::ToUInt16($dir, $at + 10) + $packed = [BitConverter]::ToUInt32($dir, $at + 20) + $size = [BitConverter]::ToUInt32($dir, $at + 24) + $nameLen = [BitConverter]::ToUInt16($dir, $at + 28) + $extraLen = [BitConverter]::ToUInt16($dir, $at + 30) + $noteLen = [BitConverter]::ToUInt16($dir, $at + 32) + $headerAt = [BitConverter]::ToUInt32($dir, $at + 42) + $name = [Text.Encoding]::UTF8.GetString($dir, $at + 46, $nameLen) + $at += 46 + $nameLen + $extraLen + $noteLen + if ($name -notmatch $Want) { continue } + # The file's own header (its extra field may be longer than the directory's), then its bytes. + $piece = Get-Range $real $headerAt ($headerAt + 30 + $nameLen + 2048 + $packed - 1) + if ([BitConverter]::ToUInt32($piece, 0) -ne 0x04034b50) { throw "no file header for $name" } + $dataAt = 30 + [BitConverter]::ToUInt16($piece, 26) + [BitConverter]::ToUInt16($piece, 28) + if ($dataAt + $packed -gt $piece.Length) { throw "the header of $name is longer than expected" } + $bytes = if ($method -eq 0) { , $piece[$dataAt..($dataAt + $packed - 1)] } + elseif ($method -eq 8) { + $in = [IO.MemoryStream]::new($piece, $dataAt, [int]$packed) + $z = [IO.Compression.DeflateStream]::new($in, [IO.Compression.CompressionMode]::Decompress) + $out = [IO.MemoryStream]::new(); $z.CopyTo($out); $z.Close(); , $out.ToArray() + } else { throw "$name is packed in a way this script does not know ($method)" } + if ($bytes.Length -ne $size) { throw "$name came out $($bytes.Length) bytes long, not $size" } + $rel = ($name -replace '^.*?(?=(bin/x64/|license\.txt$))', '') -replace '/', '\' + $to = Join-Path $Into $rel + New-Item -ItemType Directory -Force (Split-Path $to) | Out-Null + [IO.File]::WriteAllBytes($to, $bytes) + Write-Host (" {0} {1:N1} MB" -f $rel, ($size / 1MB)) + $got++ + } + $got +} + +# DLSS: the library the build links (4 MB) and the DLL the game loads (56 MB), each at NVIDIA's release tag. +$dlss = Join-Path $sdk 'DLSS' +$raw = "https://raw.githubusercontent.com/NVIDIA/DLSS/$DlssTag" +$files = @('LICENSE.txt', 'lib/Windows_x86_64/x64/nvsdk_ngx_d.lib', 'lib/Windows_x86_64/rel/nvngx_dlss.dll') +Write-Host "NVIDIA DLSS $DlssTag from github.com/NVIDIA/DLSS (about 60 MB):" +foreach ($f in $files) { + $to = Join-Path $dlss ($f -replace '/', '\') + if (Test-Path $to) { Write-Host " $f is there already"; continue } + Write-Host " $f" + Get-File "$raw/$f" $to +} +Write-Host " NVIDIA's licence for these: $(Join-Path $dlss 'LICENSE.txt')" + +# Frame generation: Streamline's five DLLs (3 MB, taken out of NVIDIA's 263 MB release archive without +# downloading the rest) and the frame generation model (7 MB, from the DLSS repository). +if (-not $NoStreamline) { + $sl = Join-Path $sdk 'Streamline' + $bin = Join-Path $sl 'bin\x64' + Write-Host "NVIDIA Streamline $StreamlineTag from github.com/NVIDIA-RTX/Streamline (about 10 MB):" + if (Test-Path (Join-Path $bin 'sl.interposer.dll')) { + Write-Host ' the Streamline DLLs are there already' + } else { + $url = "https://github.com/NVIDIA-RTX/Streamline/releases/download/$StreamlineTag/streamline-sdk-$StreamlineTag.zip" + $want = '(^|/)bin/x64/(sl\.(interposer|common|dlss_g|reflex|pcl)\.dll|[^/]*license[^/]*\.txt)$|^([^/]+/)?license\.txt$' + $got = 0 + try { $got = Get-FromZip $url $want $sl } + catch { Write-Host " Taking the files out of the archive in place did not work ($($_.Exception.Message))." } + if (-not (Test-Path (Join-Path $bin 'sl.interposer.dll'))) { + # The whole archive then (263 MB). + Write-Host ' Getting the whole archive instead (263 MB) ...' + $zip = Join-Path $sdk "streamline-sdk-$StreamlineTag.zip" + Get-File $url $zip + $into = Join-Path $sdk 'streamline-unpacked' + Expand-Archive -Path $zip -DestinationPath $into -Force -ErrorAction Stop + $found = Get-ChildItem $into -Recurse -Filter 'sl.interposer.dll' | + Where-Object { $_.FullName -match '\\bin\\x64\\sl\.interposer\.dll$' -and $_.FullName -notmatch '\\development\\' } | + Select-Object -First 1 + if (-not $found) { throw 'The Streamline archive has no bin\x64\sl.interposer.dll.' } + $top = Split-Path (Split-Path (Split-Path $found.FullName)) + New-Item -ItemType Directory -Force $bin | Out-Null + Get-ChildItem (Join-Path $top 'bin\x64') -File | + Where-Object { $_.Name -match '^(sl\.(interposer|common|dlss_g|reflex|pcl)\.dll|.*license.*\.txt)$' } | + Copy-Item -Destination $bin -Force + Copy-Item (Join-Path $top 'license.txt') $sl -Force -ErrorAction SilentlyContinue + Remove-Item $into -Recurse -Force -ErrorAction SilentlyContinue + Remove-Item $zip -Force + } + } + $model = Join-Path $bin 'nvngx_dlssg.dll' + if (Test-Path $model) { Write-Host ' nvngx_dlssg.dll is there already' } + else { Write-Host ' nvngx_dlssg.dll'; Get-File "$raw/lib/Windows_x86_64/rel/nvngx_dlssg.dll" $model } + Write-Host " licences: $(Join-Path $sl 'license.txt') (Streamline) and NVIDIA's DLSS licence above (nvngx_dlssg.dll)" +} +Write-Host '' +Write-Host 'Done. The next start of scripts\play-nvidia.ps1 builds the layer with DLSS (about a minute) and uses it.' diff --git a/scripts/play-nvidia.ps1 b/scripts/play-nvidia.ps1 index 3918918..52eff56 100644 --- a/scripts/play-nvidia.ps1 +++ b/scripts/play-nvidia.ps1 @@ -1,17 +1,28 @@ -# Starts the title on an NVIDIA card with the Series S settings measured on an RTX 5070 (about 18-22 fps, no device loss). +# Starts the title on an NVIDIA card: Series S, the game's own 720p picture taken to 1080p by DLSS, the F1 +# settings menu in the game (measured on an RTX 5070: about 15-17 fps before generated frames). # scripts\play-nvidia.ps1 -Exe <path of your own copy's executable> +# DLSS and DLSS frame generation need a few NVIDIA files (about 70 MB) that this repository does not carry: +# run Get-NVIDIA-DLSS.cmd in the repository's folder once, and they are fetched from NVIDIA's GitHub into +# nvidia-sdk\. Without them the game runs with its picture stretched to the screen instead. +# The layer is built here if it is not built yet, and built again with DLSS once those files are there. +# In the game: F1 = settings (arrows pick and change, Enter saves; kept in victory-settings.txt next to this +# folder), F3 = the numbers panel. # -NoSmoothMotion run target\<build>\victory.exe itself. By default a copy named victory_sm.exe is started instead, # so a Smooth Motion profile set for that exe in the NVIDIA App applies every time. -# -SeriesX the Series X profile instead (slower: about 7 fps at half scale) -# -Quality fewer stretched/jumping bodies and less rainbow skin, at about 13 fps instead of about 20 -# -RayTracing keep the title's ray-tracing passes (off by default: see below) -# -Resolution the height the game renders at before the title's own upscaler: 2160, 1440, 1080, 720, 540 or 480. -# Series S outputs 1080p (so up to 1080 there), Series X 2160p. Default: half the output (540 on S, -# 1080 on X). The play-S-*.ps1 and play-X-*.ps1 scripts next to this one call it with each. +# -NoDlss no DLSS: the picture is stretched (fast, softer) +# -SeriesX the Series X profile instead (much slower; no DLSS there) +# -Quality fewer stretched/jumping bodies, slower (relay stage 1, no card steps) +# -RayTracing the title's real ray tracing (the structure builder runs). Shaders build for minutes the +# first time, and DLSS frame generation is left off with it (the two together do not work yet). +# -Resolution the older path: the game renders at this height (2160, 1440, 1080, 720, 540 or 480) and the +# title's own upscaler does the rest, without DLSS. The play-S-*.ps1 and play-X-*.ps1 scripts use it. # -Adapter on a PC with more than one card, the one to use: part of its name (-Adapter 5060) or its index -# (-Adapter '#1'). Default: Windows' default card (the one the main display is on). +# (-Adapter '#1'). Default: Windows' default card. # -Build target\diag (the default, the build all measurements are of) or target\release -# (the release build ignores the ray-tracing skip list: VICTORY_SKIP_PIPELINES is a diagnostics switch) +# -DlssDir the folder with nvngx_dlss.dll, if not nvidia-sdk\DLSS\lib\Windows_x86_64\rel +# -StreamlineDir the folder with sl.interposer.dll (frame generation), if not nvidia-sdk\Streamline\bin\x64 +# -Log the layer's log goes to a file in %LOCALAPPDATA%\VIctory\logs instead of this window +# -Capture F9 in the game saves that frame and the pictures it drew, in %LOCALAPPDATA%\VIctory\captures # -WindowsBarMB maximum MiB of title memory windows in CPU-mapped VRAM (by default 3072 on PCs with under # 24 GB of RAM, else 0; -WindowsBarMB 0 turns it off). # -More other settings: -More @{VICTORY_PANEL='1'} @@ -19,70 +30,90 @@ param( [Parameter(Mandatory)][string]$Exe, [switch]$NoSmoothMotion, + [switch]$NoDlss, [switch]$SeriesX, [switch]$Quality, [switch]$RayTracing, [ValidateSet('2160', '1440', '1080', '720', '540', '480')][string]$Resolution, [string]$Adapter, [ValidateSet('diag', 'release')][string]$Build = 'diag', + [string]$DlssDir, + [string]$StreamlineDir, + [switch]$Log, + [switch]$Capture, [hashtable]$More = @{}, [uint32]$WindowsBarMB ) +$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +if (-not (Test-Path $Exe)) { Write-Host "No $Exe."; return } +$Exe = (Resolve-Path $Exe).Path + +# NVIDIA's own files: where they are (Get-NVIDIA-DLSS.cmd puts them in nvidia-sdk\). Nothing is downloaded here. +if (-not $DlssDir) { $DlssDir = $env:VICTORY_DLSS_DIR } +if (-not $StreamlineDir) { $StreamlineDir = $env:VICTORY_STREAMLINE_DIR } +$sdkDlss = Join-Path $root 'nvidia-sdk\DLSS' +$sdkDlssLib = Join-Path $sdkDlss 'lib\Windows_x86_64\x64\nvsdk_ngx_d.lib' +$sdkStreamline = Join-Path $root 'nvidia-sdk\Streamline\bin\x64' +$wantDlss = -not $NoDlss -and -not $SeriesX -and -not $Resolution +if (-not $DlssDir -and (Test-Path (Join-Path $sdkDlss 'lib\Windows_x86_64\rel\nvngx_dlss.dll'))) { $DlssDir = Join-Path $sdkDlss 'lib\Windows_x86_64\rel' } +if (-not $StreamlineDir -and (Test-Path (Join-Path $sdkStreamline 'sl.interposer.dll'))) { $StreamlineDir = $sdkStreamline } +if ($wantDlss -and -not $DlssDir) { + Write-Host 'No DLSS files here: the picture is stretched to the screen instead. Get-NVIDIA-DLSS.cmd (in the' + Write-Host "repository's folder) fetches them from NVIDIA once, about 70 MB, with frame generation's." +} + +# The build: made here if there is none, and made again with DLSS once its SDK is there (the diag build only). +$victory = Join-Path $root "target\$Build\victory.exe" +$built = Join-Path $root "target\$Build\built-with.txt" +$hasDlss = (Test-Path $built) -and ((Get-Content $built -Raw) -match 'dlss') +$canDlss = $wantDlss -and (Test-Path $sdkDlssLib) +if ($Build -eq 'diag' -and (-not (Test-Path $victory) -or ($canDlss -and -not $hasDlss -and (Test-Path $built)))) { + if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) { Write-Host 'No build and no cargo: install Rust (README.md), then start this again.'; return } + Write-Host 'Building the layer (a few minutes the first time) ...' + & (Join-Path $PSScriptRoot 'build-nvidia.ps1') + $hasDlss = (Test-Path $built) -and ((Get-Content $built -Raw) -match 'dlss') +} +if (-not (Test-Path $victory)) { Write-Host "No $victory. Build it first (scripts\build-nvidia.ps1)."; return } +# A build nobody noted the making of (cargo by hand) is taken at its word: with DLSS if the files are there. +$dlss = $wantDlss -and $DlssDir -and ($hasDlss -or -not (Test-Path $built)) + $settings = @{ - # This fork's play set (scripts\play.ps1, not -Safe): the speed set. - VICTORY_TEXTURE_NO_WAIT = '1'; VICTORY_RELAY = '2'; VICTORY_CARD_STEPS = '2' + # The play set. Textures are waited for: one loaded once at the start could stay empty for the run otherwise. + VICTORY_TEXTURE_NO_WAIT = '0'; VICTORY_RELAY = '2'; VICTORY_CARD_STEPS = '2' VICTORY_WIDE_BACK = '1'; VICTORY_CARD_REHASH_RUNS = '1' VICTORY_JOIN_COPIES = '1'; VICTORY_INDIRECT_WINDOW = '1'; VICTORY_RELAY_COPY = '1' + # Copy-backs caught half-written are fetched again (torn.rs). + VICTORY_FETCH_CHECK = '1' VICTORY_INDIRECT_BATCH = '2'; VICTORY_MAP_THREADS = '1'; VICTORY_TITLE_PRIORITIES = '0'; VICTORY_CARD_AWAKE = '1' - VICTORY_SHOW_AFTER = '1'; VICTORY_AMBIENT = '0.8'; VICTORY_D3D12_DRED = 'light'; VICTORY_SKIP_PIPELINES = 'none' + # The renderer's light stand-in is off (its coarse estimate made indoor light blotchy). + VICTORY_SHOW_AFTER = '1'; VICTORY_AMBIENT = '0'; VICTORY_D3D12_DRED = 'light' VICTORY_THIN = '1'; VICTORY_JOIN_PARTS = '8'; VICTORY_UPLOAD_AHEAD = '1' - # Cheap picture fixes, on in both sets: - # - Overbright views: without rays the light probes keep the sky's light indoors. The fog is bounded by 1.5 times - # the light around, and what the title left by 2 times the estimate (was 4; ambient.rs). - VICTORY_AMBIENT_AIR = '1.5'; VICTORY_AMBIENT_MOST = '2' - # - Black blobs: a NaN a shader writes is made 0 before blur and the temporal upscaler spread it (emit/lower.rs). - VICTORY_NAN_SCRUB = '1' - # Wait for new shaders rather than skip their draws (a hitch the first time a place is seen). Each pipeline is - # waited for at most once (VICTORY_PIPELINE_WAIT_ONCE, on by default): one that takes longer no longer stops the - # picture in every frame it is in view (pipeline/make.rs). + # Fog bounded by 1.5 times the light around; a NaN a shader writes is made 0 before blur and the upscaler spread it. + VICTORY_AMBIENT_AIR = '1.5'; VICTORY_NAN_SCRUB = '1' + # Wait for new shaders rather than skip their draws (each pipeline is waited for at most once). The F1 menu's + # SHADER WAIT MS changes it: 0 never waits, things then show up as their shaders are done. VICTORY_PIPELINE_WAIT_MS = '10000' # NVIDIA caps the shader-visible view heap at 1,000,000: without more dynamic slots thousands of draws a frame # are dropped (descriptor/host.rs dynamic_slots). VICTORY_DYNAMIC_SLOTS = '524288' - # Half render scale with the title's own upscaler (Series S needs it with a scale below 1; victory-loader hooks.rs). - VICTORY_RENDER_SCALE = '0.5'; VICTORY_OWN_UPSCALER = '1' - # Ray walks end at the root while the structure builder is off (emit/intersect.rs). - VICTORY_BVH_MISS = '1' - # Memory compares on the card instead of the CPU: 11 -> about 22 fps on Series S. + # Memory compares on the card instead of the CPU. VICTORY_CARD_BUFFERS_MIN_MB = '1'; VICTORY_CARD_BUFFERS_MB = '1536' - # Series S presents the interface as a second plane: laid over the game (compose.rs), else black before gameplay. - VICTORY_COMPOSE = '1' } -# Ray tracing mostly off. The structure builder cannot run on NVIDIA (its 64-lane programs are refused; upstream -# Marvisak/VIctory pull request 2311), so every ray misses, and the passes that turn misses into light made rooms go -# white depending on the view angle. rt_off_hashes.txt lists the 1,000 CS_RaytracingResolve and 34 traced-shadow -# shaders, which are skipped. The screen-probe and visibility traces keep running: skipping those too left their -# outputs as garbage (rainbow glitter everywhere). -$rtList = Join-Path $PSScriptRoot 'rt_off_hashes.txt' -if (-not $RayTracing -and (Test-Path $rtList)) { - $settings.VICTORY_SKIP_PIPELINES = (Get-Content $rtList -Raw).Trim() -} -if ($Quality) { - # Stretched/jumping bodies: relay stage 1 and no card steps (avatarmanz/VIctory-7900XTX issue 13, - # fxceless/victory-fork issue 89). Rainbow skin: texture refreshes wait for the runtime's remapping. - # Costs about 7 fps (the submitting thread waits about 30 ms a frame for the card). - $settings.VICTORY_RELAY = '1'; $settings.VICTORY_CARD_STEPS = '0'; $settings.VICTORY_TEXTURE_NO_WAIT = '0' -} -# The render scale is the rendered height over the output height (Series S 1080, Series X 2160). -$outHeight = if ($SeriesX) { 2160 } else { 1080 } -$console = if ($SeriesX) { 'X' } else { 'S' } +$console = if ($SeriesX) { 'series-x' } else { 'series-s' } if ($Resolution) { - if ([int]$Resolution -gt $outHeight) { - Write-Host "Series $console outputs ${outHeight}p: ${Resolution}p is above it." - return - } + # The older path: a render scale and the title's own upscaler (rendered height over output height). + $outHeight = if ($SeriesX) { 2160 } else { 1080 } + if ([int]$Resolution -gt $outHeight) { Write-Host "That console outputs ${outHeight}p: ${Resolution}p is above it."; return } $settings.VICTORY_RENDER_SCALE = ([int]$Resolution / $outHeight).ToString('0.####', [Globalization.CultureInfo]::InvariantCulture) + $settings.VICTORY_OWN_UPSCALER = '1' +} elseif ($dlss) { + $settings.VICTORY_UPSCALE = 'dlss'; $settings.VICTORY_DLSS_DIR = $DlssDir +} elseif (-not $SeriesX) { + $settings.VICTORY_UPSCALE = 'stretch' } +if ($StreamlineDir) { $settings.VICTORY_STREAMLINE_DIR = $StreamlineDir } +if ($Quality) { $settings.VICTORY_RELAY = '1'; $settings.VICTORY_CARD_STEPS = '0' } +if ($RayTracing) { $settings.VICTORY_BVH_BUILDER = '1' } if ($Adapter) { $settings.VICTORY_ADAPTER = $Adapter } if ($PSBoundParameters.ContainsKey('WindowsBarMB')) { $settings.VICTORY_WINDOWS_BAR_MB = $WindowsBarMB.ToString([Globalization.CultureInfo]::InvariantCulture) @@ -96,27 +127,99 @@ if ($PSBoundParameters.ContainsKey('WindowsBarMB')) { Write-Host "$([math]::Round($ram / 1GB)) GB of RAM: title memory windows in the card's memory the CPU maps, up to 3 GB (-WindowsBarMB 0 turns this off)" } } -foreach ($k in $More.Keys) { $settings[$k] = $More[$k] } -$scale = [double]::Parse($settings.VICTORY_RENDER_SCALE, [Globalization.CultureInfo]::InvariantCulture) -Write-Host "Series $console, rendering at $([int]($outHeight * $scale))p (render scale $($settings.VICTORY_RENDER_SCALE))" -$victory = Join-Path $PSScriptRoot "..\target\$Build\victory.exe" -if (-not (Test-Path $victory)) { Write-Host "No $victory. Build it first (README.md)."; return } -if (-not (Test-Path $Exe)) { Write-Host "No $Exe."; return } -if (-not $NoSmoothMotion) { +# What the F1 menu saved (victory-settings.txt, git-ignored), over the settings above. An empty value unsets one. +$menuFile = Join-Path $root 'victory-settings.txt' +$smooth = -not $NoSmoothMotion +if (Test-Path $menuFile) { + foreach ($line in Get-Content $menuFile) { + if ($line -notmatch '^\s*(VICTORY_[A-Z0-9_]+)\s*=(.*)$') { continue } + $k = $Matches[1]; $v = $Matches[2].Trim() + if ($k -eq 'VICTORY_MENU_SMOOTH_MOTION') { $smooth = $v -ne '0'; continue } + if ($k -eq 'VICTORY_MENU_CONSOLE') { if ($v) { $console = $v }; continue } + if ($v) { $settings[$k] = $v } else { $settings.Remove($k) } + } +} +foreach ($k in $More.Keys) { $settings[$k] = $More[$k] } +# DLSS only where it can be: a menu choice of it without the files or the build falls back to the stretch. +if ($settings.VICTORY_UPSCALE -eq 'dlss' -and -not $dlss) { $settings.VICTORY_UPSCALE = 'stretch' } +# DLSS frame generation and real ray tracing do not work together yet (0.1 frames a second): with ray tracing +# on, frame generation is left off and Smooth Motion can do the extra frames. +if ($settings.VICTORY_BVH_BUILDER -eq '1' -and $settings.VICTORY_FRAME_GEN -and $settings.VICTORY_FG_WITH_RT -ne '1') { + Write-Host 'Ray tracing is on: DLSS frame generation is left off (the two together do not work yet).' + $settings.Remove('VICTORY_FRAME_GEN') +} +if ($settings.VICTORY_FRAME_GEN -and -not $StreamlineDir) { + Write-Host 'Frame generation needs the Streamline files (Get-NVIDIA-DLSS.cmd): left off.' + $settings.Remove('VICTORY_FRAME_GEN') +} +# Smooth Motion is a second frame generator: off while DLSS frame generation is on. +if ($settings.VICTORY_FRAME_GEN -and $settings.VICTORY_FRAME_GEN -ne '1') { $smooth = $false } +# For the menu: what it shows as the current values, where it saves, and how it starts the game again. +$settings.VICTORY_MENU_SMOOTH_MOTION = if ($smooth) { '1' } else { '0' } +$settings.VICTORY_MENU_CONSOLE = $console +$settings.VICTORY_MENU_FILE = $menuFile +$settings.VICTORY_MENU_PLAY = $MyInvocation.MyCommand.Path +$again = @("-Exe '$($Exe -replace "'", "''")'", "-Build $Build") +foreach ($s in 'NoSmoothMotion', 'NoDlss', 'SeriesX', 'Quality', 'RayTracing', 'Log', 'Capture') { + if ($PSBoundParameters[$s]) { $again += "-$s" } +} +foreach ($s in 'Resolution', 'Adapter', 'DlssDir', 'StreamlineDir') { + if ($PSBoundParameters[$s]) { $again += "-$s '$($PSBoundParameters[$s] -replace "'", "''")'" } +} +if ($PSBoundParameters.ContainsKey('WindowsBarMB')) { $again += "-WindowsBarMB $WindowsBarMB" } +$settings.VICTORY_MENU_ARGS = $again -join ' ' + +$picture = if ($settings.VICTORY_RENDER_SCALE) { "render scale $($settings.VICTORY_RENDER_SCALE), the title's upscaler" } + elseif ($settings.VICTORY_UPSCALE -eq 'dlss') { 'DLSS' } + elseif ($settings.VICTORY_UPSCALE -eq 'stretch') { 'stretched (no DLSS)' } + else { "the title's upscaler" } +$extras = '' +if ($settings.VICTORY_FRAME_GEN) { $extras += ", frame generation $($settings.VICTORY_FRAME_GEN)x" } +if ($settings.VICTORY_BVH_BUILDER -eq '1') { $extras += ', ray tracing' } +Write-Host "Series $(if ($console -eq 'series-x') { 'X' } else { 'S' }), $picture$extras. F1 in the game: settings." + +if ($smooth) { # A copy under the name the NVIDIA App's Smooth Motion profile is set for, refreshed when the build changes. $sm = Join-Path (Split-Path $victory) 'victory_sm.exe' if (-not (Test-Path $sm) -or (Get-Item $sm).LastWriteTime -lt (Get-Item $victory).LastWriteTime) { - Copy-Item $victory $sm -Force + try { Copy-Item $victory $sm -Force -ErrorAction Stop } + catch { + # Still held by a game that has not quite gone: Windows lets it be renamed out of the way. + Rename-Item $sm "victory_sm.exe.old-$(Get-Date -Format HHmmss)" -ErrorAction SilentlyContinue + Copy-Item $victory $sm -Force + } } $victory = $sm } +Get-ChildItem (Join-Path (Split-Path $victory) '*.old-*') -ErrorAction SilentlyContinue | Remove-Item -ErrorAction SilentlyContinue + # (Other settings left over in this window go; where your files are stays.) $paths = 'VICTORY_CONFIG', 'VICTORY_GAME_DIR', 'VICTORY_CACHE_DIR', 'VICTORY_DATA_DIR' Get-ChildItem Env:VICTORY_* | Where-Object { $_.Name -notin $paths } | ForEach-Object { Remove-Item "Env:$($_.Name)" } foreach ($k in $settings.Keys) { Set-Item "Env:$k" $settings[$k] } -$Exe = (Resolve-Path $Exe).Path -$runArgs = @('run', $Exe, '--execute') -if (-not $SeriesX) { $runArgs += @('--console', 'series-s') } -Push-Location (Join-Path $PSScriptRoot '..') # victory.toml is looked for here -try { & $victory @runArgs } finally { Pop-Location } +# A shader cache of its own: one an earlier version of this fork filled does not fit this renderer's pipelines. +$toml = Join-Path $root 'victory.toml' +if (-not $env:VICTORY_CACHE_DIR -and -not ((Test-Path $toml) -and (Select-String -Path $toml -Pattern '^\s*cache_dir\s*=' -Quiet))) { + $env:VICTORY_CACHE_DIR = Join-Path $env:LOCALAPPDATA 'VIctory\cache-nvidia-2' +} +$stamp = Get-Date -Format 'MMdd-HHmmss' +if ($Capture) { + $env:VICTORY_CAPTURE = Join-Path $env:LOCALAPPDATA "VIctory\captures\$stamp" + $env:VICTORY_DUMP_TARGETS = '1' + New-Item -ItemType Directory -Force $env:VICTORY_CAPTURE | Out-Null + Write-Host "F9 saves a frame to $env:VICTORY_CAPTURE" +} +$runArgs = @('run', "`"$Exe`"", '--execute', '--console', $console) +Push-Location $root # victory.toml is looked for here +try { + if ($Log) { + $logs = Join-Path $env:LOCALAPPDATA 'VIctory\logs' + New-Item -ItemType Directory -Force $logs | Out-Null + Get-ChildItem $logs -Filter 'play-*.log' | Sort-Object LastWriteTime -Descending | Select-Object -Skip 4 | Remove-Item -ErrorAction SilentlyContinue + Write-Host "log: $logs\play-$stamp.log" + Start-Process -FilePath $victory -ArgumentList $runArgs -NoNewWindow -Wait -RedirectStandardError "$logs\play-$stamp.log" + } else { + Start-Process -FilePath $victory -ArgumentList $runArgs -NoNewWindow -Wait + } +} finally { Pop-Location } From b190242f8133297a38115a9c8e246666e7479f72 Mon Sep 17 00:00:00 2001 From: trustno1-coder <361337194+trustno1-coder@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:11:06 -0800 Subject: [PATCH 445/445] README: say first that DLSS is installed with Get-NVIDIA-DLSS.cmd and that F1 opens the menu Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/README.md b/README.md index 1b2b054..e88ae92 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,18 @@ # VIctory on NVIDIA +> **Before you play** +> +> - **You must install DLSS yourself:** run `Get-NVIDIA-DLSS.cmd` once (it is +> in this folder; a double click does it), or have your AI assistant run it +> for you. It downloads NVIDIA's DLSS and frame generation files, about 70 MB, +> from NVIDIA's own GitHub; they are not part of this repository. Without +> them there is no DLSS and no frame generation, and the picture is only +> stretched to the screen. +> - **F1 in the game brings up the settings menu** (arrow keys pick and +> change, Enter does it). F3 shows the numbers panel. +> +> The steps are under [How to run it](#how-to-run-it). + ## Built from many projects This repository did not come from one place. Over several weeks we built, ran